IF EXISTS (SELECT * FROM sys.objects  WHERE [type] IN ('FN','P') AND  name = 'CF_Id_Tarjeta_Socio')
	DROP FUNCTION DBO.CF_Id_Tarjeta_Socio
GO


CREATE FUNCTION [dbo].[CF_Cbtes_Id_Tarjeta](@pId_Trans INT)
RETURNS VARCHAR(10)
AS
BEGIN

DECLARE @Id_Tarjeta				VARCHAR(10)
DECLARE @Id_Cond_Pago_Debito	SMALLINT
DECLARE @Id_Cond_Pago			SMALLINT
DECLARE @Id_Contrato			INT
DECLARE @Id_Tarjeta_Cbte		VARCHAR(10)
DECLARE @Id_Tarjeta_Contrato	VARCHAR(10)
DECLARE @Id_Cliente				INT
DECLARE @Id_Tarjeta_Cliente		VARCHAR(10)


SET @Id_Cond_Pago_Debito	= CONVERT(SMALLINT, dbo.CF_xParam('Cond_Pag_Debito'))
SET @Id_Cond_Pago			= ISNULL( (SELECT Id_Cond_Pago FROM Cbtes WHERE Id_Trans = @pId_Trans) ,0)

IF(@Id_Cond_Pago_Debito = @Id_Cond_Pago AND @Id_Cond_Pago != 0 )
BEGIN
	/*Busca directamente en los datos del Cbte*/
	SET @Id_Tarjeta_Cbte = (SELECT ISNULL(Id_Tarjeta, '') FROM Cbtes WHERE Id_Trans = @pId_Trans)
	
	IF(@Id_Tarjeta_Cbte <> '')
	BEGIN
		SET @Id_Tarjeta = @Id_Tarjeta_Cbte
	END
END
ELSE
BEGIN
	/*Tiene que buscar si tiene una tarjeta cargada en el Contrato*/
	SET @Id_Contrato = (SELECT ISNULL(Id_Contrato, 0) FROM Cbtes WHERE Id_Trans = @pId_Trans)

	SET @Id_Tarjeta_Contrato = (SELECT ISNULL(Id_Tarjeta, '') FROM Contratos WHERE Id_Contrato = @Id_Contrato)

	IF(@Id_Tarjeta_Contrato <> '')
	BEGIN
		/*El Contrato tiene un Tipo de Tarjeta cargado*/
		SET @Id_Tarjeta = @Id_Tarjeta_Contrato
	END
	ELSE
	BEGIN
		/*El Contrato NO tiene un Tipo de Tarjeta cargado, tiene que revisar en la ficha del Socio de la cabecera del Cbte*/
		SET @Id_Cliente			= (SELECT ISNULL(Id_Cliente, 0) FROM Cbtes WHERE Id_Trans = @pId_Trans)
		
		IF(@Id_Cliente NOT IN (0, 1))
		BEGIN
			SET @Id_Tarjeta_Cliente = (SELECT ISNULL(Id_Tarjeta, '') FROM Clientes WHERE Id_Cliente = @Id_Cliente)
	
			IF(@Id_Tarjeta_Cliente <> '')
			BEGIN
				SET @Id_Tarjeta = @Id_Tarjeta_Cliente
			END
		END
	END
END

RETURN ISNULL(@Id_Tarjeta, '')
END
