B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=12.2
@EndOfDesignText@
Sub Class_Globals
	Private Root As B4XView 'ignore
	Private xui As XUI 'ignore
	Dim g As GPS
	Dim q_buscar As String
	
	Dim c As Cursor
	Dim c2 As Cursor
	Dim ListView1 As ListView
	Dim entro As String
	Dim lfila As Label
	Dim marca As String
	Dim tipo As String
	Private BUSCA As EditText
	Dim ya_entro As String
	Dim bmp As Bitmap
	
	Dim c As Cursor
	Dim e As Cursor
	Dim f As Cursor
	Dim h As Cursor
	Dim CC As Cursor
	Dim DD As Cursor
	Dim l_tipo As Label
	Dim l_sub As Label
	Dim l_marca As Label
	Dim l_desc As Label
	Dim l_precio As Label
	Dim l_bodega As Label
	Dim cantidad As EditText
	Dim guardar As Button
	Dim Terminar As Button
	Dim img_prod As ImageView
	Dim IMG_PASO() As Byte
	Dim L_PROID As Label
	Dim clie_id As String
	Dim sDate,sTime As String
	Dim usuario As String
	Dim t_venta As Label
	Dim PROMO_C As String
	Dim i_fotol As ImageView
	Private DESC_PROMO As Button
	Private nopromo As Button
	Dim TOT_ART_PROMO As String
	Dim cambio As String
	Dim COSTO_TOT As String
	Dim ALMACEN As String
	Dim preciosin As String
	Dim cl_ruta As String
	Dim d As Cursor
	Dim TOT_ART_PROMOR As String
	Dim PROMO_CR As String
	Dim TOTAL_PROMO As String
	Dim HCCP_CANT As String
	Private Panel1 As Panel
	Dim query As String
	Private t_precio As Label
	Private LV_PRECIOS As ListView
	Private PERFIL As String
	Private EXISTE_CAMBIO As String
	Private QUERY2 As String
	Dim CAMBIOS As String
	Dim precio2 As String
	Private B_MENOS As Button
	Private B_MAS As Button
	Private p_prods As Panel
	Private l_prodX As Label
	Private l_pCant As Label
	Private et_pCant As EditText
	Private clv_productos As CustomListView
	Dim etCantHasFocus As Boolean = False
	Dim totalProds As Int = 0
	Dim totalCompra As Int = 0
	Dim prodsMap As Map
	Dim prodsListId, prodsList, prodsListCliOrig As List
	Private l_totProds As Label
	Private l_total As Label
	Private b_terminar1 As Button
	Private p_botonesVenta As Panel
	Private l_vendido As Label
End Sub

'You can add more parameters here.
Public Sub Initialize As Object
	Return Me
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
	Root = Root1
	'load the layout to Root
	g.Initialize("GPS")
	'Do not forget to load the layout file created with the visual designer. For example:
	'Activity.LoadLayout("Layout1")
	Root.RemoveAllViews
	Root.LoadLayout("productos")
	Panel1.Visible= False
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Sub B4XPage_Appear
	query = "cat_gunaprod"
	QUERY2 = "CAT_GUNAPROD"
	prodsMap.Initialize
	prodsList.Initialize
	prodsListId.Initialize
	prodsListCliOrig.Initialize
	If ya_entro <> "1" Then
		'BUSCA.Text =""
		'SE COMENTO LA LINEA DE ARRIBA YA QUE DISPARA EL EVENTO DEL TEXTCHANGE Y PUEDE HACER LENTO EL SISTEMA
		Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
		entro ="1"
		ya_entro ="1"
		c=Starter.skmt.ExecQuery("select CAT_GP_CLASIF, COUNT(*) AS CUANTOS from " & query & " WHERE CAT_GP_ALMACEN > 0 GROUP BY CAT_GP_CLASIF order by CAT_GP_CLASIF asc")
		
		'ESTO ES PARA NO VER PROCTER
		'c=skmt.ExecQuery2("select CAT_GP_CLASIF, count(*) as cuantos from cat_gunaprod where CAT_GP_ALMACEN > 0 and cat_gp_clasif NOT IN (?,?,?,?,?,?,?,?,?,?) group by CAT_GP_CLASIF order by CAT_GP_CLASIF asc", Array As String("PROCTER","PROMOS","TRES MONTES","CAMPARI","CAMPARI-PRO","CLOROX DE MEXICO","MARS","CONAGRA","VERDE VALLE","MEAD JOHNSON"))
		ListView1.Clear
		lfila.Text = "MARCA"
		Dim label1 As Label
		label1 = ListView1.TwoLinesLayout.Label
		label1.TextSize = 10
		label1.TextColor = Colors.Black
		Dim label2 As Label
		label2 = ListView1.TwoLinesLayout.SecondLabel
		label2.TextSize = 10
		label2.TextColor = Colors.Black
		If c.RowCount>0 Then
			For i=0 To c.RowCount -1
				c.Position=i
				'		bmp = LoadBitmap(File.DirAssets, "palomita_verde.png")
				ListView1.AddTwoLines(c.GetString("CAT_GP_CLASIF"),c.GetString("CUANTOS"))
			Next
		End If
	End If
	clv_productos.GetBase.SetLayoutAnimated(100, 10dip, 140dip, Root.Width - 50, Root.Height * 0.68) 'Cambiamos el tamaño y posición de la lista de productos
	clv_productos.Base_Resize(clv_productos.GetBase.Width, clv_productos.GetBase.Height) 'Cambiamos el tamaño del panel interno de la lista para que ajuste al nuevo tamaño.
'	p_botonesVenta.Visible = False
	p_botonesVenta.Top = clv_productos.AsView.top + clv_productos.AsView.Height
	llenaProductos(False)
End Sub

Sub ListView1_ItemClick (Position As Int, Value As Object)
	If Value = "PROMOS" And B4XPages.MainPage.cliente.cuenta <> "N" Then
		entro = "3"
		marca = "PROMOS"
		tipo = "PROMOS"
	Else if Value = "PROMOS"  And B4XPages.MainPage.cliente.cuenta = "N"  Then
		entro = "5"
		B4XPages.ShowPage("Cliente")
	End If
	If entro = "1" Then
		marca = Value
		Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
		c2=Starter.skmt.ExecQuery2("select  COUNT(*) AS CUANTOS, CAT_GP_TIPO from " & query & " where CAT_GP_ALMACEN > 0 and CAT_GP_CLASIF = ? GROUP BY CAT_GP_TIPO ORDER BY CAT_GP_TIPO ASC", Array As String(Value))
		ListView1.Clear
		lfila.text = "TIPO"
		If c2.RowCount>0 Then
			For i=0 To c2.RowCount -1
				c2.Position=i
				ListView1.AddTwoLines(c2.GetString("CAT_GP_TIPO"),c2.GetString("CUANTOS"))
			Next
		End If
		entro = "3"
	Else If entro = "2" Then
		tipo = Value
		Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
		c2=Starter.skmt.ExecQuery2("select  COUNT(*) AS CUANTOS, CAT_GP_SUBTIPO from " & query & " where CAT_GP_ALMACEN > 0 and CAT_GP_CLASIF = ? and CAT_GP_TIPO = ?  GROUP BY CAT_GP_SUBTIPO ORDER BY CAT_GP_SUBTIPO ASC ", Array As String(marca, Value))
		ListView1.Clear
		lfila.text = "SUB-TIPO"
		If c2.RowCount>0 Then
			For i=0 To c2.RowCount -1
				c2.Position=i
				ListView1.AddTwoLines(c2.GetString("CAT_GP_SUBTIPO"),c2.GetString("CUANTOS"))
			Next
		End If
		entro = "3"
	   
	Else If entro = "3" Then
		Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
		c2=Starter.skmt.ExecQuery2("select  CAT_GP_NOMBRE, CAT_GP_PRECIO, CAT_GP_ALMACEN, CAT_GP_IMG from " & query & " where CAT_GP_ALMACEN > 0 and CAT_GP_CLASIF = ? AND CAT_GP_TIPO = ?   ", Array As String(marca,  Value))
		ListView1.Clear
		lfila.text = "PRODUCTO"
		Dim ins As InputStream
		Dim bmp As Bitmap
		Dim jpeg() As Byte
		If c2.RowCount>0 Then
			For i=0 To c2.RowCount -1
				c2.Position=i
				jpeg = c2.GetBlob("CAT_GP_IMG")
				ins.InitializeFromBytesArray(jpeg, 0, jpeg.Length)
				bmp.Initialize2(ins)

				ListView1.AddTwoLines(c2.GetString("CAT_GP_NOMBRE"),"# " & c2.GetString("CAT_GP_ALMACEN") & " $ " & c2.GetString("CAT_GP_PRECIO"))
			Next
		End If
		entro = "4"
	Else If entro = "4" Then
	  
		Starter.skmt.ExecNonQuery("delete from PROID")
		Starter.skmt.ExecNonQuery2("INSERT INTO PROID VALUES (?)", Array As Object(Value))
		'StartActivity(pedidos)
		HACER_PEDIDO
	End If
