Option Explicit
Public mobj_cseguridad As DB_SE_MANTENIMIENTOS.c_seguridad
Public MOBJ_CMONEDA As DB_MA_MANTENIMIENTOS.C_MONEDA
Public mobj_cdocumento As DB_MA_MANTENIMIENTOS.C_DOCUMENTO
Public mobj_cventasgen As DB_OP_FACTURACION.C_VENTASGENERAL
Public MOBJ_CVENTASCSTORE As DB_OP_FACTURACION.C_VENTASCSTORE
Public Mobj_Correlativo As DB_CORRELATIVO.C_Correlativos
'--------------------------------------------------------------------------
'datos del clientes
Public mstr_monedacliente
Public mint_limitecredito
Public mbln_afectoimpuesto
'--------------------------------------------------------------------------
Public pb_editar As Boolean
Public pb_agregar As Boolean
Public pb_primerregistro As Boolean
Public pb_ultimoregistro As Boolean
Public pbderecho_agregar As Boolean
Public pbderecho_consultar As Boolean
Public pbderecho_editar As Boolean
Public pbderecho_borrar As Boolean
Public pbderecho_imprimir As Boolean
Public pbderecho_EMITIR As Boolean
Public pbderecho_ANULAR As Boolean
Public pb_tiposcreen As String

Public GrecibeUbicacion As BookmarkEnum
Public GrecibeColumnaID As String
Public GrecibeColumnaOpcional As String
Public GrecibeColumnaOpcional2 As String
Public GrecibeColumnaOpcional3 As String

Public grscliente As ADODB.Recordset

Private WithEvents MrsGrilla As ADODB.Recordset
Public rs_prod As ADODB.Recordset

Public mbln_editandoproducto As Boolean
Public MBLN_INICIO  As Boolean

Public mbln_articuloencontrado As Boolean
Public MintTipoCliente As Integer
Public GstrTipoClienteDescr As String
Public GdblLimiteCredito As Double
Public GdblDeudaVigente As Double
Public GdblSaldoDisponible As Double
Public GstrIddeEstado As String
Public GstrDescrEstado As String
Public GstrTipodeCambio As String
Public gdblMontoTipoCambio  As Double

Public GintDiasdeGracia As Integer
Public GdblMontoExtra As Double
Public GblnconPlacas As Boolean
Public GblnAfecto As Boolean
Public GStrNumeroPlaca As String
Public GintNumeroVale As Double
Public MBlndatosasignados As Boolean
Public mbln_cabezeraprotegida As Boolean

Public LdblTotalBase As Double
Public LdblTotalExt As Double
Public LDblIGVBase As Double
Public LDblIGVExt As Double
Public LDblSubAfectoBase As Double
Public LDblSubAfectoExt As Double
Public LDblNoAfectoBase As Double
Public LDblNoAfectoExt As Double

Public LDblTOTALNOTAFFECTPEN As Double
Public LDblTOTALNOTAFFECTUSD As Double
Public LDblTOTRETURNEDPEN As Double
Public LDblTOTRETURNEDUSD As Double
Public LDblTOTCASHPEN As Double
Public LDblTOTCASHUSD As Double

Public pdbl_documentobuscado As Double
Public pbln_consulta As Boolean
Public pbln_errorcab As Boolean


Private Sub cmd_bcliente_Click()
  Dim LArrayBusqueda(1 To 4, 1 To 3) As Variant
  LArrayBusqueda(1, 1) = "CUSTIDSS"
  LArrayBusqueda(1, 2) = "Id Cliente"
  LArrayBusqueda(1, 3) = 1500
  LArrayBusqueda(2, 1) = "CUSTNAME"
  LArrayBusqueda(2, 2) = "Cliente"
  LArrayBusqueda(2, 3) = 4000
  LArrayBusqueda(3, 1) = "TAXREGNBR"
  LArrayBusqueda(3, 2) = "R.U.C."
  LArrayBusqueda(3, 3) = 1800
  LArrayBusqueda(4, 1) = "ADDR1"
  LArrayBusqueda(4, 2) = "DIRECCION"
  LArrayBusqueda(4, 3) = 2700
  GrecibeUbicacion = 0
  GrecibeColumnaID = Empty
  GrecibeColumnaOpcional = Empty
  GrecibeColumnaOpcional2 = Empty
  
  fbusquedasventas.GObtenerRegistros mobj_cventasgen.ListarClientesAyuda, LArrayBusqueda, 4, 2, 11000, 5970, 700, 700
  fbusquedasventas.Show vbModal
   
If GrecibeUbicacion <> 0 Then
    TXT_IDCLIENTE = GrecibeColumnaID
    'txt_tipodoc.Text = "FACTURA"
    txt_razonsocial.Text = GrecibeColumnaOpcional
    txt_direccion.Text = GrecibeColumnaOpcional3
    If pasar_ruc(GrecibeColumnaOpcional2) Then
        txt_ruc.Text = Trim(GrecibeColumnaOpcional2)
    Else
        txt_ruc.Text = ""
    End If
    txt_ruc.SetFocus
End If
End Sub

Private Sub cmd_bticket_Click()

End Sub

Private Sub cmd_Cancelar_Click()
If MsgBox("Esta Seguro de Cancelar la Venta Actual", vbYesNo, "Precaucion") = vbYes Then
    MBLN_INICIO = True
    Call borrar_valores
    Call INICIO
    Call enfoque_inicial
End If
End Sub

Private Sub cmd_efectivo_Click()
If Val(txt_total.Text) > 0 Then
    fpagoefectivo.LBL_MONEDAT.Caption = TXT_MONEDATOTAL.Text
    fpagoefectivo.LBL_MONEDAV.Caption = TXT_MONEDATOTAL.Text
    fpagoefectivo.LBL_MONTOV.Caption = "0"
    fpagoefectivo.txt_tc.Text = txt_tcambio.Text
    fpagoefectivo.lbl_pen = GstrSimboloMonedaBase
    fpagoefectivo.lbl_usd = GstrSimboloMonedaExt
    
    If GstrMonedaLimiteCredito = GstrCodMonedaBase Then     ' GRABAR EN MONEDA BASE Y CALCULAR MONEDA EXTRANJERA
        fpagoefectivo.txt_esoles.Text = LdblTotalBase
        fpagoefectivo.LBL_MONTOT.Caption = LdblTotalBase
    Else
        fpagoefectivo.txt_edolares.Text = LdblTotalExt
        fpagoefectivo.LBL_MONTOT.Caption = LdblTotalExt
    End If

    fpagoefectivo.Show vbModal
    
    If gbln_ventaefectuada Then   ' si se efectuo el pago, grabar y emitir
        
        Call GRABAR_VENTA(GC_OTROS)
        
    End If
    
End If

End Sub
Private Sub cmd_recupera_Click()
If GBlnpermitegrabartrans Then
    gdouloadsales = 0
    txtArticulo.SetFocus        'PARA EVITAR QUE VALIDE CODIGO CLIENTE
    frecuperartransaccion.Show vbModal
    If gdouloadsales <> 0 Then  'se eligio restaurar alguna transaccion
        MBLN_INICIO = False
        'NO SE DEBE PODER MODIFICAR LA CABEZERA
        pdbl_correlativo = gdouloadsales
        Call CARGACABEZERALOADSALE(gdouloadsales)
        Call valida_codigocliente("RT")     'obtener moneda, tipo cambio, tipo, etc
        Call valida_RUCcliente("RT")
        Call ESTADO_CABEZERA(False)         ' proteger la cabezera
        Call CARGAGRILLA(gdouloadsales)     'mostrar los datos grabados en la cabezera
        If gstrtipoventas <> "A" Then
            Call FORMATONBRDOCUMENT         'darle formato al numero de documento
        End If
        txt_NBRDOCUMENT.Enabled = False
        txtArticulo.SetFocus
        'MsgBox "Transaccion Recuperada", vbExclamation, "OK"
        ' AL CERRAR TRANSACCION VOLVER A CONSULTAR EL NRO.DE DOCUMENTO
    End If
Else
    MsgBox "No Esta Activada la Grabacion de Transacciones"
End If
End Sub
Private Sub cmd_salir_Click()
If Val(txt_total.Text) > 0 Then
    If MsgBox("Esta Seguro de Salir " + Chr(13) + "Los Cambios hechos se perderan ", vbYesNo, "Precaucion") = vbNo Then
        Exit Sub
    End If
End If
Call cierra_objetos
Unload Me
End Sub

Private Sub cmd_salvar_Click()
Dim dbl_monto As Double
If GBlnpermitegrabartrans Then
    dbl_monto = Val(txt_total.Text)
    If dbl_monto > 0 Then
        mobj_cventasgen.salvartransaccion pdbl_correlativo, dbl_monto
        Call borrar_valores
        Call INICIO
    Else
        MsgBox "No hay Registros para Salvar", vbExclamation, "Atencion"
    End If
Else
    MsgBox "No Esta Activada la Grabacion de Transacciones", vbExclamation, "Atencion"
End If
End Sub
Private Sub cmd_tarjeta_Click()
If Val(txt_total.Text) > 0 Then
    fpagotarjetas.lbl_moneda.Caption = TXT_MONEDATOTAL.Text
    fpagotarjetas.lbl_monto.Caption = txt_total.Text
    fpagotarjetas.txt_tcambio.Text = txt_tcambio.Text
    fpagotarjetas.dtc_monedat.BoundText = GstrMonedaLimiteCredito
    fpagotarjetas.Show vbModal
    If gbln_ventaefectuada Then   ' si se efectuo el pago, grabar y emitir
        Call GRABAR_VENTA(GC_TARJETACRED)
    End If
End If
End Sub
Private Sub cmdBuscaArticulo_Click()
If mbln_editandoproducto Then
    Exit Sub
End If
'If ExisteTipoCambio = False Then
'        Exit Sub
'    End If
     GrecibeUbicacion = 0
     GrecibeColumnaID = Empty
     GrecibeColumnaOpcional = Empty
     
     Dim ArrayBusqueda(1 To 5, 1 To 3) As Variant
     Dim blnExiste As Boolean
     ArrayBusqueda(1, 1) = "id"
     ArrayBusqueda(1, 2) = "InvtidSku"
     ArrayBusqueda(1, 3) = 1000
     ArrayBusqueda(2, 1) = "Descripcion"
     ArrayBusqueda(2, 2) = "Descripción "
     ArrayBusqueda(2, 3) = 4000
     ArrayBusqueda(3, 1) = "stock"
     ArrayBusqueda(3, 2) = "Stock"
     ArrayBusqueda(3, 3) = 1000
     ArrayBusqueda(4, 1) = "descrmoney"
     ArrayBusqueda(4, 2) = "Moneda"
     ArrayBusqueda(4, 3) = 700
     ArrayBusqueda(5, 1) = "precio"
     ArrayBusqueda(5, 2) = "Precio"
     ArrayBusqueda(5, 3) = 1000

     If gstrtipoventas = "A" Then
        fbusquedaarticulocstore.GObtenerRegistros mobj_cventasgen.Listarproductosventas(GstrSiteProce, True), ArrayBusqueda, 5, 2, 8600, 5970, 700, 700
     Else
         fbusquedaarticulocstore.GObtenerRegistros mobj_cventasgen.Listarproductosventas(GstrSiteProce, False), ArrayBusqueda, 5, 2, 8600, 5970, 700, 700
     End If
    fbusquedaarticulocstore.Show vbModal
     If GrecibeUbicacion <> 0 Then
         txtArticulo.Text = GrecibeColumnaID
         txtArticulo.SetFocus
         Call validaarticulo
      End If
