IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'CPJ_Cbtes_Rec_Anular') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE CPJ_Cbtes_Rec_Anular
END
GO

CREATE PROCEDURE [dbo].[CPJ_Cbtes_Rec_Anular] @pJson VARCHAR(8000)

AS
SET NOCOUNT ON
/*
 * LOG VERSIONES:
 * 04/12/2023: Se agrego Log de Versiones
*/

/*Declaracion Variables Json*/
DECLARE @pFlagUsarTrans			TINYINT
DECLARE @pModoDebug				TINYINT
DECLARE @pId_Trans				INT
DECLARE @pMotivoAnulacion		VARCHAR(1000)
DECLARE @pId_Usuario			SMALLINT

SET @pFlagUsarTrans				= ISNULL(CONVERT(TINYINT, dbo.CF_JSON_VALUE(@pJson,'FlagUsarTrans')), 0)
SET @pModoDebug					= ISNULL(CONVERT(TINYINT, dbo.CF_JSON_VALUE(@pJson,'ModoDebug')), 0)
SET @pId_Trans					= ISNULL(CONVERT(INT, dbo.CF_JSON_VALUE(@pJson,'Id_Trans')), 0)
SET @pMotivoAnulacion			= ISNULL(CONVERT(VARCHAR(1000), dbo.CF_JSON_VALUE(@pJson,'MotivoAnulacion')), '')
SET @pId_Usuario				= ISNULL(CONVERT(SMALLINT, dbo.CF_JSON_VALUE(@pJson,'Id_Usuario')), 0)
/*Fin Declaracion Variables Json*/

/*Variable de Retorno del Stored*/
DECLARE @rtaErrorStored			INT
DECLARE @rtaMsjStored			VARCHAR(4000)
/*FIN Variable de Retorono del Stored*/

/*Declaracion Variables Locales*/
DECLARE @Flag_Existe_Usuario	TINYINT
DECLARE @Mensaje				VARCHAR(100)
/*Fin de Declaraciones Variables Locales */

BEGIN TRY
	
	IF (@pFlagUsarTrans <> 0 )
	BEGIN
		BEGIN TRAN
	END

	/*===================================================================================================================================================================*/	

	IF (@pModoDebug = 1)
	BEGIN
		PRINT 'Ingreso a Stored Procedure: CPJ_Cbtes_Rec_Anular'
		PRINT 'Parametros:'	
		PRINT 'FlagUsarTrans: ' + CONVERT(VARCHAR(10), @pFlagUsarTrans) + ' Id_Trans: ' + CONVERT(VARCHAR(10), @pId_Trans)
	END
	
	/*===================================================================================================================================================================*/

	IF(@pId_Trans = 0)
	BEGIN
		SET @rtaErrorStored = 70001 /*Transaccion no abierta*/
		
		SELECT	 @rtaErrorStored	AS ErrorNumber 
				,0					AS ErrorSeverity  
				,0					AS ErrorState 
				,0					AS ErrorProcedure  
				,0					AS ErrorLine		
				,''					AS ErrorMessage
			
		IF (@pFlagUsarTrans <> 0)
		BEGIN
			ROLLBACK
		END
		
		RETURN 9999
	END

	/*===================================================================================================================================================================*/

	SET @Flag_Existe_Usuario = ISNULL((SELECT 1 FROM Seg_User WHERE No = @pId_Usuario), 0)
	IF (@Flag_Existe_Usuario = 0)
	BEGIN

		SET @Mensaje = 'No existe el usuario '

		SELECT		1001			AS ErrorNumber 
					,0				AS ErrorSeverity  
					,0				AS ErrorState 
					,0				AS ErrorProcedure  
					,0				AS ErrorLine		
					,@Mensaje		AS ErrorMessage
					,0				AS Id_Trans

		IF (@pFlagUsarTrans <> 0)
		BEGIN
			ROLLBACK
		END

		RETURN 1001
	END

	/*===================================================================================================================================================================*/

	SELECT Id_Trans INTO #Trans FROM Cbtes C, Cbtes_Tipos T
		WHERE C.Id_Tipo_Cbte = T.Id_Tipo_Cbte
		AND T.Compromete_Recibos IN (1,-1)
		AND C.Id_Trans = @pId_Trans

	UPDATE Valores SET Id_Estado_Valor = 1
		FROM Valores V, #Trans T
		WHERE T.Id_Trans  = V.Id_Trans

	UPDATE Valores_Mov SET Id_Estado_Valor = 1
		FROM Valores_Mov V, #Trans T
		WHERE T.Id_Trans  = V.Id_Trans

	UPDATE Cajas_Mov SET Id_Estado_Mov_Caja = 1
		FROM Cajas_Mov C, #Trans T
		WHERE T.Id_Trans  = C.Id_Trans
	
	UPDATE Clientes_CtaCte SET Id_Estado_Cbte = 3 
		FROM Clientes_CtaCte C, #Trans T
		WHERE T.Id_Trans  = C.Id_Trans

	UPDATE Cbtes_Items SET Id_Estado_Cbte = 3 
		FROM Cbtes_Items C, #Trans T
		WHERE T.Id_Trans  = C.Id_Trans

	UPDATE Cbtes SET Id_Estado_Cbte = 3
					,Imp_Neto = 0
					,Imp_DescEspecial  = 0
					,Imp_DescFin  = 0
					,Imp_Bonificacion  = 0
					,Imp_Gravado  = 0
					,Imp_Exento  = 0
					,Imp_IVA  = 0
					,Imp_IVA2  = 0
					,Imp_Percepcion_IB  = 0
					,Imp_Percepcion_Iva  = 0
					,Imp_Total  = 0
					,Imp_Gravado2  = 0
					,Imp_Gravado3  = 0
					,Imp_NoGravado  = 0
					,Imp_IVA3  = 0
					,Imp_Percep  = 0
					,Saldo  = 0
					,Saldo_Iva_Recup  = 0
					,Observacion = LTRIM(RTRIM(@pMotivoAnulacion)) + 
					              CHAR(13) + CHAR(10) +
								  'Anulado por '+  CONVERT(VARCHAR(10),@pId_Usuario) +
					              CHAR(13) + CHAR(10) +
								  '---'+ 
								  CHAR(13) + CHAR(10) + 
								  LTRIM(RTRIM(CONVERT(VARCHAR(MAX),C.Observacion)))
		FROM Cbtes C, #Trans T
		WHERE T.Id_Trans  = C.Id_Trans


	IF (@pFlagUsarTrans <> 0)
	BEGIN
		COMMIT
	END

		SET @rtaMsjStored	=	'{' +
								dbo.CF_Json_ParsearVariable('id_trans', @pId_Trans, 'INT') +
								'}'

		SELECT	 0				AS ErrorNumber 
				,0				AS ErrorSeverity  
				,0				AS ErrorState 
				,0				AS ErrorProcedure  
				,0				AS ErrorLine		
				,@rtaMsjStored	AS ErrorMessage

	IF(@pModoDebug = 1)
	BEGIN
		PRINT 'Fin Stored Procedure: CPJ_Cbtes_Rec_Anular'
	END

END TRY  


BEGIN CATCH  
    EXECUTE usp_GetErrorInfo

	IF (@pFlagUsarTrans <> 0 )
	BEGIN
		ROLLBACK
	END

	RETURN 9999
END CATCH

RETURN 0 