CREATE FUNCTION dbo.GetFolioBalance (@FolioNumber INT)
RETURNS FLOAT
AS
/*
    KJ 20080506: Changed @Total to datatype float.
    NB20060118: MovedDeleted added to reduce the error possibility
    NB20051102: Created

    Parameters: @FolioNumber to calculate balance on
    Notes:
*/
BEGIN
  DECLARE @Total FLOAT

  SELECT @Total = SUM(T.PriceOverwrite 
  * CASE WHEN (A.AccountType IN (4, 9)) THEN -1 ELSE 1 END 
  * CASE WHEN (T.Debit = 0) THEN -1 ELSE 1 END 
  --nb20180905 CR150714 Added: fee transaction calculation
  --* CASE WHEN WG.Payment=4 and W.SortNumber=4 THEN -1 ELSE 1 END
  --nb20180905 CR151901 Reverted: debit flag is wrong on fee transaction.
  ) 
  FROM Transactions T WITH (NOLOCK) 
    INNER JOIN Accounts A WITH (NOLOCK) ON A.AccountNumber = T.AccountNumber
	INNER JOIN Ware W WITH (NOLOCK) ON W.WareNumber= T.WareNumber 
	INNER JOIN Waregroups WG WITH (NOLOCK) ON WG.WaregroupNumber= W.WaregroupNumber 
  WHERE FolioNumber= @FolioNumber AND ShowOnBillFlag=1 AND MovedDeleted=0
  IF @Total < 0.001 AND @Total > -0.001 
    SET @Total = 0

  RETURN @Total
END