End Sub

Private Sub B4XPage_CloseRequest As ResumableSub
	' BACK key pressed
'	Log("REGRESAMOS, " & "ENTRO=" & entro)
	ya_entro ="0"
	If entro = "4" Then
		entro = "3"
		B4XPage_Appear
		Return True
	Else If entro = "3" Then
		' I want to capture the key here so I return True
		Log("Mostramos Cliente")
		B4XPages.ShowPage("Cliente")
		Return False
	End If
	B4XPages.ShowPage("Cliente")
	Return False
	' Returning False signals the system to handle the key
End Sub

Sub BUSCA_TextChanged (Old As String, New As String)
	q_buscar = "%" & BUSCA.Text & "%"
	Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
	c=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE, CAT_GP_ALMACEN, CAT_GP_PRECIO,CAT_GP_IMG from " & query & " where CAT_GP_PRECIO > 0 AND CAT_GP_ALMACEN > 0 and CAT_GP_NOMBRE like ? and CAT_GP_CLASIF <>  ?  and (length(CAT_GP_CODPROMO) = 1 OR CAT_GP_CODPROMO = CAT_GP_ID) order by CAT_GP_NOMBRE asc", Array As String(q_buscar,"PROMOS"))
	'and CAT_GP_CLASIF <>  ? group by CAT_GP_CLASIF order by CAT_GP_CLASIF asc", Array As String("PROMOS") )
	
	ListView1.Clear
	 
	Dim ins As InputStream
	Dim bmp As Bitmap
	Dim jpeg() As Byte
	If c.RowCount>0 Then
		For i=0 To c.RowCount -1
			c.Position=i
			jpeg = c.GetBlob("CAT_GP_IMG")
			ins.InitializeFromBytesArray(jpeg, 0, jpeg.Length)
			bmp.Initialize2(ins)
			ListView1.AddTwoLines(c.GetString("CAT_GP_NOMBRE"),"Existencia " & c.GetString("CAT_GP_ALMACEN") & " Precio $" & c.GetString("CAT_GP_PRECIO"))
		Next
	End If
	c.Close
	entro= "4"
End Sub

