PARAMETERS cInvoicerType, cFecha, cFuente, cBdd, cIdView

PUBLIC oInvoicer 

IF !EMPTY(cInvoicerType)

	IF EMPTY(cFecha)
		cFecha = DTOC(DATE(),1)
	ENDIF

	IF EMPTY(cBdd)
		cBdd='fss1'
	ENDIF

SET PATH TO proj,json,classes, form,prg,class

	SET TALK off
	SET STATUS BAR OFF
	SET SYSMENU off
	SET DELETED on
	SET CONFIRM OFF
	SET NOTIFY off
	SET SAFETY off
	SET CENTURY ON
	SET DATE TO DMY
	SET FIXED OFF
	SET DECIMALS TO 6
	_SCREEN.Visible=.T.

	DO app.prg WITH cBdd
	oApp.loadGhost()
	
	DO stock.prg 

	oApp.cFechaInvoicer = cFecha
	*MESSAGEBOX(oApp.cFechaInvoicer)
	oApp.cInvoicerType = cInvoicerType

	DO loader.prg WITH .T., cFuente
	oInvoicer = CREATEOBJECT ('InvoicerClass',cIdView)
	oInvoicer.run()
ELSE

	DO app.prg WITH cBdd
	oApp.cFechaInvoicer = cFecha
	oApp.cInvoicerType = cInvoicerType

	DO loader.prg WITH .F., cFuente
	oInvoicer = CREATEOBJECT ('InvoicerClass',cIdView)

ENDIF

DO stock.prg

DEFINE CLASS InvoicerClass AS CUSTOM 


pc_seriepv = '001001'
cMsgResult = ''

&& Funciones de Base de Datos



lFactDiaDespues = .f.

lredondear = .t.
nDecimales = 2


lcmdproc = .f.
linvoice_mon = .f.

dFecha = DATE()
dVenc = DATE()
nTotalFact = 0
cIdCust = PADL('0',12,'0')
cIdSalesman = PADL('0',8,'0')
cNota = ''
cIdInst = PADL('0',12,'0')
cIdInvoice = ''
cIdZona = ''
cIdcc = ''
cIdcp = ''
cId_Cuota = ''
cId_CuotaCab = ''
cIdBodega = ''
cIdUser = ''

nDiasCredito = 0
idBank = ''
numerorecibo = ''

cuenta = ''
numdoc = ''
titular = ''
moneda = 1
tipocambio = 1

MonedaDoc = 1
TipoCambioDoc = 1

idanticipo = ''
numerorecibo = ''		

IdReceiv	= ''
idRecibos	= ''
idchequespos = ''

cSerieSec = ''


nEF = 0
nRetIva = 0
nRetFte = 0

cTitulo = 'Ghost Web...'+CHR(13)

cIdView = ''
oForm = ''

lInterno = .f.
INFOADICIONAL1 = ''
fechaanuncio = ''
fe_manual = .f.
nIva = 12


FUNCTION init(cIdView)
	this.nIva 			= 12
		
	IF this.nIva < 12  
		this.nIva=oApp.nIva
	ENDIF
	
	IF !EMPTY(cIdView)
		this.cIdView = cIdView
	ENDIF
ENDFUNC

FUNCTION run (n_noPed, lInterno)
	this.cTitulo = 'Ghost Web...'
	
	IF empty(oApp.cInvoicerType)
		oApp.cInvoicerType = '00'
	ENDIF
		
	IF !EMPTY(lInterno)
		this.lInterno = .t.
	ENDIF

	IF oApp.cInvoicerType='01' OR oApp.cInvoicerType='03'
		this.cTitulo = 'FuelControl...'+CHR(13)
		this.ndecimales = 4  && 20150806
	ENDIF

	IF oApp.cInvoicerType='02'
		this.cTitulo = 'Orion...'+CHR(13)
	ENDIF
	
	IF oApp.cInvoicerType='04'
		this.cTitulo = 'Excel...'+CHR(13)
		this.lredondear = .f.
		this.ndecimales = 6  && antes
		
		this.ndecimales = 2
		
	ENDIF


	IF oApp.cInvoicerType='05'
		this.cTitulo = 'Gasolineras...'+CHR(13)
		this.lredondear = .f.
		this.ndecimales = 6  && antes
		this.ndecimales = 2
	ENDIF
	
	IF oApp.cInvoicerType='06'
		this.cTitulo = 'Avalab...'+CHR(13)
		this.lredondear = .f.
		this.ndecimales = 6  && antes
		this.ndecimales = 2
	ENDIF

	this.invoicer(n_noPed)
	oApp.setView (this.cIdView,2)
	oApp.setSetup('Ghost_lInvoicerBuzy',.F.,'L')
	
	*oApp.closeDB()

ENDFUNC