End Sub

Private Sub CTN_SUBTOTAL_GotFocus()
If Val(ctnprecio.Text) = 0 Or Len(Trim(txtArticulo.Text)) = 0 Then
    MsgBox "Debe ingresar un producto con precio", vbCritical, "Error"
    txtArticulo.SetFocus
End If

If rs_prod!classid <> GstrCategoriaFuels Then
    CTN_SUBTOTAL.Enabled = False
    MsgBox "El Producto debe ser un combustible", vbExclamation, "Atencion"
    txtArticulo.SetFocus
Else
   CTN_SUBTOTAL.Enabled = True
   CTN_SUBTOTAL.BackColor = vbCyan
End If
End Sub

Private Sub CTN_SUBTOTAL_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
 'calcular la cantidad
   Call grabarregistro
End If
If KeyCode = vbKeyUp Then
    txtArticulo.SetFocus
End If
End Sub

Private Sub CTN_SUBTOTAL_KeyUp(KeyCode As Integer, Shift As Integer)
Dim LDOU_TOT As Double
LDOU_TOT = Val(CTN_SUBTOTAL.Text)

ctnUnidades.Text = Str(Round(LDOU_TOT / Val(ctnprecio.Text), GintDecStock))
End Sub

Private Sub CTN_SUBTOTAL_LostFocus()
 CTN_SUBTOTAL.BackColor = vbWhite
End Sub

Private Sub ctnUnidades_GotFocus()
If Len(Trim(txtArticulo.Text)) = 0 Then
    MsgBox "Ingrese Primero un Articulo", vbExclamation, "Atencion"
    txtArticulo.SetFocus
Else
    If Not mbln_articuloencontrado Then
        MsgBox "Producto Incorrecto", vbExclamation, "Atencion ."
        txtArticulo.SetFocus
    Else
        ctnUnidades.BackColor = vbCyan
    End If
End If
End Sub
Private Sub ctnUnidades_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
    If Val(ctnUnidades.Text) <= 0 Then
        MsgBox "Debe Ingresar Una cantidad", vbExclamation, "Atencion"
        ctnUnidades.SetFocus
        Exit Sub
    End If

    If rs_prod!classid <> GstrCategoriaFuels Then
        If Val(Int(ctnUnidades.Text)) < Val(ctnUnidades.Text) Then
            MsgBox "No Puede Despachar cantidades con Decimales", vbExclamation, "Atencion"
            ctnUnidades.SetFocus
            Exit Sub
        End If
    End If

    If Val(ctnUnidades.Text) > rs_prod!stock And (Not GIntPermiteStkNegativo) Then
        MsgBox "Cantidad Mayor al stock Disponible", vbExclamation, "Atencion"
        ctnUnidades.SetFocus
        Exit Sub
   Else
      Call grabarregistro
    End If
End If
If KeyCode = vbKeyUp Then
    txtArticulo.SetFocus
End If
End Sub
Private Sub ctnUnidades_KeyPress(KeyAscii As Integer)

If Chr(KeyAscii) = "-" Then
    KeyAscii = 0
End If

End Sub

Private Sub ctnUnidades_KeyUp(KeyCode As Integer, Shift As Integer)
Dim LDOU_UNI As Double
LDOU_UNI = Val(ctnUnidades.Text)
CTN_SUBTOTAL.Text = Str(Round(LDOU_UNI * Val(ctnprecio.Text), GintDecPrecio))
End Sub

Private Sub ctnUnidades_LostFocus()
ctnUnidades.BackColor = vbWhite
End Sub

Private Sub DBDETALLE_DblClick()
    If Not MrsGrilla.EOF Or MrsGrilla.RecordCount > 0 Then
        Call editar_producto
        ctnUnidades.SetFocus
    End If
End Sub
Sub editar_producto()
        mbln_articuloencontrado = True
        mbln_editandoproducto = True
        txtArticulo.Text = MrsGrilla!INVTIDSKU
        lblDescripcion.Caption = MrsGrilla!DESCRINVENTORY
        ctnprecio.Text = MrsGrilla!SLSPRICESALE
        ctnUnidades.Text = MrsGrilla!QTY
        txtArticulo.Locked = True
        Call validaarticulo
        End Sub
Private Sub DBDETALLE_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then        'MODIFICAR
    If Not MrsGrilla.EOF Or MrsGrilla.RecordCount > 0 Then
        Call editar_producto
        KeyCode = vbKeyTab
        txtArticulo.SetFocus
    End If
End If
If KeyCode = vbKeyF7 Then
   Call cmd_efectivo_Click
End If
If KeyCode = vbKeyF3 Then   'ELIMINAR
    If Not MrsGrilla.EOF Or MrsGrilla.RecordCount > 0 Then
      If MsgBox("Seguro que desea Eliminar el Registro No." + Str(MrsGrilla.AbsolutePosition), vbYesNo + vbQuestion, "Advertencia") = vbYes Then
          MOBJ_CVENTASCSTORE.eliminarcstoreDetalle pdbl_correlativo, MrsGrilla!lin
          Call CARGAGRILLA(pdbl_correlativo)
          If MrsGrilla.RecordCount = 0 Then ' NO HAY REGISTROS
            ESTADO_CABEZERA (True)  'ACTIVAR CABEZERA
            txtArticulo.SetFocus
          End If
      End If
     End If
End If
If KeyCode = vbKeyF8 Then
    Call cmd_efectivo_Click
End If

End Sub

Private Sub dtc_serie_Change()
txt_NBRDOCUMENT.Text = mobj_cventasgen.obtenernrodocumento(dtc_tdocumento.BoundText, dtc_serie.BoundText, GstrSiteProce)
End Sub

Private Sub dtc_serie_GotFocus()
dtc_serie.BackColor = vbCyan
Call valida_cabezera1
End Sub

Private Sub dtc_serie_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Or KeyCode = vbKeyDown Then
    txt_NBRDOCUMENT.Text = mobj_cventasgen.obtenernrodocumento(dtc_tdocumento.BoundText, dtc_serie.BoundText, GstrSiteProce)
    txt_NBRDOCUMENT.SetFocus
End If
If KeyCode = vbKeyUp Then
    dtc_tdocumento.SetFocus
End If
End Sub

Private Sub dtc_serie_LostFocus()
If dtc_tdocumento.Text <> "" Then
    txt_NBRDOCUMENT.Text = mobj_cventasgen.obtenernrodocumento(dtc_tdocumento.BoundText, dtc_serie.BoundText, GstrSiteProce)
End If
dtc_serie.BackColor = vbWhite
End Sub

Private Sub dtc_tdocumento_Change()
txt_tipodoc.Text = dtc_tdocumento.Text
TXT_IDCLIENTE.Text = ""
txt_ruc.Text = ""
txt_direccion.Text = ""
txt_razonsocial.Text = ""
'buscar numeros de serie para ese tipo de documento
Call CargaDataCombo(dtc_serie, mobj_cventasgen.obtenerseriesdoc(dtc_tdocumento.BoundText, GstrSiteProce), "nbrseries", "nbrseries")
txt_NBRDOCUMENT.Text = mobj_cventasgen.obtenernrodocumento(dtc_tdocumento.BoundText, dtc_serie.BoundText, GstrSiteProce)
End Sub
Private Sub dtc_tdocumento_GotFocus()
dtc_tdocumento.BackColor = vbCyan
End Sub

Private Sub dtc_tdocumento_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Or KeyCode = vbKeyDown Then
   dtc_serie.SetFocus
End If
End Sub

Private Sub dtc_tdocumento_LostFocus()
dtc_tdocumento.BackColor = vbWhite
End Sub

Private Sub dtp_fecha_GotFocus()
Call valida_cabezera1
End Sub

Private Sub dtp_fecha_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
    txtArticulo.SetFocus
End If
End Sub

Private Sub dtp_fecha_LostFocus()
Call valida_cabezera1
End Sub

Private Sub dtp_fechapro_GotFocus()
Call valida_cabezera1
End Sub

Private Sub dtp_fechapro_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Then
    dtp_fecha.SetFocus
End If
End Sub

Private Sub dtp_fechapro_LostFocus()
Call valida_cabezera1
End Sub
Private Sub Form_Activate()
If pbderecho_consultar = False Then
    Unload Me
End If
Call enfoque_inicial

MBLN_INICIO = False
End Sub
Private Sub enfoque_inicial()
If MBLN_INICIO Then
    If gstrtipoventas = "A" Then
        TXT_IDCLIENTE.SetFocus
    Else
        dtc_tdocumento.SetFocus
    End If
    MBLN_INICIO = False
End If
End Sub
Private Sub Form_Load()
'GstrMonedaLimiteCredito = ""
Call gseguridad(Me)
If pbderecho_consultar Then
    Call instancia_objetos
Else
    MsgBox ("No tiene Derechos de Consultar en este formulario")
End If
Me.Width = 11800
Me.Height = 8520

dtp_fecha.Value = GDatFechaProcesoVentas
dtp_fechapro.Value = GDatFechaProceso
Me.Caption = Me.Caption + IIf(gstrtipoventas = "A", "  Emision de Tickets    ", " Ingreso Documentos Manuales") + Space(55) + GstrPuntodeVenta + " (" + GstrTerminal + ") " + CStr(GDatFechaProceso)

Call ObtenerConfiguracionTicket

CTN_SUBTOTAL.PermitirNegativos = False
CTN_SUBTOTAL.Enteros = 11
CTN_SUBTOTAL.Decimales = 2
CTN_SUBTOTAL.Enabled = False

ctnUnidades.PermitirNegativos = False
ctnUnidades.Decimales = GintDecStock
ctnUnidades.Enteros = 9

ctnprecio.PermitirNegativos = False
ctnprecio.Enteros = 9
ctnprecio.Decimales = GintDecPrecio
ctnprecio.Enabled = False

ctnprecio.BackColor = lblDescripcion.BackColor
txt_vendedor.Text = mobj_cventasgen.obtenernombrevendedor(GstrCodigoVENDEDOR)
                                    
Call CargaDataCombo(dtc_tdocumento, mobj_cventasgen.ListarDocumentosventas(GstrSiteProce), "DOCTYPEID", "DESCR")