Sub HACER_PEDIDO
	c=Starter.skmt.ExecQuery("Select SUBSTR(CUENTA,1,1) AS CUENTA from cuentaa")
	c.Position=0
	clie_id = c.GetString("CUENTA")
	c.Close
	Panel1.Visible= True
	cambio = "0"
	cantidad.Text = ""
	c=Starter.skmt.ExecQuery("select  ID_ALMACEN from CAT_ALMACEN")
	C.Position =0
	ALMACEN = C.GetString("ID_ALMACEN")
	C.Close
	i_fotol.Visible = False

	Starter.skmt.Initialize(Starter.ruta,"kmt.db", True)
	c=Starter.skmt.ExecQuery("select CAT_GP_ID,CAT_GP_NOMBRE,CAT_GP_IMP1,CAT_GP_IMP2,CAT_GP_PRECIO,CAT_GP_CLASIF,CAT_GP_STS,CAT_GP_TIPO,CAT_GP_SUBTIPO,CAT_GP_IMG,CAT_GP_ALMACEN,CAT_GP_DEV  from " & query & " where CAT_GP_NOMBRE In (Select PDESC from PROID)")
	c.Position=0
	L_PROID.Text = c.GetString("CAT_GP_ID")
	l_tipo.Text = c.GetString("CAT_GP_TIPO")
	l_sub.Text = c.GetString("CAT_GP_SUBTIPO")
	l_marca.Text = c.GetString("CAT_GP_CLASIF")
	l_desc.Text = c.GetString("CAT_GP_NOMBRE")
	
	If PERFIL = "V-SUPER" Then
		c2=Starter.skmt.ExecQuery("select PRECIO, NLISTA FROM LISTA_PRECIOS WHERE NLISTA = '10' AND  CAT_GP_ID =" & "'" &L_PROID.TEXT&"' ORDER BY NLISTA ASC")
		c2.Position=0
		l_precio.Text = c2.GetString("PRECIO")
		c2.Close
	Else
		l_precio.Text = c.GetDouble("CAT_GP_PRECIO")
	End If
	l_bodega.Text = c.GetString("CAT_GP_ALMACEN")
	IMG_PASO = c.GetBlob("CAT_GP_IMG")
	PROMO_C = c.GetString("CAT_GP_STS")
	cambio = c.GetString("CAT_GP_DEV")
	preciosin = c.GetString("CAT_GP_IMP2")
	PROMO_CR = c.GetString("CAT_GP_IMP1")
	precio2 = l_precio.Text
	If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" Then
		DESC_PROMO.Visible = True
		CC=Starter.skmt.ExecQuery2("select count(*) as CUANTOS FROM PROMOS_COMP WHERE CAT_PA_ID = ?", Array As String(c.GetString("CAT_GP_ID")))
		CC.Position =0
		If CC.GetString("CUANTOS") = 0 Then
			l_bodega.Text = "4"
		Else
			CC.Close
			CC=Starter.skmt.ExecQuery2("select CAT_PA_MAXPROM, CAT_PA_MAXPROMREC, CAT_PA_MAXPROMCLIE FROM PROMOS_COMP WHERE CAT_PA_ID = ?", Array As String(c.GetString("CAT_GP_ID")))
			CC.Position =0
				
			DD=Starter.skmt.ExecQuery2("SELECT COUNT(*) AS CUANTOS FROM HIST_CLIENTE_CANT_PROMOS WHERE HCCP_CLIENTE IN (Select cuenta from cuentaa) AND HCCP_PROMO =?", Array As String(c.GetString("CAT_GP_ID")))
			DD.Position =0
			If DD.GetString("CUANTOS")  = 0 Then
				HCCP_CANT = 0
			
			Else
				DD.Close
				
				DD=Starter.skmt.ExecQuery2("SELECT HCCP_CANT FROM HIST_CLIENTE_CANT_PROMOS WHERE HCCP_CLIENTE IN (Select cuenta from cuentaa) AND HCCP_PROMO =?", Array As String(c.GetString("CAT_GP_ID")))
				DD.Position =0
				HCCP_CANT = DD.GetString("HCCP_CANT")
				DD.Close
			End If
			TOTAL_PROMO = CC.GetString("CAT_PA_MAXPROMCLIE") - HCCP_CANT
			If HCCP_CANT = 0 Then
				
				l_bodega.Text = CC.GetString("CAT_PA_MAXPROM")
			Else IF TOTAL_PROMO > CC.GetString("CAT_PA_MAXPROMREC") Then
				l_bodega.Text = 	CC.GetString("CAT_PA_MAXPROMREC")
			Else
				l_bodega.Text = TOTAL_PROMO
			End If
		End If
	Else
		DESC_PROMO.Visible = False
	End If
            	
	c.Close
	c=Starter.skmt.ExecQuery("select CASE WHEN pe_costo_tot is null then 0 else  sum( pe_costo_tot ) end as TOTAL_CLIE FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
	c.Position=0
	t_venta.Text = c.GetString("TOTAL_CLIE")
	c.Close
	' If t_venta.Text < 100  AND l_tipo.Text = "PROMOS" Then
	'Terminar.Visible = False
	'guardar.Visible = False
	'cantidad.Visible = False
	'nopromo.Visible = True
	'Else
	'cambio = 0
	Terminar.Visible = True
	guardar.Visible = True
	cantidad.Visible = True
	nopromo.Visible = False
	'End If
	
	   
	Dim out As OutputStream
	out = File.OpenOutput(Starter.ruta, "1.jpg", False)
	out.WriteBytes(IMG_PASO, 0, IMG_PASO.Length)
	out.Close
	img_prod.Bitmap = LoadBitmap(Starter.ruta,"1.jpg")
	TOT_ART_PROMO = "0"
	TOT_ART_PROMOR = "0"
	If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And l_bodega.Text = "0" Then
		Msgbox("ALERTA","EL CLIENTE YA NO PUEDE TENER ESTA PROMOCION") 'ignore
		Panel1.Visible= False
	End If

	If marca <> "PROMOS" Then

		If PERFIL = "PREVENTA" Then
	
			t_precio.Visible = False
			LV_PRECIOS.Visible = False

		ELSE IF PERFIL = "V-ESPECIAL" Then
			c=Starter.skmt.ExecQuery("select PRECIO, NLISTA FROM LISTA_PRECIOS WHERE NLISTA IN ('5','6','7','8','10') AND  CAT_GP_ID =" & "'" &L_PROID.TEXT&"' ORDER BY NLISTA ASC")
			LV_PRECIOS.Clear
			Dim label1 As Label
			label1 = LV_PRECIOS.TwoLinesLayout.Label
			label1.TextSize = 10
			label1.TextColor = Colors.Black
			Dim label2 As Label
			label2 = LV_PRECIOS.TwoLinesLayout.SecondLabel
			label2.TextSize = 10
			label2.TextColor = Colors.Black
			
			If c.RowCount>0 Then
				For i=0 To c.RowCount -1
					c.Position=i
					LV_PRECIOS.AddTwoLines(c.GetString("NLISTA"),c.GetString("PRECIO"))
				Next
			End If
		ELSE IF PERFIL = "V-MINI" Then
			t_precio.Visible = False
			LV_PRECIOS.Visible = False

			c=Starter.skmt.ExecQuery("select PRECIO, NLISTA FROM LISTA_PRECIOS WHERE NLISTA = '2' AND  CAT_GP_ID =" & "'" &L_PROID.TEXT&"' ORDER BY NLISTA ASC")
			c.Position=0
			l_precio.Text = c.GetString("PRECIO")
			c.Close
		ELSE IF PERFIL = "V-COSTO" Then

			t_precio.Visible = False
			LV_PRECIOS.Visible = False

			c=Starter.skmt.ExecQuery("select PRECIO, NLISTA FROM LISTA_PRECIOS WHERE NLISTA = '9' AND  CAT_GP_ID =" & "'" &L_PROID.TEXT&"' ORDER BY NLISTA ASC")
			c.Position=0
			l_precio.Text = c.GetString("PRECIO")
			c.Close
		ELSE IF PERFIL = "V-SUPER" Then

			t_precio.Visible = False
			LV_PRECIOS.Visible = False

			c=Starter.skmt.ExecQuery("select PRECIO, NLISTA FROM LISTA_PRECIOS WHERE NLISTA ='9' AND  CAT_GP_ID =" & "'" &L_PROID.TEXT&"' ORDER BY NLISTA ASC")
			c.Position=0
			l_precio.Text = c.GetString("PRECIO")
			c.Close
		End If
	End If
End Sub

Sub guardar_Click
	If cantidad.Text = "" Then
		Panel1.Visible= False
	ELSE If cantidad.Text > l_bodega.Text Then
		Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
	Else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C > 0 And cantidad.Text > 0 Then
		Starter.skmt.ExecNonQuery("delete from PROIDID")
		
		Starter.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
		c=Starter.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 0)")
		c.Position =0
		If c.GetString("CUANTOSD") = 0 Then
			Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA") 'ignore
		Else
			c=Starter.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 0)")
			C.Position =0
			TOT_ART_PROMO = C.GetString("TOT_ART_PROMO")
			COSTO_TOT = C.GetString("COSTO_TOT")
			C.Close
		
			c=Starter.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO = 0 AND CAT_DP_TIPO = 1)")
			c.Position =0
			If c.GetString("CUANTOSD") = 0 Then
				TOT_ART_PROMOR = "0" 'Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA")
			Else
				c=Starter.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO = 0 AND CAT_DP_TIPO = 1)")
				C.Position =0
				TOT_ART_PROMOR = C.GetString("TOT_ART_PROMO")
			End If
			C.Close
		
		
			PROMO_C = PROMO_C * cantidad.Text
			PROMO_CR = PROMO_CR * cantidad.Text
		
			If  TOT_ART_PROMO = PROMO_C And TOT_ART_PROMOR = PROMO_CR Then
				' anterior a 29/06/2015
				'skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID))", Array As Object(l_precio.text/(TOT_ART_PROMO/cantidad.Text),l_precio.text/(TOT_ART_PROMO/cantidad.Text)))
				'en pe_cedis meto el codigo de promocion para hacer esta validacion.
				Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_CEDIS = (?) WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID))", Array As Object(L_PROID.text))
				D=Starter.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 0")
				If D.RowCount>0 Then
					For i=0 To D.RowCount -1
						D.Position=i
			 
						Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND  PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
    	
					Next
				End If
				D.Close
				D=Starter.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND CAT_DP_PRECIO = 0 AND CAT_DP_TIPO = 1")
				If D.RowCount>0 Then
					For i=0 To D.RowCount -1
						D.Position=i
			 
						Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND  PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
    	
					Next
				End If
				D.Close
				DateTime.DateFormat = "MM/dd/yyyy"
				sDate=DateTime.Date(DateTime.Now)
				sTime=DateTime.Time(DateTime.Now)
   		
				c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
				c.Position=0
				clie_id = c.GetString("CUENTA")
				c.Close

				c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
				c.Position=0
				cl_ruta = c.GetString("CAT_CL_RUTA")
				c.Close
				
				c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
				c.Position=0
				usuario = c.GetString("USUARIO")
				'skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO) VALUES(?,?,?,?,?,?,?,?,?) ", Array As Object ("COACALCO",cantidad.Text * l_precio.Text, l_precio.text, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario))
				'para insertar la promo de ades el de regalo en 0
				e=Starter.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 AND CAT_DP_PRECIO = 0")
				If e.GetString("CUANTOS") > 0 Then
					F=Starter.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 AND CAT_DP_PRECIO = 0")
					'se coloco el if por la mala promocion.
					For i=0 To F.RowCount -1
						F.Position=i
						h=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE from " & query & " where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
						h.Position=0
						Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
						h.Close
					Next
					f.Close
				End If
				e.Close
				Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
				Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
			Else
				Msgbox("Tiene " & TOT_ART_PROMO & " " & TOT_ART_PROMOR & " y necesita " & PROMO_C & " " & PROMO_CR & " Para la Promo. " , "ADVERTENCIA") 'ignore
			End If
		End If
		
		cantidad.Text = ""
		Panel1.Visible= False
	else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C = 0 Then
		Starter.skmt.ExecNonQuery("delete from PROIDID")
		Starter.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
		c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
		c.Position=0
		clie_id = c.GetString("CUENTA")
		c.Close
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
		c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position=0
		cl_ruta = c.GetString("CAT_CL_RUTA")
		c.Close
		c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
		'para insertar la promo de ades el de regalo en 0
		e=Starter.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) ")
		e.Position =0
		If e.GetString("CUANTOS") > 0 Then
			F=Starter.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS, CAT_DP_PRECIO FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID)")
			For i =0 To f.RowCount -1
				F.Position =i
				h=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE from " & query & " where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
				h.Position=0
				Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,f.GetString("CAT_DP_PRECIO") * cantidad.text * f.GetString("CAT_DP_PZAS"), f.GetString("CAT_DP_PRECIO"), f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
				h.Close
			Next
			f.Close
		End If
		e.Close
		Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
		Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
		cantidad.Text = ""
		c=Starter.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
		Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps,ALMACEN,cl_ruta,c.GetString("TOTAL_CLIE_SIN")))
		Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
		Panel1.Visible= False
	Else
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
		c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
		c.Position=0
		clie_id = c.GetString("CUENTA")
		c.Close
		c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position=0
		cl_ruta = c.GetString("CAT_CL_RUTA")
		c.Close
		c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
	
		Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (ALMACEN,cantidad.Text * l_precio.Text, l_precio.text, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,preciosin,"VENTA",precio2))
		Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
		c=Starter.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
		Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps,ALMACEN,cl_ruta,c.GetString("TOTAL_CLIE_SIN")))
		Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
		Panel1.Visible= False
	End If
