ALTER FUNCTION [App].[Fn_IsReceiptRequired] 
(
	@ApplicationRequestDetailID BIGINT,
	@ApplicationRequestTypeID INT

)
RETURNS BIT
AS
BEGIN

	DECLARE @IsRequired BIT = 0
	DECLARE @OriginalReceiptCost MONEY
	DECLARE @CorrectReceiptCost MONEY
	DECLARE @NewReceiptCost MONEY
	DECLARE @OldApplicationTypeID BIGINT

	SELECT @CorrectReceiptCost = App.Fn_GetReceiptCost(@ApplicationRequestDetailID, @ApplicationRequestTypeID,Ard.IsRenewal,Ard.IsLtpsConversion,Ard.VehicleCount)
	FROM App.ApplicationRequestDetails Ard
	WHERE ApplicationRequestDetailID = @ApplicationRequestDetailID
	
	SELECT @OriginalReceiptCost = 
	(
		SELECT SUM(Rd.TotalCost)
		FROM App.ReceiptDetails Rd
		WHERE Rd.ApplicationRequestDetailID = @ApplicationRequestDetailID
	)
	FROM App.ApplicationRequestDetails Ard
	INNER JOIN App.ApplicationApplicantDetails Aad ON Aad.ApplicationRequestDetailID = Ard.ApplicationRequestDetailID
	WHERE Ard.ApplicationRequestDetailID = @ApplicationRequestDetailID

	SET @OriginalReceiptCost = ISNULL(@OriginalReceiptCost, 0 ) 

	--change as per SUP4549. Allowing all apps to be receipted again
	--IF @ApplicationRequestTypeID NOT IN (12) AND @ApplicationRequestDetailID > 96906 AND @CorrectReceiptCost > @OriginalReceiptCost
	IF @ApplicationRequestTypeID NOT IN (12) AND @CorrectReceiptCost > @OriginalReceiptCost
	BEGIN
		SET @IsRequired = 1
    END
	ELSE
	BEGIN
		--forcing Cov applications that are R0 due to ZN change to go to payment step for a R0 invoice
		IF 
			@CorrectReceiptCost = 0.0
			AND App.Fn_IsCovType(@ApplicationRequestTypeID) = 1
			AND NOT EXISTS(SELECT * FROM App.ReceiptDetails WHERE ApplicationRequestDetailID = @ApplicationRequestDetailID)
		BEGIN			
			SET @IsRequired = 1
		END
		ELSE
		BEGIN
			SET @IsRequired = 0
		END
	END 

	RETURN @IsRequired
END



