1 | # -*- encoding: utf-8 -*- |
---|
2 | """! |
---|
3 | Vista que controla los procesos de los proyectos |
---|
4 | |
---|
5 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
6 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
7 | @date 09-01-2017 |
---|
8 | @version 1.0.0 |
---|
9 | """ |
---|
10 | |
---|
11 | import os |
---|
12 | from django.conf import settings |
---|
13 | from django.contrib.auth.mixins import LoginRequiredMixin |
---|
14 | from django.contrib import messages |
---|
15 | from django.shortcuts import ( |
---|
16 | render, redirect, render_to_response |
---|
17 | ) |
---|
18 | from django.http import HttpResponse, Http404 |
---|
19 | from django.template import RequestContext |
---|
20 | from django.core.files.storage import default_storage |
---|
21 | from django.core.files.base import ContentFile |
---|
22 | from django.core.urlresolvers import reverse_lazy, reverse |
---|
23 | from django.views.generic import ListView, TemplateView |
---|
24 | from django.views.generic.detail import DetailView |
---|
25 | from django.views.generic.edit import ( |
---|
26 | CreateView, |
---|
27 | UpdateView, |
---|
28 | DeleteView |
---|
29 | ) |
---|
30 | from dal import autocomplete |
---|
31 | from multi_form_view import MultiModelFormView |
---|
32 | |
---|
33 | from .utils import ( |
---|
34 | listObjetivoHistoricoNacional, listObjetivoEstrategico, |
---|
35 | listObjetivoGenerales |
---|
36 | ) |
---|
37 | |
---|
38 | from .models import * |
---|
39 | from .forms import * |
---|
40 | |
---|
41 | from utils.forms import ( |
---|
42 | UploadFileForm |
---|
43 | ) |
---|
44 | |
---|
45 | from users.utils import ( |
---|
46 | LoginRequeridoPerAuth |
---|
47 | ) |
---|
48 | |
---|
49 | from users.models import UserProfile |
---|
50 | |
---|
51 | |
---|
52 | ## Carga de datos del archivo csv a la base de datos |
---|
53 | def carga_masiva_csv(ruta_archivo_hist, ruta_archivo_naci, ruta_archivo_estr, ruta_archivo_genr): |
---|
54 | n_reg_obj_hist = CargaMasivaObjetivosHistoricos.import_from_filename(ruta_archivo_hist) |
---|
55 | n_reg_obj_naci = CargaMasivaObjetivosNacional.import_from_filename(ruta_archivo_naci) |
---|
56 | n_reg_obj_estr = CargaMasivaObjetivosEstrategico.import_from_filename(ruta_archivo_estr) |
---|
57 | n_reg_obj_genr = CargaMasivaObjetivosGeneral.import_from_filename(ruta_archivo_genr) |
---|
58 | |
---|
59 | return n_reg_obj_hist, n_reg_obj_naci, n_reg_obj_estr, n_reg_obj_genr |
---|
60 | |
---|
61 | |
---|
62 | def cargaObjetivos(request): |
---|
63 | """! |
---|
64 | Funcion que permite cargar un archivo csv desde la interfaz del Administrador |
---|
65 | |
---|
66 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
67 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
68 | @date 09-01-2017 |
---|
69 | @version 1.0.0 |
---|
70 | """ |
---|
71 | form = UploadFileForm() |
---|
72 | context = {'form': form} |
---|
73 | if request.method == 'POST': |
---|
74 | form = UploadFileForm(request.POST, request.FILES) |
---|
75 | if form.is_valid(): |
---|
76 | archivo_objetivos = request.FILES['cargar'] |
---|
77 | extension_objetivos = str(archivo_objetivos).split('.') |
---|
78 | longitud_historico = len(extension_objetivos) |
---|
79 | if extension_objetivos[longitud_historico - 1] == 'csv': |
---|
80 | data_historico = archivo_objetivos.readlines() |
---|
81 | formato_cabeceras = False |
---|
82 | mensaje_error = "" |
---|
83 | for cabecera_historico in range(0, 1): |
---|
84 | separador_historico = data_historico[cabecera_historico].split(b"|") |
---|
85 | if (separador_historico[0]).decode('UTF-8') == "OBJETIVOS HISTÃRICOS" \ |
---|
86 | and (separador_historico[1]).decode('UTF-8') == "OBJETIVOS NACIONALES" and \ |
---|
87 | (separador_historico[2]).decode('UTF-8') == "OBJETIVOS ESTRATÃGICOS" and \ |
---|
88 | (separador_historico[3]).decode('UTF-8') == "OBJETIVOS GENERALES\n": |
---|
89 | formato_cabeceras = True |
---|
90 | else: |
---|
91 | formato_cabeceras = False |
---|
92 | mensaje_error_historico = "Existe un error en la cabecera del csv, del formato del Plan de la Patria\n" |
---|
93 | else: |
---|
94 | mensaje_error = "El formato de archivo debe ser csv" |
---|
95 | messages.error(request, mensaje_error) |
---|
96 | if formato_cabeceras: |
---|
97 | datos_obj = listObjetivoHistoricoNacional(data_historico) |
---|
98 | datos_obj_est = listObjetivoEstrategico(data_historico, datos_obj[1]) |
---|
99 | datos_obj_gene =listObjetivoGenerales(data_historico, datos_obj_est) |
---|
100 | archivo_obj_hist = ''.join(datos_obj[0]) |
---|
101 | archivo_obj_naci = ''.join(datos_obj[1]) |
---|
102 | archivo_obj_est = ''.join(datos_obj_est) |
---|
103 | archivo_obj_gene = ''.join(datos_obj_gene) |
---|
104 | #path_historico = default_storage.save('tmp/formato_historico.csv', ContentFile(archivo_obj_hist)) |
---|
105 | #path_nacional = default_storage.save('tmp/formato_nacional.csv', ContentFile(archivo_obj_naci)) |
---|
106 | #path_estrategico = default_storage.save('tmp/formato_estrategico.csv', ContentFile(archivo_obj_est)) |
---|
107 | #path_general = default_storage.save('tmp/formato_general.csv', ContentFile(archivo_obj_gene)) |
---|
108 | #ruta_historico = os.path.join(settings.MEDIA_ROOT, path_historico) |
---|
109 | #ruta_nacional = os.path.join(settings.MEDIA_ROOT, path_nacional) |
---|
110 | #ruta_estrategico = os.path.join(settings.MEDIA_ROOT, path_estrategico) |
---|
111 | #ruta_general = os.path.join(settings.MEDIA_ROOT, path_general) |
---|
112 | #carga_masiva_csv(ruta_historico, ruta_nacional, ruta_estrategico, ruta_general) |
---|
113 | #path_historico = default_storage.delete('tmp/formato_historico.csv') |
---|
114 | #path_nacional = default_storage.delete('tmp/formato_nacional.csv') |
---|
115 | #path_estrategico = default_storage.delete('tmp/formato_estrategico.csv') |
---|
116 | #path_general = default_storage.delete('tmp/formato_general.csv') |
---|
117 | messages.success(request, 'La data se cargo con exito') |
---|
118 | else: |
---|
119 | messages.error(request, mensaje_error_historico) |
---|
120 | else: |
---|
121 | return render(request, 'utils/cargar_historica.html', context) |
---|
122 | |
---|
123 | context = {'form': form} |
---|
124 | return render(request, 'utils/cargar_historica.html', context) |
---|
125 | |
---|
126 | else: |
---|
127 | return render(request, 'utils/cargar_historica.html', context) |
---|
128 | |
---|
129 | |
---|
130 | class AlcanceAutocomplete(autocomplete.Select2QuerySetView): |
---|
131 | """! |
---|
132 | Clase que crea el autocompletado del alcance de los proyectos en un select |
---|
133 | |
---|
134 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
135 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
136 | @date 09-01-2017 |
---|
137 | @version 1.0.0 |
---|
138 | """ |
---|
139 | |
---|
140 | def get_queryset(self): |
---|
141 | # No se olvide de filtrar los resultados en función del visitante ! |
---|
142 | if not self.request.user.is_authenticated(): |
---|
143 | return Alcance.objects.none() |
---|
144 | |
---|
145 | qs = Alcance.objects.all() |
---|
146 | if self.q: |
---|
147 | qs = qs.filter(opcion_alcance__istartswith=self.q) |
---|
148 | |
---|
149 | return qs |
---|
150 | |
---|
151 | class OptionsMangProjectsView(LoginRequeridoPerAuth, TemplateView): |
---|
152 | """! |
---|
153 | Lista las opciones para la gestion de proyectos |
---|
154 | |
---|
155 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
156 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
157 | @date 09-01-2017 |
---|
158 | @version 1.0.0 |
---|
159 | """ |
---|
160 | template_name = "proyectos/gestion_proyectos.html" |
---|
161 | group_required = [u"Administradores", u"Usuarios Supervisores", u"Usuarios Enlace" ] |
---|
162 | |
---|
163 | def __init__(self): |
---|
164 | super(OptionsMangProjectsView, self).__init__() |
---|
165 | |
---|
166 | def get_context_data(self, **kwargs): |
---|
167 | """Use this to add extra context.""" |
---|
168 | try: |
---|
169 | perfil = UserProfile.objects.select_related().get(fk_user=self.request.user.id) |
---|
170 | except: |
---|
171 | perfil = None |
---|
172 | try: |
---|
173 | proyectos = Proyecto.objects.all() |
---|
174 | except: |
---|
175 | proyectos = None |
---|
176 | context = super(OptionsMangProjectsView, self).get_context_data(**kwargs) |
---|
177 | context['userprofile'] = perfil |
---|
178 | context['proyectos'] = proyectos |
---|
179 | return context |
---|
180 | |
---|
181 | |
---|
182 | |
---|
183 | |
---|
184 | class ProjectsList(ListView): |
---|
185 | """! |
---|
186 | Clase que lista los proyectos |
---|
187 | |
---|
188 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
189 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
190 | @date 09-01-2017 |
---|
191 | @version 1.0.0 |
---|
192 | """ |
---|
193 | model = Proyecto |
---|
194 | |
---|
195 | def __init__(self): |
---|
196 | super(ProjectsList, self).__init__() |
---|
197 | |
---|
198 | |
---|
199 | class ProyectoRegisterView(LoginRequeridoPerAuth, MultiModelFormView): |
---|
200 | """! |
---|
201 | Clase para crear los proyectos |
---|
202 | |
---|
203 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
204 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
205 | @date 09-01-2017 |
---|
206 | @version 1.0.0 |
---|
207 | """ |
---|
208 | template_name = 'proyectos/proyecto_form.html' |
---|
209 | model = Proyecto |
---|
210 | form_classes = { |
---|
211 | 'proyecto': FormularioRegProyecto, |
---|
212 | 'obj_proy': FormsetObj, |
---|
213 | 'resp_tec': FormularioRespTec, |
---|
214 | 'resp_gere': FormularioRespGere, |
---|
215 | } |
---|
216 | success_url = reverse_lazy('projects:crear_proyectos') |
---|
217 | record_id=None |
---|
218 | group_required = [u"Administradores", u"Usuarios Supervisores", u"Usuarios Enlace" ] |
---|
219 | |
---|
220 | def __init__(self): |
---|
221 | super(ProyectoRegisterView, self).__init__() |
---|
222 | |
---|
223 | def get_objects(self): |
---|
224 | self.record_id = self.kwargs.get('record_id', None) |
---|
225 | try: |
---|
226 | record = ObjetivosEspecificosProy.objects.get(fk_proyecto=self.record_id) |
---|
227 | except ObjetivosEspecificosProy.DoesNotExist: |
---|
228 | record = None |
---|
229 | return { |
---|
230 | 'obj_proy': record, |
---|
231 | 'proyecto': record.fk_proyecto if record else None, |
---|
232 | 'resp_tec': record.fk_proyecto if record else None, |
---|
233 | 'resp_gere': record.fk_proyecto if record else None, |
---|
234 | } |
---|
235 | |
---|
236 | def get_context_data(self, **kwargs): |
---|
237 | """Use this to add extra context.""" |
---|
238 | try: |
---|
239 | perfil = UserProfile.objects.select_related().get(fk_user=self.request.user.id) |
---|
240 | except: |
---|
241 | perfil = None |
---|
242 | try: |
---|
243 | proyectos = Proyecto.objects.all() |
---|
244 | except: |
---|
245 | proyectos = None |
---|
246 | context = super(ProyectoRegisterView, self).get_context_data(**kwargs) |
---|
247 | context['userprofile'] = perfil |
---|
248 | context['proyectos'] = proyectos |
---|
249 | return context |
---|
250 | |
---|
251 | def forms_valid(self, forms, **kwargs): |
---|
252 | """ |
---|
253 | Valida el formulario del proyecto |
---|
254 | @return: Dirige con un mensaje de exito al registro de proyecto |
---|
255 | """ |
---|
256 | nuevo_project = forms['proyecto'].save() |
---|
257 | prueba = self.form_classes['obj_proy'](self.request.POST, instance=nuevo_project) |
---|
258 | if prueba.is_valid(): |
---|
259 | prueba.save() |
---|
260 | nuevo_resp_tec = forms['resp_tec'].save(commit=False) |
---|
261 | nuevo_resp_gen = forms['resp_gere'].save(commit=False) |
---|
262 | nuevo_resp_tec.fk_proyecto = nuevo_project |
---|
263 | nuevo_resp_tec.save() |
---|
264 | nuevo_resp_gen.fk_proyecto = nuevo_project |
---|
265 | nuevo_resp_gen.save() |
---|
266 | messages.success(self.request, "El usaurio %s, ha creado con exito,\ |
---|
267 | el proyecto %s" % |
---|
268 | (str(self.request.user), |
---|
269 | str(nuevo_project))) |
---|
270 | return redirect(self.success_url) |
---|
271 | |
---|
272 | def forms_invalid(self, forms, **kwargs): |
---|
273 | messages.error(self.request, "%s, %s, %s, %s" % |
---|
274 | (str(forms['proyecto'].errors.as_data()), |
---|
275 | str(forms['obj_proy'].errors.as_data()), |
---|
276 | str(forms['resp_tec'].errors.as_data()), |
---|
277 | str(forms['resp_gere'].errors.as_data()))) |
---|
278 | return super(ProyectoRegisterView, self).forms_invalid(forms) |
---|
279 | |
---|
280 | |
---|
281 | class ProyectoUpdate(UpdateView): |
---|
282 | """! |
---|
283 | Clase para editar o actualizar un proyecto |
---|
284 | |
---|
285 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
286 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
287 | @date 09-01-2017 |
---|
288 | @version 1.0.0 |
---|
289 | """ |
---|
290 | model = Proyecto |
---|
291 | success_url = reverse_lazy('projects:consultar_proyectos') |
---|
292 | fields = [ |
---|
293 | 'fk_alcance', 'fk_sector', 'codigo', 'nombre', |
---|
294 | 'justificacion', 'objetivo_general', |
---|
295 | 'objetivos_especificos', 'monto_proyecto', 'fecha_inicio', |
---|
296 | 'fecha_culminacion' |
---|
297 | ] |
---|
298 | |
---|
299 | |
---|
300 | class SubProjectsList(ListView): |
---|
301 | """! |
---|
302 | Clase para listar o consultar los subproyectos |
---|
303 | |
---|
304 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
305 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
306 | @date 09-01-2017 |
---|
307 | @version 1.0.0 |
---|
308 | """ |
---|
309 | model = SubProyecto |
---|
310 | |
---|
311 | def __init__(self): |
---|
312 | super(SubProjectsList, self).__init__() |
---|
313 | |
---|
314 | |
---|
315 | class SubProyectoCreation(CreateView): |
---|
316 | """! |
---|
317 | Clase que crear los subproyectos |
---|
318 | |
---|
319 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
320 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
321 | @date 09-01-2017 |
---|
322 | @version 1.0.0 |
---|
323 | """ |
---|
324 | model = SubProyecto |
---|
325 | success_url = reverse_lazy('projects:consultar_subproyectos') |
---|
326 | fields = [ |
---|
327 | 'fk_proyecto', 'parroquia', 'codigo', 'nombre', |
---|
328 | 'descripcion_bien_servicio', 'unidad_medida', |
---|
329 | 'meta', 'fecha_inicio', 'fecha_culminacion', 'comunidad', |
---|
330 | 'monto_subproyecto' |
---|
331 | ] |
---|
332 | |
---|
333 | |
---|
334 | class SubProyectoUpdate(UpdateView): |
---|
335 | """! |
---|
336 | Clase que permite actualizar o editar los subproyectos |
---|
337 | |
---|
338 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
339 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
340 | @date 09-01-2017 |
---|
341 | @version 1.0.0 |
---|
342 | """ |
---|
343 | model = SubProyecto |
---|
344 | success_url = reverse_lazy('projects:consultar_subproyectos') |
---|
345 | fields = [ |
---|
346 | 'fk_proyecto', 'parroquia', 'codigo', 'nombre', |
---|
347 | 'descripcion_bien_servicio', 'unidad_medida', |
---|
348 | 'meta', 'fecha_inicio', 'fecha_culminacion', 'comunidad', |
---|
349 | 'monto_subproyecto' |
---|
350 | ] |
---|
351 | |
---|
352 | |
---|
353 | class ActividadList(ListView): |
---|
354 | """! |
---|
355 | Clase que permite listar o consular las actividades |
---|
356 | |
---|
357 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
358 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
359 | @date 09-01-2017 |
---|
360 | @version 1.0.0 |
---|
361 | """ |
---|
362 | model = Actividad |
---|
363 | |
---|
364 | def __init__(self): |
---|
365 | super(ActividadList, self).__init__() |
---|
366 | |
---|
367 | |
---|
368 | class ActividadCreation(CreateView): |
---|
369 | """! |
---|
370 | Clase que permite crear las actividades |
---|
371 | |
---|
372 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
373 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
374 | @date 09-01-2017 |
---|
375 | @version 1.0.0 |
---|
376 | """ |
---|
377 | model = Actividad |
---|
378 | success_url = reverse_lazy('projects:consultar_actividades') |
---|
379 | fields = [ |
---|
380 | 'fk_subproyecto', 'descripcion', 'unidad_medida', 'fecha_inicio', |
---|
381 | 'fecha_culminacion', 'horas_estimadas_ejecucion', |
---|
382 | 'costo_estimadao_ejecucion', 'peso_actividad', |
---|
383 | 'cantidad_estimada_trabajo' |
---|
384 | ] |
---|
385 | |
---|
386 | |
---|
387 | class ActividadUpdate(UpdateView): |
---|
388 | """! |
---|
389 | Clase que permite actualizar o editar las actividades |
---|
390 | |
---|
391 | @author Ing. Leonel P. Hernandez M. (lhernandez at cenditel.gob.ve) |
---|
392 | @copyright <a href='http://www.gnu.org/licenses/gpl-2.0.html'>GNU Public License versión 2 (GPLv2)</a> |
---|
393 | @date 09-01-2017 |
---|
394 | @version 1.0.0 |
---|
395 | """ |
---|
396 | success_url = reverse_lazy('projects:consultar_actividades') |
---|
397 | fields = [ |
---|
398 | 'fk_subproyecto', 'descripcion', 'unidad_medida', 'fecha_inicio', |
---|
399 | 'fecha_culminacion', 'horas_estimadas_ejecucion', |
---|
400 | 'costo_estimadao_ejecucion', 'peso_actividad', |
---|
401 | 'cantidad_estimada_trabajo' |
---|
402 | ] |
---|