PARAMETERS cBdd, lJson


PUBLIC  oApp, oShell
*PUBLIC oHTTP, oIP, iHTTP

oShell = createobject("WScript.Shell")

*!*	oIP = CREATEOBJECT("wwFTP")
*!*	oHTTP = CREATEOBJECT("wwHttp")
*!*	iHTTP = CREATEOBJECT("wwHttp")

PUBLIC conexion

conexion = CREATEOBJECT( "MSXML2.ServerXMLHTTP" )

SET PROCEDURE TO json/qdfoxJSON ADDITIVE
JSONStart()


PUBLIC a_t_fields, aJson, nLenJson

oApp = CREATEOBJECT ('ClassApp',cBdd, lJson)


DEFINE CLASS ClassApp AS CUSTOM 

nConn            = -1
Pswd			 = 'tecsicom'

t_nfields		 = 0
nSizeold		 = 12

lConnHost		 = .F.
nHTTPGetEx		 = 0

lgServ			 = .f.

emailconfig 	 = 'smtp.gmail.com|xxxxx@gmail.com|xxxxx@gmail.com|xxxxx|587'
emailconfig_set  = ''


cbEnterprise 	 = ''
cbManager    	 = ''
cbAddress    	 = ''
cbAddressSucursal = ''
cbDireccion   	 = ''
cbPhone      	 = ''
cbFax        	 = ''
cbZip        	 = ''
cbRUC        	 = ''
cbCity       	 = ''
cbState      	 = ''
cbPrefixState	 = ''
cbCountryName	 = ''
cbEmail       	 = ''
cbWeb        	 = ''
cbSection     	 = ''
cbComercio	 	 = ''
cbComercio1	 	 = ''
cbRucContador    = ''
cbCedulaRL       = ''
cbContribuyenteEspecial = ''
cbobligadocont   = ''
cbAutorizacion   = ''
cbValidez		 = ''
cbURLLogo		 = ''
print_lin_factura  = 20
cErr		= ''
lGhostLocal = .F.
lGhostLocalFE = .F.
cRutaWWW ='/wamp/www/data/'
lpublicidad = .F.
cPuertoWamp      =''

ltestsql = .f.

lOffLine = .T.

lError = .F.

version = 5

lsubsidioventas 	= .f.
lgasolinera			= .f.

json_idc = '0'

cbfechaautorizacion = ''
lGhost_loader_nocred = .f.
nIva 			= 12
pIva			= 1.12
nIvap			= 0.12			

cSerieUser 		= '001008'
prn_seriesec 	= ''
nInvoicer		= 60
cInvoicerType   = ''
lAppExterno     = .f.
cFechaInvoicer	= DTOC(DATE(),1)

cReportType 	= ''

lGhost_web	 	= .f.
nGhost_web		= 3  && cada 3 segundos ejecutar un link web

lGhost_json	 	= .f.
nGhost_json		= 3  && cada 3 segundos ejecutar un link web

lGhost_lGhost_upstock = .f.

lbodegas = .f. 
lboletos = .f.

alternativoDivide = .T.

cBDDSetup = ''

tipoambiente = "2"
rutaDigitalizadosFE = ''
lfacturacionelectronica = .f.
nusersucursal = 0

ghost_retardo_ventas = 0
ghost_max_connections = 10

lAutGhost = .f. 
cbdd_name = ""

ntipoemision = 2  && 0 nada, 1 pruebas, 2 produccion
demision = DATE() &&desde cuando esta vigente el ghost
dvigencia = DATE() && hasta cuando
dvigenciap = DATE() && hasta cuando dura la publicidad
lpedidos = .f.
lventas = .f.
lcompras = .f.
levale = .f.
lereceiv = .f.
lemail = .f.

lghost_fe_fv   = .f.
lghost_fe_nc   = .f.
lghost_fe_nd   = .f.
lghost_fe_gr   = .f.
lghost_fe_cr   = .f.

lGhost_fact_manual = .f. 
ghost_fet_emision = DATE()

cMsgLabel = 'Ghost: '

correo   	   = 'ghost@tecsicom.net'
etiq_correo    = 'Ghost - Facturacion Electronica'

cBdd = 'fss1'

Ghost_Version 	= 'Ghost 3.0 powered by Tecsicom'

Host 		= 'tecsicom.dnsalias.com'   &&'www.tecsicom.net'
localhost	= 'localhost'
HostJson 	= 'tecsicom.dnsalias.com'   &&'www.tecsicom.net'
Port 		= ''
PortJson 	= ''
LocalPort	= ''

FtpHost     = 'ftp.tecsicom.net'
FtpUser 	= 'data@tecsicom.net'
FtpPswd 	= 'tecsicom2012'
ltecsicom_host	= .f.

bdd 		= 'tecsicom_ghost_demo'
bdd_user 	= 'tecsicom_dventas'
bdd_pswd 	= 'Ghost2013'

cWEBResult  = ''
cIdUser = ''
cLoginUser = ''
cNameUser = ''
lJson = .f.
cFileTestDllSqlite = 'regdllsqlite'
ghost_lcontrol_stock = .F.
ldownload_msg = .f.

ghost_stock_linea = .F.

ghost_USAR_BODEGA        = 0    && Si es cero toma el stock completo, 1 toma de la bodega del usuario
ghost_MODIFICA_PRECIO    = 0    && Si es 0 no modifica precios,1 selecciona un precio A,B,C,D, si es 2 permite subir el precio en un % maximo
ghost_PORCENTAJE_PRECIO  = 0.04 && recibe el valor /100
ghost_NOTIFICA_GESTION   = 0    && 0 no Notifica, 1 Sms,2 mail, 3 mail, sms
ghost_MAIL_SUPERVISOR    = "" && Se separa con , para varios receptores
ghost_CELULAR_SUPERVISOR = "" &&Se separa con , para varios receptoresSaludos 

ghost_campo_pvp_unds = 3
ghost_campo_pvp_bultos = 4
ghost_pminb = 0
ghost_pmaxb = 3
ghost_pminu = 0
ghost_pmaxu = 8


FUNCTION init (cBdd, lJson)


	*WAIT WINDOW 'sssssss'

	IF !EMPTY(lJson)
		this.lJson = .t.
	ENDIF
	
	this.cBdd = 'fss1'
	IF !EMPTY(cBdd)
		this.cBdd = cBdd
	ENDIF

	
	IF !lJson	

		*WAIT WINDOW 'Abriendo base de datos...' nowait
		
		IF !this.openDB()
			MESSAGEBOX( 'Sin conexión a la base de datos', 63, 'Ghost')
		ENDIF
		
	
		*WAIT WINDOW 'Loadsetup...' NOWAIT 
		this.loadsetup()
		
		*WAIT WINDOW 'initview...' NOWAIT 
		this.initView()
		
		*WAIT WINDOW 'SetGhost...' NOWAIT 
		IF !this.lGhostLocalFE
			this.setGhost() && 20180608
		ENDIF
		
		*WAIT WINDOW '...' TIMEOUT .1
	ENDIF


ENDFUNC




