Exemplo n.º 1
0
def handletabs(req, ids, tabs):
    user = users.getUserFromRequest(req)
    language = lang(req)

    n = tree.getNode(ids[0])
    if n.type.startswith("workflow"):
        n = tree.getRoot()

    menu = filterMenu(getEditMenuString(n.getContentType()), user)

    spc = [Menu("sub_header_frontend", "../", target="_parent")]
    if user.isAdmin():
        spc.append(
            Menu("sub_header_administration", "../admin", target="_parent"))

    if user.isWorkflowEditor():
        spc.append(Menu("sub_header_workflow", "../publish", target="_parent"))

    spc.append(Menu("sub_header_logout", "../logout", target="_parent"))

    # a html snippet may be inserted in the editor header
    help_link = tree.getRoot('collections').get('system.editor.help.link.' + language).strip()
    ctx = {
            "user": user,
            "ids": ids,
            "idstr": ",".join(ids),
            "menu": menu,
            "hashelp": help.getHelpPath(['edit', 'modules', req.params.get('tab') or tabs]),
            "breadcrumbs": getBreadcrumbs(menu, req.params.get("tab", tabs)),
            "spc": spc,
            "system_editor_help_link": help_link,
            }
    return req.getTAL("web/edit/edit.html", ctx, macro="edit_tabs")
Exemplo n.º 2
0
def show_node(req):
    """ opens administration window with content """

    p = req.path[1:].split("/")
    style = req.params.get("style", "")
    user = users.getUserFromRequest(req)

    v = {}
    v["user"] = user
    v["guestuser"] = config.get("user.guestuser")
    v["version"] = mediatum_version
    v["content"] = show_content(req, p[0])
    v["navigation"] = adminNavigation()
    v["breadcrumbs"] = getMenuItemID(v["navigation"], req.path[1:])
    v["spc"] = list()

    spc = list()
    v["spc"].append(Menu("sub_header_frontend", "/"))
    v["spc"].append(Menu("sub_header_edit", "/edit"))
    if user.isWorkflowEditor():
        v["spc"].append(Menu("sub_header_workflow", "../publish"))
    v["spc"].append(Menu("sub_header_logout", "/logout"))
    v["hashelp"] = help.getHelpPath(
        ['admin', 'modules', req.path.split('/')[1]])

    if len(p) > 0:
        if style == "":
            req.writeTAL("web/admin/frame.html", v, macro="frame")
        else:
            req.write(v["content"])
Exemplo n.º 3
0
    def prestamoLibros(self):
        self.__log.info("Entrando a prestamos de libros")
        opcionesPrestamoLibros = {
            "\t- Solicitar un libro": 1,
            "\t- Devolver un Libro": 2
        }
        menuPrestamoLibros = Menu("Registro de Libros", opcionesPrestamoLibros)
        resmenuPrestamoLibros = menuPrestamoLibros.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuPrestamoLibros == 1:
                self.__log.info("Entrando a prestamos de libros")
                libros = Libros()
                for libro in libros.all():
                    print(
                        f"\t {libro.libro_id}\t {libro.nombre}\t {libro.isbn}\t {libro.autor_id}"
                    )

                isbnLibro = input("Escriba en ISBN del libro \n")
                Libros.table('libros').where('isbn', isbnLibro).update(
                    estado_libro_id=estado_libro_id, estado='P')
                stopMenu = False
            elif resmenuPrestamoLibros == 2:
                self.__log.info("Entrando a devolucion de libros")
                libros = Libros()
                print('Ingrese el isbn del libro a devolver')
                print('Podrá encontrar el número en la tapa del libro')
                isbnDev = input('Ingrese el isbn aquí: ')
                Libros.table('libros').where('isbn', isbnDev).update(
                    estado_libro_id=estado_libro_id, estado='D')
                stopMenu = False
            elif resmenuPrestamoLibros == 9:
                self._log.info("Saliendo")
Exemplo n.º 4
0
def show_node(req):
    """ opens administration window with content """

    p = req.path[1:].split("/")
    style = req.params.get("style", u"")
    user = current_user

    v = {}
    v["user"] = user
    v["guestuser"] = get_guest_user().login_name
    v["version"] = core.__version__
    v["content"] = show_content(req, p[0])
    v["navigation"] = adminNavigation()
    v["breadcrumbs"] = getMenuItemID(v["navigation"], req.path[1:])

    spc = [
        Menu("sub_header_frontend", u"/"),
        Menu("sub_header_edit", u"/edit"),
        Menu("sub_header_logout", u"/logout")
    ]

    if user.is_workflow_editor:
        spc.append(Menu("sub_header_workflow", u"../publish/"))

    v["spc"] = spc

    if len(p) > 0:
        if style == "":
            req.writeTAL("web/admin/frame.html", v, macro="frame")
        else:
            req.write(v["content"])
Exemplo n.º 5
0
    def registroBibliotecas(self):
        self.__log.info("Ingresando al Registro de Bibliotecas")
        while True:
            opcionesRegistroBibliotecas = {
                "\t- Registrar Bibliotecas": 1,
                "\t- Listar Bibliotecas": 2
            }
            menuRegistroBibliotecas = Menu("Registro de Bibliotecas",
                                           opcionesRegistroBibliotecas)
            resmenuRegistroBibliotecas = menuRegistroBibliotecas.mostrarMenu()

            if (resmenuRegistroBibliotecas == 1):
                self.__log.info("Entrando al registro de Bibliotecas")
                nuevaBiblioteca = Biblioteca()
                nombreBiblioteca = input(
                    "escriba el nombre de la Biblioteca \n")
                direccionBiblioteca = input(
                    "escriba la direccion de la Biblioteca \n")

                tipo_documento = TipoDocumento()
                print(f"\t Codigo\t Descripcion")
                for obj in tipo_documento.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del tipo de documento de la siguiente lista"
                )
                tipo_documento_idBiblioteca = input()
                documentoBiblioteca = input(
                    "escriba el nro de documento de la Biblioteca \n")

                nuevaBiblioteca.nombre = nombreBiblioteca
                nuevaBiblioteca.direccion = direccionBiblioteca
                nuevaBiblioteca.tipo_documento_id = tipo_documento_idBiblioteca
                nuevaBiblioteca.documento = documentoBiblioteca

                nuevaBiblioteca.save()

                input("Continuar?")

            elif (resmenuRegistroBibliotecas == 2):
                self.__log.info("Ingresando a listar Bibliotecas")
                bibliotecas = Biblioteca()
                print(f"\t Codigo\t Nombre\t\t Direccion\t tipDoc\t NroDoc")
                for obj in bibliotecas.all():
                    print(
                        f"\t {obj.id}\t {obj.nombre}\t\t {obj.direccion}\t {obj.tipo_documento_id}\t {obj.documento}"
                    )

                input("Continuar?")

            elif (resmenuRegistroBibliotecas == 9):
                self.__log.info("Saliendo")
                break
