Imports System.Data.SqlClient
Imports BD.ABD
Imports System.Windows.Forms

Public Class Funcion
    Dim ser As New BD.ABD
    Dim sql As String
    Dim cmd As SqlCommand
    Dim ds As DataSet
    Dim dr As SqlDataReader
    Dim da As SqlDataAdapter
    Dim cnn As New SqlConnection
    Dim a, b, c As String

    Dim strFecha As String
    Dim formato As New System.Globalization.CultureInfo("es-PY", True)
    Dim fecha, bb As System.DateTime

    'Para crear los colores
    Dim temp, cual, A1, A2, A3 As Integer
    Dim cargando As String
    Dim TextoCuenta1, TextoCuenta2 As String
    'Dim dt As New DataTable("dtResultado")
    Dim dt As DataTable

    ''
    ''
    '2005-04-14 Gerke Es un grabar general que tiene multiproposito para guardar cualquier String SQL
    Public Function Insertar(ByVal String_Global As String) As Boolean
        cnn = New SqlConnection
        cnn = ser.Abrir()
        Dim cmd As SqlCommand = cnn.CreateCommand()
        Dim myTrans As SqlTransaction

        '##################################################################
        'para la fecha del sistema
        b = System.DateTime.Parse(Now, formato)
        strFecha = b

        myTrans = cnn.BeginTransaction(IsolationLevel.ReadCommitted, "InsertarGlobal")
        cmd.Connection = cnn
        cmd.Transaction = myTrans
        Try
            sql = ""
            sql = String_Global
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
            myTrans.Commit()
            '#######
            '# OK  #
            '#######
            Return True
        Catch e As Exception
            MsgBox(e.ToString)
            Try
                myTrans.Rollback("InsertarGlobal")
            Catch ex As SqlException
                If Not myTrans.Connection Is Nothing Then
                    Return False
                End If
            End Try
            Return False
        Finally
            ser.Cerrar(cnn)
        End Try
    End Function

    Public Function MMddyyyy(ByVal fecha_como_string As String) As String
        Dim tempo As String
        tempo = Format(CDate(fecha_como_string), "MM")
        tempo = tempo & "/" & Format(CDate(fecha_como_string), "dd")
        tempo = tempo & "/" & Format(CDate(fecha_como_string), "yyyy")
        Return tempo
    End Function

    Public Function ddMMyyyy(ByVal fecha_como_string As String) As String
        Dim tempo As String
        tempo = Format(CDate(fecha_como_string), "dd")
        tempo = tempo & "/" & Format(CDate(fecha_como_string), "MM")
        tempo = tempo & "/" & Format(CDate(fecha_como_string), "yyyy")
        Return tempo
    End Function

    Public Function fechahora() As String
        'Dim fecha_hoy, temp, hora As String
        'fecha_hoy = Now()
        'hora = TimeOfDay()
        'hora = Cadenas.Truncar(hora, 8)
        'temp = ddMMyyyy(fecha_hoy) + " " + hora
        'Return temp
        b = Now.Hour & ":" & Now.Minute & ":" & Now.Second
        a = Now.Day & "/" & Now.Month & "/" & Now.Year
        c = a & " " & b
        Return c
    End Function

    Public Function Maximo(ByVal nombre_campo As String, ByVal nombre_tabla As String) As Long
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MAX(" & nombre_campo & ") AS MAXIMO FROM " & nombre_tabla & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                Do While dr.Read()
                    Return dr("MAXIMO")
                Loop
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally

        End Try

        Return 0
    End Function
    '########################################################################
    'es para hallar el último asiento de la empresa que se desee
    'Creador = Gerke
    '02-12-2004 13:54
    Public Function UltimoAsiento(ByVal nombre_campo_a_buscar_maximo As String, ByVal nombre_tabla As String, ByVal codigo_empresa As String, Optional ByVal nombre_campo_empresa As String = "CODEMPRESA") As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MAX(" & nombre_campo_a_buscar_maximo & ") AS maximo FROM " & nombre_tabla & " WHERE  " & nombre_campo_empresa & " = " & codigo_empresa & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("maximo")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    'Para saber si una fecha esta dentro del periodo fiscal o no lo esta
    'by Gerke
    '2005-03-14  12:00:00
    Public Function FechaEnPeriodo(ByVal Fecha_A_Analizar As String, ByVal Codgio_Empresa As Long) As Boolean
        Dim Inicio, Fin, temp As DateTime
        Inicio = Periodo_Fecha_Inicio(Codgio_Empresa)
        Fin = Periodo_Fecha_Fin(Codgio_Empresa)
        temp = CDate(Fecha_A_Analizar)
        If temp >= Inicio And temp <= Fin Then
            Return True
        Else
            Return False
        End If
    End Function
    Public Function MaximoMas1(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal numcnn As SqlConnection) As Long
        Dim valor As Long = 1
        ser = New BD.ABD
        cnn = ser.Abrir

        sql = ""
        sql = "SELECT MAX(" & nombre_campo & ") AS maximo FROM " & nombre_tabla & ""

        Try
            cmd = New SqlCommand(sql, numcnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                valor = dr("maximo") + 1
                Return valor
            Catch
                'para evitar la aparición de errores en el caso de que haya registros
                Return valor
                dr.Close()
                Exit Try
            Finally
                dr.Close()
                'numser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    '############################################################################
    'by Gerke  2005-03-15 09:04:00
    'Para devolver la palabra de donde se ha generado un asiento  Utilidad que le gusta a los Contadores para saber donde tienen
    'que ir para revertir su asiento
    Public Function AsientoDeDonde(ByVal Codigo_De_Empresa As Long, ByVal Codigo_De_Asiento As Long) As String
        Dim Temp As String
        ser = New BD.ABD
        cnn = ser.Abrir
        Try
            '########################################################################
            'PARA CONTROLAR LA COMPRA
            sql = ""
            sql = "select isnull(COM.CODconCOMPRA, 0) AS Resultado from concompras com where  com.codempresa = " & Codigo_De_Empresa & " AND com.CODASIENTO = " & Codigo_De_Asiento & ""
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()           'Compra
                Temp = dr("Resultado")
                If Temp <> "" Or Temp <> 0 Then
                    Return " Compras"
                End If
            Catch
                dr.Close()
            Finally
            End Try

            '########################################################################
            'PARA CONTROLAR LA VENTA
            sql = ""
            sql = "select isnull(CON.CODCONVENTA, 0) AS Resultado from CONVENTAS CON where  CON.CODEMPRESA = " & Codigo_De_Empresa & " AND CON.CODASIENTO = " & Codigo_De_Asiento & ""
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()           'Compra
                Temp = dr("Resultado")
                If Temp <> "" Or Temp <> 0 Then
                    Return " Ventas"
                End If
            Catch
                dr.Close()
            Finally
            End Try
        Catch
            Return " "
        Finally
            ser.Cerrar(cnn)
        End Try
    End Function
    Public Function usuario(ByVal nombre_usuario As String, ByVal password As String, ByVal codigo_empresa As Long) As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT CODUSUARIO AS codigo, CODEMPRESA AS empresa, rtrim(DESUSUARIO) AS usuario, rtrim(PASSUSUARIO) as password, NIVELCUENTA as nivel, codsucursalpertenece FROM USUARIO WHERE DESUSUARIO = '" & nombre_usuario & "' AND PASSUSUARIO = '" & password & "' AND CODEMPRESA = '" & codigo_empresa & "'"
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    '#############################################################################
    'es un validar tabla sin empresa
    Public Function Validar_Tabla_Sin_Empresa(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String) As Long
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MAX(" & nombre_campo & ") AS maximo FROM " & nombre_tabla & " where " & campo_buscado & " = '" & variable_ingresada & "'"
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("maximo")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    '#############################################################################
    'Devolver la Fecha del Periodo Contable Inicio
    Public Function Periodo_Fecha_Inicio(ByVal Codigo_de_Empresa As Long) As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT INICIO AS valor FROM CONPARAMETRO WHERE CODEMPRESA = " & Codigo_de_Empresa & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("valor")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function

    '#############################################################################
    'Devolver la Fecha del Periodo Contable Fin
    Public Function Periodo_Fecha_Fin(ByVal Codigo_de_Empresa As Long) As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT Fin AS valor FROM CONPARAMETRO WHERE CODEMPRESA = " & Codigo_de_Empresa & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("valor")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    '#############################################################################
    'Devuelve la Cantidad de registros en la Base de Datos de Cierta Tabla
    Public Function Cantidad_De_Registros_Sin_Empresa(ByVal Campo_a_Buscar_Cantidad As String) As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT COUNT(" & Campo_a_Buscar_Cantidad & ") as CANTIDAD FROM SISTEMAS"
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("CANTIDAD")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    Public Function ColorRed(ByVal objeto As String) As Integer
        Try
            A1 = 0
            A2 = 0
            A3 = 0
            cual = 1
            cargando = ""
            For temp = 0 To Len(objeto) - 1
                If objeto.Substring(temp, 1) = "," Then
                    Select Case cual
                        Case 2
                            A2 = cargando
                            cargando = ""
                            cual = 3
                            temp = temp + 1
                        Case 1
                            A1 = cargando
                            cargando = ""
                            cual = 2
                            temp = temp + 1
                    End Select
                End If
                cargando = cargando & objeto.Substring(temp, 1)
                If temp = Len(objeto) - 1 Then
                    A3 = cargando
                    cargando = ""
                    cual = 0
                    temp = temp + 1
                End If
            Next
        Catch
        Finally

        End Try
        Return A1
    End Function
    Public Function ColorGreen(ByVal objeto As String) As Integer
        Try
            A1 = 0
            A2 = 0
            A3 = 0
            cual = 1
            cargando = ""
            For temp = 0 To Len(objeto) - 1
                If objeto.Substring(temp, 1) = "," Then
                    Select Case cual
                        Case 2
                            A2 = cargando
                            cargando = ""
                            cual = 3
                            temp = temp + 1
                        Case 1
                            A1 = cargando
                            cargando = ""
                            cual = 2
                            temp = temp + 1
                    End Select
                End If
                cargando = cargando & objeto.Substring(temp, 1)
                If temp = Len(objeto) - 1 Then
                    A3 = cargando
                    cargando = ""
                    cual = 0
                    temp = temp + 1
                End If
            Next
        Catch
        Finally
        End Try
        Return A2
    End Function
    Public Function ColorBlue(ByVal objeto As String) As Integer
        Try
            A1 = 0
            A2 = 0
            A3 = 0
            cual = 1
            cargando = ""
            For temp = 0 To Len(objeto) - 1
                If objeto.Substring(temp, 1) = "," Then
                    Select Case cual
                        Case 2
                            A2 = cargando
                            cargando = ""
                            cual = 3
                            temp = temp + 1
                        Case 1
                            A1 = cargando
                            cargando = ""
                            cual = 2
                            temp = temp + 1
                    End Select
                End If
                cargando = cargando & objeto.Substring(temp, 1)
                If temp = Len(objeto) - 1 Then
                    A3 = cargando
                    cargando = ""
                    cual = 0
                    temp = temp + 1
                End If
            Next
        Catch
        Finally
        End Try
        Return A3
    End Function
    Public Function BuscarMovimiento(ByVal codigo_empresa As Long, ByVal orden As Integer, Optional ByVal nombre_campo_Codigo As String = "", Optional ByVal nombre_campo_NumCodigo As String = "", Optional ByVal nombre_campo_Descripcion As String = "", Optional ByVal nombre_campo_Order As String = "", Optional ByVal nombre_tabla As String = "", Optional ByVal nombre_campo_empresa As String = "") As SqlDataReader
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        Select Case orden
            Case 1
                sql = "SELECT CODPROVEEDOR AS Codigo, RTRIM(APELLIDO)+', '+ RTRIM(NOMBRE) AS Descripcion " & _
                "FROM PROVEEDOR WHERE EXISTS(SELECT * FROM CONCOMPRAS WHERE CONCOMPRAS.CODPROVEEDOR = PROVEEDOR.CODPROVEEDOR AND CONCOMPRAS.CODEMPRESA = '" & codigo_empresa & "') AND CODEMPRESA = '" & codigo_empresa & "' GROUP BY CODPROVEEDOR, APELLIDO, NOMBRE ORDER BY APELLIDO, NOMBRE"
            Case 2
                sql = "SELECT " & nombre_campo_Codigo & " AS Codigo, " & nombre_campo_NumCodigo & " AS NumCodigo," & nombre_campo_Descripcion & " as Descripcion, " & nombre_campo_Order & " AS Orden  FROM " & nombre_tabla & " WHERE " & nombre_campo_empresa & "= '" & codigo_empresa & "' ORDER BY " & nombre_campo_NumCodigo & ""
            Case 3
                sql = "SELECT FECCOMPROBANTE  FROM CONCOMPRAS WHERE codempresa = '" & codigo_empresa & "' GROUP BY FECCOMPROBANTE ORDER BY FECCOMPROBANTE"
        End Select
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    '####################################################
    'Es el buscar sin empresa, se utiliza en Modelo
    Public Function ConBuscar(ByVal nombre_campo_codigo As String, ByVal nombre_campo_descripcion As String, ByVal nombre_tabla As String, Optional ByVal Orden As Integer = 0) As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        Select Case Orden
            Case 0
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & "   ORDER BY  " & nombre_campo_codigo & ""
            Case 1
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " ORDER BY " & nombre_campo_descripcion & ""
        End Select
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function Buscar(ByVal nombre_campo_codigo As String, ByVal nombre_campo_numcodigo As String, ByVal nombre_campo_descripcion As String, ByVal nombre_tabla As String, ByVal cod_empresa As String, Optional ByVal Orden As Integer = 0) As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        Select Case Orden
            Case 0
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, " & nombre_campo_numcodigo & " as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " WHERE CODEMPRESA = " & cod_empresa & " ORDER BY " & nombre_campo_codigo & ""
            Case 1
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, " & nombre_campo_numcodigo & " as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " WHERE CODEMPRESA = " & cod_empresa & " ORDER BY " & nombre_campo_descripcion & ""
            Case 2
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, " & nombre_campo_numcodigo & " as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " WHERE CODEMPRESA = " & cod_empresa & " ORDER BY " & nombre_campo_numcodigo & ""
        End Select
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function BuscarCuenta(ByVal codigo_empresa As String, ByVal orden As Integer, Optional ByVal nombre_campo_CodCuenta As String = "CODPLANCUENTA", Optional ByVal nombre_campo_NumCuenta As String = "NUMPLANCUENTA", Optional ByVal nombre_campo_DesCuenta As String = "DESPLANCUENTA", Optional ByVal nombre_campo_SubCuenta As String = "SUBCUENTA", Optional ByVal nombre_tabla As String = "PLANCUENTAS", Optional ByVal nombre_campo_empresa As String = "CODEMPRESA") As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        Select Case orden
            Case 1
                sql = "SELECT " & nombre_campo_CodCuenta & " as CodCuenta, " & nombre_campo_NumCuenta & " AS NumCuenta," & nombre_campo_DesCuenta & " as DesCuenta, " & nombre_campo_SubCuenta & " AS SubCuenta  FROM " & nombre_tabla & " WHERE " & nombre_campo_empresa & "= " & codigo_empresa & " ORDER BY " & nombre_campo_DesCuenta & ""
            Case 2
                sql = "SELECT " & nombre_campo_CodCuenta & " as CodCuenta, " & nombre_campo_NumCuenta & " AS NumCuenta," & nombre_campo_DesCuenta & " as DesCuenta, " & nombre_campo_SubCuenta & " AS SubCuenta  FROM " & nombre_tabla & " WHERE " & nombre_campo_empresa & "= " & codigo_empresa & " ORDER BY " & nombre_campo_NumCuenta & ""
            Case 3
                sql = "SELECT " & nombre_campo_CodCuenta & " as CodCuenta, " & nombre_campo_NumCuenta & " AS NumCuenta," & nombre_campo_DesCuenta & " as DesCuenta, " & nombre_campo_SubCuenta & " AS SubCuenta  FROM " & nombre_tabla & " WHERE " & nombre_campo_empresa & "= " & codigo_empresa & " ORDER BY " & nombre_campo_SubCuenta & ""
        End Select
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function Empresa() As DataSet
        ser = New BD.ABD

        cnn = New SqlConnection

        Try
            cnn = ser.Abrir()

            sql = ""
            sql = "SELECT CODEMPRESA AS CODIGO, RTRIM(NOMFANTASIA) AS NOMBRE FROM EMPRESA ORDER BY NOMFANTASIA"

            da = New SqlDataAdapter(sql, cnn)
            ds = New DataSet

            da.Fill(ds)
        Catch ex As Exception
            MsgBox("No se pudo realizar la Conexión." & vbCrLf & "Verifique el Servidor.", MsgBoxStyle.Critical + MsgBoxStyle.OKOnly + MsgBoxStyle.SystemModal, _
            "Acceso")
        Finally
            ser.Cerrar(cnn)
        End Try

        Return ds
    End Function
    Public Function Sucursal(ByVal empresa As Long) As DataSet
        cnn = New SqlConnection
        cnn = ser.Abrir()
        sql = ""
        sql = "select rtrim(numsucursal) + ' ' + rtrim(dessucursal) as Nombre, codsucursal as Codigo from sucursal where codempresa = '" & empresa & "' ORDER BY NUMSUCURSAL"
        da = New SqlDataAdapter(sql, cnn)
        ds = New DataSet
        da.Fill(ds)
        ser.Cerrar(cnn)
        Return ds
    End Function
    Public Function UsuarioSucursal(ByVal empresa As Long, ByVal codSucPertenece As String) As String
        Dim retDescripSuc As String = ""
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "select rtrim(numsucursal) + ' ' + rtrim(dessucursal) as Nombre, codsucursal as Codigo from sucursal where codempresa = '" & empresa & "' AND codsucursal =" & codSucPertenece
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                Do While dr.Read()
                    retDescripSuc = dr("NOMBRE")
                Loop
            Catch
                retDescripSuc = "0"
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Catch loco As Exception
            MsgBox(loco.ToString)
        Finally

        End Try

        Return retDescripSuc
    End Function
    Public Function Predeterminado(ByVal campo_Cod As String, ByVal campo_Num As String, ByVal campo_Des As String, ByVal nombre_tabla As String, ByVal valor_empresa As Long, Optional ByVal Nombre_Campo_Prioridad As String = "PRIORIDAD") As DataSet
        cnn = New SqlConnection
        cnn = ser.Abrir()
        da = New SqlDataAdapter
        sql = ""
        sql = "SELECT " & _
        " " & campo_Cod & " ," & _
        " rtrim(" & campo_Num & ") as " & campo_Num & " ," & _
        " rtrim(" & campo_Des & ") as  " & campo_Des & " " & _
        " FROM " & nombre_tabla & " " & _
        " WHERE CODEMPRESA = " & valor_empresa & " " & _
        " AND " & Nombre_Campo_Prioridad & " = 1"
        da = New SqlDataAdapter(sql, cnn)
        ds = New DataSet
        da.Fill(ds)
        cnn.Close()
        Return ds
    End Function
    Public Function ExistePrioridad(ByVal nombre_tabla As String, ByVal nombre_campo As String, ByVal codigo_empresa As Integer, Optional ByVal nombre_campo_empresa As String = "codempresa", Optional ByVal campo_prioridad As String = "prioridad") As Boolean
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "select case " & _
        "when (select count(*) from " & nombre_tabla & " where " & nombre_campo_empresa & " = " & codigo_empresa & " and " & campo_prioridad & " = 1) <= 0  then 'False' " & _
        "when (select count(*) from " & nombre_tabla & " where " & nombre_campo_empresa & " = " & codigo_empresa & " and " & campo_prioridad & " = 1) > 0  then 'True' " & _
        "end as Existe "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                If dr("Existe") = "True" Then
                    Return True
                Else
                    Return False
                End If
            Catch
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    Public Function EstablerPrioridad(ByVal nombre_tabla As String, ByVal codigo_usuario As Integer, _
    ByVal codigo_empresa As String, Optional ByVal nombre_campo_usuario As String = "CODUSUARIO", _
    Optional ByVal nombre_campo_fecha_de_grabacion As String = "FECGRA", _
    Optional ByVal nombre_campo_empresa As String = "codempresa", _
    Optional ByVal nombre_campo_prioridad As String = "prioridad", _
    Optional ByVal Valor_de_prioridad As Integer = 0) As Boolean
        ser = New BD.ABD
        cnn = ser.Abrir

        b = System.DateTime.Parse(Now, formato)
        strFecha = b
        Try
            sql = ""
            sql = "UPDATE " & nombre_tabla & " SET " & nombre_campo_usuario & " = " & codigo_usuario & ", " & nombre_campo_fecha_de_grabacion & " = '" & strFecha & "', " & nombre_campo_prioridad & " = " & Valor_de_prioridad & " WHERE " & nombre_campo_empresa & " = " & codigo_empresa & " "
            cmd = New SqlCommand(sql, cnn)              'crea nuevo comando SQL con sql y la conexxion1
            cmd.ExecuteNonQuery()                       'ejecuta el comando
        Catch
            Return False
            Exit Function
        Finally
            cnn.Close()
            ser.Cerrar(cnn)
        End Try
        Return True
    End Function
    Public Function DsRecorrerTabla(ByVal nombre_campo_devuelto As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_buscada As String, ByVal codigo_empresa As Long) As DataSet
        cnn = New SqlConnection
        cnn = ser.Abrir()
        da = New SqlDataAdapter
        sql = ""
        sql = "SELECT rtrim(" & nombre_campo_devuelto & ") AS NUMCODIGO FROM " & nombre_tabla & " where " & campo_buscado & " = '" & variable_buscada & "' and codempresa = '" & codigo_empresa & "' "
        da = New SqlDataAdapter(sql, cnn)
        ds = New DataSet
        da.Fill(ds)
        ser.Cerrar(cnn)
        ser.Cerrar(cnn)
        Return ds
    End Function
    Public Function ExisteResgistroParaMiEmpresa(ByVal nombre_tabla As String, ByVal codigo_empresa As Long, Optional ByVal campo_de_empresa As String = "CODEMPRESA") As Boolean
        Dim temp As Long = -1
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MAX(" & campo_de_empresa & ") AS maximo FROM " & nombre_tabla & " where " & campo_de_empresa & " = " & codigo_empresa & " "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                temp = dr("maximo")
                Return True
            Catch
                Return False
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Finally

        End Try
    End Function
    Public Function Validar_Tabla(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String, ByVal codigo_empresa As String) As Long
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MAX(" & nombre_campo & ") AS maximo FROM " & nombre_tabla & " where " & campo_buscado & " = '" & variable_ingresada & "' and codempresa = " & codigo_empresa & " "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("maximo")
            Catch ex As Exception
                ' MsgBox(ex.ToString)
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    Public Function Moneda_Predeterminada(ByVal codigo_empresa As Long) As DataSet
        cnn = New SqlConnection
        cnn = ser.Abrir()
        sql = ""
        sql = "SELECT  CODMONEDA, CODUSUARIO, CODEMPRESA, rtrim(NUMMONEDA) as NUMMONEDA, rtrim(DESMONEDA) as DESMONEDA, FECGRA, PRIORIDAD, rtrim(SIMBOLO) as SIMBOLO FROM MONEDA WHERE codempresa = " & codigo_empresa & " AND prioridad = 1"
        da = New SqlDataAdapter(sql, cnn)
        ds = New DataSet
        da.Fill(ds)
        ser.Cerrar(cnn)
        ser.Cerrar(cnn)
        Return ds
    End Function
    Public Function Moneda_Cotizacion(ByVal codigo_empresa As Long, ByVal codigo_moneda As Long, Optional ByVal fecha As String = "no hay") As DataSet
        cnn = New SqlConnection
        cnn = ser.Abrir()

        If fecha = "no hay" Then
            b = System.DateTime.Parse(Now, formato)
            strFecha = b
            fecha = strFecha
        End If
        sql = ""
        sql = "DECLARE @mone numeric(9), @mone2 numeric(9), @empre numeric(9), @fecha char(30) " & _
        "set @empre = " & codigo_empresa & " " & _
        "set @mone =  " & codigo_moneda & " /*(select codmoneda from moneda WHERE CODEMPRESA = @empre AND PRIORIDAD = 1)*/ " & _
        "set @mone2 = (SELECT moneda2 FROM CONFIGURACION WHERE CODEMPRESA = @empre) " & _
        "set @fecha = '" & fecha & "'" & _
        "select C.Moneda1, (SELECT rtrim(M.DESMONEDA) FROM MONEDA M WHERE C.Moneda1 = M.CODMONEDA) AS DesMoneda1,  " & _
        "(SELECT rtrim(M.NUMMONEDA) FROM MONEDA M WHERE C.Moneda1 = M.CODMONEDA) AS NumMoneda1, " & _
        "(SELECT rtrim(M.SIMBOLO) FROM MONEDA M WHERE C.Moneda1 = M.CODMONEDA) AS SimMoneda1, " & _
        "C.Moneda2, (SELECT rtrim(M.DESMONEDA) FROM MONEDA M WHERE C.Moneda2 = M.CODMONEDA) as Desmoneda2, " & _
        "(SELECT rtrim(M.NUMMONEDA) FROM MONEDA M WHERE C.Moneda2 = M.CODMONEDA) AS NumMoneda2, " & _
        "(SELECT rtrim(M.SIMBOLO) FROM MONEDA M WHERE C.Moneda2 = M.CODMONEDA) AS SimMoneda2, " & _
        "ISNULL((select factorventa from cotizacion where fechamovimiento = (select max(fechamovimiento) as Maximo from cotizacion where codempresa = @empre and codmoneda = @mone " & _
        "and fechamovimiento <= @fecha)AND CODEMPRESA = @empre and codmoneda = @mone), 0) as Cotizacion1Venta, " & _
        "ISNULL((select factorCobro from cotizacion where fechamovimiento = (select max(fechamovimiento) as Maximo from cotizacion where codempresa = @empre and codmoneda = @mone " & _
        "and fechamovimiento <= @fecha)AND CODEMPRESA = @empre and codmoneda = @mone), 0) as Cotizacion1Compra, " & _
        "ISNULL((select factorventa from cotizacion where fechamovimiento = (select max(fechamovimiento) as Maximo from cotizacion where codempresa = @empre and codmoneda = @mone2 " & _
        "and fechamovimiento <= @fecha)AND CODEMPRESA = @empre and codmoneda = @mone2), 0) as Cotizacion2Venta, " & _
        "ISNULL((select factorCobro from cotizacion where fechamovimiento = (select max(fechamovimiento) as Maximo from cotizacion where codempresa = @empre and codmoneda = @mone2 " & _
        "and fechamovimiento <= @fecha) AND CODEMPRESA = @empre and codmoneda = @mone2), 0) as Cotizacion2Compra " & _
        "FROM Configuracion C " & _
        "WHERE C.CODEMPRESA = @empre "
        da = New SqlDataAdapter(sql, cnn)
        ds = New DataSet
        da.Fill(ds)
        ser.Cerrar(cnn)
        ser.Cerrar(cnn)
        Return ds
    End Function

    Public Function Descripcion_Tabla(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String, ByVal codigo_empresa As Long) As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT RTRIM(" & nombre_campo & ") AS DESCRIPCION FROM " & nombre_tabla & " WHERE " & campo_buscado & " = '" & variable_ingresada & "' AND CODEMPRESA = " & codigo_empresa & " "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                Do While dr.Read()
                    Return dr("DESCRIPCION")
                Loop
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Catch loco As Exception
            MsgBox(loco.ToString)
        Finally

        End Try

        Return 0
    End Function

    Public Function Descripcion_TablaOtro(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String, ByVal codigo_empresa As Long) As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT RTRIM(" & nombre_campo & ") AS DESCRIPCION FROM " & nombre_tabla & " WHERE " & campo_buscado & " = '" & variable_ingresada & "'  "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                Do While dr.Read()
                    Return dr("DESCRIPCION")
                Loop
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Catch loco As Exception
            MsgBox(loco.ToString)
        Finally

        End Try

        Return 0
    End Function


    Public Function Buscar_Tabla(ByVal nombre_campo_codigo As String, ByVal nombre_campo_numcodigo As String, ByVal nombre_campo_descripcion As String, ByVal nombre_tabla As String, ByVal sentencia_where As String, ByVal codigo_empresa As Long, Optional ByVal Orden As Integer = 0) As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        Select Case Orden
            Case 0
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, rtrim(" & nombre_campo_numcodigo & ") as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " where " & sentencia_where & " " & codigo_empresa & " ORDER BY " & nombre_campo_numcodigo & " "
            Case 1
                sql = "SELECT " & nombre_campo_codigo & " as Codigo, rtrim(" & nombre_campo_numcodigo & ") as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " where " & sentencia_where & " " & codigo_empresa & " ORDER BY " & nombre_campo_descripcion & " "
        End Select
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function


    Public Function SistemasExiste(ByVal Nombre_Del_Sistema_A_Buscar As String, ByVal Codigo_De_Empresa As Long) As Boolean
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = "SELECT CODSISTEMAS AS CODIGO FROM SISTEMAS WHERE Dessistemas Like('" & Nombre_Del_Sistema_A_Buscar & "') AND CODEMPRESA = " & Codigo_De_Empresa & " "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                If dr("Codigo") > 0 Then
                    Return True
                Else
                    Return False
                End If
            Catch
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function

    Public Function InsertarSistemas(ByVal Codigo_De_Usuario As Long, ByVal Codigo_De_Empresa As Long, ByVal Num_Sistemas As String, ByVal Descripcion_De_Sistemas As String) As Boolean
        Dim cmd As SqlCommand
        Dim myTrans As SqlTransaction
        Dim Codigo_De_Sistemas As Long

        ser = New BD.ABD
        cnn = New SqlConnection
        cnn = ser.Abrir()

        Codigo_De_Sistemas = MaximoMas1("CODSISTEMAS", "SISTEMAS", cnn)

        If Codigo_De_Sistemas = 0 Then
            Codigo_De_Sistemas = 1
        End If

        cmd = New SqlCommand
        cmd.Connection = cnn

        myTrans = cnn.BeginTransaction(IsolationLevel.ReadCommitted, "Sistemas")

        cmd.Transaction = myTrans
        Try
            sql = ""
            sql = "INSERT INTO SISTEMAS(CODSISTEMAS, CODUSUARIO, CODEMPRESA, NUMSISTEMAS, DESSISTEMAS, FECGRA) " & _
            " VALUES (" & Codigo_De_Sistemas & ", " & Codigo_De_Usuario & ", " & Codigo_De_Empresa & ", '" & Num_Sistemas & "',  '" & Descripcion_De_Sistemas & "', GETDATE())"

            cmd.CommandText = sql
            cmd.ExecuteNonQuery()

            myTrans.Commit()
            '#######
            '# OK  #
            '#######
            Return True
        Catch e As Exception
            Try
                myTrans.Rollback("Sistemas")
            Catch ex As SqlException
                If Not myTrans.Connection Is Nothing Then
                    Return False
                End If

                MsgBox(ex.ToString)
            End Try

            MsgBox(e.ToString)

            Return False
        Finally
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function

    Public Function ModulosExiste(ByVal Codigo_De_Modulo As Long, ByVal Codigo_De_Sistemas As Long, ByVal Codigo_De_Empresa As Long) As Boolean
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = "SELECT CODMODULO AS CODIGO FROM MODULOS WHERE CODMODULO = " & Codigo_De_Modulo & " AND CODSISTEMAS = " & Codigo_De_Sistemas & " AND CODEMPRESA = " & Codigo_De_Empresa & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                If dr("Codigo") > 0 Then
                    Return True
                Else
                    Return False
                End If
            Catch
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    Public Function InsertarModulo(ByVal Codigo_De_Modulo As Long, ByVal Codigo_De_Sistemas As Long, ByVal Descripcion_De_Modulo As String, ByVal Codigo_De_Usuario As Long, ByVal Codigo_De_Empresa As Long) As Boolean
        ser = New BD.ABD
        cnn = New SqlConnection
        cnn = ser.Abrir()

        Dim cmd As SqlCommand = cnn.CreateCommand()
        Dim myTrans As SqlTransaction

        '##################################################################
        'para la fecha del sistema
        'b = System.DateTime.Parse(Now, formato)
        'strFecha = b

        'Dim CodModulo As Long
        'CodModulo = sentFuncion.MaximoMas1("CODMODULO", "MODULOS", cnn)

        myTrans = cnn.BeginTransaction(IsolationLevel.ReadCommitted, "InsertarModulos")
        cmd.Connection = cnn
        cmd.Transaction = myTrans
        Try
            sql = ""
            sql = "INSERT INTO MODULOS(CODMODULO, CODSISTEMAS, CODEMPRESA, DESMODULO, USUARIO, FECGRA) " & _
            " VALUES (" & Codigo_De_Modulo & ", " & Codigo_De_Sistemas & ", " & Codigo_De_Empresa & ", '" & Descripcion_De_Modulo & "', " & Codigo_De_Usuario & ", GETDATE())"
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
            myTrans.Commit()
            '#######
            '# OK  #
            '#######
            Return True
        Catch e As Exception
            Try
                myTrans.Rollback("InsertarModulos")
            Catch ex As SqlException
                If Not myTrans.Connection Is Nothing Then
                    Return False
                End If
            End Try
            Return False
        Finally
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function
    '###################################################################### YA NO SE UTILIZA
    'Para guardar que usuario en que modulo que permisos tiene
    Public Function ModificarModulos(ByVal Codigo_De_Modulo As Long, ByVal Codigo_De_Sistemas As Long, ByVal Codigo_De_Usuario As Long, ByVal ModSelect As Integer, ByVal ModInsert As Integer, ByVal ModUpdate As Integer, ByVal ModDelete As Integer, ByVal ModPrint As Integer, ByVal ModVencidas As Integer, ByVal ModLimiteCredito As Integer, ByVal ModDesc As Integer, ByVal ModAnular As Integer, ByVal Codigo_De_Empresa As Long) As Boolean
        cnn = New SqlConnection
        cnn = ser.Abrir()
        Dim cmd As SqlCommand = cnn.CreateCommand()
        Dim myTrans As SqlTransaction

        '##################################################################
        'para la fecha del sistema
        b = System.DateTime.Parse(Now, formato)
        strFecha = b

        'If tempUsuario = 0 Then
        'tempUsuario = 1
        'End If

        myTrans = cnn.BeginTransaction(IsolationLevel.ReadCommitted, "UpdateModulo")
        cmd.Connection = cnn
        cmd.Transaction = myTrans
        Try
            sql = "UPDATE MODULOS SET [SELECT] = " & ModSelect & ", [INSERT] = " & ModInsert & ", [UPDATE] = " & ModUpdate & ", [DELETE] = " & ModDelete & ", [PRINT] = " & ModPrint & ", VENCIDAS = " & ModVencidas & ", LIMITECREDITO = " & ModLimiteCredito & ", [DESC] = " & ModDesc & ", ANULAR = " & ModAnular & ", FECGRA = '" & strFecha & "' WHERE CODMODULO = " & Codigo_De_Modulo & " AND CODSISTEMAS = " & Codigo_De_Sistemas & " AND USUARIO = " & Codigo_De_Usuario & ""
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()

            myTrans.Commit()
            '#######
            '# OK  #
            '#######
            Return True
        Catch e As Exception
            Try
                myTrans.Rollback("UpdateModulo")
            Catch ex As SqlException
                If Not myTrans.Connection Is Nothing Then
                    Return False
                End If
            End Try
            Return False
        Finally
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function
    ''
    ''Cesar
    'Cesar 2005-05-26 08:45 Para validar tablas cuya clave es del tipo string
    'Tiene la misma funcionalidad de Validar_Tabla y devuelve un valor boolean en caso de 
    'que exista una clave string igual a la variable_ingresada
    Public Function Validar_Tabla_cod_string(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String, ByVal codigo_empresa As String) As Boolean
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "select case " & _
        "when (select count(*) from " & nombre_tabla & " where " & campo_buscado & " = '" & variable_ingresada & "' AND codempresa = " & codigo_empresa & " ) <= 0  then 'False' " & _
        "when (select count(*) from " & nombre_tabla & " where " & campo_buscado & " = '" & variable_ingresada & "' AND codempresa = " & codigo_empresa & " ) > 0  then 'True' " & _
        "end as Existe"
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                If dr("Existe") = "True" Then
                    Return True
                Else
                    Return False
                End If
            Catch
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    ''
    ''
    'Cesar, 2005-05-15 09:30 Similiar al Validar tabla, valida si existe la variable ingresada en el campo numcodigo en una tabla
    Public Function Validar_NumCodigo(ByVal nombre_campo_codigo As String, ByVal nombre_tabla As String, ByVal sentencia_where As String, ByVal codigo_empresa As Long) As Boolean
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = "SELECT RTRIM(" & nombre_campo_codigo & ") AS CODIGO  FROM " & nombre_tabla & " WHERE " & sentencia_where & " " & codigo_empresa & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()

            Try
                Do While dr.Read
                    If dr("CODIGO") > 0 Then
                        Return True
                    Else
                        Return False
                    End If
                Loop
            Catch e As Exception
                MsgBox(e.ToString)
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    ''
    ''
    'Cesar, 2005-06-10 12:00 Validacion para codigos!!!!
    Public Function crear_validated_codigo(ByRef BotonGrabar As System.Windows.Forms.Button, ByRef textbox_codigo As System.Windows.Forms.TextBox, ByRef textbox_siguiente As System.Windows.Forms.TextBox, ByVal nombre_campo_codigo As String, ByVal nombre_tabla As String, ByVal nombre_campo_numcodigo As String, ByVal codigo_empresa As String) As String
        ''
        ''
        'Cesar, 2005-06-10 Validacion para codigos!!!!
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If BotonGrabar.Enabled = True And Not textbox_codigo.Text.Trim = "" Then
            If BotonGrabar.Text = "&Grabar" Then
                If sentfuncion.Validar_Tabla(nombre_campo_codigo, nombre_tabla, nombre_campo_numcodigo, textbox_codigo.Text, codigo_empresa) = 0 Then
                    Mensaje = "Código Nuevo!!!"
                    textbox_siguiente.Focus()
                Else
                    Mensaje = "Código Existe..!!!"
                    textbox_codigo.Text = ""
                    textbox_codigo.Focus()
                End If
            End If
        End If
        Return Mensaje
    End Function
    ''
    ''
    'Cesar, 2005-06-10 12:00 Validacion para codigos!!!!
    Public Function validacion_codigo_tabla_dependiente(ByRef BotonGrabar As System.Windows.Forms.Button, ByRef textbox_codigo As System.Windows.Forms.TextBox, ByRef label_descripcion As System.Windows.Forms.Label, ByVal nombre_campo_codigo As String, ByVal nombre_tabla As String, ByVal nombre_campo_descripcion As String, ByVal nombre_campo_numcodigo As String, ByVal codigo_empresa As String) As String
        ''
        ''
        'Cesar, 2005-06-10 Validacion para codigos!!!!
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If BotonGrabar.Enabled = True Then
            If Not textbox_codigo.Text.Trim = "" Then
                textbox_codigo.Tag = sentfuncion.Validar_Tabla(nombre_campo_codigo, nombre_tabla, nombre_campo_numcodigo, textbox_codigo.Text, codigo_empresa)
                If textbox_codigo.Tag = 0 Then
                    Mensaje = "Codigo No Existe!!!"
                    textbox_codigo.Text = ""
                    label_descripcion.Text = ""
                    textbox_codigo.Focus()
                Else
                    label_descripcion.Text = sentfuncion.Descripcion_Tabla(nombre_campo_descripcion, nombre_tabla, nombre_campo_numcodigo, textbox_codigo.Text, codigo_empresa)
                End If
            Else
                label_descripcion.Text = ""
                textbox_codigo.Tag = 0
            End If
        End If
        Return Mensaje
    End Function


    Public Function descripcion_rango(ByRef textbox_rango As System.Windows.Forms.TextBox, ByRef label_descripcion As System.Windows.Forms.Label, ByVal nombre_campo_numcodigo As String, ByVal nombre_tabla As String, ByVal nombre_campo_descripcion As String, ByVal codigo_empresa As String) As String
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If textbox_rango.Text.Trim.Length > 0 Then
            label_descripcion.Text = sentfuncion.Descripcion_Tabla(nombre_campo_descripcion, nombre_tabla, nombre_campo_numcodigo, textbox_rango.Text, codigo_empresa)
            If label_descripcion.Text = "0" Then
                label_descripcion.Text = ""
                Mensaje = "Codigo no existe...Verifique!!!"
            End If
        Else
            label_descripcion.Text = ""
        End If
        Return Mensaje
    End Function

    Public Function validacion_rango_informe(ByRef textbox_rango_desde As System.Windows.Forms.TextBox, ByRef textbox_rango_hasta As System.Windows.Forms.TextBox) As String
        ''
        ''
        'Cesar, 2005-06-14  15:20 Validacion para rango de informes!!!!
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If textbox_rango_desde.Text.Trim.Length <> 0 And textbox_rango_hasta.Text.Trim.Length <> 0 Then
            If (IsNumeric(textbox_rango_desde.Text) And IsNumeric(textbox_rango_hasta.Text)) Then
                If Val(textbox_rango_desde.Text) > Val(textbox_rango_hasta.Text) Then
                    Mensaje = "El Hasta no puede ser menor al desde. Favor Verifique...."
                    textbox_rango_hasta.Text = ""
                    textbox_rango_hasta.Focus()
                End If
            Else
                If textbox_rango_desde.Text > textbox_rango_hasta.Text Then
                    Mensaje = "El Hasta no puede ser menor al desde. Favor Verifique...."
                    textbox_rango_hasta.Text = ""
                    textbox_rango_hasta.Focus()
                End If
            End If
        End If
        Return Mensaje
    End Function
    Public Function calcular_precio(ByVal ultimo_costo_articulo As String, ByVal codigo_de_moneda_del_articulo As Long, ByVal moneda_seleccionada_para_informe As Long, ByVal codigo_empresa As String) As Decimal
        ''
        ''
        'Cesar, 2005-06-14  15:20 Validacion para rango de informes!!!!
        Dim sentfuncion As New Funcion
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = "SELECT (SELECT isnull(FACTORVENTA,0)*" & ultimo_costo_articulo & " FROM COTIZACION WHERE CODMONEDA = " & codigo_de_moneda_del_articulo & " " & _
        "AND CODEMPRESA = " & codigo_empresa & " AND FECHAMOVIMIENTO = " & _
        "(SELECT MAX(FECHAMOVIMIENTO) FROM COTIZACION WHERE CODEMPRESA = " & codigo_empresa & " AND CODMONEDA = " & codigo_de_moneda_del_articulo & " ))" & _
        "/isnull(FACTORVENTA,0) AS PRECIO " & _
        "FROM COTIZACION WHERE CODMONEDA = " & moneda_seleccionada_para_informe & " AND CODEMPRESA = " & codigo_empresa & " " & _
        "AND FECHAMOVIMIENTO = (SELECT MAX(FECHAMOVIMIENTO) FROM " & _
        "COTIZACION WHERE CODEMPRESA = " & codigo_empresa & " AND CODMONEDA = " & moneda_seleccionada_para_informe & ")"


        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Dim PRE As String
                PRE = dr("Precio")
                Return dr("Precio")
            Catch E As Exception
                MsgBox(E.Message, MsgBoxStyle.Exclamation, "ERROR VISUAL")
            Catch SQE As SqlException
                MsgBox(SQE.Message, MsgBoxStyle.Exclamation, "ERROR SQL")
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Catch E As Exception
            MsgBox(E.Message)
        Finally
        End Try
    End Function

    ''fin Cesar'''
    Public Function Conectar()
        cnn = ser.Abrir
        ser.Cerrar(cnn)
    End Function

    Public Function BuscarMovimientoCompra(ByVal Codigo_De_Empresa As Long, ByVal Orden As Integer, Optional ByVal Nombre_Campo_Codigo As String = "", Optional ByVal Nombre_Campo_NumCodigo As String = "", Optional ByVal Nombre_Campo_Descripcion As String = "", Optional ByVal Nombre_Campo_Order As String = "", Optional ByVal Nombre_Tabla As String = "", Optional ByVal Nombre_Campo_Empresa As String = "") As SqlDataReader
        ser = New BD.ABD
        Dim Cone As New SqlConnection
        Cone = ser.Abrir
        sql = ""
        ''
        ''
        '2005-05-11 gerke Para que la ayuda solo muestre valores dentro del periodo fiscal actual
        Dim inicio As String = Periodo_Fecha_Inicio(Codigo_De_Empresa)
        Dim fin As String = Periodo_Fecha_Fin(Codigo_De_Empresa)
        ''
        ''
        Select Case Orden
            Case 1
                sql = "SELECT CODPROVEEDOR AS Codigo, RTRIM(APELLIDO)+', '+ RTRIM(NOMBRE) AS Descripcion " & _
                "FROM PROVEEDOR WHERE EXISTS(SELECT * FROM CONCOMPRAS WHERE CONCOMPRAS.CODPROVEEDOR = PROVEEDOR.CODPROVEEDOR AND CONCOMPRAS.CODEMPRESA = " & Codigo_De_Empresa & " AND CONCOMPRAS.FECCOMPROBANTE BETWEEN '" & inicio & "' AND '" & fin & "') AND CODEMPRESA = " & Codigo_De_Empresa & "  GROUP BY CODPROVEEDOR, APELLIDO, NOMBRE ORDER BY APELLIDO, NOMBRE"
            Case 2
                sql = "SELECT " & Nombre_Campo_Codigo & " AS Codigo, " & Nombre_Campo_NumCodigo & " AS NumCodigo," & Nombre_Campo_Descripcion & " as Descripcion, " & Nombre_Campo_Order & " AS Orden  FROM " & Nombre_Tabla & " WHERE " & Nombre_Campo_Empresa & "= " & Codigo_De_Empresa & " AND LC.FECCOMPROBANTE BETWEEN '" & inicio & "' AND '" & fin & "' ORDER BY " & Nombre_Campo_NumCodigo & ""
            Case 3
                sql = "SELECT FECCOMPROBANTE  FROM CONCOMPRAS WHERE CODEMPRESA = " & Codigo_De_Empresa & " AND CONCOMPRAS.FECCOMPROBANTE BETWEEN '" & inicio & "' AND '" & fin & "' GROUP BY FECCOMPROBANTE ORDER BY FECCOMPROBANTE"
        End Select
        'sql = sql & " 
        Try
            cmd = New SqlCommand(sql, Cone)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function BuscarMovimientoVenta(ByVal Codigo_De_Empresa As Long, ByVal Orden As Integer, Optional ByVal Nombre_Campo_Codigo As String = "", Optional ByVal Nombre_Campo_NumCodigo As String = "", Optional ByVal Nombre_Campo_Descripcion As String = "", Optional ByVal Nombre_Campo_Order As String = "", Optional ByVal Nombre_Tabla As String = "", Optional ByVal Nombre_Campo_Empresa As String = "") As SqlDataReader
        ser = New BD.ABD
        Dim Cone As New SqlConnection
        Cone = ser.Abrir
        sql = ""
        ''
        ''
        '2005-05-11 gerke Para que la ayuda solo muestre valores dentro del periodo fiscal actual
        Dim inicio As String = Periodo_Fecha_Inicio(Codigo_De_Empresa)
        Dim fin As String = Periodo_Fecha_Fin(Codigo_De_Empresa)
        ''
        ''
        Select Case Orden
            Case 1
                sql = "SELECT CODCLIENTE AS Codigo, RTRIM(APELLIDO)+', '+ RTRIM(NOMBRE) AS Descripcion " & _
                "FROM CLIENTES WHERE EXISTS(SELECT * FROM CONVENTAS WHERE CONVENTAS.CODCLIENTE = CLIENTES.CODCLIENTE AND CONVENTAS.CODEMPRESA = " & Codigo_De_Empresa & " AND CONVENTAS.FECCOMPROBANTE BETWEEN '" & inicio & "' AND '" & fin & "') AND CODEMPRESA = " & Codigo_De_Empresa & "  GROUP BY CODCLIENTE, APELLIDO, NOMBRE ORDER BY APELLIDO, NOMBRE"
            Case 2
                sql = "SELECT " & Nombre_Campo_Codigo & " AS Codigo, " & Nombre_Campo_NumCodigo & " AS NumCodigo," & Nombre_Campo_Descripcion & " as Descripcion, " & Nombre_Campo_Order & " AS Orden  FROM " & Nombre_Tabla & " WHERE " & Nombre_Campo_Empresa & " = " & Codigo_De_Empresa & "  AND LC.FECCOMPROBANTE BETWEEN '" & inicio & "' AND '" & fin & "'  ORDER BY " & Nombre_Campo_NumCodigo & ""
            Case 3
                sql = "SELECT FECCOMPROBANTE  FROM CONVENTAS WHERE CODEMPRESA = " & Codigo_De_Empresa & " AND CONVENTAS.FECCOMPROBANTE BETWEEN '" & inicio & "' AND '" & fin & "'  GROUP BY FECCOMPROBANTE ORDER BY FECCOMPROBANTE"
        End Select
        Try
            cmd = New SqlCommand(sql, Cone)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function BuscarComprobanteVenta(ByVal Codigo_De_Empresa As Long, ByVal Orden As Integer, Optional ByVal Nombre_Campo_Codigo As String = "", Optional ByVal Nombre_Campo_NumCodigo As String = "", Optional ByVal Nombre_Campo_Descripcion As String = "", Optional ByVal Nombre_Campo_Order As String = "", Optional ByVal Nombre_Tabla As String = "", Optional ByVal Nombre_Campo_Empresa As String = "") As SqlDataReader
        ser = New BD.ABD
        Dim Cone As New SqlConnection
        Cone = ser.Abrir
        sql = ""

        Select Case Orden
            Case 1
                sql = "SELECT CODCLIENTE AS Codigo, RTRIM(APELLIDO)+', '+ RTRIM(NOMBRE) AS Descripcion " & _
                "FROM CLIENTES WHERE EXISTS(SELECT * FROM VENTAS WHERE VENTAS.CODCLIENTE = CLIENTES.CODCLIENTE AND VENTAS.CODEMPRESA = " & Codigo_De_Empresa & ") AND CODEMPRESA = " & Codigo_De_Empresa & "  GROUP BY CODCLIENTE, APELLIDO, NOMBRE ORDER BY APELLIDO, NOMBRE"
            Case 2
                sql = "SELECT " & Nombre_Campo_Codigo & " AS Codigo, " & Nombre_Campo_NumCodigo & " AS NumCodigo," & Nombre_Campo_Descripcion & " as Descripcion, " & Nombre_Campo_Order & " AS Orden  FROM " & Nombre_Tabla & " WHERE " & Nombre_Campo_Empresa & " = " & Codigo_De_Empresa & "  ORDER BY " & Nombre_Campo_NumCodigo & ""
            Case 3
                sql = "SELECT V.FECHAVENTA AS FECCOMPROBANTE FROM VENTAS V, CLIENTES C WHERE V.CODCLIENTE = C.CODCLIENTE AND V.CODEMPRESA = " & Codigo_De_Empresa & "  GROUP BY V.FECHAVENTA ORDER BY V.FECHAVENTA"
        End Select
        Try
            cmd = New SqlCommand(sql, Cone)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function BuscarComprobanteCompra(ByVal Codigo_De_Empresa As Long, ByVal Orden As Integer, Optional ByVal Nombre_Campo_Codigo As String = "", Optional ByVal Nombre_Campo_NumCodigo As String = "", Optional ByVal Nombre_Campo_Descripcion As String = "", Optional ByVal Nombre_Campo_Order As String = "", Optional ByVal Nombre_Tabla As String = "", Optional ByVal Nombre_Campo_Empresa As String = "") As SqlDataReader
        ser = New BD.ABD
        Dim Cone As New SqlConnection
        Cone = ser.Abrir
        sql = ""

        Select Case Orden
            Case 1
                sql = "SELECT CODPROVEEDOR AS Codigo, RTRIM(APELLIDO)+', '+ RTRIM(NOMBRE) AS Descripcion " & _
                "FROM PROVEEDOR WHERE EXISTS(SELECT * FROM COMPRAS WHERE COMPRAS.CODPROVEEDOR = PROVEEDOR.CODPROVEEDOR AND COMPRAS.CODEMPRESA = " & Codigo_De_Empresa & ") AND CODEMPRESA = " & Codigo_De_Empresa & "  GROUP BY CODPROVEEDOR, APELLIDO, NOMBRE ORDER BY APELLIDO, NOMBRE"
            Case 2
                sql = "SELECT " & Nombre_Campo_Codigo & " AS Codigo, " & Nombre_Campo_NumCodigo & " AS NumCodigo," & Nombre_Campo_Descripcion & " as Descripcion, " & Nombre_Campo_Order & " AS Orden  FROM " & Nombre_Tabla & " WHERE " & Nombre_Campo_Empresa & "= " & Codigo_De_Empresa & " ORDER BY " & Nombre_Campo_NumCodigo & ""
            Case 3
                sql = "SELECT FECHACOMPRA AS FECCOMPROBANTE FROM COMPRAS WHERE CODEMPRESA = " & Codigo_De_Empresa & " GROUP BY FECHACOMPRA ORDER BY FECHACOMPRA"
        End Select
        'sql = sql & " 
        Try
            cmd = New SqlCommand(sql, Cone)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    Public Function validacion_rango_informe(ByRef textbox_rango_desde As System.Windows.Forms.Control, ByRef textbox_rango_hasta As System.Windows.Forms.Control) As String
        ''
        ''
        'Cesar, 2005-06-14  15:20 Validacion para rango de informes!!!!
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If textbox_rango_desde.Text.Trim.Length <> 0 And textbox_rango_hasta.Text.Trim.Length <> 0 Then
            If (IsNumeric(textbox_rango_desde.Text) And IsNumeric(textbox_rango_hasta.Text)) Then
                If Val(textbox_rango_desde.Text) > Val(textbox_rango_hasta.Text) Then
                    Mensaje = "El Hasta no puede ser menor al desde. Favor Verifique...."
                    textbox_rango_hasta.Text = ""
                    textbox_rango_hasta.Focus()
                End If
            Else
                If textbox_rango_desde.Text > textbox_rango_hasta.Text Then
                    Mensaje = "El Hasta no puede ser menor al desde. Favor Verifique...."
                    textbox_rango_hasta.Text = ""
                    textbox_rango_hasta.Focus()
                End If
            End If
        End If
        Return Mensaje
    End Function

    Public Function calcular_precio_moneda_principal(ByVal ultimo_costo_articulo As String, ByVal codigo_de_moneda_del_articulo As Long, ByVal codigo_empresa As String) As Decimal
        ''
        ''
        'Cesar, 2005-06-14  15:20 Validacion para rango de informes!!!!
        Dim sentfuncion As New Funcion
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = " SELECT " & ultimo_costo_articulo & "* " & _
        " (SELECT ISNULL(FACTORVENTA,0) FROM COTIZACION WHERE CODMONEDA = " & codigo_de_moneda_del_articulo & " " & _
        " AND FECHAMOVIMIENTO = (SELECT MAX(FECHAMOVIMIENTO) FROM COTIZACION WHERE CODMONEDA = " & codigo_de_moneda_del_articulo & ")) AS PRECIO "

        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Dim PRE As String
                PRE = dr("Precio")
                Return dr("Precio")
            Catch e As Exception
                MsgBox(e.Message)
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Catch e As Exception
            MsgBox(e.Message)
        Finally
        End Try
    End Function
    '''''''''''''''''''''''''''''''''''Ester 15-07-2005''''''''''''''''''''''''
    '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    Public Function StockActual(ByVal EmpCodigo As Long, ByVal DesNumSucursal As String, ByVal HasNumSucursal As String, ByVal HastaFecha As String, ByVal DesCodBarraProducto As String) As Decimal
        ser = New BD.ABD
        Dim Cone As New SqlConnection
        Cone = ser.Abrir
        sql = ""
        sql = "DECLARE @HASTA DATETIME, @DESPRODUCTO VARCHAR(25), @HASPRODUCTO VARCHAR(25), " & _
              "@DESSUCURSAL VARCHAR(5), @HASSUCURSAL VARCHAR(5), @empre numeric(9) " & _
              "SET @EMPRE  = " & EmpCodigo & " " & _
              "SET @HASTA  = '" & HastaFecha & "' " & _
              "SET @DESPRODUCTO = '" & DesCodBarraProducto & "' " & _
              "SET @HASPRODUCTO = '" & DesCodBarraProducto & "' " & _
              "SET @DESSUCURSAL = '" & DesNumSucursal & "' " & _
              "SET @HASSUCURSAL = '" & HasNumSucursal & "' " & _
              "" & _
              "SELECT PS.CODSUCURSAL, PS.CODPRODUCTO, PS.STOCKINICIAL, PS.ULTIMOINVENTARIO, PS.CANTIDAD, " & _
              "RTRIM(S.NUMSUCURSAL) AS NUMSUCURSAL, RTRIM(S.DESSUCURSAL) AS DESSUCURSAL, " & _
              "RTRIM(P.CODIGOBARRA) AS CODIGOBARRA, RTRIM(P.DESPRODUCTO) AS DESPRODUCTO, " & _
              "isnull((select sum(CD.CANTIDADCOMPRA) from COMPRASDETALLE cd, COMPRAS C where C.codempresa = @empre and C.codcompra = cd.codcompra AND p.codproducto = cd.codproducto AND P.CODPRODUCTO = PS.CODPRODUCTO AND PS.CODSUCURSAL = C.CODSUCURSAL  AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA, 103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO, 103) AS DATETIME)  AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA, 103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))), 0) as cantidadcom, " & _
              "isnull((select sum(VD.CANTIDADVENTA) from VENTASDETALLE Vd, VENTAS V where (V.ESTADO = 0 OR V.ESTADO = 9) and V.codempresa = @empre and V.codventa = Vd.codventa AND p.codproducto = vd.codproducto AND P.CODPRODUCTO = PS.CODPRODUCTO AND PS.CODSUCURSAL = v.CODSUCURSAL  AND CAST(CONVERT(CHAR(10), v.FECHAVENTA,103) AS DATETIME) >= CAST(CONVERT(CHAR(10),PS.ULTIMOINVENTARIO,103) AS DATETIME) AND CAST(CONVERT(CHAR(10), v.fechaventa,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))), 0) as cantidadven, " & _
              "isnull((select sum(AD.CANTIDADAJUSTE) from AJUSTEDETALLE Ad, AJUSTE A where A.TIPOAJUSTE = 1 and A.codempresa = @empre and A.codajuste = Ad.codajuste AND p.codproducto = ad.codproducto AND P.CODPRODUCTO = PS.CODPRODUCTO AND PS.CODSUCURSAL = a.CODSUCURSAL  AND CAST(CONVERT(CHAR(10), a.FECHAAJUSTE,103) AS DATETIME) >= CAST(CONVERT(CHAR(10),PS.ULTIMOINVENTARIO, 103) AS DATETIME) AND CAST(CONVERT(CHAR(10), a.fechaajuste,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))), 0) as cantidadmas, " & _
              "isnull((select sum(AD.CANTIDADAJUSTE) from AJUSTEDETALLE Ad, AJUSTE A where A.TIPOAJUSTE = 0 and A.codempresa = @empre and A.codajuste = Ad.codajuste AND p.codproducto = ad.codproducto AND P.CODPRODUCTO = PS.CODPRODUCTO AND PS.CODSUCURSAL = a.CODSUCURSAL  AND CAST(CONVERT(CHAR(10), a.FECHAAJUSTE,103) AS DATETIME) >= CAST(CONVERT(CHAR(10),PS.ULTIMOINVENTARIO, 103) AS DATETIME) AND CAST(CONVERT(CHAR(10), a.fechaajuste,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))), 0) as cantidadmenos, " & _
              "isnull((select sum(DD.CANTIDADDEVUELTA) from DEVOLUCIONDETALLE Dd, DEVOLUCION D where D.codempresa = @empre and D.coddevolucion = dd.coddevolucion AND p.codproducto = dd.codproducto AND P.CODPRODUCTO = PS.CODPRODUCTO AND PS.CODSUCURSAL = D.CODSUCURSAL  AND CAST(CONVERT(CHAR(10), D.FECHADEVOLUCION,103) AS DATETIME) >= CAST(CONVERT(CHAR(10),PS.ULTIMOINVENTARIO, 103) AS DATETIME) AND CAST(CONVERT(CHAR(10), D.fechadevolucion, 103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))), 0) as cantidaddev " & _
              "FROM PRODUCTOSUCURSAL PS, SUCURSAL S, PRODUCTOS P " & _
              "WHERE PS.CODSUCURSAL = S.CODSUCURSAL AND  P.CODPRODUCTO = PS.CODPRODUCTO AND " & _
              "S.NUMSUCURSAL BETWEEN @DESSUCURSAL AND @HASSUCURSAL AND P.CODIGOBARRA BETWEEN @DESPRODUCTO AND @HASPRODUCTO " & _
              "order by s.numsucursal, p.codigobarra"
        Try
            cmd = New SqlCommand(sql, Cone)
            dr = cmd.ExecuteReader()
            Dim CantidadStock As Decimal
            Do While dr.Read
                CantidadStock = CantidadStock + dr("stockinicial")
                CantidadStock = CantidadStock + dr("cantidadcom")
                CantidadStock = CantidadStock - dr("cantidadven")
                CantidadStock = CantidadStock + dr("cantidadmas")
                CantidadStock = CantidadStock - dr("cantidadmenos")
                CantidadStock = CantidadStock + dr("cantidaddev")
            Loop

            Return CantidadStock
        Catch ex As Exception
            Return 0
        Finally
            dr.Close()
            Cone.Close()
            ser.Cerrar(Cone)
        End Try
    End Function
    ''Cesar 16-09-2005
    Public Function MinimoFecha(ByVal nombre_campo As String, ByVal nombre_tabla As String) As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MIN(" & nombre_campo & ") AS minimo FROM " & nombre_tabla & ""
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("minimo")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function

    Public Function Buscar_Where(ByVal nombre_campo_codigo As String, ByVal nombre_campo_numcodigo As String, ByVal nombre_campo_descripcion As String, ByVal nombre_tabla As String, ByVal sentencia_where As String, ByVal codigo_empresa As Long, Optional ByVal Orden As Integer = 0) As SqlDataReader
        Dim temp As Integer

        ser = New BD.ABD
        cnn = ser.Abrir

        sql = ""

        Select Case Orden
            Case 0
                If sentencia_where.Trim = "" Then
                    sql = "SELECT " & nombre_campo_codigo & " as Codigo, rtrim(" & nombre_campo_numcodigo & ") as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion, /*Para ordene correctamente by ctroche 16/03/2006*/replicate('0',10-len(" & nombre_campo_numcodigo & "))+ltrim(rtrim(" & nombre_campo_numcodigo & ")) as NumCodigoOrden FROM " & nombre_tabla & " where CODEMPRESA = " & codigo_empresa & " " & sentencia_where & " ORDER BY NumCodigoOrden /*end orden*/"
                Else
                    sql = "SELECT " & nombre_campo_codigo & " as Codigo, rtrim(" & nombre_campo_numcodigo & ") as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion, /*Para ordene correctamente by ctroche 16/03/2006*/replicate('0',10-len(" & nombre_campo_numcodigo & "))+ltrim(rtrim(" & nombre_campo_numcodigo & ")) as NumCodigoOrden FROM " & nombre_tabla & " where " & sentencia_where & " " & codigo_empresa & "  ORDER BY NumCodigoOrden /*end orden*/"
                End If
            Case 1
                If sentencia_where.Trim = "" Then
                    sql = "SELECT " & nombre_campo_codigo & " as Codigo, rtrim(" & nombre_campo_numcodigo & ") as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " where CODEMPRESA = " & codigo_empresa & " " & sentencia_where & " ORDER BY " & nombre_campo_descripcion & " "
                Else
                    sql = "SELECT " & nombre_campo_codigo & " as Codigo, rtrim(" & nombre_campo_numcodigo & ") as NumCodigo, " & nombre_campo_descripcion & " AS Descripcion FROM " & nombre_tabla & " where " & sentencia_where & " " & codigo_empresa & " ORDER BY " & nombre_campo_descripcion & " "
                End If
        End Select
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Catch e As SqlException
            MsgBox(e.Message)
        Finally
        End Try
    End Function

    Public Function Buscar_Datos(ByVal nombre_campo_codigo As String, _
    ByVal nombre_campo_numcodigo As String, _
    ByVal nombre_campo_descripcion As String, _
    ByVal nombre_tabla As String, _
    ByVal sentencia_where As String, _
    ByVal codigo_empresa As Long, _
    Optional ByVal Orden As Integer = 0) As DataTable
        Dim temp As Integer
        Dim dt As New DataTable("DATOS")

        ser = New BD.ABD
        cnn = ser.Abrir

        sql = ""
        Select Case Orden
            Case 0
                If sentencia_where.Trim = "" Then
                    sql = "SELECT " & nombre_campo_codigo & " AS CODIGO, RTRIM(" & nombre_campo_numcodigo & ") AS NUMCODIGO, RTRIM(" & nombre_campo_descripcion & ") AS DESCRIPCION, /*PARA ORDENE CORRECTAMENTE BY CTROCHE 16/03/2006*/REPLICATE('0',10-LEN(" & nombre_campo_numcodigo & "))+LTRIM(RTRIM(" & nombre_campo_numcodigo & ")) AS NUMCODIGOORDEN FROM " & nombre_tabla & " WHERE CODEMPRESA = " & codigo_empresa & " " & sentencia_where & " ORDER BY NUMCODIGOORDEN /*END ORDEN*/"
                Else
                    sql = "SELECT " & nombre_campo_codigo & " AS CODIGO, RTRIM(" & nombre_campo_numcodigo & ") AS NUMCODIGO, RTRIM(" & nombre_campo_descripcion & ") AS DESCRIPCION, /*PARA ORDENE CORRECTAMENTE BY CTROCHE 16/03/2006*/REPLICATE('0',10-LEN(" & nombre_campo_numcodigo & "))+LTRIM(RTRIM(" & nombre_campo_numcodigo & ")) AS NUMCODIGOORDEN FROM " & nombre_tabla & " WHERE " & sentencia_where & " " & codigo_empresa & "  ORDER BY NUMCODIGOORDEN /*END ORDEN*/"
                End If
            Case 1
                If sentencia_where.Trim = "" Then
                    sql = "SELECT " & nombre_campo_codigo & " AS CODIGO, RTRIM(" & nombre_campo_numcodigo & ") AS NUMCODIGO, RTRIM(" & nombre_campo_descripcion & ") AS DESCRIPCION FROM " & nombre_tabla & " WHERE CODEMPRESA = " & codigo_empresa & " " & sentencia_where & " ORDER BY " & nombre_campo_descripcion & " "
                Else
                    sql = "SELECT " & nombre_campo_codigo & " AS CODIGO, RTRIM(" & nombre_campo_numcodigo & ") AS NUMCODIGO, RTRIM(" & nombre_campo_descripcion & ") AS DESCRIPCION FROM " & nombre_tabla & " WHERE " & sentencia_where & " " & codigo_empresa & " ORDER BY " & nombre_campo_descripcion & " "
                End If
        End Select

        Try
            da = New SqlDataAdapter(sql, cnn)
            da.Fill(dt)

            Return dt
        Catch e As Exception
            MsgBox(e.ToString)
        Finally
            ser.Cerrar(cnn)
        End Try
    End Function

    '''''SEGURIDAD DEL SISTEMA
    Public Function Otorgarpermisos_sin_reporte(ByVal Descripcion_De_Modulo As String, ByVal Num_De_Sistemas As String, ByVal Codigo_De_Usuario As Long, ByVal nombre_tabla1 As String, ByVal nombre_tabla2 As String, ByVal nombre_tabla3 As String, ByVal nombre_tabla4 As String, _
    ByRef BotonAnterior As System.Windows.Forms.Button, ByRef BotonPrimero As System.Windows.Forms.Button, ByRef BotonSiguiente As System.Windows.Forms.Button, ByRef BotonUltimo As System.Windows.Forms.Button, _
    ByRef BotonBorrar As System.Windows.Forms.Button, ByRef BotonBuscar As System.Windows.Forms.Button, ByRef BotonNuevo As System.Windows.Forms.Button, ByRef BotonModificar As System.Windows.Forms.Button, ByVal Codigo_De_Empresa As Long) As Boolean
        cnn = New SqlConnection
        cnn = ser.Abrir()
        Dim cmd As SqlCommand = cnn.CreateCommand()
        cmd.Connection = cnn
        Try
            sql = "SELECT M.CODMODULO, S.CODSISTEMAS, MU.CODUSUARIO, (MU.[SELECT])AS S, (MU.[INSERT])AS I , (MU.[UPDATE])AS U, (MU.[DELETE]) AS D, (MU.[PRINT])AS P, " & _
                  "(MU.VENCIDAS)AS V, (MU.LIMITECREDITO)AS L, (MU.[DESC])AS D,(MU.ANULAR)AS A FROM MODULOS M, SISTEMAS S, MODULOUSUARIO MU " & _
                  "WHERE S.NUMSISTEMAS = '" & Num_De_Sistemas & "' AND " & _
                  "MU.CODUSUARIO = " & Codigo_De_Usuario & " " & _
                  "AND M.DESMODULO = '" & Descripcion_De_Modulo & "' AND M.CODMODULO = MU.CODMODULO " & _
                  "AND M.CODSISTEMAS = S.CODSISTEMAS "
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
        Catch e As Exception
            MsgBox("Error" & vbCrLf & e.Message)
            'cmd = New SqlCommand(sql, cnn)
        End Try
        dr = cmd.ExecuteReader()
        Dim sel, ins, upd, del, pri, ven, lim, des, anu As Integer
        sel = 0
        ins = 0
        upd = 0
        del = 0
        pri = 0
        ven = 0
        lim = 0
        des = 0
        anu = 0
        Do While dr.Read()
            sel = dr("S")
            ins = dr("I")
            upd = dr("U")
            del = dr("D")
            pri = dr("P")
            ven = dr("V")
            lim = dr("L")
            des = dr("D")
            anu = dr("A")
        Loop
        'MsgBox(dr("S"))
        Try
            If sel = 0 Then
                BotonPrimero.Visible = False
                BotonAnterior.Visible = False
                BotonSiguiente.Visible = False
                BotonUltimo.Visible = False
                BotonBuscar.Visible = False
            Else
                BotonPrimero.Visible = True
                BotonAnterior.Visible = True
                BotonSiguiente.Visible = True
                BotonUltimo.Visible = True
                BotonBuscar.Visible = True
            End If
            If ins = 0 Then
                BotonNuevo.Visible = False
            Else
                BotonNuevo.Visible = True
            End If
            If upd = 0 Then
                BotonModificar.Visible = False
            Else
                BotonModificar.Visible = True
            End If
            If del = 0 Then
                BotonBorrar.Visible = False
            Else
                BotonBorrar.Visible = True
            End If
            If sel = 0 And ins = 0 And upd = 0 And del = 0 Then
                Return False
            End If
            Return True
        Finally
            dr.Close()
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function
    Public Function Otorgarpermisos_reportes(ByVal Descripcion_De_Modulo As String, ByVal Num_De_Sistemas As String, ByVal Codigo_De_Usuario As Long, ByVal nombre_tabla1 As String, ByVal nombre_tabla2 As String, ByVal nombre_tabla3 As String, ByVal nombre_tabla4 As String, _
    ByRef BotonMostrar As System.Windows.Forms.Button, ByVal Codigo_De_Empresa As Long) As Boolean
        cnn = New SqlConnection
        cnn = ser.Abrir()
        Dim cmd As SqlCommand = cnn.CreateCommand()
        cmd.Connection = cnn
        Try
            sql = "SELECT M.CODMODULO, S.CODSISTEMAS, MU.CODUSUARIO, (MU.[SELECT])AS S, (MU.[INSERT])AS I , (MU.[UPDATE])AS U, (MU.[DELETE]) AS D, (MU.[PRINT])AS P, " & _
                  "(MU.VENCIDAS)AS V, (MU.LIMITECREDITO)AS L, (MU.[DESC])AS D,(MU.ANULAR)AS A FROM MODULOS M, SISTEMAS S, MODULOUSUARIO MU " & _
                  "WHERE S.NUMSISTEMAS = '" & Num_De_Sistemas & "' AND " & _
                  "MU.CODUSUARIO = " & Codigo_De_Usuario & " " & _
                  "AND M.DESMODULO = '" & Descripcion_De_Modulo & "' AND M.CODMODULO = MU.CODMODULO " & _
                  "AND M.CODSISTEMAS = S.CODSISTEMAS "
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
        Catch e As Exception
            MsgBox("Error" & vbCrLf & e.Message)
            'cmd = New SqlCommand(sql, cnn)
        End Try
        dr = cmd.ExecuteReader()
        Dim sel, ins, upd, del, pri, ven, lim, des, anu As Integer
        sel = 0
        ins = 0
        upd = 0
        del = 0
        pri = 0
        ven = 0
        lim = 0
        des = 0
        anu = 0
        Do While dr.Read()
            sel = dr("S")
            ins = dr("I")
            upd = dr("U")
            del = dr("D")
            pri = dr("P")
            ven = dr("V")
            lim = dr("L")
            des = dr("D")
            anu = dr("A")
        Loop
        'MsgBox(dr("S"))
        Try
            If pri = 0 Then
                BotonMostrar.Visible = False
            Else
                BotonMostrar.Visible = True
            End If
            If pri = 0 Then
                Return False
            End If
            Return True
        Finally
            dr.Close()
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function

    Public Function Otorgarpermisos_sin_AlgunBoton(ByVal Descripcion_De_Modulo As String, ByVal Num_De_Sistemas As String, ByVal Codigo_De_Usuario As Long, ByVal nombre_tabla1 As String, ByVal nombre_tabla2 As String, ByVal nombre_tabla3 As String, ByVal nombre_tabla4 As String, _
    ByRef BotonAnterior As System.Windows.Forms.Button, ByRef BotonPrimero As System.Windows.Forms.Button, ByRef BotonSiguiente As System.Windows.Forms.Button, ByRef BotonUltimo As System.Windows.Forms.Button, _
    ByRef BotonBorrar As System.Windows.Forms.Button, ByRef BotonBuscar As System.Windows.Forms.Button, ByRef BotonNuevo As System.Windows.Forms.Button, ByVal Codigo_De_Empresa As Long) As Boolean
        cnn = New SqlConnection
        cnn = ser.Abrir()
        Dim cmd As SqlCommand = cnn.CreateCommand()
        cmd.Connection = cnn
        Try
            sql = "SELECT M.CODMODULO, S.CODSISTEMAS, MU.CODUSUARIO, (MU.[SELECT])AS S, (MU.[INSERT])AS I , (MU.[UPDATE])AS U, (MU.[DELETE]) AS D, (MU.[PRINT])AS P, " & _
                  "(MU.VENCIDAS)AS V, (MU.LIMITECREDITO)AS L, (MU.[DESC])AS D,(MU.ANULAR)AS A FROM MODULOS M, SISTEMAS S, MODULOUSUARIO MU " & _
                  "WHERE S.NUMSISTEMAS = '" & Num_De_Sistemas & "' AND " & _
                  "MU.CODUSUARIO = " & Codigo_De_Usuario & " " & _
                  "AND M.DESMODULO = '" & Descripcion_De_Modulo & "' AND M.CODMODULO = MU.CODMODULO " & _
                  "AND M.CODSISTEMAS = S.CODSISTEMAS "
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
        Catch e As Exception
            MsgBox("Error" & vbCrLf & e.Message)
            'cmd = New SqlCommand(sql, cnn)
        End Try
        dr = cmd.ExecuteReader()
        Dim sel, ins, upd, del, pri, ven, lim, des, anu As Integer
        sel = 0
        ins = 0
        upd = 0
        del = 0
        pri = 0
        ven = 0
        lim = 0
        des = 0
        anu = 0
        Do While dr.Read()
            sel = dr("S")
            ins = dr("I")
            upd = dr("U")
            del = dr("D")
            pri = dr("P")
            ven = dr("V")
            lim = dr("L")
            des = dr("D")
            anu = dr("A")
        Loop
        'MsgBox(dr("S"))
        Try
            If sel = 0 Then
                BotonPrimero.Visible = False
                BotonAnterior.Visible = False
                BotonSiguiente.Visible = False
                BotonUltimo.Visible = False
                BotonBuscar.Visible = False
            Else
                BotonPrimero.Visible = True
                BotonAnterior.Visible = True
                BotonSiguiente.Visible = True
                BotonUltimo.Visible = True
                BotonBuscar.Visible = True
            End If
            If ins = 0 Then
                BotonNuevo.Visible = False
            Else
                BotonNuevo.Visible = True
            End If
            If del = 0 Then
                BotonBorrar.Visible = False
            Else
                BotonBorrar.Visible = True
            End If
            If sel = 0 And ins = 0 And upd = 0 And del = 0 Then
                Return False
            End If
            Return True
        Finally
            dr.Close()
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function

    Public Function Entrar_OpciondeMenu(ByVal CodUsuario As Long, ByVal CodModulo As String, ByVal CodEmpresa As Long, ByVal NumSistema As String) As Long
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "declare @CodUsuario as numeric(18), @CodEmpresa as numeric(18), @CodModulo as CHAR(40) " & _
              "set @CodUsuario = " & CodUsuario & " " & _
              "set @codempresa = " & CodEmpresa & " " & _
              "set @codmodulo  = '" & CodModulo & "' " & _
              "select isnull(MU.codmodulo,0) as modulo, (MU.[SELECT]) AS S, (MU.[INSERT]) AS I , (MU.[UPDATE]) AS U, (MU.[DELETE]) AS D, (MU.[PRINT]) AS P, " & _
              "(MU.VENCIDAS) AS V, (MU.LIMITECREDITO) AS L, (MU.[DESC]) AS D,(MU.ANULAR) AS A " & _
              "from MODULOUSUARIO MU, MODULOS M, SISTEMAS S " & _
              "WHERE MU.CODUSUARIO = @CODUSUARIO " & _
              "AND MU.CODMODULO = M.CODMODULO " & _
              "AND S.NUMSISTEMAS = '" & NumSistema & "' " & _
              "AND M.CODSISTEMAS = S.CODSISTEMAS " & _
              "AND MU.CODEMPRESA = @CODEMPRESA " & _
              "AND M.DESMODULO = @CODMODULO "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()

                If dr("S") = 0 And dr("I") = 0 And dr("U") = 0 And dr("D") = 0 And dr("P") = 0 And dr("V") = 0 And dr("L") = 0 And dr("D") = 0 And dr("A") = 0 Then
                    Return 0
                End If
                Return dr("modulo")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function

    Public Function Otorgarpermisos_sin_reporte_anular(ByVal Descripcion_De_Modulo As String, ByVal Num_De_Sistemas As String, ByVal Codigo_De_Usuario As Long, ByVal nombre_tabla1 As String, ByVal nombre_tabla2 As String, ByVal nombre_tabla3 As String, ByVal nombre_tabla4 As String, _
    ByRef BotonAnterior As System.Windows.Forms.Button, ByRef BotonPrimero As System.Windows.Forms.Button, ByRef BotonSiguiente As System.Windows.Forms.Button, ByRef BotonUltimo As System.Windows.Forms.Button, _
    ByRef BotonBorrar As System.Windows.Forms.Button, ByRef BotonBuscar As System.Windows.Forms.Button, ByRef BotonNuevo As System.Windows.Forms.Button, ByRef BotonModificar As System.Windows.Forms.Button, _
    ByRef BotonAnular As System.Windows.Forms.Button, ByVal Codigo_De_Empresa As Long) As Boolean
        cnn = New SqlConnection
        cnn = ser.Abrir()
        Dim cmd As SqlCommand = cnn.CreateCommand()
        cmd.Connection = cnn
        Try
            sql = "SELECT M.CODMODULO, S.CODSISTEMAS, MU.CODUSUARIO, (MU.[SELECT])AS S, (MU.[INSERT])AS I , (MU.[UPDATE])AS U, (MU.[DELETE]) AS D, (MU.[PRINT])AS P, " & _
                  "(MU.VENCIDAS)AS V, (MU.LIMITECREDITO)AS L, (MU.[DESC])AS D,(MU.ANULAR)AS A FROM MODULOS M, SISTEMAS S, MODULOUSUARIO MU " & _
                  "WHERE S.NUMSISTEMAS = '" & Num_De_Sistemas & "' AND " & _
                  "MU.CODUSUARIO = " & Codigo_De_Usuario & " " & _
                  "AND M.DESMODULO = '" & Descripcion_De_Modulo & "' AND M.CODMODULO = MU.CODMODULO " & _
                  "AND M.CODSISTEMAS = S.CODSISTEMAS "
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()
        Catch e As Exception
            MsgBox("Error" & vbCrLf & e.Message)
            'cmd = New SqlCommand(sql, cnn)
        End Try
        dr = cmd.ExecuteReader()
        Dim sel, ins, upd, del, pri, ven, lim, des, anu As Integer
        sel = 0
        ins = 0
        upd = 0
        del = 0
        pri = 0
        ven = 0
        lim = 0
        des = 0
        anu = 0
        Do While dr.Read()
            sel = dr("S")
            ins = dr("I")
            upd = dr("U")
            del = dr("D")
            pri = dr("P")
            ven = dr("V")
            lim = dr("L")
            des = dr("D")
            anu = dr("A")
        Loop
        'MsgBox(dr("S"))
        Try
            If sel = 0 Then
                BotonPrimero.Visible = False
                BotonAnterior.Visible = False
                BotonSiguiente.Visible = False
                BotonUltimo.Visible = False
                BotonBuscar.Visible = False
            Else
                BotonPrimero.Visible = True
                BotonAnterior.Visible = True
                BotonSiguiente.Visible = True
                BotonUltimo.Visible = True
                BotonBuscar.Visible = True
            End If
            If ins = 0 Then
                BotonNuevo.Visible = False
            Else
                BotonNuevo.Visible = True
            End If
            If upd = 0 Then
                BotonModificar.Visible = False
            Else
                BotonModificar.Visible = True
            End If
            If del = 0 Then
                BotonBorrar.Visible = False
            Else
                BotonBorrar.Visible = True
            End If
            If anu = 0 Then
                BotonAnular.Visible = False
            Else
                BotonAnular.Visible = True
            End If
            If sel = 0 And ins = 0 And upd = 0 And del = 0 And anu = 0 Then
                Return False
            End If
            Return True
        Finally
            dr.Close()
            ser.Cerrar(cnn)
            ser.Cerrar(cnn)
        End Try
    End Function

    '07-12-2005
    'LUIS GROSSLING
    '''''''''''''''''''''''''''''''''''
    Public Function DecimalPrincipal(ByVal Codigo_Empresa As Long) As Boolean
        'Determina si la moneda predeterminada utiliza decimales

        ser = New BD.ABD
        cnn = ser.Abrir

        sql = ""
        sql = "SELECT DECIMALES AS DECIMALES FROM CONFIGURACION C INNER JOIN MONEDA M ON C.MONEDA1 = M.CODMONEDA " & _
            "WHERE C.CODEMPRESA = " & Codigo_Empresa & ""

        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            dr.Read()

            If dr("DECIMALES") = 0 Then
                Return False
            Else
                Return True
            End If
        Catch e As Exception
            MsgBox(e.ToString)
        Finally
            dr.Close()
            ser.Cerrar(cnn)
        End Try
    End Function

    Public Function CostoPromedio(ByVal EmpCodigo As Long, ByVal HastaFecha As String, ByVal codproducto As Long, ByVal candecimal As Integer) As Decimal
        Dim ser4 As New BD.ABD
        Dim ser2 As New BD.ABD
        Dim ser3 As New BD.ABD
        Dim Cone As New SqlConnection
        Dim Cone2 As New SqlConnection
        Dim Cone3 As New SqlConnection
        Dim dr2 As SqlDataReader
        Dim dr3 As SqlDataReader
        Dim dr4 As SqlDataReader
        Dim sql2 As String
        Dim cnn2 As New SqlConnection
        Dim cantidad, costo, sumacantidad, sumacosto, costopro, stockinicial, cppalcierre, primerCosto, ultimocosto As Decimal
        Dim codmoneda As Long
        Dim ultimoc As String


        sql2 = ""
        sql2 = "DECLARE @HASTA DATETIME, @PRODUCTO numeric(9), " & _
              "@DESSUCURSAL VARCHAR(5), @HASSUCURSAL VARCHAR(5), @empre numeric(9) " & _
              "SET @EMPRE  = " & EmpCodigo & " " & _
              "SET @HASTA  = '" & HastaFecha & "' " & _
              "SET @PRODUCTO = '" & codproducto & "' " & _
              "" & _
              "SELECT PS.CODSUCURSAL, PS.CODPRODUCTO, PS.STOCKINICIAL, P.ULTIMOCOSTO, P.CODMONEDA, " & _
        "PS.ULTIMOINVENTARIO, PS.CANTIDAD, isnull(PS.COSTOPPALCIERRE,0) as COSTOPPALCIERRE, " & _
        "M.DECIMALES " & _
        "FROM PRODUCTOSUCURSAL PS, SUCURSAL S, PRODUCTOS P, MONEDA M " & _
        "WHERE PS.CODSUCURSAL = S.CODSUCURSAL AND  P.CODPRODUCTO = PS.CODPRODUCTO AND " & _
        "P.CODPRODUCTO = @PRODUCTO AND P.CODMONEDA = M.CODMONEDA "

        Cone2 = ser2.Abrir
        cmd = New SqlCommand(sql2, Cone2)
        dr2 = cmd.ExecuteReader()

        cantidad = 0.0
        costo = 0.0
        sumacantidad = 0.0
        sumacosto = 0.0
        costopro = 0.0
        stockinicial = 0.0
        cppalcierre = 0.0

        Do While dr2.Read()
            If IsDBNull(dr2("STOCKINICIAL")) Then
                stockinicial = 0
            Else
                stockinicial = dr2("STOCKINICIAL")
            End If
            If IsDBNull(dr2("COSTOPPALCIERRE")) Then
                cppalcierre = 0
            Else
                cppalcierre = dr2("COSTOPPALCIERRE")
            End If
            If IsDBNull(dr2("ULTIMOCOSTO")) Then
                ultimocosto = 0
            Else
                ultimocosto = dr2("ULTIMOCOSTO")
            End If
            If IsDBNull(dr2("CODMONEDA")) Then
                codmoneda = 0
            Else
                codmoneda = dr2("CODMONEDA")
            End If
            If dr2("DECIMALES") = 0 Then
                candecimal = 0
            Else
                candecimal = 5
            End If

        Loop
        dr2.Close()


        sql = ""
        sql = "DECLARE @HASTA DATETIME, @PRODUCTO NUMERIC(9), " & _
              "@DESSUCURSAL VARCHAR(5), @HASSUCURSAL VARCHAR(5), @EMPRE NUMERIC(9), @MONE NUMERIC(9) " & _
              "SET @EMPRE  = " & EmpCodigo & " " & _
              "SET @HASTA  = '" & HastaFecha & "' " & _
              "SET @PRODUCTO = '" & codproducto & "' " & _
              "SET @MONE = '" & codmoneda & "' " & _
              "" & _
                    " SELECT T.DESCOMPROBANTE AS DESCOMPROBANTE, V.NUMVENTA AS NUMMOVIMIENTO, V.FECHAVENTA AS FECHAMOVIMIENTO, " & _
                    " VD.CANTIDADVENTA AS CANTIDADMOVIMIENTO, 0 AS TIPOMOVIMIENTO, 'VENTA' AS TIPOMOV, " & _
                    " 0.00 AS COSTO, 0.00 AS COSTOPRO " & _
                    " FROM VENTAS V, VENTASDETALLE VD, TIPOCOMPROBANTE T, PRODUCTOSUCURSAL PS  " & _
                    " WHERE VD.CODPRODUCTO = @PRODUCTO AND V.CODEMPRESA = @EMPRE " & _
                    " AND V.CODVENTA = VD.CODVENTA AND V.CODCOMPROBANTE = T.CODCOMPROBANTE  " & _
                    " AND (V.ESTADO = 0 OR V.ESTADO = 9) " & _
                    " AND VD.CODPRODUCTO = PS.CODPRODUCTO " & _
                    " AND CAST(CONVERT(CHAR(10), V.FECHAVENTA,103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO,103) AS DATETIME) " & _
                    " AND CAST(CONVERT(CHAR(10), V.FECHAVENTA,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME)) " & _
                    " UNION ALL " & _
                    " SELECT T.DESCOMPROBANTE AS DESCOMPROBANTE, C.NUMCOMPRA AS NUMMOVIMIENTO, C.FECHACOMPRA AS FECHAMOVIMIENTO, " & _
                    " CD.CANTIDADCOMPRA AS CANTIDADMOVIMIENTO, 1 AS TIPOMOVIMIENTO, 'COMPRA' AS TIPOMOV, " & _
                    " (CD.COSTOUNITARIO*C.COTIZACION1) / " & _
                    " ISNULL((SELECT FACTORVENTA FROM COTIZACION WHERE FECHAMOVIMIENTO = (SELECT MAX(FECHAMOVIMIENTO) AS MAXIMO FROM COTIZACION WHERE CODEMPRESA = @EMPRE AND CODMONEDA = @MONE " & _
                    " AND FECHAMOVIMIENTO <= C.FECHACOMPRA)AND CODEMPRESA = @EMPRE AND CODMONEDA = @MONE),0) " & _
                    " AS COSTO, 0.00 AS COSTOPRO " & _
                    " FROM COMPRAS C, COMPRASDETALLE CD, TIPOCOMPROBANTE T, PRODUCTOSUCURSAL PS  " & _
                    " WHERE CD.CODPRODUCTO = @PRODUCTO AND C.CODEMPRESA = @EMPRE " & _
                    " AND C.CODCOMPRA = CD.CODCOMPRA AND C.CODCOMPROBANTE = T. CODCOMPROBANTE  " & _
                    " AND CD.CODPRODUCTO = PS.CODPRODUCTO " & _
                    " AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA,103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO,103) AS DATETIME) " & _
                    " AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME)) " & _
                    " UNION ALL " & _
                    " SELECT T.DESCOMPROBANTE AS DESCOMPROBANTE, A.NUMAJUSTE AS  NUMMOVIMIENTO,  A.FECHAAJUSTE AS FECHAMOVIMIENTO, " & _
                    " AD.CANTIDADAJUSTE AS CANTIDADMOVIMIENTO, A.TIPOAJUSTE AS TIPOMOVIMIENTO, 'AJUSTE' AS TIPOMOV, " & _
                    " 0.00 AS COSTO, 0.00 AS COSTOPRO " & _
                    " FROM AJUSTE A, AJUSTEDETALLE AD, TIPOCOMPROBANTE T, PRODUCTOSUCURSAL PS  " & _
                    " WHERE AD.CODPRODUCTO = @PRODUCTO AND A.CODEMPRESA = @EMPRE " & _
                    " AND A.CODAJUSTE = AD.CODAJUSTE  " & _
                    " AND A.CODCOMPROBANTE = T.CODCOMPROBANTE " & _
                    " AND AD.CODPRODUCTO = PS.CODPRODUCTO " & _
                    " AND CAST(CONVERT(CHAR(10), A.FECHAAJUSTE,103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO,103) AS DATETIME) " & _
                    " AND CAST(CONVERT(CHAR(10), A.FECHAAJUSTE,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME)) " & _
                    " UNION ALL " & _
                    " SELECT T.DESCOMPROBANTE AS DESCOMPROBANTE, D.NUMDEVOLUCION AS NUMMOVIMIENTO, D.FECHADEVOLUCION AS FECHAMOVIMIENTO, " & _
                    " DD.CANTIDADDEVUELTA AS CANTIDADMOVIMIENTO, 1 AS TIPOMOVIMIENTO, 'DEVOLUCION' AS TIPOMOV, " & _
                    " 0.00 AS COSTO, 0.00 AS COSTOPRO " & _
                    " FROM DEVOLUCION D, DEVOLUCIONDETALLE DD, TIPOCOMPROBANTE T, PRODUCTOSUCURSAL PS  " & _
                    " WHERE DD.CODPRODUCTO = @PRODUCTO AND D.CODEMPRESA = @EMPRE " & _
                    " AND D.CODDEVOLUCION = DD.CODDEVOLUCION AND D.CODCOMPROBANTE = T. CODCOMPROBANTE  " & _
                    " AND DD.CODPRODUCTO = PS.CODPRODUCTO " & _
                    " AND CAST(CONVERT(CHAR(10), D.FECHADEVOLUCION,103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO,103) AS DATETIME) " & _
                    " AND CAST(CONVERT(CHAR(10), D.FECHADEVOLUCION,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))"

        Try
            Cone = ser4.Abrir
            cmd = New SqlCommand(sql, Cone)
            dr4 = cmd.ExecuteReader()

            sumacantidad = stockinicial
            sumacosto = stockinicial * cppalcierre

            If sumacosto = 0 Then
                sql2 = ""
                sql2 = "DECLARE @HASTA DATETIME, @PRODUCTO numeric(9), " & _
              "@DESSUCURSAL VARCHAR(5), @HASSUCURSAL VARCHAR(5), @empre numeric(9), @mone numeric(9) " & _
              "SET @EMPRE  = " & EmpCodigo & " " & _
              "SET @HASTA  = '" & HastaFecha & "' " & _
              "SET @PRODUCTO = '" & codproducto & "' " & _
              "SET @MONE = '" & codmoneda & "' " & _
              "" & _
              "SELECT " & _
                    " (CD.COSTOUNITARIO*C.COTIZACION1) / " & _
                    " ISNULL((SELECT FACTORVENTA FROM COTIZACION WHERE FECHAMOVIMIENTO = (SELECT MAX(FECHAMOVIMIENTO) AS MAXIMO FROM COTIZACION WHERE CODEMPRESA = @EMPRE AND CODMONEDA = @MONE " & _
                    " AND FECHAMOVIMIENTO <= C.FECHACOMPRA)AND CODEMPRESA = @EMPRE AND CODMONEDA = @MONE),0) AS COSTOUNITARIO  " & _
                    " FROM COMPRASDETALLE CD, COMPRAS C, PRODUCTOSUCURSAL PS WHERE C.FECHACOMPRA = " & _
                    " (SELECT MIN(C.FECHACOMPRA) AS MINIMO FROM COMPRASDETALLE CD, COMPRAS C, PRODUCTOSUCURSAL PS WHERE " & _
                    " CD.CODPRODUCTO = @PRODUCTO AND " & _
                    " C.CODEMPRESA = @EMPRE " & _
                    " AND C.CODCOMPRA = CD.CODCOMPRA " & _
                    " AND CD.CODPRODUCTO = PS.CODPRODUCTO " & _
                    " AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA,103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO,103) AS DATETIME) " & _
                    " AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME))) " & _
                    " AND CD.CODPRODUCTO = @PRODUCTO AND " & _
                    " C.CODEMPRESA = @EMPRE " & _
                    " AND C.CODCOMPRA = CD.CODCOMPRA " & _
                    " AND CD.CODPRODUCTO = PS.CODPRODUCTO " & _
                    " AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA,103) AS DATETIME) >= CAST(CONVERT(CHAR(10), PS.ULTIMOINVENTARIO,103) AS DATETIME) " & _
                    " AND CAST(CONVERT(CHAR(10), C.FECHACOMPRA,103) AS DATETIME) <= (CAST(@HASTA AS DATETIME)) " & _
                    " ORDER BY NUMCOMPRA DESC "

                Cone3 = ser3.Abrir
                cmd = New SqlCommand(sql2, Cone3)
                dr3 = cmd.ExecuteReader()

                Do While dr3.Read()
                    primerCosto = dr3("COSTOUNITARIO")
                Loop
                dr3.Close()


                If stockinicial > 0 Then
                    sumacosto = stockinicial * primerCosto
                End If

                costopro = primerCosto

            End If

            If sumacosto = 0 And ultimocosto > 0 And costopro = 0 Then
                costopro = ultimocosto
                ultimoc = ultimocosto
                ultimoc = ultimoc.Replace(".", "")
                ultimoc = ultimoc.Replace(",", ".")
                If stockinicial > 0 Then
                    'sumacosto = stockinicial * calcular_precio_moneda_principal(ultimoc, codmoneda, EmpCodigo)
                    sumacosto = stockinicial * ultimocosto
                    sumacosto = Math.Round(sumacosto, candecimal)
                End If
            End If

            Dim existe As Boolean
            existe = dr4.HasRows

            If existe Then        'el datareader seleccionó registros de movimientos de stock

                Do While dr4.Read()

                    cantidad = dr4("CANTIDADMOVIMIENTO")
                    If dr4("TIPOMOV") = "COMPRA" Then
                        costo = dr4("COSTO")
                    Else
                        costo = costopro
                    End If

                    If dr4("TIPOMOVIMIENTO") = 1 Then
                        sumacantidad = sumacantidad + cantidad
                        sumacosto = sumacosto + (costo * cantidad)
                    Else
                        sumacantidad = sumacantidad - cantidad
                        sumacosto = sumacosto - (costo * cantidad)
                    End If

                    If sumacantidad <> 0 Then
                        costopro = Math.Round(sumacosto / sumacantidad, candecimal)
                    End If

                Loop
            Else
                ' si no tuvo ningun movimiento
                If sumacantidad <> 0 And sumacosto <> 0 Then
                    costopro = Math.Round(sumacosto / sumacantidad, candecimal)
                End If

            End If


            Return costopro

        Catch e As Exception
            MsgBox(e.Message)
            Return 0
        Finally
            dr2.Close()
            dr3.Close()
            dr4.Close()
            Cone.Close()
            Cone2.Close()
            Cone3.Close()
            ser4.Cerrar(Cone)
            ser2.Cerrar(Cone2)
            ser3.Cerrar(Cone3)
        End Try
    End Function

    ''
    ''
    'ctroche, 03/03/2006 Lista todas las monedas disponibles, especial para cargar un combobox o listbox por ejemplo.
    Public Function lista_moneda(ByVal codigo_empresa As Long) As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT CODMONEDA, NUMMONEDA, RTRIM(DESMONEDA) AS DESMONEDA, PRIORIDAD FROM MONEDA WHERE CODEMPRESA = '" & codigo_empresa & "' ORDER BY PRIORIDAD DESC"
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    ''
    ''
    'ctroche, 03/03/2006 Lista todos los tipos de clientes disponibles, especial para cargar un combobox o listbox por ejemplo.!!!!
    Public Function lista_TipoCliente(ByVal codigo_empresa As Long) As SqlDataReader
        Dim temp As Integer
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT CODTIPOCLIENTE, NUMTIPOCLIENTE, RTRIM(DESTIPOCLIENTE) AS TIPOCLIENTE FROM TIPOCLIENTE WHERE CODEMPRESA = '" & codigo_empresa & "' "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Return dr
        Finally
        End Try
    End Function
    ''
    ''
    'ctroche, 20/03/2006 Para validar los rangos en los informes. Test ok al 100%!!!!
    Public Function validated_rango_informe(ByRef textbox_desde As System.Windows.Forms.TextBox, ByRef textbox_hasta As System.Windows.Forms.TextBox) As Boolean
        Dim Mensaje As String = "0"
        Dim ceros As String = "0000000000"
        If textbox_desde.Text.Trim.Length <> 0 And textbox_hasta.Text.Trim.Length <> 0 Then
            If (Microsoft.VisualBasic.Left(ceros, Len(ceros) - Len(textbox_desde.Text.Trim)) + textbox_desde.Text.Trim) > (Microsoft.VisualBasic.Left(ceros, Len(ceros) - Len(textbox_hasta.Text.Trim)) + textbox_hasta.Text.Trim) Then
                textbox_hasta.SelectionStart = 0
                textbox_hasta.SelectionLength = Len(textbox_hasta.Text)
                textbox_hasta.Focus()
                Return False
            End If
        End If
        Return True
    End Function
    'ctroche, 20/03/2006 Para armar las condiciones en los informes, compara  Test ok al 100%!!!!
    Public Function armar_condiciones_informe(ByVal condiciones As String, ByVal tabla_num_or_des As String, ByRef objeto_desde As System.Windows.Forms.Control, ByRef objeto_hasta As System.Windows.Forms.Control, Optional ByVal cantidad_ceros As Integer = 10, Optional ByVal control As Integer = 0) As String
        Dim condicion As String = condiciones
        'control = 0 POR DEFECTO, ES PARA EL CASO EN QUE LA COMPARACION SEA ENTRE TEXTBOX'S
        'control = 1 ES PARA EL CASO EN QUE LA COMPARACION SEA ENTRE LABEL'S OR FECHAS'S

        Select Case control
            Case Is = 0
                If objeto_desde.Text.Trim.Length <> 0 And objeto_hasta.Text.Trim.Length <> 0 Then
                    condicion = condicion + " AND replicate('0'," & cantidad_ceros & "-len(" & tabla_num_or_des & "))+ltrim(rtrim(" & tabla_num_or_des & ")) >= replicate('0'," & cantidad_ceros & "-len('" & objeto_desde.Text.Trim & "'))+ltrim(rtrim(' " & objeto_desde.Text.Trim & "'))" & " AND replicate('0'," & cantidad_ceros & "-len(" & tabla_num_or_des & "))+ltrim(rtrim(" & tabla_num_or_des & ")) <= replicate('0'," & cantidad_ceros & "-len('" & objeto_hasta.Text.Trim & "'))+ltrim(rtrim(' " & objeto_hasta.Text.Trim & "'))"
                End If
                If objeto_desde.Text.Trim.Length <> 0 And objeto_hasta.Text.Trim.Length = 0 Then
                    condicion = condicion + " AND replicate('0'," & cantidad_ceros & "-len(" & tabla_num_or_des & "))+ltrim(rtrim(" & tabla_num_or_des & ")) >= replicate('0'," & cantidad_ceros & "-len('" & objeto_desde.Text.Trim & "'))+ltrim(rtrim(' " & objeto_desde.Text.Trim & "'))"
                End If
                If objeto_desde.Text.Trim.Length = 0 And objeto_hasta.Text.Trim.Length <> 0 Then
                    condicion = condicion + " AND replicate('0'," & cantidad_ceros & "-len(" & tabla_num_or_des & "))+ltrim(rtrim(" & tabla_num_or_des & ")) <= replicate('0'," & cantidad_ceros & "-len('" & objeto_hasta.Text.Trim & "'))+ltrim(rtrim(' " & objeto_hasta.Text.Trim & "'))"
                End If
                Return condicion

            Case Is = 1
                If objeto_desde.Text.Trim.Length <> 0 And objeto_hasta.Text.Trim.Length <> 0 Then
                    condicion = condicion + " AND " & tabla_num_or_des & " >= '" & objeto_desde.Text.Trim & "' AND " & tabla_num_or_des & " <= '" & objeto_hasta.Text.Trim & "'"
                End If
                If objeto_desde.Text.Trim.Length <> 0 And objeto_hasta.Text.Trim.Length = 0 Then
                    condicion = condicion + " AND " & tabla_num_or_des & " >= '" & objeto_desde.Text.Trim & "'"
                End If
                If objeto_desde.Text.Trim.Length = 0 And objeto_hasta.Text.Trim.Length <> 0 Then
                    condicion = condicion + " AND " & tabla_num_or_des & " <= '" & objeto_hasta.Text.Trim & "'"
                End If
                Return condicion

        End Select
    End Function

    Public Function validacion_rango_informe_por_COD(ByRef textbox_rango_desde As System.Windows.Forms.TextBox, ByRef textbox_rango_hasta As System.Windows.Forms.TextBox) As String
        ''
        ''
        'ctroche, 2005-01-23  Validacion para rango de informes pór el COD!!!!
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If textbox_rango_desde.Text.Trim.Length <> 0 And textbox_rango_hasta.Text.Trim.Length <> 0 Then
            If (IsNumeric(textbox_rango_desde.Tag) And IsNumeric(textbox_rango_hasta.Tag)) Then
                If Val(textbox_rango_desde.Tag) > Val(textbox_rango_hasta.Tag) Then
                    Mensaje = "El Hasta no puede ser menor al desde. Favor Verifique...."
                    textbox_rango_hasta.Text = ""
                    textbox_rango_hasta.Focus()
                End If
            End If
        End If
        Return Mensaje
    End Function

    Public Function codigo_rango(ByRef textbox_rango As System.Windows.Forms.TextBox, ByVal nombre_campo_codigo As String, ByVal nombre_tabla As String, ByVal nombre_campo_numcodigo As String, ByVal codigo_empresa As String) As String
        ''
        ''
        '21/01/2006  ctroche - Validación de los parametros.
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"
        If textbox_rango.Text.Trim <> "" Then
            textbox_rango.Tag = sentfuncion.Descripcion_Tabla(nombre_campo_codigo, nombre_tabla, nombre_campo_numcodigo, textbox_rango.Text, codigo_empresa)
        End If
        Return Mensaje
    End Function

    Public Function TraeImporte(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String, ByVal codigo_empresa As String) As Decimal
        Dim valor As Long = 1
        ser = New BD.ABD
        cnn = ser.Abrir

        sql = ""
        sql = "SELECT " & nombre_campo & " AS importe FROM " & nombre_tabla & " where " & campo_buscado & " = '" & variable_ingresada & "' and codempresa = " & codigo_empresa & " "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("importe")
            Catch
                Return 0
            Finally
                dr.Close()
                cnn.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function

    Public Function Ajuste(ByVal importe As Decimal, ByVal candecimales As Integer)
        If importe - Int(importe) = 0.5 Then
            importe = importe + 0.01
        End If
        importe = Math.Round(importe, candecimales)
        Return importe
    End Function

    Public Function textomes(ByRef mes As Integer) As String
        Dim texto As String
        Dim meses(12) As String
        meses(1) = "Enero"
        meses(2) = "Febrero"
        meses(3) = "Marzo"
        meses(4) = "Abril"
        meses(5) = "Mayo"
        meses(6) = "Junio"
        meses(7) = "Julio"
        meses(8) = "Agosto"
        meses(9) = "Setiembre"
        meses(10) = "Octubre"
        meses(11) = "Noviembre"
        meses(12) = "Diciembre"
        texto = meses(mes)
        Return texto
    End Function

    Public Function Sueldo(ByRef empresa As Long) As DataTable
        Dim dt As New DataTable("SUELDOS")

        dt.Rows.Clear()

        ser = New BD.ABD
        cnn = ser.Abrir

        Try
            sql = ""
            sql = "SELECT ISNULL(HORASLABORALES, 8) AS HORASLABORALES, ISNULL(DIASLABORALES, 30) AS DIASLABORALES, " & _
            "ISNULL(MOVI1, 0) AS AUSENCIAS, ISNULL(MOVI2, 0) AS HORASEXTRASNORMALES, " & _
            "ISNULL(MOVI3, 0) AS HORASEXTRASNOCTURNAS, ISNULL(MOVI4, 0) AS BONIFICACIONFAMILIAR, " & _
            "ISNULL(MOVI5, 0) AS VACACIONES, ISNULL(MOVI6, 0) AS AGUINALDO, " & _
            "ISNULL(MOVI7, 0) AS SUELDO, ISNULL(MOVI8, 0) AS IPS, " & _
            "ISNULL(MOVI9, 0) AS MASCULINO, ISNULL(MOVI10, 0) AS FEMENINO, " & _
            "ISNULL(MOVI11, 0) AS SUPERVISOR, ISNULL(MOVI12, 0) AS EMPLEADOS, " & _
            "ISNULL(MOVI13, 0) AS OBRERO, ISNULL(MOVI14, 0) AS MENOR " & _
            "FROM SUELDOCONFIG WHERE CODEMPRESA = " & empresa & ""

            cmd = New SqlCommand
            cmd.Connection = cnn
            cmd.CommandText = sql

            da = New SqlDataAdapter(cmd)
            da.Fill(dt)
            Return dt
        Catch ex As Exception

        End Try
    End Function

    Public Function CargarBuscadorGrilla(ByVal nombre_tabla As String, ByVal nombre_codigo As String, _
    ByVal nombre_numcodigo As String, ByVal nombre_descripcion As String, _
    ByVal EmpCodigo As String, ByVal Orden As Integer, _
    Optional ByVal sentencia_where As String = "", _
    Optional ByVal groupby As String = "", Optional ByVal having As String = "", _
    Optional ByVal ordenby As String = "", Optional ByVal Campo1 As String = "", _
    Optional ByVal Campo2 As String = "", Optional ByVal Campo3 As String = "", _
    Optional ByVal Campo4 As String = "") As DataTable

        dt = New DataTable("dtResultado")

        Try
            dt.Rows.Clear()
            ser = New BD.ABD
            cnn = ser.Abrir
            sql = ""
            sql = "SELECT " & nombre_codigo & " AS CODIGO, " & nombre_numcodigo & " AS NUMCODIGO, " & _
                  " RTRIM(" & nombre_descripcion & ") AS DESCRIPCION"
            If Campo1.Trim <> "" Then
                sql = sql & ", " & Campo1.Trim & " AS CAMPO1 "
            End If
            If Campo2.Trim <> "" Then
                sql = sql & ", " & Campo2.Trim & " AS CAMPO2 "
            End If
            If Campo3.Trim <> "" Then
                sql = sql & ", " & Campo3.Trim & " AS CAMPO3 "
            End If
            If Campo4.Trim <> "" Then
                sql = sql & ", " & Campo4.Trim & " AS CAMPO4 "
            End If

            sql = sql & " FROM " & nombre_tabla & " "

            If sentencia_where.Trim = "" Then
                sql = sql & " WHERE CODEMPRESA =" & EmpCodigo & " "
            Else
                sql = sql & " WHERE " & sentencia_where & " " & EmpCodigo & " "
            End If

            If groupby.Trim <> "" Then
                sql = sql & " GROUP BY " & groupby
            End If

            If having.Trim <> "" Then
                sql = sql & " HAVING " & having
            End If

            Select Case Orden
                Case 0 'NUMCODIGO
                    sql = sql & " ORDER BY NUMCODIGO "
                Case 1 'DESCRIPCION
                    sql = sql & " ORDER BY DESCRIPCION "
                Case 2 'CAMPO1
                    sql = sql & " ORDER BY CAMPO1 "
                Case 3 'CAMPO2
                    sql = sql & " ORDER BY CAMPO2 "
                Case 4 'CAMPO3
                    sql = sql & " ORDER BY CAMPO3 "
                Case 5 'CAMPO4
                    sql = sql & " ORDER BY CAMPO4 "
            End Select
            da = New SqlDataAdapter(sql, cnn)
            da.Fill(dt)
            Return dt
        Catch ex As Exception
            MsgBox(ex.ToString)
        Finally
            dt.Dispose()
        End Try
    End Function

    Public Shared Function NumeroaLetras(ByVal vnum As Decimal) As String

        Dim vnumero As String
        Dim vlongitud As Long
        Dim vagregar, vconta As Long
        Dim vgrupo1, vgrupo2, vgrupo3, vgrupo4, vdescrip As String
        Dim vgrup, vgrupo As String
        Dim vlongg, vbande, vconta2 As Long
        Dim vdecimal As Decimal

        vdecimal = vnum

        Dim UNIDAD(9)
        Dim DECENA(9)
        Dim DECENA2(15)
        Dim CENTENA(9)
        Dim AGREGADO(4)

        UNIDAD(1) = "UN "
        UNIDAD(2) = "DOS "
        UNIDAD(3) = "TRES "
        UNIDAD(4) = "CUATRO "
        UNIDAD(5) = "CINCO "
        UNIDAD(6) = "SEIS "
        UNIDAD(7) = "SIETE "
        UNIDAD(8) = "OCHO "
        UNIDAD(9) = "NUEVE "

        DECENA(1) = "DIEZ "
        DECENA(2) = "VEINTE "
        DECENA(3) = "TREINTA "
        DECENA(4) = "CUARENTA "
        DECENA(5) = "CINCUENTA "
        DECENA(6) = "SESENTA "
        DECENA(7) = "SETENTA "
        DECENA(8) = "OCHENTA "
        DECENA(9) = "NOVENTA "

        DECENA2(11) = "ONCE "
        DECENA2(12) = "DOCE "
        DECENA2(13) = "TRECE "
        DECENA2(14) = "CATORCE "
        DECENA2(15) = "QUINCE "

        CENTENA(1) = "CIENTO "
        CENTENA(2) = "DOSCIENTOS "
        CENTENA(3) = "TRESCIENTOS "
        CENTENA(4) = "CUATROCIENTOS "
        CENTENA(5) = "QUINIENTOS "
        CENTENA(6) = "SEISCIENTOS "
        CENTENA(7) = "SETECIENTOS "
        CENTENA(8) = "OCHOCIENTOS "
        CENTENA(9) = "NOVECIENTOS "

        AGREGADO(1) = ""
        AGREGADO(2) = "MIL "
        AGREGADO(3) = "MILLONES "
        'AGREGADO(4) = "BILLONES "
        AGREGADO(4) = "MIL "

        vnum = Int(vnum)
        vnumero = LTrim(Str(vnum))
        vlongitud = Len(vnumero)
        vagregar = 0

        vgrupo1 = "   "
        vgrupo2 = "   "
        vgrupo3 = "   "
        vgrupo4 = "   "

        vdescrip = ""

        Select Case vlongitud
            Case 1 To 3
                vagregar = 1
                vgrupo1 = vnumero
            Case 4 To 6
                vagregar = 2
                vgrupo2 = vnumero.Substring(0, vlongitud - 3)
                vgrupo1 = Right(vnumero, 3)
            Case 7 To 9
                vagregar = 3
                vgrupo3 = vnumero.Substring(0, vlongitud - 6)
                vgrupo2 = vnumero.Substring(vlongitud - 6, 3)
                vgrupo1 = Right(vnumero, 3)
            Case 10 To 12
                vagregar = 4
                vgrupo4 = vnumero.Substring(0, vlongitud - 9)
                vgrupo3 = vnumero.Substring(vlongitud - 9, 3)
                vgrupo2 = vnumero.Substring(vlongitud - 6, 3)
                vgrupo1 = Right(vnumero, 3)
        End Select

        vconta = vagregar

        Do While vconta > 0
            Dim prueba As String

            Select Case vconta
                Case Is = 4
                    vgrupo = vgrupo4
                Case Is = 3
                    vgrupo = vgrupo3
                Case Is = 2
                    vgrupo = vgrupo2
                Case Is = 1
                    vgrupo = vgrupo1
            End Select

            vlongg = Len(vgrupo)
            vbande = 0

            If Val(vgrupo) <> 0 Then
                vconta2 = vlongg
                Do While vconta2 > 0

                    Select Case vconta2
                        Case Is = 3
                            If Val(vgrupo) = 100 Then
                                vdescrip = vdescrip + "CIEN "
                                Exit Do
                            Else
                                vdescrip = vdescrip + CENTENA(Val(vgrupo.Substring(0, 1)))
                                If vgrupo.Substring(1, 2) = "00" Then
                                    Exit Do
                                End If
                            End If
                        Case Is = 2
                            If Val(vgrupo.Substring(vlongg - 2, 1)) <> 0 Then
                                If Val(vgrupo.Substring(vlongg - 2, 2)) > 10 And Val(vgrupo.Substring(vlongg - 2, 2)) < 16 Then
                                    vdescrip = vdescrip + DECENA2(Val(vgrupo.Substring(vlongg - 2, 2)))
                                    Exit Do
                                Else
                                    vdescrip = vdescrip + DECENA(Val(vgrupo.Substring(vlongg - 2, 1)))
                                    If vgrupo.Substring(vlongg - 1, 1) = "0" Then
                                        Exit Do
                                    End If
                                End If
                            Else
                                vbande = 1
                            End If
                        Case Is = 1
                            If Val(vgrupo) > 9 And vbande = 0 Then
                                vdescrip = vdescrip + "Y "
                            End If
                            If Val(vgrupo.Substring(vlongg - 1, 1)) = 1 And vconta = 1 Then
                                vdescrip = vdescrip + "UNO "
                            Else
                                vdescrip = vdescrip + UNIDAD(Val(vgrupo.Substring(vlongg - 1, 1)))
                            End If


                    End Select
                    vconta2 = vconta2 - 1

                Loop

                If vconta = 4 And Val(vgrupo) = 1 Then
                    vdescrip = vdescrip + "MIL "    ' "BILLON "
                Else
                    If vconta = 3 And Val(vgrupo) = 1 Then
                        vdescrip = vdescrip + "MILLON "
                    Else
                        vdescrip = vdescrip + AGREGADO(vconta)
                    End If
                End If
            End If
            vconta = vconta - 1

        Loop

        If vdecimal <> Int(vdecimal) Then
            vdecimal = (vdecimal - Int(vdecimal)) * 100
            vdecimal = Math.Round(vdecimal, 0)
            vdescrip = vdescrip + "CON " + AllTrim(Str(vdecimal)) + "/100"
        End If

        Return vdescrip

    End Function

    Public Shared Function AllTrim(ByVal MiCadena As String) As String
        Return MiCadena.Trim
    End Function

    Public Function MakeTableMIVA(ByRef mIva As DataTable) As DataTable
        Dim Entrar As Boolean
        Try
            If mIva.Columns.Count > 0 Then
                Entrar = False
            Else
                Entrar = True
            End If
        Catch ex As Exception
            Entrar = True
        End Try
        If Entrar = True Then
            mIva = New DataTable("IVA")
            'columna para las cuentas
            mIva = New DataTable("IVA")
            'columna para la CodigoIVA
            Dim colCodigo As DataColumn
            colCodigo = New DataColumn("Codigo", GetType(System.Int32))
            mIva.Columns.Add(colCodigo)
            'columna para la NumIVA
            Dim colNumIva As DataColumn
            colNumIva = New DataColumn("NumIVA", GetType(System.String))
            mIva.Columns.Add(colNumIva)
            'columna para la descripcion
            Dim colDescripcion As DataColumn
            colDescripcion = New DataColumn("Descripcion", GetType(System.String))
            mIva.Columns.Add(colDescripcion)
            'columna para la Importe del GRABADO
            Dim colImporte As DataColumn
            colImporte = New DataColumn("Importe", GetType(System.Decimal))
            mIva.Columns.Add(colImporte)
            'columna para la Impuesto del IVA
            Dim colImpuesto As DataColumn
            colImpuesto = New DataColumn("Impuesto", GetType(System.Decimal))
            mIva.Columns.Add(colImpuesto)
        End If
        Return mIva
    End Function

    Public Function validacion_codigo_dgtabla_dependiente(ByRef BotonGrabar As System.Windows.Forms.Button, ByRef textbox_codigo As System.Windows.Forms.TextBox, ByRef Text_descripcion As System.Windows.Forms.TextBox, ByVal nombre_campo_codigo As String, ByVal nombre_tabla As String, ByVal nombre_campo_descripcion As String, ByVal campo_buscado As String, ByVal codigo_empresa As String) As String
        ''
        ''
        'Cesar, 2005-06-10 Validacion para codigos!!!!
        Dim sentfuncion As New Funcion
        Dim Mensaje As String = "0"

        If BotonGrabar.Enabled = True And Not textbox_codigo.Text.Trim = "" Then
            textbox_codigo.Tag = sentfuncion.Validar_Tabla(nombre_campo_codigo, nombre_tabla, campo_buscado, textbox_codigo.Text, codigo_empresa)
            If textbox_codigo.Tag = 0 Then
                Mensaje = "Codigo No Existe!!!"
                Text_descripcion.Text = ""
                textbox_codigo.Focus()
            Else
                Text_descripcion.Text = sentfuncion.Descripcion_Tabla(nombre_campo_descripcion, nombre_tabla, campo_buscado, textbox_codigo.Text, codigo_empresa)
            End If
        Else
            Mensaje = "Debe cargar un codigo"
            textbox_codigo.Focus()
        End If
        If Mensaje.Trim.Length = 0 Then
            Mensaje = "0"
        End If
        Return Mensaje
    End Function

    Public Function EjecutarScript() As Boolean
        Dim direccionScript As String
        Dim texto As New RichTextBox

        ser = New BD.ABD
        cnn = ser.Abrir

        Try
            direccionScript = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly.Location) & "\SCRIPT.SQL"

            sql = ""

            'Verifica si existe el archivo
            If System.IO.File.Exists(direccionScript) = False Then
                Return False
            Else
                texto.LoadFile(direccionScript, RichTextBoxStreamType.PlainText)
                sql = texto.Text

                If sql.Equals("") = False Then
                    If MsgBox("¿Desea ejecutar este SCRIPT?" & vbCrLf & _
                    sql, MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Función") = MsgBoxResult.Yes Then
                        ser.Abrir(cnn)

                        cmd = New SqlCommand
                        cmd.Connection = cnn
                        cmd.CommandText = sql

                        cmd.ExecuteNonQuery()

                        texto.Dispose()
                        System.IO.File.Delete(direccionScript)

                        Return True
                    Else
                        Return False
                    End If
                Else
                    Return False
                End If
            End If
        Catch e As Exception
            'MsgBox(e.ToString)
            Return False
        Finally
            ser.Cerrar(cnn)
        End Try
    End Function

    'Devolver la Fecha del Servidor
    Public Function FunFechaServidor() As String
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "select convert(varchar(10), getdate(), 103) as valor "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("valor")
            Catch
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
    Public Function Buscar_Contado(ByVal nombre_campo As String, ByVal nombre_tabla As String, ByVal campo_buscado As String, ByVal variable_ingresada As String, ByVal codigo_empresa As String) As Long
        ser = New BD.ABD
        cnn = ser.Abrir
        sql = ""
        sql = "SELECT MAX(" & nombre_campo & ") AS maximo FROM " & nombre_tabla & " where " & campo_buscado & " = '" & variable_ingresada & "' and codempresa = " & codigo_empresa & " "
        Try
            cmd = New SqlCommand(sql, cnn)
            dr = cmd.ExecuteReader()
            Try
                dr.Read()
                Return dr("maximo")
            Catch ex As Exception
                'MsgBox(ex.ToString)
                Return 0
            Finally
                dr.Close()
                ser.Cerrar(cnn)
                ser.Cerrar(cnn)
            End Try
        Finally
        End Try
    End Function
End Class