FUNCTION setGhost (lclear)

	this.lAutGhost 		= .f. 
	this.cbdd_name 		= ""
	
	this.demision 		= DATE()
	this.dvigencia 		= DATE()
	this.lpedidos 		= .f.
	this.lventas 		= .f.
	this.lcompras 		= .f.
	this.levale 		= .f.
	this.lereceiv 		= .f.
	this.lemail 		= .f.
	this.lghost_fe_fv   = .f.
	this.lghost_fe_nc   = .f.
	this.lghost_fe_nd   = .f.
	this.lghost_fe_gr   = .f.
	this.lghost_fe_cr   = .f.

	this.tipoambiente 	= this.ntipoemision

	cWEB = '@@'
	
	cFileConfig = ALLTRIM(transform(SYS(11,DATE())))
	cFileConfigIdc = cFileConfig+'.idc'	
	
	cFileKey = '\ghost_key\ghost_key_'+ALLTRIM(this.cbRuc) 
	*WAIT WINDOW cFileKey
	
	lKeyGhost = FILE(cFileKey)
	
	
	IF lKeyGhost
		cWeb = this.Desencripta(FILETOSTR(cFileKey))
		lSeguir = .T.
		*MESSAGEBOX(cWeb)
	ELSE
		
		
		cFileConfig0 = ALLTRIM(transform(VAL(SYS(11,DATE()))-1))
		cFileConfigIdc0 = cFileConfig0+'.idc'
		
		IF FILE(cFileConfig0)
			DELETE FILE (cFileConfig0)
			DELETE FILE (cFileConfigIdc0)
		ENDIF
		
		IF !EMPTY(lClear)
			IF FILE(cFileConfig)
				DELETE FILE (cFileConfig)
			ENDIF
			
		ENDIF
		
		lSeguir = .T.
		IF FILE(cFileConfig)
			cWEB = FILETOSTR(cFileConfig)	
		ELSE
			this.ltecsicom_host	= .T.
			lSeguir = this.runLink("fe2/get_data.php?ruce="+this.cbRUC, @cWEB)
		ENDIF
	ENDIF
	
	
	
	
				*MESSAGEBOX(cWeb)
	
	IF (lSeguir AND cWEB!='@@' AND !EMPTY(cWEB))
	
				*MESSAGEBOX(cWeb)
	
		IF 'BDD_NAME' $ UPPER(cWEB)
		

			IF !lKeyGhost
				IF !FILE(cFileConfig)
					STRTOFILE(cWEB,cFileConfig)
				ENDIF
				
			ENDIF
			
		
						
			o = JSON.Parse(cWEB) 
			


			this.lAutGhost = .T. 
			
			this.cbdd_name 		= allTRIM(o.bdd_name)
			this.ntipoemision 	= o.tipoemision 
			this.tipoambiente 	= this.ntipoemision 
			this.demision 		= this.converD(o.emision) 
			this.dvigencia 		= this.converD(o.vigencia)
			
			
			this.dvigenciap 	= this.converD(o.vigenciap)
			
			this.lGhost_web 	= o.lweb="1"
			this.lGhost_json	= o.ljson="1"
			this.json_idc 		= o.id
			this.lOffLine 		= .t. &&o.offline="1"
			
			this.lpedidos 		= o.pedidos="1"
			this.lventas 		= o.ventas="1"
			this.lcompras 		= o.compras="1"
			this.levale 		= o.evale="1"
			this.lereceiv 		= o.ereceiv="1"
			this.lemail 		= o.email="1"
		
			this.lghost_fe_fv   = o.lghost_fe_fv="1"
			this.lghost_fe_nc   = o.lghost_fe_nc="1"
			this.lghost_fe_nd   = o.lghost_fe_nd="1"
			this.lghost_fe_gr   = o.lghost_fe_gr="1"
			this.lghost_fe_cr   = o.lghost_fe_cr="1"
			
			this.correo   		= ALLTRIM(o.correo)
			this.etiq_correo   	= ALLTRIM(o.etiq_correo)
			
			this.ghost_fet_emision = this.demision
			
			this.host 			= ALLTRIM(o.host)
			this.hostjson		= ALLTRIM(o.hostjson)
			this.localhost		= ALLTRIM(o.localhost)
			
			this.port 			= TRIM(o.port)
			this.portjson		= TRIM(o.portjson)
			
			this.localport		= TRIM(o.localport)
			
			
			this.ftphost 		= o.ftphost
			this.ftpuser 		= o.ftpuser
			this.ftppswd 		= o.ftppswd
			
			this.version 		= o.version
			
		ELSE 
			MESSAGEBOX('Error de conexion '+CHR(13)+cWEB ,63,'Ghost')
			this.lAutGhost = .f.
		ENDIF
		
		IF this.lGhostLocalFE
			this.host = IIF(!EMPTY(this.localhost),this.localhost,'localhost')
		ENDIF
		
		IF this.lGhostLocal AND this.lGserv
			*this.host = IIF(!EMPTY(this.localhost),this.localhost,'localhost')
			this.host = 'localhost'+IIF(!EMPTY(this.portjson),':'+this.portjson,'')
		ENDIF

		
	ENDIF
	
	
	*MESSAGEBOX(this.host)
	
	lSeguir = .T.
	cWeb = '0'
	IF FILE(cFileConfigIdc)
		cWEB = FILETOSTR(cFileConfigIdc)	
	ELSE
		lSeguir = this.runLink('json/json_init.php?ruc='+this.cbRuc, @cWeb)
	ENDIF
	
	*WAIT WINDOW 'json/json_init.php?ruc='+this.cbRuc

	IF lSeguir AND VAL(cWeb)>0
		STRTOFILE(cWEB,cFileConfigIdc)
		this.json_idc = ALLTRIM(cWeb)
		this.lGhost_json	= .T.
	ENDIF
	
	
	cUrl = "http://tecsicom.dnsalias.com/fe2/get_email_config.php?ruce="+this.cbRUC
	
	this.runUrl(cUrl)
	
	THIS.emailconfig_set = ""
	IF This.cWebResult!='@@'
		THIS.emailconfig_set = This.cWebResult
		*DIMENSION aMyArray[1]
		*ALINES(aMyArray, this.emailconfig_set, CHR(13)) 
		*nLIm = ALEN(aMyArray)
		*MESSAGEBOX(nLim)
	ENDIF

	
	
ENDFUNC

FUNCTION converD (cDate)
	RETURN CTOD(SUBSTR(cDate,9,2)+'/'+SUBSTR(cDate,6,2)+'/'+SUBSTR(cDate,1,4))
ENDFUNC


FUNCTION loadSetup()

	
	*this.sqlexec('select id,value from setup','curSetup')
	*SELECT curSetup
	*INDEX on id TAG uno
	*brow
	
	this.cbEnterprise 	 		= this.setup('cbEnterprise','C')
	this.cbManager    	 		= this.setup('cbManager','C')
	this.cbAddress    	 		= this.setup('cbAddress','C')
	this.cbAddressSucursal 		= this.setup('cbAddressSucursal','C')
	this.cbDireccion   	 		= this.setup('cbDireccion','C')
	this.cbPhone      	 		= this.setup('cbPhone','C')
	this.cbFax        	 		= this.setup('cbFax','C')
	
	this.cPuertoWamp			= ALLTRIM(this.setup('cPuertoWamp','C'))
	
	this.emailconfig			= ALLTRIM(this.setup('emailconfig','C',,,'smtp.gmail.com|xxxxx@gmail.com|xxxxx@gmail.com|clave_xxxxx|587'))
	
	
	
	IF !EMPTY(this.cPuertoWamp)
		this.cPuertoWamp = ":"+this.cPuertoWamp
	ENDIF
	
	
	this.ntipoemision 			= this.setup('tipoambiente','C') 
	this.tipoambiente 			= this.ntipoemision
	
	this.lPublicidad			= THIS.setup ('ghost_mark','L',,,.T.)

	this.cbZip        	 		= this.setup('cbZip','C')
	this.cbRUC        	 		= ALLTRIM(this.setup('cbRUC','C'))
	this.cbCity       	 		= PROPER(this.setup('cbCity','C'))
	this.cbState      	 		= this.setup('cbState','C')
*	this.cbPrefixState	 		= this.setup('cbPrefixState','C')
	*this.cbCountryName	 		= this.setup('cbCountryName','C')
	this.cbEmail       	 		= this.setup('cbEmail','C')
	this.cbWeb        	 		= this.setup('cbWeb','C')
	this.cbSection     	 		= ALLTRIM(this.setup('cbSection','C'))
	this.cbComercio	 	 		= ALLTRIM(this.setup('cbComercio','C'))
	this.cbComercio1	 		= this.setup('cbComercio1','C')
*	this.cbRucContador   		= this.setup('cbRucContador','C')
*	this.cbCedulaRL      		= this.setup('cbCedulaRL','C')
	this.cbContribuyenteEspecial = this.setup('cbContribuyenteEspecial','C')
	this.cbobligadocont  		= this.setup('cbobligadocont','C')
*	this.cbAutorizacion  		= this.setup('cbAutorizacion','C')
*	this.cbValidez		 		= this.setup('cbValidez','C')
*	this.cbfechaautorizacion 	= this.setup('cbfechaautorizacion','D')
	*this.cbURLLogo 				= this.setupC('PDAURLLOGO','C')
	this.rutaDigitalizadosFE 	= this.setup('rutaDigitalizadosFE','C') && facturacion electronica
	this.lsubsidioventas		= this.setup('lsubsidioventas','L')
	this.lgasolinera			= this.setup('lgasolinera','L')
	
	IF EMPTY(this.cbAddressSucursal)
		this.cbAddressSucursal = this.cbAddress
	ENDIF
	this.niva			= this.setup('TAXPERCENT','N',,,12)
	this.piva			= this.niva/100+1.0
	this.nIvap			= this.niva/100
	this.lfacturacionelectronica = this.setup('GHOST_lfacturacionelectronica','L')
	
	this.lGhostLocal	= this.setup ('lGhostLocal','L')
	this.lGhostLocalFE  = this.setup ('lGhostLocalFE','L')
	
	this.host           = ALLTRIM(this.setup('GHOST_HOST','C')) &&,,,'http://ghost.dnsalias.net')) && tecsicom.net
	
	this.cRutaWWW = this.setup('cRutaWWW ','C',,,'/wamp/www/data/')
	
	
*	http://tecsicom.dnsalias.com/fe2/get_email_config.php
	
	
ENDFUNC


FUNCTION loadGhost

	
	this.print_lin_factura 		= this.setup('print_lin_factura','N')	
	this.ghost_lcontrol_stock 	= this.setup('ghost_lcontrol_stock','L')
	
	
	
	this.ghost_stock_linea	= this.setup('ghost_stock_linea','L')

	this.lGhost_fact_manual 	= this.setup('lGhost_fact_manual','L')	
	this.lbodegas 				= this.setup('lBodegas','L')
	this.lboletos 				= this.setup('lboletos','L')
	this.ghost_retardo_ventas 	= this.setup('ghost_retardo_ventas','N') 
	this.ghost_max_connections 	= this.setup('ghost_max_connections','N',10) 
	this.alternativoDivide 		= this.setup('alternativoDivide','L',.T.)
	this.lAppExterno			= this.setup('ghost_lAppExterno','L') 
	this.nInvoicer				= INT(this.setup('ghost_invoicer_timeout','N',60))
	this.cInvoicerType  		= this.setup('ghost_invoicer_type','C')

	IF EMPTY(this.cInvoicerType)
		this.lAppExterno = .f.
		this.cInvoicerType  = ""
	ENDIF
	
	
	this.lGhost_web 			= this.setup('ghost_lGhost_web','L') 
	this.nGhost_web				= INT(this.setup('ghost_nGhost_web','N',3))
	this.lGhost_lGhost_upstock 	= this.setup('ghost_lGhost_upstock','L') 
	this.lGhost_loader_nocred 	= this.setup('ghost_lGhost_loader_nocred','L') 
	this.ntipoemision 			= this.setup('tipoambiente','C') 
	this.nGhost_json			= INT(this.setup('ghost_nGhost_json','N',3))
	
	
	this.ghost_USAR_BODEGA        = IIF(this.lbodegas,1,0) && Si es cero toma el stock completo, 1 toma de la bodega del usuario
	this.ghost_MODIFICA_PRECIO    = INT(this.setup('ghost_MODIFICA_PRECIO','N',0))    && Si es 0 no modifica precios,1 selecciona un precio A,B,C,D, si es 2 permite subir el precio en un % maximo
	this.ghost_PORCENTAJE_PRECIO  = INT(this.setup('ghost_PORCENTAJE_PRECIO','N',0.04))  && recibe el valor /100
	this.ghost_NOTIFICA_GESTION   = INT(this.setup('ghost_NOTIFICA_GESTION','N',0)) && 0 no Notifica, 1 Sms,2 mail, 3 mail, sms
	this.ghost_MAIL_SUPERVISOR    = this.setup('ghost_MAIL_SUPERVISOR','C') && Se separa con , para varios receptores
	this.ghost_CELULAR_SUPERVISOR = this.setup('ghost_CELULAR_SUPERVISOR','C') && Se separa con , para varios receptoresSaludos 
	
	
	*WAIT WINDOW 'modifica precio: '+TRANSFORM(this.ghost_MODIFICA_PRECIO)
	
	this.ghost_campo_pvp_unds     = INT(this.setup('ghost_campo_pvp_unds','N',3)) 
	this.ghost_campo_pvp_bultos   = INT(this.setup('ghost_campo_pvp_bultos','N',4)) 
	this.ghost_pminb  			  = INT(this.setup('ghost_pminb','N',0))
	this.ghost_pmaxb			  = INT(this.setup('ghost_pmaxb','N',3))
	this.ghost_pminu			  = INT(this.setup('ghost_pminu','N',0))
	this.ghost_pmaxu			  = INT(this.setup('ghost_pmaxu','N',8))

