def __init__(self, padre):
     self.padre = padre
     arch = leerglade.leer('nav_nc_compras.glade')
     self.nav = arch.get_object
     self.nav('window1').set_title('Listado de Nota de Credito Compras')
     self.nav('window1').set_default_size(900, 600)
     self.nav('window1').set_position(1)
     self.nav('bt_nuevo').set_label('Nuevo')
     self.nav('bt_editar').set_label('Editar')
     self.nav('bt_eliminar').set_label('Eliminar')
     self.nav('bt_cerrar').set_label('Cerrar')
     self.entity = NotaCreditoCompras()
     self.tipo_facturas = TipoFacturas()
     self.detalle = DetalleNotaCreditoCompras()
     self.contactos = Contactos()
     self.articulos = Articulos()
     self.old_precio = None
     self.encabezado = False
     self.nav('window1').set_transient_for(self.padre.main('window1'))
     self.nav('window1').set_modal(True)
     self.nav('window1').set_border_width(5)
     self.nav('window1').show_all()
     arch.connect_signals(self)
     self.nav('bt_editar').set_visible(False)
     self.nav('bt_eliminar').set_visible(False)
     self.consultar()
class RegFacturaNcCompra:
    def __init__(self, padre):
        self.padre = padre
        arch = leerglade.leer('nav_nc_compras.glade')
        self.nav = arch.get_object
        self.nav('window1').set_title('Listado de Nota de Credito Compras')
        self.nav('window1').set_default_size(900, 600)
        self.nav('window1').set_position(1)
        self.nav('bt_nuevo').set_label('Nuevo')
        self.nav('bt_editar').set_label('Editar')
        self.nav('bt_eliminar').set_label('Eliminar')
        self.nav('bt_cerrar').set_label('Cerrar')
        self.entity = NotaCreditoCompras()
        self.tipo_facturas = TipoFacturas()
        self.detalle = DetalleNotaCreditoCompras()
        self.contactos = Contactos()
        self.articulos = Articulos()
        self.old_precio = None
        self.encabezado = False
        self.nav('window1').set_transient_for(self.padre.main('window1'))
        self.nav('window1').set_modal(True)
        self.nav('window1').set_border_width(5)
        self.nav('window1').show_all()
        arch.connect_signals(self)
        self.nav('bt_editar').set_visible(False)
        self.nav('bt_eliminar').set_visible(False)
        self.consultar()


    def consultar(self, widget=None):
        self.nav('liststore1').clear()
        color = False
        for row in self.entity.compras_all(self.nav('entry1').get_text()):
            if not color:
                t_color = "#FFFFDA"
                color = True
            else:
                t_color = "#A9FFA9"
                color = False
            self.nav('liststore1').append([
                row[0], row[1], row[2], row[3],
                Format.number(row[4]), Format.number(row[5]),
                Format.number(row[6]), Format.number(row[7]), t_color
            ])

        if len(self.nav('liststore1')) == 0:
            self.nav('bt_editar').set_sensitive(False)
            self.nav('bt_eliminar').set_sensitive(False)
            self.nav('label1').set_text(' 0 Registros Encontrados')
        else:
            self.nav('bt_editar').set_sensitive(True)
            self.nav('bt_eliminar').set_sensitive(True)
            self.nav('label1').set_text(' %s Registros Encontrados' % len(self.nav('liststore1')))

        self.nav('entry1').set_text(self.nav('entry1').get_text().upper())

    def bt_nuevo_cb(self, widget):
        self.formulario()
        self.frm('entry8').set_text(self.padre.user_login.nombres_apellidos)
        self.frm('entry1').grab_focus()
        self.frm('button2').set_sensitive(False)

    def bt_editar_cb(self, widget):
        pass

    def bt_eliminar_cb(self, widget):
        pass

    def bt_cerrar_cb(self, widget):
        self.nav('window1').destroy()

    def formulario(self):
        arch = leerglade.leer('frm_nc_compra.glade')
        self.frm = arch.get_object
        self.frm('window1').set_default_size(800, 600)
        self.frm('window1').set_transient_for(self.nav('window1'))
        self.frm('window1').set_position(1)
        self.frm('window1').set_modal(True)
        self.frm('window1').set_border_width(5)
        self.frm('window1').set_title('Formulario de Nota de Credito')
        self.frm('window1').show_all()
        arch.connect_signals(self)


    def validar_entrys(self, widget=None):
        pass

    def guardar(self, widget=None):

        if len(self.frm('entry1').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Nro. Documento es Obligatorio!")
            self.frm('entry1').grab_focus()
            return
        if len(self.frm('entry2').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Fecha es Obligatorio!")
            self.frm('entry2').grab_focus()
            return
        if len(self.frm('entry3').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Tipo Factura es Obligatorio!")
            self.frm('entry3').grab_focus()
            return
        if len(self.frm('entry4').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Proveedor es Obligatorio!")
            self.frm('entry4').grab_focus()
            return
        if len(self.frm('entry7').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Timbrado es Obligatorio!")
            self.frm('entry7').grab_focus()
            return

        if len(self.frm('entry9').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Articulo es Obligatorio!")
            self.frm('entry9').grab_focus()
            return

        if len(self.frm('entry10').get_text()) == 0:
            msg.errorMsgBox(self.frm('window1'), "Campo Obligatorio",
                            "El campo Precio Costo es Obligatorio!")
            self.frm('entry10').grab_focus()
            return

        if not self.encabezado:
            self.entity.nro_notacredito = self.frm('entry1').get_text()
            self.entity.nro_timbrado = self.frm('entry7').get_text()
            self.entity.idcontacto = self.frm('entry4').get_text()
            self.entity.fecha = self.frm('entry2').get_text()
            self.entity.idtipo_factura = self.frm('entry3').get_text().split('-')[0]
            self.entity.idusuario = self.padre.user_login.idusuario

            self.entity.nro_factura = self.frm('entry13').get_text()
            self.entity.nro_timbrado_compras = self.frm('entry15').get_text()
            self.entity.idcontacto_compras = self.frm('entry4').get_text()

            if self.entity.save():
                self.desactivar_encabezado()
                self.encabezado = True
                self.consultar()

        if self.encabezado:
            cantidad = self.articulo_en_detalle(self.frm('entry9').get_text())
            if cantidad:
                cantidad += float(self.frm('entry12').get_text())
                update = self.detalle.update_cantidad(
                    cantidad, self.frm('entry1').get_text(),
                    self.frm('entry7').get_text(),
                    self.frm('entry4').get_text(),
                    self.frm('entry9').get_text()
                )
                if update:
                    self.limpiar_articulos()
                    self.refrescar_detalle()
                    self.frm('entry9').grab_focus()

                return

            self.detalle.nro_notacredito = self.frm('entry1').get_text()
            self.detalle.nro_timbrado = self.frm('entry7').get_text()
            self.detalle.idcontacto = self.frm('entry4').get_text()
            self.detalle.idarticulo = self.frm('entry9').get_text()
            self.detalle.idunidad_medida = self.frm('label8').get_text().split('-')[0]
            self.detalle.cantidad_empaque = self.frm('label8').get_text().split('-')[1]
            self.detalle.precio_costo = self.frm('entry11').get_text()
            self.detalle.iva = self.frm('label9').get_text()
            self.detalle.cantidad = self.frm('entry12').get_text()

            if self.detalle.save():
                self.refrescar_detalle()
                self.limpiar_articulos()
                self.frm('entry9').grab_focus()
                self.frm('button2').set_sensitive(True)

    def articulo_en_detalle(self, idarticulo):
        for row in self.frm('liststore1'):
            if idarticulo == row[0]:
                return float(row[2])
        return False

    def refrescar_detalle(self):
        self.frm('liststore1').clear()
        ex = 0.0
        g5 = 0.0
        g10 = 0.0
        for row in self.detalle.get_detalle(self.frm('entry1').get_text(), self.frm('entry7').get_text(),
                                            self.frm('entry4').get_text()):
            ex += row[4]
            g5 += row[5]
            g10 += row[6]
            self.frm('liststore1').append([
                str(row[0]), row[1], Format.number(row[2]), Format.number(row[3]),
                Format.number(row[4]), Format.number(row[5]),
                Format.number(row[6])
            ])

        self.frm('exentas').set_text(Format.number(ex))
        self.frm('gravada5').set_text(Format.number(g5))
        self.frm('gravada10').set_text(Format.number(g10))
        self.frm('iva5').set_text(Format.number(round(g5/21)))
        self.frm('iva10').set_text(Format.number(round(g10/11)))
        self.frm('t_iva').set_text(Format.number(round(g5/21)+round(g10/11)))
        self.frm('t_documento').set_text(Format.number(ex+g5+g10))



    def limpiar_articulos(self):
        self.frm('entry9').set_text("")
        self.frm('entry10').set_text("")
        self.frm('entry11').set_text("")
        self.frm("entry12").set_text("")
        self.frm('label8').set_text("Empaque")
        self.frm('label9').set_text("IVA")

    def desactivar_encabezado(self):
        self.frm('entry1').set_sensitive(False)
        self.frm('entry7').set_sensitive(False)
        self.frm('entry4').set_sensitive(False)
        self.frm('entry2').set_sensitive(False)
        self.frm('entry3').set_sensitive(False)
        self.frm('entry13').set_sensitive(False)
        self.frm('entry14').set_sensitive(False)
        self.frm('entry15').set_sensitive(False)

    def cancelar_cb(self, widget):
        self.encabezado = False
        self.frm('window1').destroy()
        self.consultar()

    def cargar_combos(self):
        pass
        #
        #for row in self.tipo_comprobantes.all(order_by=1, descripcion__ilike="%%"):
        #    self.frm('liststore1').append([str(row[0])+'-'+row[1]])
        #self.frm('combobox1').set_active(0)

    def set_active_combo(self, pk):
        it = 0
        for row in self.frm('liststore1'):
            if row[0].split('-')[0] == str(pk):
                self.frm('combobox1').set_active(it)
                break
            it += 1

    def buscar_fechas(self, widget, icon_pos, event):
        Calendar.Pegar(self.frm('window1'), widget)

    def buscar_referencias(self, widget, event):
        if event.keyval == 65470:
            
            if widget == self.frm('entry3'):
                data = self.tipo_facturas.all(order_by=2)
                busquedas.Buscar(self, data, widget)
            elif widget == self.frm('entry4'):
                data = self.contactos.get_all_contactos(2, "")
                busquedas.Buscar(self, data, widget, True)
            elif widget == self.frm('entry9'):
                data = self.articulos.all(order_by=3, where="habil_compras = True")
                busquedas.Buscar(self, data, widget, True, 2)
            elif widget == self.frm('entry9'):
                data = self.procedencias.all(order_by=2)
                busquedas.Buscar(self, data, widget)

    def treeview_key_press_cb(self, widget, event):
        if event.keyval == 65535:
            sl, it = self.frm('treeview1').get_selection().get_selected()
            try:
                idarticulo = sl.get_value(it, 0)
            except:
                msg.errorMsgBox(self.frm('window1'), "Sin selección", "Seleccione un registro para eliminar")
                return
            res = msg.preguntaMsgBox(self.frm('window1'), "Eliminando Registro",
                                     "Estas seguro?")
            if res == -8:
                quitar = self.detalle.quitar_detalle(
                    self.frm('entry1').get_text(),
                    self.frm('entry7').get_text(),
                    self.frm('entry4').get_text(),
                    idarticulo
                )

                self.refrescar_detalle()

    def iva_set(self, widget=None):
        try:
            cat = int(self.frm('entry8').get_text().split('-')[0])
        except:
            return
        self.categorias.find(idcategoria=cat)
        self.frm('entry13').set_text(str(self.categorias.iva))

    def cargar_proveedor(self):
        if len(self.frm('entry4').get_text()) == 0:
            return 
        
        dato = self.contactos.get_contacto(2, self.frm('entry4').get_text())
        if dato is None:
            msg.errorMsgBox(
                self.frm('window1'),
                "Contacto Inexistente",
                "Contacto inexistente o no establecido como Proveedor"
            )
            return 
        self.frm('entry5').set_text(dato[1])
        self.frm('entry6').set_text(dato[2])

    def cargar_articulos(self):
        if len(self.frm('entry9').get_text()) == 0:
            return
        dato = self.articulos.find(
            idarticulo=self.frm('entry9').get_text()
        )
        if dato[0] is None:
            msg.errorMsgBox(
                self.frm('window1'),
                "Articulo Inexistente",
                "El id ingresado no corresponde a ningún artículo registrado!"
            )
            self.frm('entry8').grab_focus()
            self.limpiar_articulos()
            return
        if not self.articulos.habil_compras:
            msg.errorMsgBox(
                self.frm('window1'),
                "Atención",
                "El articulo no está habilitado para compras."
            )
            self.limpiar_articulos()
            self.frm('entry8').grab_focus()
            return

        self.frm('entry10').set_text(self.articulos.descripcion)
        self.frm('label8').set_text(self.articulos.idunidad_medida + '-' + str(self.articulos.empaque))
        self.frm('label9').set_text(str(self.articulos.get_iva(self.articulos.idarticulo)))
        self.frm('entry11').set_text(str(self.articulos.precio_costo))
        self.frm('entry12').set_text('1')

    def set_focus(self, widget):
        if widget == self.frm('entry2'):
            widget.set_text(Format.fecha(widget.get_text()))
        if widget == self.frm('entry4'):
            self.cargar_proveedor()
        if widget == self.frm('entry1'):
            widget.set_text(Format.factura(widget.get_text()))
        if widget == self.frm('entry9'):
            self.cargar_articulos()
        widget.get_toplevel().child_focus(Gtk.DirectionType.TAB_FORWARD)

        if widget == self.frm('entry12'):
            self.guardar()

    def buscar_factura(self, widget, event):
        if event.keyval == 65470:
            busqueda_compras.Buscar(self, [self.frm('entry13'), self.frm('entry14'),
                                           self.frm('entry15'), self.frm('entry4'),
                                           self.frm('entry5'), self.frm('entry6')])
    def confirmar_cb(self, widget):
        #por el momento
        self.frm('window1').destroy()
        self.encabezado = False
        self.consultar()

    def win_delete_event(self, widget, event):
        self.encabezado = False
        self.consultar()