PARAMETERS cBdd, lJson


PUBLIC  oApp
PUBLIC oHTTP, oIP, oShell, iHTTP

oShell = createobject("WScript.Shell")

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

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


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/'

version = 1

lsubsidioventas 	= .f.

json_idc = '0'

cbfechaautorizacion = ''
lGhost_loader_nocred = .f.
nIva 			= 14
pIva			= 1.14
nIvap			= 0.14			

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 = "1"
rutaDigitalizadosFE = ''
lfacturacionelectronica = .f.
nusersucursal = 0

ghost_retardo_ventas = 0
ghost_max_connections = 10

lAutGhost = .f. 
cbdd_name = ""

ntipoemision = 0  && 0 nada, 1 pruebas, 2 produccion
demision = DATE() &&desde cuando esta vigente el ghost
dvigencia = DATE() && hasta cuando
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 2.0 powered by Tecsicom'

Host 		= 'www.tecsicom.net'
HostJson 	= '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 


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	
	ELSE
		
		*WAIT WINDOW 'Abriendo base de datos...' nowait
		
		IF !this.openDB()
			MESSAGEBOX( 'Sin conexión a la base de datos', 63, 'Ghost')
		ENDIF
		
		this.init_dbJson()


		WAIT WINDOW 'Loadsetup...' NOWAIT 
		this.loadsetup()
		
		WAIT WINDOW 'initview...' NOWAIT 
		this.initView()
		
		WAIT WINDOW 'SetGhost...' NOWAIT 
		this.setGhost()
		WAIT WINDOW '...' TIMEOUT .1
	ENDIF


ENDFUNC

FUNCTION init_dbJson(lClear)

		IF !EMPTY(lClear)
			oApp.sqlexec('drop table ghost_json')
			oApp.sqlexec('drop table ghost_dblog')
			oApp.sqlexec('drop table loader_d')
			oApp.sqlexec('drop table loader_h')
		ENDIF
		
		
		TEXT TO cCmd NOSHOW
			CREATE TABLE IF NOT EXISTS ghost_json (
			ID BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,  
			idcmd INTEGER DEFAULT 0,  
			cmd varchar(40) DEFAULT '',  
			param longtext,
			jparam longtext,
			iduser INTEGER DEFAULT 0,
			leido tinyint(4) DEFAULT 0,
			PRIMARY KEY (ID)
			) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
		ENDTEXT
		
		this.sqlexec(cCmd)

		TEXT TO cCmd NOSHOW
			CREATE TABLE IF NOT EXISTS ghost_dblog (
			ID BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,  
			error longtext,
			PRIMARY KEY (ID)
			) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
		ENDTEXT
		
		this.sqlexec(cCmd)
		
		
		TEXT TO cCmd NOSHOW
			CREATE TABLE IF NOT EXISTS ghost_dblog (
			ID BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,  
			error longtext,
			PRIMARY KEY (ID)
			) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
		ENDTEXT
		
		this.sqlexec(cCmd)
		
		TEXT TO cCmd NOSHOW
			CREATE TABLE IF NOT EXISTS ghost.commander (  
			id int(10) NOT NULL AUTO_INCREMENT,  
			iduser int(10) DEFAULT '0',  
			idc int(11) DEFAULT '0',  
			cmd varchar(40) DEFAULT NULL,  
			param longtext,  jparam longtext NOT NULL,  
			respuesta longtext,  tiempo datetime DEFAULT NULL,  
			tleido datetime DEFAULT NULL,  estado int(11) DEFAULT '0',  
			leido tinyint(4) NOT NULL DEFAULT '0',  
			PRIMARY KEY (id),  KEY ipk1 (idc),  
			KEY ipk2 (idc,iduser,cmd)
			) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
		ENDTEXT
		
		this.sqlexec(cCmd)
		
		TEXT TO cCmd NOSHOW
			CREATE TABLE IF NOT EXISTS ghost.control (  
			id int(10) NOT NULL AUTO_INCREMENT,  
			ruc varchar(20) DEFAULT NULL,
			nombre varchar(80) DEFAULT NULL,
			users_vfac text NOT NULL,
			activa int(11) DEFAULT '0',
			activity int(11) DEFAULT '0',
			PRIMARY KEY (id),  KEY ipk1 (ruc)
			) ENGINE=MYISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
		ENDTEXT	
		
		this.sqlexec(cCmd)
		
		IF this.sqlexec('SELECT id from ghost.control where ruc="'+this.cbRuc+'"')=0
		
			TEXT TO cCmd NOSHOW TEXTMERGE
				INSERT INTO ghost.control (ruc, nombre, users_vfac, activa, activity) 
				VALUES("<<this.cbRUC>>", "<<this.cbComercio>>", '1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21', 1, 1) ;
			ENDTEXT	
			
			this.sqlexec(cCmd)
		ENDIF
		
		