ENDFUNC



FUNCTION openDB
	LOCAL lcSQLStringConnect
	this.nConn = -1
	IF FILE('SQLStringConnect.ini')
		lcSQLStringConnect = FILETOSTR('SQLStringConnect.ini')
		this.nConn = SQLSTRINGCONNECT(lcSQLStringConnect)
	ELSE
		this.nConn = SQLCONNECT('fss1')
	ENDIF
	
	IF this.nConn <0
		this.msg ('No se puede connectar a la base de datos ')			
		RETURN .f.
	ELSE
		SQLEXEC(this.nConn ,'USE '+this.cBdd)
	ENDIF
	RETURN .t.
ENDFUNC

FUNCTION closeDB
	IF This.nConn>0
		SQLDISCONNECT(This.nConn)
	ENDIF
ENDFUNC

FUNCTION execDB (cSqlString,cCursor,cFileOut,cTypeOut)
LOCAL nRegs
	nRegs = 0
	&&MESSAGEBOX(cSqlString)
	&&IF this.openDB()
		nRegs = this.SQLExec(cSqlString,cCursor,cFileOut,cTypeOut)
		&&this.closeDB()
	&&ENDIF
	RETURN nRegs
ENDFUNC

FUNCTION msg (cMsg)
	MESSAGEBOX(cMsg,63,'Ghost')
ENDFUNC

FUNCTION TableExists (cTable)


	IF !EMPTY(cTable) .and. !ISNULL(cTable)
		nConn = this.nConn

		nn=SQLEXEC(nConn,'SELECT * FROM '+cTable)
		
		IF this.sqlOk(nn, cTable)
			RETURN nn>0
		ENDIF
	ENDIF

	*WAIT WINDOW this.nConn	
	RETURN .f.
	
ENDFUNC


FUNCTION sqlOk(nResultSqlExec, cMsg)
LOCAL __n__, cErr

	IF nResultSqlExec<0
 		DIMENSION aErrorArray[7]
	  	=AERROR(aErrorArray)  
	  	
	  	cErr = IIF(EMPTY(cMsg),'Error: sql',cMsg)+CHR(13)
	  	FOR __n__= 1 TO 7
	      	cErr = cErr +  TRANSFORM(aErrorArray(__n__))+CHR(13)
	   	ENDFOR
	   	
	   	this.cErr = cErr
	   	
	   	
	   	*STRTOFILE(cErr,'/temp/error.txt')
	   	*MESSAGEBOX(cErr)
	   	*this.closeDb()
	   	*this.openDb()

		RETURN .f.
	ENDIF
	RETURN .t.
ENDFUNC


FUNCTION SQLExec
	LPARAMETERS cCad,cCursor,cFileOut,cTypeOut


	IF this.ltestsql
		MESSAGEBOX(cCad)
	ENDIF

	DIMENSION aCountInfo[2]
	LOCAL nn, cMsgErr, nLim, iCount
	
	cCad = ALLTRIM(cCad)

	IF EMPTY(cCursor)
		cCursor='SQLResult'
	ENDIF
	
	nn=SQLEXEC(this.nConn,cCad,cCursor,aCountInfo)
	
	IF !this.sqlOk(nn, cCad)
	   RETURN -1
	ELSE
		IF USED(cCursor)
			SELECT (cCursor)
			IF !EMPTY(cFileOut)
				IF !EMPTY(cTypeOut)
					cTypeOut=LOWER(cTypeOut)
					COPY TO (cFileOut) &cTypeOut	
				ELSE
					COPY TO (cFileOut) 
				ENDIF
			ENDIF
		ENDIF
	ENDIF

	RETURN aCountInfo[2]
ENDFUNC


FUNCTION SQLExec_local
	LPARAMETERS cCad,cCursor,cFileOut,cTypeOut


	IF this.ltestsql
		MESSAGEBOX(cCad)
	ENDIF

	DIMENSION aCountInfo[2]
	LOCAL nn, cMsgErr, nLim, iCount
	
	cCad = ALLTRIM(cCad)

	IF EMPTY(cCursor)
		cCursor='SQLResult'
	ENDIF
	
	nConn = SQLCONNECT('ghost')
	nn=SQLEXEC(nConn,cCad,cCursor,aCountInfo)
	
	IF !this.sqlOk(nn, cCad)
	   RETURN -1
	ELSE
		IF USED(cCursor)
			SELECT (cCursor)
			IF !EMPTY(cFileOut)
				IF !EMPTY(cTypeOut)
					cTypeOut=LOWER(cTypeOut)
					COPY TO (cFileOut) &cTypeOut	
				ELSE
					COPY TO (cFileOut) 
				ENDIF
			ENDIF
		ENDIF
	ENDIF

	SQLDISCONNECT(nConn)

	RETURN aCountInfo[2]
ENDFUNC


*---------------------------------------------
* Función que encripta una cadena
* Parámetros:
*    tcCadena - Cadena a encriptar
*    tcLlave - Llave para encriptar (Debe ser la misma para Desencriptar)
*    tlSinDesencripta - .F. para proceso que se puede usar Desencripta
*       Los textos encriptados con este tlSinDesencripta en .T. no se pueden
*       desencriptar, ya que el mecanismo de encriptamiento utilizado
*       produce perdida de informacion que impide la inversion del proceso
* Retorno: Caracter (el doble de largo que el texto pasado)
*---------------------------------------------
FUNCTION Encripta(tcCadena, tcLlave, tlSinDesencripta)
	LOCAL lc, ln, lcRet
	LOCAL lnClaveMul, lnClaveXor
	IF EMPTY(tcLlave)
		tcLlave = this.Pswd
	ENDIF
	this.GetClaves(tcLlave,@lnClaveMul,@lnClaveXor)
	lcRet = ""
	lc = tcCadena
	DO WHILE LEN(lc) > 0
		ln = BITXOR(ASC(lc)*(lnClaveMul+1),lnClaveXor)
		IF tlSinDesencripta
			*-- Encripta de modo que no se puede desencriptar
			ln = BITAND(ln+(ln%256)*17+INT(ln/256)*135+ ;
				INT(ln/256)*(ln%256),65535)
		ENDIF
		lcRet = lcRet+BINTOC(ln-32768,2)
		lnClaveMul = BITAND(lnClaveMul+59,0xFF)
		lnClaveXor = BITAND(BITNOT(lnClaveXor),0xFFFF)
		lc = IIF(LEN(lc) > 1,SUBS(lc,2),"")
	ENDDO
	RETURN lcRet
ENDFUNC

*---------------------------------------------
* Función que desencripta una cadena encriptada
* Parámetros:
*    tcCadena - Cadena a desencriptar
*    tcLlave - Llave para desencriptar (Debe ser la misma de Encriptar)
* Retorno: Caracter (la mitad de largo que el texto pasado)
*---------------------------------------------
FUNCTION Desencripta(tcCadena, tcLlave)
	LOCAL lc, ln, lcRet, lnByte
	LOCAL lnClaveMul, lnClaveXor
	IF EMPTY(tcLlave)
		tcLlave = this.Pswd
	ENDIF
	this.GetClaves(tcLlave, @lnClaveMul, @lnClaveXor)
	lcRet = ""
	FOR ln = 1 TO LEN(tcCadena)-1 STEP 2
		lnByte = BITXOR(CTOBIN(SUBS(tcCadena, ln,2))+ ;
			32768,lnClaveXor)/(lnClaveMul+1)
		lnClaveMul = BITAND(lnClaveMul+59, 0xFF)
		lnClaveXor = BITAND(BITNOT(lnClaveXor), 0xFFFF)
		lcRet = lcRet+CHR(IIF(BETWEEN(lnByte,0,255),lnByte,0))
	ENDFOR
	RETURN lcRet
ENDFUNC

*---------------------------------------------
* Función usada por Encripta y Desencripta
*---------------------------------------------
FUNCTION GetClaves(tcLlave, tnClaveMul, tnClaveXor)
	LOCAL lc, ln
	lc = ALLTRIM(LOWER(tcLlave))
	tnClaveMul = 31
	tnClaveXor = 3131
	DO WHILE NOT EMPTY(lc)
		tnClaveMul = BITXOR(tnClaveMul,ASC(lc))
		tnClaveXor = BITAND((tnClaveXor+1)*(ASC(lc)+1),0xFFFF)
		lc = IIF(LEN(lc) > 1,SUBS(lc,2),"")
	ENDDO