Exemplo n.º 6
0
    def registroLectores(self):
        self.__log.info("Ingresando al Registro de Lectores")
        opcionesRegistroLectores = {
            "\t- Registrar Lectores": 1,
            "\t- Listar Lectores": 2
        }
        menuRegistroLectores = Menu("Registro de Lectores",
                                    opcionesRegistroLectores)
        resmenuRegistroLectores = menuRegistroLectores.mostrarMenu()
        #menuRegistrolos .mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuRegistroLectores == 1:
                self.__log.info("Entrando al registro de lectores")
                nuevoLector = User()
                nombreLector = input("Escriba el nombre del lector \n")
                correoLector = input("Escriba el correo del lector \n")

                tipodocumentos = TipoDocumento()
                print(f"\t Codigo\t Descripción")
                for obj in tipodocumentos.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del tipo de documento de la siguiente lista \n"
                )
                tipodocumento_idLector = input()

                nroDocumentoLector = input("Escriba el numero de documento \n")
                estado_usuarioLector = 1

                nuevoLector.nombre = nombreLector
                nuevoLector.correo = correoLector
                nuevoLector.tipo_documento_id = tipodocumento_idLector
                nuevoLector.documento = nroDocumentoLector
                nuevoLector.estado_user_id = estado_usuarioLector

                nuevoLector.save()

                stopMenu = False

            elif resmenuRegistroLectores == 2:
                self.__log.info("Entrando  a consultar los lectores")
                listarLectores = User()
                print(
                    f"\t Codigo\t Nombre\t Correo\t Tipo de documento\t Documento\t Estado de Usuario"
                )
                for obj in listarLectores.all():
                    #print(f"\t {obj.id}\t {obj.nombre}\t {obj.correo}\t {obj.tipodocumento_id}\t {obj.documento}\t {obj.estado_user_id}")
                    print(
                        f"\t {obj.id}\t {obj.nombre}\t {obj.correo}\t {obj.tipo_documento_id}\t {obj.documento}\t {obj.estado_user_id}"
                    )
                sleep(5)
                stopMenu = False
Exemplo n.º 7
0
    def registroLibros(self):
        self.__log.info("Ingresando al Registro de los ")
        opcionesRegistrolos = {
            "\t- Registrar Libros ": 1,
            "\t- Listar Libros ": 2
        }
        menuRegistrolos = Menu("Registro de Libros ", opcionesRegistrolos)
        resmenuRegistrolos = menuRegistrolos.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuRegistrolos == 1:
                self.__log.info("Entrando al registro de Libros ")
                nuevoLibro = Libro()
                nombreLibro = input("escriba el nombre del Libro \n")
                isbnLibro = input("escriba en ISBN del libro \n")

                autores = Autor()
                print(f"\t Codigo\t Nombre\t Tipo")
                for obj in autores.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.tipo}")
                print("Escriba el id del Autor de la siguiente lista")
                autor_idLibro = input()
                estados = EstadoLibro()
                print(f"\t Codigo\t Estado")
                for obj in estados.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del Estado del Libro de la siguiente lista")
                estadoLibro = input()

                nuevoLibro.nombre = nombreLibro
                nuevoLibro.isbn = isbnLibro
                nuevoLibro.autor_id = autor_idLibro
                nuevoLibro.estado_libro_id = estadoLibro

                nuevoLibro.save()

                stopMenu = False

            elif resmenuRegistrolos == 2:
                self.__log.info("Entrando  a consultar los ")
                listarLibro = Libro()
                print(f"\t Codigo\t Nombre\t ISBN\t Autor\t Estado de Libro")
                for obj in listarLibro.all():
                    print(
                        f"\t {obj.id}\t {obj.nombre}\t {obj.isbn}\t {obj.autor_id}\t {obj.estado_libro_id}"
                    )
                sleep(5)
                stopMenu = False

            elif resmenuRegistrolos == 9:
                self._log.info("Saliendo")
Exemplo n.º 8
0
    def registroLibros(self):
        self.__log.info("Ingresando al Registro de Libros")
        opcionesRegistroLibros = {"\t- Registrar Libros":1,"\t- Listar Libros":2}
        menuRegistroLibros = Menu("Registro de Libros",opcionesRegistroLibros)
        resmenuRegistroLibros = menuRegistroLibros.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if (resmenuRegistroLibros == 1):
                self.__log.info("Entrando al registro de libros")
                nuevoLibro = Libros()
                nombreLibro = input("escriba el nombre del Libro \n")
                isbnLibro = input("escriba en ISBN del libro \n")

                autores = Autor()
                print(f"\t Codigo\t Nombre\t Tipo")
                for obj in autores.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.tipo}")
                print("Escriba el id del Autor de la siguiente lista")
                print("*Importante : Si no lo ve ingrese NA*")
                autor_idLibro = input()
                if (autor_idLibro == 'NA'):
                    nuevoAutor = Autor()
                    nombrenuevoAutor = input('Ingrese el nombre del Autor: ')
                    correonuevoAutor = input('Ingrese el correo del Autor: ')
                    tiponuevoAutor = input('Ingrese si (01) si es Autor o (02) si es Editorial: ')
                    nuevoAutor.nombre = nombrenuevoAutor
                    nuevoAutor.correo = correonuevoAutor
                    nuevoAutor.tipo = tiponuevoAutor
                    nuevoAutor.save()
                    print('Inicializando menu de regsitro nuevamente')
                    Registros.registroLibros()
                else:
                    estados = Estado_libro()
                    print(f"\t Codigo\t Estado")
                    for obj in estados.all():
                        print(f"\t {obj.id}\t {obj.descripcion}")
                    print("Escriba el id del Estado del Libro de la siguiente lista")
                    estadoLibro = input()

                nuevoLibro.nombre = nombreLibro
                nuevoLibro.isbn = isbnLibro
                nuevoLibro.autor_id = autor_idLibro
                nuevoLibro.estado_libro_id = estadoLibro

                nuevoLibro.save()



                stopMenu = False
            
            elif resmenuRegistroLibros == 9:
                self._log.info("Saliendo")
Exemplo n.º 9
0
    def registroLectores(self):
        self.__log.info("Ingresando al Registro de Lectores")
        opcionesRegistroLectores = {"\t- Registrar nuevo Lector":1,"\t- Listar Lectores":2}
        menuRegistroLectores = Menu("Registro de Lectores",opcionesRegistroLectores)
        resmenuRegistroLectores = menuRegistroLectores.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if (resmenuRegistroLectores == 1):
                self.__log.info("Entrando al opcion de nuevo registro")
                nuevoLector = usuario()
                nombreNusuario = input("Escriba el nombre del Lector \n")
                correoNusuario = input("Escriba el correo del lector \n")
                tipodedocumentoNusuario = input("Escriba DNI, CE o Carnet de Biblioteca \n")
                nodocumentoNusuario = input("Ingrese el no. de documento \n")
                estadousuarioNusuario = 2

                nuevoLector.nombre = nombreNusuario
                nuevoLector.correo = correoNusuario
                nuevoLector.tipo_documento_id = tipodedocumentoNusuario
                nuevoLector.documento= nodocumentoNusuario
                nuevoLector.estado_usuario_id= estadousuarioNusuario

                nuevoLector.save()
                print(f"\t El usuario '{nombreNusuario}'\t ha sido creado")
                stopMenu = False
            elif (resmenuRegistroLectores == 2):
                vistaUsuarios = usuario()
                print(f"\t ID\t Nombre\t Correo\t Tipo de Doc\t No. Doc\t Estado\t")
                stopMenu =False
                for obj in vistaUsuarios.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.correo}\t {obj.tipo_documento_id}\t {obj.documento}\t {obj.estado_usuario_id}")
                    opcionlistarusuarios = input('Desea editar algun usuario? S/N: ')
                    if (opcionlistarusuarios == 'S'):
                        usuariocambio = usuario()
                        nombrecambio = input("Escriba el nombre del Lector \n")
                        correocambio = input("Escriba el correo del lector \n")
                        tipodedocumentocambio = input("Escriba (01) DNI, (02) CE o (03)Carnet de Biblioteca \n")
                        nodocumentocambio = input("Ingrese el no. de documento \n")
                        estadousuariocambio = input("Ingrese (01) para Activo y (03) para Pendiente \n")
                        usuariocambio.nombre = nombrecambio
                        usuariocambio.correo = correocambio
                        usuariocambio.tipo_documento_id = tipodedocumentocambio
                        usuariocambio.documento = nodocumentocambio
                        usuariocambio.estado_usuario_id = estadousuariocambio
                        usuariocambio.update()
                        
            elif resmenuRegistroLectores == 9:
                self._log.info("Saliendo")
                