FUNCTION invoicer(n_noPed)
LOCAL cNumero
	
	this.msg_add('Cargando...')
	
	cCmd = 'SELECT * FROM loader_h WHERE estado=0 '+IIF(!EMPTY(n_noPed),' and noped='+transform(n_noPed),'')
	
	*STRTOFILE(cCmd,'\loader_h.txt')
		
	nRegProcesar = oApp.sqlexec(cCmd,'cabeza')
	
	oApp.sqlexec('SELECT distinct d.iditem FROM loader_h as h inner join loader_d as d on h.noped=d.noped WHERE estado=0','curStockUp')
		
	
	*oApp.sqlexec('UPDATE loader_h SET estado=1 WHERE estado=0')
	
	
	nsec = SECONDS()

	SELECT cabeza
	
	*BROWSE
	
	SELECT cabeza
	
	SCAN all
	
		Id_loader_h		= cabeza.id
		
		no_ped 			= cabeza.noped
	
		cTF 	  		= cabeza.tipo
		
		this.nIva 		= Cabeza.taxpercent
		
		IF this.nIva < 12  
			this.nIva=oApp.nIva
		ENDIF
				
		cAutorizacion 	= ''
		dValidez  		= DATE()
		nTipoPago 		= Cabeza.formapago && credito
		
		IF cabeza.lcontado=1
			nTipoPago = 12
		ENDIF
		
		
		this.cNota 			= ''
		this.nDiasCredito 	= 3 &&Credito
		
		this.cIdCust   		= oApp.fill_id(Cabeza.idcustomer,12)
		
		
		this.cIdSalesman	= Cabeza.idSalesman
		
		
		this.cIdCC 	  	= cabeza.idcc
		this.cIdBodega 	= cabeza.idbodega
		this.cIdcp		= cabeza.idcp
		
		cHora 	  		= Cabeza.hora
		this.dFecha	  	= Cabeza.fecha
		
		cNumero   		= PADL(INT(val(Cabeza.idSalesman)),4,'0')+'-'+PADL(cabeza.noped,9,'0')
		
		IF oApp.cInvoicerType='01' 
			*cNumero   	= ALLTRIM(TRANSFORM(cabeza.SERIE))+'-'+ALLTRIM(TRANSFORM(cabeza.noped))
			*cNumero   	= PADL(INT(val(Cabeza.idSalesman)),4,'0')+'-'+ALLTRIM(transform(cabeza.noped))
			cNumero 	= PADL(INT(val(Cabeza.idSalesman)),2,'0')+SUBSTR(DTOC(this.dfecha,1),3)+'-'+ALLTRIM(transform(cabeza.noped))
		ENDIF
		
		IF oApp.cInvoicerType='03' 
			*cNumero   	= ALLTRIM(TRANSFORM(cabeza.SERIE))+'-'+ALLTRIM(TRANSFORM(cabeza.noped))
			cNumero 	= ALLTRIM(transform(cabeza.noped))
		ENDIF
		
		IF oLoader.lBodegasVendor
			cNumero   		= transform(cabeza.noped)
		ENDIF
		
		IF oApp.cInvoicerType='88' OR oApp.cInvoicerType = '06'
			cNumero   		= ALLTRIM(transform(cabeza.noped))
		ENDIF
		
		
		IF oApp.cInvoicerType = '06'
			cNumero   		= SUBSTR(DTOC(this.dfecha,1),3)+'-'+ALLTRIM(transform(cabeza.noped))
		ENDIF
	

		nPvp			= Cabeza.pvp
	
		this.cIdZona 	= "000000001"
		this.cIdInst    = "000000000001"
		
		cIdRuta 		= "000000001"
		cIdWH			= "000000000001"
						   
		cIdDep  		= ""
		
