コード例 #1
0
ファイル: presupuesto.py プロジェクト: BlasFerna/hardsoft
 def __init__(self, padre):
     self.dic_rp = {}
     self.padre = padre
     arch = leerglade.leer("nav_presupuesto.glade")
     self.nav = arch.get_object
     self.nav("window1").set_title("Listado de Presupuestos")
     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 = Presupuesto()
     self.detalle = DetallePresupuesto()
     self.contactos = Contactos()
     self.articulos = Articulos()
     self.categorias = Categorias()
     self.precios = Precios()
     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()
コード例 #2
0
 def __init__(self, padre):
     self.padre = padre
     arch = leerglade.leer('nav_nc_ventas.glade')
     self.nav = arch.get_object
     self.nav('window1').set_title('Listado de Nota de Credito Ventas')
     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 = NotaCreditoVentas()
     self.tipo_facturas = TipoFacturas()
     self.detalle = DetalleNotaCreditoVentas()
     self.contactos = Contactos()
     self.articulos = Articulos()
     self.precios = Precios()
     self.categorias = Categorias()
     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()
コード例 #3
0
ファイル: presupuesto.py プロジェクト: BlasFerna/hardsoft
class RegPresupuesto:
    def __init__(self, padre):
        self.dic_rp = {}
        self.padre = padre
        arch = leerglade.leer("nav_presupuesto.glade")
        self.nav = arch.get_object
        self.nav("window1").set_title("Listado de Presupuestos")
        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 = Presupuesto()
        self.detalle = DetallePresupuesto()
        self.contactos = Contactos()
        self.articulos = Articulos()
        self.categorias = Categorias()
        self.precios = Precios()
        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.presupuesto_all(self.nav("entry1").get_text()):
            if not color:
                t_color = "#FFFFDA"
                color = True
            else:
                t_color = "#A9FFA9"
                color = False
            self.nav("liststore1").append(
                [
                    str(row[0]),
                    row[1],
                    str(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").set_text(str(self.entity.get_id()))
        self.frm("entry4").grab_focus()
        self.frm("entry2").set_text(datetime.now().strftime("%d/%m/%Y"))
        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_presupuesto.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("Presupuestos")
        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!")
            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("entry4").get_text()) == 0:
            msg.errorMsgBox(self.frm("window1"), "Campo Obligatorio", "El campo Cliente es Obligatorio!")
            self.frm("entry4").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.numero = self.frm("entry1").get_text()
            self.entity.fecha = self.frm("entry2").get_text()
            self.entity.idcontacto = self.frm("entry4").get_text()
            self.entity.idusuario = self.padre.user_login.idusuario

            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("entry9").get_text()
                )
                if update:
                    self.limpiar_articulos()
                    self.refrescar_detalle()
                    self.frm("entry9").grab_focus()

                return

            self.detalle.numero = self.frm("entry1").get_text()
            self.detalle.idarticulo = self.frm("entry9").get_text()
            self.detalle.cantidad = self.frm("entry12").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_venta = self.frm("entry11").get_text()
            self.detalle.iva = self.frm("label9").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.det_all(self.frm("entry1").get_text()):
            ex += row[4]
            g5 += row[5]
            g10 += row[6]
            self.frm("liststore1").append(
                [
                    str(row[0]),
                    row[1],
                    Format.number(float(row[2].split("-")[0])),
                    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("entry4").set_sensitive(False)
        self.frm("entry2").set_sensitive(False)
        # self.frm('entry3').set_sensitive(False)

    def cancelar_cb(self, widget):
        if (
            msg.preguntaMsgBox(
                self.frm("window1"), "Atención: Transacción en curso", "Cancelando operació, esta seguro?"
            )
            == -8
        ):
            self.encabezado = False
            self.entity.eliminar(self.frm("entry1").get_text())
            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)
        return

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

    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(), 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(1, self.frm("entry4").get_text())
        if dato is None:
            msg.errorMsgBox(
                self.frm("window1"), "Contacto Inexistente", "Contacto inexistente o no indicado como Cliente"
            )
            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
        try:
            dato = self.articulos.find(idarticulo=self.frm("entry9").get_text())
        except:
            msg.errorMsgBox(
                self.frm("window1"),
                "Articulo Inexistente",
                "El id ingresado no corresponde a ningún artículo registrado!",
            )
            return
        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_ventas:
            msg.errorMsgBox(self.frm("window1"), "Atención", "El articulo no está habilitado para ventas.")
            self.limpiar_articulos()
            self.frm("entry8").grab_focus()
            return

        self.frm("entry10").set_text(self.articulos.descripcion)
        precios = self.precios.all(where="idarticulo=%s and vigente = True" % self.articulos.idarticulo)
        if len(precios) > 1:
            busquedas.Buscar(self, precios, [self.frm("entry11"), self.frm("label8")], None, 1, True)
        else:
            self.frm("entry11").set_text(str(precios[0][5]))
            self.frm("label8").set_text(precios[0][3] + "-" + str(precios[0][4]))
        self.frm("label9").set_text(str(self.articulos.get_iva(self.articulos.idarticulo)))

        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()
            # en este caso clientes
        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 confirmar_cb(self, widget):
        self.imprimir()
        self.frm("window1").destroy()
        self.encabezado = False
        self.consultar()

    def win_delete_event(self, widget, event):
        self.cancelar_cb(0)

    def pdf(self, filename):

        f = file(os.path.join("reportes", "presupuesto.pdf"), "wb")
        # Crea un archivo para enviarlo como parametro
        pisa.CreatePDF(filename, f)
        # cierra el archivo para que no produzca un error
        file.close(f)
        if sys.platform == "win32":
            os.startfile(os.path.join("reportes", "presupuesto.pdf"))
        else:
            os.system("evince reportes/presupuesto.pdf")

    def getLines(self, row):
        for texto in self.dic_rp.keys():
            if texto in row:
                return row.replace(texto, str(self.dic_rp[texto]))
        return row

    def imprimir(self):
        file = open("reportes/presupuesto.html", "r").readlines()

        rows = ""

        for row in self.frm("liststore1"):
            stotal = float(row[4].replace(",", "")) + float(row[5].replace(",", "")) + float(row[6].replace(",", ""))
            rows += """
               <tr>
                   <td style = "{text-align: right;}" width = 50>%s</td>
                   <td style = "{text-align: left;}">%s</td>
                   <td style = "{text-align: right;}" width = 80>%s</td>
                   <td style = "{text-align: right;}" width = 80>%s</td>
                   <td style = "{text-align: right;}" width = 80>%s</td>
               </tr>
            """ % (
                row[0],
                row[1],
                row[2],
                row[3],
                Format.number(stotal),
            )

        rows += """
               <tr>
                   <td style = "{text-align: right;}" width = 50>&nbsp;</td>
                   <td style = "{text-align: left;}">&nbsp;</td>
                   <td style = "{text-align: right;}" width = 80>&nbsp;</td>
                   <td style = "{text-align: right;}" width = 80><big>TOTAL</big></td>
                   <td style = "{text-align: right;}" width = 80>%s</td>
               </tr>
        """ % (
            self.frm("t_documento").get_text()
        )

        self.dic_rp = {
            "{TITLE}": "Nota de Presupuesto",
            "{EMPRESA}": self.padre.main("label1").get_text(),
            "{FECHA}": datetime.now().strftime("%d/%m/%Y"),
            "{CLIENTE}": self.frm("entry5").get_text(),
            "{ROW}": rows,
        }

        html = ""
        for row in file:
            line = self.getLines(row)
            html += line
            html += "\n"
        # print html
        self.pdf(html)
コード例 #4
0
class RegFacturaNcVenta:
    def __init__(self, padre):
        self.padre = padre
        arch = leerglade.leer('nav_nc_ventas.glade')
        self.nav = arch.get_object
        self.nav('window1').set_title('Listado de Nota de Credito Ventas')
        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 = NotaCreditoVentas()
        self.tipo_facturas = TipoFacturas()
        self.detalle = DetalleNotaCreditoVentas()
        self.contactos = Contactos()
        self.articulos = Articulos()
        self.precios = Precios()
        self.categorias = Categorias()
        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.nc_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.encabezado = False
        fac = self.entity.get_new(
            self.padre.tim_nc_ventas,
            self.padre.establecimiento,
            self.padre.idpunto_expedicion
        )

        if str(fac[0]) == '1':
            fac = (self.padre.num_ini_nc_ventas,)

        if int(fac[0]) > self.padre.num_fin_nc_ventas:
            msg.errorMsgBox(self.nav('window1'), "Numero Maximo Alcanzado",
                            "Se ha superado la cantidad de numeros permitidos en el timbrado actual, avise al CONTADOR!")
            return

        est = '{:0>3}'.format(str(self.padre.establecimiento))
        pex = '{:0>3}'.format(str(self.padre.idpunto_expedicion))
        num = '{:0>7}'.format(str(fac[0]))
        factura = "%s-%s-%s" % (est, pex, num)

        self.formulario()
        self.frm('entry1').set_text(factura)
        self.frm('entry8').set_text(self.padre.user_login.nombres_apellidos)
        self.frm('entry7').set_text(str(self.padre.tim_nc_ventas))
        self.frm('entry2').set_text(datetime.now().strftime('%d/%m/%Y'))
        self.frm('entry3').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_ventas.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 Cliente 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_nota = self.frm('entry1').get_text().split('-')[2]
            self.entity.idpunto_expedicion = self.padre.idpunto_expedicion
            self.entity.idestablecimiento = self.padre.establecimiento
            self.entity.nro_timbrado = self.frm('entry7').get_text()
            self.entity.idtipo_factura = self.frm('entry3').get_text().split('-')[0]
            self.entity.fecha = self.frm('entry2').get_text()
            self.entity.idcontacto = self.frm('entry4').get_text()
            self.entity.idusuario = self.padre.user_login.idusuario
            self.entity.nro_factura_venta = self.frm('entry13').get_text().split('-')[2]
            self.entity.idpunto_expedicion_venta = self.frm('entry13').get_text().split('-')[1]
            self.entity.idestablecimiento_venta = self.frm('entry13').get_text().split('-')[0]
            self.entity.nro_timbrado_venta = self.frm('entry15').get_text()

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

        if self.encabezado:
            nro_factura = self.frm('entry1').get_text().split('-')[2]
            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, nro_factura,
                    self.frm('entry7').get_text(),
                    self.padre.establecimiento,
                    self.padre.idpunto_expedicion,
                    self.frm('entry9').get_text()
                )
                if update:
                    self.limpiar_articulos()
                    self.refrescar_detalle()
                    self.frm('entry9').grab_focus()

                return

            self.detalle.nro_nota = self.frm('entry1').get_text().split('-')[2]
            self.detalle.nro_timbrado = self.frm('entry7').get_text()
            self.detalle.idpunto_expedicion = self.padre.idpunto_expedicion
            self.detalle.idestablecimiento = self.padre.establecimiento
            self.detalle.idarticulo = self.frm('entry9').get_text()
            self.detalle.idunidad_medida = self.frm('label8').get_text().split('-')[0]
            self.detalle.canidad_empaque = self.frm('label8').get_text().split('-')[1]
            self.detalle.precio_venta = self.frm('entry11').get_text()
            self.detalle.iva = self.frm('label9').get_text()
            self.detalle.cantidad = self.frm('entry12').get_text()
            actualizar = self.detalle.save()
            print actualizar
            if actualizar:
                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
        nro_factura = self.frm('entry1').get_text().split('-')[2]
        for row in self.detalle.get_detalle(nro_factura, self.frm('entry7').get_text(),
                                            self.padre.idpunto_expedicion,
                                            self.padre.establecimiento):
            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(1, "")
                busquedas.Buscar(self, data, widget, True)
            elif widget == self.frm('entry9'):
                data = self.articulos.all(order_by=3, where="habil_ventas = True")
                busquedas.Buscar(self, data, widget, True, 2)

    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:
                nro_factura = self.frm('entry1').get_text().split('-')[2]
                quitar = self.detalle.quitar_detalle(
                    nro_factura,
                    self.frm('entry7').get_text(),
                    self.padre.establecimiento,
                    self.padre.idpunto_expedicion,
                    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(1, self.frm('entry4').get_text())
        if dato is None:
            msg.errorMsgBox(
                self.frm('window1'),
                "Contacto Inexistente",
                "Contacto inexistente o no establecido como Cliente"
            )
            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
        try:
            dato = self.articulos.find(
                idarticulo=self.frm('entry9').get_text()
            )
        except:
            msg.errorMsgBox(
                self.frm('window1'),
                "Articulo Inexistente",
                "El id ingresado no corresponde a ningún artículo registrado!"
            )
            return
        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_ventas:
            msg.errorMsgBox(
                self.frm('window1'),
                "Atención",
                "El articulo no está habilitado para ventas."
            )
            self.limpiar_articulos()
            self.frm('entry8').grab_focus()
            return

        self.frm('entry10').set_text(self.articulos.descripcion)
        precios = self.precios.all(where = "idarticulo=%s and vigente = True"%self.articulos.idarticulo)
        if len(precios) > 1:
            busquedas.Buscar(self, precios,
                             [self.frm('entry11'), self.frm('label8')], None, 1, True)
        else:
            self.frm('entry11').set_text(str(precios[0][5]))
            self.frm('label8').set_text(precios[0][3] + '-' + str(precios[0][4]))
        self.frm('label9').set_text(str(self.articulos.get_iva(self.articulos.idarticulo)))

        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_ventas.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):
        self.imprimir()
        self.frm('window1').destroy()
        self.encabezado = False
        self.consultar()

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


    def pdf(self, filename):
        #impresión de la factura
        f =  file(os.path.join('reportes', 'factura_venta.pdf'), 'wb')
        pisa.CreatePDF(filename, f)

        file.close(f)
        if sys.platform == 'win32':
            os.startfile(os.path.join('reportes', 'factura_venta.pdf'))
        else:
            os.system('evince reportes/factura_venta.pdf')

    def detalle_html(self):
        html = ""
        for row in self.frm('liststore1'):
            html += """
                <tr>
                    <td class = "row-codigo">%s</td>
                    <td class = "row-cantidad">%s</td>
                    <td widht = "300px" class = "row-descrip">%s</td>
                    <td class = "row-precio">%s</td>
                    <td class = "totales">%s</td>
                    <td class = "totales">%s</td>
                    <td class = "totales">%s</td>
                </tr>
            """ % (row[0], row[2], row[1],
            row[3], row[4], row[5], row[6])

        t_rows = 12
        if len(self.frm('liststore1')) < t_rows:
            for i in range(len(self.frm('liststore1')), t_rows):
                html += """<tr>
                            <td class = "row-codigo">&nbsp;</td>
                            <td class = "row-cantidad">&nbsp;</td>
                            <td widht = "300px" class = "row-descrip">&nbsp;</td>
                            <td class = "row-precio">&nbsp;</td>
                            <td class = "totales">&nbsp;</td>
                            <td class = "totales">&nbsp;</td>
                            <td class = "totales">&nbsp;</td>
                        </tr>
                    """
        return html

    def total_html(self):
        html = """
                <td class = "totales-totales">%s</td>
                <td class = "totales-totales">%s</td>
                <td class = "totales-totales">%s</td>
                <tr>
                    <td colspan = "5" class = "total-apagar">TOTAL A PAGAR: %s</td>
                    <td colspan = "2" class = "total-general">%s</td>
                </tr>
                <table class = "box-liquid">
                    <td class = "liquid">LIQUIDACION DEL IVA(5): %s</td>
                    <td class = "liquid">IVA 10: %s</td>
                    <td class = "liquid">TOTAL IVA: %s</td>
                </table>
        """%(self.frm('exentas').get_text(), self.frm('gravada5').get_text(), self.frm('gravada10').get_text(),
        num_to_text.to_word(int(self.frm('t_documento').get_text().replace(',', ''))), self.frm('t_documento').get_text(),
        self.frm('iva5').get_text(), self.frm('iva10').get_text(), self.frm('t_iva').get_text())

        return html

    def imprimir(self):
        contado = ' '
        credito = ' '
        if self.frm('entry3').get_text().split('-')[0] == '1':
            contado = 'x'
            credito = ' '
        else:
            credito = 'x'
            contado = ' '
        html = """
        <html>
            <head>
            <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
            <title>Factura Ventas</title></head>
            <style>
                @page {
                     size: legal;
                     margin: 0.5cm;
                    }
                .empresa{
                    padding-top: 3px;
                    border: 0.5px solid black;
                    padding-left: 2px;

                }
                .numero{
                    padding-top: 3px;
                    border: 0.5px solid black;
                    width: 250px;
                    padding-left: 2px;
                    padding-right: 2px;
                    background-color: #FFFFFF;

                }
                .datos{
                    border: 0.5px solid black;
                    padding-top: 3px;
                    padding-left: 2px;
                    padding-right: 2px;
                }

                .detalle{
                    margin-top: 10px;
                    padding-top: 3px;
                    padding-left: 2px;
                    padding-right: 2px;
                }

                .codigo{
                    border: 0.5px solid black;
                }
                .descripcion{
                    border: 0.5px solid black;
                    width: 300px;
                    text-align: center;
                }
                .cantidad{
                    border: 0.5px solid black;
                    text-align: right;

                }
                .precio{
                    border: 0.5px solid black;
                    text-align: center;
                }

                .exentas{
                    border: 0.5px solid black;
                    text-align: center;
                }
                .porcc{
                    border: 0.5px solid black;
                    text-align: center;
                }
                .porcd{
                    border: 0.5px solid black;
                    text-align: center;
                }

                .fecha{
                    text-align: left;
                }
                .condicion{
                    text-align: right;
                }

                .textbold{
                    font-weight: bold;
                }

                .str-empresa{
                    font-weight: bold;
                    font: 16px;
                    text-align: center;
                    color: #1A1A1A;
                }
                .str-actividad{
                    font-weight: bold;
                    font: 14px;
                    text-align: center;
                    color: #1A1A1A;
                }

                .header-detalle{
                    background-color: #FFFFFF;
                }

               .row-codigo{
                    text-align: right;
                    border-left: 0.5px solid black;
                    border-right: 0.5px solid black;
                }

                .row-cantidad{
                    text-align: right;
                    border-right: 0.5px solid black;
                }

               .row-descrip{
                    border-right: 0.5px solid black;
                }
               .row-precio{
                    text-align: right;
                    border-right: 0.5px solid black;
                }
               .totales{
                    text-align: right;
                    border-right: 0.5px solid black;
                }
               .sub-totales{
                    border-top: 0.5px solid black;
                    border-bottom: 0.5px solid black;
                    border-left: 0.5px solid black;
                    border-right: 0.5px solid black;
                    font-weight: bold;
               }
               .totales-totales{
                    text-align: right;
                    border-right: 0.5px solid black;
                    font-weight: bold;
                    border-top: 0.5px solid black;
                    border-bottom: 0.5px solid black;
                }

                .total-apagar{
                   font-weight: bold;
                   border-bottom: 0.5px solid black;
                   border-left: 0.5px solid black;
                   border-right: 0.5px solid black;
                }

                .total-general{
                    font-weight: bold;
                   border-bottom: 0.5px solid black;
                   border-right: 0.5px solid black;
                   text-align: right;
                   font-size: 11px;
                }

                .liquid{
                   font-weight: bold;
                   border-bottom: 0.5px solid black;
                }
                .box-liquid{
                   border-left: 0.5px solid black;
                   border-right: 0.5px solid black;
                   padding-top: 3px;
                   padding-left: 2px;
                   padding-right: 2px;
                }
            </style>
            <body>

                <table>
                    <tr>
                        <td class = "empresa">
                            <table>
                                <tr>
                                    <td colspan = "2" class = "str-empresa"><i>%s</i></td>
                                </tr>
                                <tr>
                                    <td colspan = "2" class = "str-actividad"><i>%s</i></td>
                                </tr>
                                <tr>
                                    <td class = "fecha"><span class = "textbold">Direccion: </span>%s</td>
                                    <td class = "condicion" style = "{padding-right: 2px; width: 150px;}">
                                        <span class = "textbold">Telefono: </span> %s
                                    </td>
                                </tr>
                                <tr>
                                    <td class = "fecha"><span class = "textbold">Ciudad: </span>%s</td>
                                    <td class = "condicion" style = "{padding-right: 2px; width: 150px;}">
                                        <span class = "textbold">Barrio: </span> %s
                                    </td>
                                </tr>
                            </table>
                        </td>
                        <td class = "numero">
                                <table>
                                    <tr>
                                        <td style = "{text-align: center; font-size: 10px}">
                                            Timbrado Nro: %s
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style = "{text-align: center; font-size: 10px}">
                                            Validez: %s
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style = "{text-align: center; font-size: 12px}">
                                            RUC: %s
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style = "{text-align: center; font-weight: bold; font-size: 17px}">
                                            NOTA DE CREDITO
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style = "{text-align: center; font-size: 14px}">
                                            NRO.: <span style = '{color: #E60000;}'>%s</span>
                                        </td>
                                    </tr>
                                </table>
                        </td>
                    </tr>
                </table>
                <table style = "{margin-top: 5px;}">
                    <tr>
                        <td class = "datos">
                            <table>
                                <tr>
                                    <td class  = "fecha"> <span class = "textbold">Fecha de emision: </span> %s </td>
                                    <td class  = "condicion"><span class = "textbold">Condicion de Venta: Contado(%s) Credito (%s)</span></td>
                                </tr>
                                <tr>
                                    <td class  = "fecha"> <span class = "textbold">Nombre o Razon Social: </span> %s </td>
                                    <td class  = "condicion"> <span class = "textbold">RUC/C.I.Nro.: </span> %s</td>
                                </tr>
                                <tr>
                                    <td class  = "fecha"> <span class = "textbold">Direccion: </span>%s</td>
                                    <td class  = "condicion"> <span class = "textbold">Telefono: </span> %s</td>
                                </tr>
                                <tr>
                                    <td class  = "fecha"> <span class = "textbold">Factura Venta Número: </span>%s</td>
                                    <td class  = "condicion">&nbsp;</td>
                                </tr>
                            </table>

                        </td>
                    </tr>
                 </table>

                <table class = "detalle">
                    <tr class = 'header-detalle'>
                        <td class = "codigo">Art./Codigo </td>
                        <td class = "cantidad">Cantidad </td>
                        <td class = "descripcion">Descripcion </td>
                        <td class = "precio">Precio Unit. </td>
                        <td class = "exentas">Exentas </td>
                        <td class = "porcc">Gravada 5 </td>
                        <td class = "porcd">Gravada 10</td>
                    </tr>
                    %s
                    <tr>
                        <td colspan = "4" class = "sub-totales">SUBTOTALES</td>
                        %s
                    </tr>
                </table>
            </body>
        </html>

        """ % (self.padre.main('label1').get_text(),
             self.padre.main('label4').get_text(),
             'Avda Principal Caaguazu', '0522-42001',
             'Caaguazu - Paraguay', 'Centro',
             self.frm('entry7').get_text(),
             self.padre.tim_nc_validez,
             self.padre.main('label3').get_text(),
             self.frm('entry1').get_text(), self.frm('entry2').get_text(),
             contado, credito, self.frm('entry5').get_text(),
             self.frm('entry6').get_text(), '', '',
             self.frm('entry13').get_text(), self.detalle_html(), self.total_html())
        self.pdf(html)