Exemplo n.º 10
0
 def getEditMenuTabs(self):
     menu = list()
     try:
         submenu = Menu("menuglobals", "..")
         menu.append(submenu)
     except TypeError:
         pass
     return ";".join([m.getString() for m in menu])
Exemplo n.º 11
0
    def registroPrestamos(self):
        self.__log.info("Ingresando al Módulo de Prestamos")
        stopMenu = True
        while stopMenu:
            opcionesPrestamoLibros = {
                "\t- Lista de Prestamos": 1,
                "\t- Registrar Prestamos": 2,
                "\t- Devolucion de Libros": 3
            }
            menuPrestamoLibros = Menu("Módulo de Prestamos",
                                      opcionesPrestamoLibros)
            resmenuPrestamoLibros = menuPrestamoLibros.mostrarMenu()
            if resmenuPrestamoLibros == 1:
                self.__log.info("Entrando a la Lista de Prestamos")
                PrestamoN = Prestamo()
                print(
                    str("Codigo").ljust(5) + "\t " +
                    str("Fecha Prestamo").ljust(10) + "\t " +
                    str("Usuario").ljust(10) + "\t" +
                    str("Biblioteca").ljust(25) + "\t " +
                    str("Libro").ljust(7) + "\t " + str("Estado").ljust(7))
                contador = 0
                for obj in PrestamoN.all():
                    ObjUserTemp = User.find(obj.user_id)
                    ObjLibrTemp = Libro.find(obj.libros_id)
                    ObjBiblioTemp = Biblioteca.find(obj.bibliotecas_id)
                    ObjEstaLibTempp = EstadoLibro.find(
                        ObjLibrTemp.estado_libro_id)
                    contador += 1
                    print(
                        str(obj.id).ljust(5) + "\t " +
                        str(obj.prestamo_on).ljust(10) + "\t " +
                        str(ObjUserTemp.nombre).ljust(10) + "\t" +
                        str(ObjBiblioTemp.nombre).ljust(25) + "\t " +
                        str(ObjLibrTemp.nombre).ljust(7) + "\t " +
                        str(ObjEstaLibTempp.descripcion).ljust(7))
                if contador > 0:
                    print("Lista Completa")
                else:
                    print("No hay registros")
                stopMenu = False

            elif resmenuRegistroLibros == 2:
                self.__log.info("Registrar Prestamos")
                nuevo = Prestamo()

                UserN = User()
                print(f"\t Codigo\t\t\t Nombre\t\t\t Estado")
                for obj in UserN.all():
                    print(
                        f"\t {obj.id}\t\t\t {obj.nombre}\t\t\t {obj.estado_user_id}"
                    )
                print("Escriba el id del usuario: ")
                usuario_id = input()

                LibroN = Libro()
                print(f"\t Codigo\t Libro")
                for obj in LibroN.all():
                    print(f"\t {obj.id}\t {obj.nombre}")
                print("Escriba el id del libro: ")
                libroId = input()

                BibliotecaN = Biblioteca()
                print(f"\t Codigo\t Biblioteca")
                for obj in BibliotecaN.all():
                    print(f"\t {obj.id}\t {obj.nombre}")
                print("Escriba el id de la Biblioteca: ")
                bibliotecaId = input()

                nuevo.user_id = usuario_id
                nuevo.libros_Id = libroId
                nuevo.prestamo_on = datetime.now()
                nuevo.bibliotecas_id = bibliotecaId
                nuevo.save()

                nuevoD = Libro.find(nuevo.libros_Id)
                nuevoD.estado_libro_id = 3
                nuevoD.save()

                print("Registro completo")
                stopMenu = False

            elif resmenuRegistroLibros == 3:
                self.__log.info("Devolución de Libros")
                librosTemporal = []
                libroNN = Libro.where('estado_libro_id', '=', '3').get()
                for libt in libroNN.all():
                    idlibTemp = libt.id
                    PrestamoN = Prestamo.where('libros_id', '=',
                                               f"{idlibTemp}").get()
                    for presIn in PrestamoN.all():
                        temporalDato = {
                            "id": str(presIn.id),
                            "user_id": str(presIn.user_id),
                            "libros_id": str(presIn.libros_id),
                            "prestamo_on": str(presIn.prestamo_on),
                            "bibliotecas_id": str(presIn.bibliotecas_id)
                        }
                        librosTemporal.append(temporalDato)
                contaDD = 0
                print(f"\t Codigo\t\t " + str("Libros").ljust(15) +
                      "\t\t Fecha\t\t Bibliotecas")
                for obj in librosTemporal:
                    contaDD += 1
                    LibTempN = Libro.find(obj["libros_id"])
                    BibliTempN = Biblioteca.find(obj["bibliotecas_id"])
                    ididD = str(obj["id"])
                    prest = str(obj["prestamo_on"])
                    print(f"\t{ididD}\t\t " + str(LibTempN.nombre).ljust(15) +
                          "\t\t" + prest + "\t\t" + BibliTempN.nombre)
                if contaDD > 0:
                    print("Escriba el id del Préstamo")
                    Prestamo_NID = input()
                    nuevoPresD = Prestamo.find(Prestamo_NID)
                    nuevoD = Libro.find(nuevoPresD.libros_id)
                    nuevoD.estado_libro_id = 1
                    nuevoD.save()
                    print(f"Devolucion correcta")
                else:
                    print("No hay registros")
                stopMenu = False

            elif resmenuRegistroLibros == 9:
                stopMenu = False
                self.__log.info("Saliendo")