Call INICIO
End Sub
Sub INICIO()

    Call ESTADO_CABEZERA(True)
    'GstrTipodeCambio
    pdbl_correlativo = Mobj_Correlativo.ObtenerCorrelativo(GCUSERID)
    GstrTipodeCambio = GstrTipoCambioVentas
    If gstrtipoventas = "A" Then
        dtp_fecha.Enabled = False
        dtp_fechapro.Enabled = False
        txt_NBRDOCUMENT.Enabled = False
        txt_NBRDOCUMENT.Text = ""
        dtc_serie.Enabled = False
        'dtc_tdocumento.BoundText = mobj_cventasgen.obtenertipoticket
        
        txt_tipodoc.Text = "TICKET BOLETA"
        txt_NBRDOCUMENT.Text = CStr(mobj_cventasgen.obtenernroticket(GstrPuntodeVenta, txt_tipodoc.Text))
        dtc_tdocumento.Enabled = False
        dtc_tdocumento.Visible = False
        lbl_tdocumento.Visible = False
        txt_NBRDOCUMENT.MaxLength = 10
        mnu_op_cierrex.Visible = True
        mnu_op_cierrez.Visible = True
    Else
        dtp_fecha.Enabled = True
        dtp_fechapro.Enabled = True
        If gblnsaltarcorrelativo Then
            txt_NBRDOCUMENT.Enabled = True
            txt_NBRDOCUMENT.Locked = True
        Else
            txt_NBRDOCUMENT.Enabled = True
            txt_NBRDOCUMENT.Locked = False
        End If
        lbl_tdocumento.Visible = True
        dtc_tdocumento.Visible = True
        dtc_tdocumento.Enabled = True
        dtc_tdocumento.Text = ""
        dtc_serie.Enabled = True
        txt_NBRDOCUMENT.MaxLength = 7
        dtc_tdocumento.BoundText = mobj_cventasgen.obtenertipoboleta
        mnu_op_cierrex.Visible = False
        mnu_op_cierrez.Visible = False
    End If
    'INDICA QUE EL FORMULARIO ACABA DE INCIARSE
    dtp_fecha.Value = Date
    TXT_MONEDATOTAL.Text = GstrSimboloMoneda    'moneda de la caja cuando se inicia
    MBLN_INICIO = True
    mbln_editandoproducto = False
    gbln_ventaefectuada = False
    mbln_articuloencontrado = False
    dtp_fechapro.Value = GDatFechaProceso
    dtp_fecha.Value = GDatFechaProcesoVentas
    Call Datosclientepordefecto
    txt_tcambio.Text = gdblMontoTipoCambio
    Call CARGAGRILLA(pdbl_correlativo)
End Sub
Private Sub mnu_op_buscar_Click()
Call busquedaventas
End Sub
Private Sub mnu_op_cashdrop_Click()
F_CASHDROP.Show vbModal
End Sub

Private Sub mnu_pagos_efectivo_Click()
Call cmd_efectivo_Click
End Sub
Private Sub mnu_pagos_restaurar_Click()
Call cmd_recupera_Click
End Sub
Private Sub mnu_pagos_salvar_Click()
Call cmd_salvar_Click
End Sub
Private Sub mnu_pagos_Tarjeta_Click()
Call cmd_tarjeta_Click
End Sub
Sub instancia_objetos()
Set mobj_cseguridad = New DB_SE_MANTENIMIENTOS.c_seguridad
Set MOBJ_CMONEDA = New DB_MA_MANTENIMIENTOS.C_MONEDA
Set mobj_cventasgen = New DB_OP_FACTURACION.C_VENTASGENERAL
Set MOBJ_CVENTASCSTORE = New DB_OP_FACTURACION.C_VENTASCSTORE
Set Mobj_Correlativo = New DB_CORRELATIVO.C_Correlativos
Set mobj_cdocumento = New DB_MA_MANTENIMIENTOS.C_DOCUMENTO
End Sub

Private Sub mnu_pagosanular_Click()
 Call anular_ticket
End Sub

Private Sub mnu_pagoseliminar_Click()
Call eliminar_ticket
End Sub

Private Sub txt_direccion_GotFocus()
txt_direccion.BackColor = vbCyan
Call valida_cabezera1
Call valida_cabezera2
Call valida_cabezera3
End Sub

Private Sub txt_direccion_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDown Or KeyCode = 13 Then
    KeyCode = 0
    If gstrtipoventas = "A" Then
        txtArticulo.SetFocus
    Else
        KeyCode = 0
        dtp_fechapro.SetFocus
    End If
End If
If KeyCode = vbKeyUp Then
    txt_razonsocial.SetFocus
End If
End Sub

Private Sub txt_direccion_KeyPress(KeyAscii As Integer)
KeyAscii = GBloqueaCaracter(KeyAscii)
End Sub

Private Sub txt_direccion_LostFocus()
txt_direccion.BackColor = vbWhite
End Sub

Private Sub txt_docreferencia_GotFocus()
txt_docreferencia.BackColor = vbCyan
End Sub

Private Sub TXT_IDCLIENTE_GotFocus()
TXT_IDCLIENTE.BackColor = vbCyan
Call valida_cabezera2
End Sub

Private Sub TXT_IDCLIENTE_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = 13 Or KeyCode = vbKeyDown Then
    Call valida_codigocliente("KD")
End If
If KeyCode = vbKeyUp And gstrtipoventas = "M" Then
    txt_NBRDOCUMENT.SetFocus
End If
If KeyCode = vbKeyF2 Then
    Call cmd_bcliente_Click
End If
End Sub

Private Sub TXT_IDCLIENTE_KeyPress(KeyAscii As Integer)
 KeyAscii = GBloqueaCaracter(KeyAscii)
End Sub

Private Sub TXT_IDCLIENTE_LostFocus()
'Call valida_codigocliente("LF")
TXT_IDCLIENTE.BackColor = vbWhite

End Sub

Private Sub txt_NBRDOCUMENT_GotFocus()
txt_NBRDOCUMENT.BackColor = vbCyan
Call valida_cabezera1
End Sub

Private Sub txt_NBRDOCUMENT_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDown Or KeyCode = 13 Then
    Call valida_NUMERODOCUMENTO("KD")
End If
If KeyCode = vbKeyUp Then
    dtc_serie.SetFocus
End If

If KeyCode = vbKeyEscape Then
    CMD_CANCELAR.SetFocus
End If

End Sub

Private Sub txt_NBRDOCUMENT_KeyPress(KeyAscii As Integer)
KeyAscii = GBloqueanonumeros(KeyAscii)
End Sub

Private Sub txt_NBRDOCUMENT_LostFocus()
txt_NBRDOCUMENT.BackColor = vbWhite
Call FORMATONBRDOCUMENT
End Sub
Private Sub txt_razonsocial_GotFocus()
txt_razonsocial.BackColor = vbCyan
Call valida_cabezera1
Call valida_cabezera2
Call valida_cabezera3
End Sub

Private Sub txt_razonsocial_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDown Or KeyCode = 13 Then
    If gstrtipoventas = "A" Then
        If txt_tipodoc.Text = "TICKET FACTURA" And Len(txt_razonsocial.Text) = 0 Then
            MsgBox "Debe Ingresar una Razon social", vbExclamation, "Atencion"
        Else
            txt_direccion.SetFocus
        End If
    Else
        If dtc_tdocumento.BoundText = mobj_cventasgen.obtenertipofactura And Len(txt_razonsocial.Text) = 0 Then
            MsgBox "Debe Ingresar una Razon social", vbExclamation, "Atencion"
        Else
            txt_direccion.SetFocus
        End If
    End If
End If
If KeyCode = vbKeyUp Then
    If Len(Trim(txt_ruc.Text)) > 0 Then
        txt_ruc.SetFocus
    Else
        TXT_IDCLIENTE.SetFocus
    End If
End If
End Sub

Private Sub txt_razonsocial_KeyPress(KeyAscii As Integer)
KeyAscii = GBloqueaCaracter(KeyAscii)
End Sub

Private Sub txt_razonsocial_LostFocus()
If txt_tipodoc.Text = "TICKET FACTURA" And Len(txt_razonsocial.Text) = 0 Then
    MsgBox "Debe Ingresar una Razon social", vbExclamation, "Atencion"
    txt_razonsocial.SetFocus
Else
    txt_razonsocial.BackColor = vbWhite
End If
End Sub

Private Sub txt_ruc_GotFocus()
txt_ruc.BackColor = vbCyan
Call valida_cabezera1
Call valida_cabezera2
End Sub

Private Sub txt_ruc_KeyDown(KeyCode As Integer, Shift As Integer)
If KeyCode = vbKeyDown Or KeyCode = 13 Then
    Call valida_RUCcliente("KD")
End If
If KeyCode = vbKeyUp Then
    TXT_IDCLIENTE.SetFocus
End If
End Sub

Private Sub txt_ruc_KeyPress(KeyAscii As Integer)
 KeyAscii = GBloqueanonumeros(KeyAscii)
End Sub

Private Sub txt_ruc_LostFocus()
txt_ruc.BackColor = vbWhite
End Sub

Private Sub txtArticulo_GotFocus()
Dim DOCTYPEID As String
Dim NBRDOCUMENT As Double

Call valida_cabezera1
If Not pbln_errorcab Then
    Call valida_cabezera2
End If
If Not pbln_errorcab Then
    Call valida_cabezera3
End If
  
If pbln_errorcab Then
    Exit Sub
End If

If gstrtipoventas = "A" Then
    DOCTYPEID = mobj_cventasgen.obtenertipoticket
    NBRDOCUMENT = Val(txt_NBRDOCUMENT.Text)
Else
    DOCTYPEID = dtc_tdocumento.BoundText
    NBRDOCUMENT = Val(dtc_serie.BoundText + txt_NBRDOCUMENT.Text)
End If

If mobj_cventasgen.existedocumento(DOCTYPEID, NBRDOCUMENT, GstrSiteProce) Then
    MsgBox "Documento Ya Existe" + Chr(13) + "Modifique el Numero de Documento", vbExclamation, "Datos Incorrectos"
    Exit Sub
End If

If (Not mbln_cabezeraprotegida) And MrsGrilla.RecordCount = 0 Then    ' si la cabezera esta desprotegida
    Call GRABAR_CABEZERA_TEMPORAL       'grabar o actualizar los datos
End If                                  'solo se actualiza si no hay registros

If MrsGrilla.RecordCount = 1 Then ' HAY ALGUN REGISTROS
    ESTADO_CABEZERA (False)  'DESACTIVAR CABEZERA
End If

txtArticulo.BackColor = vbCyan
End Sub
Private Sub txtArticulo_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbKeyDown Or KeyCode = 13 Then
    Call validaarticulo
End If
If KeyCode = vbKeyUp Then
    If Not mbln_cabezeraprotegida Then
        txt_direccion.SetFocus
    Else
        DBDETALLE.SetFocus
    End If
