CREATE PROCEDURE OnlineCreateBillAndCheckout @AFolioNumber INT, @AHotelCustomerNumber INT AS
SET NOCOUNT ON
/*
  Created by Nenad Blagojevic july 2012
  Changes:
    20120705: New  
*/

DECLARE --local var 
  @BillNumber INT, 
  @SystemDateStr CHAR(8),
  @SystemDate DATETIME,
  @OnlineUserId INT,
  @FK_Department INT,
  @DoContinue BIT
------------Pre
SET @DoContinue = 1
--Get Department
SELECT @FK_Department = dbo.GetHotelSetupKeyValue('PicassoOnlinePosteringDepartment', @AHotelCustomerNumber)
IF ISNULL(@FK_Department, 0) <= 0
BEGIN
  SET @DoContinue = 0
  RAISERROR('Error in storedprocedure <<OnlineCreateBillAndCheckout>>: @FK_Department not valid.', 15, 1)
END
--Get SystemDate   
SET @SystemDate = CURRENT_TIMESTAMP  
SELECT @SystemDateStr = SystemDate FROM System WITH (NOLOCK)  WHERE NUMBER = 1  -- Only one record
IF CONVERT(INT, @SystemDate) <> CONVERT(INT, CONVERT(DATETIME, @SystemDateStr))
  SET @SystemDate = CONVERT(DATETIME, @SystemDateStr+' '+ CONVERT(CHAR(8), CURRENT_TIMESTAMP,108)) 
--Get UserIdNumber
SELECT @OnlineUserId = Keyvalue FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'PicassoOnlinePosteringUserIdNumber'
IF @OnlineUserId <= 0
  SELECT TOP 1 @OnlineUserId = UserIDNumber FROM Personel WITH (NOLOCK)
  
------------Exec  
IF @DoContinue = 1
BEGIN
  --Insert new Bill
  EXEC GetNextNumber 'BILLIDENTITY', 1, @BillNumber OUTPUT
  INSERT INTO Invoices (BillNumber, UserIdNumber, SettledStatus, DateTimeStamp, HotelCustomerNumber, FkDepartment) 
  VALUES (@BillNumber, @OnlineUserId, 1, @SystemDate, @AHotelCustomerNumber, @FK_Department)
  --Insert new Folio relation
  INSERT INTO FolioBillXTab (FolioNumber, BillNumber, HotelCustomerNumber) 
  VALUES (@AFolioNumber, @BillNumber, @AHotelCustomerNumber)
  --Update Transaction relation
  UPDATE Transactions SET InvoiceBillNumber = @BillNumber
  WHERE FolioNumber = @AFolioNumber AND ISNULL(InvoiceBillNumber,0) = 0 AND MovedDeleted = 0 
  --Checkout Folio
  UPDATE Folios SET OpenFolio = 0 WHERE FolioNumber = @AFolioNumber
END  
------------Post