*!*			IF ('SELECT id,idinstitucion,idzona,idDepart,diascredito FROM Customer where id=?cIdCust')>0
*!*				cIdInst = sqlresult.idinstitucion
*!*				cIdZona = sqlresult.idzona
*!*				cIdDep  = sqlresult.idDepart
*!*				nDiasCredito = sqlresult.DiasCredito
*!*			ENDIF
		
		
		
		lConsumidorFinal = .F.
	
		cCliente 	= ALLTRIM(cabeza.cliente)
		cComercio 	= ALLTRIM(cabeza.comercio)
		cAddress 	= ALLTRIM(cabeza.address)
		cRuc 		= ALLTRIM(cabeza.ruc)
		cPhone 		= ALLTRIM(cabeza.phone)
		cCity 		= ALLTRIM(cabeza.city)
		cEmail 		= ALLTRIM(cabeza.email)
		
		cTipoRuc   	= IIF(LEN(cRuc)=13,'04','05')
		
		IF LEN(cRuc)<10
			cTipoRuc   	= '06'
		ENDIF
		
		
		this.nDiasCredito  = 0 &&Contado
		
		IF cRuc='9999999999'
			lConsumidorFinal = .T.
			cTipoRuc = '07'
			this.cIdCust = PADL(0,12,'0')
		ENDIF

		cIdCust = this.cIdCust
		cIdInst = this.cIdInst
		cIdSalesman = this.cIdSalesman
		cIdZona = this.cIdZona		
		
		sss = ALLTRIM(transform(cabeza.noped))
		
		IF !lConsumidorFinal AND !EMPTY(cRuc)
			IF oApp.sqlexec('SELECT id,idsalesman, idinstitucion,idzona,idDepart,diascredito FROM Customer where ruc=?cRuc')=0
				&&IF !EMPTY(this.valRuc (cRuc))  && sin errores
					&&lConsumidorFinal = .F.
				&&ELSE
				this.cIdCust = oApp.newid('customer',12,.t.)
				c_idCust__ = this.cIdCust
				oApp.sqlexec('insert into customer (id,name,comercio,address,ruc,tiporuc,phone,idinstitucion,idsalesman,iddepart,idzona,pvp,state,applytax, city, email,ya) values '+;
						     '(?c_idCust__,?cCliente,?cComercio,?cAddress ,?cRuc,?cTipoRuc,?cPhone,?cIdInst,?cIdSalesman,?cIdDep,?cIdZona,1,1,1,?cCity ,?cEmail,0)')
				&&ENDIF
			ELSE
				this.cIdCust = sqlresult.id
				this.cIdInst = sqlresult.idInstitucion
				cIdCust = this.cIdCust
				
				IF EMPTY(this.cIdSalesman)
					this.cIdSalesman = sqlresult.idSalesman
				ENDIF
				
				IF EMPTY(this.cIdZona)
					this.cIdZona = sqlresult.idZona
				ENDIF
				
				cIdDep = sqlresult.idDepart
	
				this.nDiasCredito  = sqlresult.DiasCredito
				
				IF !lConsumidorFinal 
					IF oApp.cInvoicerType='06'
						oApp.sqlexec('update customer set email=?cEmail, ya=0 where id=?cIdCust ')
						oApp.sqlexec('update customer set address=?cAddress, ya=0 where id=?cIdCust  ')
						oApp.sqlexec('update customer set phone=?cPhone, ya=0 where id=?cIdCust ')
					ENDIF
				ENDIF
			ENDIF
		ENDIF

		cIdRecaud		= this.cIdSalesman		
		cIdCust = this.cIdCust
		cIdInst = this.cIdInst
		cIdSalesman = this.cIdSalesman
		cIdZona = this.cIdZona		
		
		this.cIdCC     = cabeza.idcc
		this.cIdCp     = cabeza.idcp
		this.cIdUser   = cabeza.iduser
		
		IF EMPTY(this.cIdUser)
			this.cIdUser = PADL(2,8,'0')
		ENDIF
		
		
		IF !EMPTY(cabeza.idbodega)
			this.cIdBodega = cabeza.idbodega
		ENDIF
		
		cIdUser = this.cIdUser
		IF oApp.sqlexec('SELECT idbodega,idcc,idcp,seriepv FROM user where id=?cIdUser','curUser')>0

			IF EMPTY(this.cIdBodega)
				this.cIdBodega = curUser.idbodega
			ENDIF

			IF EMPTY(this.cIdCC)
				this.cIdCC = curUser.idcc
			ENDIF

			IF EMPTY(this.cIdCp)
				this.cIdCp = curUser.idcp
			ENDIF

			
		ENDIF
		
		
	 	this.cNota = Cabeza.nota
	 	cNota = Cabeza.nota
		this.nTotalFact = 0
		this.cId_Cuota = ''
		
		this.msg_add('Doc. nro. '+ cNumero )
	

		oApp.t_clear()
		
		cCmd ='SELECT id,serie,secuencia,seriesec,usersec FROM Invoice WHERE numero="'+cNumero+'"'
		
		sss = ALLTRIM(transform(cabeza.noped))
		
		IF !this.lInterno 
			*oApp.doLink("./web/invoice_release.php?pedido="+sss)
		ENDIF
		

		IF oApp.sqlexec(cCmd)>0
			this.msg_add('Pedido No. '+cNumero+' ya ha sido registrado!')
			*MESSAGEBOX(cNumero+CHR(13)+oApp.cInvoicerType)
		ELSE
		

		
			IF oApp.cInvoicerType='88'
				cSerie = ALLTRIM(curUser.seriepv)+'01'
				cSecuencia = oApp.newSeq('INVOICE',10,'SERIE',cSerie ,'SECUENCIA',.t.)
				cSerieSec = LEFT(cserie,6)+'-'+PADL(INT(VAL(csecuencia)),9,'0')
			ELSE
				cSerie 	   = Cabeza.serie+cTF
				cSecuencia = oApp.newSeq('INVOICE',10,'SERIE',cSerie ,'SECUENCIA',.t.)
				cSerieSec  = LEFT(cSerie ,6)+'-'+PADL(cabeza.numero,9,'0')
			ENDIF
			cUserSec   = oApp.newSeq('INVOICE',10,'IDUSER',this.cIdUser,'USERSEC',.t.)				
			
			this.cSerieSec = cSerieSec
			
			IF (vartype(this.oForm)='O')
				oForm = this.oForm
				oForm.seriesec.value = cSeriesec
			ENDIF
		
			this.cIdInvoice = oApp.newId('Invoice',14,.T.)
			
			STORE 0 TO nSubt0, nSubtX, nSubtotal, nDescUnit
			
			this.detalle_(cabeza.noped, @nSubt0, @nSubtX, @nSubtotal, @nDescUnit)


			nSubtotal 	= ROUND(nSubtotal,this.nDecimales)
			nDiscount 	= ROUND(cabeza.descuento/100*(nSubt0+nSubtX),this.nDecimales)
			pDiscount 	= ROUND(cabeza.descuento,this.nDecimales)
			nSubt0 		= ROUND(nSubt0*(1-pDiscount/100),this.nDecimales)
			nSubtX 		= ROUND(nSubtX*(1-pDiscount/100),this.nDecimales)
			nIvaTotal 	= ROUND(nSubtX * this.nIva/100,this.nDecimales)
			this.nTotalFact 	= ROUND(nSubTotal - nDiscount + nIvaTotal,2)
			
			
			oApp.t_clear()	
			oApp.t_set('Id',this.cIdInvoice,'C')
			oApp.t_set('serie',cSerie)
			oApp.t_set('seriesec',cSerieSec)
			oApp.t_set('secuencia',cSecuencia)
			oApp.t_set('usersec',cUserSec)
			
			this.dVenc = this.dFecha+this.nDiasCredito
			
			oApp.t_set('archivado ',IIF (cabeza.accion>0,1,0))
			oApp.t_set('date',this.dFecha)
			oApp.t_set('due',this.dVenc)
			oApp.t_set('Total',this.nTotalFact)
			oApp.t_set('cobros',0)
			oApp.t_set('balance',this.nTotalFact)
			oApp.t_set('idcustomer',this.cIdCust) 
			oApp.t_set('iduser',this.cIdUser)
			oApp.t_set('iduserInicial',this.cIdUser)
			oApp.t_set('idinst',this.cIdInst)
			oApp.t_set('idBodega',this.cIdBodega)
			oApp.t_set('idZona',this.cIdZona)
			oApp.t_set('idtipoventa',cabeza.idtipoventa)
			

			oApp.t_set('idRuta',cIdRuta)
			oApp.t_set('idwarehouse',cIdWH)
			oApp.t_set('idRecaudador',cIdRecaud)
		
			
			oApp.t_set('IdSalesman',this.cIdSalesman)
			oApp.t_set('iddepart',cIdDep)
			oApp.t_set('Moneda',this.moneda)
			oApp.t_set('tipocambio',this.tipocambio)
			oApp.t_set('tax',nIvaTotal)
			oApp.t_set('taxPercent',this.nIva)
			oApp.t_set('subtotal',nSubtotal)
			oApp.t_set('discount',nDiscount)
			oApp.t_set('overcharge',0)
			oApp.t_set('subtx',nSubtX)
			oApp.t_set('subt0',nSubt0)
			oApp.t_set('descunit',nDescUnit)	
			oApp.t_set('hora',cHora)
			oApp.t_set('codeprinter',1)		
			oApp.t_set('autorizacion','') 
			&&oApp.t_set('caduca',oApp.cbvalidez)				
			oApp.t_set('pvp',cabeza.pvp)
			oApp.t_set('formaPago',nTipoPago)
			oApp.t_set('ocasional',2)
			oApp.t_set('contado', IIF(nTipoPago= 12 or nTipoPago=8,0,1))
			oApp.t_set('numero',cNumero)			
			oApp.t_set('DISCOUNTPERCENT',pDiscount)	
			oApp.t_set('tipo',cTF)
			oApp.t_set('idCC',this.cIdCC)
			oApp.t_set('idCp',this.cIdCP)
			oApp.t_set('sri_tipoventa',1)
			
			oApp.t_set('xmlfe',IIF (oApp.lGhost_fact_manual or this.fe_manual,1,0))
			
			IF oApp.lgasolinera
				*oApp.t_set('Nofacturaelectronica',0)
				oApp.t_set('lsubsidioventas',1)
			else
				*oApp.t_set('Nofacturaelectronica',IIF (VAL(oApp.cInvoicerType)!=88,1,0))
			ENDIF
			oApp.t_set('Nofacturaelectronica',0)
			
			
			oApp.t_set('void',cabeza.anulado)
			
			IF oApp.lgasolinera
				oApp.t_set('guia',ALLTRIM(cabeza.placa))
			ENDIF
			
		
			oApp.t_insert('Invoice')
			
	
			IF cabeza.ruc='9999999999'
				this.invoice_('cliente',cabeza.cliente)
				this.invoice_('ruc',cabeza.ruc)
				this.invoice_('phone',cabeza.phone)
				this.invoice_('address',cabeza.address)
			ENDIF
			
			IF !EMPTY(cNota)
				IF !EMPTY(this.INFOADICIONAL1)
					cNota = ALLTRIM(cNota) +'|'+ this.cIdInvoice
				ENDIF
				this.invoice_('noteprint',cNota)
			ENDIF
			
			IF cTF!='03'
			
				oApp.t_clear()

				oApp.t_set('idinvoice',this.cIdInvoice,'C')
				oApp.t_set('seriesec',cSerieSec,'C')
				oApp.t_set('secuencia',cSecuencia,'C')
				oApp.t_set('usersec',cUserSec)
				oApp.t_set('date',this.dFecha)
				oApp.t_set('due',this.dVenc)
				oApp.t_set('Total',this.nTotalFact)
				oApp.t_set('balance',this.nTotalFact)
				oApp.t_set('idcustomer',this.cIdCust)
				oApp.t_set('idaccountype',"00",'C')
				oApp.t_set('iduser',this.cIdUser)
				oApp.t_set('idinst',this.cIdInst)
				oApp.t_set('IdSalesman',this.cIdSalesman)
				oApp.t_set('iddepart',cIdDep)	
				oApp.t_set('Moneda',this.moneda)
				oApp.t_set('tipocambio',this.tipocambio)
				oApp.t_set('formaPago',nTipoPago)
				oApp.t_set('efectivo',IIF(nTipoPago= 12 or nTipoPago=8  or nTipoPago=9,1,0)) 
				
				
				this.cId_CuotaCab	= oApp.newid('ACCOUNTCUS',14,.t.)
				oApp.t_set('Id',this.cId_CuotaCab)
				oApp.t_insert('ACCOUNTCUS')

				&& Save table acountcuscuota


				oApp.t_clear()
				oApp.t_set('idAccountCus',this.cId_CuotaCab,'C')
				oApp.t_set('reference',cSerieSec )
				oApp.t_set('date',this.dFecha)
				oApp.t_set('due',this.dVenc)
				oApp.t_set('total',this.nTotalFact)
				oApp.t_set('balance',this.nTotalFact)
				oApp.t_set('cuota',1)
				oApp.t_set('idaccountype',"00")
				oApp.t_set('Tipo',IIF(nTipoPago=12 or nTipoPago=8 or nTipoPago=9,1,0)) && 0->Factura x cobrar; 1->efectivo; 2-> cuota ini

				this.cId_cuota = oApp.newId('AccountCusCuota',14,.T.)
				oApp.t_set('Id',this.cId_cuota,'C')
				oApp.t_insert('AccountCusCuota')	
				

				IF cabeza.accion>0 AND cTF='01' && deja en pendiente
					
					this.nEF = cabeza.efectivo
					
					IF nTipoPago=12
						this.nEF = this.nTotalFact
					ENDIF	
					
					this.cuenta = cabeza.cuenta
					this.idbank = cabeza.idbank
					this.numdoc = cabeza.numdoc
					
					this.Receiv (nTipoPago, this.nEF,this.nRetFte,this.nRetIva)

				ENDIF
			ENDIF 
		ENDIF
		
		SELECT cabeza
		
		oApp.sqlexec('delete from loader_h WHERE noped=?no_ped')
	ENDSCAN	
	
	
