PARAMETERS llocal

PUBLIC  oJson,conexion

oJson = CREATEOBJECT ('ClassJson', llocal)
conexion = CREATEOBJECT( "MSXML2.ServerXMLHTTP" )


DEFINE CLASS ClassJson AS CUSTOM 


cWebResult = ''
cIdUser = '1'
cRuc    = ''
cIdc    = '1'
json_idc = 0

cIdu 	= '0000002'
cIds	= '0000001'
cFileName = ''
cBddName = '' 

cDirBddPd = '\ghost_pd'
cFileNamePd = ''
cBddNamePd = '' 

_cFileName = ''
_cBddName = '' 

cHost = '181.198.190.234'
cLocalHost = '192.168.1.200'

t_nfields = 0
nHTTPGetEx = 0

lConnHost = -1



FUNCTION init (llocal)
	DECLARE aV4 [1]
	
	IF FILE('v4.ini')
		oApp.explode(FILETOSTR('v4.ini'),@aV4)
		
		*MESSAGEBOX('HOOLLAAA')
		
		this.cIdc = aV4[1]
		this.cIdu = aV4[2]
		
		this.cFileName = this.cIdc+'_'+this.cIdu
		this.cBddName = this.cFileName+'.sqlite'
		
		

		this.cFileNamePd = this.cDirBddPd+'\p'+this.cFileName
		this.cBddNamePd = this.cFileNamePd+'.sqlite'

		
		IF !DIRECTORY(this.cDirBddPd)
			MKDIR (this.cDirBddPd)
		ENDIF
		
	ENDIF
	

	
	IF FILE('v4host.ini')
		this.cHost = TRIM(FILETOSTR('v4host.ini'))
	ENDIF

	

	IF FILE('v4localhost.ini')
		this.cLocalHost = TRIM(FILETOSTR('v4localhost.ini'))
	ENDIF

	IF llocal
	 	this.cHost = this.cLocalHost
	
	ENDIF
	
	
	oApp.HostJson = this.cHost
	
	
	*WAIT WINDOW oApp.HostJson
	
ENDFUNC




FUNCTION run (cCmd, cParam, cAccion, oForm, lnowait)
LOCAL cIdCmd, cMsgOut, cResult, cSecond

	cMsgOut = cCmd
	*WAIT WINDOW cMsgOut nowait
	
	cCmd = '/json/run.php?iduser='+this.cIdUser+'&cmd='+cCmd+'&param='+cParam+'&idc='+this.json_idc
	
	IF EMPTY(this.json_idc)
		MESSAGEBOX('NO ENCUENTRA LA EMPRESA '+cCmd)
		return	
	ENDIF

	
	
	nSecond = SECONDS()
	IF EMPTY(lnowait)
		WAIT WINDOW cMsgOut+ ' ('+cParam+')' nowait
	ENDIF
	
	this.runLink(cCmd, @cResult)

	IF cResult!='@@' 			
		nTimeOut = SECONDS()-nSecond
		IF EMPTY(lnowait)
			WAIT WINDOW cMsgOut+ ' ('+cParam+')  '+TRANSFORM(nTimeOut)+ ' seg. ' nowait
		ENDIF
		
		
		IF vartype(oForm)='O'
			oForm.&cAccion
		ENDIF
	ENDIF
	
ENDFUNC 


FUNCTION initMon
LOCAL cCmd


	cCmd = '/json/json_init.php?ruc='+this.cIdc

	*MESSAGEBOX(cCmd)

	this.runLink(cCmd)
	
	this.json_idc = '0'
	IF This.cWebResult='0'
		MESSAGEBOX('No esta registrada esta empresa o hay problemas en la conexión.',63,'Ghost')
	ELSE
		this.json_idc = This.cWebResult
	ENDIF
	
	*MESSAGEBOX('json_idc: '+this.json_idc)
ENDFUNC


FUNCTION runLink(cHttp,cResult)
LOCAL lcHTML,lnText,lRet, iCount

	url = 'http://'+THIS.cHost+'/'+cHttp
	conexion.open("GET", url, .F.)
	
	*STRTOFILE(url,'\temp\url.txt')
	
	lResolve = 5 * 1000
	lConnect = 5 * 1000
	lSend = 60 * 1000
	lReceive = 60 * 1000
	conexion.setTimeouts(lResolve, lConnect, lSend, lReceive);
	
	conexion.send(null)
	
	cResult = ''
	This.cWebResult = ''
	
	IF conexion.status = 200 THEN
		cResult = conexion.responseText
		This.cWebResult = cResult 
		RETURN .t.
	ENDIF
	
	*MESSAGEBOX(cResult)
	
	RETURN .f.
ENDFUNC



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

	