Exemplo n.º 12
0
    def registroPrestamos(self):
        self.__log.info("Ingresando al Registro de los ")
        opcionesRegistrolos = {
            "\t- Registrar Prestamos ": 1,
            "\t- Registrar devolucion de prestamo ": 2
        }
        menuRegistrolos = Menu("Registro de Prestamos ", opcionesRegistrolos)
        resmenuRegistrolos = menuRegistrolos.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuRegistrolos == 1:
                self.__log.info("Entrando al registro de Prestamos ")
                nuevoPrestamo = Prestamo()
                codigoLibro = input("escriba el codigo del Libro \n")
                codigoUsuario = input("escriba el codigo del usuario \n")
                fechaPrestamo = datetime.today().strftime('%Y-%m-%d')
                bibliotecaId = 1
                flagUpdate = False

                nuevoPrestamo.user_id = codigoUsuario
                nuevoPrestamo.libros_id = codigoLibro
                nuevoPrestamo.prestado_on = fechaPrestamo
                nuevoPrestamo.bibliotecas_id = bibliotecaId

                listaLibros = Libro.where('id', '=', f'{codigoLibro}').get()
                for row in listaLibros:
                    libro = row

                if libro.estado_libro_id == 1:
                    listaAutor = Autor.where('id', '=',
                                             f'{libro.autor_id}').get()
                    for row in listaAutor:
                        autor = row

                    print(
                        "\tCodigo Usuario\t\tLibro\t\tISBN\t\tAutor\t\tBiblioteca"
                    )
                    print(
                        f"\t{str(codigoUsuario)}\t\t{str(libro.nombre)}\t\t{str(libro.isbn)}\t\t{str(autor.nombre)}\t\t{str(bibliotecaId)}"
                    )

                    registro = input(
                        "Desea registrar el prestamo Si(1)/No(0)?: ")
                    if str(registro) == '1':
                        if nuevoPrestamo.save():
                            print("Registro de prestamo satisfactorio")
                            sleep(5)
                            flagUpdate = Libro.where(
                                'id', '=',
                                f'{codigoLibro}').update(estado_libro_id=3)

                            if flagUpdate:
                                print("Actualización de libro satisfactorio")
                                sleep(5)
                            else:
                                print("No se pudo actualizar el libro")
                else:
                    print(
                        "No se puede prestar el libro.\nLibro ha sido prestado."
                    )
                    sleep(5)

                stopMenu = False

            elif resmenuRegistrolos == 2:
                self.__log.info("Entrando a la devolución de libro Prestado ")
                codigoUsuario = input("escriba el codigo del usuario \n")
                fechaDevolucion = '9999-12-31'  #Constante para identificar devolucion
                flagUpdate = False

                listaDev = Prestamo.where('user_id', '=',
                                          f'{codigoUsuario}').get()
                if listaDev:
                    print(
                        "\tID Prestamo\tLibro\t\tISBN\t\tAutor\t\tBiblioteca")
                    for rowDev in listaDev:
                        if str(rowDev.prestado_on
                               ) != fechaDevolucion:  #No mostrar devoluciones
                            listaLibros = Libro.where(
                                'id', '=', f'{rowDev.libros_id}').get()
                            for rowLibro in listaLibros:
                                libro = rowLibro
                                listaAutor = Autor.where(
                                    'id', '=', f'{libro.autor_id}').get()
                                for rowAutor in listaAutor:
                                    autor = rowAutor
                                print(
                                    f"\t{str(rowDev.id)}\t\t{str(libro.nombre)}\t\t{str(libro.isbn)}\t\t{str(autor.nombre)}\t\t{str(rowDev.bibliotecas_id)}"
                                )

                    idDev = input("Escriba el Id de Prestamo: ")

                    if idDev:
                        flagUpdate = Prestamo.where(
                            'id', '=',
                            f'{idDev}').update(prestado_on=fechaDevolucion)
                        if flagUpdate:
                            print("Actualización de Devolución satisfactoria")
                            sleep(5)
                            flagUpdate = Libro.where(
                                'id', '=', f'{rowDev.libros_id}').update(
                                    estado_libro_id=1)
                            if flagUpdate:
                                print("Actualización de libro satisfactorio")
                                sleep(5)
                            else:
                                print("No se pudo actualizar el libro")
                        else:
                            print("No se pudo actualizar Devolución")

                stopMenu = False

            elif resmenuRegistrolos == 9:
                self._log.info("Saliendo")
                stopMenu = False
Exemplo n.º 13
0
    def registroLibros(self):
        self.__log.info("Ingresando al Módulo de Registro")
        opcionesRegistroLibros = {
            "\t- Registrar Libros": 1,
            "\t- Listar Libros": 2,
            "\t- Registrar Usuarios": 3,
            "\t- Listar Usuarios": 4,
            "\t- Registrar Biblioteca": 5,
            "\t- Listar Biblioteca": 6
        }
        menuRegistroLibros = Menu("Módulo de Registro", opcionesRegistroLibros)
        resmenuRegistroLibros = menuRegistroLibros.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuRegistroLibros == 1:
                self.__log.info("Entrando al Registro de Libros")
                nuevoLibro = Libro()
                nombreLibro = input("Escriba el nombre del libro: \n")
                isbnLibro = input("Escriba el ISBN del libro: \n")

                autores = Autor()
                print(f"\t Codigo\t Nombre\t Tipo")
                for obj in autores.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.tipo}")
                print("Escriba el id del Autor de la siguiente lista:")
                autor_idLibro = input()
                estados = EstadoLibro()
                print(f"\t Codigo\t Estado")
                for obj in estados.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del Estado del Libro de la siguiente lista:"
                )
                estadoLibro = input()

                nuevoLibro.nombre = nombreLibro
                nuevoLibro.isbn = isbnLibro
                nuevoLibro.autor_id = autor_idLibro
                nuevoLibro.estado_libro_id = estadoLibro

                nuevoLibro.save()
                print("Registro Completo")
                stopMenu = False

            elif resmenuRegistroLibros == 2:
                self.__log.info("Entrando a la Lista de libros")
                libros = Libro()
                print("\t " + str("Codigo").ljust(10) + "\t\t\t " +
                      str("Libro").ljust(10) + "\t\t\t " +
                      str("ISBN").ljust(10) + "\t\t\t " +
                      str("Autor").ljust(10))
                contador = 0
                for obj in libros.all():
                    contador += 1
                    print("\t" + str(obj.id).ljust(10) + "\t\t\t " +
                          str(obj.nombre).ljust(10) + "\t\t\t " +
                          str(obj.isbn).ljust(10) + "\t\t\t " +
                          str(obj.autor_id).ljust(10))
                if contador > 0:
                    print("Lista completa")
                else:
                    print("No hay registros")
                stopMenu = False

            elif resmenuRegistroLibros == 3:
                self.__log.info("Entrando al Registro de Usuario")
                nuevo = User()
                nombre = input("Nombre Completo: ")
                correo = input("Correo: ")
                tipoDoc = TipoDocumento()
                print(f"\t Codigo\t TipoDocumento")
                for obj in tipoDoc.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                tipoDoc_Id = input("Ingrese el Tipo de Documento: ")
                tipoDoc_Desc = input("Ingrese el número: ")
                estados = EstadoUser()
                print(f"\t Codigo\t Estado")
                for obj in estados.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                estado_Id = input("Estado: ")
                nuevo.nombre = nombre
                nuevo.correo = correo
                nuevo.tipo_documento_id = tipoDoc_Id
                nuevo.documento = tipoDoc_Desc
                nuevo.estado_user_id = estado_Id
                nuevo.save()
                print("Registro completo")
                stopMenu = False

            elif resmenuRegistroLibros == 4:
                self.__log.info("Entrando a la Lista de Usuarios")
                Usuario = User()
                print("\t " + str("Codigo").ljust(10) + "\t\t\t " +
                      str("Usuario").ljust(10) + "\t\t\t " +
                      str("Correo").ljust(10))
                contador = 0
                for obj in Usuario.all():
                    contador += 1
                    print("\t" + str(obj.id).ljust(10) + "\t\t\t " +
                          str(obj.nombre).ljust(10) + "\t\t\t " +
                          str(obj.correo).ljust(10))
                if contador > 0:
                    print("Lista Completa")
                else:
                    print("No hay nadie registrado")
                stopMenu = False

            elif resmenuRegistroLibros == 5:
                self.__log.info("Entrando al Registro de Bibliotecas")
                nuevo = Biblioteca()
                nombre = input("Escriba el nombre: ")
                direccion = input("Escriba la direccion: ")

                nuevo.nombre = nombre
                nuevo.direccion = direccion
                nuevo.save()
                print("Registro Completo")
                stopMenu = False

            elif resmenuRegistroLibros == 6:
                self.__log.info("Entrando a la Lista de Bibliotecas")
                BibliotecaN = Biblioteca()
                print("\t " + str("Codigo").ljust(10) + "\t\t\t " +
                      str("Biblioteca").ljust(10) + "\t\t\t " +
                      str("Direccion").ljust(10))
                contador = 0
                for obj in BibliotecaN.all():
                    contador += 1
                    print("\t" + str(obj.id).ljust(10) + "\t\t\t " +
                          str(obj.nombre).ljust(10) + "\t\t\t " +
                          str(obj.direccion).ljust(10))
                if contador > 0:
                    print("Lista Completa")
                else:
                    print("No hay registros")
                stopMenu = False

            elif resmenuRegistroLibros == 9:
                self._log.info("Saliendo")