ENDFUNC

FUNCTION genKey()
	IF !DIRECTORY('\ghost_key')
		MKDIR \ghost_key
	ENDIF
	
	** COMISARIATO FAMLIAR  181.113.26.182
	TEXT TO sKey NOSHOW textmerge
{"id":"5","nombre":"COMISARIATO FAMILIAR","ruc":"2290326047001","tovacompu":"0","valor":"6000","pagado":"6000","web":"http://www.comisariatofamiliar.com","contacto":"","correocontacto":"facturacion@grubaluzon.com","telefonos":"062882213","fe_activa":"1","bdd_name":"","tipoemision":"2","emision":"2015-01-05","vigencia":"2020-12-31","pedidos":"0","ventas":"0","compras":"1","evale":"1","ereceiv":"1","email":"1","correo":"facturacion@grubaluzon.com","etiq_correo":"GRUBALUZON - Facturacion Electronica","lghost_fe_fv":"1","lghost_fe_nc":"1","lghost_fe_nd":"0","lghost_fe_gr":"0","lghost_fe_cr":"1","frm01":"frm01","frm04":"frm04","frm05":"frm05","frm06":"frm06","frm07":"frm07","frm_cxc":"","frm_vale":"","frm_valei":"","ciudad":"","lweb":"0","ljson":"0","lfamilia":"0","lcambiar_porc_iva":"1","rep_legal":"","host":"181.113.26.182","hostjson":"181.113.26.182","ftphost":"ftp.tecsicom.net","ftpuser":"data@tecsicom.net","ftppswd":"tecsicom2012","version":"3","emaile":"comis_familiar@tecsicom.net","final":"1"}
	ENDTEXT
	
	STRTOFILE(this.encripta(sKey),'\ghost_key\ghost_key_2290326047001')
	
	** COMISARIATO OK
	
	TEXT TO sKey NOSHOW textmerge
{"id":"5","nombre":"COMISARIATO OK","ruc":"0501339568001","tovacompu":"0","valor":"6000","pagado":"6000","web":"http://www.comisariatook.com","contacto":"","correocontacto":"facturacion@grubaluzon.com","telefonos":"062882213","fe_activa":"1","bdd_name":"","tipoemision":"2","emision":"2015-01-05","vigencia":"2020-12-31","pedidos":"0","ventas":"0","compras":"1","evale":"1","ereceiv":"1","email":"1","correo":"facturacion@grubaluzon.com","etiq_correo":"OK - Facturacion Electronica","lghost_fe_fv":"1","lghost_fe_nc":"1","lghost_fe_nd":"0","lghost_fe_gr":"0","lghost_fe_cr":"1","frm01":"frm01","frm04":"frm04","frm05":"frm05","frm06":"frm06","frm07":"frm07","frm_cxc":"","frm_vale":"","frm_valei":"","ciudad":"","lweb":"0","ljson":"0","lfamilia":"0","lcambiar_porc_iva":"1","rep_legal":"","host":"localhost","hostjson":"localhost","ftphost":"ftp.tecsicom.net","ftpuser":"data@tecsicom.net","ftppswd":"tecsicom2012","version":"3","emaile":"comis_familiar@tecsicom.net","final":"1"}
	ENDTEXT
	
	
	STRTOFILE(this.encripta(sKey),'\ghost_key\ghost_key_0501339568001')
	
	
		** PLASTIFE 181.198.190.234:91