End Sub

Sub GPS_LocationChanged (Location1 As Location)
'	lat_gps=Location1.ConvertToSeconds(Location1.Latitude)
'	lon_gps=Location1.ConvertToSeconds(Location1.Longitude)
End Sub

Sub Terminar_Click
	If cantidad.Text = "" Then
		B4XPages.ShowPage("Cliente")
	ELSE If cantidad.Text > l_bodega.Text Then
		Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
	Else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C > 0 And cantidad.Text > 0 Then
		Starter.skmt.ExecNonQuery("delete from PROIDID")
		Starter.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
		c=Starter.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 0)")
		c.Position =0
		If c.GetString("CUANTOSD") = 0 Then
			Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA") 'ignore
		Else
			c=Starter.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 0)")
			C.Position =0
			TOT_ART_PROMO = C.GetString("TOT_ART_PROMO")
			COSTO_TOT = C.GetString("COSTO_TOT")
			C.Close
			c=Starter.skmt.ExecQuery("Select count(*) as CUANTOSD from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO = 0 AND CAT_DP_TIPO = 1)")
			c.Position =0
			If c.GetString("CUANTOSD") = 0 Then
				TOT_ART_PROMOR = "0" 'Msgbox("No tiene venta el cliente para la promo", "ADVERTENCIA")
			Else
				c=Starter.skmt.ExecQuery("Select sum(pe_cant) As TOT_ART_PROMO, sum(PE_COSTO_TOT) as COSTO_TOT from pedido where PE_CLIENTE IN (Select CUENTA from cuentaa)  and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID) AND CAT_DP_PRECIO = 0 AND CAT_DP_TIPO = 1)")
				C.Position =0
				TOT_ART_PROMOR = C.GetString("TOT_ART_PROMO")
			End If
			C.Close
			PROMO_C = PROMO_C * cantidad.Text
			PROMO_CR = PROMO_CR * cantidad.Text
			If  TOT_ART_PROMO = PROMO_C And TOT_ART_PROMOR = PROMO_CR Then
				'en pe_cedis meto el codigo de promocion para hacer esta validacion.
				Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_CEDIS = (?) WHERE PE_CLIENTE IN (Select CUENTA from cuentaa) and pe_proid In (Select cat_dp_idprod from CAT_DETALLES_PAQ WHERE CAT_DP_ID In (Select PROIDID from PROIDID))", Array As Object(L_PROID.text))
				D=Starter.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND CAT_DP_PRECIO > 0")
				If D.RowCount>0 Then
					For i=0 To D.RowCount -1
						D.Position=i
						Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND  PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
					Next
				End If
				D.Close
				D=Starter.skmt.ExecQuery("select CAT_DP_ID, CAT_DP_PRECIO, CAT_DP_PRECIO_SIMPTOS, CAT_DP_IDPROD FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) AND CAT_DP_PRECIO = 0 AND CAT_DP_TIPO = 1")
				If D.RowCount>0 Then
					For i=0 To D.RowCount -1
						D.Position=i
						Starter.skmt.ExecNonQuery2("UPDATE PEDIDO SET PE_COSTOU = (?), PE_COSTO_TOT = PE_CANT * (?) , PE_COSTO_SIN = (?) WHERE PE_PROID = (?) And PE_CEDIS In (Select PROIDID from PROIDID) AND  PE_CLIENTE IN (Select CUENTA from cuentaa) ",Array As Object( D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO"), D.GetString("CAT_DP_PRECIO_SIMPTOS"),D.GetString("CAT_DP_IDPROD")))
					Next
				End If
				D.Close
				DateTime.DateFormat = "MM/dd/yyyy"
				sDate=DateTime.Date(DateTime.Now)
				sTime=DateTime.Time(DateTime.Now)
   		
				c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
				c.Position=0
				clie_id = c.GetString("CUENTA")
				c.Close
				c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
				c.Position=0
				cl_ruta = c.GetString("CAT_CL_RUTA")
				c.Close
				c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
				c.Position=0
				usuario = c.GetString("USUARIO")
				'para insertar la promo de ades el de regalo en 0
				e=Starter.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 AND CAT_DP_PRECIO = 0")
				e.Position =0
				If e.GetString("CUANTOS") > 0 Then
					F=Starter.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) and CAT_DP_TIPO = 0 AND CAT_DP_PRECIO = 0")
					'meter el otro
					F.Position =0
					h=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE from " & query & " where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
					h.Position=0
					Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
					h.Close
					f.Close
				End If
				e.Close
				Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
				Log("insertamos en PEDIDO")
				Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
			Else
				Msgbox("Tiene " & TOT_ART_PROMO & " " & TOT_ART_PROMOR & " y necesita " & PROMO_C & " " & PROMO_CR & " Para la Promo. " , "ADVERTENCIA") 'ignore
			End If
		End If
		
		cantidad.Text = ""
		Panel1.Visible= False
		B4XPages.ShowPage("Cliente")
	else If l_marca.text = "PROMOS" And l_tipo.Text ="PROMOS" And PROMO_C = 0 Then
		Starter.skmt.ExecNonQuery("delete from PROIDID")
		
		Starter.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
		c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
		c.Position=0
		clie_id = c.GetString("CUENTA")
		c.Close
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
 
		c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position=0
		cl_ruta = c.GetString("CAT_CL_RUTA")
		c.Close
		
		c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
		'para insertar la promo de ades el de regalo en 0
		e=Starter.skmt.ExecQuery("select count(*) as CUANTOS FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID) ")
		e.Position =0
		If e.GetString("CUANTOS") > 0 Then
			F=Starter.skmt.ExecQuery("select CAT_DP_IDPROD, CAT_DP_PZAS, CAT_DP_PRECIO FROM CAT_DETALLES_PAQ WHERE CAT_DP_ID IN (Select PROIDID from PROIDID)")
			For i =0 To f.RowCount -1
				F.Position =i
				h=Starter.skmt.ExecQuery2("select CAT_GP_NOMBRE from " & query & " where CAT_GP_ID = ? ", Array As String(f.GetString("CAT_DP_IDPROD")))
				h.Position=0
				Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,f.GetString("CAT_DP_PRECIO") * cantidad.text * f.GetString("CAT_DP_PZAS"), f.GetString("CAT_DP_PRECIO"), f.GetString("CAT_DP_PZAS") * cantidad.text, h.GetString("CAT_GP_NOMBRE"), f.GetString("CAT_DP_IDPROD"),clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
				h.Close
			Next
			f.Close
		End If
		e.Close
		Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (L_PROID.text,0, 0, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,"VENTA",precio2))
		Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
		cantidad.Text = ""
		c=Starter.skmt.ExecQuery("select sum(pe_costo_tot) as TOTAL_CLIE, SUM(PE_CANT) AS CANT_CLIE, SUM(PE_COSTO_SIN) AS TOTAL_CLIE_SIN FROM PEDIDO WHERE PE_CLIENTE IN (Select CUENTA from cuentaa)")
		c.Position=0
		Starter.skmt.ExecNonQuery("delete from pedido_cliente where PC_CLIENTE In (select cuenta from cuentaa)")
		Starter.skmt.ExecNonQuery2("insert into pedido_cliente(PC_CLIENTE, PC_FECHA, PC_USER, PC_NOART, PC_MONTO,PC_LON, PC_LAT,PC_ALMACEN,PC_RUTA,PC_COSTO_SIN) VALUES (?,?,?,?,?,?,?,?,?,?)", Array As Object(clie_id, sDate & sTime, usuario, c.GetString("CANT_CLIE"),c.GetString("TOTAL_CLIE"), B4XPages.MainPage.lon_gps, B4XPages.MainPage.lat_gps,  ALMACEN,cl_ruta, c.GetString("TOTAL_CLIE_SIN")))
		Starter.skmt.ExecNonQuery("UPDATE kmt_info set gestion = 2  where CAT_CL_CODIGO In (select cuenta from cuentaa)")
		B4XPages.ShowPage("Cliente")
	Else
		DateTime.DateFormat = "MM/dd/yyyy"
		sDate=DateTime.Date(DateTime.Now)
		sTime=DateTime.Time(DateTime.Now)
		c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
		c.Position=0
		clie_id = c.GetString("CUENTA")
		c.Close
		c=Starter.skmt.ExecQuery("select CAT_CL_RUTA from kmt_info where CAT_CL_CODIGO In (Select cuenta from cuentaa)")
		c.Position=0
		cl_ruta = c.GetString("CAT_CL_RUTA")
		c.Close
		
		c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
		c.Position=0
		usuario = c.GetString("USUARIO")
	
		Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_RUTA,PE_COSTO_SIN,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ", Array As Object (ALMACEN,cantidad.Text * l_precio.Text, l_precio.text, cantidad.text, l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,cl_ruta,preciosin,"VENTA",precio2))
		Log("Insertamos en PEDIDO")
		Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
		Panel1.Visible= False
		B4XPages.ShowPage("Cliente")
	End If
