DROP proc op_anularventa_proc
GO
create proc op_anularventa_proc
--FUNCIONES
--ELIMINAR DOCUMENTO DE INTRAMOV
--MARCAR OP_sALES COMO ANULADO
--MARCAR OP_sALESDET COMO ANULADO
--MARCAR OP_sALEScard COMO ANULADO
--REVERTIR STOCK
--REVERTIR LIMITE CREDITO DEL CLIENTE

@DOCTYPEID      UD_DOCTYPEID,    
@NBRDOCUMENT    UD_CORRELATIVOS, 
@SITEID         UD_IDSITE,
@DOCSTATUS CHAR(2),
@TYPEPAYMENTID UD_TYPEPAYMENTID ,
@custidss ud_codclient,
@montopen ud_monto=0,
@montousd ud_monto=0

as
declare @qty ud_stock
declare @INVTIDSKU ud_idcorporativo
declare @batnbr char(10)
declare @NUMEROPAGOS INT
declare @NUMEROREFERENCIAS INT
declare @CURYID ud_curyid
declare @monedaorigen ud_curyid
declare @TYPEPAYMENTIDREF UD_TYPEPAYMENTID 
declare @stkitem bit
declare @DOCTYPEIDNC UD_DOCTYPEID
declare @DOCTYPEIDND UD_DOCTYPEID

SELECT @DOCTYPEIDND=@DOCTYPEIDND,@DOCTYPEIDNC= DOCTYPEIDNC from op_setup

SET @batnbr = CAST( @NBRDOCUMENT   AS CHAR(10) )

if(@DOCSTATUS='AN')	--SI EL DOCUMENTO YA ESTA ANULADO ABORTAR
BEGIN
	select 2 AS ERROR
	RETURN(2)
END

IF(@TYPEPAYMENTID='06')	--SI EL DOCUMENTO ES DE CREDITO 
BEGIN
	--saber si el documento tiene pagos parciales o totales
	SET @NUMEROPAGOS =(select count(*) from ar_ccdocdet 
				WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID and DOCSTATUSID<>'AN' )

	IF(@NUMEROPAGOS>0)
	BEGIN
		select 3 AS ERROR
		RETURN(3)	--TIENE PAGOS PARCIALES	
	END

	SET @NUMEROREFERENCIAS =(select count(*) from OP_DOCREFERENCE
				WHERE DOCTYPEIDREF = @DOCTYPEID  and NBRDOCUMENTREF=@NBRDOCUMENT and  SITEID=@SITEID)

	IF(@NUMEROREFERENCIAS >0)
	BEGIN
		select 4 AS ERROR
		RETURN(4)	--TIENE REFERENCIAS NOTAS DE CREDITO O DEBITO
	END

END

begin tran
--declarar cursor para recorrer el detalle de los movimientos
declare CURSORDETALLEVENTA CURSOR for 
			select INVTIDSKU,qty,stkitem
			from op_salesdet 
			WHERE DOCTYPEID = @DOCTYPEID  and NBRDOCUMENT = @NBRDOCUMENT and  SITEID=@SITEID 


OPEN CURSORDETALLEVENTA 

FETCH NEXT FROM CURSORDETALLEVENTA 
	INTO @INVTIDSKU,@QTY,@stkitem

--recorrer el detalle de tarjetas'
WHILE @@FETCH_STATUS = 0
BEGIN
	--------------------------------------------------------------------------------------------------
	--SE APLICA IGUAL SI ES ANULACION O ELIMINACION
	--PERO SI EL DOCUMENTO YA ESTA ANULADO NO SE HACE

	--revertir stock si el producto es inventariable
	if( @stkitem=1)		--si es producto inventariable	
	begin

		IF( @DOCTYPEIDNC =@DOCTYPEID )	--SI EL DOCUMENTO ES UNA NOTA DE CREDITO DISMINUIR STOCK
			UPDATE IN_INVENTORYDAT SET QTYAVAIL=QTYAVAIL - @QTY  		
		          WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
		ELSE
			UPDATE IN_INVENTORYDAT SET QTYAVAIL=QTYAVAIL + @QTY  		
		          WHERE SITEID=@SITEID AND INVTIDSKU=@INVTIDSKU 
	          				
		IF (@@ERROR!=0)
		BEGIN   
			CLOSE CURSORDETALLEVENTA
			DEALLOCATE CURSORDETALLEVENTA
		        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al actualizar stock'
	        	ROLLBACK TRAN
			select 1 AS ERROR
			RETURN(1)  
		END 
	end	--fin del si es producto inventariable

	FETCH NEXT FROM CURSORDETALLEVENTA 
	INTO @INVTIDSKU,@QTY,@stkitem