TEXT TO sKey NOSHOW textmerge
{"id":"64","nombre":"PLASTI-FE","ruc":"1711828812001","tovacompu":"0","valor":"800","pagado":"0","web":"","contacto":"","correocontacto":"distribucionesplasti-fe@hotmail.com       ",
"telefonos":"022370653","fe_activa":"1","bdd_name":null,"tipoemision":"2","emision":"2015-11-02","vigencia":"2016-12-01","pedidos":"0","ventas":"0","compras":"0","evale":"0","ereceiv":"0","email":"1","correo":"distribucionesplasti-fe@hotmail.com       ","etiq_correo":"PLASTIFE - Facturacion Electronica","lghost_fe_fv":"1","lghost_fe_nc":"1","lghost_fe_nd":"1","lghost_fe_gr":"1","lghost_fe_cr":"1","frm01":"frm01uc","frm04":"frm04","frm05":"frm05","frm06":"frm06","frm07":"frm07","frm_cxc":"","frm_vale":"","frm_valei":"","ciudad":"SANTO DOMINGO","lweb":"0","ljson":"1","lfamilia":"0","lcambiar_porc_iva":"1","rep_legal":"","host":"181.198.190.234:91","port":"8080","hostjson":"181.198.190.234:91","portjson":"8080","ftphost":"ftp.plastife.com","ftpuser":"ghost@plastife.com","ftppswd":"1q2w3e4r","version":"3","emaile":"ghost@plastife.com","final":"1"}
ENDTEXT
	
	STRTOFILE(this.encripta(sKey),'\ghost_key\ghost_key_1711828812001')
	
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("json/get_data.php?ruce="+this.cbRUC, @cWEB)
		ENDIF
	ENDIF
	
	
	
	IF (lSeguir AND cWEB!='@@' AND !EMPTY(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.lGhost_web 	= o.lweb="1"
			this.lGhost_json	= o.ljson="1"
			this.json_idc 		= o.id
			
			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 			= o.host
			this.hostjson		= o.hostjson
			
			this.port 			= TRIM(o.port)
			this.portjson		= TRIM(o.portjson)
			
			IF VARTYPE(o.localport)='O'
				this.localport		= TRIM(o.localport)
			ENDIF
			
			
			this.ftphost 		= o.ftphost
			this.ftpuser 		= o.ftpuser
			this.ftppswd 		= o.ftppswd
			
			this.version 		= o.version
			
			&&mESSAGEBOX( this.host +CHR(13) +this.ftphost+CHR(13)+this.ftpuser+CHR(13)+this.ftppswd)
		ELSE 
			MESSAGEBOX('Error de conexion '+CHR(13)+cWEB ,63,'Ghost')
			this.lAutGhost = .f.
		ENDIF
		
		IF this.lGhostLocalFE
			this.host = 'localhost'+IIF(!EMPTY(this.localport),':'+this.localport,'')
		ENDIF
		
	ENDIF
	
	lSeguir = .T.
	cWeb = '0'
	IF FILE(cFileConfigIdc)
		cWEB = FILETOSTR(cFileConfigIdc)	
	ELSE
		lSeguir = this.runLink('json/json_init.php?ruc='+this.cbRuc, @cWeb)
	ENDIF

	IF lSeguir AND VAL(cWeb)>0
		STRTOFILE(cWEB,cFileConfigIdc)
		this.json_idc = ALLTRIM(cWeb)
		this.lGhost_json	= .T.
	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.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')
	
	IF EMPTY(this.cbAddressSucursal)
		this.cbAddressSucursal = this.cbAddress
	ENDIF
	this.niva			= this.setup('TAXPERCENT','N',,,14)
	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.cRutaWWW = this.setup('cRutaWWW ','C',,,'/wamp/www/data/')

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 

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

		RETURN .f.
	ENDIF
	RETURN .t.
ENDFUNC


FUNCTION SQLExec
	LPARAMETERS cCad,cCursor,cFileOut,cTypeOut
	

	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


*---------------------------------------------
* 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 &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
			this.sqlexec('INSERT INTO ghost_dblog (error) values ("'+this.cErr+'")')
		ENDIF

	ENDIF

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 runLink(cHttp,cResult)
LOCAL lcHTML,lnText,lRet, iCount

	IF this.ltecsicom_host	
		this.lConnHost = .f.
		this.ltecsicom_host	= .f.
		IF !this.HTTPConnectHost ()
			RETURN .f.
		ENDIF
		
	ELSE
		IF !this.lConnHost
			IF !this.HTTPConnect()
				WAIT WINDOW 'NO SE CONECTO: '+THIS.hostJson
				RETURN .f.
			ENDIF
		ENDIF
	ENDIF
	

	lcHTML=""
	lnText=0
	this.nHTTPGetEx = oHTTP.HTTPGetEx(cHttp,@lcHTML,@lnText)
	cResult = lcHTML
	This.cWebResult = lcHTML
	
	RETURN this.nHTTPGetEx=0
ENDFUNC

FUNCTION HTTPConnect ()

	
	
	this.lConnHost = (oHTTP.HTTPConnect(this.host)=0)
	
	IF !this.lConnHost
		MESSAGEBOX("Sin conexión a internet",63,"Ghost")
	ENDIF
	RETURN this.lConnHost
ENDFUNC

FUNCTION HTTPConnectHost ()

	this.HTTPclose()
	
	this.lConnHost = (oHTTP.HTTPConnect('www.tecsicom.net')=0)
	
	IF !this.lConnHost
		MESSAGEBOX("Sin conexión a internet",63,"Ghost")
	ENDIF
	RETURN this.lConnHost
ENDFUNC

FUNCTION HTTPclose()
	this.lConnHost = .f.
	oHTTP.HTTPclose()
ENDFUNC


*!*	FUNCTION doHttp
*!*	PARAMETERS cHttp, nAplicaBdd, noUtil

*!*		IF VARTYPE(oHTTP)!='O'
*!*			RETURN .F.
*!*		ENDIF

*!*		lcRet = .f.
*!*		IF this.HTTPConnect ()
*!*			lcRet = this.doHttp_(cHttp, nAplicaBdd, noUtil)
*!*			oHTTP.HTTPclose()		
*!*		ENDIF


*!*		
*!*		RETURN lcRet
*!*	ENDFUNC


*!*	FUNCTION _runLink(cHttp,cResult)
*!*	LOCAL lcHTML,lnText,lRet 

*!*		IF VARTYPE(oHTTP)!='O'
*!*			RETURN .F.
*!*		ENDIF

*!*		lcHTML=""
*!*		lnText=0
*!*		
*!*		lRet = -1
*!*		
*!*		This.cWebResult = ''
*!*		IF this.HTTPConnect ()

*!*			lRet = oHTTP.HTTPGetEx(cHttp,@lcHTML,@lnText)
*!*			cResult = lcHTML
*!*			This.cWebResult = lcHTML
*!*			oHTTP.HTTPclose()

*!*		ELSE
*!*			MESSAGEBOX('No se conecto: '+cHttp)
*!*		ENDIF 
*!*		
*!*		RETURN lRet=0
*!*	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 doHttp_
*!*	PARAMETERS cHttp, nAplicaBdd, noUtil

*!*		IF VARTYPE(oHTTP)!='O'
*!*			RETURN .F.
*!*		ENDIF
*!*		
*!*		IF EMPTY(noUtil)
*!*			cHttp = "./web/"+cHttp 
*!*		ENDIF	
*!*		
*!*		IF EMPTY(nAplicaBdd)
*!*			nAplicaBdd = 0
*!*		ENDIF
*!*		
*!*		IF nAplicaBdd= 1 && con parametros
*!*			cHttp = cHttp + '&bdd='+this.bdd+'&user='+this.bdd_user+'&pswd='+this.bdd_pswd
*!*		ENDIF

*!*		IF nAplicaBdd= 2 && sin parametros
*!*			cHttp = cHttp + '?bdd='+this.bdd+'&user='+this.bdd_user+'&pswd='+this.bdd_pswd
*!*		ENDIF
*!*			
*!*		lcHTML=""
*!*		lnText=0
*!*		
*!*	*	WAIT WINDOW cHttp

*!*		oHTTP.HTTPGetEx(cHttp,@lcHTML,@lnText)
*!*		
*!*		
*!*		RETURN lcHTML
*!*	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 = this.cMsgLabel + CHR(13) + 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. '+CHR(13)
	CASE cTipo='04'
		cTit = 'Nota de Crédito Nro. '+CHR(13)
	CASE cTipo='05'
		cTit = 'Nota de Débito Nro. '+CHR(13)
	CASE cTipo='06'
		cTit = 'Guía de Remisión Nro. '+CHR(13)
	CASE cTipo='07'
		cTit = 'Comp. de Retención Nro. '+CHR(13)
	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,'&','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]


	
	IF oJs.ltest
		*MESSAGEBOX(cCmd)
		*STRTOFILE(cCmd,'\android_reverse_cd.txt')
	ENDIF
	
	*STRTOFILE(cCmd,'\android_reverse_cd.txt')

	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
		
*!*			IF oJs.ltest
*!*				MESSAGEBOX(cRet)
*!*			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
		
*!*			IF oJs.ltest
*!*				MESSAGEBOX(cRet)
*!*			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

ENDDEFINE