End Sub

Sub i_fotol_Click
	i_fotol.Visible = False

End Sub

Sub DESC_PROMO_Click 'BORRAR
'	Starter.skmt.ExecNonQuery("delete from PROIDID")
'	Starter.skmt.ExecNonQuery2("INSERT INTO PROIDID VALUES (?)", Array As Object(L_PROID.text))
'	B4XPages.ShowPage("Detalle_Promo")
End Sub

Sub nopromo_Click 'BORRAR
'	c=Starter.skmt.ExecQuery2("select CAT_VA_VALOR from CAT_VARIABLES WHERE CAT_VA_DESCRIPCION = ?", Array As String ("CAMBIOS"))
'	c.Position =0
'	CAMBIOS = c.GetString("CAT_VA_VALOR")
'	c.Close
'	If CAMBIOS = "1" Then
'		c=Starter.skmt.ExecQuery("select COUNT(*) AS CUANTOS from HIST_RMI WHERE HR_CLIENTE IN (Select CUENTA from cuentaa) and  HR_PROID = '" & L_PROID.Text & "'")
'		c.Position =0
'		EXISTE_CAMBIO = c.GetString("CUANTOS")
'		c.Close
'		If EXISTE_CAMBIO = 0 Then
'			EXISTE_CAMBIO = 0
'		Else
'			c=Starter.skmt.ExecQuery("select SUM(HR_CANT) AS CUANTOS from HIST_RMI WHERE HR_CLIENTE IN (Select CUENTA from cuentaa) and  HR_PROID = '" & L_PROID.Text & "'")
'			c.Position =0
'			EXISTE_CAMBIO = c.GetString("CUANTOS")
'			c.Close
'		End If
'		If EXISTE_CAMBIO = 0 Then
'			Msgbox("NO SE VENDIO ESTE PRODUCTO, NO SE PUEDE CAMBIAR","ALERTA") 'ignore
'		ELSE If cantidad.Text = "" Then
'			Msgbox("Cantidad no puede ser 0","Cantidad") 'ignore
'		Else If cantidad.Text > EXISTE_CAMBIO Then
'			Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
'		Else
'			DateTime.DateFormat = "MM/dd/yyyy"
'			sDate=DateTime.Date(DateTime.Now)
'			sTime=DateTime.Time(DateTime.Now)
'			c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
'			c.Position=0
'			clie_id = c.GetString("CUENTA")
'			c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
'			c.Position=0
'			usuario = c.GetString("USUARIO")
'			Starter.skmt.ExecNonQuery2("INSERT INTO  PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object ("DUR",0,0, cantidad.text,"CAMBIO" & l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,"VENTA",precio2))
'			Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
'			cantidad.Text = ""
'			Panel1.Visible= False
'		End If
'	Else
'		If cantidad.Text > 15 Then
'			Msgbox("Exede la existencia", "ADVERTENCIA") 'ignore
'		Else
'			DateTime.DateFormat = "MM/dd/yyyy"
'			sDate=DateTime.Date(DateTime.Now)
'			sTime=DateTime.Time(DateTime.Now)
'			c=Starter.skmt.ExecQuery("Select CUENTA from cuentaa")
'			c.Position=0
'			clie_id = c.GetString("CUENTA")
'			c=Starter.skmt.ExecQuery("select USUARIO from usuarioa")
'			c.Position=0
'			usuario = c.GetString("USUARIO")
'	
'			Starter.skmt.ExecNonQuery2("INSERT INTO PEDIDO (PE_CEDIS,PE_COSTO_TOT,PE_COSTOU,PE_CANT,PE_PRONOMBRE,PE_PROID,PE_CLIENTE,PE_FECHA,PE_USUARIO,PE_TIPO,PE_PRECIO2) VALUES(?,?,?,?,?,?,?,?,?,?,?) ", Array As Object ("DUR",0,0, cantidad.text,"CAMBIO" & l_desc.text, L_PROID.Text,clie_id, sDate & sTime, usuario,"VENTA",precio2))
'			Starter.skmt.ExecNonQuery2("update " & query & " set cat_gp_almacen = cat_gp_almacen - ? where cat_gp_id = ? ", Array As Object(cantidad.Text, L_PROID.Text))
'			cantidad.Text = ""
'			Panel1.Visible= False
'		End If
'	End If
End Sub

Sub LV_PRECIOS_ItemClick (Position As Int, Value As Object) 'BORRAR
'	c=Starter.skmt.ExecQuery("select PRECIO, NLISTA FROM LISTA_PRECIOS WHERE NLISTA = " & "'" & Value &"' AND  CAT_GP_ID =" & "'" &L_PROID.TEXT&"' ORDER BY NLISTA ASC")
'	c.Position=0
'	l_precio.Text = c.GetString("PRECIO")
'	c.Close
End Sub

'****************************************************************************
'***************** PARA EL MAS/MENOS *************************************
'****************************************************************************

Sub B_MENOS_Click
	If cantidad.Text = "" Then
		cantidad.Text = ""
	Else IF cantidad.Text > 0 Then
		cantidad.Text = cantidad.Text -1
	End If
End Sub

Sub B_MAS_Click
	If cantidad.Text = "" Then
		cantidad.Text = 1
	Else
		cantidad.Text = cantidad.Text + 1
	End If
End Sub

Sub llenaProductos(limpiar As Boolean)
	If limpiar Then clv_productos.Clear
	Private c2 As Cursor
'	c2 = Starter.skmt.ExecQuery("select REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_PRECIO, REP_PRODID from REPARTO where REP_RECHAZO = 1 and REP_CANT <> '0'")
	c2 = Starter.skmt.ExecQuery("Select rep_cliente As cliente, rep_idalmacen, rep_prodid As prodid, rep_pronombre As nombre, rep_precio As precio, rep_cant As cantidad, rep_prodregistro as registro, 'r' as f from reparto where REP_RECHAZO = 1 And REP_CANT > 0 order by REP_PRODID")