Exemplo n.º 14
0
def frameset(req):
    id = req.params.get("id", tree.getRoot("collections").id)
    tab = req.params.get("tab", None)
    language = lang(req)

    access = AccessData(req)
    if not access.getUser().isEditor():
        req.writeTAL("web/edit/edit.html", {}, macro="error")
        req.writeTAL("web/edit/edit.html",
                     {"id": id, "tab": (tab and "&tab=" + tab) or ""}, macro="edit_notree_permission")
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return

    try:
        currentdir = tree.getNode(id)
    except tree.NoSuchNodeError:
        currentdir = tree.getRoot("collections")
        req.params["id"] = currentdir.id
        id = req.params.get("id")

    nodepath = []
    n = currentdir
    while n:
        nodepath = [n] + nodepath
        p = n.getParents()
        if p:
            n = p[0]
        else:
            n = None

    path = nidpath = ['%s' % p.id for p in nodepath]
    containerpath = [('%s' % p.id) for p in nodepath if p.isContainer()]

    user = users.getUserFromRequest(req)
    menu = filterMenu(getEditMenuString(currentdir.getContentType()), user)

    spc = [Menu("sub_header_frontend", "../", target="_parent")]
    if user.isAdmin():
        spc.append(
            Menu("sub_header_administration", "../admin", target="_parent"))

    if user.isWorkflowEditor():
        spc.append(Menu("sub_header_workflow", "../publish", target="_parent"))

    spc.append(Menu("sub_header_logout", "../logout", target="_parent"))

    def getPathToFolder(node):
        n = node
        path = []
        while n:
            path = ['/%s' % (n.id)] + path
            p = n.getParents()
            if p:
                n = p[0]
            else:
                n = None
        return (node, "".join(path[2:]))

    def _getIDPath(nid, sep="/", containers_only=True):
        res = getIDPaths(nid, access, sep=sep, containers_only=containers_only)
        return res

    folders = {'homedir': getPathToFolder(users.getHomeDir(user)), 'trashdir': getPathToFolder(users.getSpecialDir(
        user, 'trash')), 'uploaddir': getPathToFolder(users.getSpecialDir(user, 'upload')), 'importdir': getPathToFolder(users.getSpecialDir(user, 'import'))}

    cmenu = sorted(getContainerTreeTypes(req), key=lambda x: x.getName())
    cmenu_iconpaths = []

    for ct in cmenu:
        ct_name = ct.getName()
        _n = tree.Node("", type=ct_name)
        # translations of ct_name will be offered in editor tree context menu
        cmenu_iconpaths.append(
            [ct, getEditorIconPath(_n), ct_name, translation_t(language, ct_name)])

    # a html snippet may be inserted in the editor header
    header_insert = tree.getRoot('collections').get('system.editor.header.insert.' + language).strip()
    help_link = tree.getRoot('collections').get('system.editor.help.link.' + language).strip()
    homenodefilter = req.params.get('homenodefilter', '')

    v = {
        "id": id,
        "tab": (tab and "&tab=" + tab) or "",
        'user': user,
        'spc': spc,
        'folders': folders,
        'collectionsid': tree.getRoot('collections').id,
        "basedirs": [tree.getRoot('home'), tree.getRoot('collections')],
        'cmenu': cmenu,
        'cmenu_iconpaths': cmenu_iconpaths,
        'path': path,
        'containerpath': containerpath,
        'language': lang(req),
        't': translation_t,
        '_getIDPath': _getIDPath,
        'system_editor_header_insert': header_insert,
        'system_editor_help_link': help_link,
        'homenodefilter': homenodefilter,
       }

    req.writeTAL("web/edit/edit.html", v, macro="edit_main")
Exemplo n.º 15
0
    def registroLibros(self):
        self.__log.info("Ingresando al Registro de Libros")
        opcionesRegistro = {
            "\t- Registrar Libros": 1,
            "\t- Listar Libros": 2,
            "\t- Registrar Lector": 3,
            "\t- Listar Lectores": 4
        }
        menuRegistro = Menu("Registro de Libros", opcionesRegistro)
        resmenuRegistro = menuRegistro.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuRegistro == 1:
                self.__log.info("Entrando al registro de libros")
                print("Registrar Libros")
                nuevoLibro = Libro()
                nombreLibro = input("escriba el nombre del Libro \n")
                isbnLibro = input("escriba en ISBN del libro \n")

                autores = Autor()
                print(f"\t Codigo\t Nombre\t Tipo")
                for obj in autores.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.tipo}")
                print("Escriba el id del Autor de la siguiente lista")
                autor_idLibro = input()
                estados = EstadoLibro()
                print(f"\t Codigo\t Estado")
                for obj in estados.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del Estado del Libro de la siguiente lista")
                estadoLibro = input()

                nuevoLibro.nombre = nombreLibro
                nuevoLibro.isbn = isbnLibro
                nuevoLibro.autor_id = autor_idLibro
                nuevoLibro.estado_libro_id = estadoLibro
                nuevoLibro.save()
                stopMenu = False
            if resmenuRegistro == 2:
                self.__log.info("Entrando a listar libros")
                print("Listar libros")
                libros = Libro()
                print(f"\t Codigo\t Nombre\t ISBN")
                for obj in libros.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.isbn}")

                stopMenu = False

            if resmenuRegistro == 3:
                self.__log.info("Entrando al registro de lectores")
                print("Registrar Lectores")
                nuevoUser = User()
                nombreUser = input("escriba el nombre del nuevo Usuario \n")
                correoUser = input("escriba el correo \n")

                tipodocumento = TipoDocumento()
                print(f"\t id\t Descripcion")
                for obj in tipodocumento.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del tipo de documento de la anterior lista")
                documento_idTipodocumento = input()
                documentoUser = input("escriba el numero del documento \n")

                estadoUser = EstadoUser()
                print(f"\t id\t descripcion")
                for obj in estadoUser.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del Estado del Usuario de la anterior lista"
                )
                estado_User = input()

                nuevoUser.nombre = nombreUser
                nuevoUser.correo = correoUser
                nuevoUser.tipo_documento_id = documento_idTipodocumento
                nuevoUser.documento = documentoUser
                nuevoUser.estado_user_id = estado_User

                nuevoUser.save()
                stopMenu = False

            if resmenuRegistro == 4:
                self.__log.info("Entrando a listar lector")
                print("Listar lectores")
                Usuarios = User()
                print(f"\t Codigo\t Nombre\t correo")
                for obj in Usuarios.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.correo}")

                stopMenu = False

            elif resmenuRegistro == 9:
                self._log.info("Saliendo")
