CREATE PROCEDURE dbo.OnlineCreateBillAndCheckout @AFolioNumber INT, @AHotelCustomerNumber INT AS
SET NOCOUNT ON
/*
nb20161115 ReceiptType & ReceiptNumber fields added - currently only supports receipt receipttypes
ReceiptType 
0-Prebill-not supported
1-Receipt-hardcoded
2-Invoice-not supported
ReceiptNumber from number series dictated by ReceiptType:
0-Prebill number serie value
1-Bill number serie value
2-Invoice number serie value

nb20120705 New  
Created by Nenad Blagojevic july 2012

*/

DECLARE --local var 
  @BillNumber INT, 
  @SystemDateStr CHAR(8),
  @SystemDate DATETIME,
  @OnlineUserId INT,
  @FK_Department INT,
  @DoContinue BIT,
  @PkInvoice INT
------------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, @AHotelCustomerNumber
  INSERT INTO Invoice (BillNumber, FkStaff, CreatedDate, FkCustomerHotel, FkDepartment, ReceiptType, ReceiptNumber) 
  VALUES (@BillNumber, @OnlineUserId, @SystemDate, @AHotelCustomerNumber, @FK_Department, 1, @BillNumber)
  SET @PkInvoice = @@IDENTITY
  --Insert transaction relation
  INSERT INTO InvoiceTransactionXTab (FkInvoice, FkTransaction) 
    SELECT @PkInvoice, TransactionNumber FROM Transactions WITH (NOLOCK) 
	WHERE FolioNumber = @AFolioNumber AND ShowOnBillFlag = 1 and MovedDeleted = 0
	EXCEPT
    SELECT @PkInvoice, TR.TransactionNumber FROM Transactions TR WITH (NOLOCK)
    INNER JOIN InvoiceTransactionXtab ITX WITH (NOLOCK) ON TR.TransactionNumber = ITX.FkTransaction
    INNER JOIN Invoice I WITH (NOLOCK) ON ITX.FkInvoice = I.PkInvoice
    WHERE TR.FolioNumber = @AFolioNumber and I.CancelDate IS NULL
 
  --Checkout Folio
  UPDATE Folios SET OpenFolio = 0 WHERE FolioNumber = @AFolioNumber
END  
------------Post