End If
If KeyCode = vbKeyF2 Then
    Call cmdBuscaArticulo_Click
End If
End Sub
Private Sub txtArticulo_KeyPress(KeyAscii As Integer)
 KeyAscii = GBloqueaCaracter(KeyAscii)
End Sub

Private Sub txtArticulo_LostFocus()
txtArticulo.BackColor = vbWhite
End Sub

Private Sub valida_codigocliente(STRID As String)
Dim lsid As String
Dim I As Integer
GblnAfecto = True
lsid = Trim(TXT_IDCLIENTE.Text)
'---------------------------------------------------
If gstrtipoventas = "A" Then         'VENTA AUTOMATICA
    If Len(lsid) = 0 Then
        txt_ruc.Text = ""
        Call valida_RUCcliente("CC")
        If STRID = "KD" Then
            txt_razonsocial.SetFocus
        End If
        Call Datosclientepordefecto
        txt_tcambio.Text = gdblMontoTipoCambio
    Else
       Set grscliente = mobj_cventasgen.ListarDatosdeClienteFactura(lsid)
       If grscliente.EOF Then  'codigo de cliente no existe
            'ingresar datos
            If pasar_ruc(lsid) Then
                txt_ruc.Text = TXT_IDCLIENTE.Text
            Else
                txt_ruc.Text = ""
            End If
            txt_razonsocial.Text = ""
            txt_direccion.Text = ""
            If STRID = "KD" Then
                txt_ruc.SetFocus
            End If
            Call Datosclientepordefecto
            txt_tcambio.Text = gdblMontoTipoCambio
        Else
            Call GAsignarDatosdeCliente
            If STRID = "KD" Or STRID = "LF" Then    ' SI ES KEYDOWN O LOSTFOCUS ASIGNAR DIRECCION
                If pasar_ruc(grscliente!ruc) Then
                    txt_ruc.Text = Trim(grscliente!ruc)       'SI SE ESTA RESTAURANDO el documentoNO ASIGNAR
                Else
                    txt_ruc.Text = ""
                End If
            txt_razonsocial.Text = grscliente!RAZONSOCIAL
            txt_direccion.Text = grscliente!DIRECCION
            End If
            txt_tcambio.Text = gdblMontoTipoCambio
            'llenar datos obtenidos del recordset
            If STRID = "KD" Then
                txt_ruc.SetFocus
            End If
        End If
    End If
'---------------------------------------------------
Else         'VENTA MANUAL --------------------------------
    If Len(lsid) = 0 Then
        'ES MANUAL, SE ESCOGIO FACTURA Y NO INGRESO CODIGO
        If dtc_tdocumento.BoundText = mobj_cventasgen.obtenertipofactura Then
            MsgBox "Debe ingresar Codigo Cliente", vbExclamation, "Error"
        Else
            If STRID = "KD" Then
                txt_razonsocial.SetFocus
            End If
        End If
        Call Datosclientepordefecto
        txt_tcambio.Text = gdblMontoTipoCambio
    Else    'si ingreso codigo, pasar a ruc
    Set grscliente = mobj_cventasgen.ListarDatosdeClienteFactura(lsid)
       If grscliente.EOF Then  'codigo de cliente no existe
            'ingresar datos
            If pasar_ruc(lsid) Then
                txt_ruc.Text = TXT_IDCLIENTE.Text
            Else
                txt_ruc.Text = ""
            End If
            txt_razonsocial.Text = ""
            txt_direccion.Text = ""
            If STRID = "KD" Then
                txt_ruc.SetFocus
            End If
            Call Datosclientepordefecto
            txt_tcambio.Text = gdblMontoTipoCambio
        Else
            Call GAsignarDatosdeCliente
            'llenar datos obtenidos del recordset
            If STRID = "KD" Or STRID = "LF" Then    ' SI ES KEYDOWN O LOSTFOCUS ASIGNAR DIRECCION
                If pasar_ruc(grscliente!ruc) Then
                    txt_ruc.Text = grscliente!ruc       'SI SE ESTA RESTAURANDO el documentoNO ASIGNAR
                Else
                    txt_ruc.Text = ""
                End If
                txt_razonsocial.Text = grscliente!RAZONSOCIAL
                txt_direccion.Text = grscliente!DIRECCION
            End If
            txt_tcambio.Text = gdblMontoTipoCambio
            If STRID = "KD" Then
                txt_ruc.SetFocus
            End If
        End If
    End If
End If
If GstrMonedaLimiteCredito = "" Then
    GstrMonedaLimiteCredito = GStrMonedaCaja
End If
End Sub
Public Sub validaarticulo()
Dim lstr_idproducto As String
Dim strid_cliente As String
Dim lstr_monedaprod As String    'moneda del producto
Dim ldat_fecha As Date
Dim ldou_precio As Double
Dim rs_temporal As ADODB.Recordset

lstr_idproducto = Trim(txtArticulo.Text)
strid_cliente = Trim(TXT_IDCLIENTE.Text)
Set rs_prod = mobj_cventasgen.obtenerprecio(strid_cliente, lstr_idproducto)

If IsNull(rs_prod!descr) Then
    MsgBox "Codigo no Existe", vbExclamation, "Atencion"
      txtArticulo.SetFocus
Else
    If Not rs_prod!stkstore And gstrtipoventas = "A" Then
        MsgBox "Producto no puede Venderse en tienda", vbExclamation, "Atencion"
        txtArticulo.SetFocus
        Exit Sub
    End If
    If rs_prod!stksales Then
        MsgBox "Producto esta bloqueado para la venta", vbExclamation, "Atencion"
        txtArticulo.SetFocus
        Exit Sub
    End If
    
    If Not rs_prod!Status Then
        MsgBox "Producto Desactivado", vbExclamation, "Atencion"
        txtArticulo.SetFocus
        Exit Sub
    End If
    
    If rs_prod!precio <= 0 Then
        MsgBox "Producto con precio incorrecto", vbExclamation, "Atencion"
        txtArticulo.SetFocus
        Exit Sub
    End If
    
    If rs_prod!stdcostpen <= 0 Or rs_prod!stdcostusd <= 0 Then
        MsgBox "Producto con Costo incorrecto", vbExclamation, "Atencion"
        txtArticulo.SetFocus
        Exit Sub
    End If
    
    If (rs_prod!curyid = GstrCodMonedaBase And rs_prod!stdcostpen > rs_prod!precio) Or _
    (rs_prod!curyid = GstrMonedaExtranjera And rs_prod!stdcostusd > rs_prod!precio) Then
        MsgBox "Producto con relacion Costo/Precio incorrecto", vbExclamation, "Atencion"
        txtArticulo.SetFocus
        Exit Sub
    End If
    
    If rs_prod!stock <= 0 Then
        If Not GIntPermiteStkNegativo Then
            MsgBox "Producto Sin Stock", vbExclamation, "Atencion"
            txtArticulo.Text = ""
            txtArticulo.SetFocus
            
            Exit Sub
        End If
    End If
    
    Set rs_temporal = MrsGrilla.Clone
    If rs_temporal.RecordCount > 0 And (Not mbln_editandoproducto) Then
        rs_temporal.MoveFirst
        Do While Not rs_temporal.EOF
            If Trim(rs_temporal!INVTIDSKU) = lstr_idproducto Then
                MsgBox "Producto Ya esta Registrado", vbExclamation, "Atencion"
                txtArticulo.SetFocus
                Exit Sub
            End If
            rs_temporal.MoveNext
        Loop
    End If
    
    ldat_fecha = dtp_fecha.Value
        
    If mbln_editandoproducto Then
        ldou_precio = Val(ctnprecio.Text)
    Else
        mbln_articuloencontrado = True
        lblDescripcion.Caption = rs_prod!descr
        lstr_monedaprod = rs_prod!curyid
        ldou_precio = rs_prod!precio
        'CONvERTIR EL PRECIO
        'si la moneda cliente igual a moneda producto
        If GstrMonedaLimiteCredito = lstr_monedaprod Then     ' no es necesario convertir
            ctnprecio.Text = rs_prod!precio
        Else                'hay que convertir
            If lstr_monedaprod = GstrCodMonedaBase Then     'si esta en moneda nacional
                ctnprecio.Text = mobj_cventasgen.ConvertirMoneda(ldou_precio, GstrCodMonedaBase, GstrMonedaExtranjera, GDatFechaProcesoVentas, GstrTipodeCambio, GintDecPrecio)
            Else
                ctnprecio.Text = mobj_cventasgen.ConvertirMoneda(ldou_precio, GstrMonedaExtranjera, GstrCodMonedaBase, GDatFechaProcesoVentas, GstrTipodeCambio, GintDecPrecio)
            End If
        End If
    
    End If
        
    ' SI ESTA ACTIVADO EL SALTO AUTOMATICO PONER LA CANTIDAD Y GRABAR EL REGISTRO
    If GBlnpermitesaltoautomatico And (Not mbln_editandoproducto) And rs_prod!classid <> GstrCategoriaFuels Then
      ctnUnidades.Text = gIntsaltoautomatico
      If Val(ctnUnidades.Text) > rs_prod!stock And (Not GIntPermiteStkNegativo) Then
        MsgBox "Cantidad Mayor al stock Disponible", vbExclamation, "Atencion"
        ctnUnidades.SetFocus
        Exit Sub
      End If
      
      Call grabarregistro
      txtArticulo.SetFocus
    Else
        If rs_prod!classid <> GstrCategoriaFuels Then
            CTN_SUBTOTAL.Enabled = False
            If Not mbln_editandoproducto Then
                ctnUnidades.Text = "1"
            End If
            ctnUnidades.SetFocus
        Else
            CTN_SUBTOTAL.Enabled = True
            CTN_SUBTOTAL.SetFocus
        End If
    End If
End If
End Sub

Public Sub CARGAGRILLA(ByVal MDblIdentificador As Double)
Dim LdblImpuesto As Double
Dim BlnExisteunNoAfecto As Boolean
Dim BlnTodosLosImpIguales As Boolean
 
