DROP proc op_revertirventa_proc
GO
create proc op_revertirventa_proc
@DOCTYPEID      UD_DOCTYPEID,    
@NBRDOCUMENT    UD_CORRELATIVOS, 
@SITEID         UD_IDSITE

as
declare @qty ud_stock
DECLARE @DOCSTATUS CHAR(2)
declare @INVTIDSKU ud_idcorporativo
declare @batnbr char(10)

--declarar cursor para recorrer el detalle de los movimientos
SET @batnbr = CAST( @NBRDOCUMENT   AS CHAR(10) )
SET @DOCSTATUS= (SELECT DOCSTATUSID FROM OP_SALES WHERE DOCTYPEID = @DOCTYPEID  and NBRDOCUMENT = @NBRDOCUMENT and  SITEID=@SITEID )

declare OPDETALLEVENTA CURSOR for 
			select INVTIDSKU
			from op_salesdet 
			WHERE DOCTYPEID = @DOCTYPEID  and NBRDOCUMENT = @NBRDOCUMENT and  SITEID=@SITEID

OPEN OPDETALLEVENTA 

FETCH NEXT FROM OPDETALLEVENTA 
	INTO @QTY

--recorrer el detalle de tarjetas'
WHILE @@FETCH_STATUS = 0
BEGIN
	--------------------------------------------------------------------------------------------------
	--borrar de intramov
	UPDATE IN_INVENTORYDAT SET QTYAVAIL=QTYAVAIL + @QTY  
	          WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
          				
	IF (@@ERROR!=0)
	BEGIN   
		CLOSE OPDETALLEVENTA
		DEALLOCATE OPDETALLEVENTA
	        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al actualizar stock'
        	ROLLBACK TRAN
		RETURN(1)  
	END 


	--------------------------------------------------------------------------------------------------
	--borrar de intramov
	delete intramov 
		WHERE DOCTYPEID = @DOCTYPEID  and batnbr = @NBRDOCUMENT and  SITEID=@SITEID

	IF (@@ERROR!=0)
	BEGIN   
		CLOSE OPDETALLEVENTA
		DEALLOCATE OPDETALLEVENTA
	        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al actualizar intramov'
        	ROLLBACK TRAN
		RETURN(1)  
	END 
	
	FETCH NEXT FROM OPDETALLEVENTA 
	INTO @QTY

END -- FIN DEL BUCLE DEL CURSOS

CLOSE OPDETALLEVENTA
DEALLOCATE OPDETALLEVENTA
--------------------------------------------------------------------------------------------------
--borrar op_salescard
delete op_salescar 
	WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID
IF (@@ERROR!=0)
BEGIN   
        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al eliminar Movimientos de Tarjetas'
       	ROLLBACK TRAN
	RETURN(1)  
END 
--------------------------------------------------------------------------------------------------
--borrar op_salesdet
delete op_salesdet
	WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID 
IF (@@ERROR!=0)
BEGIN   
        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al eliminar Detalle de Venta'
       	ROLLBACK TRAN
	RETURN(1)  
END 
--------------------------------------------------------------------------------------------------
--borrar op_sales
delete op_sales
	WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID

IF (@@ERROR!=0)
BEGIN   
        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al eliminar Venta'
       	ROLLBACK TRAN
	RETURN(1)  
END 

COMMIT TRAN   
RETURN (0)  

go