*	oApp.sqlexec('delete from loader_h where estado=1 ')
	oApp.sqlexec('delete from loader_d where noped not in (select noped from loader_h) ')

	this.msg_add(TRANSFORM(SECONDS()-nsec)+' segs.') 
	
	
	oStock.actualizarStock ('curStockUp')
	
	IF nRegProcesar>0
		oApp.setSetup('ghost_actualizar_vfac',.T.,'L')
	ENDIF
		
	RETURN this.cMsgResult
ENDFUNC
	
FUNCTION invoice_(cCampo,cValor)
	cId_Invoice = this.cIdInvoice
	IF !EMPTY(cValor) 
		lAct = oApp.sqlexec('select id from invoice_'+cCampo+' where id=?cId_Invoice')
		oApp.t_clear()				
		oApp.t_set(cCampo,cValor)
		IF lAct>0
			oApp.t_update('invoice_'+cCampo,cId_Invoice)
		ELSE
			oApp.t_set('Id',cId_Invoice)	
			oApp.t_insert('invoice_'+cCampo)
		ENDIF
	ENDIF	
ENDFUNC

FUNCTION detalle_ 
PARAMETERS _noPed, nSubt0,nSubtX, nSubtotal, nDescUnit

	nRecs = oApp.sqlexec('SELECT * FROM loader_d WHERE noped='+transform(_noPed),'detalleCur')

	nDescUnit = 0
	
	cIdInvoice = this.cIdInvoice
	cIdBodega = this.cIdBodega
	
	SELECT detalleCur

	IF nRecs>0
		oApp.sqlexec('DELETE FROM invoicedet WHERE id=?cIdInvoice')
			
		oApp.t_clear()
		SELECT detalleCur

		nLine = 0
		nSubt0 = 0
		nSubtX = 0
		nSubtotal = 0
		GO top
		SCAN ALL
			cIdItem = detalleCur.iditem
			liva = 1
			cNoteUnidad = ''
			
			nPrecioBase = detalleCur.precio
			nuc=1
			nOp = 1
			IF oApp.sqlexec('SELECT id,iva,noteunidad,costo, unidadescaja,price,priceb,pricec,priced,pricee  FROM item where id=?cidItem','curItem')>0
		
				lIva = curItem.iva
				IF lIva=0
					nIva = 0
				ENDIF
				cNoteUnidad = curItem.noteunidad
				
				nPrecioBase = curItem.price
				nOp = VAL(TRANSFORM(detalleCur.pvp))
				IF nOp=2
					nPrecioBase = curItem.priceb
				ENDIF
				IF nOp=3
					nPrecioBase = curItem.pricec
				ENDIF
				IF nOp=4
					nPrecioBase = curItem.priced
				ENDIF
				IF nOp=5
					nPrecioBase = curItem.pricee
				ENDIF
				
				nuc = IIF(curItem.unidadescaja<1,1,curItem.unidadescaja)
				
				
			ENDIF
			
			nPrecio = detalleCur.precio &&/ IIF(lIva=1,this.pIva,1) &&77
			nCosto = nPrecio *.8
			IF oApp.sqlexec('SELECT stock,costavg FROM stock WHERE idItem=?cIdItem')>0
				nCosto = sqlresult.costavg
			ENDIF

			
			nIva = detalleCur.cantidad*nPrecio*IIF(lIva=1,this.nIva/100,1)
			
			nLine = nLine + 1
			
			pDesc = detalleCur.descuento
			nDesc = pDesc/100*nPrecio
			
			nDescUnit = nDescUnit + nDesc 
	
			nSubtDet = ROUND(detalleCur.cantidad*(nPrecio-nDesc),this.nDecimales)
			
			IF lIva=0
		   		nSubt0 = nSubt0 + nSubtDet
		   	ELSE
		   		nSubtX = nSubtX + nSubtDet
		   	ENDIF
		   	
		   	nSubtotal = nSubtotal + nSubtDet
		   	
		   	oApp.t_clear()	
			oApp.t_set('Id',this.cIdInvoice)
			oApp.t_set('line',PADL(nLine,4,'0'))
			oApp.t_set('idItem',cIdItem)
			oApp.t_set('cost',nCosto,'N')
			oApp.t_set('price',detalleCur.precio,'N')
			oApp.t_set('precioBase',nPrecioBase,'N')
			oApp.t_set('iva',this.nIva)
			oApp.t_set('liva',liva,'I')
			oApp.t_set('quantity',detalleCur.cantidad,'N')
			oApp.t_set('quantitySal',detalleCur.cantidad,'N')
			oApp.t_set('noteunidad',cNoteUnidad,'C')
			oApp.t_set('imprimir',1,'I')
			oApp.t_set('factconv',1,'I')
			oApp.t_set('descunit',nDesc)
			oApp.t_set('idBodega',this.cIdBodega)
			oApp.t_set('pdescunit',pDesc)
			oApp.t_set('pvp',detalleCur.pvp)
			oApp.t_set('IdSalesman',this.cIdSalesman)

			nunidades=detalleCur.cantidad
			nbultos = FLOOR(nunidades/nuc)
			nunidades = nunidades-nbultos*nuc
			

			oApp.t_set('bultos', 	transform(nbultos))
			oApp.t_set('uc', 		transform(nuc))
			oApp.t_set('unidades', 	transform(nunidades))
			
			
			IF !EMPTY(this.INFOADICIONAL1)
				oApp.t_set('INFOADICIONAL1',this.INFOADICIONAL1)
			ENDIF
			
			IF !EMPTY(this.fechaanuncio)
				oApp.t_set('fechaanuncio',this.fechaanuncio)
			ENDIF
			
			
			oApp.t_insert('invoiceDet')	
			
				oApp.t_clear()	
			
			nVenta = detalleCur.cantidad
			*oApp.sqlexec('UPDATE stock SET stock=stock-?nVenta, ya=3 WHERE idItem=?cIdItem')
			*oApp.sqlexec('UPDATE stockbod SET cantidad=cantidad-?nVenta, salida=salida+?nVenta, ya=3 WHERE idbodega=?cIdBodega and idItem=?cIdItem')
			
			SELECT detalleCur
		ENDSCAN
	ENDIF