'	Private cv As Cursor = Starter.skmt.ExecQuery("Select v_cliente_orig As cliente, V_PRODID As prodid, V_PRODNOMBRE As nombre, V_PRECIO As precio, v_cantidad As cantidad, v_prodregistro as registro, 'v' as f from ventas where V_CLIENTE in (select cuenta from cuentaa)")

	Private bgColor, textColor As Int
	bgColor = Colors.RGB(177, 200, 249)'azul
	clv_productos.Clear : Log("limpiamos productos")
	If c2.RowCount > 0 And clv_productos.Size <> c2.RowCount Then
		Log("******  TRAEMOS RECHAZOS DESDE REPARTO")
		For i=0 To c2.RowCount -1
			c2.Position=i
			Private inv, inv2 As Int
			If c2.GetString("f") = "r" Then
				inv = c2.GetString("cantidad")
				inv2 = 0
			Else
				inv = 0
				inv2 = c2.GetString("cantidad")
			End If
'			LogColor($"${c2.GetString("nombre")}, ${c2.GetString("precio")}, ${inv}, ${inv2}, ${c2.GetString("cliente")}"$, Colors.Blue)
			textColor = Colors.Black
			clv_productos.Add(CreateListItem(c2.GetString("nombre"), Subs.traePrecio(c2.GetString("prodid"), 1), inv, inv2, c2.GetString("cliente"), clv_productos.AsView.Width, 50dip, bmp, c2.GetString("prodid"), bgColor, textColor, c2.GetString("REP_IDALMACEN")), c2.GetString("nombre"))
		Next
	End If
'	If cv.RowCount > 0 Then
'		Log("******+  VENTAS")
'		For i=0 To cv.RowCount -1
'			cv.Position=i
'			Private inv, inv2 As Int
'			If cv.GetString("f") = "r" Then
'				inv = cv.GetString("cantidad")
'				inv2 = 0
'			Else
'				inv = 0
'				inv2 = cv.GetString("cantidad")
'			End If
'			LogColor($"${cv.GetString("nombre")}, ${cv.GetString("precio")}, ${inv}, ${inv2}, ${cv.GetString("cliente")}"$, Colors.red)
'			textColor = Colors.Black
'			clv_productos.Add(CreateListItem(cv.GetString("nombre"), cv.GetString("precio"), inv, inv2, cv.GetString("cliente"), clv_productos.AsView.Width, 50dip, bmp, cv.GetString("prodid"), bgColor, textColor), cv.GetString("nombre"))
'		Next
'	End If
'	ponProdsEnCero
	c2.Close
End Sub

Sub CreateListItem(Text As String, precioU As String, inv As Int, inv2 As Int, cliente As String, Width As Int, Height As Int, img As Bitmap, prodId As String, bc As Int, tc As Int, idAlmacen As String) As Panel
	Dim p As B4XView = xui.CreatePanel("")
	p.SetLayoutAnimated(0, 0, 0, Width, Height)
	p.LoadLayout("prodItem")
'	Log($"***************** PROD=${prodId}, INV2=${inv2}, INV=${inv}"$)
	If inv2 <> "0" Then l_vendido.Visible = True
'	Log($"***************** PROD=${prodId}, INV2=${inv2}, INV=${inv}"$)
	p_prods.Color = bc
	l_prodX.TextColor = tc
	l_prodX.Text = Text&CRLF&"# " & inv & " $ " & precioU
	l_prodX.Tag = $"ID: ${prodId}${CRLF}${Text}${CRLF}Precio: $$1.2{precioU}${CRLF}Inv: ${inv} pzs"$
	l_vendido.Tag = precioU&"|"&inv&"|"&prodId&"|"&inv2&"|"&cliente&"|"&idAlmacen
	p_prods.Tag = precioU&"|"&inv&"|"&prodId&"|"&inv2&"|"&cliente&"|"&idAlmacen
	l_pCant.Tag = precioU&"|"&inv&"|"&prodId&"|"&cliente&"|"&idAlmacen
	et_pCant.Tag = precioU&"|"&inv&"|"&prodId&"|"&cliente&"|"&idAlmacen
'	l_pCant.Text = 0
'	et_pCant.Text = inv2
	et_pCant.BringToFront
'	i_prod.Bitmap = img
	Return p
End Sub

Sub p_prods_Click
	Log(Sender.As(Panel).tag)
End Sub

Sub b_prodMenos_Click
	etCantHasFocus = False
	LogColor("b_prodMenos_Click", Colors.Magenta)
	Dim index As Int = clv_productos.GetItemFromView(Sender)
	Dim pnl0 As B4XView = clv_productos.GetPanel(index)
	Dim pnl As B4XView = pnl0.GetView(0)
	Dim laCant As B4XView = pnl.GetView(2).GetView(3)
'	Log(pnl.GetView(2).GetView(0) & "|" & pnl.GetView(2).GetView(1) & "|" & pnl.GetView(2).GetView(2))
'	Log($"precio|stock:${laCant.tag}"$)
	If laCant.Text = "" Then laCant.Text = 0
	laCant.Text = $"$1.0{laCant.Text-1}"$
	If laCant.Text < 0 Then laCant.Text = 0
	
	Dim esteTag As List = Regex.Split("\|", laCant.Tag)
	Log($"ACTUALIZAMOS REPARTO"$)
	Private precio As String = Subs.traePrecio(esteTag.Get(2), 1)
	Private prodId As String = esteTag.Get(2)
	Private clienteOriginal As String = esteTag.get(3)
	Starter.skmt.ExecNonQuery2("update HIST_VENTAS set HVD_PARCIAL = 1, HVD_CANT = 0, HVD_COSTO_TOT = '0' WHERE HVD_PROID = ? and HVD_CLIENTE in (Select CUENTA from cuentaa)", Array As String(prodId))
	Starter.skmt.ExecNonQuery($"update reparto set REP_CANT = REP_CANT + 1 where REP_CLIENTE = '${clienteOriginal}' and REP_CLI_ORIG = '${clienteOriginal}' and REP_RECHAZO = 1 and REP_PRODID = '${prodId}'"$)
	Starter.skmt.ExecNonQuery($"update reparto set REP_CANT = REP_CANT - 1 where REP_CLIENTE in (Select CUENTA from cuentaa) and REP_CLI_ORIG = '${clienteOriginal}' and REP_RECHAZO = 0 and REP_PRODID = '${prodId}'"$)
'		Log($"update reparto set REP_CANT = REP_CANT + 1 where REP_CLIENTE = '${clienteOriginal}' and REP_CLI_ORIG = '${clienteOriginal}' and REP_RECHAZO = 1 and REP_PRODID = '${prodId}'"$)
'		Log($"update reparto set REP_CANT = REP_CANT - 1 where REP_CLIENTE in (Select CUENTA from cuentaa) and REP_CLI_ORIG = '${clienteOriginal}' and REP_RECHAZO = 0 and REP_PRODID = '${prodId}'"$)
	Starter.skmt.ExecNonQuery($"update reparto set REP_COSTO_TOT = REP_CANT * ${precio}, REP_PRECIO = '${precio}' where REP_CLIENTE in (Select CUENTA from cuentaa) and REP_CLI_ORIG = '${clienteOriginal}'  and REP_PRODID = '${prodId}'"$)

'	Dim chk As B4XView = pnl.GetView(2)
	cuentaProds
End Sub

Sub b_prodMas_Click
	etCantHasFocus = False
	LogColor("b_prodMas_Click", Colors.Magenta)
	Dim index As Int = clv_productos.GetItemFromView(Sender)
	Dim pnl0 As B4XView = clv_productos.GetPanel(index)
	Dim pnl As B4XView = pnl0.GetView(0)
	Dim laCant As B4XView = pnl.GetView(2).GetView(3)
