DROP PROCEDURE OP_CTRLFUELPRICEInsProc
GO
CREATE PROCEDURE OP_CTRLFUELPRICEInsProc
(	@CORRNBR	INT,
	@USERID		UD_USERID,
	@SITEID	UD_IDSITE,
  	@DATEPROCE	UD_FECHA 
)
AS
BEGIN
	BEGIN TRAN

	DECLARE @MONEDABASE UD_CURYID

	DECLARE @CATEGORYFUEL UD_CATEGORY
	
	SET @MONEDABASE=(SELECT CURYORIG FROM SETUP)
	SET @CATEGORYFUEL=(SELECT CATEGORYFUEL FROM OP_SETUP)
	
	-- SI EXISTE EL REGISTRO LO ELININO
	IF (EXISTS(SELECT * FROM OP_CTRLFUELPRICE WHERE DATEPROCE=@DATEPROCE AND SITEID=@SITEID ))
	BEGIN
		DELETE FROM OP_CTRLFUELPRICE WHERE DATEPROCE=@DATEPROCE AND SITEID=@SITEID

		IF(@@ERROR!=0 OR @@ROWCOUNT=0)
		BEGIN
			ROLLBACK
			RAISERROR 20000 'Error eliminando en OP_CTRLFUELPRICE'
			RETURN(1)
		END

		DELETE FROM OP_CTRLFUELPRICESALES WHERE DATEPROCE=@DATEPROCE AND SITEID=@SITEID

		IF(@@ERROR!=0 OR @@ROWCOUNT=0)
		BEGIN
			ROLLBACK
			RAISERROR 20000 'Error eliminando en OP_CTRLFUELPRICESALES'
			RETURN(1)
		END
 

	END 	

	INSERT INTO OP_CTRLFUELPRICE(SITEID,DATEPROCE,INVTIDSKU,SLS_PRICE,CURYID,QTY,STATUS,USERID,TOTALPEN)
	SELECT  SITEID,DATEPROCE,INVTIDSKU,SLS_PRICE,CURYID,QTYSALES,0,@USERID,TOTAL FROM TMP_OP_CTRLFUELPRICE
	WHERE 	CORRNBR=@CORRNBR
	
	IF(@@ERROR!=0 OR @@ROWCOUNT=0)
	BEGIN
		ROLLBACK
		RAISERROR 20000 'Error Insentando Ventas segun gasboy'
		RETURN(1)
	END 

	INSERT INTO OP_CTRLFUELPRICESALES(SITEID,DATEPROCE,INVTIDSKU,SLS_PRICESALES,CURYID,QTYSALES,STATUS,TOTALPENSALES,USERID)
	SELECT S.SITEID,@DATEPROCE,S.INVTIDSKU AS CODIGO,S.SLSPRICESALE AS Precio_Gal,@MONEDABASE,SUM(S.QTY) AS Gal_Vendidos,0,SUM(S.TOTALPEN) AS Monto,@USERID FROM OP_SALESDET AS S JOIN IN_INVENTORY AS A
	ON S.INVTIDSKU=A.INVTIDSKU
	WHERE A.CLASSID=@CATEGORYFUEL AND SITEID=@SITEID AND DATEPROCESALES=@DATEPROCE AND S.DOCSTATUSID<>'AN'
	GROUP BY S.SITEID,S.INVTIDSKU,A.DESCR,S.SLSPRICESALE

	IF(@@ERROR!=0 OR @@ROWCOUNT=0)
	BEGIN
		ROLLBACK
		RAISERROR 20000 'Error Insentando en Ventas de Combustible'
		RETURN(1)
	END 

	COMMIT TRAN
	RETURN(0)
END