LdblTotalBase = 0
LdblTotalExt = 0
LDblIGVBase = 0
LDblIGVExt = 0
LDblSubAfectoBase = 0
LDblSubAfectoExt = 0
LDblNoAfectoBase = 0
LDblNoAfectoExt = 0
 
 Set MrsGrilla = MOBJ_CVENTASCSTORE.ObtenerDatosTMPSCTORE(MDblIdentificador, GintDecPrecio)
     
  '***************************************************
  ' Parte que recalcula los Datos de los Resultados
  '***************************************************
   
  If Not MrsGrilla.EOF Then
   MrsGrilla.MoveFirst
   
   'Capturo el Primer Impuesto de la Grilla
   LdblImpuesto = MrsGrilla.Fields("PORCENTTAXIGV")
   'Inicializo la variable si es falso todos son Afectos
   BlnExisteunNoAfecto = False
   'Inicializo la variable Por defecto todos los impuestos son iguales
   BlnTodosLosImpIguales = True
   
   Do While Not MrsGrilla.EOF
     If MrsGrilla!PORCENTTAXIGV > 0 Then
       'Comparo los impuestos para revisar si son iguales
       If MrsGrilla.Fields("PORCENTTAXIGV") <> LdblImpuesto Then
          BlnTodosLosImpIguales = False
       End If
       LDblSubAfectoBase = LDblSubAfectoBase + MrsGrilla!SUBTOTALPEN
       LDblSubAfectoExt = LDblSubAfectoExt + MrsGrilla!SUBTOTALUSD
     Else
       LDblNoAfectoBase = LDblNoAfectoBase + MrsGrilla!SUBTOTALPEN
       LDblNoAfectoExt = LDblNoAfectoExt + MrsGrilla!SUBTOTALUSD
       BlnExisteunNoAfecto = True
     End If
     
     LDblIGVBase = LDblIGVBase + MrsGrilla!TAXPEN
     LDblIGVExt = LDblIGVExt + MrsGrilla!TAXUSD
     LdblTotalBase = LdblTotalBase + MrsGrilla!TOTALPEN
     LdblTotalExt = LdblTotalExt + MrsGrilla!TOTALUSD
     MrsGrilla.MoveNext
   Loop
      
   If BlnExisteunNoAfecto = False Then ' Es decir Todos son Afectos
      ' Ademas se tiene que verificar que que todos los impuestos son iguales
      If BlnTodosLosImpIguales = True Then
        LDblSubAfectoBase = LdblTotalBase / (1 + (LdblImpuesto / 100))
        LDblSubAfectoExt = LdblTotalExt / (1 + (LdblImpuesto / 100))
        LDblIGVBase = LdblTotalBase - LDblSubAfectoBase
        LDblIGVExt = LdblTotalExt - LDblSubAfectoExt
      End If
   End If
   
  End If
  
  '*********************************************************************************
  'Esta parte asigna a las Etiquetas de los Resultados los Valores Calculados arriba
  'Teniendo en Consideración la Moneda del Cliente y de la Caja
  '*********************************************************************************
  
     If GstrMonedaLimiteCredito = GstrCodMonedaBase Then
        ' Si la Moneda del Cliente no está Vacía Manda su Moneda
       txt_subtotal.Text = GFormatodeNumero(LDblSubAfectoBase, GintDecResultado)
       TXT_NOAFECTO.Text = GFormatodeNumero(LDblNoAfectoBase, GintDecResultado)
       txt_igv.Text = GFormatodeNumero(LDblIGVBase, GintDecResultado)
       txt_total.Text = GFormatodeNumero(LdblTotalBase, GintDecResultado)
     Else
       txt_subtotal.Text = GFormatodeNumero(LDblSubAfectoExt, GintDecResultado)
       TXT_NOAFECTO.Text = GFormatodeNumero(LDblNoAfectoExt, GintDecResultado)
       txt_igv.Text = GFormatodeNumero(LDblIGVExt, GintDecResultado)
       txt_total.Text = GFormatodeNumero(LdblTotalExt, GintDecResultado)
     End If
       LDblSubAfectoBase = Round(LDblSubAfectoBase, GintDecResultado)
       LDblNoAfectoBase = Round(LDblNoAfectoBase, GintDecResultado)
       LDblIGVBase = Round(LDblIGVBase, GintDecResultado)
       LdblTotalBase = Round(LdblTotalBase, GintDecResultado)
       LDblSubAfectoExt = Round(LDblSubAfectoExt, GintDecResultado)
       LDblNoAfectoExt = Round(LDblNoAfectoExt, GintDecResultado)
       LDblIGVExt = Round(LDblIGVExt, GintDecResultado)
       LdblTotalExt = Round(LdblTotalExt, GintDecResultado)
       

      Set DBDETALLE.DataSource = MrsGrilla
    'BDETALLE.Refresh
      Call FormatoGrilla
      If MrsGrilla.RecordCount > 0 Then
      MrsGrilla.MoveLast
      End If
   '*************************************************
End Sub
   
Public Sub FormatoGrilla()
DBDETALLE.Columns(0).Caption = "Reg"
DBDETALLE.Columns(0).Width = 380
DBDETALLE.Columns(0).AllowSizing = False

DBDETALLE.Columns(1).Width = 1350 '
DBDETALLE.Columns(1).Caption = "Codigo"
DBDETALLE.Columns(1).AllowSizing = False

DBDETALLE.Columns(2).Caption = "Descripcion"
DBDETALLE.Columns(2).Width = 5200
DBDETALLE.Columns(2).AllowSizing = False

DBDETALLE.Columns(3).Caption = "Precio"
DBDETALLE.Columns(3).Width = 1200  'Precio
DBDETALLE.Columns(3).Alignment = dbgRight
DBDETALLE.Columns(3).NumberFormat = GMascara(GintDecPrecio)
DBDETALLE.Columns(3).AllowSizing = False

DBDETALLE.Columns(4).Caption = "%Impto"
DBDETALLE.Columns(4).Width = 590
DBDETALLE.Columns(4).Alignment = dbgRight
DBDETALLE.Columns(4).NumberFormat = GMascara(GintDecPrecio)
DBDETALLE.Columns(4).AllowSizing = False

DBDETALLE.Columns(5).Caption = "Cantidad"
DBDETALLE.Columns(5).Width = 920
DBDETALLE.Columns(5).Alignment = dbgRight
DBDETALLE.Columns(5).NumberFormat = GMascara(GintDecStock)
DBDETALLE.Columns(5).AllowSizing = False

   If GstrMonedaLimiteCredito = GstrCodMonedaBase Then
      DBDETALLE.Columns(6).Visible = True       'mostrara moneda nacional
      DBDETALLE.Columns(6).Width = 1500
      DBDETALLE.Columns(6).Alignment = dbgRight
      DBDETALLE.Columns(6).NumberFormat = GMascara(GintDecPrecio)
      DBDETALLE.Columns(6).Caption = "Total"
      DBDETALLE.Columns(6).AllowSizing = False
      
      DBDETALLE.Columns(7).Visible = False      'oculta moneda extranjera
   Else
      DBDETALLE.Columns(7).Visible = True       'mostrara moneda extranjera
      DBDETALLE.Columns(7).Width = 1500
      DBDETALLE.Columns(7).Alignment = dbgRight
      DBDETALLE.Columns(7).NumberFormat = GMascara(GintDecPrecio)
      DBDETALLE.Columns(7).Caption = "Total"
      DBDETALLE.Columns(7).AllowSizing = False
      DBDETALLE.Columns(6).Visible = False      'oculta la moneda nacional
   End If

'ocultar campos para calculos internos
DBDETALLE.Columns(8).Visible = False            'oculta SUBTOTALPEN
DBDETALLE.Columns(9).Visible = False            'oculta SUBTOTALUSD
DBDETALLE.Columns(10).Visible = False           'oculta TAXPEN
DBDETALLE.Columns(11).Visible = False           'oculta TAXUSD
DBDETALLE.Columns(12).Visible = False           'oculta  % igv

End Sub
Private Sub valida_RUCcliente(STRID As String)
Dim lsid As String
Dim lbl_pasar As Boolean
Dim I As Integer
Dim NUMERO As Double
Dim lstr_ndocumento As String
Dim lstr_tfac As String
lstr_tfac = mobj_cventasgen.obtenertipofactura
lsid = Trim(txt_ruc.Text)

If gstrtipoventas = "A" Then        'emision automatico de ticket
    If Len(lsid) = 0 Then
        txt_tipodoc.Text = "TICKET BOLETA"
        If STRID = "KD" Then
            txt_razonsocial.SetFocus
        End If
    Else
        If Len(lsid) < 11 Then
            MsgBox "Debe ingresar 11 digitos", vbExclamation, "RUC Incorrecto"
            txt_tipodoc.Text = "TICKET BOLETA"
        Else
            txt_tipodoc.Text = "TICKET FACTURA"
            If STRID = "KD" Then
                txt_razonsocial.SetFocus
            End If
        End If
    End If
 
    txt_NBRDOCUMENT.Text = CStr(mobj_cventasgen.obtenernroticket(GstrPuntodeVenta, txt_tipodoc.Text))
    
    'dtc_serie.Text = Mid(lstr_ndocumento, 1, 3)
Else        'ingreso manual de documentos
    'si es tipo factura y no se ha ingresado un ruc
    If Len(lsid) = 0 And dtc_tdocumento.BoundText = lstr_tfac Then
        MsgBox "Debe Ingresar un RUC", vbExclamation, "Atencion"
    Else
        If Len(lsid) < 11 And dtc_tdocumento.BoundText = lstr_tfac Then
            MsgBox "Debe Ingresar 11 digitos en el RUC", vbExclamation, "Atencion"
        Else
            If txt_razonsocial.Enabled Then
            txt_razonsocial.SetFocus
        End If
        End If
    End If
End If

End Sub
Public Sub grabarregistro()
Dim dou_CORRNBR As Double
Dim str_DOCTYPEID As String
Dim dou_NBRDOCUMENT As Double
Dim int_nlin As Integer
Dim str_SITEID As String
Dim str_INVTIDSKU As String
Dim str_CURYID As String
Dim str_DATEDOC As String
Dim str_DATEPROCESALES As String
Dim dou_NBRTURN As Double
Dim dou_PORCENTTAXIGV As Double
Dim dou_PORCENTTAXISC As Double
Dim dou_TOTALPEN As Double
Dim dou_TOTALUSD As Double
Dim dou_TAXPEN As Double
Dim dou_TAXUSD As Double
Dim byt_STKITEM As Byte
Dim byt_STKFISI As Byte
Dim dou_SLS_PRICE As Double
Dim dou_SLSPRICESALE As Double
Dim dou_STDCOSTPEN As Double
Dim dou_STDCOSTUSD As Double
Dim str_INVTIDALTER As String
Dim dou_QTY As Double
Dim str_USERID As String
Dim STR_DESCR As String
Dim STRUNIDAD As String
                                
dou_CORRNBR = pdbl_correlativo
If gstrtipoventas = "A" Then
    str_DOCTYPEID = mobj_cventasgen.obtenertipoticket
Else
    str_DOCTYPEID = dtc_tdocumento.BoundText
    dou_NBRDOCUMENT = Val(dtc_serie.BoundText + txt_NBRDOCUMENT.Text)
End If

If MrsGrilla.RecordCount > 0 Then
    int_nlin = MrsGrilla!lin
Else
    int_nlin = 0
End If
str_SITEID = GstrSiteProce
str_INVTIDSKU = Trim(rs_prod!sku)

str_DATEDOC = CStr(dtp_fecha.Value)
str_DATEPROCESALES = CStr(dtp_fechapro.Value)
dou_NBRTURN = mobj_cventasgen.obtenerturnoventas
dou_PORCENTTAXISC = 0   'USO FUTURO
dou_PORCENTTAXIGV = rs_prod!taxvalue