Exemplo n.º 16
0
    def registroLectores(self):
        self.__log.info("Ingresando al Registro de Lectores")
        while True:
            opcionesRegistroLectores = {
                "\t- Registrar Lectores": 1,
                "\t- Listar Lectores": 2
            }
            menuRegistroLectores = Menu("Registro de Lectores",
                                        opcionesRegistroLectores)
            resmenuRegistroLectores = menuRegistroLectores.mostrarMenu()
            if (resmenuRegistroLectores == 1):
                self.__log.info("Entrando al registro de Lectores")
                nuevoLector = User()
                nombreLector = input("escriba el nombre del Lector \n")
                correoLector = input("escriba el correo del Lector \n")

                tipo_documento = TipoDocumento()
                print(f"\t Codigo\t Descripcion")
                for obj in tipo_documento.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del tipo de documento de la siguiente lista"
                )
                tipo_documento_idLector = input()
                documentoLector = input(
                    "escriba el nro de documento del Lector \n")
                estados = EstadoUser()
                print(f"\t Codigo\t Estado")
                for obj in estados.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del Estado del Lector de la siguiente lista"
                )
                estadoLector = input()

                nuevoLector.nombre = nombreLector
                nuevoLector.correo = correoLector
                nuevoLector.tipo_documento_id = tipo_documento_idLector
                nuevoLector.documento = documentoLector
                nuevoLector.estado_user_id = estadoLector

                nuevoLector.save()

                input("Continuar?")

            elif (resmenuRegistroLectores == 2):
                self.__log.info("Ingresando a listar lectores")
                lectores = User()
                print(
                    f"\t Codigo\t Nombre\t\t Correo\t tipDoc\t NroDoc\t Estado"
                )
                for obj in lectores.all():
                    print(
                        f"\t {obj.id}\t {obj.nombre}\t\t {obj.correo}\t {obj.tipo_documento_id}\t {obj.documento}\t {obj.estado_user_id}"
                    )

                input("Continuar?")

            elif (resmenuRegistroLectores == 9):
                self.__log.info("Saliendo")
                break
Exemplo n.º 17
0
    def registroLibros(self):
        self.__log.info("Ingresando al Registro de Libros")

        while True:
            opcionesRegistroLibros = {
                "\t- Registrar Libros": 1,
                "\t- Listar Libros": 2
            }
            menuRegistroLibros = Menu("Registro de Libros",
                                      opcionesRegistroLibros)
            resmenuRegistroLibros = menuRegistroLibros.mostrarMenu()
            if resmenuRegistroLibros == 1:
                self.__log.info("Entrando al registro de libros")
                nuevoLibro = Libro()
                nombreLibro = input("escriba el nombre del Libro \n")
                isbnLibro = input("escriba en ISBN del libro \n")

                autores = Autor()
                print(f"\t Codigo\t Nombre\t Tipo")
                for obj in autores.all():
                    print(f"\t {obj.id}\t {obj.nombre}\t {obj.tipo}")
                print("Escriba el id del Autor de la siguiente lista")
                autor_idLibro = input()
                estados = EstadoLibro()
                print(f"\t Codigo\t Estado")
                for obj in estados.all():
                    print(f"\t {obj.id}\t {obj.descripcion}")
                print(
                    "Escriba el id del Estado del Libro de la siguiente lista")
                estadoLibro = input()

                nuevoLibro.nombre = nombreLibro
                nuevoLibro.isbn = isbnLibro
                nuevoLibro.autor_id = autor_idLibro
                nuevoLibro.estado_libro_id = estadoLibro

                nuevoLibro.save()

                input("Continuar?")

            elif resmenuRegistroLibros == 2:
                self.__log.info("Ingresando a listar libros")
                libros = Libro()
                print(f"\t Codigo\t Nombre\t\t ISBN\t Autor\t Estado")
                for obj in libros.all():
                    y = obj.estado_libro_id
                    if (y == 1):
                        estado = "Disponible"
                    elif (y == 2):
                        estado = "Reservado"
                    elif (y == 3):
                        estado = "Prestado"
                    print(
                        f"\t {obj.id}\t {obj.nombre}\t\t {obj.isbn}\t {obj.autor_id}\t {estado}"
                    )

                input("Continuar?")

            elif resmenuRegistroLibros == 9:
                self.__log.info("Saliendo")
                break