ENDFUNC



FUNCTION t_clear
	this.t_nfields = 0
	DIMENSION a_t_fields[1,2]
ENDFUNC

FUNCTION t_set (cField, eField, cType)

	this.t_nfields = this.t_nfields + 1
	DIMENSION a_t_fields[this.t_nfields,2]
	a_t_fields[this.t_nfields,1] = cField
	a_t_fields[this.t_nfields,2] = this.fixstr(eField)
ENDFUNC

FUNCTION i_field (ccField, eCursor)
	IF this.i_exist(ccField, eCursor)
		RETURN ALLTRIM(&eCursor..&ccField)
	ENDIF
	RETURN ''
ENDFUNC


FUNCTION i_exist(ccField, eCursor)
LOCAL iCount,  nLen
	eCursor = ALLTRIM(eCursor)
	DIMENSION aCursor[1]
	nLen = AFIELDS(aCursor,eCursor)
	ccField = UPPER(ALLTRIM(ccField))
	FOR iCount = 1 TO nLen
		IF UPPER(allt(aCursor[iCount,1]))==ccField
			RETURN .t.
		ENDIF
	ENDFOR
	RETURN .f.
ENDFUN


FUNCTION t_insert
LPARAMETERS cNameTable, lLog

	LOCAL __cNameCampo, __cCadInsert, ii

	IF this.t_nfields>0
		
		cmdInsert = 'insert into '+cNameTable+' ('
		cmdValues = ') VALUES ('	

		FOR ii = 1 TO this.t_nfields
		
			cmdInsert = cmdInsert + IIF(ii>1, ',', '') + a_t_Fields[ii,1]
			cmdValues = cmdValues + IIF(ii>1, ',', '') + '"'+ALLTRIM(TRANSFORM(a_t_Fields[ii,2]))+'"'
			
		ENDFOR
		cmdValues = cmdValues + ')'

		__cCadInsert = cmdInsert+cmdValues 


		DIMENSION aCountInfo[2]

		IF !EMPTY(lLog)
			*STRTOFILE(__cCadInsert, '\eddy_t_insert.sql')
		ENDIF
		
		nResultSqlExec = SQLEXEC(this.nConn,__cCadInsert,'',aCountInfo)  &&revisar script 
		
		IF !this.sqlOk(nResultSqlExec, __cCadInsert)
			*STRTOFILE(__cCadInsert, '\eddy_t_insert.sql')
			messagebox(this.cErr,63,'Error') && ,3
			
			RETURN .f.
			
			*this.sqlexec('INSERT INTO ghost_dblog (error) values ("'+this.cErr+'")')
		ENDIF

	ENDIF

	RETURN .t.
ENDFUNC


FUNCTION newId
PARAMETERS __cTableName, nSize, lUpdate,lNoCentroCosto

	LOCAL cResult

	this.nSizeold = nSize

	__ccIdSuc = '0000'

	lUpdate = IIF(EMPTY(lUpdate),.f.,lUpdate)
	__cTableName = UPPER(ALLTRIM(__cTableName))

	__cId = __ccIdSuc+__cTableName
	
	__nValue = this.sqlexec('SELECT value FROM ultimos WHERE id=?__cId','cur_Id')
	
	IF __nValue=0
		this.sqlexec('INSERT INTO ultimos (id) values (?__cId)')
		__nValue = 1
	ELSE
		__nValue = cur_Id.value + 1
	ENDIF


	IF lNoCentroCosto && Viene con valor .T. en la pantalla de accounttype, para todos los demas FORMS viene con .F.
		__cResult = padl(INT(__nValue),nSize,'0')
	ELSE
		__cResult = __ccIdSuc+padl(INT(__nValue),nSize-4,'0')
	ENDIF 

	IF lUpdate
		this.sqlexec('UPDATE ultimos SET value = ?__nValue WHERE TRIM(id)=?__cId')
	ENDIF
	

	RETURN __cResult
ENDFUNC


FUNCTION t_update
	PARAMETERS cNameTable, cIdUpdate, cCond, lVerif_newId, cIdNameField

	NOTE      cNametable   =  Nombre de la tabla
	NOTE      cIdUpdate    =  valor con que se compara el Id " WHERE Id = cIdUpdate "
	NOTE      cCond        =  condicion reemplza al anterior " ' WHERE '+cCond  "
	NOTE      lVerif_newId =  forza insertar registro si no lo encuentra, rango valor de la llave
	NOTE      cIdNameField =  nombre del campo del Id, por defecto Id

	IF EMPTY(cIdNameField)
		cIdNameField = 'Id'
	ENDIF


	IF this.t_nfields>0
		LOCAL ii, cCad, cWhere0
		
		cWhere0 = ' WHERE '+cIdNameField+'=?cIdUpdate'
		IF !EMPTY(cCond)
			cWhere0 = ' WHERE '+cCond
		ENDIF
		
		DIMENSION a_t_fields[this.t_nfields,2]
	
		cmdInsert0 = 'UPDATE '+cNameTable+' SET '+a_t_Fields[1,1]+'=?m.c001 '
		cmdInsert = cmdInsert0 
		
		FOR ii = 2 TO this.t_nfields
			cmdInsert = cmdInsert + ', '+a_t_Fields[ii,1]+'=?m.c'+PADL(ii,3,'0')
		ENDFOR

		cmdInsert = cmdInsert + cWhere0	
		
		FOR ii = 1 TO this.t_nfields
			cc='m.c'+PADL(ii,3,'0')
			&cc = a_t_fields[ii,2]
		ENDFOR	

		this.sqlexec(cmdInsert)
		
		this.t_nfields = 0
	ENDIF
ENDFUNC

FUNCTION explode
	LPARAM cCad, aRet, cCharType

	LOCAL ss, nLen, lExit

	IF EMPTY(cCharType)
		cCharType = ' '
	ENDIF

	DIMENSION aRet [1]
	nLen = 0
	lExit = .f.
	IF !EMPTY(cCad)
		DO WHILE !lExit
			pos = AT(cCharType, cCad)
			IF pos > 0
				ss   = allt(SUBSTR(cCad,1,pos-1))
				cCad = allt(SUBSTR(cCad,pos+1))
			ELSE
				ss   = cCad
				lExit = .t.
			ENDIF
			nLen = nLen +1
			DIMENSION aRet [nLen]
			aRet [nLen] = ss
		ENDDO
	ENDIF
	RETURN nLen
ENDFUNC


FUNCTION str2array
	PARAM cCad, aRet, cCharType
	RETURN this.explode(cCad, @aRet, cCharType)
ENDFUNC

FUNCTION stringToArray
	PARAM cCad, aRet, cCharType
	RETURN this.explode(cCad, @aRet, cCharType)
ENDFUNC

FUNCTION valRuc (cRUC,cTp)
LOCAL nLen, _ii, _ss, _nn, nDV, _nRet

	cRuc = ALLTRIM(cRuc)
	nLen = LEN(cRuc)

	IF EMPTY(cTp)
		IF nLen = 13
			cTp = '01'
		ELSE
			cTp = '02'
		ENDIF		
	ELSE
		cTp  = ALLTRIM(cTp)
	ENDIF
	
	IF EMPTY (cRUC) .OR. (cTp $ '03 06 11 14 17')
		RETURN ''
	ENDIF
	
	
	IF cRUC==REPLICATE('9',13)
		RETURN ''
	ENDIF

	IF nLen < 10 
		RETURN 'RUC o CI tiene menos de 10 digitos'
	ENDIF

	IF nLen > 10 AND nLen < 13
		RETURN 'RUC no tiene 13 digitos'
	ENDIF

	IF !EMPTY(cTp)
		IF cTp $ '01 04 10 12 15'
			IF nLen # 13				
				RETURN 'RUC no tiene 13 digitos'
			ENDIF
		ENDIF
		IF cTp $ '02 05 13 16'
			IF nLen # 10				
				RETURN 'CI no tiene 10 digitos'
			ENDIF
		ENDIF		
	ENDIF

	IF nLen = 13
	
		IF SUBSTR(cRUC,11,3) # '001'
			RETURN 'RUC no termina en 001'
		ENDIF
		
		IF SUBSTR(cRUC,3,1) $ '69'
			RETURN ''
		ENDIF
	ENDIF

	
	nDV = INT(VAL(SUBSTR(cRUC,10,1)))
	_ss = 0
	FOR _ii = 1 TO 9
		_nn = INT(VAL(SUBSTR(cRUC,_ii,1)))
		_nn = _nn * IIF (_ii % 2 = 0,1,2)
		_nn = int(_nn/10) + (_nn%10)
		_ss = _ss + _nn
	ENDFOR
	_nRet = (10 - (_ss % 10 )) % 10

	IF nDV#_nRet
		RETURN 'No. de CI inválido, digito verificador debe ser: '+ALLTRIM(STR(_nRet))
	ENDIF
	RETURN ''
ENDFUNC