If GstrMonedaLimiteCredito = GstrCodMonedaBase Then     ' GRABAR EN MONEDA BASE Y CALCULAR MONEDA EXTRANJERA
    str_CURYID = GstrCodMonedaBase
    'calcular el total si no es fuel
    If rs_prod!classid <> GstrCategoriaFuels Then
        dou_TOTALPEN = Round(Val(ctnUnidades.Text) * Val(ctnprecio.Text), GintDecPrecio)
    Else       'si es fuel calcular la cantidad segun el total
        dou_TOTALPEN = Val(CTN_SUBTOTAL.Text)
    End If
    If GblnAfecto Then
        dou_TOTALUSD = mobj_cventasgen.ConvertirMoneda(dou_TOTALPEN, GstrCodMonedaBase, GstrMonedaExtranjera, str_DATEPROCESALES, GstrTipoCambioVentas, GintDecPrecio)
        dou_TAXPEN = Round(dou_TOTALPEN / (100 + dou_PORCENTTAXIGV) * dou_PORCENTTAXIGV, GintDecPrecio)
        dou_TAXUSD = mobj_cventasgen.ConvertirMoneda(dou_TAXPEN, GstrCodMonedaBase, GstrMonedaExtranjera, str_DATEPROCESALES, GstrTipoCambioVentas, GintDecPrecio)
    End If
Else                                        ' GRABAR EN MONEDA EXTRANJERA Y CALCULAR MONEDA BASE
    str_CURYID = GstrMonedaExtranjera
    'calcular el total si no es fuel
    If rs_prod!classid <> GstrCategoriaFuels Then
        dou_TOTALUSD = Round(Val(ctnUnidades.Text) * Val(ctnprecio.Text), GintDecPrecio)
    Else       'si es fuel calcular la cantidad segun el total
        dou_TOTALUSD = Val(CTN_SUBTOTAL.Text)
    End If
    dou_TOTALPEN = mobj_cventasgen.ConvertirMoneda(dou_TOTALUSD, GstrMonedaExtranjera, GstrCodMonedaBase, str_DATEPROCESALES, GstrTipoCambioVentas, GintDecPrecio)
    
    If GblnAfecto Then
        dou_PORCENTTAXIGV = rs_prod!taxvalue
        dou_TAXUSD = Round(dou_TOTALUSD / (100 + dou_PORCENTTAXIGV) * dou_PORCENTTAXIGV, GintDecPrecio)
        dou_TAXPEN = mobj_cventasgen.ConvertirMoneda(dou_TAXUSD, GstrMonedaExtranjera, GstrCodMonedaBase, str_DATEPROCESALES, GstrTipoCambioVentas, GintDecPrecio)
    End If
End If


If Not GblnAfecto Then
    dou_PORCENTTAXIGV = 0
    dou_TAXUSD = 0
    dou_TAXPEN = 0
End If
    
byt_STKITEM = rs_prod!STKITEM
byt_STKFISI = rs_prod!stkfisi
dou_SLS_PRICE = rs_prod!preciodat
dou_SLSPRICESALE = Val(ctnprecio.Text)
dou_STDCOSTPEN = rs_prod!stdcostpen
dou_STDCOSTUSD = rs_prod!stdcostusd
str_INVTIDALTER = IIf(IsNull(rs_prod!ALTERN), "", rs_prod!ALTERN)
dou_QTY = Val(ctnUnidades.Text)
STR_DESCR = lblDescripcion.Caption
STRUNIDAD = rs_prod!UNIDAD

If mbln_editandoproducto Then

MOBJ_CVENTASCSTORE.actualizarcstoreDetalle dou_CORRNBR, str_DOCTYPEID, _
                                    dou_NBRDOCUMENT, int_nlin, str_SITEID, str_INVTIDSKU, _
                                    str_CURYID, str_DATEDOC, str_DATEPROCESALES, _
                                    dou_NBRTURN, dou_PORCENTTAXIGV, dou_PORCENTTAXISC, _
                                    dou_TOTALPEN, dou_TOTALUSD, _
                                    dou_TAXPEN, dou_TAXUSD, byt_STKITEM, _
                                    byt_STKFISI, dou_SLS_PRICE, _
                                    dou_SLSPRICESALE, dou_STDCOSTPEN, _
                                    dou_STDCOSTUSD, str_INVTIDALTER, _
                                    dou_QTY, STR_DESCR, STRUNIDAD
Else
MOBJ_CVENTASCSTORE.GrabarcstoreTmp dou_CORRNBR, str_DOCTYPEID, dou_NBRDOCUMENT, _
                                    str_SITEID, str_INVTIDSKU, str_CURYID, _
                                    str_DATEDOC, str_DATEPROCESALES, _
                                    dou_NBRTURN, dou_PORCENTTAXIGV, _
                                    dou_PORCENTTAXISC, dou_TOTALPEN, _
                                    dou_TOTALUSD, dou_TAXPEN, dou_TAXUSD, _
                                    byt_STKITEM, byt_STKFISI, dou_SLS_PRICE, _
                                    dou_SLSPRICESALE, dou_STDCOSTPEN, _
                                    dou_STDCOSTUSD, str_INVTIDALTER, dou_QTY, _
                                    STR_DESCR, STRUNIDAD
End If

mbln_articuloencontrado = False
mbln_editandoproducto = False
txtArticulo.Text = ""
lblDescripcion.Caption = ""
ctnprecio.Text = ""
ctnUnidades.Text = ""
CTN_SUBTOTAL.Text = ""
txtArticulo.SetFocus
txtArticulo.Locked = False
Call CARGAGRILLA(pdbl_correlativo)
End Sub
Sub valida_NUMERODOCUMENTO(STRID As String)
Dim DOCTYPEID As String
Dim NBRDOCUMENT As Double
        
If gstrtipoventas = "A" Then        'facturacion automatica
    If Len(Trim(txt_NBRDOCUMENT.Text)) = 0 Then
        MsgBox "Debe Ingresar un numero de documento", vbExclamation, "Atencion"
    Else
               
       If STRID = "KD" Then
            TXT_IDCLIENTE.SetFocus
        End If
    End If
Else        'facturacion manual
    If Len(Trim(txt_NBRDOCUMENT.Text)) = 0 Then
        MsgBox "Debe Ingresar un numero de documento", vbExclamation, "Atencion"
    Else
        DOCTYPEID = dtc_tdocumento.BoundText
        NBRDOCUMENT = Val(dtc_serie.BoundText + txt_NBRDOCUMENT.Text)
               
        If mobj_cventasgen.existedocumento(DOCTYPEID, NBRDOCUMENT, GstrSiteProce) Then
            MsgBox "Documento Ya Existe" + Chr(13) + "Modifique el Numero de Documento", vbExclamation, "Datos Incorrectos"
            Exit Sub
        End If
        If STRID = "KD" Then
            TXT_IDCLIENTE.SetFocus
        End If
    End If
End If
End Sub
Sub borrar_valores()
    TXT_IDCLIENTE = ""
'    txt_tipodoc.Text = ""
    txt_razonsocial.Text = ""
    txt_direccion.Text = ""
    txt_ruc.Text = ""
    txtArticulo.Text = ""
    ctnUnidades.Text = ""
    lblDescripcion.Caption = ""
    txt_subtotal.Text = ""
    txt_igv.Text = ""
    txt_total.Text = ""
    LdblTotalBase = 0
    LdblTotalExt = 0
    LDblIGVBase = 0
    LDblIGVExt = 0
    LDblSubAfectoBase = 0
    LDblSubAfectoExt = 0
    LDblNoAfectoBase = 0
    LDblNoAfectoExt = 0
    LDblTOTALNOTAFFECTPEN = 0
    LDblTOTALNOTAFFECTUSD = 0
    LDblTOTRETURNEDPEN = 0
    LDblTOTRETURNEDUSD = 0
    LDblTOTCASHPEN = 0
    LDblTOTCASHUSD = 0
End Sub

Function pasar_ruc(ByVal StrRuc As String) As Boolean
Dim I As Integer
pasar_ruc = True
StrRuc = Trim(StrRuc)
For I = 1 To Len(StrRuc)
    If Not IsNumeric(Mid(StrRuc, I, 1)) Then
        pasar_ruc = False
        Exit For
    End If
Next
End Function
Public Sub GAsignarDatosdeCliente()
   If IsNull(grscliente!credito) Then
    MintTipoCliente = 0
   Else
    MintTipoCliente = grscliente!credito
   End If
   If Not IsNull(grscliente!TIPOCLIENTE) Then
     GstrTipoClienteDescr = grscliente!TIPOCLIENTE
   Else
     GstrTipoClienteDescr = Empty       'cambiar por cliente id contado
   End If
   ' Variables de Manejo para el Límite de Crédito
   
   GstrIddeEstado = grscliente!IDESTADO ' A,H,R,I,O
   GstrDescrEstado = grscliente!ESTADO
      
   If IsNull(grscliente!MONEDACREDITO) Then
      GstrMonedaLimiteCredito = GStrMonedaCaja
   Else
      GstrMonedaLimiteCredito = grscliente!MONEDACREDITO
   End If
        
   If GstrMonedaLimiteCredito = GstrCodMonedaBase Then
      'Establecer Nombres de las Etiquetas
      'Con la Moneda de la Caja por defecto
       TXT_MONEDATOTAL.Text = GstrSimboloMonedaBase
   Else
       TXT_MONEDATOTAL.Text = GstrSimboloMonedaExt
   End If

   If IsNull(grscliente!TIPODECAMBIO) Or Len(Trim(grscliente!TIPODECAMBIO)) = 0 Then
        GstrTipodeCambio = GstrTipoCambioVentas
   Else
        GstrTipodeCambio = grscliente!TIPODECAMBIO
   End If
   
    If GStrMonedaCaja = GstrCodMonedaBase Then
        gdblMontoTipoCambio = mobj_cventasgen.ObtenerMontoTipodeCambio(GstrCodMonedaBase, GstrMonedaExtranjera, GDatFechaProcesoVentas, GstrTipodeCambio)
    Else
        gdblMontoTipoCambio = mobj_cventasgen.ObtenerMontoTipodeCambio(GstrMonedaExtranjera, GstrCodMonedaBase, GDatFechaProcesoVentas, GstrTipodeCambio)
    End If
   'si no hay tipo de cambio no se debe vender
   GintDiasdeGracia = grscliente!DIASDEGRACIA
   GdblLimiteCredito = mobj_cventasgen.ConvertirMoneda(grscliente!LIMITECRED, GstrMonedaLimiteCredito, GStrMonedaCaja, GDatFechaProcesoVentas, GstrTipodeCambio, GintDecResultado)
   GdblDeudaVigente = mobj_cventasgen.ConvertirMoneda(grscliente!DEUDACLIENTE, GstrMonedaLimiteCredito, GStrMonedaCaja, GDatFechaProcesoVentas, GstrTipodeCambio, GintDecResultado)
   GdblSaldoDisponible = GdblLimiteCredito - GdblDeudaVigente
   GdblMontoExtra = mobj_cventasgen.ConvertirMoneda(grscliente!EXTRA, GstrMonedaLimiteCredito, GStrMonedaCaja, GDatFechaProcesoVentas, GstrTipodeCambio, GintDecResultado)
   GblnAfecto = grscliente!afecto
   'Variable que Indica que los Datos del Cliente
   'Fueron Cargados con éxito
      
   MBlndatosasignados = True