ENDFUNC



PROCEDURE Receiv (nTipoPago, nEF, nRetFte, nRetIva)

	nEF = IIF (EMPTY(nEF),0,nEF)

	nRetFte = IIF (EMPTY(nRetFte),0,nRetFte)
	nRetIva = IIF (EMPTY(nRetIva),0,nRetIva)
	

	nImporte = nEF +  nRetFte + nRetIva 
	
	nRecibo = nImporte 
	IF nTipoPago=8 OR nTipoPago=9
		nRecibo = this.nTotalFact
	ENDIF

	IF this.nTotalFact>0
		this.Recibos(this.nTotalFact)
	ENDIF
	
	
	IF nImporte > 0
	
		this.IdReceiv	= oApp.newid('RECEIV',14,.t.)

		oApp.t_clear()
		
		oApp.t_set('Id'       		,this.idreceiv)	
		oApp.t_set('numero'   		,this.numerorecibo)
		oApp.t_set('date'      		,this.dFecha)
		oApp.t_set('Importe'   		,nImporte)
		oApp.t_set('iduser'    		,this.cIdUser)
		oApp.t_set('Moneda'    		,this.moneda)
		oApp.t_set('TipoCambio'		,this.tipocambio)
		oApp.t_set('frc'      		,this.dFecha)
		oApp.t_set('idcustomer'		,this.cIdCust)
		oApp.t_set('idsalesman'		,this.cIdSalesman)
		oApp.t_set('idrecpda'		,'') && guarda las recaudaciones que se hace desde el poket (tabla recaudaciones)
		oApp.t_set('idRecibos' 		,this.idRecibos)
		oApp.t_set('idCPIngreso'	,'')
		oApp.t_set('idbookentry'	,'')	
		oApp.t_set('cxc'       		,0) && 0-> Se registra 0 cuando se cancela desde una factura de venta; 1 Cuando se cancela una cuota desde cxc

		oApp.t_insert('RECEIV')

		IF !EMPTY(this.cNota)
			oApp.t_clear()
			oApp.t_set('Id'		,this.idreceiv)	
			oApp.t_set('Note'	,this.cNota)
			oApp.t_insert('RECEIVAUX')
		ENDIF 
		
				
		oApp.t_clear()
		oApp.t_set('idReceiv'         ,this.IdReceiv,'C')	
		oApp.t_set('IdAccountCusCuota',this.cId_cuota,'C')
		oApp.t_set('IdSalesman'       ,this.cIdSalesman)
		oApp.t_set('SaldoCuota'       ,0)
		oApp.t_set('Importe'          ,nImporte)
		oApp.t_set('Chequeposf'       ,0)  && this.chequeposf
		oApp.t_insert('AuxCxC')
		
		this.DetaReceiv (nEF,'03')
		this.DetaReceiv (nRetFte,'10')
		this.DetaReceiv (nRetIVA,'09')
	ENDIF
	
	nCustodio = this.nTotalFact-nImporte
	IF nTipoPago=8 AND nCustodio>0 &&TC
		this.custodio (nCustodio,'02')
	ENDIF

	IF nTipoPago=9 AND nCustodio>0  &&CH
		this.custodio (nCustodio,'01')
	ENDIF
	