'	Log(pnl.GetView(2).GetView(1).text&"|"&pnl.GetView(2).GetView(2)&"|"&pnl.GetView(2).GetView(4).text)
	Log($"precio|stock:${laCant.tag}"$)
	Log($"Indice: ${index}, cant:${laCant.Text+1}, precioU: ${laCant.tag}"$)
	Dim esteTag As List = Regex.Split("\|", laCant.Tag)
	Log("LC_TEXT:"&laCant.Text&"|LC_TAG:"&laCant.Tag&"|ET:"&esteTag)
	If laCant.Text = "" Then laCant.Text = 0
	If laCant.Text + 1 <= esteTag.get(1) Then
		laCant.Text = $"$1.0{laCant.Text+1}"$
		LogColor("XXXXXXXXX " & esteTag, Colors.Green)
		Private precio As String = Subs.traePrecio(esteTag.Get(2), 1)
		
		Private rv As Cursor = Starter.skmt.ExecQuery($"select count(*) as hayVenta from REPARTO where REP_PRODID = '${esteTag.Get(2)}' and REP_CLIENTE in (Select cuenta from cuentaa) and REP_CLI_ORIG = '${esteTag.Get(3)}'"$)
		rv.Position = 0
		If rv.GetString("hayVenta") = 0 Then
			Log("Insertamos en REPARTO")
			Private cp As Cursor = Starter.skmt.ExecQuery($"select * from HIST_VENTAS where HVD_PROID = '${esteTag.Get(2)}' and HVD_CLIENTE = '${esteTag.get(3)}'"$)
			If cp.RowCount > 0 Then
				cp.Position = 0
				Log(esteTag)
				Starter.skmt.ExecNonQuery2("insert into reparto(REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA, REP_RECHAZO, REP_PRODID, REP_PRECIO, REP_PRODREGISTRO, REP_CLI_ORIG, REP_IDALMACEN) VALUES (?,?,?,?,?,1,?,?,?,?,?) ", Array As String(Subs.traeCliente, cp.GetString("HVD_PRONOMBRE"), 0, cp.GetString("HVD_COSTO_TOT"), Subs.fechaKMT(DateTime.now), cp.GetString("HVD_PROID"), precio, 50, esteTag.get(3), esteTag.get(4)))
				Log(4)
				Starter.skmt.ExecNonQuery2("insert into reparto(REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA, REP_RECHAZO, REP_PRODID, REP_PRECIO, REP_PRODREGISTRO, REP_CLI_ORIG, REP_IDALMACEN) VALUES (?,?,?,?,?,0,?,?,?,?,?) ", Array As String(Subs.traeCliente, cp.GetString("HVD_PRONOMBRE"), laCant.text, cp.GetString("HVD_COSTO_TOT"), Subs.fechaKMT(DateTime.now), cp.GetString("HVD_PROID"), precio, 50, esteTag.get(3), esteTag.get(4)))
				Log(5)
				Starter.skmt.ExecNonQuery($"update reparto set REP_CANT = REP_CANT - 1, REP_PRECIO = '${precio}', REP_COSTO_TOT = ((REP_CANT - 1) * REP_PRECIO) where REP_CLIENTE = '${esteTag.get(3)}' and REP_CLI_ORIG = '${esteTag.get(3)}' and REP_RECHAZO = 1 and REP_PRODID = '${esteTag.Get(2)}'"$)
				Starter.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_nombre = ?", Array As Object(laCant.Text, cp.GetString("HVD_PRONOMBRE")))
			End If
		Else
'			Log($"update reparto set REP_CANT = REP_CANT - 1, REP_PRECIO = '${precio}', REP_COSTO_TOT = '0' where REP_CLIENTE = '${esteTag.get(3)}' and REP_CLI_ORIG = '${esteTag.get(3)}' and REP_RECHAZO = 1 and REP_PRODID = '${esteTag.Get(2)}'"$)
'			Log($"update reparto set REP_CANT = REP_CANT + 1, REP_PRECIO = '${precio}', REP_COSTO_TOT = '0' where REP_CLIENTE in (Select CUENTA from cuentaa) and REP_CLI_ORIG = '${esteTag.get(3)}' and REP_RECHAZO = 0 and REP_PRODID = '${esteTag.Get(2)}'"$)
			Starter.skmt.ExecNonQuery($"update reparto set REP_CANT = REP_CANT - 1, REP_PRECIO = '${precio}', REP_COSTO_TOT = '0' where REP_CLIENTE = '${esteTag.get(3)}' and REP_CLI_ORIG = '${esteTag.get(3)}' and REP_RECHAZO = 1 and REP_PRODID = '${esteTag.Get(2)}'"$)
			Starter.skmt.ExecNonQuery($"update reparto set REP_CANT = REP_CANT + 1, REP_PRECIO = '${precio}', REP_COSTO_TOT = '0' where REP_CLIENTE in (Select CUENTA from cuentaa) and REP_CLI_ORIG = '${esteTag.get(3)}' and REP_RECHAZO = 0 and REP_PRODID = '${esteTag.Get(2)}'"$)
			Starter.skmt.ExecNonQuery($"update reparto set REP_COSTO_TOT = REP_CANT * ${precio} where REP_CLIENTE in (Select CUENTA from cuentaa) and REP_CLI_ORIG = '${esteTag.get(3)}' and REP_RECHAZO = 1 and REP_PRODID = '${esteTag.Get(2)}'"$)
		End If
		cuentaProds
	End If
'	Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
End Sub

Private Sub et_pCant_TextChanged (Old As String, New As String)
'	LogColor($"txt changed: ${Old}|${New}, hasfocus=${etCantHasFocus}"$,Colors.Magenta)
	If Not(Old = "0" And New = "") And etCantHasFocus Then cuentaProds
End Sub

Private Sub et_pCant_FocusChanged (HasFocus As Boolean)
'	LogColor($"focus changed=${HasFocus}"$, Colors.Magenta)
	etCantHasFocus = HasFocus
	cuentaProds
End Sub

Sub cuentaProds
'	Log("CUENTAPRODS")
	totalProds = 0
	totalCompra = 0
	For i = 0 To clv_productos.GetSize - 1
		Private p0 As B4XView = clv_productos.GetPanel(i)
		Private p As B4XView = p0.GetView(0)
'		Log($"${p.GetView(2).GetView(0)}, ${p.GetView(2).GetView(1)}, ${p.GetView(2).GetView(2)}, ${p.GetView(2).GetView(3)}"$)
		Private cant1 As B4XView = p.GetView(2).GetView(3)
		If cant1.Text = "" Then cant1.Text = 0
		totalProds = totalProds + cant1.Text
		Private esteTag As List = Regex.Split("\|", cant1.Tag)
'		Log(esteTag)
		Private prodId As String = esteTag.Get(2)
		Private m As Map
'		Log($"CANTIDAD = ${cant1.text}"$)
		If cant1.Text > esteTag.Get(1) Then cant1.Text = esteTag.Get(1)
		If cant1.Text > 0 Then 'Lo agregamos al mapa
'			Log(esteTag.Get(2) & "|" & cant1.Text)
			Log("Cant > 0")
			totalCompra = totalCompra + (esteTag.get(0) * cant1.text)
			Log($"${esteTag.Get(2)}, Cant: ${cant1.Text}, Suma: ${esteTag.get(0) * cant1.text}"$)
			m=CreateMap("cant":cant1.Text, "precio":esteTag.get(0), "cli_ori":esteTag.get(3))
			prodsMap.Put(esteTag.Get(2), m)
			prodsListId.Add(esteTag.Get(2))
			prodsListCliOrig.Add(esteTag.get(3))
			prodsList.Add(m)
		Else 'Si la cantidad es CERO lo quitamos del mapa.
'			Log($"QUITAMOS EL PRODS POR CERO : ${esteTag.Get(2)}, ${esteTag.Get(3)}"$)
'			Log($"${esteTag.Get(2)}, Cant: ${cant1.Text}, Suma: ${esteTag.get(0) * cant1.text}"$)
			prodsMap.Remove(esteTag.Get(2))
			Private indice As Int = -1
