def eliminarProyecto(request, proyid): try: projDeci = models.ProjectDecision.objects.filter( project__proj_id=proyid) for p in projDeci: p.delete() projContx = models.ProjectContext.objects.filter( project__proj_id=proyid) for p in projContx: p.delete() projTeam = models.ProjectTeam.objects.filter(project__proj_id=proyid) for p in projTeam: p.delete() query = "select dim.* \ from opx.territorial_dimension as dim \ inner join opx.project_dimension as pd on dim.dimension_id = pd.territorial_dimension_id \ where pd.project_id = '" + proyid + "' and dim.preloaded = 0;" with connection.cursor() as cursor: cursor.execute(query) territorios = dictfetchall(cursor) projTerr = models.ProjectTerritorialDimension.objects.filter( project__proj_id=proyid) for p in projTerr: p.delete() for p in territorios: models.TerritorialDimension.objects.get( pk=p['dimension_id']).delete() projComentario = models.Comment.objects.filter(project__proj_id=proyid) for p in projComentario: p.delete() projTask = models.Task.objects.filter(project__proj_id=proyid) for p in projTask: p.delete() #borrar las tareas antes de borrar e pj al igual que proyecto = models.Project.objects.get(pk=proyid) proyecto.delete() return JsonResponse({'status': 'success'}) except ObjectDoesNotExist: return JsonResponse( { 'status': 'error', 'message': 'El usuario no existe' }, safe=True, status=404) except ValidationError: return JsonResponse( { 'status': 'error', 'message': 'Información inválida' }, safe=True, status=400)
def listadoProyectos(request): search = request.GET.get('search') page = request.GET.get('page') all = request.GET.get('all') try: if 'HTTP_AUTHORIZATION' in request.META.keys( ) and request.META['HTTP_AUTHORIZATION'] != 'null': # # Decodificando el access token # tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], # settings.SIMPLE_JWT['VERIFYING_KEY']) # tokenDecoded = tokenBackend.decode(request.META['HTTP_AUTHORIZATION'].split()[1], verify=True) # #consultando el usuario # user = models.Usuario.objects.get(pk = tokenDecoded['user_id']) user = usuarioAutenticado(request) # ============================ Consultando proyectos ==================================== #Consulta de proyectos para super administrador person = models.Person.objects.get(user__userid=user.userid) if str(person.role.role_id) == ROL_SUPER_ADMIN: proyectos = models.Project.objects.all() # Especificando orden proyectos = proyectos.order_by('-proj_creation_date') # convirtiendo a lista de diccionarios proyectos = list(proyectos.values()) # Consulta de proyectos para proyectista elif str(person.role.role_id) == ROL_PROYECTISTA: proyectos = models.Project.objects.filter( proj_owner__pers_id__exact=person.pers_id) # Especificando orden proyectos = proyectos.order_by('-proj_creation_date') # convirtiendo a lista de diccionarios proyectos = list(proyectos.values()) # Consulta de proyectos para voluntarios o validadores elif str(person.role.role_id) == ROL_VOLUNTARIO or str( person.role.role_id) == ROL_VALIDADOR: #consultar los proyectos a los que está asociado el voluntario o validador query = "select distinct pj.* from opx.team_person as tp inner join opx.project_team as pt on pt.team_id = tp.team_id inner join opx.project as pj on pt.project_id = pj.proj_id where tp.person_id = '" + str( person.pers_id) + "' order by pj.proj_creation_date DESC;" with connection.cursor() as cursor: cursor.execute(query) PJ = dictfetchall(cursor) proyectos = list(PJ) #Tipo de usuario distinto else: proyectos = models.Project.objects.filter(proj_name='qwerty') # Usuario Invitado else: proyectos = models.Project.objects.all() # ================= Busqueda de proyectos if search: proyectos = models.Project.objects.filter( proj_name__icontains=search) proyectos = list(proyectos.values()) listadoProyectos = [] type(proyectos) for p in proyectos: type(p) #Consulta del proyectista name = p['proj_external_id'] #proj_owner_id = p['proj_owner_id'] persona = models.Person.objects.get(pk=p['proj_owner_id']) p['proyectista'] = persona.pers_name + ' ' + persona.pers_lastname if 'user' in locals() and ( str(person.role.role_id) == ROL_PROYECTISTA or str(person.role.role_id) == ROL_SUPER_ADMIN): p['dimensiones_territoriales'] = [] query = "select dim.* from opx.territorial_dimension as dim inner join opx.project_dimension as pd on pd.territorial_dimension_id = dim.dimension_id where pd.project_id = '" + str( p['proj_id']) + "';" with connection.cursor() as cursor: cursor.execute(query) territorios = dictfetchall(cursor) p['dimensiones_territoriales'] = list(territorios) query1 = "select tarea.*, dim.* from opx.task as tarea \ inner join opx.territorial_dimension as dim on dim.dimension_id = tarea.territorial_dimension_id \ where tarea.project_id = '" + str(p['proj_id']) + "';" with connection.cursor() as cursor: cursor.execute(query1) tareas = dictfetchall(cursor) p['tareas'] = list(tareas) #Reportes p['reportes'] = reporteEstadoProyecto(str(p['proj_id'])) listadoProyectos.append(p) if all is not None and all == "1": data = { 'code': 200, 'proyectos': listadoProyectos, 'status': 'success' } else: # Paginación paginator = Paginator(listadoProyectos, 10) # Validación de página if page is None: page = 1 #Petición de página proyectos = paginator.page(page).object_list data = { 'code': 200, 'paginator': { 'currentPage': int(page), 'perPage': paginator.per_page, 'lastPage': paginator.num_pages, 'total': paginator.count }, 'proyectos': proyectos, 'status': 'success', } except EmptyPage: data = { 'code': 404, 'message': 'Página inexistente', 'status': 'error' } except IndexError: data = {'code': 400, 'status': 'error'} except TokenBackendError as e: data = {'code': 400, 'message': str(e), 'status': 'error'} return JsonResponse(data, safe=False, status=data['code'])
def detalleUsuario(request, userid): try: #usuario = models.Usuario.objects.get(pk=userid) usuario = {} with connection.cursor() as cursor: query = "SELECT p.*, r.role_name, u.useremail from opx.person p \ INNER JOIN opx.role r ON r.role_id = p.role_id " \ "INNER JOIN opx.user u on u.userid = p.user_id WHERE p.user_id = '{}'".format(userid) cursor.execute(query) queryResult = dictfetchall(cursor) if(len(queryResult) > 0): usuario = queryResult[0] # Puntaje esperado para llegar a rol proximo # Voluntario if str(usuario['role_id']) == '0be58d4e-6735-481a-8740-739a73c3be86': usuario['promocion'] = { 'rol': "Validador", 'puntaje': 22 # int(settings['umbral-validador']) } # Proyectista elif str(usuario['role_id']) == '53ad3141-56bb-4ee2-adcf-5664ba03ad65': usuario['promocion'] = { 'rol': "Proyectista", 'puntaje': 22 # int(settings['umbral-proyectista']) } # Remover la información que no se desea mostrar #del usuario['password'] #del usuario['usertoken'] data = { 'code': 200, 'usuario': usuario, 'status': 'success' } else: raise ObjectDoesNotExist("") except ObjectDoesNotExist: data = { 'code': 404, 'status': 'error' } except ValidationError: data = { 'code': 400, 'status': 'error' } except DataError: data = { 'code': 400, 'status': 'error' } return JsonResponse(data, status=data['code'])
def listadoTareas(request): try: # Obtener usuario autenticado usuario = usuarioAutenticado(request) # Superadministrador if str(usuario.rolid) == '8945979e-8ca5-481e-92a2-219dd42ae9fc': proyectosUsuario = [] # Consulta de proyectos para un usuario proyectista elif str(usuario.rolid) == '628acd70-f86f-4449-af06-ab36144d9d6a': proyectosUsuario = list( models.Proyecto.objects.filter( proypropietario=usuario.userid).values('proyid')) # Consulta de proyectos para un usuario voluntario o validador elif str(usuario.rolid ) == '0be58d4e-6735-481a-8740-739a73c3be86' or str( usuario.rolid) == '53ad3141-56bb-4ee2-adcf-5664ba03ad65': proyectosUsuario = list( models.Equipo.objects.filter( userid=usuario.userid).values('proyid')) # ================ Obtener página validación de la misma ======================== page = request.GET.get('page') if (page is None): page = 1 all = request.GET.get('all') # Obtener Búsqueda y validación de la misma search = request.GET.get('search') query = "select t.*, i.instrnombre, p.proynombre from v1.tareas as t " \ "inner join v1.proyectos as p on t.proyid = p.proyid " \ "inner join v1.instrumentos as i on t.instrid = i.instrid" if len(proyectosUsuario) > 0 or search is not None: query += " where " # Busqueda de tareas por proyecto if len(proyectosUsuario) == 1: query += "t.proyid = '" + str( proyectosUsuario[0]['proyid']) + "'" if len(proyectosUsuario) > 1: firstItemQuery = True for p in proyectosUsuario[:-1]: if firstItemQuery: query += "(" firstItemQuery = False query += "t.proyid = '" + str(p['proyid']) + "' or " query += "t.proyid = '" + str( proyectosUsuario[-1]['proyid']) + "')" # Busqueda por Nombre if search is not None: if len(proyectosUsuario) > 0: query += " and" query += " (t.tarenombre ~* '" + search + "');" with connection.cursor() as cursor: cursor.execute(query) # formatear respuesta de base de datos tareas = dictfetchall(cursor) # Progreso de las Tareas for t in tareas: # Tipo encuesta if t['taretipo'] == 1: encuestas = models.Encuesta.objects.filter( tareid__exact=t['tareid']) progreso = (len(encuestas) * 100) / t['tarerestriccant'] t['progreso'] = progreso # instrumento = models.Instrumento.objects.get(pk=t['instrid']) # detalleFormulario = detalleFormularioKoboToolbox(instrumento.instridexterno) # # if(detalleFormulario): # progreso = (detalleFormulario['deployment__submission_count'] * 100) / t['tarerestriccant'] # t['progreso'] = progreso if all is not None and all == "1": data = {'code': 200, 'tareas': tareas, 'status': 'success'} else: # Obtener Página paginator = Paginator(tareas, 10) # Obtener lista de tareas tareas = paginator.page(page).object_list data = { 'code': 200, 'paginator': { 'currentPage': page, 'perPage': paginator.per_page, 'lastPage': paginator.num_pages, 'total': paginator.count }, 'tareas': tareas, 'status': 'success' } except EmptyPage: data = { 'code': 400, 'message': 'Página inexistente', 'status': 'error' } return JsonResponse(data, safe=False, status=data['code'])
def listadoDecisiones(request): with connection.cursor() as cursor: cursor.execute("select opx.decision.decs_id, opx.decision.decs_description, opx.decision.decs_name from opx.decision order by opx.decision.decs_name ASC") columns = dictfetchall(cursor) return JsonResponse(columns, safe = False)
def listadoTareas(request): try: # Obtener usuario autenticado usuario = usuarioAutenticado(request) person = models.Person.objects.get(user__userid=usuario.userid) tareasUsuario = [] proyectosUsuario = [] n = "" # Superadministrador if str(person.role_id) == ROL_SUPER_ADMIN: tareasUsuario = [] n = "select tk.* from opx.task as tk order by tk.task_creation_date DESC;" # Consulta de proyectos para un usuario proyectista elif str(person.role_id) == ROL_PROYECTISTA: n = "select tk.*, restric.* \ from opx.person as persona \ inner join opx.project as proyecto on proyecto.proj_owner_id = persona.pers_id \ inner join opx.task as tk on tk.project_id = proyecto.proj_id \ inner join opx.task_restriction as restric on tk.task_restriction_id = restric.restriction_id \ where persona.pers_id = '" + str( person.pers_id) + "' order by tk.task_creation_date DESC;" # Consulta de proyectos para un usuario voluntario o validador elif str(person.role_id) == ROL_VOLUNTARIO or str( person.pers_id) == ROL_VALIDADOR: n = "select distinct tk.*, restric.* \ from opx.person as person \ inner join opx.team_person as tp on person.pers_id = tp.person_id \ inner join opx.project_team as pt on tp.team_id = pt.team_id \ inner join opx.task as tk on tk.project_id = pt.project_id \ inner join opx.task_restriction as restric on tk.task_restriction_id = restric.restriction_id \ where person.pers_id = '" + str( person.pers_id) + "' order by tk.task_creation_date DESC;" # ================ Obtener página validación de la misma ======================== page = request.GET.get('page') if (page is None): page = 1 all = request.GET.get('all') with connection.cursor() as cursor: cursor.execute(n) # formatear respuesta de base de datos tareas = dictfetchall(cursor) # Progreso de las Tareas for t in tareas: t['task_type_name'] = (models.TaskType.objects.get( pk=t['task_type_id'])).task_type_name t['instrument_name'] = (models.Instrument.objects.get( pk=t['instrument_id'])).instrument_name t['proj_name'] = (models.Project.objects.get( pk=t['project_id'])).proj_name t['priority_name'] = (models.TaskPriority.objects.get( pk=t['task_priority_id'])).priority_name t['task_completness'] = t['task_completness'] * 100 # Obtener Búsqueda y validación de la misma search = request.GET.get('search') if search is not None: tareas = models.Task.objects.filter(task_name__icontains=search) tareas = list(tareas.values()) if all is not None and all == "1": data = {'code': 200, 'tareas': tareas, 'status': 'success'} else: # Obtener Página paginator = Paginator(tareas, 10) # Obtener lista de tareas tareas = paginator.page(page).object_list data = { 'code': 200, 'paginator': { 'currentPage': page, 'perPage': paginator.per_page, 'lastPage': paginator.num_pages, 'total': paginator.count }, 'tareas': tareas, 'status': 'success' } # Obtener Búsqueda y validación de la misma except EmptyPage: data = { 'code': 400, 'message': 'Página inexistente', 'status': 'error' } return JsonResponse(data, safe=False, status=data['code'])
def semanal(request): try: barrioUbicacion = request.GET.get('barrioUbicacion') barrioSeleccion = request.GET.get('barrioSeleccion') year = request.GET.get('year') if request.META['HTTP_AUTHORIZATION'] != 'null': # Decodificando el access token tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], settings.SIMPLE_JWT['VERIFYING_KEY']) tokenDecoded = tokenBackend.decode( request.META['HTTP_AUTHORIZATION'].split()[1], verify=True) # consultando el usuario user = User.objects.get(pk=tokenDecoded['user_id']) edadUsuario = calculoEdad(user.fecha_nacimiento) if barrioUbicacion is not None and barrioSeleccion is not None and year is not None: semana = [{ 'label': 'Domingo', 'value': 1 }, { 'label': 'Lunes', 'value': 2 }, { 'label': 'Martes', 'value': 3 }, { 'label': 'Miercoles', 'value': 4 }, { 'label': 'Jueves', 'value': 5 }, { 'label': 'Viernes', 'value': 6 }, { 'label': 'Sabado', 'value': 7 }] conflictividadesCiudad = [] conflictividadesUbicacion = [] conflictividadesSeleccion = [] conflictividadesPerfil = [] for sem in semana: queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(year, sem['value']) queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} and " \ "barrioid = {2} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(year, sem['value'], barrioUbicacion) queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} and " \ "barrioid = {2} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(year, sem['value'], barrioSeleccion) if 'user' in locals(): queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} " \ "and barrioid = {2}" \ "and generoid = '{3}' " \ "and nivelid = '{4}' " \ "and edad = {5} " \ "and (fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(year, sem['value'], user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario) with connection.cursor() as cursor: #Indicador Ciudad cursor.execute(queryIndicadorCiudad) indicadorCiudad = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesCiudad.append(indicadorCiudad) #Indicador Ubicación cursor.execute(queryIndicadorUbicacion) indicadorUbicacion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesUbicacion.append(indicadorUbicacion) #Indicador Selección cursor.execute(queryIndicadorSeleccion) indicadorSeleccion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesSeleccion.append(indicadorSeleccion) if 'user' in locals(): #Indicador Perfil cursor.execute(queryIndicadorPerfil) indicadorPerfil = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesPerfil.append(indicadorPerfil) data = { 'labels': [d['label'] for d in semana], 'datasets': [{ 'label': 'ciudad', 'fill': False, 'borderColor': 'orange', 'data': conflictividadesCiudad }, { 'label': 'Ubicación', 'fill': False, 'borderColor': 'blue', 'data': conflictividadesUbicacion }, { 'indicador': 'Selección', 'fill': False, 'borderColor': 'green', 'data': conflictividadesSeleccion }] } if 'user' in locals(): data['datasets'].append({ 'label': 'Perfil', 'fill': False, 'borderColor': 'red', 'data': conflictividadesPerfil }) response = {'code': 200, 'data': data, 'status': 'success'} else: response = {'code': 400, 'status': 'error'} except (IndexError): response = {'code': 400, 'status': 'error'} except TokenBackendError as e: response = {'code': 400, 'message': str(e), 'status': 'error'} return JsonResponse(response, safe=False, status=response['code'])
def dia(request): try: barrioUbicacion = request.GET.get('barrioUbicacion') barrioSeleccion = request.GET.get('barrioSeleccion') year = request.GET.get('year') if request.META['HTTP_AUTHORIZATION'] != 'null': # Decodificando el access token tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], settings.SIMPLE_JWT['VERIFYING_KEY']) tokenDecoded = tokenBackend.decode( request.META['HTTP_AUTHORIZATION'].split()[1], verify=True) # consultando el usuario user = User.objects.get(pk=tokenDecoded['user_id']) edadUsuario = calculoEdad(user.fecha_nacimiento) if barrioUbicacion is not None and barrioSeleccion is not None and year is not None: conflictividadesCiudad = [] conflictividadesUbicacion = [] conflictividadesSeleccion = [] conflictividadesPerfil = [] diasSemana = { 'Sunday': 1, 'Monday': 2, 'Tuesday': 3, 'Wednesday': 4, 'Thursday': 5, 'Friday': 6, 'Saturday': 7 } diaSemana = diasSemana.get(date.today().strftime("%A")) hora = 0 horas = [] while hora <= 23: horas.append(str(hora) + 'h') if hora < 10: horaInicio = "0{}:00:00".format(str(hora)) horaFin = "0{}:59:59".format(str(hora)) else: horaInicio = "{}:00:00".format(str(hora)) horaFin = "{}:59:59".format(str(hora)) queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31') and" \ "(hora_hecho between '{2}' and '{3}')) t" \ .format(year, diaSemana, horaInicio, horaFin) queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} and " \ "barrioid = {4} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31') and" \ "(hora_hecho between '{2}' and '{3}')) t" \ .format(year, diaSemana, horaInicio, horaFin, barrioUbicacion) queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} and " \ "barrioid = {4} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31') and" \ "(hora_hecho between '{2}' and '{3}')) t" \ .format(year, diaSemana, horaInicio, horaFin, barrioSeleccion) if 'user' in locals(): queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE dia = {1} " \ "and barrioid = {4}" \ "and generoid = '{5}' " \ "and nivelid = '{6}' " \ "and edad = {7} " \ "and (fecha_hecho between '{0}-01-01' and '{0}-12-31') " \ "and (hora_hecho between '{2}' and '{3}')) t" \ .format(year, diaSemana, horaInicio, horaFin, user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario) with connection.cursor() as cursor: # Indicador Ciudad cursor.execute(queryIndicadorCiudad) indicadorCiudad = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesCiudad.append(indicadorCiudad) # Indicador Ubicación cursor.execute(queryIndicadorUbicacion) indicadorUbicacion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesUbicacion.append(indicadorUbicacion) # Indicador Selección cursor.execute(queryIndicadorSeleccion) indicadorSeleccion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesSeleccion.append(indicadorSeleccion) if 'user' in locals(): # Indicador Perfil cursor.execute(queryIndicadorPerfil) indicadorPerfil = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesPerfil.append(indicadorPerfil) hora += 1 data = { 'labels': horas, 'datasets': [{ 'label': 'ciudad', 'fill': False, 'borderColor': 'orange', 'data': conflictividadesCiudad }, { 'label': 'Ubicación', 'fill': False, 'borderColor': 'blue', 'data': conflictividadesUbicacion }, { 'label': 'Selección', 'fill': False, 'borderColor': 'green', 'data': conflictividadesSeleccion }] } if 'user' in locals(): data['datasets'].append({ 'label': 'Perfil', 'fill': False, 'borderColor': 'red', 'data': conflictividadesPerfil }) response = {'code': 200, 'data': data, 'status': 'success'} else: response = {'code': 400, 'status': 'error'} except (IndexError): response = {'code': 400, 'status': 'error'} except TokenBackendError as e: response = {'code': 400, 'message': str(e), 'status': 'error'} return JsonResponse(response, safe=False, status=response['code'])
def todo(request): try: barrioUbicacion = request.GET.get('barrioUbicacion') barrioSeleccion = request.GET.get('barrioSeleccion') if request.META['HTTP_AUTHORIZATION'] != 'null': # Decodificando el access token tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], settings.SIMPLE_JWT['VERIFYING_KEY']) tokenDecoded = tokenBackend.decode( request.META['HTTP_AUTHORIZATION'].split()[1], verify=True) # consultando el usuario user = User.objects.get(pk=tokenDecoded['user_id']) edadUsuario = calculoEdad(user.fecha_nacimiento) if barrioUbicacion is not None and barrioSeleccion is not None: anioInicial = 2010 anioFinal = 2019 anios = [] count = anioInicial conflictividadesCiudad = [] conflictividadesUbicacion = [] conflictividadesSeleccion = [] conflictividadesPerfil = [] while count <= anioFinal: anios.append(count) queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE fecha_hecho between '{0}-01-01' and '{0}-12-31') t" \ .format(count) queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE barrioid = {1} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(count, barrioUbicacion) queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE barrioid = {1} and " \ "(fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(count, barrioSeleccion) if 'user' in locals(): queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE barrioid = {1} " \ "and generoid = '{2}' " \ "and nivelid = '{3}' " \ "and edad = {4} " \ "and (fecha_hecho between '{0}-01-01' and '{0}-12-31')) t" \ .format(count, user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario) with connection.cursor() as cursor: # Indicador Ciudad cursor.execute(queryIndicadorCiudad) indicadorCiudad = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesCiudad.append(indicadorCiudad) # Indicador Ubicación cursor.execute(queryIndicadorUbicacion) indicadorUbicacion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesUbicacion.append(indicadorUbicacion) # Indicador Selección cursor.execute(queryIndicadorSeleccion) indicadorSeleccion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesSeleccion.append(indicadorSeleccion) if 'user' in locals(): # Indicador Perfil cursor.execute(queryIndicadorPerfil) indicadorPerfil = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesPerfil.append(indicadorPerfil) count += 1 data = { 'labels': anios, 'datasets': [{ 'label': 'ciudad', 'fill': False, 'borderColor': 'orange', 'data': conflictividadesCiudad }, { 'label': 'Ubicación', 'fill': False, 'borderColor': 'blue', 'data': conflictividadesUbicacion }, { 'label': 'Selección', 'fill': False, 'borderColor': 'green', 'data': conflictividadesSeleccion }] } if 'user' in locals(): totalConflictividadesPerfil = 0 for cp in conflictividadesPerfil: totalConflictividadesPerfil = totalConflictividadesPerfil + cp data['datasets'].append({ 'label': 'Perfil', 'fill': False, 'borderColor': 'red', 'data': conflictividadesPerfil, 'promedio': totalConflictividadesPerfil / len(conflictividadesPerfil) }) response = {'code': 200, 'data': data, 'status': 'success'} else: response = {'code': 400, 'status': 'error'} except (IndexError): response = {'code': 400, 'status': 'error'} except TokenBackendError as e: response = {'code': 400, 'message': str(e), 'status': 'error'} return JsonResponse(response, safe=False, status=response['code'])
def mensual(request): try: barrioUbicacion = request.GET.get('barrioUbicacion') barrioSeleccion = request.GET.get('barrioSeleccion') year = request.GET.get('year') if request.META['HTTP_AUTHORIZATION'] != 'null': # Decodificando el access token tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], settings.SIMPLE_JWT['VERIFYING_KEY']) tokenDecoded = tokenBackend.decode( request.META['HTTP_AUTHORIZATION'].split()[1], verify=True) # consultando el usuario user = User.objects.get(pk=tokenDecoded['user_id']) edadUsuario = calculoEdad(user.fecha_nacimiento) if barrioUbicacion is not None and barrioSeleccion is not None and year is not None: meses = [{ 'label': 'Enero', 'value': '01', 'lastDay': '31' }, { 'label': 'Febrero', 'value': '02', 'lastDay': bisiesto(int(year), anio=False, mes=True) }, { 'label': 'Marzo', 'value': '03', 'lastDay': '31' }, { 'label': 'Abril', 'value': '04', 'lastDay': '30' }, { 'label': 'Mayo', 'value': '05', 'lastDay': '31' }, { 'label': 'Junio', 'value': '06', 'lastDay': '30' }, { 'label': 'Julio', 'value': '07', 'lastDay': '31' }, { 'label': 'Agosto', 'value': '08', 'lastDay': '31' }, { 'label': 'Septiembre', 'value': '09', 'lastDay': '30' }, { 'label': 'Octubre', 'value': '10', 'lastDay': '31' }, { 'label': 'Noviembre', 'value': '11', 'lastDay': '30' }, { 'label': 'Diciembre', 'value': '12', 'lastDay': '31' }] conflictividadesCiudad = [] conflictividadesUbicacion = [] conflictividadesSeleccion = [] conflictividadesPerfil = [] for mes in meses: queryIndicadorCiudad = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}') t" \ .format(year, mes['value'], mes['lastDay']) queryIndicadorUbicacion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE barrioid = {3} and " \ "(fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}')) t" \ .format(year, mes['value'], mes['lastDay'], barrioUbicacion) queryIndicadorSeleccion = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE barrioid = {3} and " \ "(fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}')) t" \ .format(year, mes['value'], mes['lastDay'], barrioSeleccion) if 'user' in locals(): queryIndicadorPerfil = "SELECT SUM(t.cantidad) as count FROM (" \ "SELECT * FROM opx.contextualizaciones " \ "WHERE barrioid = {3} " \ "and generoid = '{4}' " \ "and nivelid = '{5}' " \ "and edad = {6} " \ "and (fecha_hecho between '{0}-{1}-01' and '{0}-{1}-{2}')) t" \ .format(year, mes['value'], mes['lastDay'], user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario) with connection.cursor() as cursor: #Indicador Ciudad cursor.execute(queryIndicadorCiudad) indicadorCiudad = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesCiudad.append(indicadorCiudad) #Indicador Ubicación cursor.execute(queryIndicadorUbicacion) indicadorUbicacion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesUbicacion.append(indicadorUbicacion) #Indicador Selección cursor.execute(queryIndicadorSeleccion) indicadorSeleccion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesSeleccion.append(indicadorSeleccion) if 'user' in locals(): #Indicador Perfil cursor.execute(queryIndicadorPerfil) indicadorPerfil = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) conflictividadesPerfil.append(indicadorPerfil) data = { 'labels': [m['label'] for m in meses], 'datasets': [{ 'label': 'ciudad', 'fill': False, 'borderColor': 'orange', 'data': conflictividadesCiudad }, { 'label': 'Ubicación', 'fill': False, 'borderColor': 'blue', 'data': conflictividadesUbicacion }, { 'label': 'Selección', 'fill': False, 'borderColor': 'green', 'data': conflictividadesSeleccion }] } if 'user' in locals(): data['datasets'].append({ 'label': 'Perfil', 'fill': False, 'borderColor': 'red', 'data': conflictividadesPerfil }) response = {'code': 200, 'data': data, 'status': 'success'} else: response = {'code': 400, 'status': 'error'} except (IndexError): response = {'code': 400, 'status': 'error'} except TokenBackendError as e: response = {'code': 400, 'message': str(e), 'status': 'error'} return JsonResponse(response, safe=False, status=response['code'])
def categorizacion(request): try: barrioUbicacion = request.GET.get('barrioUbicacion') barrioSeleccion = request.GET.get('barrioSeleccion') year = request.GET.get('year') if request.META['HTTP_AUTHORIZATION'] != 'null': # Decodificando el access token tokenBackend = TokenBackend(settings.SIMPLE_JWT['ALGORITHM'], settings.SIMPLE_JWT['SIGNING_KEY'], settings.SIMPLE_JWT['VERIFYING_KEY']) tokenDecoded = tokenBackend.decode( request.META['HTTP_AUTHORIZATION'].split()[1], verify=True) # consultando el usuario user = User.objects.get(pk=tokenDecoded['user_id']) edadUsuario = calculoEdad(user.fecha_nacimiento) if barrioUbicacion is not None and barrioSeleccion is not None and year is not None: conflictividades = Conflictividad.objects.all() data = [] for conf in conflictividades: queryIndicadorCiudad = "select SUM(t.cantidad) as count from \ (select * from opx.contextualizaciones \ where (confid = '{0}') \ and (fecha_hecho between '{1}-01-01' and '{1}-12-31')) t;" \ .format(conf.confid, year) queryIndicadorUbicacion = "select SUM(t.cantidad) as count from \ (select * from opx.contextualizaciones \ where confid = '{0}' \ and barrioid = '{1}' \ and (fecha_hecho between '{2}-01-01' and '{2}-12-31')) t;" \ .format(conf.confid, barrioUbicacion, year) queryIndicadorSeleccion = "select SUM(t.cantidad) as count from \ (select * from opx.contextualizaciones \ where confid = '{0}' \ and barrioid = '{1}' \ and (fecha_hecho between '{2}-01-01' and '{2}-12-31')) t;" \ .format(conf.confid, barrioSeleccion, year) if 'user' in locals(): queryIndicadorPerfil = "select SUM(t.cantidad) as count from \ (select * from opx.contextualizaciones \ where confid = '{0}' \ and barrioid = {1} \ and generoid = '{2}' \ and nivelid = '{3}' \ and edad = {4} \ and (fecha_hecho between '{5}-01-01' and '{5}-12-31')) t;" \ .format(conf.confid, user.barrioid, user.generoid, user.nivel_educativo_id, edadUsuario, year) with connection.cursor() as cursor: cursor.execute(queryIndicadorCiudad) indicadorCiudad = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) cursor.execute(queryIndicadorUbicacion) indicadorUbicacion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) cursor.execute(queryIndicadorSeleccion) indicadorSeleccion = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) if 'user' in locals(): cursor.execute(queryIndicadorPerfil) indicadorPerfil = verificacionExistenciaConflictividades( dictfetchall(cursor)[0]['count']) if (indicadorCiudad != 0): indicadorPromedio = indicadorCiudad / bisiesto( int(year)) else: indicadorPromedio = 0 indicadores = { 'conflictividad': model_to_dict(conf), 'indicadores': { 'ciudad': indicadorCiudad, 'ubicacion': indicadorUbicacion, 'seleccion': indicadorSeleccion, 'promedio': indicadorPromedio }, } if 'user' in locals(): indicadores['indicadores']['perfil'] = indicadorPerfil data.append(indicadores) response = {'code': 200, 'data': data, 'status': 'success'} else: response = {'code': 400, 'status': 'error'} except (IndexError): response = {'code': 400, 'status': 'error'} except TokenBackendError as e: response = {'code': 400, 'message': str(e), 'status': 'error'} return JsonResponse(response, safe=False, status=response['code'])
def detalleCartografia(tareid): try: tarea = models.Tarea.objects.get(pk=tareid) instrumento = models.Instrumento.objects.get(pk=tarea.instrid) if instrumento.instrtipo == 2: query = "SELECT c.*, eo.nombre as tipo_elemento_osm, eo.closed_way FROM v1.cartografias as c " \ "INNER JOIN v1.elementos_osm as eo ON c.elemosmid = eo.elemosmid " \ "WHERE c.tareid = '" + tareid + "' " \ "AND c.estado <> 1" with connection.cursor() as cursor: cursor.execute(query) cartografias = dictfetchall(cursor) if len(cartografias) > 0: geometries = [] #Detalle de Way OSM for ct in cartografias: wayHttpClient = http.client.HTTPSConnection(osmRestApiUrl) wayHttpClient.request('GET', '/api/0.6/way/' + ct['osmid'], None, osmHeaders()) wayHttpResponse = wayHttpClient.getresponse() if wayHttpResponse.status == 200: xmlResponse = str(wayHttpResponse.read(), 'utf-8') xmlObject = ET.fromstring(xmlResponse) nodes = xmlObject.findall('way')[0].findall('nd') # print(xmlResponse) nodesGeometry = [] #Detalle de cada uno de los nodos del way for node in nodes: nodeHttpClient = http.client.HTTPSConnection( osmRestApiUrl) nodeHttpClient.request( 'GET', '/api/0.6/node/' + node.get('ref'), None, osmHeaders()) nodeHttpResponse = nodeHttpClient.getresponse() if nodeHttpResponse.status == 200: xmlResponse = str(nodeHttpResponse.read(), 'utf-8') xmlObject = ET.fromstring(xmlResponse) nodeElement = xmlObject.findall('node')[0] # print(xmlResponse) nodesGeometry.append( (float(nodeElement.get('lon')), float(nodeElement.get('lat')))) else: raise TypeError( "No se pudo obtener información de nodo OSM" ) if ct['closed_way'] == 1: geometry = Polygon(nodesGeometry) else: geometry = LineString(nodesGeometry) geometries.append(geometry) else: raise TypeError( "No se pudo obtener información de way OSM " + str(wayHttpResponse.read(), 'utf-8')) geojson = geopandas.GeoSeries(geometries).__geo_interface__ # Agregando propiedades a cada uno de los Features del GEOJSON for index, item in enumerate(geojson['features']): properties = { 'id': str(cartografias[index]['cartografiaid']), 'tipo': cartografias[index]['tipo_elemento_osm'] } item['properties'] = properties response = { 'code': 200, 'geojson': json.dumps(geojson), 'status': 'success' } else: response = { 'code': 200, 'geojson': '{"type": "FeatureCollection", "features": []}', 'status': 'success' } #raise ObjectDoesNotExist("No hay cartografias para este instrumento") else: raise TypeError("Instrumento Inválido") except ObjectDoesNotExist as e: response = {'code': 404, 'message': str(e), 'status': 'error'} except ValidationError: response = {'code': 400, 'status': 'error'} except TypeError as e: response = {'code': 400, 'message': str(e), 'status': 'error'} except: response = {'code': 500, 'status': 'error'} return response
def equipoProyecto(request, proyid): try: if proyid is None: data = { 'code': 400, 'equipo': 'El proyecto no fue especificado', 'status': 'error' } else: #query = "select e.equid, u.userfullname, u.latitud, u.longitud, u.horaubicacion from v1.equipos as e inner join v1.usuarios as u on u.userid = e.userid where e.proyid = '" + proyid + "'" user = usuarioAutenticado(request) # Superadministrador o Proyectista if (str(user.rolid) == '628acd70-f86f-4449-af06-ab36144d9d6a' or str(user.rolid) == '8945979e-8ca5-481e-92a2-219dd42ae9fc'): query = "select distinct on(u.userid) \ u.userid, e.equid, u.userfullname, u.latitud, u.longitud, u.horaubicacion \ from v1.equipos as e \ inner join v1.usuarios as u on u.userid = e.userid \ and e.proyid = '{}'" \ .format(proyid) with connection.cursor() as cursor: cursor.execute(query) equipo = dictfetchall(cursor) for eq in equipo: eq['equipos'] = '' equiposUsuario = models.MiembroPlantilla.objects.filter(userid = eq['userid']) for equs in equiposUsuario: team = models.PlantillaEquipo.objects.get(pk=equs.planid) if team.userid == user.userid: eq['equipos'] += str(team.descripcion) + ', ' data = { 'code': 200, 'equipo': equipo, 'status': 'success' } else: data = { 'code': 403, 'message': 'Usuario no permitido', 'status': 'error' } except ValidationError as e: data = { 'code': 400, 'equipo': list(e), 'status': 'success' } return JsonResponse(data, safe = False, status = data['code'])
def usuariosDisponiblesProyecto(request, proyid): try: proyecto = models.Proyecto.objects.get(pk = proyid) user = usuarioAutenticado(request) # Superadministrador o Proyectista if (str(user.rolid) == '628acd70-f86f-4449-af06-ab36144d9d6a' or str(user.rolid) == '8945979e-8ca5-481e-92a2-219dd42ae9fc'): # Busqueda de Usuarios search = request.GET.get('search') # query = "select u.userid, u.userfullname from v1.usuarios u where (u.rolid = '0be58d4e-6735-481a-8740-739a73c3be86' or u.rolid = '53ad3141-56bb-4ee2-adcf-5664ba03ad65') and u.userid not in (select e.userid from v1.equipos e where e.proyid = '" + proyid + "')" query = "select distinct on(u.userid) \ u.userid, u.userfullname \ from v1.miembros_plantilla as mp \ inner join v1.usuarios as u on u.userid = mp.userid \ inner join v1.plantillas_equipo as pe on pe.planid = mp.planid \ where pe.userid = '{}' \ and u.userid not in (select e.userid from v1.equipos e where e.proyid = '{}') \ and (u.rolid = '0be58d4e-6735-481a-8740-739a73c3be86' or u.rolid = '53ad3141-56bb-4ee2-adcf-5664ba03ad65')" \ .format(user.userid, proyid) if search is not None: query += "and u.userfullname ~* '" + search + "'" with connection.cursor() as cursor: cursor.execute(query) usuarios = dictfetchall(cursor) for u in usuarios: u['equipos'] = '' equiposUsuario = models.MiembroPlantilla.objects.filter(userid=u['userid']) for equs in equiposUsuario: team = models.PlantillaEquipo.objects.get(pk=equs.planid) if team.userid == user.userid: u['equipos'] += str(team.descripcion) + ', ' data = { 'code': 200, 'usuarios': usuarios, 'status': 'success' } else: data = { 'code': 403, 'message': 'Usuario no permitido', 'status': 'error' } except ObjectDoesNotExist: data = { 'code': 404, 'message': 'El proyecto no existe', 'status': 'error' } except ValidationError as e: data = { 'code': 400, 'errors': tuple(e), 'status': 'error' } return JsonResponse(data, safe = False, status = data['code'])
def proyectosTareasVencidos(request): #proyectos = Proyecto.objects.all() with connection.cursor() as cursor: fechaActual = date.today().strftime("%Y-%m-%d") query = "SELECT p.proyid, p.proynombre, p.proydescripcion, proyfechacreacion, p.proyfechacierre from opx.proyectos as p " \ "WHERE p.proyfechacreacion <= '{0} 23:59:59' " \ "AND p.proyfechacierre <= '{0}'" \ .format(fechaActual) cursor.execute(query) proyectos = dictfetchall(cursor) data = [] project = {} tareasProyecto = [] progresoProyecto = 0 for proyecto in proyectos: progresoProyecto = 0 tareasProyecto = [] project = { 'id': proyecto['proyid'], 'name': proyecto['proynombre'], 'start': proyecto['proyfechacreacion'], 'end': proyecto['proyfechacierre'], 'dependencies': '', 'type': 'project' } tareas = Tarea.objects.filter(proyid__exact=proyecto['proyid']) for tarea in tareas: if tarea.taretipo == 1: task = { 'id': tarea.tareid, 'name': tarea.tarenombre, 'start': proyecto['proyfechacreacion'], 'end': proyecto['proyfechacierre'], 'dependencies': proyecto['proyid'], 'type': 'task' } encuestas = Encuesta.objects.filter(tareid__exact=tarea.tareid) progreso = (len(encuestas) * 100) / tarea.tarerestriccant task['progress'] = progreso tareasProyecto.append(task) progresoProyecto = progresoProyecto + progreso if progresoProyecto > 0: progresoProyecto = (progresoProyecto * 100) / (len(tareas) * 100) project['progress'] = progresoProyecto data.append(project) data.extend(tareasProyecto) response = {'code': 200, 'data': data, 'status': 'success'} return JsonResponse(response, safe=False, status=response['code'])