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


CREATE PROCEDURE dbo.CP_Cbtes_Lotes_Anular 
@pLote			 VARCHAR(20),
@pMotivoAnulacion VARCHAR(1000),
@pId_Usuario	 SMALLINT
AS 
DECLARE @Mensaje				VARCHAR(100)
		,@Usuario				VARCHAR(200)
		,@Flag_Existe_Usuario	SMALLINT



BEGIN TRY
	BEGIN TRAN

	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
		ROLLBACK
		RETURN 1001
	END

	SET @Usuario = ISNULL((SELECT RTRIM(LTRIM(LastName)) +' '+ RTRIM(LTRIM(FirstName))  FROM Seg_User WHERE No = @pId_Usuario),'NO IDENTIFICADO')
	

	SELECT Id_Trans INTO #Trans FROM Cbtes C, Cbtes_Tipos T
		WHERE C.Id_Tipo_Cbte = T.Id_Tipo_Cbte
		AND T.Compromete_Factura IN (1,-1)
		AND C.Lote = @pLote 
		AND C.Id_Estado_Cbte IN (1)
	
	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 '+  @Usuario +
					              CHAR(13) + CHAR(10) +
								  '---'+ 
								  CHAR(13) + CHAR(10) + 
								  LTRIM(RTRIM(C.Observacion))
		FROM Cbtes C, #Trans T
		WHERE T.Id_Trans  = C.id_Trans

	
	
	COMMIT

	SELECT	 0				AS ErrorNumber 
			,0				AS ErrorSeverity  
			,0				AS ErrorState 
			,0				AS ErrorProcedure  
			,0				AS ErrorLine		
			,@Mensaje		AS ErrorMessage
			,(SELECT COUNT(*) FROM #Trans) AS Cant_Cbtes
	RETURN 0		

END TRY
  


BEGIN CATCH  
    EXECUTE usp_GetErrorInfo;  
	ROLLBACK
	RETURN 999
END CATCH;   