ENDPROC 


PROCEDURE DetaReceiv (nMonto,cTipo)

	IF nMonto>0

		cId0 = oApp.newid('DETARECEIV',14,.t.)

		oApp.t_clear()
						
		oApp.t_set('Id'					,this.idreceiv)
		oApp.t_set('Id0'				,cId0) && Secuencial intero 	
		oApp.t_set('idinst'				,this.cIdinst)
		oApp.t_set('idaccountypeorig'	,cTipo)
		oApp.t_set('idchequespos'		,this.idchequespos)
		oApp.t_set('Monto'				,nMonto)
		oApp.t_set('Montooriginal'		,nMonto)
		oApp.t_set('Descuento'			,0)
		oApp.t_set('recargo'			,0)
		oApp.t_set('anticipoutilizado'	,0)
		oApp.t_set('idinvoice'			,this.cIdInvoice)
		oApp.t_set('idaccountcuscuota'	,this.cId_Cuota)
		oApp.t_set('Moneda'				,this.MonedaDoc)
		oApp.t_set('TipoCambio'			,this.TipoCambioDoc)
		oApp.t_set('codeRetFte'			,'')
		oApp.t_set('codeRetIVA'			,'')	
		oApp.t_set('frc'      			,this.dFecha)
		oApp.t_set('MontoDoc'			,nMonto)
		oApp.t_set('idaccountbank'		,'')
		oApp.t_set('TipoCambioDeuda'	,this.TipoCambioDoc)
		oApp.t_set('idzona'				,this.cIdzona)
		oApp.t_set('idcc'				,this.cIdcc)
		oApp.t_set('idcp'				,this.cIdcp)
		oApp.t_set('titular'			,this.titular)	
		oApp.t_set('idaccountype'		,cTipo)
		oApp.t_set('ValorCheque'		,nMonto)
		oApp.t_set('idbank'				,this.Idbank)
		oApp.t_set('cuenta'				,this.cuenta)
		oApp.t_set('numero'				,this.numdoc)

		oApp.t_insert('DETARECEIV')
		
		this.Restar_saldo (nMonto)


	ENDIF
	
