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


CREATE PROCEDURE [dbo].[CP_Cbtes_Fac_Fin] @Id_Trans VARCHAR(20)
AS 

DECLARE @Mensaje			VARCHAR(100),@trans_ND INT
DECLARE @Id_Cond_Pago		INT

BEGIN TRY
	BEGIN TRAN
	SELECT @trans_ND = Id_trans , @Id_Cond_Pago = Id_Cond_Pago  FROM Cbtes WHERE Id_Estado_Cbte = 0 AND Id_Trans = @Id_Trans

	SET @trans_ND = ISNULL(@trans_ND,0)


	IF (@trans_ND = 0)
	BEGIN
	    SET @Mensaje = 'No hay trans de Factura'
		COMMIT
		SELECT	 1099					AS ErrorNumber 
				,0					AS ErrorSeverity  
				,0					AS ErrorState 
				,0					AS ErrorProcedure  
				,0					AS ErrorLine		
				,@Mensaje			AS ErrorMessage
				,@trans_ND			AS Id_Trans		
		RETURN 1
	END
	ELSE
	BEGIN
		PRINT @trans_ND
		IF @Id_Cond_Pago = 1 -- Contado
			BEGIN
			UPDATE Cbtes SET Id_Estado_Cbte = 2,Saldo = 0			WHERE Id_Trans = @trans_ND
			UPDATE Cbtes_Items SET Id_Estado_Cbte = 2				WHERE Id_Trans = @trans_ND
			UPDATE Clientes_CtaCte SET Id_Estado_Cbte = 2,Saldo = 0 WHERE Id_Trans = @trans_ND
			UPDATE Cajas_Mov		SET Id_Estado_Mov_Caja = 2		WHERE Id_Trans = @trans_ND  --en siempre va en completo
			END
		ELSE
			BEGIN
				UPDATE Cbtes SET Id_Estado_Cbte = 1				WHERE Id_Trans = @trans_ND
				UPDATE Cbtes_Items SET Id_Estado_Cbte = 1		WHERE Id_Trans = @trans_ND
				UPDATE Clientes_CtaCte SET Id_Estado_Cbte = 1	WHERE Id_Trans = @trans_ND
			END
	END

	COMMIT

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

END TRY  


BEGIN CATCH  
    EXECUTE usp_GetErrorInfo;  
	ROLLBACK
END CATCH;   