End Sub
Public Sub CARGACABEZERALOADSALE(gdouloadsales)
Dim RS_TEMP As ADODB.Recordset
Set RS_TEMP = MOBJ_CVENTASCSTORE.obtenercabezeratransgrabadas(gdouloadsales)
dtc_tdocumento.BoundText = RS_TEMP!DOCTYPEID
txt_NBRDOCUMENT.Text = Trim(Str(RS_TEMP!NBRDOCUMENT))
dtp_fecha.Value = RS_TEMP!DATEDOC
TXT_IDCLIENTE.Text = RS_TEMP!custidss
txt_ruc.Text = RS_TEMP!taxregnbr
txt_razonsocial.Text = RS_TEMP!CUSTNAME
txt_direccion.Text = RS_TEMP!ADDR1
'LA CABEZERA DEBE DESACTIVARSE
End Sub
Public Sub ESTADO_CABEZERA(ByVal BOL_ESTADO As Boolean)
'SI TIPO DE VENTA NO ES AUTOMATICO DESACTIVAR TAMBIEN CAMPOS ADICIONALES

TXT_IDCLIENTE.Enabled = BOL_ESTADO
txt_ruc.Enabled = BOL_ESTADO
txt_razonsocial.Enabled = BOL_ESTADO
cmd_bcliente.Enabled = BOL_ESTADO
txt_direccion.Enabled = BOL_ESTADO
mbln_cabezeraprotegida = Not BOL_ESTADO

If gstrtipoventas <> "A" Then
    dtc_tdocumento.Enabled = BOL_ESTADO
    dtc_serie.Enabled = BOL_ESTADO
    dtc_tdocumento.Enabled = BOL_ESTADO
    dtp_fecha.Enabled = BOL_ESTADO
    dtp_fechapro.Enabled = BOL_ESTADO
    dtc_serie.Enabled = BOL_ESTADO
    txt_NBRDOCUMENT.Enabled = BOL_ESTADO
End If

End Sub
Public Sub FORMATONBRDOCUMENT()
Dim LS_NDOC As String
LS_NDOC = Trim(txt_NBRDOCUMENT.Text)
txt_NBRDOCUMENT.Text = String(7 - Len(LS_NDOC), "0") + LS_NDOC
End Sub
Private Sub GRABAR_CABEZERA_TEMPORAL()
'grabar si existe alguna linea

Dim ldou_loadsale As Double
Dim CORRNBR As Double
Dim DOCTYPEID As String
Dim NBRDOCUMENT As Double
Dim TYPEPAYMENTID As String
Dim STKINVENTORY As Byte
Dim SITEID As String
Dim curyid As String
Dim TERMID As String
Dim SALESPERID As String
Dim USERID As String
Dim DATEDOC As String
Dim DATEPROCESALES As String
Dim PERPOST As String
Dim TAXIGVID As String
Dim TAXISCID As String
Dim TOTALPEN As Double
Dim TOTALUSD As Double
Dim SUBTOTALPEN As Double
Dim SUBTOTALUSD As Double
Dim TAXIGVPEN As Double
Dim TAXIGVUSD As Double
Dim TAXISCPEN As Double
Dim TAXISCUSD As Double
Dim TOTALNOTAFFECTPEN As Double
Dim TOTALNOTAFFECTUSD As Double
Dim TOTRETURNEDPEN As Double
Dim TOTRETURNEDUSD As Double
Dim TOTCASHPEN As Double
Dim TOTCASHUSD As Double
Dim custidss As String
Dim taxregnbr As String
Dim CUSTNAME As String
Dim ADDR1 As String
Dim PLACA As String
Dim NBRBONUS As Double
Dim CURYTYPEID As String
Dim CURYRATE As Double
Dim PROMOTIONCARDID As String
Dim POINTNUMBER As Integer
Dim SALESPOINT As String
Dim KILOMETRAJE As Integer
Dim typesales As String
If gstrtipoventas = "A" Then
    DOCTYPEID = mobj_cventasgen.obtenertipoticket
Else
    DOCTYPEID = dtc_tdocumento.BoundText
End If

NBRDOCUMENT = Val(txt_NBRDOCUMENT.Text)
TYPEPAYMENTID = "00"
STKINVENTORY = 1
SITEID = GstrSiteProce
curyid = "PEN"
TERMID = "00"
SALESPERID = GstrCodigoVENDEDOR
USERID = GCUSERID
DATEDOC = CStr(dtp_fecha.Value)
DATEPROCESALES = CStr(dtp_fechapro.Value)
PERPOST = ""
TAXIGVID = 0
TAXISCID = 0
TOTALPEN = Val(txt_total.Text)
TOTALUSD = 0
SUBTOTALPEN = (txt_subtotal.Text)
SUBTOTALUSD = 0
TAXIGVPEN = Val(txt_igv.Text)
TAXIGVUSD = 0
TAXISCPEN = 0
TAXISCUSD = 0
TOTALNOTAFFECTPEN = Val(TXT_NOAFECTO.Text)
TOTALNOTAFFECTUSD = 0
TOTRETURNEDPEN = 0
TOTRETURNEDUSD = 0
TOTCASHPEN = 0
TOTCASHUSD = 0
custidss = TXT_IDCLIENTE.Text
taxregnbr = txt_ruc.Text
CUSTNAME = txt_razonsocial.Text
ADDR1 = txt_direccion.Text
PLACA = ""
NBRBONUS = 0
CURYTYPEID = GstrTipoCambioVentas
CURYRATE = Val(txt_tcambio.Text)
PROMOTIONCARDID = ""
POINTNUMBER = 0
SALESPOINT = GstrPuntodeVenta
KILOMETRAJE = 0
typesales = gstrtipoventas

'MsgBox "Grabando"
'VERIFICAR QUE LA TRANSACION NO ESTE GRABADA YA
If mobj_cventasgen.existecorrelativotemporal(pdbl_correlativo) Then
    ' ya esta grabada, hay que actualizar
'MsgBox "actualizando"
mobj_cventasgen.actualizatransaccion pdbl_correlativo, DOCTYPEID, NBRDOCUMENT, TYPEPAYMENTID, _
                   STKINVENTORY, SITEID, curyid, TERMID, SALESPERID, USERID, _
                   DATEDOC, DATEPROCESALES, PERPOST, TAXIGVID, TAXISCID, _
                   TOTALPEN, TOTALUSD, SUBTOTALPEN, SUBTOTALUSD, TAXIGVPEN, _
                   TAXIGVUSD, TAXISCPEN, TAXISCUSD, TOTALNOTAFFECTPEN, _
                   TOTALNOTAFFECTUSD, TOTRETURNEDPEN, _
                    TOTRETURNEDUSD, TOTCASHPEN, TOTCASHUSD, _
                   custidss, taxregnbr, CUSTNAME, PLACA, NBRBONUS, CURYTYPEID, _
                   CURYRATE, PROMOTIONCARDID, POINTNUMBER, SALESPOINT, KILOMETRAJE, _
                   typesales, ADDR1
Else

'MsgBox "insertando"
mobj_cventasgen.grabartransaccion pdbl_correlativo, DOCTYPEID, NBRDOCUMENT, TYPEPAYMENTID, _
                   STKINVENTORY, SITEID, curyid, TERMID, SALESPERID, USERID, _
                   DATEDOC, DATEPROCESALES, PERPOST, TAXIGVID, TAXISCID, _
                   TOTALPEN, TOTALUSD, SUBTOTALPEN, SUBTOTALUSD, TAXIGVPEN, _
                   TAXIGVUSD, TAXISCPEN, TAXISCUSD, TOTALNOTAFFECTPEN, _
                   TOTALNOTAFFECTUSD, TOTRETURNEDPEN, _
                    TOTRETURNEDUSD, TOTCASHPEN, TOTCASHUSD, _
                   custidss, taxregnbr, CUSTNAME, PLACA, NBRBONUS, CURYTYPEID, _
                   CURYRATE, PROMOTIONCARDID, POINTNUMBER, SALESPOINT, KILOMETRAJE, _
                   typesales, ADDR1

End If
End Sub
Private Sub GRABAR_VENTA(ByVal strtipoventa As String)
Dim CORRNBR As Double
Dim DOCTYPEID As String
Dim NBRDOCUMENT As Double
Dim TYPEPAYMENTID As String
Dim STKINVENTORY As Byte
Dim SITEID As String
Dim curyid As String
Dim TERMID As String
Dim SALESPERID As String
Dim USERID As String
Dim DATEDOC As String
Dim DATEPROCESALES As String
Dim TAXIGVID As String
Dim TAXISCID As String
Dim TAXISCPEN As Double
Dim TAXISCUSD As Double

Dim custidss As String
Dim taxregnbr As String
Dim CUSTNAME As String
Dim PLACA As String
Dim NBRBONUS As Double
Dim CURYTYPEID As String
Dim CURYRATE As Double
Dim PROMOTIONCARDID As String
Dim POINTNUMBER As Integer
Dim SALESPOINT As String
Dim KILOMETRAJE As Integer
Dim typesales As String
Dim PORCENTDISCOUNT1 As Double
Dim PORCENTDISCOUNT2 As Double
Dim TOTDISCOUNTPEN As Double
Dim TOTDISCOUNTUSD As Double
Dim error As Integer

Dim STR_RAZONSOCIAL As String
Dim STR_RUC As String
Dim STR_DIRECCION As String
Dim IntTurno As Integer
Dim STR_CAJERO As String
Dim STR_TIPODOC As String

If gstrtipoventas = "A" Then
    DOCTYPEID = mobj_cventasgen.obtenertipoticket
    STR_TIPODOC = "Ticket"
    NBRDOCUMENT = Val(txt_NBRDOCUMENT.Text)
Else
    DOCTYPEID = dtc_tdocumento.BoundText
    STR_TIPODOC = Trim(txt_tipodoc.Text)
    NBRDOCUMENT = Val(dtc_serie.BoundText + txt_NBRDOCUMENT.Text)
End If


TYPEPAYMENTID = strtipoventa
STKINVENTORY = 1            '-------------------------------------------
SITEID = GstrSiteProce
curyid = GstrMonedaLimiteCredito
TERMID = "00"               '-------------------------------------------

SALESPERID = GstrCodigoVENDEDOR
USERID = GCUSERID
DATEDOC = CStr(dtp_fecha.Value)
DATEPROCESALES = CStr(dtp_fechapro.Value)