Exemplo n.º 18
0
def content(req):

    user = users.getUserFromRequest(req)

    access = AccessData(req)
    language = lang(req)
    if not access.user.isEditor():
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    if 'id' in req.params and len(req.params) == 1:
        nid = req.params.get('id')
        try:
            node = tree.getNode(nid)
        except:
            node = None
        if node:
            cmd = "cd (%s %r, %r)" % (nid, node.name, node.type)
            logger.info("%s: %s" % (user.getName(), cmd))
            #logging.getLogger("usertracing").info("%s: in editor %s" % (user.getName(), cmd))
        else:
            cmd = "ERROR-cd to non-existing id=%r" % nid
            logger.error("%s: %s") % (user.getName(), cmd)

    if 'action' in req.params and req.params['action'] == 'upload':
        pass

    content = {'script': '', 'body': ''}
    v = {'dircontent': '', 'notdirectory': 0, 'operations': ''}
    try:
        v['nodeiconpath'] = getEditorIconPath(node)
    except:
        v['nodeiconpath'] = "webtree/directory.gif"

    path = req.path[1:].split("/")
    if len(path) >= 4:
        req.params["style"] = "popup"
        req.params["id"] = path[1]
        req.params["tab"] = path[2]
        req.params["option"] = path[3]
    getEditModules()

    if not access.user.isEditor():
        return req.writeTAL("web/edit/edit.html", {}, macro="error")

    # remove all caches for the frontend area- we might make changes there
    for sessionkey in ["contentarea", "navframe"]:
        try:
            del req.session[sessionkey]
        except:
            pass

    ids = getIDs(req)

    if req.params.get("type", "") == "help" and req.params.get("tab", "") == "upload":
        return upload_help(req)

    if len(ids) > 0:
        node = tree.getNode(ids[0])
    tabs = "content"
    if node.type == "root":
        tabs = "content"
    elif node.id == users.getUploadDir(access.getUser()).id:
        tabs = "upload"
    elif node.id == users.getImportDir(access.getUser()).id:
        tabs = "imports"
    elif hasattr(node, "getDefaultEditTab"):
        tabs = node.getDefaultEditTab()
        v["notdirectory"] = 0

    current = req.params.get("tab", tabs)
    logger.debug("... %s inside %s.%s: ->  !!! current = %r !!!" %
                 (get_user_id(req), __name__, funcname(), current))
    msg = "%s selected editor module is %r" % (user.getName(), current)
    jsfunc = req.params.get("func", "")
    if jsfunc:
        msg = msg + (', js-function: %r' % jsfunc)
    logger.info(msg)

    # some tabs operate on only one file
    # if current in ["files", "view", "upload"]:
    if current in ["files", "upload"]:
        ids = ids[0:1]

    # display current images
    if not tree.getNode(ids[0]).isContainer():
        v["notdirectory"] = 1
        items = []
        if current != "view":
            for id in ids:
                node = tree.getNode(id)
                if hasattr(node, "show_node_image"):
                    if not isDirectory(node) and not node.isContainer():
                        items.append((id, node.show_node_image()))
                    else:
                        items.append(("", node.show_node_image()))
        v["items"] = items
        logger.debug("... %s inside %s.%s: -> display current images: items: %r" %
                     (get_user_id(req), __name__, funcname(), [_t[0] for _t in items]))
        try:
            n = tree.getNode(req.params.get('src', req.params.get('id')))
            if current == 'metadata' and 'save' in req.params:
                pass
            s = []
            while n:
                try:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.getLabel(lang=language))] + s
                except:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.name)] + s

                p = n.getParents()
                if p:
                    n = p[0]
                else:
                    n = None
            v["dircontent"] = ' <b>&raquo;</b> '.join(s[1:])
        except:
            logger.exception('ERROR displaying current images')

    else:  # or current directory
        n = tree.getNode(ids[0])
        s = []
        while n:
            if len(s) == 0:
                try:
                    s = ['%s' % (n.getLabel(lang=language))]
                except:
                    s = ['%s' % (n.name)]
            else:
                try:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.getLabel(lang=language))] + s
                except:
                    s = ['<a onClick="activateEditorTreeNode(%r); return false;" href="/edit/edit_content?id=%s">%s</a>' %
                         (n.id, n.id, n.name)] + s

            p = n.getParents()
            if p:
                n = p[0]
            else:
                n = None
        v["dircontent"] = ' <b>&raquo;</b> '.join(s[1:])

    if current == "globals":
        basedir = config.get("paths.datadir")
        file_to_edit = None

        if "file_to_edit" in req.params:
            file_to_edit = req.params["file_to_edit"]

        if not file_to_edit:
            d = node.getStartpageDict()
            if d and lang(req) in d:
                file_to_edit = d[lang(req)]

        found = False
        for f in node.getFiles():
            if f.mimetype == 'text/html':
                filepath = f.retrieveFile().replace(basedir, '')
                if file_to_edit == filepath:
                    found = True
                    result = edit_editor(req, node, f)
                    if result == "error":
                        logger.error("error editing %r" % f.retrieveFile())
                    break

        if not found:
            edit_editor(req, node, None)

    elif current == "tab_metadata":
        edit_metadata(req, ids)  # undefined
    elif current == "tab_upload":
        edit_upload(req, ids)  # undefined
    elif current == "tab_import":
        edit_import(req, ids)  # undefined
    elif current == "tab_globals":
        req.write("")
    elif current == "tab_lza":
        edit_lza(req, ids)  # undefined
    elif current == "tab_logo":
        edit_logo(req, ids)  # undefined
    else:
        t = current.split("_")[-1]
        if t in editModules.keys():
            c = editModules[t].getContent(req, ids)
            if c:
                content["body"] += c  # use standard method of module
            else:
                logger.debug('empty content')
                return
        else:
            req.setStatus(httpstatus.HTTP_INTERNAL_SERVER_ERROR)
            content["body"] += req.getTAL("web/edit/edit.html", {"module": current}, macro="module_error")

    if req.params.get("style", "") != "popup":  # normal page with header
        v["tabs"] = handletabs(req, ids, tabs)
        v["script"] = content["script"]
        v["body"] = content["body"]
        v["paging"] = showPaging(req, current, ids)
        v["node"] = node
        v["ids"] = req.params.get("ids", "").split(",")
        if req.params.get("ids", "") == "":
            v["ids"] = req.params.get("id", "").split(",")
        v["tab"] = current
        v["operations"] = req.getTAL("web/edit/edit_common.html", {'iscontainer': node.isContainer()}, macro="show_operations")
        user = users.getUserFromRequest(req)
        v['user'] = user
        v['language'] = lang(req)
        v['t'] = translation_t

        v['spc'] = [Menu("sub_header_frontend", "../", target="_parent")]
        if user.isAdmin():
            v['spc'].append(Menu("sub_header_administration", "../admin", target="_parent"))

        if user.isWorkflowEditor():
            v['spc'].append(Menu("sub_header_workflow", "../publish", target="_parent"))

        v['spc'].append(Menu("sub_header_logout", "../logout", target="_parent"))

        # add icons to breadcrumbs
        ipath = 'webtree/directory.gif'
        if node and node.isContainer():
            if node.name == 'home' or 'Arbeitsverzeichnis' in node.name:
                ipath = 'webtree/homeicon.gif'
            elif node.name == 'Uploads':
                ipath = 'webtree/uploadicon.gif'
            elif node.name == 'Importe':
                ipath = 'webtree/importicon.gif'
            elif node.name == 'Inkonsistente Daten':
                ipath = 'webtree/faultyicon.gif'
            elif node.name == 'Papierkorb':
                ipath = 'webtree/trashicon.gif'
            else:
                ipath = getEditorIconPath(node)

        v["dircontent"] += '&nbsp;&nbsp;<img src="' + '/img/' + ipath + '" />'

        return req.writeTAL("web/edit/edit.html", v, macro="frame_content")
Exemplo n.º 19
0
def frameset(req):
    id = req.params.get("id", q(Collections).one().id)
    page = int(req.params.get("page", 1))
    nodes_per_page = req.params.get("nodes_per_page", "")
    if nodes_per_page:
        nodes_per_page = int(nodes_per_page)
    sortfield = req.params.get("sortfield", "")
    value = req.params.get("value", "")
    tab = req.params.get("tab", None)
    language = lang(req)
    user = current_user

    if not user.is_editor:
        req.writeTAL("web/edit/edit.html", {}, macro="error")
        req.writeTAL("web/edit/edit.html", {
            "id": id,
            "tab": (tab and "&tab=" + tab) or ""
        },
                     macro="edit_notree_permission")
        req.setStatus(httpstatus.HTTP_FORBIDDEN)
        return

    currentdir = q(Data).get(id)

    if currentdir is None:
        currentdir = q(Collections).one()
        req.params["id"] = currentdir.id
        id = req.params.get("id")

    # use always the newest version
    currentdir = currentdir.getActiveVersion()

    if unicode(currentdir.id) != id:
        req.params["id"] = unicode(currentdir.id)
        id = req.params.get("id")

    nodepath = []
    n = currentdir
    while n:
        nodepath = [n] + nodepath
        p = n.parents
        if p:
            n = p[0]
        else:
            n = None

    path = ['%s' % p.id for p in nodepath]
    containerpath = [('%s' % p.id) for p in nodepath
                     if isinstance(p, Container)]

    spc = [Menu("sub_header_frontend", "../", target="_parent")]
    if user.is_admin:
        spc.append(
            Menu("sub_header_administration", "../admin", target="_parent"))

    if user.is_workflow_editor:
        spc.append(Menu("sub_header_workflow", "../publish/",
                        target="_parent"))

    spc.append(
        Menu("sub_header_help",
             "http://mediatum.readthedocs.io",
             target="_blank"))

    spc.append(Menu("sub_header_logout", "../logout", target="_parent"))

    def getPathToFolder(node):
        n = node
        path = []
        while n:
            path = ['/%s' % n.id] + path
            p = n.parents
            if p:
                n = p[0]
            else:
                n = None
        return (node, "".join(path[2:]))

    def _getIDPath(nid, sep="/", containers_only=True):
        res = getIDPaths(nid, sep=sep, containers_only=containers_only)
        return res

    # does the user have a homedir? if not, create one
    if user.home_dir is None:
        user.create_home_dir()
        db.session.commit()
        logg.info("created new home dir for user #%s (%s)", user.id,
                  user.login_name)

    folders = {
        'homedir': getPathToFolder(user.home_dir),
        'trashdir': getPathToFolder(user.trash_dir),
        'uploaddir': getPathToFolder(user.upload_dir)
    }

    containertypes = Container.get_all_subclasses(
        filter_classnames=("collections", "home", "container"))

    if not user.is_admin:
        # search all metadatatypes which are container
        container_nodetype_names = [c.__name__.lower() for c in containertypes]
        allowed_container_metadatanames = [
            x[0] for x in q(Metadatatype.name).filter(
                Metadatatype.name.in_(
                    container_nodetype_names)).filter_read_access()
        ]

        # remove all elements from containertypes which names are not in container_metadatanames
        new_containertypes = []
        for ct in containertypes:
            ct_name = ct.__name__
            if ct_name.lower() in allowed_container_metadatanames:
                new_containertypes += [ct]
        containertypes = new_containertypes

    cmenu_iconpaths = []

    for ct in containertypes:
        ct_name = ct.__name__
        # translations of ct_name will be offered in editor tree context menu
        cmenu_iconpaths.append([
            ct_name.lower(),
            t(language, ct_name),
            get_editor_icon_path_from_nodeclass(ct)
        ])

    homenodefilter = req.params.get('homenodefilter', '')

    v = {
        "id": id,
        "page": page,
        "nodes_per_page": nodes_per_page,
        "sortfield": sortfield,
        "value": value,
        "searchitems": get_searchitems(req),
        "tab": (tab and "&tab=" + tab) or "",
        'user': user,
        'spc': spc,
        'folders': folders,
        'collectionsid': q(Collections).one().id,
        "basedirs": [q(Home).one(), q(Collections).one()],
        'cmenu_iconpaths': cmenu_iconpaths,
        'path': path,
        'containerpath': containerpath,
        'language': lang(req),
        't': t,
        '_getIDPath': _getIDPath,
        'homenodefilter': homenodefilter,
    }

    req.writeTAL("web/edit/edit.html", v, macro="edit_main")