'			For q=0 To prodsList.Size-1
'				If prodsListId.Get(q) = esteTag.Get(2) And prodsListCliOrig = esteTag.Get(3) Then
''					prodsList.RemoveAt(q)
'					indice = q
'					prodsListId.RemoveAt(q)
'					prodsListCliOrig.RemoveAt(q)
'				End If
'			Next
			If indice > -1 Then prodsList.RemoveAt(indice)
'			prodsList.Get(0)
		End If
		l_total.Visible = True
		l_totProds.Visible = True
		l_total.Text = $"Total: $$1.2{totalCompra}"$
		l_totProds.text = $"Prods: ${totalProds}"$
	Next
'	LogColor($"prodsmap=${prodsMap}"$, Colors.blue)
'	LogColor($"prodsListID=${prodsListId} ${CRLF}prodsList=${prodsList} ${CRLF}prodsListCliOrig=${prodsListCliOrig}"$, Colors.Magenta)
	p_botonesVenta.Visible = True
	Log($"Total Prods: ${totalProds}, Total Compra: $$1.2{totalCompra}"$)
End Sub

Private Sub b_terminar1_Click
	Log("b_terminar1_Click")
'	cuentaProds
'	Private p1 As Map
'	Log(Subs.fechaKMT(DateTime.Now))
'	For Each p As String In prodsMap.Keys
'		p1 = prodsMap.Get(p)
'		Log(p & "|" & p1)
'		Private pn As String = Subs.traeNombre(p)
'		LogColor($"---------------- prodsMap= ${prodsMap}"$, Colors.Magenta)
'		Log($"Guardamos ${p}-${pn}, cant=${p1.Get("cant")}, precio=${p1.Get("precio")}"$)
'		Starter.skmt.ExecNonQuery($"update REPARTO set REP_CANT = REP_CANT - ${p1.Get("cant")} where REP_PRODID = '${p}' and REP_RECHAZO = 1 and REP_CLIENTE = '${p1.Get("cli_ori")}' and REP_CLI_ORIG = '${p1.Get("cli_ori")}'"$)
'		Starter.skmt.ExecNonQuery($"update REPARTO set REP_CANT = REP_CANT + ${p1.Get("cant")} where REP_PRODID = '${p}' and REP_RECHAZO = 0 and REP_CLIENTE in (select cuenta from cuentaa) and REP_CLI_ORIG = '${p1.Get("cli_ori")}'"$)
'		Starter.skmt.ExecNonQuery($"update CAT_GUNAPROD set CAT_GP_ALMACEN = CAT_GP_ALMACEN - ${p1.Get("cant")} where CAT_GP_ID = '${p}'"$)
'		
'		Private rv As Cursor = Starter.skmt.ExecQuery($"select count(*) as hayVenta from REPARTO where REP_PRODID = '${p}' and REP_CLIENTE in (Select cuenta from cuentaa)"$)
'		rv.Position = 0
'		Log($"+++++++++++++++ PRODSMAP = ${p1}"$)
'		If rv.GetString("hayVenta") = 0 Then
'			Log("Insertamos en REPARTO")
'			Starter.skmt.ExecNonQuery2("insert into reparto(REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA, REP_RECHAZO, REP_PRODID, REP_PRECIO, REP_PRODREGISTRO, REP_CLI_ORIG) VALUES (?,?,?,?,?,1,?,?,?,?) ", Array As String(Subs.traeCliente, pn, 0, p1.Get("cant") * p1.Get("precio"), Subs.fechaKMT(DateTime.now), p, p1.Get("precio"), 50, p1.Get("cli_ori")))
'			Starter.skmt.ExecNonQuery2("insert into reparto(REP_CLIENTE, REP_PRONOMBRE, REP_CANT, REP_COSTO_TOT, REP_FECHA, REP_RECHAZO, REP_PRODID, REP_PRECIO, REP_PRODREGISTRO, REP_CLI_ORIG) VALUES (?,?,?,?,?,0,?,?,?,?) ", Array As String(Subs.traeCliente, pn, p1.Get("cant"), p1.Get("cant") * p1.Get("precio"), Subs.fechaKMT(DateTime.now), p, p1.Get("precio"), 50, p1.Get("cli_ori")))
'			Starter.skmt.ExecNonQuery2("update cat_gunaprod set cat_gp_almacen = cat_gp_almacen + ? where cat_gp_nombre = ?", Array As Object(p1.Get("cant"), pn))
'		End If
'	Next
	ya_entro = "0" : Log("ya_entro=1")
''	lv_promos.Visible = False
'	clv_productos.AsView.Visible = False
'	lv_catalogos.Visible = True
'	Log("Terminar")
''	clv_productos.Clear
'	ponProdsEnCero
	prodsMap.Initialize
	B4XPages.ShowPage("Cliente")
End Sub

Private Sub p_prods_LongClick
	Log($"${Sender.As(Panel).tag}"$)
	Private esteTag As List = Regex.Split("\|", Sender.As(Panel).Tag)
	Log($"|${esteTag.Get(3)}|"$)
	If esteTag.Get(3) <> "0" Then
		Log("VENDIDO")
		borraProdVenta(esteTag.Get(2), esteTag.Get(5))
	Else
		Log("NO VENDIDO")
	End If
End Sub

Private Sub l_vendido_LongClick
	Log($"${Sender.As(Label).tag}"$)
	Private esteTag As List = Regex.Split("\|", Sender.As(Label).Tag)
	Log($"|${esteTag.Get(3)}|"$)
	If esteTag.Get(3) <> "0" Then
		Log("VENDIDO")
		borraProdVenta(esteTag.Get(2), esteTag.Get(5))
	Else
		Log("NO VENDIDO")
	End If
End Sub

Sub borraProdVenta(prodId As String, idAlmacen As String)
	Private cant As Int = 0
	Private cliOrig As String = ""
	Private RES As String =  Msgbox2("Seguro que desea borrar este producto?","Borrar", "Si", "", "No",LoadBitmap(File.DirAssets,"alert2.png")) 'ignore
	If RES = DialogResponse.POSITIVE Then
'	Private rr As Cursor = Starter.skmt.ExecQuery($"select REP_CANT from REPARTO where REP_PRODID = '${prodId}' and REP_RECHAZO = 0 and REP_CLIENTE in (select CUENTA from CUENTAA)"$)
		LogColor($"Buscamos - ${prodId}, ${cant}"$, Colors.Blue)
		Private rr As Cursor = Starter.skmt.ExecQuery($"select * from VENTAS where V_CLIENTE in (select CUENTA from CUENTAA) and V_PRODID = '${prodId}'"$)
		Log($"ID=${prodId}, RC=${rr.RowCount}"$)
		If rr.RowCount > 0 Then 'Si hay producto con venta en VENTAS ...
			rr.Position = 0
			cant = rr.GetInt("V_CANTIDAD")
			cliOrig = rr.GetString("V_CLIENTE_ORIG")
			LogColor($"Hay prod con venta en VENTAS - ${prodId}, ${cant}"$, Colors.Blue)
			Starter.skmt.ExecNonQuery($"update CAT_GUNAPROD set CAT_GP_ALMACEN = CAT_GP_ALMACEN + ${cant} where CAT_GP_ID = '${prodId}'"$)
		End If
		Starter.skmt.ExecNonQuery($"update REPARTO set REP_CANT = REP_CANT + ${cant} where REP_RECHAZO = 1 and REP_IDALMACEN = '${idAlmacen}' and REP_PRODID = '${prodId}' and REP_CLIENTE = '${cliOrig}'"$)
		Starter.skmt.ExecNonQuery($"update REPARTO set REP_CANT = REP_CANT - ${cant} where REP_RECHAZO = 0 and REP_IDALMACEN = '${idAlmacen}' and REP_PRODID = '${prodId}' and REP_CLIENTE = '${cliOrig}'"$)
		Starter.skmt.ExecNonQuery($"delete from VENTAS where V_PRODID = '${prodId}' and V_CLIENTE_ORIG = '${cliOrig}' and V_CLIENTE in (select CUENTA from CUENTAA)"$)
		B4XPages.ShowPage("Cliente")
	End If
End Sub