CREATE FUNCTION dbo.GetFolioBalanceCustomer (@FolioNumber INT, @CustomerNumber INT = 0)
RETURNS FLOAT
AS
/*
    NB20060607: HotelCustomerNumber specification
    NB20060118: MovedDeleted added to reduce the error possibility
    NB20051102: Created

    Parameters: @FolioNumber to calculate balance on
    Notes:
*/
BEGIN
DECLARE @Total INT
IF @CustomerNumber > 0
  SELECT @Total = SUM(Transactions.PriceOverwrite * (CASE WHEN (Accounts.AccountType IN (4, 9)) THEN -1 ELSE 1 END)*  (CASE WHEN (Transactions.Debit = 0) THEN -1 ELSE 1 END)) 
  FROM Transactions WITH (NOLOCK) 
    INNER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Transactions.AccountNumber 
  WHERE FolioNumber= @FolioNumber AND ShowOnBillFlag=1 AND MovedDeleted=0 AND HotelCustomerNumber = @CustomerNumber
ELSE
  SELECT @Total = SUM(Transactions.PriceOverwrite * (CASE WHEN (Accounts.AccountType IN (4, 9)) THEN -1 ELSE 1 END)*  (CASE WHEN (Transactions.Debit = 0) THEN -1 ELSE 1 END)) 
  FROM Transactions WITH (NOLOCK) 
    INNER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Transactions.AccountNumber 
  WHERE FolioNumber= @FolioNumber AND ShowOnBillFlag=1 AND MovedDeleted=0
IF @Total < 0.001 AND @Total > -0.001 SET @Total = 0
RETURN @Total
END

