Beispiel #1
0
def gestionar_absentismo(request):
    g_e = request.session['gauser_extra']
    expedientes = ExpedienteAbsentismo.objects.filter(expedientado__ronda=g_e.ronda)[:10]

    if request.method == 'POST':
        if request.POST['action'] == 'pdf_absentismo' and g_e.has_permiso('crea_informe_absentismo'):
            doc_abs = 'Configuración de informes de absentismo'
            dce = get_dce(g_e.ronda.entidad, doc_abs)
            expediente = ExpedienteAbsentismo.objects.get(expedientado__ronda=g_e.ronda,
                                                          id=request.POST['expediente_id'])
            c = render_to_string('absentismo2pdf.html', {'expediente': expediente, 'MEDIA_ANAGRAMAS': MEDIA_ANAGRAMAS})
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            logger.info('%s, pdf_absentismo %s' % (g_e, expediente.id))
            response = HttpResponse(fich, content_type='application/pdf')
            alumno = slugify(expediente.expedientado.gauser.get_full_name())
            response['Content-Disposition'] = 'attachment; filename=expediente_absentismo_%s.pdf' % alumno
            return response

    return render(request, "absentismo.html",
                  {
                      'formname': 'absentismo',
                      'expedientes': expedientes,
                      'g_e': g_e,
                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False),
                  })