END -- FIN DEL BUCLE DEL CURSOR

CLOSE CURSORDETALLEVENTA
DEALLOCATE CURSORDETALLEVENTA

--------------------------------------------------------------------------------------------------
--borrar de intramov
delete intramov 
	WHERE DOCTYPEID = @DOCTYPEID  and REFNBR = @NBRDOCUMENT and  SITEID=@SITEID
IF (@@ERROR!=0)
BEGIN   
	CLOSE CURSORDETALLEVENTA
	DEALLOCATE CURSORDETALLEVENTA
        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al actualizar intramov'
       	ROLLBACK TRAN
	select 1 AS ERROR
	RETURN(1)  
END 
--------------------------------------------------------------------------------------------------
--si la accion es anular se marca como AN
update op_salesdet 
	SET DOCSTATUSID='AN'
	WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID 

IF (@@ERROR!=0)
BEGIN   
        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al anular Detalle de Venta'
       	ROLLBACK TRAN
	select 1 AS ERROR
	RETURN(1)  
END 

--------------------------------------------------------------------------------------------------
update op_sales
	SET DOCSTATUSID='AN'
	WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID

IF (@@ERROR!=0)
BEGIN   
        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al anular venta Venta'
       	ROLLBACK TRAN
	select 1 AS ERROR
	RETURN(1)  
END 
--------------------------------------------------------------------------------------------------
--SI ES NOTA DE CREDITO O NOTA DE DEBITO ELIMINAR LAS REFERENCIAAS
IF( @DOCTYPEIDNC =@DOCTYPEID or @DOCTYPEIDND =@DOCTYPEID ) --SI EL DOCUMENTO ES UNA NOTA DE CREDITO o nota de debito
begin
	SET @TYPEPAYMENTIDREF=( SELECT TOP 1 TYPEPAYMENTIDREF FROM OP_DOCREFERENCE 
		WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID )

	DELETE OP_DOCREFERENCE 
		WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID

	IF (@@ERROR!=0)
	BEGIN   
	        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al eliminar referencias del documento'
	       	ROLLBACK TRAN
		select 1 AS ERROR
		RETURN(1)  
	END 

end

-------SI EL DOCUMENTO ES DE CREDITO o es nota de credito y el documento de referencia es de credito
IF(@TYPEPAYMENTID='06' OR (@TYPEPAYMENTIDREF='06' AND ( @DOCTYPEIDNC =@DOCTYPEID or @DOCTYPEIDND =@DOCTYPEID)))	
BEGIN
	--borrar cuenta corriente
	set @CURYID = (select CURYID from customer where custidss=@custidss)
	set @monedaorigen =(select CURYORIG from setup)

	delete ar_ccdoc
		WHERE DOCTYPEID = @DOCTYPEID  and @NBRDOCUMENT=NBRDOCUMENT and  SITEID=@SITEID 

	IF (@@ERROR!=0)
	BEGIN   
	        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al anular cta.cte.'
	       	ROLLBACK TRAN
		select 1 AS ERROR
		RETURN(1)  
	END 

	if( @DOCTYPEIDNC =@DOCTYPEID )	--si el nota de credito aumentar limite
		begin
			if(@monedaorigen=@CURYID )
				UPDATE OP_CUST_LIMIT SET CURRBAL = CURRBAL + @montopen WHERE custidss = @custidss 
			else
				UPDATE OP_CUST_LIMIT SET CURRBAL = CURRBAL + @montousd WHERE custidss = @custidss 
			end
	else
		begin
			if(@monedaorigen=@CURYID )
				UPDATE OP_CUST_LIMIT SET CURRBAL = CURRBAL - @montopen WHERE custidss = @custidss 
			else
				UPDATE OP_CUST_LIMIT SET CURRBAL = CURRBAL - @montousd WHERE custidss = @custidss 
		end

	IF (@@ERROR!=0)
	BEGIN   
	        RAISERROR  20000 'OP_GRABARVENTASCTORE: Error al anular cta.cte.'
	       	ROLLBACK TRAN
		select 1 AS ERROR
		RETURN(1)  
	END 
END

COMMIT TRAN   
select 0 AS ERROR
RETURN (0)  
go

