CREATE PROCEDURE DBO.OwnerGetPaymentTotal @ARoomNumber INT, @AStartDateTime DateTime, @AEndDateTime DateTime, @AHotelNumber INT = -1, @ATotal MONEY OUTPUT, @AOnlyPayment BIT = 1 AS
SET NOCOUNT ON

/*
  Created by Kent Johansen January 2007
    Returns the total amount of owner payments

  Changes:
    KJ 20090902: Ext: case #400. Owner calculation to Vigsų
    KJ 20070530: Added HotelNumber as input param

*/
IF (ISNULL(@ARoomNumber, 0) > 0)
BEGIN
  DECLARE @CreditorWareNumber INT
  DECLARE @CustomerNumber INT
  DECLARE @HotelCustomerNumber INT

  IF @AOnlyPayment = 1
  BEGIN
    SELECT @CreditorWareNumber = WareNumber FROM Ware WITH (NOLOCK) WHERE Payment = 14 -- ptCreditor

    SELECT @CustomerNumber = CustomerNumber FROM Rooms WITH (NOLOCK) WHERE Number = @ARoomNumber AND ((@AHotelNumber = -1) OR (HotelNumber = @AHotelNumber))

    SELECT @HotelCustomerNumber = CustomerNumber FROM Customer WITH (NOLOCK) WHERE CustomerTypeNumber=7 AND HotelNumber = @AHotelNumber
    IF ISNULL(@HotelCustomerNumber, -1) = -1 SET @HotelCustomerNumber = -1

    IF ISNULL(@CreditorWareNumber, 0) > 0
    BEGIN
      SELECT @ATotal = SUM(t.PriceOverwrite * (CASE t.Debit WHEN 1 THEN 1 ELSE -1 END)*CASE WHEN a.AccountType IN (4,5,6) THEN 1 ELSE 1+(VatValue/100) END)
      FROM Transactions t WITH (NOLOCK) 
      INNER JOIN Folios f WITH (NOLOCK) ON f.FolioNumber = t.FolioNumber
      INNER JOIN ReservationAddress ra WITH (NOLOCK) ON ra.AddressNumber = f.ReservationAddressNumber AND Link = @CustomerNumber
      INNER JOIN Accounts a WITH (NOLOCK) ON a.AccountNumber = t.AccountNumber
      WHERE WareNumber = @CreditorWareNumber
      AND ShowOnBillFlag = 1
      AND CONVERT(CHAR(8), DateStamp, 112) >= CONVERT(CHAR(8), @AStartDateTime, 112)
      AND CONVERT(CHAR(8), DateStamp, 112) <= CONVERT(CHAR(8), @AEndDateTime, 112)
      AND t.HotelCustomerNumber = @HotelCustomerNumber
    END
  END
  ELSE
  BEGIN
    SELECT @ATotal = SUM(t.PriceOverwrite * (CASE t.Debit WHEN 1 THEN 1 ELSE -1 END)*CASE WHEN a.AccountType IN (4,5,6) THEN 1 ELSE 1+(VatValue/100) END)
    FROM Transactions t WITH (NOLOCK) 
    INNER JOIN Folios f WITH (NOLOCK) ON f.FolioNumber = t.FolioNumber
    INNER JOIN ReservationAddress ra WITH (NOLOCK) ON ra.AddressNumber = f.ReservationAddressNumber AND Link = @CustomerNumber
    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 wg.Payment = 2 -- System Rooms
    AND ShowOnBillFlag = 1
    AND CONVERT(CHAR(8), DateStamp, 112) >= CONVERT(CHAR(8), @AStartDateTime, 112)
    AND CONVERT(CHAR(8), DateStamp, 112) <= CONVERT(CHAR(8), @AEndDateTime, 112)
    AND t.HotelCustomerNumber = @HotelCustomerNumber
    AND ISNULL(t.ProductWareLinkNumber, 0) = 0
  END

  IF ISNULL(@ATotal, 0) <> 0
    SET @ATotal = @ATotal * -1 
  SET @ATotal = ISNULL(@ATotal,0)
END