TAXIGVID = ""                '-------------------------------------------
TAXISCID = ""
TAXISCPEN = 0
TAXISCUSD = 0
PORCENTDISCOUNT1 = 0
PORCENTDISCOUNT2 = 0
TOTDISCOUNTPEN = 0
TOTDISCOUNTUSD = 0

custidss = TXT_IDCLIENTE.Text
taxregnbr = txt_ruc.Text
CUSTNAME = txt_razonsocial.Text
PLACA = ""
NBRBONUS = 0
CURYTYPEID = GstrTipoCambioVentas   '-------------------------------------------
CURYRATE = Val(txt_tcambio.Text)
PROMOTIONCARDID = ""
POINTNUMBER = 0
SALESPOINT = GstrPuntodeVenta
KILOMETRAJE = 0
typesales = gstrtipoventas

IntTurno = mobj_cventasgen.obtenerturnoventas
STR_RAZONSOCIAL = Trim(txt_razonsocial.Text)
STR_RUC = Trim(txt_ruc.Text)
STR_DIRECCION = Trim(txt_direccion.Text)
STR_CAJERO = Trim(txt_vendedor.Text)


If MintTipoCliente = 0 Then ' SI NO ES CREDITO ACTUALIZAR DATOS O AGREGAR CLIENTE
     
 MOBJ_CVENTASCSTORE.OP_AGREGACLIENTECSTORE custidss, STR_RUC, STR_RAZONSOCIAL, STR_DIRECCION, _
                                                DATEPROCESALES, USERID

End If

error = MOBJ_CVENTASCSTORE.grabarventa(pdbl_correlativo, DOCTYPEID, _
                   NBRDOCUMENT, TYPEPAYMENTID, _
                   STKINVENTORY, SITEID, curyid, TERMID, SALESPERID, USERID, _
                   DATEDOC, DATEPROCESALES, TAXIGVID, TAXISCID, _
                   LdblTotalBase, LdblTotalExt, LDblSubAfectoBase, _
                   LDblSubAfectoExt, LDblIGVBase, _
                   LDblIGVExt, TAXISCPEN, TAXISCUSD, LDblNoAfectoBase, _
                   LDblNoAfectoExt, PORCENTDISCOUNT1, PORCENTDISCOUNT2, _
                   TOTDISCOUNTPEN, TOTDISCOUNTUSD, LDblTOTRETURNEDPEN, _
                    LDblTOTRETURNEDUSD, LDblTOTCASHPEN, LDblTOTCASHUSD, _
                   custidss, taxregnbr, CUSTNAME, PLACA, NBRBONUS, CURYTYPEID, _
                   CURYRATE, PROMOTIONCARDID, POINTNUMBER, SALESPOINT, KILOMETRAJE)

If error = 0 Then
If gstrtipoventas = "A" Then
Call Imprimir_Ticketcstore(STR_TIPODOC, CStr(NBRDOCUMENT), 40, STR_RAZONSOCIAL, STR_RUC, _
                                STR_DIRECCION, curyid, _
                                pdbl_correlativo, LDblSubAfectoBase, LDblSubAfectoExt, _
                                LDblIGVBase, LDblIGVExt, LdblTotalBase, LdblTotalExt, _
                                LDblNoAfectoBase, LDblNoAfectoExt, LDblTOTCASHPEN, LDblTOTCASHUSD, _
                                LDblTOTRETURNEDPEN, LDblTOTRETURNEDUSD, _
                                MrsGrilla, TYPEPAYMENTID, _
                                IntTurno, STR_CAJERO, Val(POINTNUMBER), PLACA)
End If

    If gstrtipoventas = "A" Then
         mobj_cventasgen.aumentarnroticket GstrPuntodeVenta, txt_tipodoc.Text ' INCREMENTAR EL NUMERO DE TICKET SEGUN EL TIPO
    Else
        mobj_cventasgen.aumentarnrodocumento dtc_tdocumento.BoundText, dtc_serie.BoundText, GstrSiteProce, GstrPuntodeVenta ' INCREMENTAR EL NUMERO DE DOCUMENTO SEGUN EL TIPO
    End If
        
    Call borrar_valores
    Call INICIO
Else
    MsgBox "Error Grabando Venta", vbCritical, "Error"
End If
End Sub

Sub anular_ticket()
Dim li_resp As Integer
li_resp = MsgBox("Esta Seguro que desea Anular el Documento", vbYesNo, "Precaucion")
If li_resp = vbYes Then
    
End If
End Sub

Sub eliminar_ticket()
Dim li_resp As Integer
li_resp = MsgBox("Esta Seguro que desea Eliminar el Documento ", vbYesNo, "Precaucion")
If li_resp = vbYes Then
    
End If
End Sub

Sub busquedaventas()

fbuscardocumentos.Show vbModal
If pdbl_documentobuscado <> 0 Then
    'recuperar documento y marcar flag como consulta
    pbln_consulta = True
End If
pdbl_documentobuscado = 0

End Sub

Sub Datosclientepordefecto()
    MintTipoCliente = 0
    GstrMonedaLimiteCredito = GStrMonedaCaja
    TXT_MONEDATOTAL.Text = GstrSimboloMoneda
    GstrTipodeCambio = GstrTipoCambioVentas
    If GStrMonedaCaja = GstrCodMonedaBase Then
        gdblMontoTipoCambio = mobj_cventasgen.ObtenerMontoTipodeCambio(GstrCodMonedaBase, GstrMonedaExtranjera, GDatFechaProcesoVentas, GstrTipodeCambio)
    Else
        gdblMontoTipoCambio = mobj_cventasgen.ObtenerMontoTipodeCambio(GstrMonedaExtranjera, GstrCodMonedaBase, GDatFechaProcesoVentas, GstrTipodeCambio)
    End If
    GblnAfecto = True
End Sub
Sub valida_cabezera1()
If gstrtipoventas = "A" Then

Else
    If dtc_tdocumento.Text = "" Then
        MsgBox "Debe Escoger un tipo de documento", vbExclamation, "Precaucion"
        dtc_tdocumento.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If dtc_serie.Text = "" Then
        MsgBox "Debe Escoger una serie de documentos", vbExclamation, "Precaucion"
        dtc_serie.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If Val(txt_NBRDOCUMENT.Text) = 0 Then
        MsgBox "Debe Ingresar un numero de documento", vbExclamation, "Precaucion"
        dtc_serie.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
'    If dtp_fechapro.Value > GDatFechaProcesoVentas Then
'        MsgBox " La fecha de proceso ingresada es mayor que la fecha de Venta", vbExclamation, "Error"
'        dtp_fechapro.SetFocus
'       pbln_errorcab = True
'        Exit Sub
'    End If
'    If dtp_fechapro.Value < GDatFechaProceso Then
'        MsgBox " La fecha Ingresada es menor que la fecha de Proceso", vbExclamation, "Error"
'        dtp_fechapro.SetFocus
'       pbln_errorcab = True
'        Exit Sub
'    End If
'    If dtp_fecha.Value > GDatFechaProcesoVentas Then
'        MsgBox " La fecha de proceso ingresada es mayor que la fecha de Venta", vbExclamation, "Error"
'        dtp_fecha.SetFocus
'        pbln_errorcab = True
'        Exit Sub
'    End If

End If
pbln_errorcab = False
End Sub

Sub valida_cabezera2()
If pbln_errorcab Then
    Exit Sub    ' ya existe un error
End If
If gstrtipoventas = "A" Then

    
Else
    If Len(Trim(TXT_IDCLIENTE.Text)) = 0 And _
    dtc_tdocumento.BoundText = mobj_cventasgen.obtenertipofactura And _
    Me.ActiveControl.Name <> "TXT_IDCLIENTE" Then
        MsgBox "Debe Ingresar  Codigo Cliente", vbExclamation, "Precaucion"
        TXT_IDCLIENTE.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
End If
pbln_errorcab = False
End Sub
Sub valida_cabezera3()
Dim lstr_tfact As String
If pbln_errorcab Then
    Exit Sub    ' ya existe un error
End If
lstr_tfact = mobj_cventasgen.obtenertipofactura
If gstrtipoventas = "A" Then
    If Len(Trim(txt_ruc.Text)) = 0 And txt_tipodoc.Text = "TICKET FACTURA" Then
        MsgBox "Debe Ingresar un RUC", vbExclamation, "Precaucion"
        txt_ruc.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If Len(Trim(txt_ruc.Text)) < 11 And txt_tipodoc.Text = "TICKET FACTURA" Then
        MsgBox "Debe Ingresar 11 digitos en el RUC", vbExclamation, "Precaucion"
        txt_ruc.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If txt_tipodoc.Text = "TICKET FACTURA" And _
        Len(txt_razonsocial.Text) = 0 And _
        Me.ActiveControl.Name <> "txt_razonsocial" Then
        MsgBox "Debe Ingresar una Razon social", vbExclamation, "Atencion"
        txt_razonsocial.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If Len(Trim(txt_ruc.Text)) > 0 And txt_tipodoc.Text = "TICKET BOLETA" Then
        MsgBox "Una Boleta no debe tener RUC", vbExclamation, "Precaucion"
        txt_ruc.Text = ""
        'pbln_errorcab = True
        Exit Sub
    End If

Else
    If Len(Trim(txt_ruc.Text)) = 0 And dtc_tdocumento.BoundText = lstr_tfact Then
        MsgBox "Debe Ingresar un RUC", vbExclamation, "Precaucion"
        txt_ruc.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If Len(Trim(txt_ruc.Text)) < 11 And dtc_tdocumento.BoundText = lstr_tfact Then
        MsgBox "Debe Ingresar 11 digitos en el RUC", vbExclamation, "Precaucion"
        txt_ruc.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If dtc_tdocumento.BoundText = lstr_tfact And _
        Len(txt_razonsocial.Text) = 0 And _
        Me.ActiveControl.Name <> "txt_razonsocial" Then
        MsgBox "Debe Ingresar una Razon social", vbExclamation, "Atencion"
        txt_razonsocial.SetFocus
        pbln_errorcab = True
        Exit Sub
    End If
    If Len(Trim(txt_ruc.Text)) > 0 And dtc_tdocumento.BoundText = mobj_cventasgen.obtenertipoboleta Then
        MsgBox "Una Boleta no debe tener RUC", vbExclamation, "Precaucion"
        txt_ruc.Text = ""
        'pbln_errorcab = True
        Exit Sub
    End If
End If
pbln_errorcab = False
End Sub

Sub cierra_objetos()
Set mobj_cseguridad = Nothing
Set MOBJ_CMONEDA = Nothing
Set mobj_cdocumento = Nothing
Set mobj_cventasgen = Nothing
Set MOBJ_CVENTASCSTORE = Nothing
Set Mobj_Correlativo = Nothing
Set grscliente = Nothing
Set MrsGrilla = Nothing
Set rs_prod = Nothing
End Sub