ENDPROC 


FUNCTION Recibos(nImporte)

	cYear = PADL(YEAR(this.dFecha),4,'0')
	cSec  = oApp.newSeq('RECIBOS',6,'YEAR',cYear,'SECUENCIA',.t.)
		
	this.idRecibos = oApp.newid('RECIBOS',14,.t.)
	
	oApp.t_clear()
	oApp.t_set('Id'			,this.idRecibos)
	oApp.t_set('secuencia'	,cSec)
	oApp.t_set('Year'		,cYear)
	oApp.t_set('date'      	,this.dFecha)
	oApp.t_set('Importe'	,nImporte)
	oApp.t_set('idcustomer'	,this.cIdCust)
	oApp.t_set('idsalesman'	,this.cIdSalesman)
	oApp.t_set('numero'    	,this.numerorecibo)
	oApp.t_set('iduser'    	,this.cIdUser)
	oApp.t_set('TipoRecibo' ,0) && 0 ->proviene de una pago en cxc, 1 ->proviene de una cuota inicial
	oApp.t_set('Nota'       ,this.cNota)
	oApp.t_set('Moneda'    	,this.moneda)
	oApp.t_set('TIPOCAMBIO' ,this.tipocambio)
	oApp.t_insert('RECIBOS')
	

ENDFUNC


