PUBLIC nConn

nConn = SQLCONNECT('fss1')


fsqlexec('SELECT * FROM accountcus where balance>0 and idinvoice in (SELECT id FROM invoice where formapago=12)','curCus')

select curCus


SCAN all
	
	cidaccountcus = curCus.id
	cid = curCus.idinvoice


	fsqlexec('SELECT idaccountcuscuota FROM detareceiv where idinvoice=?cid  ','curR')
	
	SELECT curR

	GO top

	IF EOF()
		

		fsqlexec('SELECT id FROM accountcuscuota where idaccountcus=?cidaccountcus ','curCuota')
				
		cidaccountcuscuota = curCuota.id 
		
		WAIT WINDOW cidaccountcuscuota nowait

		cidreceiv = ultimo('receiv')
		
		cidcustomer = curCus.idcustomer
		ddate = curCus.date
		ntotal = curCus.total
		ciduser = curCus.iduser
		cidsalesman = curCus.idsalesman
		
		cidcc = curCus.idcc

		ciddetareceiv = ultimo('detareceiv',.t.)



		ccad4 = 'insert into receiv(id,idcustomer,date,importe,iduser,idsalesman,moneda,tipocambio,contabil)'+;
				'values(?cidreceiv,?cidcustomer,?ddate,?ntotal,?ciduser,?cidsalesman,1,1,1)'

		fsqlexec(ccad4)		


		ccad5 = 'insert into detareceiv(id0,id,idaccountype,idaccountypeorig,idaccountcuscuota,idinvoice,montooriginal,monto,moneda,tipocambio,idcc)'+;
				'values(?ciddetareceiv,?cidreceiv,"03","03",?cidaccountcuscuota,?cid,?ntotal,?ntotal,1,1,?cidcc)'

		fsqlexec(ccad5)		

		ccad6 = 'insert into auxcxc(idreceiv,idaccountcuscuota,idsalesman,chequeposf)'+;
				'values(?cidreceiv ,?cidaccountcuscuota ,?cidsalesman,1)'

		fsqlexec(ccad6)
		
		fsqlexec('update invoice set balance=0 where id=?cid')
		fsqlexec('update accountcus set balance=0 where id=?cidaccountcus')
		fsqlexec('update accountcuscuota set balance=0 where id=?cidaccountcuscuota')
	ENDIF
	
	
	SELECT curCus
		
ENDSCAN





FUNCTION ultimo

LPARAMETERS ctable,id0

IF id0
	fsqlexec('select MAX(SUBSTR(Id0,5)+0) as ultimo from '+ctable,'cultimo')
ELSE
	fsqlexec('select MAX(SUBSTR(Id,5)+0) as ultimo from '+ctable,'cultimo')
ENDIF 

SELECT cultimo
IF ISNULL(cultimo.ultimo) OR EMPTY(cultimo.ultimo)
	___cid = PADL(1,14,'0')
ELSE
	___cid = PADL(INT(cultimo.ultimo)+1,14,'0')
ENDIF 
RETURN ___cid


FUNCTION fSQLExec
	LPARAMETERS cCad,cCursor,cFileOut,cTypeOut
	

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

	IF EMPTY(cCursor)
		cCursor='SQLResult'
	ENDIF
	
	nn=sqlexec(nConn,cCad,cCursor,aCountInfo)
	
	IF !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 sqlOk(nR,cSql)
	cErr = ''
	IF nR<0
		AERROR(aErrorArray)
		FOR i= 1 TO 7
			ciErr = aErrorArray[i]
			IF VARTYPE(ciErr)='N'
				ciErr = TRANSFORM(ciErr)
			ENDIF
			
			cErr = cErr +  ciErr + CHR(13)
		ENDFOR	
	ENDIF
	IF !EMPTY(cErr)
		MESSAGEBOX(cSql+CHR(13)+cErr,63,'Ghost')
		RETURN .f.
	ENDIF
	RETURN .t.
ENDFUNC
