CREATE PROCEDURE dbo.BalanceEconomyExtGet @AHotelCustomerNumber INT, @AType INT AS
SET NOCOUNT ON

/*
  Created by Kent Johansen, november 2012
  Changes:
    KJ 20191129: Bug: Fix for "Folios is shown even if amount is "almost" 0". Case #CR173634
  
*/

CREATE TABLE #tab
(
  FolioNumber INT,
  AllAmount MONEY,
  DepositAmount MONEY,
  InhouseAmount MONEY
)

INSERT INTO #tab EXEC BalanceEconomyExt @AHotelCustomerNumber

IF @AType = 0
BEGIN
  -- list of inhouse debtors
  SELECT #tab.FolioNumber, 
  CASE WHEN (ISNULL(#tab.AllAmount, 0) - ISNULL(#tab.DepositAmount, 0) <> 0) THEN 
    (ISNULL(#tab.AllAmount, 0) - ISNULL(#tab.DepositAmount, 0))
  ELSE 
    #tab.InhouseAmount END AS DebtorAmount, 
  ReservationAddress.LastName + CASE WHEN ReservationAddress.FirstName = '' THEN '' ELSE ', ' + ReservationAddress.FirstName END AS FullName
  FROM #tab
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = #tab.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  WHERE (ROUND(ISNULL(#tab.AllAmount, 0) - ISNULL(#tab.DepositAmount, 0), 2) <> 0) OR (ROUND(ISNULL(#tab.InhouseAmount, 0), 2) <> 0)
END
ELSE IF @AType = 1
BEGIN
  -- List of folios with diff
  SELECT #tab.FolioNumber, #tab.AllAmount-#tab.DepositAmount AS DebtorAmount, #tab.InhouseAmount,
  ReservationAddress.LastName + CASE WHEN ReservationAddress.FirstName = '' THEN '' ELSE ', ' + ReservationAddress.FirstName END AS FullName
  FROM #tab
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = #tab.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  WHERE ISNULL(AllAmount, 0) - ISNULL(DepositAmount, 0) <> ISNULL(InhouseAmount, 0)
/*
  SELECT #tab.FolioNumber, #tab.AllAmount-#tab.DepositAmount AS DebtorAmount, #tab.InhouseAmount,
  ReservationAddress.LastName + CASE WHEN ReservationAddress.FirstName = '' THEN '' ELSE ', ' + ReservationAddress.FirstName END AS FullName
  FROM #tab
  INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = #tab.FolioNumber
  LEFT OUTER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = Folios.ReservationAddressNumber
  WHERE 
  (
    (DepositAmount IS NOT NULL AND AllAmount <> DepositAmount) OR
    (InhouseAmount IS NOT NULL AND AllAmount <> InhouseAmount)
  )
*/
END

DROP TABLE #tab