Beispiel #2
0
    def pdf_actividades(actividad):
        doc_act = 'Configuración de documentos para actividades'
        dce = get_dce(g_e.ronda.entidad, doc_act)
        if actividad == 'todas' and g_e.has_permiso(
                'crea_informe_actividades'):
            fecha_inicio = datetime.strptime(
                request.POST['search_fecha_inicio'], '%d-%m-%Y')
            fecha_fin = datetime.strptime(request.POST['search_fecha_fin'],
                                          '%d-%m-%Y')
            actividades = Actividad.objects.filter(
                organizador__ronda__entidad=g_e.ronda.entidad,
                fecha_hora_inicio__gte=fecha_inicio,
                fecha_hora_fin__lte=fecha_fin).order_by('fecha_inicio')
            fichero = 'memoria_extraescolares_' + str(
                g_e.ronda.entidad.code) + '.pdf'
            profesores = []
            # sub_docentes = Subentidad.objects.get(entidad=g_e.ronda.entidad, clave_ex='docente')
            # docentes = usuarios_de_gauss(g_e.ronda.entidad, subentidades=[sub_docentes])
            cargo = Cargo.objects.get(entidad=g_e.ronda.entidad,
                                      clave_cargo='g_docente')
            docentes = Gauser_extra.objects.filter(ronda=g_e.ronda,
                                                   cargos__in=[cargo])

            for docente in docentes:
                organizaciones_actividad = actividades.filter(
                    organizador=docente).distinct()
                colaboraciones_actividad = actividades.filter(
                    colaboradores__in=[docente]).distinct()
                duracion_mayor_un_dia = actividades.filter(
                    Q(colaboradores__in=[docente]) | Q(organizador=docente),
                    ~Q(fecha_inicio=F('fecha_fin'))).distinct()
                profesores.append({
                    'docente':
                    docente.gauser.get_full_name(),
                    'organizaciones_actividad':
                    organizaciones_actividad,
                    'colaboraciones_actividad':
                    colaboraciones_actividad,
                    'duracion_mayor_un_dia':
                    duracion_mayor_un_dia
                })
        else:
            actividades = Actividad.objects.filter(pk=actividad)
            fichero = 'actividad_%s_%s.pdf' % (g_e.ronda.entidad.code,
                                               actividad)
            profesores = []
        c = render_to_string('actividades2pdf.html', {
            'actividades': actividades,
            'profesores': profesores
        },
                             request=request)
        fich = pdfkit.from_string(c, False, dce.get_opciones)
        logger.info('%s, pdf_informe_actividades' % g_e)
        response = HttpResponse(fich, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=' + fichero
        return response
Beispiel #3
0
def presupuesto(request, id=False):
    if id:
        g_e = request.session["gauser_extra"]
        try:
            presupuesto = Presupuesto.objects.get(entidad=g_e.ronda.entidad, id=id)
        except:
            return HttpResponseRedirect(reverse('presupuestos'))
    else:
        return HttpResponseRedirect(reverse('presupuestos'))

    partidas = Partida.objects.filter(presupuesto=presupuesto)

    if request.method == 'POST':
        if request.POST['action'] == 'pdf_presupuesto':
            dce = get_dce(g_e.ronda.entidad, 'Configuración de informes de contabilidad')
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            partidas = Partida.objects.filter(presupuesto=presupuesto)
            gastos = partidas.filter(tipo='GASTO').aggregate(gasto_total=Sum('cantidad'))
            ingresos = partidas.filter(tipo='INGRE').aggregate(ingreso_total=Sum('cantidad'))

            fichero = 'presupuesto_%s_%s' % (g_e.ronda.entidad.id, g_e.ronda.id)
            c = render_to_string('presupuesto2pdf.html',
                                 {'presupuesto': presupuesto, 'partidas': partidas, 'gastos': gastos,
                                  'ingresos': ingresos})
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            response = HttpResponse(fich, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=' + fichero + '.pdf'
            return response

    gastos = partidas.filter(tipo='GASTO').aggregate(gasto_total=Sum('cantidad'))
    ingresos = partidas.filter(tipo='INGRE').aggregate(ingreso_total=Sum('cantidad'))
    return render(request, "presupuesto.html",
                  {
                      'formname': 'Presupuesto',
                      'iconos':
                          ({'tipo': 'button', 'nombre': 'check', 'texto': 'Aceptar',
                            'title': 'Aceptar los cambios realizados', 'permiso': 'edita_presupuestos'},
                           {'tipo': 'button', 'nombre': 'plus', 'texto': 'Partida',
                            'title': 'Añadir nueva partida al presupuesto',
                            'permiso': 'edita_presupuestos'},
                           {'tipo': 'button', 'nombre': 'pencil', 'texto': 'Editar',
                            'title': 'Editar la partida para su modificación',
                            'permiso': 'edita_presupuestos'},
                           {'tipo': 'button', 'nombre': 'trash-o', 'texto': 'Borrar',
                            'title': 'Borrar la partida seleccionada', 'permiso': 'edita_presupuestos'},
                           {'tipo': 'button', 'nombre': 'file-text-o', 'texto': 'PDF',
                            'title': 'Generar documento pdf del presupuesto',
                            'permiso': 'edita_presupuestos'}),
                      'presupuesto': presupuesto,
                      'partidas': partidas,
                      'gastos': gastos,
                      'ingresos': ingresos,
                      'avisos': Aviso.objects.filter(usuario=request.session["gauser_extra"],
                                                     aceptado=False),
                  })
Beispiel #4
0
def politica_cuotas(request):
    g_e = request.session['gauser_extra']
    if request.method == 'POST':
        if request.POST['action'] == 'pdf_politicas_cuotas':
            dce = get_dce(g_e.ronda.entidad, 'Configuración de informes de contabilidad')
            politicas = Politica_cuotas.objects.filter(entidad=g_e.ronda.entidad)
            fichero = 'Politica_cuotas_%s_%s' % (g_e.ronda.entidad.id, g_e.ronda.id)
            c = render_to_string('politica_cuotas2pdf.html', {'politicas': politicas})
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            response = HttpResponse(fich, content_type='application/pdf')
            response.set_cookie('fileDownload',
                                value='true')  # Creo cookie para controlar la descarga (fileDownload.js)
            response['Content-Disposition'] = 'attachment; filename=' + fichero + '.pdf'
            return response
        elif request.POST['action'] == 'descarga_remesa':
            remesa_emitida = Remesa_emitida.objects.get(id=request.POST['id_remesa_emitida'])
            ruta = MEDIA_CONTABILIDAD + str(g_e.ronda.entidad.code) + '/'
            grupo = remesa_emitida.grupo
            fichero = '%s.xml' % (grupo)
            xmlfile = open(ruta + fichero, 'rb')
            response = HttpResponse(xmlfile, content_type='application/xml')
            response['Content-Disposition'] = 'attachment; filename=Remesas_%s-%s-%s.xml' % (
                remesa_emitida.creado.year, remesa_emitida.creado.month, remesa_emitida.creado.day)
            return response
        elif request.POST['action'] == 'descarga_excel':
            remesa_emitida = Remesa_emitida.objects.get(id=request.POST['id_remesa_emitida'])
            ruta = MEDIA_CONTABILIDAD + str(g_e.ronda.entidad.code) + '/'
            grupo = remesa_emitida.grupo
            fichero = '%s.xls' % (grupo)
            xlsfile = open(ruta + '/' + fichero, 'rb')
            response = HttpResponse(xlsfile, content_type='application/vnd.ms-excel')
            response['Content-Disposition'] = 'attachment; filename=Remesas_%s-%s-%s.xls' % (
                remesa_emitida.creado.year, remesa_emitida.creado.month, remesa_emitida.creado.day)
            return response
    try:
        Politica_cuotas.objects.get(entidad=g_e.ronda.entidad, tipo='extraord', seqtp='OOFF').delete()
    except:
        pass
        # pext = Politica_cuotas.objects.create(entidad=g_e.ronda.entidad, tipo='extraord', tipo_cobro='ANU',
        #                                       concepto='Remesa extraordinaria', seqtp='OOFF')
    politicas = Politica_cuotas.objects.filter(entidad=g_e.ronda.entidad)
    return render(request, "politica_cuotas.html",
                  {
                      'formname': 'Politica_cuotas',
                      'iconos':
                          ({'tipo': 'button', 'nombre': 'plus', 'texto': 'Política',
                            'title': 'Añadir una nueva política de cuotas', 'permiso': 'crea_politica_cuotas'},
                           {'tipo': 'button', 'nombre': 'file-text-o', 'texto': 'PDF',
                            'permiso': 'libre',
                            'title': 'Genera documento PDF con las políticas de cuotas'}),
                      'politicas': politicas,
                      'g_e': g_e,
                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False),
                  })
Beispiel #5
0
def gestionar_reparaciones(request):
    g_e = request.session["gauser_extra"]
    if request.method == 'POST':
        if request.POST['action'] == 'genera_informe' and g_e.has_permiso('genera_informe_reparaciones'):
            doc_rep = 'Configuración de informes de reparaciones'
            dce = get_dce(g_e.ronda.entidad, doc_rep)
            try:
                inicio = datetime.strptime(request.POST['id_fecha_inicio'], '%d-%m-%Y')
            except:
                inicio = datetime.strptime('01-01-2000', '%d-%m-%Y')
            try:
                fin = datetime.strptime(request.POST['id_fecha_fin'], '%d-%m-%Y')
            except:
                fin = datetime.strptime('01-01-3000', '%d-%m-%Y')
            texto = request.POST['busca_reparaciones'] if request.POST['busca_reparaciones'] else ' '
            tipos = ['inf', 'ele', 'fon', 'alb', 'gen', 'car']
            tipo = [request.POST['tipo_busqueda']] if request.POST['tipo_busqueda'] in tipos else tipos
            q_texto = Q(describir_problema__icontains=texto) | Q(describir_solucion__icontains=texto)
            q_inicio = Q(fecha_comunicado__gte=inicio)
            q_fin = Q(fecha_comunicado__lte=fin)
            q_tipo = Q(tipo__in=tipo)
            q_entidad = Q(detecta__ronda__entidad=g_e.ronda.entidad)
            reparaciones = Reparacion.objects.filter(q_entidad, q_texto, q_inicio, q_fin, q_tipo)

            fichero = 'Reparaciones%s_%s_%s' % (
                str(g_e.ronda.entidad.code), request.POST['tipo_busqueda'], g_e.gauser.username)
            c = render_to_string('reparaciones2pdf.html', {'reparaciones': reparaciones, 'MA': MEDIA_ANAGRAMAS, })
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            logger.info('%s, pdf_reparaciones' % g_e)
            response = HttpResponse(fich, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=' + fichero + '.pdf'
            return response

    Reparacion.objects.filter(detecta__ronda__entidad=g_e.ronda.entidad, borrar=True).delete()
    reparaciones = Reparacion.objects.filter(detecta__ronda__entidad=g_e.ronda.entidad, fecha_comunicado__gte=g_e.ronda.inicio,
                                             detecta__ronda=g_e.ronda).order_by('-fecha_comunicado', 'resuelta')

    return render(request, "reparaciones.html",
                  {
                      'iconos':
                          ({'tipo': 'button', 'nombre': 'plus', 'texto': 'Añadir',
                            'title': 'Crear una nueva solicitud de reparación',
                            'permiso': 'crea_solicitud_reparacion'},
                           {'tipo': 'button', 'nombre': 'file-pdf-o', 'texto': 'Informe',
                            'title': 'Generar informe con las reparaciones de la entidad',
                            'permiso': 'genera_informe_reparaciones'},
                           ),
                      'formname': 'Reparaciones',
                      'reparaciones': reparaciones,
                      'g_e': g_e,
                      'avisos': Aviso.objects.filter(usuario=request.session["gauser_extra"],
                                                     aceptado=False),
                  })
Beispiel #6
0
def ordenes_adeudo(request):
    g_e = request.session['gauser_extra']
    if request.method == 'POST':
        dce = get_dce(g_e.ronda.entidad, 'Configuración para órdenes de adeudo')
        orden = OrdenAdeudo.objects.get(id=request.POST['orden_id'], politica__entidad=g_e.ronda.entidad,
                                        firma__isnull=False, gauser=g_e.gauser)
        c = orden.texto_firmado
        pdfkit.from_string(c, dce.url_pdf, dce.get_opciones)
        fich = open(dce.url_pdf, 'rb')
        response = HttpResponse(fich, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=orden_adeudo_directo_SEPA%s.pdf' % orden.id
        return response
    ordenes_firmadas = OrdenAdeudo.objects.filter(fecha_firma__isnull=False, politica__entidad=g_e.ronda.entidad)
    politicas = Politica_cuotas.objects.filter(entidad=g_e.entidad)
    return render(request, "ordenes_adeudo.html",
                  {
                      'formname': 'ordenes_adeudo',
                      'ordenes_firmadas': ordenes_firmadas,
                      'politicas': politicas,
                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False)
                  })
Beispiel #7
0
def mis_ordenes_adeudo(request):
    g_e = request.session['gauser_extra']
    if request.method == 'POST':
        dce = get_dce(g_e.ronda.entidad, 'Configuración para órdenes de adeudo')
        orden = OrdenAdeudo.objects.get(id=request.POST['orden_id'], politica__entidad=g_e.ronda.entidad,
                                        firma__isnull=False, gauser=g_e.gauser)
        c = orden.texto_firmado
        pdfkit.from_string(c, dce.url_pdf, dce.get_opciones)
        fich = open(dce.url_pdf, 'rb')
        response = HttpResponse(fich, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=orden_adeudo_directo_SEPA%s.pdf' % orden.id
        return response
    mis_ordenes_firmadas = OrdenAdeudo.objects.filter(gauser=g_e.gauser, fecha_firma__isnull=False,
                                                      politica__entidad=g_e.ronda.entidad)
    mis_ordenes_pendientes = comprueba_ordenes_adeudo(g_e)
    return render(request, "mis_ordenes_adeudo.html",
                  {
                      'formname': 'mis_ordenes_adeudo',
                      'mis_ordenes_firmadas': mis_ordenes_firmadas,
                      'mis_ordenes_pendientes': mis_ordenes_pendientes,
                      'g_e': g_e
                  })
Beispiel #8
0
def informes_seguimiento(request):
    g_e = request.session['gauser_extra']
    informes_solicitados = Informe_seguimiento.objects.filter(
        solicitante=g_e, usuario__entidad=g_e.ronda.entidad).distinct()
    informes_a_rellenar = Informe_seguimiento.objects.filter(
        Q(usuarios_destino__in=[g_e]), Q(deadline__gte=date.today()),
        ~Q(id__in=informes_solicitados)).distinct()

    if request.method == 'POST':
        if request.POST['action'] == 'pdf_informe_seguimiento':
            informe = Informe_seguimiento.objects.get(
                usuario__ronda=g_e.ronda, id=request.POST['informe_id'])
            if informe.solicitante == g_e or g_e.has_permiso(
                    've_informes_seguimiento'):
                doc_seg = 'Configuración de informes de seguimiento'
                dce = get_dce(g_e.ronda.entidad, doc_seg)
                c = render_to_string('informe_seguimiento2pdf.html', {
                    'informe': informe,
                    'MEDIA_ANAGRAMAS': MEDIA_ANAGRAMAS,
                })
                fich = pdfkit.from_string(c, False, dce.get_opciones)
                logger.info('%s, pdf_informe_seguimiento %s' %
                            (g_e, informe.id))
                response = HttpResponse(fich, content_type='application/pdf')
                usuario = slugify(informe.usuario.gauser.get_full_name())
                response[
                    'Content-Disposition'] = 'attachment; filename=Informe_Seguimiento_%s.pdf' % usuario
                return response

    return render(
        request, "informes_seguimiento.html", {
            'formname': 'informe_seguimiento',
            'informes_solicitados': informes_solicitados,
            'informes_a_rellenar': informes_a_rellenar,
            'g_e': g_e,
            'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False)
        })
Beispiel #9
0
def sancionar_conductas(request):
    g_e = request.session['gauser_extra']

    inf_actual = None
    if request.method == 'POST' and not request.is_ajax():
        if request.POST['action'] == 'genera_pdf':
            doc_ie = 'Configuración de informes sancionadores de alumnos'
            dce = get_dce(entidad=g_e.ronda.entidad, nombre=doc_ie)
            informe = Informe_sancionador.objects.get(
                sancionado__ronda=g_e.ronda, id=request.POST['inf_actual'])
            coherente, mensaje = informe.is_coherente
            if coherente:
                if informe.fichero:
                    os.remove(informe.fichero.path)
                listar_conductas, informes, expulsiones = False, None, None
                if 'listar_conductas' in request.POST:
                    listar_conductas = True
                    informes = Informe_sancionador.objects.filter(
                        sancionado=informe.sancionado)
                    sanciones_expulsion = Sancion.objects.filter(
                        entidad=g_e.ronda.entidad, expulsion=True)
                    expulsiones = informes.filter(
                        sanciones__in=sanciones_expulsion)
                # Código para enviar correo
                asunto = render_to_string(
                    'informe_sancionador_mail_asunto.html',
                    {'informe': informe})
                texto = render_to_string('informe_sancionador_mail.html',
                                         {'informe': informe})
                permisos = ['recibe_mensajes_aviso_informes_sancionadores']
                cargos = Cargo.objects.filter(
                    permisos__code_nombre__in=permisos,
                    entidad=g_e.ronda.entidad).distinct()
                try:
                    tutor = informe.sancionado.gauser_extra_estudios.tutor.id
                    q = Q(permisos__code_nombre__in=permisos) | Q(
                        cargos__in=cargos) | Q(id=tutor)
                except:
                    q = Q(permisos__code_nombre__in=permisos) | Q(
                        cargos__in=cargos)
                receptores = Gauser_extra.objects.filter(
                    Q(activo=True), Q(ronda=g_e.ronda),
                    q).values_list('gauser__id', flat=True).distinct()
                try:
                    # Comprobamos si un mensaje igual se ha mandado ya
                    Mensaje.objects.get(emisor=g_e,
                                        asunto=asunto,
                                        mensaje=texto)
                except:
                    mc = Mensaje_cola.objects.filter(mensaje__emisor=g_e,
                                                     mensaje__asunto=asunto,
                                                     enviado=False)
                    if mc.count() > 0:
                        mc[0].mensaje.delete()
                        mc.delete()
                    encolar_mensaje(emisor=g_e,
                                    receptores=receptores,
                                    asunto=asunto,
                                    html=texto,
                                    etiqueta='is%s' % informe.id)
                # Fin de código para enviar correo
                texto_html = render_to_string(
                    'is2pdf.html', {
                        'informe': informe,
                        'MEDIA_ANAGRAMAS': MEDIA_ANAGRAMAS,
                        'listar_conductas': listar_conductas,
                        'expulsiones': expulsiones,
                        'informes': informes
                    })
                nombre = '%s_%s.pdf' % (
                    slugify(informe.sancionado.gauser.get_full_name()),
                    timezone.localtime(
                        informe.created).strftime('%d-%m-%Y_%H%M'))
                url_pdf = MEDIA_CONVIVENCIA + '%s/%s' % (
                    g_e.ronda.entidad.code, nombre)
                pdfkit.from_string(texto_html, url_pdf, dce.get_opciones)
                fich = open(url_pdf, 'rb')
                informe.texto_html = texto_html
                nombre_fichero = 'convivencia/%s/%s' % (g_e.ronda.entidad.code,
                                                        nombre)
                informe.fichero.save(nombre_fichero, File(fich))
                fich.close()
                informe.save()
                response = HttpResponse(informe.fichero,
                                        content_type='application/pdf')
                response[
                    'Content-Disposition'] = 'attachment; filename=%s' % nombre
                return response
            else:
                inf_actual = informe
                crear_aviso(request, False, '<ul>%s</ul>' % mensaje)
        if request.POST['action'] == 'descargar_informe':
            informe = Informe_sancionador.objects.get(
                sancionado__ronda=g_e.ronda, id=request.POST['inf_descargar'])
            filename = informe.fichero.name.split('/')[-1]
            response = HttpResponse(informe.fichero,
                                    content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename=%s' % filename
            return response

    informes = Informe_sancionador.objects.filter(Q(sancionador=g_e),
                                                  ~Q(fichero=''))
    informes_como_tutor = Informe_sancionador.objects.filter(
        Q(sancionado__gauser_extra_estudios__tutor=g_e),
        ~Q(fichero='')).exclude(id__in=informes)
    respuesta = {
        'iconos': ({
            'tipo': 'button',
            'nombre': 'file-pdf-o',
            'texto': 'Generar',
            'title': 'Generar informe sancionador',
            'permiso': 'genera_informe_sancionador'
        }, ),
        'formname':
        'gestionar_conductas',
        'conductas':
        Conducta.objects.filter(entidad=g_e.ronda.entidad),
        'sanciones':
        Sancion.objects.filter(entidad=g_e.ronda.entidad),
        'informes':
        informes,
        'informes_como_tutor':
        informes_como_tutor,
        'inf_actual':
        inf_actual,
        'avisos':
        Aviso.objects.filter(usuario=g_e, aceptado=False),
    }
    return render(request, "sancionar_conductas.html", respuesta)
Beispiel #10
0
def informes_tareas(request):
    g_e = request.session['gauser_extra']
    informes_solicitados = Informe_tareas.objects.filter(
        solicitante=g_e, usuario__entidad=g_e.ronda.entidad).distinct()
    informes_a_rellenar = Informe_tareas.objects.filter(
        Q(usuario__entidad=g_e.ronda.entidad), Q(usuarios_destino__in=[g_e]),
        Q(deadline__gte=date.today()),
        ~Q(id__in=informes_solicitados)).distinct()

    if request.method == 'POST':
        if request.POST['action'] == 'pdf_informe_tareas':
            doc_tar = 'Configuración de informes con tareas'
            dce = get_dce(g_e.ronda.entidad, doc_tar)
            informe = Informe_tareas.objects.get(usuario__ronda=g_e.ronda,
                                                 id=request.POST['informe_id'])
            ficheros_list = Fichero_tarea.objects.filter(
                tarea__informe=informe)
            if informe.solicitante == g_e or g_e.has_permiso(
                    've_informes_tareas'):
                fichero = 'informe_informe_tareas_%s_%s.pdf' % (
                    g_e.ronda.entidad.code, informe.id)
                c = render_to_string('informe_tareas2pdf.html', {
                    'informe': informe,
                    'ficheros_list': ficheros_list,
                })
                ruta = MEDIA_INFORMES + '%s/' % g_e.ronda.entidad.code
                informe_pdf = ruta + '%s' % fichero
                pdfkit.from_string(c, informe_pdf, dce.get_opciones)
                if ficheros_list.count() > 0:
                    ruta_zip = ruta + 'informe_informe_tareas_%s_%s.zip' % (
                        g_e.ronda.entidad.code, informe.id)
                    with ZipFile(ruta_zip, 'w') as zipObj:
                        # Añadir varios archivos en un ZIP
                        # Primero incluimos el pdf y después los archivos adjuntos
                        zipObj.write(informe_pdf,
                                     os.path.basename(informe_pdf))
                        for f in ficheros_list:
                            zipObj.write(f.fichero.path,
                                         os.path.basename(f.fichero.path))
                    logger.info('%s, pdf_informe_tareas %s' %
                                (g_e, informe.id))
                    response = FileResponse(open(ruta_zip, 'rb'))
                    response[
                        'Content-Disposition'] = 'attachment; filename=informe_informe_tareas_%s_%s.zip' % (
                            slugify(informe.usuario.gauser.get_full_name()),
                            str(informe.id))
                    return response
                else:
                    logger.info('%s, pdf_informe_tareas %s' %
                                (g_e, informe.id))
                    response = FileResponse(open(informe_pdf, 'rb'))
                    response[
                        'Content-Disposition'] = 'attachment; filename=informe_informe_tareas_%s_%s.pdf' % (
                            slugify(informe.usuario.gauser.get_full_name()),
                            str(informe.id))
                    return response

    return render(
        request, "informes_tareas.html", {
            'formname': 'informe_tareas',
            'informes_solicitados': informes_solicitados,
            'informes_a_rellenar': informes_a_rellenar,
            'g_e': g_e,
            'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False)
        })
Beispiel #11
0
def cc_configuracion(request):
    g_e = request.session["gauser_extra"]
    # Etapas afectas-> da:secundaria
    etapas = ['da']
    materias = Materia.objects.filter(curso__ronda=g_e.ronda)
    for materia in materias:
        CompetenciasMateria.objects.get_or_create(materia=materia,
                                                  ronda=g_e.ronda)
    if request.method == 'POST' and request.is_ajax():
        action = request.POST['action']
        if action == 'mod_percentage':
            try:
                competenciasmateria = CompetenciasMateria.objects.get(
                    id=request.POST['materia'])
                setattr(competenciasmateria, request.POST['cc'],
                        int(request.POST['valor']))
                competenciasmateria.save()
                t = competenciasmateria.total_percentage
                mensaje = False
                if (100 - t) < 0:
                    setattr(competenciasmateria, request.POST['cc'],
                            int(request.POST['valor']) + 100 - t)
                    competenciasmateria.save()
                    mensaje = True
                valor = getattr(competenciasmateria, request.POST['cc'])
                return JsonResponse({
                    'ok': True,
                    'total': t,
                    'mensaje': mensaje,
                    'cm': competenciasmateria.id,
                    'valor': valor,
                    'cc': request.POST['cc']
                })
            except:
                return JsonResponse({'ok': False})
        elif action == 'open_accordion':
            curso = Curso.objects.get(id=request.POST['id'], ronda=g_e.ronda)
            materias = CompetenciasMateria.objects.filter(materia__curso=curso)
            html = render_to_string('cc_configuracion_curso_content.html',
                                    {'materias': materias})
            return JsonResponse({'ok': True, 'html': html})
            alumnos = Gauser_extra_estudios.objects.filter(
                grupo__id=request.POST['id'])
            cm = CompetenciasMateria.objects.get(id=request.POST['cm'])
            for a in alumnos:
                CompetenciasMateriaAlumno.objects.get_or_create(profesor=g_e,
                                                                alumno=a.ge,
                                                                materia=cm)
            cmas = CompetenciasMateriaAlumno.objects.filter(
                profesor=g_e,
                materia=cm,
                alumno__gauser_extra_estudios__grupo__id=request.POST['id'])
            html = render_to_string(
                'cc_alumnos_grupo.html',
                {'cmas': cmas.order_by('alumno__gauser__last_name')})
            return JsonResponse({'ok': True, 'html': html})
        elif action == 'mod_valor':
            try:
                competenciasmateriaalumno = CompetenciasMateriaAlumno.objects.get(
                    id=request.POST['cma'])
                setattr(competenciasmateriaalumno, request.POST['cc'],
                        int(request.POST['v']))
                competenciasmateriaalumno.save()
                return JsonResponse({'ok': True})
            except:
                return JsonResponse({'ok': False})
        elif action == 'nota':
            try:
                nota = int(request.POST['nota'])
                ccs = ['ccl', 'cmct', 'cd', 'cpaa', 'csc', 'sie', 'cec']
                competenciasmateriaalumno = CompetenciasMateriaAlumno.objects.get(
                    id=request.POST['cma'], profesor=g_e)
                for cc in ccs:
                    setattr(competenciasmateriaalumno, cc, nota)
                    competenciasmateriaalumno.save()
                return JsonResponse({'ok': True, 'nota': nota})
            except:
                return JsonResponse({'ok': False})
    elif request.method == 'POST':
        if request.POST['action'] == 'informe_pdf' and g_e.has_permiso(
                'genera_informe_ccs'):
            doc_cc = 'Configuración de informes Competencias Clave'
            dce = get_dce(g_e.ronda.entidad, doc_cc)
            cmas = CompetenciasMateriaAlumno.objects.filter(
                profesor__ronda=g_e.ronda,
                materia__materia__curso__etapa__in=etapas)
            ids = cmas.values_list('alumno', flat=True).distinct()
            alumnos = Gauser_extra.objects.filter(
                id__in=ids).order_by('gauser_extra_estudios__grupo')
            fichero = 'valoracionesCC_%s.pdf' % str(g_e.ronda.entidad.code)
            c = render_to_string('valoracionescc2pdf.html', {
                'alumnos': alumnos,
            })
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            response = HttpResponse(fich, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=' + fichero
            return response

    respuesta = {
        'formname': 'configura_materias_pendientes',
        'cursos': Curso.objects.filter(ronda=g_e.ronda, etapa='da'),
        'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False)
    }
    return render(request, "cc_configuracion.html", respuesta)
Beispiel #12
0
def cc_valorar_mis_alumnos(request):
    g_e = request.session["gauser_extra"]
    # Etapas afectas-> da:secundaria
    etapas = ['da']
    if request.method == 'GET':
        if 'm' in request.GET:
            id = request.GET['m']

    horario = Horario.objects.get(entidad=g_e.ronda.entidad,
                                  predeterminado=True)
    sesiones = Sesion.objects.filter(horario=horario,
                                     g_e=g_e,
                                     grupo__isnull=False)
    materias_id = sesiones.values_list('materia__id', flat=True).distinct()
    materias = Materia.objects.filter(id__in=materias_id,
                                      curso__etapa__in=etapas)
    try:
        materia_seleccionada = materias.get(id=id)
    except:
        try:
            materia_seleccionada = materias[0]
        except:
            materia_seleccionada = None
    competenciasmateria, c = CompetenciasMateria.objects.get_or_create(
        ronda=g_e.ronda, materia=materia_seleccionada)
    grupos_id_materia_seleccionada = sesiones.filter(
        materia=materia_seleccionada).values_list('grupo__id',
                                                  flat=True).distinct()
    grupos_materia_seleccionada = Grupo.objects.filter(
        id__in=grupos_id_materia_seleccionada)
    if request.method == 'POST' and request.is_ajax():
        action = request.POST['action']
        if action == 'mod_percentage':
            try:
                competenciasmateria = CompetenciasMateria.objects.get(
                    id=request.POST['cm'])
                setattr(competenciasmateria, request.POST['cc'],
                        int(request.POST['v']))
                competenciasmateria.save()
                t = competenciasmateria.total_percentage
                mensaje = False
                if (100 - t) < 0:
                    setattr(competenciasmateria, request.POST['cc'],
                            int(request.POST['v']) + 100 - t)
                    competenciasmateria.save()
                    mensaje = True
                return JsonResponse({
                    'ok':
                    True,
                    'total':
                    t,
                    'mensaje':
                    mensaje,
                    'valor':
                    getattr(competenciasmateria, request.POST['cc'])
                })
            except:
                return JsonResponse({'ok': False})
        elif action == 'open_accordion':
            alumnos = Gauser_extra_estudios.objects.filter(
                grupo__id=request.POST['id'])
            cm = CompetenciasMateria.objects.get(id=request.POST['cm'])
            for a in alumnos:
                CompetenciasMateriaAlumno.objects.get_or_create(profesor=g_e,
                                                                alumno=a.ge,
                                                                materia=cm)
            cmas = CompetenciasMateriaAlumno.objects.filter(
                profesor=g_e,
                materia=cm,
                alumno__gauser_extra_estudios__grupo__id=request.POST['id'])
            html = render_to_string(
                'cc_alumnos_grupo.html',
                {'cmas': cmas.order_by('alumno__gauser__last_name')})
            return JsonResponse({'ok': True, 'html': html})
        elif action == 'mod_valor':
            try:
                competenciasmateriaalumno = CompetenciasMateriaAlumno.objects.get(
                    id=request.POST['cma'])
                setattr(competenciasmateriaalumno, request.POST['cc'],
                        int(request.POST['v']))
                competenciasmateriaalumno.save()
                return JsonResponse({'ok': True})
            except:
                return JsonResponse({'ok': False})
        elif action == 'nota':
            try:
                nota = int(request.POST['nota'])
                ccs = ['ccl', 'cmct', 'cd', 'cpaa', 'csc', 'sie', 'cec']
                competenciasmateriaalumno = CompetenciasMateriaAlumno.objects.get(
                    id=request.POST['cma'], profesor=g_e)
                for cc in ccs:
                    setattr(competenciasmateriaalumno, cc, nota)
                    competenciasmateriaalumno.save()
                return JsonResponse({'ok': True, 'nota': nota})
            except:
                return JsonResponse({'ok': False})
    elif request.method == 'POST':
        if request.POST['action'] == 'informe_pdf' and g_e.has_permiso(
                'genera_informe_ccs'):
            doc_cc = 'Configuración de informes Competencias Clave'
            dce = get_dce(g_e.ronda.entidad, doc_cc)
            cmas = CompetenciasMateriaAlumno.objects.filter(
                profesor__ronda=g_e.ronda,
                materia__materia__curso__etapa__in=etapas)
            ids = cmas.values_list('alumno', flat=True).distinct()
            alumnos = Gauser_extra.objects.filter(
                id__in=ids).order_by('gauser_extra_estudios__grupo')
            fichero = 'valoracionesCC_%s.pdf' % str(g_e.ronda.entidad.code)
            c = render_to_string('valoracionescc2pdf.html', {
                'alumnos': alumnos,
            })
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            logger.info('%s, pdf_cc_valorar_mis_alumnos' % g_e)
            response = HttpResponse(fich, content_type='application/pdf')
            response[
                'Content-Disposition'] = 'attachment; filename=%s' % fichero
            return response

    return render(
        request, "cc_valorar_mis_alumnos.html", {
            'iconos': ({
                'tipo': 'button',
                'nombre': 'file-pdf-o',
                'texto': 'Informe',
                'title': 'Generar informe competencias clave',
                'permiso': 'genera_informe_ccs'
            }, ),
            'formname':
            'cc_valorar_mis_alumnos',
            'materias':
            materias,
            'materia_seleccionada':
            materia_seleccionada,
            'grupos_materia_seleccionada':
            grupos_materia_seleccionada,
            'competenciasmateria':
            competenciasmateria
        })
Beispiel #13
0
def presupuestos(request):
    g_e = request.session["gauser_extra"]
    if request.method == 'POST':
        if request.POST['action'] == 'pdf_presupuesto':
            dce = get_dce(g_e.ronda.entidad, 'Configuración de informes de contabilidad')
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            partidas = Partida.objects.filter(presupuesto=presupuesto)
            gastos = partidas.filter(tipo='GASTO').aggregate(gasto_total=Sum('cantidad'))
            ingresos = partidas.filter(tipo='INGRE').aggregate(ingreso_total=Sum('cantidad'))
            fichero = 'presupuesto_%s_%s' % (g_e.ronda.entidad.id, presupuesto.id)
            c = render_to_string('presupuesto2pdf.html',
                                 {'presupuesto': presupuesto, 'partidas': partidas, 'gastos': gastos,
                                  'ingresos': ingresos})
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            logger.info('%s, pdf_presupuesto' % g_e)
            response = HttpResponse(fich, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=' + fichero + '.pdf'
            return response
        elif request.POST['action'] == 'add_presupuesto':
            describir = request.POST['describir']
            describir = 'No hay descripción para este presupesto.' if len(describir) < 5 else describir
            Presupuesto.objects.create(nombre=request.POST['nombre'], describir=describir, entidad=g_e.ronda.entidad)
        elif request.POST['action'] == 'mod_presupuesto':
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            presupuesto.nombre = request.POST['nombre']
            presupuesto.describir = request.POST['describir']
            presupuesto.save()
        elif request.POST['action'] == 'borrar_presupuesto':
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            if Partida.objects.filter(presupuesto=presupuesto).count() == 0:
                presupuesto.delete()
            else:
                crear_aviso(request, False, 'El presupuesto no se puede borrar porque contiene partidas')
        elif request.POST['action'] == 'copiar_presupuesto':
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            p = Presupuesto.objects.create(entidad=g_e.ronda.entidad, nombre=presupuesto.nombre + ' (copia)',
                                           describir=presupuesto.describir)
            partidas = Partida.objects.filter(presupuesto=presupuesto)
            for partida in partidas:
                Partida.objects.create(presupuesto=p, tipo=partida.tipo, nombre=partida.nombre,
                                       cantidad=partida.cantidad)
        elif request.POST['action'] == 'archivar_presupuesto':
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            presupuesto.archivado = True
            presupuesto.save()
        elif request.POST['action'] == 'abrir_presupuesto':
            presupuesto = Presupuesto.objects.get(id=request.POST['id_presupuesto'], entidad=g_e.ronda.entidad)
            presupuesto.archivado = False
            presupuesto.save()

    presupuestos = Presupuesto.objects.filter(entidad=g_e.ronda.entidad)
    return render(request, "presupuestos_list.html",
                  {
                      'formname': 'Presupuestos',
                      'iconos':
                          ({'tipo': 'button', 'nombre': 'check', 'texto': 'Aceptar',
                            'title': 'Aceptar los cambios realizados', 'permiso': 'edita_presupuestos'},
                           {'tipo': 'button', 'nombre': 'plus', 'texto': 'Presupuesto',
                            'title': 'Crear un nuevo presupuesto',
                            'permiso': 'crea_presupuestos'},
                           {'tipo': 'button', 'nombre': 'list-alt', 'texto': 'Presupuestos',
                            'title': 'Mostrar la lista de presupuestos',
                            'permiso': 'edita_presupuestos'},),
                      'presupuestos': presupuestos,
                      'avisos': Aviso.objects.filter(usuario=request.session["gauser_extra"],
                                                     aceptado=False),
                  })
Beispiel #14
0
def gastos_ingresos(request):
    g_e = request.session["gauser_extra"]
    if request.method == 'POST':
        presupuestos = None
        presupuesto = Presupuesto.objects.get(entidad=g_e.ronda.entidad, id=request.POST['id_presupuesto'])
        asientos = Asiento.objects.filter(partida__presupuesto=presupuesto)
        partidas_gastos = Partida.objects.filter(presupuesto=presupuesto, tipo='GASTO')
        partidas_ingresos = Partida.objects.filter(presupuesto=presupuesto, tipo='INGRE')
        if request.POST['action'] == 'pdf_gastos_ingresos':
            dce = get_dce(g_e.ronda.entidad, 'Configuración de informes de contabilidad')
            gi_gastos = []
            for partida in partidas_gastos:
                asientos_partida = Asiento.objects.filter(partida=partida)
                total_partida = asientos_partida.aggregate(total=Sum('cantidad'))
                gi_gastos.append([partida, asientos_partida, total_partida['total']])
            gi_ingresos = []
            for partida in partidas_ingresos:
                asientos_partida = Asiento.objects.filter(partida=partida)
                total_partida = asientos_partida.aggregate(total=Sum('cantidad'))
                gi_ingresos.append([partida, asientos_partida, total_partida['total']])
            fichero = 'gastos_ingresos_%s_%s' % (g_e.ronda.entidad.id, g_e.ronda.id)
            c = render_to_string('gastos_ingresos2pdf.html', {
                'gi_ingresos': gi_ingresos,
                'gi_gastos': gi_gastos,
                'g_total': asientos.filter(partida__tipo='GASTO').aggregate(total=Sum('cantidad'))['total'],
                'i_total': asientos.filter(partida__tipo='INGRE').aggregate(total=Sum('cantidad'))['total'],
                'pg_total': partidas_gastos.aggregate(total=Sum('cantidad'))['total'],
                'pi_total': partidas_ingresos.aggregate(total=Sum('cantidad'))['total']})
            fich = pdfkit.from_string(c, False, dce.get_opciones)
            response = HttpResponse(fich, content_type='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=' + fichero + '.pdf'
            return response

        if request.POST['action'] == 'bajar_justificante':
            asiento = Asiento.objects.get(id=request.POST['asiento_id'])
            url_file = asiento.escaneo.fichero.url
            fichero = url_file.replace('/media/contabilidad/', MEDIA_CONTABILIDAD)
            response = HttpResponse(open(fichero, 'rb'))
            response['Content-Disposition'] = 'attachment; filename=' + asiento.escaneo.fich_name
            return response
    else:
        presupuestos = Presupuesto.objects.filter(entidad=g_e.ronda.entidad, archivado=False)
        if len(presupuestos) != 1:
            presupuesto = None
            data = ''
        else:
            presupuesto = presupuestos[0]
            asientos = Asiento.objects.filter(partida__presupuesto=presupuesto)
            data = render_to_string("list_asientos.html", {
                'gi_ingresos': asientos.filter(partida__tipo='INGRE').reverse().order_by('modificado'),
                'gi_gastos': asientos.filter(partida__tipo='GASTO').reverse().order_by('modificado'),
                'g_total': asientos.filter(partida__tipo='GASTO').aggregate(total=Sum('cantidad'))['total'],
                'i_total': asientos.filter(partida__tipo='INGRE').aggregate(total=Sum('cantidad'))['total'],
            }, request=request)

    iconos = ({'tipo': 'button', 'nombre': 'list-alt', 'texto': 'Ingresos/Gastos', 'permiso': 'edita_gastos_ingresos',
               'title': 'Mostrar la lista de gastos e ingresos'},
              {'tipo': 'button', 'nombre': 'check', 'texto': 'Aceptar', 'title': 'Guardar los cambios realizados',
               'permiso': 'edita_gastos_ingresos'},
              {'tipo': 'button', 'nombre': 'plus', 'texto': 'Gasto/Ingreso', 'title': 'Añadir nuevo gasto o ingreso',
               'permiso': 'edita_gastos_ingresos'},
              {'tipo': 'button', 'nombre': 'pencil', 'texto': 'Editar',
               'title': 'Editar el gasto/ingreso para su modificación', 'permiso': 'edita_gastos_ingresos'},
              {'tipo': 'button', 'nombre': 'trash-o', 'texto': 'Borrar',
               'title': 'Borrar el ingreso o gasto seleccionado', 'permiso': 'edita_gastos_ingresos'},
              {'tipo': 'button', 'nombre': 'file-pdf-o', 'texto': 'PDF', 'permiso': 'pdf_gastos_ingresos',
               'title': 'Generar documento pdf con los gastos e ingresos registrados'})
    return render(request, "gastos_ingresos.html",
                  {
                      'formname': 'Ingreso_gasto',
                      'iconos': iconos,
                      'data': data,
                      'presupuesto': presupuesto,
                      'presupuestos': presupuestos,
                      'avisos': Aviso.objects.filter(usuario=g_e, aceptado=False),
                  })