CREATE PROCEDURE DBO.[UpdateForecast] @AccountNumber int, @Date char(8), @Amount Money, @HotelCustomerNumber INT, @AFK_ExDepartment SMALLINT, @AReferenceNumber INT = -1 AS
/*
  Changes: 
    KJ 20120112: Ext: Removed unwanted print.
    KJ 20110810: Ext: Added ReferenceNumber to the ForecastDaily table. Req #984
    KJ 20100607: Only raise errer when Budget per department
    KJ 20100503: Bug: Fix for "Only raise error if BookkeepingPerHotel"
    KJ 20100212: Ext: Raise error if wrong department
    KJ 20090810: Ext: Added @FK_ExDepartment Req# 348
    KJ 20080505: Bug: Fix for "@Date sometimes NULL"
    KJ 20070223: Fix for 'negative amount never posted'
    KJ 20070201: Fix for "Can not insert the value NULL into AccountNumber"
*/

if ISNULL(@AccountNumber, 0) > 0 and ISNULL(@Amount, 0) <> 0 AND ISNULL(@Date, '') <> ''
BEGIN
  DECLARE @DepHotelCustomerNumber INT
  
  SELECT @DepHotelCustomerNumber = CustomerNumber FROM Customer WITH (NOLOCK) 
  INNER JOIN Departments WITH (NOLOCK) ON Departments.HotelNumber = Customer.HotelNumber
    AND PK_Department = @AFK_ExDepartment


  IF @DepHotelCustomerNumber <> @HotelCustomerNumber
  BEGIN
    DECLARE @BookkeepingPerHotel BIT
    SELECT @BookkeepingPerHotel = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'BookkeepingPerHotel'
    DECLARE @BudgetPerDepartment BIT
    SELECT @BudgetPerDepartment = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'EnableBudgetPerDepartment'

    IF @BookkeepingPerHotel = 1 AND @BudgetPerDepartment = 1 
    BEGIN
      DECLARE @s VARCHAR(500)
      SET @s = 'Illegal Department for ref: ' + CONVERT(VARCHAR, @AReferenceNumber) + ' Dep Hotel: ' + CONVERT(VARCHAR, @DepHotelCustomerNumber) + ' Hotel cust: ' + CONVERT(VARCHAR, @HotelCustomerNumber) + ' Department: ' +CONVERT(VARCHAR, @AFK_ExDepartment) + ' Amount: ' + CONVERT(VARCHAR, @Amount)
      RAISERROR(@s, 15, 1)      
    END  
  END

  UPDATE ForecastDaily SET Amount = Amount + @Amount 
  WHERE Date = @Date 
  AND AccountNumber = @AccountNumber 
  AND HotelCustomerNumber = @HotelCustomerNumber 
  AND FK_DepartmentNumber = @AFK_ExDepartment 
  AND ReferenceNumber = @AReferenceNumber
  
  IF @@RowCount = 0 -- Nothing was updated -> insert row!
    INSERT INTO ForecastDaily (AccountNumber, Date, Amount, HotelCustomerNumber, FK_DepartmentNumber, ReferenceNumber) VALUES
    (@AccountNumber, @Date, @Amount, @HotelCustomerNumber, @AFK_ExDepartment, @AReferenceNumber)
END