Exemplo n.º 20
0
    def registroPrestamos(self):
        self.__log.info("Ingresando al menu de Prestamos")
        opcionesPrestamo = {
            "\t- Registrar Prestamo": 1,
            "\t- Registrar Devolucion": 2
        }
        menuPrestamo = Menu("Prestamo de Libros", opcionesPrestamo)
        resmenuPrestamo = menuPrestamo.mostrarMenu()
        stopMenu = True
        while stopMenu:
            if resmenuPrestamo == 1:
                self.__log.info("Entrando al prestamo de libros")
                usuario = User()
                numDocumento = input("Ingrese su numero de documento: ")
                try:
                    listaUser = []
                    for obj in usuario.all():
                        a = [
                            obj.id, obj.nombre, obj.documento,
                            obj.estado_user_id
                        ]
                        listaUser.append(a)
                    aaa = False
                    i = 0
                    while aaa == False:
                        if listaUser[i][2] == numDocumento:
                            aaa = True
                            user_id = listaUser[i][0]
                            name = listaUser[i][1]
                            resultado = listaUser[i][3]
                            estadoUser = EstadoUser()
                            listaEstadoUser = []
                            for obj in estadoUser.all():
                                a = [obj.id, obj.descripcion]
                                listaEstadoUser.append(a)
                            bbb = False
                            j = 0
                            while bbb == False:
                                if listaEstadoUser[j][0] == resultado:
                                    est_User = listaEstadoUser[j][1]
                                    if est_User == "Inactivo" or est_User == "Pendiente Aprobacion":
                                        print("Su estado es: ", est_User,
                                              "no puede retirar libros")
                                        stopMenu = False
                                    elif est_User == "Activo":
                                        print("Bienvenido ", name,
                                              "su estado de usuario es: ",
                                              est_User)

                                        libros = Libro()
                                        nombreLibro = input(
                                            "Ingrese el nombre del libro: ")
                                        try:
                                            guiaLibros = []
                                            for obj in libros.all():
                                                a = [
                                                    obj.id, obj.nombre,
                                                    obj.estado_libro_id
                                                ]
                                                guiaLibros.append(a)

                                            ccc = False
                                            i = 0
                                            while ccc == False:
                                                if guiaLibros[i][
                                                        1] == nombreLibro:
                                                    libro_id = guiaLibros[i][0]
                                                    resultado1 = guiaLibros[i][
                                                        2]
                                                    ccc = True
                                                    estadoLibro = EstadoLibro()
                                                    estadoLibros = []
                                                    for obj in estadoLibro.all(
                                                    ):
                                                        a = [
                                                            obj.id,
                                                            obj.descripcion
                                                        ]
                                                        estadoLibros.append(a)

                                                    bbb = False
                                                    j = 0
                                                    while bbb == False:
                                                        if estadoLibros[j][
                                                                0] == resultado1:
                                                            est_Libros = estadoLibros[
                                                                j][1]

                                                            if est_Libros == "Disponible":
                                                                print(
                                                                    "El libro, se encuentra ",
                                                                    est_Libros)
                                                                est_Libros = "Prestado"
                                                                prestamo = Prestamo(
                                                                )
                                                                prestamo.user_id = user_id
                                                                prestamo.libros_id = libro_id
                                                                prestamo.prestado_on = datetime.now(
                                                                )
                                                                prestamo.bibliotecas_id = 1
                                                                prestamo.save()
                                                                stopMenu = False
                                                                print(
                                                                    "El registro del prestamo, se realizo con exito"
                                                                )
                                                            elif est_Libros == "Reservado" or est_Libros == "Prestado":
                                                                print(
                                                                    "El libro se encuentra: ",
                                                                    est_Libros)
                                                                stopMenu = False
                                                            else:
                                                                print(
                                                                    "digito mal"
                                                                )
                                                                stopMenu = False
                                                            bbb = True
                                                        else:
                                                            j = j + 1

                                                else:
                                                    i = i + 1
                                        except:
                                            print("El libro no existe")
                                            stopMenu = False

                                    else:
                                        print("Digito mal")
                                        stopMenu = False
                                    bbb = True
                                else:
                                    j = j + 1
                        else:
                            i = i + 1
                except:
                    print("ALGO FALLO EN EL PROGRAMA")
                stopMenu = False

            elif resmenuPrestamo == 2:
                libros = Libro()
                isbnLibro = input("Ingrese el ISBN del libro a devolver: ")
                try:
                    listaLibros = []
                    for obj in libros.all():
                        a = [obj.id, obj.nombre, obj.isbn]
                        listaLibros.append(a)
                    aaa = False
                    i = 0
                    while aaa == False:
                        if listaLibros[i][2] == isbnLibro:
                            idLibro = listaLibros[i][0]
                            prestamo = Prestamo()
                            listaPrestamos = []
                            for obj in libros.all():
                                a = [
                                    obj.id, obj.user_id, obj.libros_id,
                                    obj.prestado_on, obj.bibliotecas_id
                                ]
                                listaPrestamos.append(a)
                            bbb = False
                            j = 0
                            while bbb == False:
                                if listaPrestamos[i][2] == idLibro:
                                    prestamo.user_id = listaPrestamos[i][1]
                                    prestamo.libros_id = listaPrestamos[i][2]
                                    prestamo.prestado_on = datetime.now()
                                    prestamo.bibliotecas_id = listaPrestamos[
                                        i][4]
                                    prestamo.save()
                                    stopMenu = False
                                    bbb = True
                                else:
                                    j = j + 1
                            aaa = True
                        else:
                            i = i + 1
                except:
                    print(
                        "El libro no existe o no está registrado en la biblioteca"
                    )
                stopMenu = False

            elif resmenuPrestamo == 9:
                self._log.info("Saliendo")
                stopMenu = False