PROCEDURE Custodio (nMonto, cTipo)
	

	IF nMonto<=0
		return
	ENDIF
	
	
	this.idchequespos = oApp.newid('CHEQUESPOSF',14,.t.)

	oApp.t_clear()
	oApp.t_set('id',this.idchequespos)	
	oApp.t_set('idreceiv',this.idreceiv)
	oApp.t_set('idrecibos',this.idRecibos) && Numero de recibo, por el pago realizado
	oApp.t_set('iduser',this.cIdUser)
	oApp.t_set('idcustomer',this.cIdCust)
	oApp.t_set('IdAccountype',cTipo)
	oApp.t_set('Monto',nMonto)
	oApp.t_set('Date',this.dFecha)
	oApp.t_set('Due',this.dVenc)
	oApp.t_set('IdBank',this.idBank)
	oApp.t_set('Cuenta',this.cuenta)
	oApp.t_set('Numero',this.numdoc)
	oApp.t_set('Titular',this.titular)
	oApp.t_set('idsalesman',this.cIdSalesman)
	oApp.t_set('moneda',this.Moneda)
	oApp.t_set('tipocambio',this.tipocambio)
	oApp.t_set('tipocambiodeuda',this.tipocambio)
	oApp.t_set('montodoc',nMonto)
	oApp.t_set('isinvoice',1) && 0=cheque de cxc;  1=cheque en ventas;  2=cheque por un anticipo
	oApp.t_set('idanticipo',this.idanticipo)
	oApp.t_set('cuotainicial', 0) && 1 cuando es una venta a credito y se dio un alcance con cheque
	oApp.t_set('posfechado', IIF(this.dVenc>this.dFecha,1,0)) && 1: cuand es cheque posfechado; 0 cheque a la vista
	oApp.t_insert('CHEQUESPOSF')
	
	oApp.t_clear()
	oApp.t_set('id',this.idchequespos)	
	oApp.t_set('Valororiginal',nMonto)
	oApp.t_set('Valor',nMonto)	
	oApp.t_set('idinvoice',this.cIdInvoice)
	oApp.t_set('idaccountcuscuota',this.cId_Cuota)
	oApp.t_set('idinst',this.cIdInst)
	oApp.t_set('idzona',this.cIdZona)
	oApp.t_set('idcc',this.cIdCC)
	oApp.t_set('idcp',this.cIdCP)
	
	oApp.t_insert('DETALLECHEQUESPOSF')
	
	*this.Restar_saldo (nMonto)
ENDPROC 

PROCEDURE Restar_saldo 
PARAMETERS nValor

	cCmd = 'SELECT balance FROM Invoice WHERE id="'+this.cIdInvoice+'"'
	oApp.sqlexec(cCmd,'curSaldo')
	
	IF nValor > curSaldo.balance
		nValor = curSaldo.balance
	ENDIF
	
	cCmd = 'UPDATE Invoice SET balance = balance - ?nValor, cobros = cobros + ?nValor WHERE id="'+this.cIdInvoice+'"'
	oApp.sqlexec(cCmd)
	cCmd = 'UPDATE AccountCus SET balance = balance - ?nValor WHERE id="'+this.cId_CuotaCab+'"'
	oApp.sqlexec(cCmd)
	cCmd = 'UPDATE AccountCusCuota SET balance = balance - ?nValor WHERE id="'+this.cId_Cuota+'"'
	oApp.sqlexec(cCmd)

ENDPROC 

FUNCTION msg_add (cMsg)
	IF EMPTY(this.cIdView)
		WAIT WINDOW cMsg nowait
	ELSE
		cMsg = this.cTitulo + CHR(13)+ cMsg
		oApp.msg_add(this.cIdView, cMsg)
	ENDIF
	
ENDFUNC

ENDDEFINE