FUNCTION newSeq

	PARAMETERS _cTablaSeq, nSizeSeq, _cTipoSeq, _cValTipSeq, _cCampoSeq, lUpdateSeq, setValueSeq

	
	lUpdateSeq = IIF(EMPTY(lUpdateSeq),.f.,lUpdateSeq)
	_cTablaSeq= UPPER(ALLTRIM(_cTablaSeq))


	__nValueSeq = this.sqlexec('SELECT id, valor FROM secuencias WHERE '+;
				'TRIM(tabla)      = ?_cTablaSeq AND '+;
				'TRIM(TipoSeq)    = ?_cTipoSeq AND '+;
				'TRIM(ValTipoSeq) = ?_cValTipSeq AND '+;
				'TRIM(camposeq)   = ?_cCampoSeq','curSeq')
	IF __nValueSeq=0
		__cIdSeq = this.newId('secuencias',8,.t.)
		_cCmd_ = 'INSERT INTO secuencias (id,tabla,tiposeq,valtiposeq,camposeq) values '+;
				'("'+__cIdSeq+'","'+_cTablaSeq+'","'+_cTipoSeq+'","'+_cValTipSeq+'","'+_cCampoSeq+'")'
		this.sqlexec(_cCmd_)
		__nValueSeq = 1
	ELSE
		__nValueSeq = curSeq.valor + 1
		__cIdSeq = curSeq.id
	ENDIF

	__cResultSeq = padl(INT(__nValueSeq),nSizeSeq,'0')

	IF lUpdateSeq
		IF !EMPTY(setValueSeq)
			__nValueSeq = setValueSeq
		ENDIF
		
		__nValueSeq = INT(__nValueSeq)
		
		_cCmd_ = 'UPDATE secuencias SET valor = ?__nValueSeq WHERE id="'+__cIdSeq+'"'
		
		this.sqlexec(_cCmd_)
	ENDIF

	RETURN __cResultSeq

ENDFUNC
	
FUNCTION ActUlti
PARAMETERS ccIdSuc,cFileD,lId0
	IF lId0
		this.sqlexec('SELECT max(SUBSTR(Id0,5)+0) as valor FROM '+cFileD+' WHERE LEFT(id0,4)=?ccIdSuc;','curUltimo')
	ELSE
		this.sqlexec('SELECT max(SUBSTR(Id,5)+0) as valor FROM '+cFileD+' WHERE LEFT(id,4)=?ccIdSuc;','curUltimo')
	ENDIF
	
	SELECT curUltimo
	nIdu = IIF (EOF() .or. ISNULL(curUltimo.valor), 0, curUltimo.valor)

	_cIdu = ccIdSuc+cFileD
	IF this.sqlexec('select id from ultimos where id=?_cIdu')>0
		this.sqlexec('UPDATE ultimos SET value=?nIdu WHERE id=?_cIdu')
	ELSE					
		this.sqlexec('INSERT INTO ultimos (id,value) values (?_cIdu,?nIdu )')
	ENDIF
ENDFUNC




FUNCTION setBDDSetup (cBDDName)
	this.cBDDSetup = ALLTRIM(cBDDName)
ENDFUNC


FUNCTION setSetup(cKey, eValor, cType)
	
	IF EMPTY(cType)
		cType = 'C'
	ENDIF
	
	this.setup(cKey,cType,eValor,.t.)

ENDFUNC

FUNCTION setupC (cKey, cType, eRetVal)
	SELECT curSetup
	SEEK UPPER(ALLTRIM(cKey))
	IF !EOF()
		RETURN this.setup_s_type(curSetup.value,cType)
	ENDIF
	
	IF EMPTY(eRetVal)
		eRetVal = ''
	ENDIF
	
	RETURN this.setup_s_type(eRetVal,cType)
	
	
ENDFUNC



FUNCTION setup 
PARAM cKey, cType, eValue, lWrite, eDefault
	LOCAL eRetVal

	IF EMPTY(cKey)
		RETURN 'e'
	ENDIF
	
	cTableSetup = 'Setup'
	IF !EMPTY(this.cBDDSetup)
		cTableSetup = this.cBDDSetup + '.Setup'
	ENDIF
	
	IF !this.TableExists (cTableSetup)
		messagebox('error: no existe '+cTableSetup)
		RETURN ''
	ENDIF
	
	

	cKey    = UPPER(ALLT(cKey))
	cType   = UPPER(ALLTRIM(cType))
	IF this.sqlexec('SELECT value FROM '+cTableSetup+' WHERE Id = "'+cKey+'"','cSetup')=0
		cCadSetup = this.setup_type_s(eDefault,cType)
		this.sqlexec('INSERT INTO '+cTableSetup+' (id,type,value) VALUES (?cKey, ?cType,?cCadSetup);')
		eRetVal   = this.setup_s_type(cCadSetup,cType)
	ELSE
		IF EMPTY(lWrite) 
			eRetVal = this.setup_s_type(cSetup.value,cType)
		ELSE
			cCadSetup = this.setup_type_s(eValue,cType)
			this.sqlexec('UPDATE '+cTableSetup+' SET value= ?cCadSetup WHERE Id = "'+cKey+'"')
			eRetVal = eValue
		ENDIF
	ENDIF
	this.cBDDSetup = ''
	RETURN eRetVal
ENDFUNC


FUNCTION setup_s_type
	LPARAMETERS cValue, cType
	LOCAL cRetVal

	cType = UPPER(cType)

	cRetVal = ''
	DO CASE
	CASE cType = 'C'
		cRetVal = RTRIM(cValue)
	CASE cType = 'I'
		cRetVal = this.num(cValue,.T.)
	CASE cType = 'N'
		cRetVal = this.num(cValue)
	CASE cType = 'D'
		cRetVal = this.CTOD(cValue)
	CASE cType = 'L'
		cRetVal = (ALLTRIM(cValue) $ '.T. TRUE V 1')
	ENDCASE

	RETURN cRetVal
ENDFUNC

FUNCTION num
	lPARAMETERS lExp, isInt
	LOCAL nRet, cType


	cType = VARTYPE(lExp)

	DO CASE
	   CASE cType $ 'N IB' 
	   		nRet = lExp
	   CASE cType $ 'Y'
	   		nRet = MTON(lExp)
	   CASE cType $ 'DT'
		   	nRet = VAL(SYS(11,lExp))
	   CASE cType $ 'CM'
	   		nRet = VAL(lExp)
	   CASE cType='L'
	   		nRet = IIF(cValue,1,0)
	ENDCASE

	IF !EMPTY(isInt)
		nRet = INT(nRet)
	ENDIF

	RETURN nRet
ENDFUNC


FUNCTION CTOD 
	LPARAMETERS cFecha 
	LOCAL oldSetDate,dFecha
	oldSetDate = SET('DATE')
	SET DATE TO dmy
	dFecha = ctod(cFecha )	
	SET DATE TO &oldSetDate

	RETURN dFecha
ENDFUNC

FUNCTION vacia
LPARAMETERS  expresion

RETURN ISNULL(expresion) .or. EMPTY(expresion)

ENDFUNC