FUNCTION ftpsend(cFileDes, cFileOri)
	

	WAIT WINDOW 'Enviando... '+cFileDes NOWAIT
	

	cmdZip =  '7z a -mx=9 '+cFileDes+' '+cFileOri
	RUN &cmdZip
	
	*oShell.Run(cmdZip)
	
	lRetVal = .T.

	IF oIp.FTPSendFile (oApp.FtpHost,;
	            cFileDes,;
	            cFileDes,;
	            oApp.FtpUser,;
	            oApp.FtpPswd)=0
	            
	ELSE
		lRetVal = .f.
		this.msg_add('Error ftp: '+oIp.cErrorMsg)
	ENDIF

	*IF !oJs.ltest
		DELETE FILE (cFileDes)
		*DELETE FILE (cFileOri)
	*ENDIF
	
	
	*MESSAGEBOX('ssssss')

	WAIT WINDOW 'Enviado '+cFileDes TIMEOUT .3

	RETURN lRetVal 

ENDFUNC




FUNCTION msg_add (cMsg)
	cMsg = 'Json Web... ' + CHR(13) + cMsg
	WAIT WINDOW cMsg nowait
	
ENDFUNC


FUNCTION jexec(cmd)
	RETURN this.sqlite(db,cmd)
ENDFUNC

FUNCTION pexec(cmd)
	RETURN this.sqlite(pd,cmd)
ENDFUNC


FUNCTION sqlite (odb,cmd)
	LOCAL o as "adodb.recordset"

	o = odb.execute(cmd)

	IF !empty(odb.LastError) or isnull(o)

	  = MessageBox ( "Ha ocurrido un error al ejecutar: " + ;
	  	chr(13)+ odb.LastError,63,'Ghost' )
	  	
	ENDIF	

	RETURN o

ENDFUNC


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

FUNCTION t_set
	LPARAMETERS cField, eField

	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 t_insert
LPARAMETERS odb, cNameTable

	LOCAL o as "adodb.recordset"
	LOCAL lastId as "adodb.recordset"
	LOCAL nLastId
	
	nLastId = 0

	IF this.t_nfields>0
		LOCAL ii
		
		cmdInsert = 'insert into '+cNameTable+' ('+a_t_Fields[1,1]
		cmdValues = ') VALUES ('+a_t_fields[1,2]
			
		FOR ii = 2 TO this.t_nfields	
			
			cmdInsert = cmdInsert + ', '+a_t_Fields[ii,1]
			cmdValues = cmdValues + ', '+a_t_fields[ii,2]
			
		ENDFOR
		
		cmdValues = cmdValues + ')'


		*STRTOFILE(cmdInsert+cmdValues, '\eddy.txt')
		
		o = this.sqlite(odb, cmdInsert+cmdValues )
		
		lastId = this.sqlite(odb,'select id from '+cNameTable+' order by 1 desc limit 1')
		
		nLastId = lastId.item(1).item("id");

		this.t_nfields   = 0
		

	ENDIF
	
	RETURN nLastId
	
ENDFUNC

FUNCTION t_update
	PARAMETERS odb, cNameTable, cIdUpdate, cCond, cIdNameField
	
	LOCAL o as "adodb.recordset"
	
	IF VARTYPE(cIdUpdate)='N'
		cIdUpdate = ALLTRIM(STR(cIdUpdate,20,0))
	ENDIF
	

	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      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]+'='+a_t_Fields[1,2]
		cmdInsert = cmdInsert0 
		
		FOR ii = 2 TO this.t_nfields
			cmdInsert = cmdInsert + ', '+a_t_Fields[ii,1]+'='+a_t_Fields[ii,2]
		ENDFOR

		o = this.sqlite(odb,cmdInsert + cWhere0	)
		
		this.t_nfields = 0
	ENDIF
ENDFUNC




FUNCTION fixStr(sVal)
	IF ISNULL(sval) 
		sVal = ''
	ENDIF

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

	RETURN '"'+ALLTRIM(sVal)+'"'
ENDFUNC

FUNCTION setbdd_remote

DIMENSION aVv4[1]
LOCAL cRuc, cUser
	oApp.explode(oJs.cParam,@aVv4,'|')
		
	cRuc = aVv4[1]
	cUser = aVv4[2]
		
	this._cFileName = cRuc+'_'+cUser
	this._cBddName = this._cFileName+'.sqlite'

ENDFUNC

FUNCTION open_db_pd
	pd.close()
	IF !pd.Open(this.cBddNamePd) THEN
		MESSAGEBOX('Error al intentar abrir la bdd de pedidos',63,'Ghost')
		RETURN .F.
	ENDIF	
	RETURN .T.
ENDFUNC