FUNCTION setup_type_s
	LPARAMETERS cValue, cType
	LOCAL cRetVal

	cType = UPPER(cType)

	cRetVal = cValue
	DO CASE
	CASE cType = 'C'
		cValue = IIF(EMPTY(cValue),'',cValue)
		cRetVal = RTRIM(cValue)
	CASE cType = 'I'
		cValue = IIF(EMPTY(cValue),0,cValue)
		cRetVal = ALLTRIM(STR(INT(cValue),15,0))
	CASE cType = 'N'
		cValue = IIF(EMPTY(cValue),0,cValue)
		cRetVal = ALLTRIM(STR(cValue,20,8))
	CASE cType = 'D'
		cValue = IIF(EMPTY(cValue),{//},cValue)
		cRetVal = DTOC(cValue)
	CASE cType = 'L'
		cValue = IIF(EMPTY(cValue),.f.,cValue)
		cRetVal = IIF(cValue, '.T.', '.F.')
	ENDCASE
	
	RETURN cRetVal
ENDFUNC

PROCEDURE getFechIni(iFecha)
	LOCAL dFecha
	
	nAnio = YEAR(iFecha)
	nMes  = MONTH(iFecha)
	
	dFecha = '01/'+padl(INT(nMes),2,'0')+'/'+padl(INT(nAnio),4,'0')		
	dFecha = ctod(dFecha)	
	RETURN dFecha 
ENDPROC

PROCEDURE getFechFin(iFecha)
	LOCAL dFecha
	
	nAnio = YEAR(iFecha)
	nMes  = MONTH(iFecha)
	
	dFecha = '01/'+PADL(INT(nMes)+1,2,'0')+'/'+PADL(INT(nAnio),4,'0')
	IF nMes=12
		dFecha = '01/01/'+PADL(INT(nAnio)+1,4,'0')
	ENDIF
	dFecha = ctod(dFecha)-1
	RETURN dFecha		
ENDPROC

FUNCTION getFechaPer(iFecha, dFechIni, dFechFin)
	dFechIni = this.getfechIni(iFecha)
	dFechFin = this.getfechFin(iFecha)
ENDFUNC

FUNCTION runUrl
	PARAMETERS url, cData, cMetodo

	LOCAL lcHTML,lnText,lRet, iCount

	*WAIT WINDOW 'Ejecutando '+url+' ... ' nowait
	
	*STRTOFILE(url,'\url.txt')

	cResult = '@@'

	IF EMPTY(cMetodo)
		cMetodo = 'GET'
	ENDIF
	
	lConn = ""

	TRY
		conexion.open(cMetodo, url, .F.)
		lResolve = 5 * 1000
		lConnect = 5 * 1000
		lSend = 60 * 1000
		lReceive = 60 * 1000
		conexion.setTimeouts(lResolve, lConnect, lSend, lReceive)

		IF EMPTY(cData)
			cData = null
		ENDIF

		conexion.send(cData)

		IF conexion.status = 200 THEN
			cResult = conexion.responseText
		ELSE
			cResult = '@@'+TRANSFORM(conexion.status)
		ENDIF
	CATCH TO lConn
	ENDTRY
	lConn = TRANSFORM(lConn)
	IF !EMPTY(lConn)
		cResult = '@@'+lConn
	ENDIF

	This.cWebResult = cResult
	
	RETURN cResult
ENDFUNC

FUNCTION runLink(cHttp, cResult)
	cResult = this.rUrl (cHttp)
	This.cWebResult = cResult
	RETURN cResult != '@@'
ENDFUNC

FUNCTION rUrl(url, cData, cMetodo)
	cUrl = this.getHostUrl()+ url
	
	*STRTOFILE(cUrl,'\temp\url.txt')
	RETURN this.runUrl(cUrl, cData, cMetodo) 
ENDFUNC

FUNCTION getHostUrl

	*lcHost = 'http://www.tecsicom.net'  
	lcHost = 'http://tecsicom.dnsalias.com'
	
	IF this.ltecsicom_host
		this.ltecsicom_host	= .f.	
	ELSE
		lcHost = 'http://'+this.host
	ENDIF
	
	lcHost = lcHost + '/'
	
	RETURN lcHost
ENDFUNC


FUNCTION doLink(cHttp)
	This.cWebResult = ''
	IF this.lGhost_web
		cHttp = cHttp + IIF(AT('?',cHttp)>0,'&','?')+'bdd='+this.cbdd_name
		this.runLink(cHttp)
	ENDIF
	RETURN This.cWebResult
ENDFUNC


FUNCTION ftpdownload(cFileName, lBorrar)

	IF VARTYPE(oIp)!='O'
		RETURN .F.
	ENDIF
	
	DELETE FILE (cFileName)
	*WAIT WINDOW 'borrando...'
	
	IF oIp.FTPGetFile(this.FtpHost,cFileName,cFileName,2,oApp.FtpUser,oApp.FtpPswd) = 0
		
		cCmdPHP = "/json/deldata.php?path="+cFileName
		*this.doHttp (cCmdPHP, 1)
	ELSE
	   MESSAGEBOX(oIp.cErrorMsg,63,'Error ftp: ')
	   RETURN .F.
	ENDIF

	RETURN .T.

ENDFUNC


FUNCTION initView

	TEXT TO cCmd NOSHOW	
		CREATE TABLE IF NOT EXISTS Ghost_view (id varchar(30), msg varchar(200), estado INT, primary KEY (id)) ENGINE = MYISAM
	ENDTEXT  			
	this.sqlexec(cCmd ) 	

ENDFUNC

FUNCTION msg_add (cIdView,cMsg)

	LOCAL _id,_Msg,_estado
	
	cMsg = IIF(EMPTY(cMsg), "", cMsg)
	

	IF EMPTY(cIdView)
		WAIT WINDOW cMsg nowait
	ELSE
		_id = cIdView
		_Msg = SUBSTR(cMsg,1,200)
		_estado = "0"
		
		cCmd = 'INSERT INTO Ghost_View (id, msg, estado) values ("'+_id+'", "'+_msg+'", '+_estado+') '
		IF oApp.sqlexec('select id from Ghost_view where id="'+_id+'"')>0
			cCmd = 'UPDATE Ghost_View SET msg="'+_msg+'" WHERE id="'+_id+'"'
		ENDIF
		
		oApp.sqlexec(cCmd) 	
	ENDIF
	
 	
ENDFUNC

FUNCTION setView (cIdView,nEstado)

	_estado = nEstado

	IF EMPTY(cIdView)
		cCmd = 'UPDATE Ghost_View set estado=?_estado '
		oApp.sqlexec(cCmd) 	
	ELSE

		_id = cIdView
		cCmd = 'UPDATE Ghost_View set estado=?_estado WHERE id="'+_id+'"'
		
		oApp.sqlexec(cCmd) 	

	ENDIF
	 	
ENDFUNC

FUNCTION getView (cIdView, nOp) 

	IF !EMPTY(cIdView)
		_id = cIdView

		nEstado = 0
		cMsg = ''
		
		IF oApp.sqlexec('select msg, estado from Ghost_view where id="'+_id+'"','curViewEst')>0
			nEstado = curViewEst.estado 
			cMsg = curViewEst.msg
		ENDIF

		RETURN IIF(nOp=1,cMsg, nEstado)
	ENDIF
	
	RETURN ""
 	
ENDFUNC

FUNCTION KillView (cIdView) 

	IF !EMPTY(cIdView)
		oApp.sqlexec('DELETE FROM Ghost_view where id="'+cIdView+'"')
	ENDIF
	 	
ENDFUNC


FUNCTION getViewTitleDoc (cTipo,cSerieSec)
	cNroDoc = SUBSTR(cSerieSec,1,3)		
	cNroDoc = cNroDoc + '-' + SUBSTR(cSerieSec,4,3)		
	cNroDoc = cNroDoc + '-' + PADL(ALLTRIM(SUBSTR(cSerieSec,8,9)),9,'0')		

	cTit = ''
	DO case
	CASE cTipo='01'
		cTit = 'Factura Nro. '
	CASE cTipo='04'
		cTit = 'Nota de Crédito Nro. '
	CASE cTipo='05'
		cTit = 'Nota de Débito Nro. '
	CASE cTipo='06'
		cTit = 'Guía de Remisión Nro. '
	CASE cTipo='07'
		cTit = 'Comp. de Retención Nro. '
	ENDCASE
	RETURN  cTit + cNroDoc + CHR(13)+CHR(13)
ENDFUNC


FUNCTION xchr (cname, nMaxLen)

	cname = ALLTRIM(cname)

	cname = strtran(cname,'&','&amp;')
	cname = strtran(cname,'<','&lt;')
	cname = strtran(cname,'>','&gt;')
	cname = strtran(cname,"'",'&apos;')
	cname = strtran(cname,'"','&quot;')
	cname = strtran(cname,CHR(0),'')
	
	*cname = STRTRAN(cname,'&','Y')
	*cname = STRTRAN(cname,'<',' ')
	*cname = STRTRAN(cname,'>',' ')
	*cname = strtran(cname,'"',' ')
	*cname = strtran(cname,"'",' ')
	
	*cname = strtran(cname,CHR(209),'&Ntilde;')
	
	*cname = strtran(cname,'Ñ','&Ntilde;')
	*cname = strtran(cname,'ñ','&ntilde;')
	*cname = strtran(cname,'Á','&Aacute;')
	*cname = strtran(cname,'á','&aacute;')


	cname = STRTRAN(cname,'Ñ','N')
	cname = STRTRAN(cname,'ñ','n')
	
	cname = STRTRAN(cname,CHR(13),' ')
	cname = STRTRAN(cname,CHR(10),'')

	*cname = STRTRAN(cname,'/',' ')
	*cname = STRTRAN(cname,'\',' ') 
	*cname = STRTRAN(cname,'.',' ')
	*cname = STRTRAN(cname,'-',' ')
	
	cname = STRTRAN(cname,'Ç','C')
	cname = STRTRAN(cname,'ç','c')
	cname = STRTRAN(cname,'´',' ')
	cname = STRTRAN(cname,'{',' ')
	cname = STRTRAN(cname,'}',' ')
	cname = STRTRAN(cname,'#',' ')
	cname = STRTRAN(cname,'?',' ')
	cname = STRTRAN(cname,'%',' ')
	cname = STRTRAN(cname,'º',' ')
	cname = STRTRAN(cname,CHR(176),' ')
	cname = STRTRAN(cname,'ª',' ')
	cname = STRTRAN(cname,'^',' ')
	
	*cname = STRTRAN(cname,'  ',' ')
	
	cname = STRTRAN(cname,'Á','A')
	cname = STRTRAN(cname,'É','E')
	cname = STRTRAN(cname,'Í','I')
	cname = STRTRAN(cname,'Ó','O')
	cname = STRTRAN(cname,'Ü','U')
	
	cname = STRTRAN(cname,'á','a')
	cname = STRTRAN(cname,'é','e')
	cname = STRTRAN(cname,'í','i')
	cname = STRTRAN(cname,'ó','o')
	cname = STRTRAN(cname,'ú','u')
	cname = STRTRAN(cname,'û','u')
	cname = STRTRAN(cname,'ù','u')
	

	cname = STRTRAN(cname,'½',' 1/2')
	cname = STRTRAN(cname,'¼',' 1/4')
	cname = STRTRAN(cname,'¾',' 3/4')
	
	cname = STRTRAN(cname,'*',' ')
	
	IF !EMPTY(nMaxLen)
		cname = SUBSTR(cname,1,nMaxLen)
	ENDIF
	
	
	RETURN ALLTRIM(cname)

ENDFUNC



FUNCTION converString(cString, cCodigo)
	cString = ALLTRIM(cString)
	cCodigo = ALLTRIM(cCodigo)
	nKey = 0
	FOR iCount = 1 TO LEN(cCodigo)
		nKey = (nKey + ASC(SUBSTR(cCodigo,iCount,1)))%7		
	ENDFOR
	
	cRetString = ''
	FOR iCount = 1 TO LEN(cString)
		cRetString = cRetString + chr(ASC(SUBSTR(cString,iCount,1))+27+nKey*IIF(iCount%2=0,1,-1)+(iCount%3))
	ENDFOR
	
	RETURN cRetString
ENDFUNC


FUNCTION DeconverString(cString, cCodigo)
	cString = ALLTRIM(cString)
	cCodigo = ALLTRIM(cCodigo)
	nKey = 0
	FOR iCount = 1 TO LEN(cCodigo)
		nKey = (nKey + ASC(SUBSTR(cCodigo,iCount,1)))%7		
	ENDFOR
	
	cRetString = ''
	FOR iCount = 1 TO LEN(cString)
		cRetString = cRetString + chr(ASC(SUBSTR(cString,iCount,1))-27-nKey*IIF(iCount%2=0,1,-1)-(iCount%3))			
	ENDFOR
	
	RETURN cRetString
	
ENDFUNC

FUNCTION web_getruc
PARAMETERS cRuc, aRet

	cHttp = "/vfac/down_ruc.php?ruc="+cRuc
	IF this.runLink(cHttp)
		this.stringToArray(this.cWebResult, @aRet, '|')
		RETURN ALEN(aRet)>2
	ENDIF

	RETURN .F.
ENDFUNC

FUNCTION vacio
PARAMETERS cCad

	IF EMPTY(cCad) OR ISNULL(cCad)
		RETURN .t.
	ENDIF
	
	RETURN .f.

ENDFUNC


FUNCTION dtoc_sql(dFecha)
	cFechaO = DTOC(dFecha,1)
	RETURN SUBSTR(cFechaO,1,4)+'-'+SUBSTR(cFechaO,5,2)+'-'+SUBSTR(cFechaO,7,2)
ENDFUNC


FUNCTION getMes
LPARAMETERS dFec, nMes

	LOCAL _nMes, cRetVal
	cRetVal = ' '
	_nMes = 1
	*ON ERROR _nMes = dFec
	_nMes = MONTH(dFec)
	*ON ERROR _nMes = 1


	IF !EMPTY(nMes)
		_nMes = nMes 
	ENDIF

	_nMes = iif (_nMes > 12 .or. _nMes < 1, 1, _nMes)



	DIMENSION aMes[12]
	aMes [1] = 'Enero'
	aMes [2] = 'Febrero'
	aMes [3] = 'Marzo'
	aMes [4] = 'Abril'
	aMes [5] = 'Mayo'
	aMes [6] = 'Junio'
	aMes [7] = 'Julio'
	aMes [8] = 'Agosto'
	aMes [9] = 'Septiembre'
	aMes [10] = 'Octubre'
	aMes [11] = 'Noviembre'
	aMes [12] = 'Diciembre'
	cRetVal = aMes [_nMes]
	RETURN cRetVal
ENDFUNC


FUNCTION runrpt (cRpt, nDest, lcPrinter)

	lErrorPrint = .f.
	LOCAL lcOrigPrinter,lcEval

	IF !EMPTY(lcPrinter)
		lcOrigPrinter = set("Printer", 3)
		lcPrinter =  lcOrigPrinter  && nombre de la impresora a seleccionar

		lcEval = "SET PRINTER TO NAME '" +lcPrinter+"'"

		ON ERROR lErrorPrint = .t.
		&lcEval
		ON ERROR
	ENDIF

	if  !lErrorPrint 

		IF EMPTY(nDest)
			cDest = ' PREVIEW IN SCREEN '	
		ELSE
			IF nDest = 2
				cDest =  ' TO PRINTER noconsole '
			ENDIF	

			IF nDest = 3
				cDest = ' TO PRINTER PROMPT noconsole '
			ENDIF
		ENDIF
		
		REPORT FORM &cRpt &cDest
	ELSE
		WAIT WINDOW "Impresora no esta lista: "+alltrim(lcPrinter)
	ENDIF

	IF !EMPTY(lcPrinter)
		lcEval = "SET PRINTER TO NAME '" +lcOrigPrinter +"'"
		&lcEval
	ENDIF


ENDFUNC




FUNCTION getymd
PARAMETERS t

IF !EMPTY(t)
	RETURN PADL(year(t),4,'0')+'-'+PADL(Month(t),2,'0')+'-'+PADL(day(t),2,'0')
ENDIF

RETURN '2015-01-01'
ENDFUNC


FUNCTION jset (cLlave, cValor, lFree)
	cValor = ALLTRIM(cValor)
	RETURN cLlave+':\"'+cValor+'\"'+IIF(lFree,'',',')
ENDFUNC



FUNCTION android_reverse_cd (cCmd)

LOCAL nLenCab, i, j, k, nLen, nCampos, sss, sDet, nLenC, nLenD
	DIMENSION aa[1], hh[1], dd[1], ee[1], aHCab[1], aHDet[1]


	*STRTOFILE(cCmd,'\android_reverse_cd.txt')
	
	cCmd = this.fixChars (cCmd)

	nLenCab = oApp.explode(cCmd,@aa,'{')
	
	oApp.explode(aa[1],@hh,'~')
		
	DIMENSION aCampos[1]
	nLenC = oApp.android_reverse_cursor ('pda_cur_cab',hh[1], @aCampos)
	ACOPY(aCampos,aHCab)
	
	DIMENSION aCampos[1]
	nLenD = oApp.android_reverse_cursor ('pda_cur_det',hh[2], @aCampos)
	ACOPY(aCampos,aHDet)
	
	FOR i = 2 TO nLenCab
		*STRTOFILE(aa[i],'\android_reverse_cd_aa.txt')
		
		
		oApp.explode(aa[i],@dd,'~')
		oApp.explode(dd[1],@ee,'|')
		sDet = dd[2]
		
		SELECT pda_cur_cab 
		APPEND BLANK
		

		FOR j = 1 TO nLenC
			sss = aHCab[j]
			replace &sss WITH TRANSFORM(ee[j])
		ENDFOR

		nLen = oApp.explode(sDet,@dd,'_')
		
		*MESSAGEBOX(sDet)

		FOR j = 1 TO nLen
		
			oApp.explode(dd[j],@ee,'|')
			
			SELECT pda_cur_det 
			APPEND BLANK
			
			FOR k = 1 TO nLenD
				sss = aHDet[k]
				replace &sss WITH TRANSFORM(ee[k])
			ENDFOR
		ENDFOR
	ENDFOR

	RETURN .t.
	
ENDFUNC


FUNCTION android_reverse_tabla (cCmd)

LOCAL nLenCab, i, k, nLen, nCampos, sss, nLenC
	DIMENSION aa[1], aHCab[1], dd[1]
	
	nLenCab = oApp.explode(cCmd,@aa,'~')
	
	IF nLenCab=0
		RETURN .F.
	ENDIF
	
	
	DIMENSION aCampos[1]
	nLenC = oApp.android_reverse_cursor ('pda_cur_cab',aa[1], @aCampos)
	ACOPY(aCampos,aHCab)
	
	FOR i = 2 TO nLenCab
		oApp.explode(aa[i],@dd,'|')

		SELECT pda_cur_cab
		APPEND BLANK
		
		FOR k = 1 TO nLenC
			sss = aHCab[k]
			replace &sss WITH TRANSFORM(dd[k])
		ENDFOR

	ENDFOR
	RETURN .T.
ENDFUNC


FUNCTION android_reverse_tabla_db0 (db,cCmd, cTablaDest)

LOCAL nLenCab, i, k, nLen, nCampos, sss, nLenC, cCmd
	DIMENSION aa[1], aHCab[1], dd[1]
	
	nLenCab = oApp.explode(cCmd,@aa,'~')
	
	DIMENSION aCampos[1]
	
	nLenC = oApp.explode(aa[1],@aHCab,'|')

	cCmd = ''
	FOR i = 2 TO nLenCab
	
		IF !EMPTY(aa[i])
			oApp.explode(aa[i],@dd,'|')
			
			cCmd = cCmd +  'INSERT INTO '+cTablaDest+' ('
			
			FOR k = 1 TO nLenC-1
				cCmd = cCmd + aHCab[k] + ','
			ENDFOR
			cCmd = cCmd + aHCab[nLenC] + ') VALUES ('
			
			FOR k = 1 TO nLenC-1
				cCmd = cCmd +  this.fixStr(dd[k],3) + ','
			ENDFOR
			cCmd = cCmd + this.fixStr(dd[nLenC],3) + '); '+CHR(13)
		ENDIF
	ENDFOR
*!*		IF cTablaDest='customer'
*!*			STRTOFILE(cCmd,'\eddy_cliente.txt')
*!*		ENDIF
	db.execute(cCmd)
ENDFUNC


FUNCTION android_reverse_tabla_db (db,cCmd, cTablaDest)

LOCAL nLenCab, i, k, nLen, nCampos, sss, nLenC, cCmd
	DIMENSION aa[1], aHCab[1], dd[1]
	
	nLenCab = oApp.explode(cCmd,@aa,'~')
	
	DIMENSION aCampos[1]
	
	nLenC = oApp.explode(aa[1],@aHCab,'|')

	
	FOR i = 2 TO nLenCab
		
		cCmd = ''
		IF !EMPTY(aa[i])
			oApp.explode(aa[i],@dd,'|')
			
			cCmd = cCmd +  'INSERT INTO '+cTablaDest+' ('
			
			FOR k = 1 TO nLenC-1
				cCmd = cCmd + aHCab[k] + ','
			ENDFOR
			cCmd = cCmd + aHCab[nLenC] + ') VALUES ('
			
			FOR k = 1 TO nLenC-1
				cCmd = cCmd +  this.fixStr(dd[k],3) + ','
			ENDFOR
			cCmd = cCmd + this.fixStr(dd[nLenC],3) + '); '
			db.execute(cCmd)
		
		ENDIF

	ENDFOR
*!*		IF cTablaDest='customer'
*!*			STRTOFILE(cCmd,'\eddy_cliente.txt')
*!*		ENDIF
	
ENDFUNC

FUNCTION android_reverse_cursor (cCurName, cCampos, aCampos)
LOCAL cRet, nLen, iCount
	DIMENSION acampos[1]

	IF cCampos!='@@' AND !EMPTY(cCampos)

		nLen = oApp.explode(cCampos,@aCampos,'|')
		cRet = 'CREATE CURSOR '+cCurName+' ('
		
		FOR iCount = 1 TO nLen
			cRet = cRet + aCampos[iCount] + ' c(200) ' + IIF(iCount<nLen,',','')
		ENDFOR
		
		cRet = cRet + ')'

		IF USED(cCurName)
			SELECT &cCurName
			USE
		ENDIF

		&cRet
		RETURN nLen	
		
	ENDIF
	RETURN 0
	
ENDFUNC


FUNCTION android_reverse_cursor_db (cCurName, cCampos, aCampos)
LOCAL cRet, nLen, iCount
	DIMENSION acampos[1]

	IF cCampos!='@@' AND !EMPTY(cCampos)

		nLen = oApp.explode(cCampos,@aCampos,'|')
		cRet = 'CREATE CURSOR '+cCurName+' ('
		
		FOR iCount = 1 TO nLen
			cRet = cRet + aCampos[iCount] + ' c(200) ' + IIF(iCount<nLen,',','')
		ENDFOR
		
		cRet = cRet + ')'

		IF USED(cCurName)
			SELECT &cCurName
			USE
		ENDIF
		

		&cRet
		
		RETURN nLen
	ENDIF
	RETURN 0
	
ENDFUNC


FUNCTION fill_id(cId,nSize)

	IF VARTYPE(cId)='C'
		cId = VAL(cId)
	ENDIF
	
	cId = INT(cId)
	RETURN PADL(cId,nSize,'0')
	
ENDFUNC

FUNCTION Enc3(s)
	LOCAL sRet, i, l, c
	sRet=''
	l = LEN (ALLTRIM(S))
	FOR i = 1 TO l
	    c = ASC(SUBSTR (s, i, 1))
	    c = IIF(i%2==0, c-7, c+5)
	    sRet = sRet + chr(c)
	NEXT
	RETURN sRet
ENDFUNC

FUNCTION DEnc3(s)
	LOCAL sRet, i, l, c
	sRet=''
	l = LEN (ALLTRIM(S))
	FOR i = 1 TO l
	    c = ASC(SUBSTR (s, i, 1))
	    c = IIF(i%2==0, c+7, c-5)
	    sRet = sRet + chr(c)
	NEXT
	RETURN sRet
ENDFUNC



FUNCTION fixStr(sVal,lCom)
	
	IF EMPTY(lCom)
		lCom=0
	ENDIF
	
	IF ISNULL(sval)
		sval = ''
	ENDIF

	IF vartype(sval)='N'
		sval = transform(sVal)
	ENDIF
	
	IF vartype(sval)='D'
		sval = DTOC(sVal,1)
	ENDIF

	IF vartype(sval)='T'
		sval = TTOC(sVal,1)
	ENDIF

	IF lCom=0 
		sval = ALLTRIM(STRTRAN(sval ,'"','\"'))
	ENDIF
	
	IF lCom=2 OR lCom=3
		sval = ALLTRIM(STRTRAN(sval ,'"',''))
	ENDIF

		
	
	IF lCom=2
		sval = '\"'+sval+'\"'
	ENDIF
	
	IF lCom=1 OR lCom=3
		sval = '"'+sval+'"'
	ENDIF
	 
	RETURN ALLTRIM(sVal)
ENDFUNC

FUNCTION db_fix0 (db,cTable,cCampo,nSize)
	LOCAL cCmd
	
	TEXT TO cCmd NOSHOW TEXTMERGE
		update <<cTable>> set <<cCampo>> = substr('00000000000000' || <<cCampo>> , -<<nSize>>, <<nSize>>) 
	ENDTEXT
	
	db.execute(cCmd) 
ENDFUNC

FUNCTION aleatorio(gnLower, gnUpper)
	RETURN  INT((gnUpper - gnLower + 1) * RAND( ) + gnLower)
ENDFUNC


FUNCTION SetLatLng (cIdCust, nLat, nLng)
	cIdCust = ALLTRIM(cIdCust)
	
	IF !EMPTY(cIdCust) AND ((nLat+nLng) # 0) and (nLat#nLng)
	
		TEXT TO cCmd NOSHOW TEXTMERGE 
			UPDATE Customer SET latitud = <<nLat>>, longitud = <<nLng>> WHERE id=<<cIdCust>>
		ENDTEXT
		
		oApp.sqlexec(cCmd)
		
	ENDIF
	
ENDFUNC	

FUNCTION fixd (cValor)
	RETURN STRTRAN(TRANSFORM(cValor),',','.')
ENDFUNC



FUNCTION init_aJson(jParam)
	LOCAL iCount
	DIMENSION aTmp[1]
	jParam = ALLTRIM(jParam)
	IF SUBSTR(jParam,1,1)$ '{[('	
	 	nLenJson = this.explode(SUBSTR(jParam,2,LEN(jparam)-2),@aTmp,',')
	ELSE
		nLenJson = this.explode(jparam,@aTmp,',')
	ENDIF 
 	*MESSAGEBOX(jParam)
 	DIMENSION aJson[1,2]
 	IF nLenJson>0
	 	DIMENSION aJson[nLenJson,2]
	 	FOR iCount = 1 TO nLenJson
	 		DIMENSION aRow[2]
	 		this.explode(aTmp[iCount],@aRow,':')
	 		aJson[iCount,1] = SUBSTR(aRow[1],2,LEN(aRow[1])-2)
	 		aJson[iCount,2] = SUBSTR(aRow[2],2,LEN(aRow[2])-2)
	 		*MESSAGEBOX(aTmp[iCount])
	 		*MESSAGEBOX(aRow[2])
	 	ENDFOR 
	 ENDIF
ENDFUNC

FUNCTION get_aJson(cToken)
	LOCAL iCount
 	FOR iCount = 1 TO nLenJson
 		IF aJson[iCount,1] = cToken
	 		return aJson[iCount,2] 
	 	ENDIF
	 	
 	ENDFOR 
	RETURN ''
ENDFUNC

FUNCTION get_cmes (c_m)
LOCAL cRet
	cRet =  IIF(c_m='enero','01',;
			IIF(c_m='febrero','02',;
			IIF(c_m='marzo','03',;
			IIF(c_m='abril','04',;
			IIF(c_m='mayo','05',;
			IIF(c_m='junio','06',;
			IIF(c_m='julio','07',;
			IIF(c_m='agosto','08',;
			IIF(c_m='septiembre','09',;
			IIF(c_m='octubre','10',;
			IIF(c_m='noviembre','11',;
			IIF(c_m='diciembre','12','01'))))))))))))
	RETURN cRet
ENDFUNC

FUNCTION getcdate(cFecha)
	cFecha = ALLTRIM(cFecha) && 05/31/2016
	RETURN SUBSTR(cFecha,7,4)+SUBSTR(cFecha,1,2)+SUBSTR(cFecha,4,2)
ENDFUNC

FUNCTION gAMD(cFecha)
	cFecha = ALLTRIM(cFecha) && 2016-01-01
	RETURN ctod(SUBSTR(cFecha,9,2)+'/'+SUBSTR(cFecha,6,2)+'/'+SUBSTR(cFecha,1,4))
ENDFUNC

FUNCTION ruta_docs(_ca) 


	_rutabase = this.rutaDigitalizadosFE+'/'
	
	*1509201601119172477800110010080000003571234567812
	
	_ruc     = substr(_ca,11,13)
	_periodo = substr(_ca,5,4)+substr(_ca,3,2)
	_tipo    = ALLTRIM(TRANSFORM(INT(VAL(substr(_ca,9,2)))))
	
	_ruta = _rutabase+_ruc+"/"+_periodo+"/"+_tipo+'/'
		
	IF (!directory(_ruta)) 
		mkdir(_ruta)
	ENDIF
	
	RETURN  _ruta
ENDFUNC 

FUNCTION clasificar_docs (_mask)
	DIMENSION dir[1]
	
	IF EMPTY(_mask)
		_mask = '*.xml'
	ENDIF
	_files = oApp.rutaDigitalizadosFE+'/autorizados/'+_mask	
	nDir = ADIR(dir,_files)
	FOR iCount = 1 TO nDir
		_ca = ALLTRIM(dir[iCount,1])
		IF LEN(_ca)>49
			_ca = SUBSTR(_ca, 1, AT('.',_ca)-1)	
			_ruta = this.ruta_docs(_ca)
			
			cZipFileName = _ruta+_ca+'.zip'
			cFileXMLFirmado  = oApp.rutaDigitalizadosFE+'/autorizados/'+_ca+".XML"
			cmdZip =  '7z a -tzip -mx=9 '+cZipFileName+' '+cFileXMLFirmado
			RUN &cmdZip
			DELETE FILE (cFileXMLFirmado)	
		ENDIF
	ENDFOR

ENDFUNC


FUNCTION getC(cTable,cCampo, cWhere)

	IF this.sqlexec('select '+cCampo+' as ret from '+cTable+ ' where '+cWhere,'__sqlc')>0
		RETURN __sqlc.ret
	ENDIF
	RETURN ''
ENDFUNC

FUNCTION getR(cTable,cWhere)

	IF this.sqlexec('select * from '+cTable+ ' where '+cWhere,'sqlrow')>0
		RETURN .T.
	ENDIF
	RETURN .F.
ENDFUNC


FUNCTION setRespuesta (lOk)

IF oApp.lGhostLocal

	oApp.sqlexec_local("update ghost.commander set estado=1,respuesta='"+IIF(lOk,'Ok','Error')+"' WHERE id="+oJs.cIdCmd)
	
ELSE
	cCmd = 'json/cmd_procesado.php?id='+oJs.cIdCmd+'&resp='+IIF(lOk,'Ok','Error')
	oApp.runLink(cCmd)
ENDIF

ENDFUNC

FUNCTION fixn (cCampo)
	cCampo = ALLTRIM(cCampo)
RETURN STRTRAN(cCampo,' ','_')


FUNCTION fixChars (sCad)
	sCad = STRTRAN(sCad,'&',' ')
	sCad = STRTRAN(sCad,'"',' ')
	sCad = STRTRAN(sCad,"'",' ')
	RETURN sCad
ENDFUNC

FUNCTION rand
	LPARAMETERS nLim
	RETURN INT(RAND(2008)*SECONDS()*1000000%nLim)
ENDFUNC


ENDDEFINE