FUNCTION preSendPed (nIdPed)

	LOCAL cParam

	cParam = this.cIdc+'|'+this.cIdu


	LOCAL oPed as "adodb.recordset"


	TEXT TO cmd NOSHOW TEXTMERGE 
		SELECT id, idcustomer, t_ini, idsalesman, pvp,
	           subtotal, subt0, subtx, iva, total,  iduser, nota, idbodega
	    FROM pedido WHERE id = <<nIdPed>>
	ENDTEXT

	LOCAL oCab as "adodb.recordset"


	oCab = this.pexec(cmd)

	
	CREATE CURSOR curCab (id int, idcustomer int, date d, hora c(8), idsalesman int, idbodega int, pvp int,;
	  subtotal double, subt0 double, subtx double, tax double, total double, iduser int, taxpercent double,;
	  nota c(250), c_lat double, c_lng double, ruc c(15))

	IF oCab.Count>0
		iCount   	= 1 
		tt = CTOT(oCab.item(iCount).item("t_ini"))
		SELECT curCab
		APPEND BLANK
		replace id		 	WITH oCab.item(iCount).item("id")
		replace idcustomer 	WITH val( oCab.item(iCount).item("idcustomer"))
		replace date	 	WITH TTOD(tt)
		replace hora	 	WITH PADL(hour(tt),2,'0')+':'+PADL(minute(tt),2,'0')+':'+PADL(sec(tt),2,'0')
		
		replace idsalesman 	WITH VAL(oCab.item(iCount).item("idsalesman"))
		
		replace idbodega 	WITH VAL(oCab.item(iCount).item("idbodega"))
		
		replace pvp	 		WITH oCab.item(iCount).item("pvp")
		replace subtotal 	WITH oCab.item(iCount).item("subtotal")
		replace subt0	 	WITH oCab.item(iCount).item("subt0")
		replace subtx	 	WITH oCab.item(iCount).item("subtX")
		replace tax			WITH oCab.item(iCount).item("iva")
		replace total	 	WITH oCab.item(iCount).item("total")
		replace idUser	 	WITH VAL(oCab.item(iCount).item("iduser"))
		replace taxpercent 	WITH oApp.niva
		replace nota	 	WITH oCab.item(iCount).item("nota")
		
		TEXT TO cmd NOSHOW TEXTMERGE 
			SELECT idpedido,id,iditem,linea,precio,descunit,
			       iva,cantidad,bultos,unidades,uc,pvp
			 FROM pedidodet WHERE idpedido=<<nIdPed>>
		ENDTEXT


		CREATE CURSOR curDet (idcab int, iddet n(12), line n(3), price n(12,6),descunit n(12,6),quantity n(10,2),bultos N(7,2),;
			unidades n(8,2),liva n(1), iva n(12,4), uc n(8,2),pvp n(1),iditem int)

		oDet = this.pexec(cmd)

		IF oDet.Count>0
			FOR iCount = 1 TO oDet.Count
			
				SELECT curDet 
				APPEND BLANK
				
				nlIva = oDet.item(iCount).item("iva")
				
				nprice = oDet.item(iCount).item("precio")
				
				nprice = ROUND(nprice/IIF(nliva=1,oApp.piva,1),6)
				
				
				*WAIT WINDOW nprice
				
				replace IdCab 		WITH oDet.item(iCount).item("idpedido")
				replace Iddet 		WITH oDet.item(iCount).item("id")
				replace IdItem 		WITH VAL(oDet.item(iCount).item("iditem"))
				replace line 		WITH oDet.item(iCount).item("linea")
				replace price 		WITH nprice
				replace DescUnit 	WITH oDet.item(iCount).item("descunit")
				replace liva 		WITH nliva
				replace iva 		WITH nprice * quantity * IIF(nliva=1,oApp.nivap,0)
				replace quantity	WITH oDet.item(iCount).item("cantidad")
				replace Bultos		WITH oDet.item(iCount).item("bultos")
				replace unidades	WITH oDet.item(iCount).item("unidades")
				replace uc			WITH oDet.item(iCount).item("uc")
				replace pvp			WITH IIF(oDet.item(iCount).item("pvp")=2,3,4)


*!*				nPrecioBase = curItemTemp.priceD
*!*				IF citems.pvp=2  && es precio C
*!*					nPrecioBase = curItemTemp.priceC
*!*				ENDIF
			
			
			ENDFOR
		ELSE
			MESSAGEBOX('Pedido en blanco',63, 'Ghost')
			RETURN ''
		ENDIF

		SELECT curDet
		*brow
		RETURN oJs.android_cd ('curCab', 'curDet')

		*this.run('salvar_pd2',cParam, 'salvar_pd',thisform,.t.)
	ENDIF
	
	RETURN ''

ENDFUNC


ENDDEFINE