CREATE PROCEDURE [dbo].[MadeOrderBook] @CalcOrderBookFromDate Char(8) = '', @DebugCustomerNumber INT = -1, @DebugReferenceNumber INT = -1, @DebugGuestNumber INT = -1  AS
SET NOCOUNT ON

/*
Changes:
  KJ 20240603: Bug: Fix for "Reservations not included in calculation when guest has customer related and main reservation hasn't". Case #CR244890
  KJ 20231208: Bug: Fix for "Restaurant and other turnover to small. Extras on reservation not included."
  KJ 20230629: Bug: Fix for "Extras wrong if multiple roomslines/halllines and namelist not created". Case #CR233322
  KJ 20230629: Formatting
  KJ 20230512: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. Arrangmentlines has date = 00010101. Case #CR231976
  SG 20230223: Changed InternalRefMove (in transaction section)
  SG 20221011: Added support for PlusProductSamePeriod
  SG 20221011: +product: Departure package was missing
  SG 20220927: Added reservations without room or hall
  SG 20211130: Don't select addressType. It caused double entries when there was two addresstypes.
  SG 20210211: When moved, the moved to transaction was missing.
  SG 20201002: Added to previous change:  It must be a correction.
  SG 20200113: Include manual user combined with WarePayment = 3 (auto Hall) and 2 (auto room)
  SG 20191003: Reservations.Status may be NULL, converts to 0.
  SG 20190926: CR170740, CR 166965: Back to previous version! OrderBook uses primarely reservation data - also back in time (in contrast to MIS)
	            Moved transaction, Halls, treated as Rooms (Changed 20121129!)
  SG 20190909: CR 166965: When calculated back in time, records from both reservation and transaction was included.
  SG 20190905: Reservation section: Don't multiply with PAX in this case (if @NameListSetting = 1 AND @OnePersonPaysForAll = 0)
  SG 20190619: Transaction section: Look at Datestamp instead of OriginalDate in order to reflect movement between folios (more than one day back)
  SG 20181024: Hotel for extra changed in order to get Mixed Resources correct
  KJ / SG 20181023: Insure that we don't try to store records with invalid customernumber (would violate new key)(caused by invalid records in RESERVATIONADDRESS)
  KJ 20180629: Possible error in select data from transactions
  KJ 20180621: Optimized sp
  SG 20180416: See rev. 20141111: Only on SystemDate
  SG 20171002: Removed @MISOrderbookEarliestRecalcDate. Funktionality fullfilled through fct. GetLatestDeletedBefore. 
	            A second 'ReservationsDeletedBefore' and 'FoliosDeletedBefore' also removed.
  SG 20170928: Added @MISOrderbookEarliestRecalcDate 
  SG 20170828: Store discount backwards
  SG 20170410: Use #PacketInfo in order to allow ProductPricesDay to cache.
  SG 20170331: Room, ReservationCur: Exclude Link = -1 to avoid double amounts for contactperson
  SG 20170110: Don't use HotelSetup InternalCourseProduction any more. @MainCourceResNotInclMIS_OrderBook default 0
  SG 20160126: Changes of @TodayDateStr because the orderbook now runs after date change in nightaudit.
  SG 20160122: Change from 2015-12-04 reversed.
  SG 20160112: Checked for missing WITH (NOLOCK)'s.
  SG 20151217: Reservations: HotelNumber is primarely from RoomTypes / ConferenceRoomType. If NULL, HotelNumber from ReservationMain is used instead of 0. 
  SG 20151204: Condition added 20150522 moved from JOIN to WHERE and made depending on no namelist.
  SG 20150522: Guest added to INNER JOIN RESERVATIONROOMLINEXTAB
  SG 20150427: Added distinct in Transaction section
  SG 20150414: Main course reservations may not be included (hotelSetup). When EventsEnableCommonNamelist=1, company link is taken from guest 0
  SG 20141111: Extras type Manual room and manuel halls are included in transaction section and should be excluded in reservation section
  SG 20141031: CR 078471: RESERVATIONCONFERENCELINE.LinkLineNumber 0 same as null
  SG 20141031: CR 078471: Hall extras was included several times
  SG 20140709: CR 074196: When two shares a room, only one had amount in the orderbook.
  SG 20131107: CR 066000: Extras in Restaurant and Other were included for canceled reservations
  SG 20130823: CR 063532: WherePayment for extras corrected.
  SG 20130412: CR 054585: Wrong count of rooms for company and company Co. when linked to guest. Related with Cr 045099 below.
  SG 20130219: CR 047097: RoomType was not used in price calculation of halls (RoomTypeNumber=0 always used)
  SG 20130215: CR 052390: Deleted transactions not handled correctly. GuestNumber added from transaction to orderbook.
  SG 20121206: CR 045099: Wrong count of Roomnight when sharing rooms using namelist 
  SG 20121129: Ext: HotelSetup "EnableOrderBookWithTransactions" added
  SG 20121129: CR 046677: When transaction was moved from Customer 1 to Customer 2 (not linked), the orderbook was wrong for Custumer1.
  OF 20120611: Ext: When internal ref move and new customer then turnover must be written for that customer.
  OF 20120316: Ext: SegmentNumber resolved from Customer table when there is no reservation (transaction section).
  OF 20120305: Bug: Extras as ManualRoom/ManualHalls added to mis.
  OF 20111209: Ext: Departments set as auto department must only be ahead in time in reservation part. Never back in time hence it is resolved in transactions.		 
  OF 20110530: Ext: Transactions.DateStamp changed to Transactions.OriginalDate in transaction section.
  OF 20110204: Bug: Orderbook correction did only consider when Transactions.Debit = 0. Correction is both - and +.
  OF 20110201: Bug: If Auto Room transaction moved from one folio to another on the same reference number, then ignore and don´t store in orderbook.
  OF 20110131: Ext: Tablebooking enabled. "(Tablebooking=0 or Tablebooking is null)" uncommented in conferencesection 
  OF 20101220: Bug: Rooms and hotels did join correctly. Fixed in Rooms section.
  OF 20101004: Bug: Fix for missing Extras. Extras resolving moved out of "enumerate days" loop, both for rooms and conference section.
  OF 20100628: Bug: Fix for extras for outofhouse reservations missing i ordrebook when recalculating back in time.
  KJ 20100602: Bug: Fix for "Customer/Hotel sometimes deleted"
  Old checkin notes deleted 2015-12-04
*/

DECLARE @ShowPrint BIT
SET @ShowPrint = 0

DECLARE @TotalCalcPriceDay MONEY

DECLARE @CalcPriceDay MONEY
DECLARE @PacketNumber INT
DECLARE @EnviromentFee MONEY
DECLARE @AllocatedTypeNumber INT
DECLARE @BookedTypeNumber INT

DECLARE @ProductStartDate DATETIME
DECLARE @ProductEndDate DATETIME

DECLARE @StarProduct BIT

DECLARE @CustomerNumberInTab INT
DECLARE @CustomerNumber INT
DECLARE @MainHotelCustomerNumber INT

DECLARE @FixedPrice BIT

DECLARE @PriceOverwritten BIT
DECLARE @Price MONEY
DECLARE @TotalPriceDay MONEY
DECLARE @FirstPrice1 MONEY
DECLARE @ProductNumber INT

DECLARE @PlusProductSamePeriod BIT
DECLARE @PriceOverwritten2 BIT
DECLARE @FirstPrice2 MONEY
DECLARE @Day2 SMALLINT
DECLARE @ProductNumber2 INT

DECLARE @PriceOverwritten3 BIT
DECLARE @FirstPrice3 MONEY
DECLARE @Day3 SMALLINT
DECLARE @ProductNumber3 INT

DECLARE @PriceOverwritten4 BIT
DECLARE @FirstPrice4 MONEY
DECLARE @Day4 SMALLINT
DECLARE @ProductNumber4 INT

DECLARE @SegmentNumber SMALLINT

DECLARE @NumberOfRooms INT
DECLARE @ArrivalDate CHAR(8)
DECLARE @DepartureDate CHAR(8)

DECLARE @Adults INT
DECLARE @Children1 INT
DECLARE @Children2 INT
DECLARE @Pieces INT

DECLARE @PaysAdults INT
DECLARE @PaysChildren1 INT
DECLARE @PaysChildren2 INT

DECLARE @Status SMALLINT

DECLARE @NumberOfPax INT
DECLARE @NumberOfCXL INT
DECLARE @NumberOfNoShow INT
DECLARE @NumberOfNight INT
DECLARE @NumberOfStay INT
DECLARE @NumberOfHalls INT

DECLARE @TodayDateStr CHAR(8)
DECLARE @TodayDateDT DATE

DECLARE @CurrentDateStr CHAR(8)
DECLARE @CurrentDate DATETIME
DECLARE @CurrentDate1 DATETIME

DECLARE @BookedConferenceRoomTypeNumber INT

DECLARE @ROOMNUMBER INT

DECLARE @PriceProduct1 MONEY
DECLARE @PriceProduct2 MONEY
DECLARE @PriceProduct3 MONEY
DECLARE @PriceProduct4 MONEY

DECLARE @Addon MONEY
DECLARE @Addon1 MONEY
DECLARE @Addon2 MONEY
DECLARE @Addon3 MONEY
DECLARE @Addon4 MONEY

DECLARE @BillTextProduct VARCHAR(50)
DECLARE @BillTextAddOnProduct  VARCHAR(50)

DECLARE @ReferenceNumber INT
DECLARE @FolioNumber INT
DECLARE @InvoiceNumber INT
DECLARE @InternalRefMove BIT
DECLARE @OrderBookCorrection BIT
DECLARE @OrderBookMovedTo BIT
DECLARE @GuestNumber SMALLINT

DECLARE @PrevReferenceNumber INT
DECLARE @PrevGuestNumber SMALLINT

DECLARE @VATProduct BIT
DECLARE @SpecifiedDepartureAddOn BIT
DECLARE @NumberOfReserve INT
DECLARE @NameListReservationPerPerson BIT

DECLARE @LineNumber INT
DECLARE @TempLineNumber INT
DECLARE @TempCustomerNumberInTab INT

DECLARE @LinkedGuest BIT --1: The current guest is sharing room with the previous guest (see order by)

DECLARE @SomeNotCanceledRes BIT

DECLARE @ContactpersonCustomerNumber INT

DECLARE @AddonIfPriceOverwritten BIT

DECLARE @TotalExtraOnDay MONEY

DECLARE @TransDate CHAR(8)
DECLARE @TransDateDT DATETIME
DECLARE @Totalsum MONEY
DECLARE @WarePayment SMALLINT
DECLARE @WareType SMALLINT
DECLARE @DefaultOrdrebookSegment INT
DECLARE @SystemDateStr CHAR(8)
DECLARE @SystemDateDT DATE

DECLARE @OnePersonPaysForAll BIT
DECLARE @NameListSetting INT

DECLARE @IncludeProvisionbackward BIT    --discount backwards (transactions)
DECLARE @OrderBookBudgetCalcDiscount BIT --discount forward (reservations) (not implemented)

DECLARE @IncludeDayroomsInSoldRooms BIT
DECLARE @DayroomsLaterThanTime CHAR(5)

DECLARE @DepartureTime CHAR(5)
DECLARE @ArrivalTime CHAR(5)

DECLARE @NightAuditRunning BIT

DECLARE @HotelCustomerNumber INT

DECLARE @LastOrderBookUpdate DATETIME

DECLARE @LatestDeletedBefore CHAR(8)

DECLARE @Plenum BIT

DECLARE @Arr24 CHAR(5)
DECLARE @ManuelUser BIT
DECLARE @LinkLineNumber INT

DECLARE @ExtraOnDay VARCHAR(8)
DECLARE @MovedFolioNumber INT
DECLARE @EnableOrderBookWithTransactions SMALLINT
DECLARE @MainCourceResNotInclMIS_OrderBook BIT

--Used by SP ProductPricesDay if excist for cashing
CREATE TABLE #PacketInfo
(
  ProductNumber INT,
  DateStamp DATE,
  PacketType INT,
  PacketNumber INT
)

SET @CalcOrderBookFromDate = ISNULL(@CalcOrderBookFromDate, '')
SET @DebugCustomerNumber = ISNULL(@DebugCustomerNumber, -1)
SET @DebugReferenceNumber = ISNULL(@DebugReferenceNumber, -1)
SET @DebugGuestNumber = ISNULL(@DebugGuestNumber, -1)

SELECT @EnableOrderBookWithTransactions = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'EnableOrderBookWithTransactions'
SET @EnableOrderBookWithTransactions = ISNULL(@EnableOrderBookWithTransactions, 0)
  
SELECT @Arr24 = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'Arr24HoursStarts'

SET @MainHotelCustomerNumber = -1
IF EXISTS(SELECT CustomerNumber FROM Customer WITH (NOLOCK) WHERE LocalHotel = 1)
  SELECT @MainHotelCustomerNumber = CustomerNumber FROM Customer WITH (NOLOCK) WHERE LocalHotel = 1

SELECT @NightAuditRunning = NightAuditRunning FROM Terminals WITH (NOLOCK) WHERE NightAuditRunning = 1
SET @NightAuditRunning = ISNULL(@NightAuditRunning, 0)

SELECT @IncludeDayroomsInSoldRooms = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'IncludeDayroomsInSoldRooms'
SELECT @DayroomsLaterThanTime = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'DayroomsLaterThanTime'

SET @IncludeDayroomsInSoldRooms = ISNULL(@IncludeDayroomsInSoldRooms, 0)

if ISNULL(@DayroomsLaterThanTime, '') = ''
  SET @DayroomsLaterThanTime = '13:00'

SELECT @OnePersonPaysForAll = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'OnePersonPaysForAll'
SET @OnePersonPaysForAll = ISNULL(@OnePersonPaysForAll,0)

SET @PrevReferenceNumber = 0
SET @PrevGuestNumber = -1
SET @TempLineNumber = 0
SET @TempCustomerNumberInTab = 0

SELECT @DefaultOrdrebookSegment = CONVERT(INT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'DefaultOrdrebookSegment'
SET @DefaultOrdrebookSegment = ISNULL(@DefaultOrdrebookSegment, 0)
IF @DefaultOrdrebookSegment = 0
  SELECT @DefaultOrdrebookSegment = Number FROM Segments WITH (NOLOCK) WHERE ((MarkAsDeleted = '0') OR (MarkAsDeleted IS NULL))

SELECT @SystemDateStr = SYSTEMDATE FROM System WITH (NOLOCK) WHERE NUMBER = 1
SET @SystemDateDT = CONVERT(DATE, @SystemDateStr, 112)

IF @CalcOrderBookFromDate = '' 
BEGIN
  IF @NightAuditRunning = 0
    SET @TodayDateStr = @SystemDateStr
  ELSE
  BEGIN
    SET @TodayDateStr = Convert(Char(8), DateAdd(day, -1, Convert(DateTime, @SystemDateStr)), 112) --Natkørslen har lige skiftet dato
    
  	SELECT @LastOrderBookUpdate = CONVERT(DATETIME, Keyvalue) FROM HotelSetup WITH (NOLOCK) WHERE Searchkey = 'LastOrderBookUpdate'

    IF @@Rowcount = 0
      INSERT INTO Hotelsetup (Searchkey, KeyValue) VALUES ('LastOrderBookUpdate', @SystemDateStr)
    ELSE
    BEGIN
      DECLARE @NextDay DATETIME
      SET @NextDay = DATEADD(DAY, 1, @LastOrderBookUpdate)
      IF CONVERT(CHAR(8), @NextDay, 112) < @SystemDateStr --evt. ordrebog fejlet i foregående natkørsel
        SET @TodayDateStr = CONVERT(CHAR(8), @NextDay, 112)
    END
  END
END
Else
  SET @TodayDateStr = @CalcOrderBookFromDate

-- Limit the recalculation date 
EXEC dbo.GetLatestDeletedBefore @LatestDeletedBefore OUTPUT
IF @TodayDateStr < @LatestDeletedBefore
  SET @TodayDateStr = @LatestDeletedBefore
SET @TodayDateDT = CONVERT(DATE, @TodayDateStr, 112) 

DELETE CustomerOrdreBook
WHERE ISDATE(CustomerOrdreBook.DateForValue) = 0

DELETE FROM CustomerOrdreBook 
WHERE (ReadOnly = 0 AND (CONVERT(DATETIME, DateForValue)) >= CONVERT(DATETIME, @TodayDateStr)) 
AND ((ISNULL(@DebugCustomerNumber, -1) = -1) OR (CustomerNumber = @DebugCustomerNumber) or (ContactpersonCustomerNumber = @DebugCustomerNumber))

SELECT @NameListReservationPerPerson = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'NameListReservationPerPerson'

SELECT @AddonIfPriceOverwritten = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'AddonIfPriceOverwritten'
SET @AddonIfPriceOverwritten = ISNULL(@AddonIfPriceOverwritten, 0)

SELECT @IncludeProvisionbackward = dbo.GetHotelSetupKeyValue('IncludeProvisionbackwardInOrderbook', -1)
SET @IncludeProvisionbackward = ISNULL(@IncludeProvisionbackward, 0)

SELECT @OrderBookBudgetCalcDiscount = dbo.GetHotelSetupKeyValue('OrderBookBudgetCalcDiscount', -1)
SET @OrderBookBudgetCalcDiscount = ISNULL(@OrderBookBudgetCalcDiscount, 0)

SELECT @MainCourceResNotInclMIS_OrderBook = CONVERT(BIT, KeyValue) FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'MainCourceResNotInclMIS_OrderBook'
SET @MainCourceResNotInclMIS_OrderBook = ISNULL(@MainCourceResNotInclMIS_OrderBook, 0)

--******* Reservation Roomline Section ***********
DECLARE ReservationCur CURSOR SCROLL READ_ONLY FOR
  SELECT DISTINCT
  Reservations.ReferenceNumber,
  Reservations.GuestNumber,
  Reservations.MARKETSEGMENT,
  Reservations.Status,
  ISNULL(ReservationAddress.Link, dbo.GetMainReservationLinkNumber (Reservations.ReferenceNumber, ReservationAddress.AddressType)) AS Link11,
  ReservationAddress.ContactpersonCustomerNumber,
  ReservationRoomLineXTab.LineNumber,
  ISNULL(Customer.CustomerNumber, -1)
  FROM ReservationAddressXTab WITH (NOLOCK)
  INNER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
  INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationAddressXTab.REFERENCENUMBER
    AND Reservations.GuestNumber = ReservationAddressXTab.GuestNumber
    AND Reservations.Referencenumber > 0 
    AND Reservations.DepartureDate >= @TodayDateStr 
  INNER JOIN ReservationRoomLineXTab WITH (NOLOCK) ON ReservationRoomLineXTab.ReferenceNumber = Reservations.ReferenceNumber 
    AND ReservationRoomLineXTab.GuestNumber = Reservations.GuestNumber
  INNER JOIN ReservationRoomLine WITH (NOLOCK) ON ReservationRoomLine.LineNumber = ReservationRoomLineXTab.LineNumber
  INNER JOIN ReservationMain WITH (NOLOCK) ON ReservationMain.Referencenumber = Reservations.ReferenceNumber 
  LEFT OUTER JOIN ReservationConferenceLine WITH (NOLOCK) ON ReservationConferenceLine.ReferenceNumber = Reservations.ReferenceNumber
  LEFT OUTER JOIN Rooms WITH (NOLOCK) ON Rooms.RoomNumber = ReservationRoomLine.RoomNumber
  LEFT OUTER JOIN RoomTypes WITH (NOLOCK) ON RoomTypes.RoomTypeNumber = ReservationRoomLine.BookedTypeNumber
  LEFT OUTER JOIN Customer WITH (NOLOCK) ON Customer.HotelNumber = ISNULL(RoomTypes.HotelNumber, ReservationMain.HotelNumber)
    AND Customer.HotelNumber >= 0 
    AND Customer.CustomerTypeNumber = 7 
    AND ISNULL(Customer.MarkAsDeleted, 0) = 0
  LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) ON resx.FK_ReferenceNumber = Reservations.ReferenceNumber 
  LEFT OUTER JOIN reservations sub WITH (NOLOCK) ON sub.ReferenceNumber = resx.FK_ReferenceNumberSub 
    AND sub.Status < 7 
  WHERE 1=1
  AND
    ((Reservations.GuestNumber > 0 AND @NameListReservationPerPerson=1 AND (ISNULL(Reservations.PaysAdults, 0) + ISNULL(Reservations.PaysChildren1, 0) + ISNULL(Reservations.PaysChildren2, 0) > 0)) 
    OR 
    (Reservations.GuestNumber > 0 AND @NameListReservationPerPerson=1 AND (Reservations.Status = 7)) -- When cancelled reservation, extract all guests
    OR 
    (Reservations.GuestNumber > 0 AND @NameListReservationPerPerson=0 AND (ISNULL(Reservations.Adults, 0) + ISNULL(Reservations.Children1, 0) + ISNULL(Reservations.Children2, 0) > 0)) 
    OR 
    (Reservations.GuestNumber = 0 AND (ISNULL(ReservationRoomLine.Adults, 0) + ISNULL(ReservationRoomLine.Children1, 0) + ISNULL(ReservationRoomLine.Children2, 0) > 0)))
  AND ((Reservations.DepartureDate <> Reservations.ArrivalDate) 
    OR (Reservations.DepartureDate = Reservations.ArrivalDate AND @IncludeDayroomsInSoldRooms=1 AND Reservations.ArrivalDate <= @SystemDateStr)) 
  AND ((ISNULL(@DebugCustomerNumber, -1) = -1) OR (ISNULL(ReservationAddress.Link, dbo.GetMainReservationLinkNumber(Reservations.ReferenceNumber, ReservationAddress.AddressType)) = @DebugCustomerNumber) OR (ISNULL(ReservationAddress.ContactpersonCustomerNumber,-1) = @DebugCustomerNumber))
  AND ((ISNULL(@DebugReferenceNumber, -1) = -1) OR (Reservations.ReferenceNumber = @DebugReferenceNumber))
  AND ((ISNULL(@DebugGuestNumber, -1) = -1) OR (Reservations.GuestNumber = @DebugGuestNumber))
  AND ISNULL(ReservationAddress.Link , dbo.GetMainReservationLinkNumber (Reservations.ReferenceNumber, ReservationAddress.AddressType)) > 0
  AND (ISNULL(FK_ReferenceNumber, 0) = 0 OR @MainCourceResNotInclMIS_OrderBook = 0)
  AND (Reservations.GuestNumber = ReservationRoomLineXTab.GuestNumber OR (Reservations.GuestNumber = 0 AND dbo.GetHotelSetupKeyValue('EventsEnableCommonNamelist', ISNULL(Customer.CustomerNumber, -1)) = 1))
  ORDER BY Reservations.ReferenceNumber, Link11, Reservations.GuestNumber, ReservationRoomLineXTab.LineNumber, Reservations.Status
Open ReservationCur

Fetch Next From ReservationCur Into @ReferenceNumber, @GuestNumber, @SegmentNumber, @Status, @CustomerNumberInTab, @ContactpersonCustomerNumber,@LineNumber, @HotelCustomerNumber

While (@@FETCH_STATUS <> -1)
Begin
  Set @Status = IsNull(@Status, 0)
  
  if @GuestNumber=0
  begin
    SELECT
      @ArrivalDate = RESERVATIONROOMLINE.ArrivalDate,
      @DepartureDate = RESERVATIONROOMLINE.DepartureDate,
      @DepartureTime = RESERVATIONROOMLINE.DepartureTime,
      @Adults = RESERVATIONROOMLINE.Adults,
      @Children1 = RESERVATIONROOMLINE.Children1,
      @Children2 = RESERVATIONROOMLINE.Children2,
      @Price = RESERVATIONROOMLINE.Price,
      @PriceOverwritten = RESERVATIONROOMLINE.PriceOverwritten,
      @ProductNumber = RESERVATIONROOMLINE.ProductNumber,
      @FirstPrice1 = RESERVATIONROOMLINE.FirstPrice1,
      @PriceOverwritten2 = RESERVATIONROOMLINE.PriceOverwritten2,
      @FirstPrice2 = RESERVATIONROOMLINE.FirstPrice2,
      @Day2 = isnull(RESERVATIONROOMLINE.Day2,0),
      @ProductNumber2 = RESERVATIONROOMLINE.ProductNumber2,
      @PriceOverwritten3 = RESERVATIONROOMLINE.PriceOverwritten3,
      @FirstPrice3 = RESERVATIONROOMLINE.FirstPrice3,
      @Day3 = isnull(RESERVATIONROOMLINE.Day3,0),
      @ProductNumber3 = RESERVATIONROOMLINE.ProductNumber3,
      @PriceOverwritten4 = RESERVATIONROOMLINE.PriceOverwritten4,
      @FirstPrice4 = RESERVATIONROOMLINE.FirstPrice4,
      @Day4 = isnull(RESERVATIONROOMLINE.Day4,0),
      @ProductNumber4 = RESERVATIONROOMLINE.ProductNumber4,
      @NumberOfRooms = RESERVATIONROOMLINE.NumberOfRooms,
      @ROOMNUMBER = RESERVATIONROOMLINE.RoomNumber,
      @BookedTypeNumber = RESERVATIONROOMLINE.BookedTypeNumber,
      @PlusProductSamePeriod = RESERVATIONROOMLINE.PlusProductSamePeriod

    FROM RESERVATIONROOMLINE  WITH (NOLOCK)
    Where LineNumber=@LineNumber
  end
  else
  begin
    SET @PaysAdults = 0
    SET @PaysChildren1 = 0
    SET @PaysChildren2 = 0
    SET @Adults = 0
    SET @Children1 = 0
    SET @Children2 = 0
    SET @PriceOverwritten = 0

    SELECT
      @ArrivalDate = RESERVATIONS.ArrivalDate,
      @DepartureDate = RESERVATIONS.DepartureDate,
      @DepartureTime = RESERVATIONS.DepartureTime,
      @PaysAdults = ISNULL(RESERVATIONS.PaysAdults, 0),
      @PaysChildren1 = ISNULL(RESERVATIONS.PaysChildren1, 0),
      @PaysChildren2 = ISNULL(RESERVATIONS.PaysChildren2, 0),
      @Adults = ISNULL(RESERVATIONS.Adults, 0),
      @Children1 = ISNULL(RESERVATIONS.Children1, 0),
      @Children2 = ISNULL(RESERVATIONS.Children2, 0),
      @Price = RESERVATIONS.Price,
      @PriceOverwritten = RESERVATIONS.PriceOverwritten,
      @ProductNumber = RESERVATIONS.ProductNumber,
      @FirstPrice1 = RESERVATIONS.FirstPrice1,
      @PriceOverwritten2 = RESERVATIONS.PriceOverwritten2,
      @FirstPrice2 = RESERVATIONS.FirstPrice2,
      @Day2 = isnull(RESERVATIONS.Day2,0),
      @ProductNumber2 = RESERVATIONS.ProductNumber2,
      @PriceOverwritten3 = RESERVATIONS.PriceOverwritten3,
      @FirstPrice3 = RESERVATIONS.FirstPrice3,
      @Day3 = isnull(RESERVATIONS.Day3,0),
      @ProductNumber3 = RESERVATIONS.ProductNumber3,
      @PriceOverwritten4 = RESERVATIONS.PriceOverwritten4,
      @FirstPrice4 = RESERVATIONS.FirstPrice4,
      @Day4 = isnull(RESERVATIONS.Day4,0),
      @ProductNumber4 = RESERVATIONS.ProductNumber4,
      @NumberOfRooms = RESERVATIONROOMLINE.NumberOfRooms,
      @ROOMNUMBER = RESERVATIONROOMLINE.RoomNumber,
      @BookedTypeNumber = RESERVATIONROOMLINE.BookedTypeNumber,
      @PlusProductSamePeriod = RESERVATIONS.PlusProductSamePeriod
    FROM RESERVATIONROOMLINE  WITH (NOLOCK) 
      INNER JOIN RESERVATIONROOMLINEXTAB  WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LINENUMBER
      INNER JOIN RESERVATIONS  WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber

    WHERE (RESERVATIONROOMLINEXTAB.ReferenceNumber=@ReferenceNumber) AND (RESERVATIONROOMLINEXTAB.GuestNumber=@GuestNumber)
    AND ((@NameListReservationPerPerson=1 AND isnull(RESERVATIONS.PaysAdults, 0) + isnull(RESERVATIONS.PaysChildren1, 0) + isnull(RESERVATIONS.PaysChildren2, 0) > 0)
      OR (@NameListReservationPerPerson=0 AND isnull(RESERVATIONS.Adults, 0) + isnull(RESERVATIONS.Children1, 0) + isnull(RESERVATIONS.Children2, 0) > 0))  
  end  

  if IsNull(@ROOMNUMBER,0)=0
    Set @ROOMNUMBER = 0

  Set @AllocatedTypeNumber = @BookedTypeNumber

  if (Convert (DATETIME, @TodayDateStr)>=convert(Datetime,@ArrivalDate))
    SET @CurrentDateStr = @TodayDateStr
  else
    SET @CurrentDateStr = @ArrivalDate

  Set @CurrentDate = Convert (DATETIME, @CurrentDateStr)

  if (@CurrentDateStr <= @DepartureDate)
  begin
    if @TempLineNumber = @LineNumber and @TempCustomerNumberInTab = @CustomerNumberInTab
      SET @LinkedGuest = 1
    else
    begin
      SET @LinkedGuest = 0
      SET @SomeNotCanceledRes = 0
    end 

    if @PrevReferenceNumber <> @ReferenceNumber
    begin 
      if (@LinkedGuest=0) 
        SET @SomeNotCanceledRes = 0
    end

    SET @TempLineNumber = @LineNumber
    SET @TempCustomerNumberInTab = @CustomerNumberInTab

	  if ((@Day2+@Day3+@Day4)>0)
	  begin
      SET @StarProduct=1

      Select @NameListSetting = NameListSetting from ReservationRoomLine  WITH (NOLOCK) where LineNumber = @LINENUMBER
      if isnull(@NameListSetting,0) = 0 SET @NameListSetting = 0

      if @NameListSetting = 1 AND @GuestNumber > 0 -- only if namelist created
      begin
        SET @Adults = @PaysAdults
        SET @Children1 = @PaysChildren1
        SET @Children2 = @PaysChildren2
      end               
    end 
    else
    begin
      SET @StarProduct=0
      if @ProductNumber>0
      begin 
        if @GuestNumber>0
          Select @NameListSetting = ISNULL(NameListSetting,0) from ReservationRoomLine  WITH (NOLOCK) where LineNumber = @LINENUMBER
        else 
          SET @NameListSetting = 0

        if @NameListSetting = 0  
        begin
          Select @NameListSetting = NameListSetting from Products  WITH (NOLOCK) where productnumber = @ProductNumber
            if isnull(@NameListSetting,0) = 0 
              SET @NameListSetting = 0
        end
      end
      else
        SET @NameListSetting = 0

      if @NameListSetting = 0
        Select @NameListSetting = @NameListReservationPerPerson  --@NameListSettingHotelSetup

      if  @NameListSetting = 1 AND @GuestNumber > 0 -- only if namelist created
      begin
        SET @Adults = @PaysAdults
        SET @Children1 = @PaysChildren1
        SET @Children2 = @PaysChildren2
      end
    end 

    While (@CurrentDateStr <= @DepartureDate)
    begin
      SET @PriceProduct1 = 0
      SET @PriceProduct2 = 0
      SET @PriceProduct3 = 0
      SET @PriceProduct4 = 0

      SET @Addon1 = 0
      SET @Addon2 = 0
      SET @Addon3 = 0
      SET @Addon4 = 0
		
      if ((@Status= 7)or (@Status=8) )--   rsCancelled,   
      begin
        SET @NumberOfPax =0
        SET @Price = 0
        SET @NumberOfNight = 0
        SET @NumberOfStay = 0

        IF (((@DepartureDate <> @CurrentDateStr) OR (@IncludeDayroomsInSoldRooms = 1 AND @DepartureDate = @CurrentDateStr AND @DayroomsLaterThanTime<@DepartureTime)) AND (@DepartureDate<>@ArrivalDate))  OR ((@DepartureDate = @CurrentDateStr) AND (@DepartureDate = @ArrivalDate))
        begin
          if (@Status= 7)
          begin
            if (@GuestNumber = 0)
              SET @NumberOfCXL = @NumberOfRooms
            else
              SET @NumberOfCXL = 1

            SET @NumberOfNoShow = 0
          end
          else
          begin                    
            SET @NumberOfNoShow = @NumberOfRooms                   
            SET @NumberOfCXL = 0
          end
        end
        else
        begin
          SET @NumberOfNoShow = 0
          SET @NumberOfCXL = 0
        end
      end
      else
      begin
        -- Fra idag om frem beregn price
        SET @TotalCalcPriceDay = 0
        SET @NumberOfCXL = 0
        SET @NumberOfNoShow = 0

        if (@StarProduct=0)
        Begin
          Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)
          Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)

          if (@PriceOverWritten=0)
            exec ProductPricesDay @ProductNumber,@ProductStartDate, @ProductEndDate, @CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2,@Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
          else
          begin
            if (@CurrentDateStr = @DepartureDate) AND (@DepartureDate <> @ArrivalDate)
              SET @PriceProduct1 = 0
            else
            begin
              if @AddonIfPriceOverwritten = 1
              begin
                SET @CurrentDate1 = @CurrentDate + 1
                exec ProductPricesDay @ProductNumber,@ProductStartDate, @ProductEndDate, @CurrentDate1, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2,@Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
                SET @Addon1 = @Addon1 * @NumberOfRooms 
              end

              SET @PriceProduct1 = @Price *@NumberOfRooms 
            end
          end
        end
        else -- StarProduct (+Product)
        Begin
          if (@CurrentDate<(Convert (DATETIME, @ArrivalDate)+@Day2-1))
          Begin
            if (@PriceOverWritten=0)
            Begin
              Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)
              Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day2-1

              exec ProductPricesDay @ProductNumber,@ProductStartDate, @ProductEndDate,@CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT,@PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting,@OnePersonPaysForAll -- New added @NameListSetting
            end
            else
            begin
              if @AddonIfPriceOverwritten = 1
              begin
                exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber, @AllocatedTypeNumber, @Addon1 OUTPUT
                SET @Addon1 = @Addon1 * @NumberOfRooms 
              end
              SET @PriceProduct1 = @FirstPrice1 *@NumberOfRooms 
            end
          end

          --2. and last period
          if (@Day3=0)
          Begin
            if (@CurrentDate>=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) AND ((Convert (DATETIME,@ArrivalDate)+ @Day2-1)<>Convert (DATETIME, @DepartureDate)) --AND (@CurrentDate <> CONVERT(DATETIME, @DepartureDate))
            Begin
              if (@PriceOverWritten2=0)
              Begin
                If @PlusProductSamePeriod = 0
                BEGIN 
                  Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day2-1
                  Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)
                END 
                ELSE
                BEGIN
                  Set @ProductStartDate = Convert (DATETIME, @ArrivalDate) --force stay
                  Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)
                END
                exec ProductPricesDay @ProductNumber2,@ProductStartDate, @ProductEndDate, @CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon2 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT,@PriceProduct2 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
              end	
              else if @CurrentDate <> CONVERT(DATETIME, @DepartureDate)
              begin
                if @AddonIfPriceOverwritten = 1
                begin
                  exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber2, @AllocatedTypeNumber, @Addon2 OUTPUT
                  SET @Addon2 = @Addon2 * @NumberOfRooms 
                end
                SET @PriceProduct2 = @FirstPrice2 *@NumberOfRooms 
              end
            end
          end
          else
          Begin --2. period, there is a 3. period
            if ((@CurrentDate>=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) AND (@CurrentDate<(Convert (DATETIME, @ArrivalDate)+@Day3-1))) AND (@CurrentDate <> CONVERT(DATETIME, @DepartureDate))
            Begin
              if (@PriceOverWritten2=0) 
              Begin
                If @PlusProductSamePeriod = 0
                BEGIN 
                  Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day2-1
                  Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day3-1
                END 
                ELSE
                BEGIN
                  Set @ProductStartDate = Convert (DATETIME, @ArrivalDate) --forse stay
                  Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day3-1
                END
                exec ProductPricesDay @ProductNumber2,@ProductStartDate,@ProductEndDate, @CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon2 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT,@PriceProduct2 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
              end
              else
              begin
                if @AddonIfPriceOverwritten = 1
                begin
                  exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber2, @AllocatedTypeNumber, @Addon2 OUTPUT
                  SET @Addon2 = @Addon2 * @NumberOfRooms 
                end
                SET @PriceProduct2 = @FirstPrice2 *@NumberOfRooms 
              end
            end

            if (@Day4=0)
            begin --3. and last period
              if (@CurrentDate>=(Convert (DATETIME,@ArrivalDate)+ @Day3-1)) AND ((Convert (DATETIME,@ArrivalDate)+ @Day3-1)<>Convert (DATETIME, @DepartureDate)) --AND (@CurrentDate <> CONVERT(DATETIME, @DepartureDate))
              begin
                if (@PriceOverWritten3=0)
                begin
                  If @PlusProductSamePeriod = 0
                  BEGIN 
                    Set @ProductStartDate = Convert (DATETIME,@ArrivalDate)+ @Day3-1
                    Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)
                  END
                  ELSE
                  BEGIN 
                    Set @ProductStartDate = Convert (DATETIME,@ArrivalDate)
                    Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)
                  END
                  exec ProductPricesDay @ProductNumber3,@ProductStartDate, @ProductEndDate,@CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon3 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct3 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
                end
                else IF @CurrentDate <> CONVERT(DATETIME, @DepartureDate)
                begin
                  if @AddonIfPriceOverwritten = 1
                  begin
                    exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber3, @AllocatedTypeNumber, @Addon3 OUTPUT
                    SET @Addon3 = @Addon3 * @NumberOfRooms 
                  end
                  SET @PriceProduct3 = @FirstPrice3 *@NumberOfRooms 
                end
              end
            end
            else
            begin --3. period, there is a 4. period
              if ((@CurrentDate>=(Convert (DATETIME,@ArrivalDate)+ @Day3-1)) AND (@CurrentDate<(Convert (DATETIME,@ArrivalDate)+ @Day4-1))) AND (@CurrentDate <> CONVERT(DATETIME, @DepartureDate))
              begin
                if (@PriceOverWritten3=0)
                begin
                  If @PlusProductSamePeriod = 0
                  BEGIN
                    Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day3-1
                    Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day4-1
                  END
                  ELSE
                  BEGIN 
                    Set @ProductStartDate = Convert (DATETIME, @ArrivalDate) -- force stay
                    Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day4-1
                  END
                  exec ProductPricesDay @ProductNumber3,@ProductStartDate,@ProductEndDate, @CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon3 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct3 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
                end
                else
                begin
                  if @AddonIfPriceOverwritten = 1
                  begin
                    exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber3, @AllocatedTypeNumber, @Addon3 OUTPUT
                    SET @Addon3 = @Addon3 * @NumberOfRooms 
                  end
                  SET @PriceProduct3 = @FirstPrice3 *@NumberOfRooms 
                end
              End

              --4. period
              if ((@CurrentDate>=(Convert (DATETIME,@ArrivalDate)+ @Day4-1)) AND (@CurrentDate<=(Convert (DATETIME,@DepartureDate))))
              begin
                if (@PriceOverWritten4=0) 
                begin
                  If @PlusProductSamePeriod = 0
                  BEGIN 
                    Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day4-1
                    Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)
                  END
                  ELSE
                  BEGIN 
                    Set @ProductStartDate = Convert (DATETIME, @ArrivalDate) --force stay
                    Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)
                  END
                  exec ProductPricesDay @ProductNumber4,@ProductStartDate,@ProductEndDate, @CurrentDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon4 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT,@PriceProduct4 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll -- New added @NameListSetting
                end
                else
                begin
                  if @AddonIfPriceOverwritten = 1
                  begin
                    exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber4, @AllocatedTypeNumber, @Addon4 OUTPUT
                    SET @Addon4 = @Addon4 * @NumberOfRooms 
                  end
                  SET @PriceProduct4 = @FirstPrice4 *@NumberOfRooms 
                end
              end
            end -- @Day4>0
          end -- else if (@Day3=0)
        end -- END *-product

        if ((@CurrentDateStr = @DepartureDate) OR (@IncludeDayroomsInSoldRooms = 1 AND @DepartureDate = @CurrentDateStr AND @DayroomsLaterThanTime>@DepartureTime AND @CurrentDateStr < @SystemDateStr))  AND (@DepartureDate <> @ArrivalDate)
        begin
          SET @NumberOfNight = 0
          SET @NumberOfPax = 0
        end
        else
        begin
          if (@Status <= 6) 
          begin
            if (@LinkedGuest=0) OR (@LinkedGuest=1 AND @SomeNotCanceledRes=0)
            begin
              --SG/20121206: CR 045099: When sharing a room, only the first guest should contribute to the room-night count
              SET @NumberOfNight = @NumberOfRooms --SG
              SET @NumberOfPax=(@Adults+@Children1+@Children2)*@NumberOfNight
            end                     
            else
            begin
              SET @NumberOfPax=(@Adults+@Children1+@Children2)
              SET @NumberOfNight = 0
            end
          end
        end
      end  --

      SET @TotalCalcPriceDay = @PriceProduct1 + @PriceProduct2 + @PriceProduct3 + @PriceProduct4 + @Addon1 + @Addon2 + @Addon3 + @Addon4
		
      if isnull(@TotalCalcPriceDay,0)=0 
        SET @TotalCalcPriceDay = 0

      SET @NumberOfStay = 0
      IF (@CurrentDateStr = @ArrivalDate)-- First day?
      begin	
        if @Status<=6
          SET @NumberOfStay = @NumberOfRooms	-- Only set number of stays when processing first day.  
      end

	  	-- Store Rooms data in CustomerOrdreBook section start *****
      if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
      begin
        if isnull(@SegmentNumber,0) = 0 
          SET @SegmentNumber = @DefaultOrdrebookSegment
        if isnull(@HotelCustomerNumber, -1) = -1 and @MainHotelCustomerNumber <> -1 
          SET @HotelCustomerNumber = @MainHotelCustomerNumber --of
			
        if (@TotalCalcPriceDay <> 0) or (@NumberOfNight <> 0) or (@NumberOfPax <> 0) or (@NumberOfStay <> 0) or (@NumberOfCXL <> 0) or (@NumberOfNoShow <> 0) -- something to update
        begin
          -- Store Rooms data in CustomerOrdreBook *****
          INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
          VALUES (@CustomerNumberInTab, @SegmentNumber, @CurrentDateStr, @TotalCalcPriceDay, @NumberOfNight, @NumberOfPax, @NumberOfStay, @NumberOfCXL, @NumberOfNoShow, 0, 0, 0, 0, 0, 0, 0, 0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, null, null, 0, 2, 0, @ContactpersonCustomerNumber, @GuestNumber, 0)
        end
      end
	  	-- Store Rooms data in CustomerOrdreBook section end *****

      Set @CurrentDate = @CurrentDate +1
      Set @CurrentDateStr =  Convert (Char (8), @CurrentDate, 112)
    end -- While (@CurrentDateStr <= @DepartureDate)

/*
    -- Store Extras data in CustomerOrdreBook section start *****
    Declare @HotelCustomerNumberFromArrangement int

    if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber))) and @status < 7 --CR 066000/SG
    begin
      if isnull(@SegmentNumber,0) = 0 
        SET @SegmentNumber = @DefaultOrdrebookSegment
      if isnull(@HotelCustomerNumber, -1) = -1 and @MainHotelCustomerNumber <> -1 
        SET @HotelCustomerNumber = @MainHotelCustomerNumber
			
      DECLARE ExtraOnDayCur CURSOR FAST_FORWARD READ_ONLY FOR
        SELECT Sum(ArrangementLines.Pieces * ArrangementLines.Price), ArrangementLines.Date, WareGroups.WareType, WareGroups.Payment, Hotel.CustomerNumber
        FROM ArrangementLines WITH (NOLOCK) 
        INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementReservationsXtab.ArrangementLineNumber = ArrangementLines.ArrangementLineNumber
        INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = ArrangementLines.WareNumber
        INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WaregroupNumber = Ware.WareGroupNumber
        LEFT OUTER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment
        INNER JOIN Customer AS Hotel WITH (NOLOCK) ON Hotel.HotelNumber = Departments.HotelNumber
          AND Hotel.HotelNumber >= 0
          AND Hotel.CustomerTypeNumber = 7
          AND ISNULL(Hotel.MarkAsDeleted, 0) = 0
        WHERE ((ArrangementReservationsXtab.ReferenceNumber=@ReferenceNumber) AND (((@RESERVATIONCONFLINENUMBER=0) AND (ArrangementReservationsXtab.GuestNumber = @GuestNumber OR ((@PrevReferenceNumber <> @ReferenceNumber) AND (ArrangementReservationsXtab.GuestNumber=0)))) OR ((@RESERVATIONCONFLINENUMBER>0) AND (@GuestNumber>0) AND (ArrangementReservationsXtab.GuestNumber=@GuestNumber))) 
        AND NOT ArrangementLines.FK_ExDepartment IS NULL
        AND (ArrangementLines.WareNumber > 0) AND ArrangementLines.Price>0) 
        AND (WareGroups.WareType in (0, 1, 2)) -- 2 = rest, 1 = other, 0 = None
        AND ISNULL(ArrangementLines.PacketItemNumber, 0) = 0	
        AND not (ISNULL(Departments.Autocharge, 1) in (0) AND ArrangementLines.Date <= @SystemDateStr) -- Departments set as auto department must only be ahead in time. Never back in time hence it is resolved in transactions.		 
        AND ISDATE(ArrangementLines.Date) = 1
        GROUP BY ArrangementLines.Date, WareGroups.WareType, Departments.Autocharge, WareGroups.Payment, Hotel.CustomerNumber
      OPEN ExtraOnDayCur

      FETCH NEXT FROM ExtraOnDayCur INTO @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @HotelCustomerNumberFromArrangement
			 
      WHILE (@@FETCH_STATUS<>-1)
      BEGIN
        IF @TotalExtraOnDay <> 0
        BEGIN
          IF @WareType = 1
          BEGIN
            -- Store other Extra *****
            IF ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            BEGIN
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, 0, @TotalExtraOnDay,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 2, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            END
          END
          ELSE IF @WareType = 2
          BEGIN
            -- Store restaurant Extra *****
            IF ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            BEGIN
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, @TotalExtraOnDay, 0,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 2, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            END
          END
          ELSE IF @WareType = 0
          BEGIN
            IF @WarePayment = 7 -- ManualRoom
            BEGIN
                --print '4 Reservation Roomline EXTRA TurnOverRooms=' + convert(varchar(15), @TotalExtraOnDay)
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverHalls, NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, 0, 0, @TotalExtraOnDay, 0, 0, 0, 0, 0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 2, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            END
            ELSE IF @WarePayment = 8 -- ManualHalls
            BEGIN
              --print '5 Reservation Roomline EXTRA TurnOverHalls=' + convert(varchar(15), @TotalExtraOnDay)
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverHalls, NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, @TotalExtraOnDay, 0, 0, 0, 0,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 2, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            END
          END
        END
        FETCH NEXT FROM ExtraOnDayCur INTO @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @HotelCustomerNumberFromArrangement
      END
	         
      CLOSE ExtraOnDayCur
      DEALLOCATE ExtraOnDayCur
    END
    -- Store Extras data in CustomerOrdreBook section end *****
*/
    SET @PrevReferenceNumber = @ReferenceNumber 
    SET @PrevGuestNumber = @GuestNumber

    if not (@Status IN (7,8)) 
      SET @SomeNotCanceledRes = 1
  end -- if (@CurrentDateStr <= @DepartureDate)

  Fetch Next From ReservationCur Into @ReferenceNumber,@GuestNumber, @SegmentNumber, @Status, @CustomerNumberInTab, @ContactpersonCustomerNumber, @LineNumber, @HotelCustomerNumber
end

Close ReservationCur
Deallocate ReservationCur

--******* Reservation Conferenceline Section ***********
Declare ReservationCur Cursor SCROLL READ_ONLY For
  SELECT DISTINCT
  RESERVATIONS.ReferenceNumber,
  RESERVATIONS.GuestNumber,
  RESERVATIONS.MARKETSEGMENT,
  IsNull(RESERVATIONS.Status, 0),
  RESERVATIONADDRESS.Link,
  RESERVATIONADDRESS.ContactpersonCustomerNumber,
  RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER,
  isnull(Customer.CustomerNumber,-1),
  case when isnull(RESERVATIONCONFERENCELINE.LinkLineNumber, 0) > 0 then (select top 1 Plenum from RESERVATIONCONFERENCELINE rcl  WITH (NOLOCK) where rcl.ReservationConfLineNumber = RESERVATIONCONFERENCELINE.LinkLineNumber) else ISNULL(RESERVATIONCONFERENCELINE.Plenum, 0) end as Plenum, -- when conference line is linked to a main conferenceline like schema booking, then collect plenum field on main conferenceline
  isnull(RESERVATIONCONFERENCELINE.LinkLineNumber, -1) as LinkLineNumber
  FROM RESERVATIONADDRESSXTAB  WITH (NOLOCK) 
  INNER JOIN Reservations  WITH (NOLOCK) on RESERVATIONADDRESSXTAB.REFERENCENUMBER = RESERVATIONS.ReferenceNumber
    AND RESERVATIONADDRESSXTAB.GUESTNUMBER = RESERVATIONS.GuestNumber
    AND RESERVATIONS.ReferenceNumber > 0 
    AND RESERVATIONS.GuestNumber=0
    AND RESERVATIONS.Status<7
  INNER JOIN RESERVATIONADDRESS  WITH (NOLOCK) ON RESERVATIONADDRESSXTAB.ADDRESSNUMBER = RESERVATIONADDRESS.AddressNumber
    AND RESERVATIONADDRESS.Link>0 
  INNER JOIN RESERVATIONCONFERENCELINE  WITH (NOLOCK) ON RESERVATIONCONFERENCELINE.ReferenceNumber=RESERVATIONS.ReferenceNumber
  INNER JOIN ReservationMain  WITH (NOLOCK) on  RESERVATIONMAIN.ReferenceNumber=RESERVATIONS.ReferenceNumber
  LEFT OUTER JOIN ConferenceRoomTypes  WITH (NOLOCK) ON ConferenceRoomTypes.ConferenceRoomTypeNumber = RESERVATIONCONFERENCELINE.BookedConferenceRoomTypeNumber
  Left outer join Customer WITH (NOLOCK) ON isnull(ConferenceRoomTypes.HotelNumber, RESERVATIONMAIN.HOTELNUMBER) = Customer.HotelNumber 
    AND Customer.HotelNumber >= 0 
    AND Customer.CustomerTypeNumber = 7 
    AND ISNULL(Customer.MarkAsDeleted, 0) = 0
  LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) on resx.FK_ReferenceNumber = reservations.ReferenceNumber 
  LEFT OUTER JOIN reservations sub WITH (NOLOCK) on sub.ReferenceNumber = resx.FK_ReferenceNumberSub and sub.Status < 7 
  WHERE RESERVATIONCONFERENCELINE.DepartureDate >= @TodayDateStr 
  AND ((ISNULL(@DebugCustomerNumber, -1) = -1) OR (isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, RESERVATIONADDRESS.ADDRESSTYPE)) = @DebugCustomerNumber) or (isnull(RESERVATIONADDRESS.ContactpersonCustomerNumber,-1) = @DebugCustomerNumber))
  AND ((ISNULL(@DebugReferenceNumber, -1) = -1) OR (Reservations.ReferenceNumber = @DebugReferenceNumber))
  AND ((ISNULL(@DebugGuestNumber, -1) = -1) OR (Reservations.GuestNumber = @DebugGuestNumber))
  AND isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, RESERVATIONADDRESS.ADDRESSTYPE)) > 0
  AND ISNULL(RESERVATIONCONFERENCELINE.SchemePattern, 0) = 0
  AND (ISNULL(FK_ReferenceNumber, 0) = 0 OR @MainCourceResNotInclMIS_OrderBook = 0)
  order by RESERVATIONS.ReferenceNumber, Reservations.GuestNumber, RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER
Open ReservationCur

Fetch Next From ReservationCur Into @ReferenceNumber, @GuestNumber, @SegmentNumber, @Status, @CustomerNumberInTab, @ContactpersonCustomerNumber, @LineNumber, @HotelCustomerNumber, @Plenum, @LinkLineNumber

SET @PrevReferenceNumber = 0

While (@@FETCH_STATUS <> -1)
Begin
  -- rsCancelled, rsNoShow shall not be included in conference part of orderbook as long their is no Cxl and Nosh column for daymeeting and halls. 
  -- Turnover, pax, stays is set to 0 when cancelled or noshow.  
  
--  print '@HotelCustomerNumber=' + convert(char(2), @HotelCustomerNumber) + ' @LineNumber=' + convert(char(6), @LineNumber)
  --if (@Status < 7) 
  --Begin
  Select @ArrivalDate=ArrivalDate, @DepartureDate=DepartureDate, @Adults=Adults, @Children1=Children1, @Children2 = Children2, @Price=Price, @ArrivalTime=ArrivalTime, @DepartureTime = DepartureTime,
  @PriceOverwritten=PriceOverwritten, @ProductNumber=ProductNumber,@NumberOfRooms=NumberOfRooms, @ROOMNUMBER=ConferenceRoomNumber, @BookedConferenceRoomTypeNumber = BookedConferenceRoomTypeNumber
  From RESERVATIONCONFERENCELINE  WITH (NOLOCK) where RESERVATIONCONFLINENUMBER=@LineNumber

  if @ArrivalTime < @Arr24
    SET @ArrivalDate = Convert(Char(8),convert(DateTime,@ArrivalDate) - 1,112)

  if (Convert (DATETIME, @TodayDateStr) >= Convert (DATETIME, @ArrivalDate))
    SET @CurrentDateStr = @TodayDateStr
  else
    SET @CurrentDateStr = @ArrivalDate

  Set @CurrentDate = Convert (DATETIME, @CurrentDateStr)

  if IsNull(@BookedConferenceRoomTypeNumber,0)=0  SET @BookedConferenceRoomTypeNumber = 0

  if (@BookedConferenceRoomTypeNumber=0)
    SET @DepartureDate =  Convert (Char (8), Convert (DATETIME,@DepartureDate)-1, 112)

  if (@DepartureTime < @Arr24) AND (@BookedConferenceRoomTypeNumber>0)
    SET @DepartureDate = Convert(Char(8),convert(DateTime,@DepartureDate) - 1,112)

  if (@CurrentDateStr <= @DepartureDate)
  Begin
    if IsNull(@Price,0)=0 SET @Price = 0

    if IsNull(@NumberOfRooms,1)=1
      SET @NumberOfRooms = 1
    else if (@NumberOfRooms=0)
      SET @NumberOfRooms = 1

    if IsNull(@Adults,0)=0    Set  @Adults = 0
    if IsNull(@Children1,0)=0 Set  @Children1 = 0
    if IsNull(@Children2,0)=0 Set  @Children2 = 0

    While (@CurrentDateStr <= @DepartureDate)
    begin
      SET @EnviromentFee = 0
      begin
        if (@ProductNumber>0)
          Select @FixedPrice=FixedPrice from Products  WITH (NOLOCK) where ProductNumber=@ProductNumber
        else
          SET @FixedPrice = 0

        if ((@ProductNumber>0) AND @PriceOverWritten=0)
        begin
          Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)
          Set @ProductEndDate =  Convert (DATETIME,@DepartureDate)

          exec ProductPricesDay @ProductNumber,@ProductStartDate,@ProductEndDate, @CurrentDate, @BookedConferenceRoomTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon, @BillTextProduct, @BillTextAddOnProduct, @CalcPriceDay OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT  -- new
        end
        else
        begin 
          Set @CalcPriceDay = @Price*@NumberOfRooms
          if @FixedPrice = 0
            SET @CalcPriceDay = @CalcPriceDay * (@Adults+@Children1+@Children2)               
        end

        if isNull(@Addon,0)=0 SET @Addon = 0

        SET @NumberOfPax=(@Adults+@Children1+@Children2)*@NumberOfRooms
        SET @TotalPriceDay = @CalcPriceDay + @EnviromentFee  + @Addon 

        if isnull(@SegmentNumber,0) = 0 
          SET @SegmentNumber = @DefaultOrdrebookSegment
        if isnull(@HotelCustomerNumber, -1) = -1 and @MainHotelCustomerNumber <> -1 
          SET @HotelCustomerNumber = @MainHotelCustomerNumber --of

		   -- Store Halls/Daymeeting data in CustomerOrdreBook section start *****
        SET @NumberOfStay = 0
        IF @Plenum = 0
          SET @NumberOfPax = 0
        ELSE
        BEGIN
          IF (@CurrentDateStr = @ArrivalDate)-- First day?
            SET @NumberOfStay = @NumberOfRooms -- Only set number of stays when processing first day.     
        END

        if (@FixedPrice=0)
        begin                 
          if (@TotalPriceDay <> 0) or (@NumberOfPax <> 0) or (@NumberOfStay <> 0) -- Something to update?
          begin
            -- Store Daymeeting data in CustomerOrdreBook *****
            if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            begin 
              --print '6 TurnOverDaymeetings=' + convert(varchar(15), @TotalPriceDay) + ' @HotelCustomerNumber=' + convert(char(2),@HotelCustomerNumber)
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverDaymeetings,  NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @CurrentDateStr, @TotalPriceDay, @NumberOfPax, @NumberOfStay, 0, 0,0,0,0,0,0,0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, null, null, 0, 3, null, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end
          end
        end
        else -- Fast pris
        begin
          if (@TotalPriceDay <> 0) or (@NumberOfRooms <> 0) or (@NumberOfPax <> 0) -- Something to update?
          begin
            -- Store Halls data in CustomerOrdreBook *****
            if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            begin
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @CurrentDateStr, @TotalPriceDay, @NumberOfRooms, @NumberOfPax, 0, 0,0,0,0,0,0,0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, null, null, 0, 3, null, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end   
          end
        end
      end -- if (@Status< 7) --   rsCancelled

      Set @CurrentDate = @CurrentDate +1
      Set @CurrentDateStr =  Convert (Char (8), @CurrentDate, 112)
    end -- while(@CurrentDateStr <= @DepartureDate)

/*
    --When LinkLineNumber is greater than 0 then it is a "Sub conference line" of a SchemeBooking and can have Extras on it.		   
    if ((@PrevReferenceNumber <> @ReferenceNumber) or (@LinkLineNumber > 0))  AND (@Status <= 6)  -- OutOfHouse included for extras
    begin
      Declare ExtraOnDayCur Cursor Fast_Forward READ_ONLY For
        SELECT
          Sum(ArrangementLines.Pieces * ArrangementLines.Price),
          ArrangementLines.Date,
          WareGroups.WareType,
          WareGroups.Payment,
          IsNull(Hotel.CustomerNumber, -1)
        FROM ArrangementLines  WITH (NOLOCK) 
        INNER JOIN ArrangementReservationsXtab  WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber 
        INNER JOIN Ware  WITH (NOLOCK) ON ArrangementLines.WareNumber = Ware.WareNumber
        INNER JOIN WareGroups  WITH (NOLOCK) on WareGroups.WaregroupNumber = Ware.WareGroupNumber
        LEFT OUTER JOIN DEPARTMENTS  WITH (NOLOCK) on DEPARTMENTS.PK_Department = ArrangementLines.FK_ExDepartment	
        INNER JOIN Customer AS Hotel WITH (NOLOCK) ON Hotel.HotelNumber = Departments.HotelNumber
          AND Hotel.HotelNumber >= 0
          AND Hotel.CustomerTypeNumber = 7
          AND ISNULL(Hotel.MarkAsDeleted, 0) = 0
        WHERE ((ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber)  AND (ArrangementReservationsXtab.GuestNumber = @GuestNumber) AND NOT ArrangementLines.FK_ExDepartment IS NULL
        AND (ArrangementLines.WareNumber > 0) AND ArrangementLines.Price>0) 
        AND (WareGroups.WareType in (0, 1, 2)) -- 2 = rest, 1 = other, 0 = None
        AND not (isnull(DEPARTMENTS.Autocharge, 1) in (0) and ArrangementLines.Date <= @SystemDateStr) -- Departments set as auto department must only be ahead in time. Never back in time hence it is resolved in transactions.
        AND (WareGroups.Payment not in (7,8) Or ArrangementLines.Date > @SystemDateStr) --Manual room and manuel halls are included in transaction section
        group by ArrangementLines.Date, WareGroups.WareType, DEPARTMENTS.Autocharge, WareGroups.Payment, Hotel.CustomerNumber
      Open ExtraOnDayCur

      Fetch Next From ExtraOnDayCur into @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @HotelCustomerNumberFromArrangement 
			 
      WHILE (@@FETCH_STATUS<>-1)
      Begin
        if (@TotalExtraOnDay <> 0)
        begin
          if @WareType = 1
          begin
            -- Store other Extra *****
            if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            begin     
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverDaymeetings,  NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, 0, @TotalExtraOnDay,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 0, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end
          end
          else if @WareType = 2  --Restaurant
          begin
            -- Store restaurant Extra *****
            if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            begin 
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverDaymeetings,  NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, @TotalExtraOnDay, 0,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 0, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end
          end
          else if @WareType = 0
          begin
            if @WarePayment = 7 -- ManualRoom
            begin
              --print '10 Reservation Conferenceline EXTRA TurnOverRooms=' + convert(varchar(15), @TotalExtraOnDay)
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, 0, 0,@TotalExtraOnDay,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 7, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end
            else if @WarePayment = 8 -- ManualHalls
            begin
              --print '11 Reservation Conferenceline EXTRA TurnOverHalls=' + convert(varchar(15), @TotalExtraOnDay)
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, @TotalExtraOnDay, 0, 0, 0, 0,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 8, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end 
          end
        end
        Fetch Next From ExtraOnDayCur into @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @HotelCustomerNumberFromArrangement
      end
	         
      Close ExtraOnDayCur
      Deallocate ExtraOnDayCur
    end
*/
  end -- if (@CurrentDateStr <= @DepartureDate)
    
  SET @PrevReferenceNumber = @ReferenceNumber
      
  Fetch Next From ReservationCur Into @ReferenceNumber,@GuestNumber, @SegmentNumber, @Status, @CustomerNumberInTab, @ContactpersonCustomerNumber, @LineNumber, @HotelCustomerNumber, @Plenum, @LinkLineNumber
end --Reservation conferenceline section

Close ReservationCur
Deallocate ReservationCur

/*
--******* Only extra Section (no room, no hall) ***********
Declare ReservationCur Cursor SCROLL READ_ONLY For
  SELECT DISTINCT
  RESERVATIONS.ReferenceNumber,
  RESERVATIONS.MARKETSEGMENT,
  IsNull(RESERVATIONS.Status, 0),
  RESERVATIONADDRESS.Link,
  RESERVATIONADDRESS.ADDRESSTYPE,
  RESERVATIONADDRESS.ContactpersonCustomerNumber,
  isnull(Customer.CustomerNumber,-1)
  FROM RESERVATIONADDRESSXTAB  WITH (NOLOCK) 
  INNER JOIN Reservations  WITH (NOLOCK) on RESERVATIONADDRESSXTAB.REFERENCENUMBER = RESERVATIONS.ReferenceNumber
    AND RESERVATIONADDRESSXTAB.GUESTNUMBER = RESERVATIONS.GuestNumber
    AND RESERVATIONS.ReferenceNumber > 0 
    AND RESERVATIONS.GuestNumber=0
    AND RESERVATIONS.Status < 7
  INNER JOIN RESERVATIONADDRESS  WITH (NOLOCK) ON RESERVATIONADDRESSXTAB.ADDRESSNUMBER = RESERVATIONADDRESS.AddressNumber
    AND RESERVATIONADDRESS.Link>0 
  INNER JOIN ArrangementReservationsXtab x on x.ReferenceNumber = RESERVATIONS.ReferenceNumber
  INNER JOIN ArrangementLines al on x.ArrangementLineNumber = al.ArrangementLineNumber  
  INNER JOIN ReservationMain rm WITH (NOLOCK) on  rm.ReferenceNumber=RESERVATIONS.ReferenceNumber
  Left outer join Customer WITH (NOLOCK) ON rm.HOTELNUMBER = Customer.HotelNumber 
    AND Customer.HotelNumber >= 0 
    AND Customer.CustomerTypeNumber = 7 
    AND ISNULL(Customer.MarkAsDeleted, 0) = 0
  LEFT OUTER JOIN RESERVATIONCONFERENCELINE rc WITH (NOLOCK) on  rc.ReferenceNumber = rm.REFERENCENUMBER
  LEFT OUTER JOIN  RESERVATIONROOMLINEXTAB rr WITH (NOLOCK) on rr.ReferenceNumber = rm.REFERENCENUMBER
  WHERE IsNull(rc.ReferenceNumber, -1) = -1 -- to exclude res. with hall
  And IsNull(rr.ReferenceNumber, -1) = -1 -- to exclude res. with room
  And RESERVATIONS.DepartureDate >= @TodayDateStr 
  AND ((ISNULL(@DebugCustomerNumber, -1) = -1) OR (isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, RESERVATIONADDRESS.ADDRESSTYPE)) = @DebugCustomerNumber) or (isnull(RESERVATIONADDRESS.ContactpersonCustomerNumber,-1) = @DebugCustomerNumber))
  AND ((ISNULL(@DebugReferenceNumber, -1) = -1) OR (Reservations.ReferenceNumber = @DebugReferenceNumber))
  AND ((ISNULL(@DebugGuestNumber, -1) = -1) OR (Reservations.GuestNumber = @DebugGuestNumber))
  AND isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, RESERVATIONADDRESS.ADDRESSTYPE)) > 0
  order by RESERVATIONS.ReferenceNumber, RESERVATIONADDRESS.ADDRESSTYPE;
Open ReservationCur

Fetch Next From ReservationCur Into @ReferenceNumber, @SegmentNumber , @Status, @CustomerNumberInTab, @CustomerTypeNumber, @ContactpersonCustomerNumber, @HotelCustomerNumber

SET @PrevLineNumber = 0
SET @PrevReferenceNumber = 0

While (@@FETCH_STATUS <> -1)
Begin
  SET @TotalRestExtraOnDay = 0
  SET @TotalOtherExtraOnDay = 0

  if @ArrivalTime < @Arr24
    SET @ArrivalDate = Convert(Char(8),convert(DateTime,@ArrivalDate) - 1,112)

  if (Convert (DATETIME, @TodayDateStr) >= Convert (DATETIME, @ArrivalDate))
    SET @CurrentDateStr = @TodayDateStr
  else
    SET @CurrentDateStr = @ArrivalDate

  Set @CurrentDate = Convert (DATETIME, @CurrentDateStr)

  if (@CurrentDateStr <= @DepartureDate)
  Begin
    if (@PrevReferenceNumber <> @ReferenceNumber) AND (@Status <= 6)  -- OutOfHouse included for extras
    begin
      --store extra only
      Declare ExtraOnDayCur Cursor Fast_Forward READ_ONLY For
        SELECT
          Sum(ArrangementLines.Pieces * ArrangementLines.Price),
          ArrangementLines.Date,
          WareGroups.WareType,
          WareGroups.Payment,
          IsNull(Hotel.CustomerNumber, -1)
        FROM ArrangementLines  WITH (NOLOCK) 
        INNER JOIN ArrangementReservationsXtab  WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber 
        INNER JOIN Ware  WITH (NOLOCK) ON ArrangementLines.WareNumber = Ware.WareNumber
        INNER JOIN WareGroups  WITH (NOLOCK) on WareGroups.WaregroupNumber = Ware.WareGroupNumber
        LEFT OUTER JOIN DEPARTMENTS  WITH (NOLOCK) on DEPARTMENTS.PK_Department = ArrangementLines.FK_ExDepartment	
        INNER JOIN Customer AS Hotel WITH (NOLOCK) ON Hotel.HotelNumber = Departments.HotelNumber
          AND Hotel.HotelNumber >= 0
          AND Hotel.CustomerTypeNumber = 7
          AND ISNULL(Hotel.MarkAsDeleted, 0) = 0
        WHERE ((ArrangementReservationsXtab.ReferenceNumber = @ReferenceNumber)  AND (ArrangementReservationsXtab.GuestNumber = 0) AND NOT ArrangementLines.FK_ExDepartment IS NULL
        AND (ArrangementLines.WareNumber > 0) AND ArrangementLines.Price > 0) 
        AND (WareGroups.WareType in (0, 1, 2)) -- 2 = rest, 1 = other, 0 = None
        AND not (isnull(DEPARTMENTS.Autocharge, 1) in (0) and ArrangementLines.Date <= @SystemDateStr) -- Departments set as auto department must only be ahead in time. Never back in time hence it is resolved in transactions.
        AND (WareGroups.Payment not in (7,8) Or ArrangementLines.Date > @SystemDateStr) 
        group by ArrangementLines.Date, WareGroups.WareType, DEPARTMENTS.Autocharge, WareGroups.Payment, Hotel.CustomerNumber	
      Open ExtraOnDayCur

      Fetch Next From ExtraOnDayCur into @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @HotelCustomerNumberFromArrangement 
			 
      WHILE (@@FETCH_STATUS<>-1)
      Begin
        if (@TotalExtraOnDay <> 0)
        begin
          if @WareType = 1
          begin
            -- Store other Extra *****
            if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            begin     
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverDaymeetings,  NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, 0, @TotalExtraOnDay,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 0, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end
          end
          else if @WareType = 2  --Restaurant
          begin
            -- Store restaurant Extra *****
            if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
            begin 
              INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverDaymeetings,  NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
              VALUES (@CustomerNumberInTab, @SegmentNumber, @ExtraOnDay, 0, 0, 0, @TotalExtraOnDay, 0,0,0,0,0,0,0, @HotelCustomerNumberFromArrangement, 0, @Status, @ReferenceNumber, null, null, 0, 0, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
            end
          end
        end

        Fetch Next From ExtraOnDayCur into @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @HotelCustomerNumberFromArrangement
      end
	         
      Close ExtraOnDayCur
      Deallocate ExtraOnDayCur
    end       
  end -- if (@CurrentDateStr <= @DepartureDate)
    
  SET @PrevReferenceNumber = @ReferenceNumber
      
  Fetch Next From ReservationCur Into @ReferenceNumber, @SegmentNumber , @Status, @CustomerNumberInTab, @CustomerTypeNumber, @ContactpersonCustomerNumber, @HotelCustomerNumber
end --While
--******* Only extra Section end ***********

Close ReservationCur
Deallocate ReservationCur
*/
--******* Extras BEGIN ***********
DECLARE @LCustomerNumber INT
DECLARE @LSegment INT
DECLARE @LHotelCustomerNumber INT
DECLARE @LStatus INT
DECLARE @LReferenceNumber INT
DECLARE @LContactPersonCustomerNumber INT
DECLARE @LGuestNumber INT

DECLARE ExtraCur CURSOR FAST_FORWARD READ_ONLY FOR
  SELECT DISTINCT
  ArrangementLines.Pieces * ArrangementLines.Price, ArrangementLines.Date, WareGroups.WareType, WareGroups.Payment, 
  Reservations.ReferenceNumber,
  Reservations.GuestNumber,
  Reservations.MarketSegment,
  Reservations.Status,
  ISNULL(ReservationAddress.Link, resaddMain.Link) as Link11,
  ReservationAddress.ContactpersonCustomerNumber,
  ISNULL(Customer.CustomerNumber,-1)
  FROM ReservationAddressXtab WITH (NOLOCK)
  INNER JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXtab.AddressNumber
  INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = ReservationAddressXtab.ReferenceNumber
    AND Reservations.GuestNumber = ReservationAddressXtab.GuestNumber
    AND Reservations.Referencenumber > 0 
    AND Reservations.DepartureDate >= @TodayDateStr 
    AND Reservations.Status < 7
  INNER JOIN ReservationMain WITH (NOLOCK) ON ReservationMain.Referencenumber = Reservations.ReferenceNumber 
  INNER JOIN Customer RealCust WITH (NOLOCK) ON RealCust.CustomerNumber = ReservationAddress.Link
  INNER JOIN ArrangementReservationsXtab WITH (NOLOCK) ON ArrangementReservationsXtab.ReferenceNumber = Reservations.ReferenceNumber
    AND ArrangementReservationsXtab.GuestNumber = Reservations.GuestNumber
  INNER JOIN ArrangementLines WITH (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
    AND NOT ArrangementLines.FK_ExDepartment IS NULL
    AND ArrangementLines.WareNumber > 0
    AND ArrangementLines.Price>0
    AND ISNULL(ArrangementLines.PacketItemNumber, 0) = 0	
    AND ISDATE(ArrangementLines.Date) = 1
    AND ArrangementLines.Date > @SystemDateStr
  INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = ArrangementLines.WareNumber
  INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WaregroupNumber = Ware.WareGroupNumber
    AND WareGroups.WareType in (0, 1, 2) -- 2 = rest, 1 = other, 0 = None
  LEFT OUTER JOIN Departments WITH (NOLOCK) ON Departments.PK_Department = ArrangementLines.FK_ExDepartment
    AND Departments.Autocharge = 1
  LEFT OUTER JOIN Customer WITH (NOLOCK) ON Customer.CustomerNumber = ReservationMain.FKCustomerHotel
  LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) ON resx.FK_ReferenceNumber = Reservations.ReferenceNumber 
  LEFT OUTER JOIN Reservations sub WITH (NOLOCK) ON sub.ReferenceNumber = resx.FK_ReferenceNumberSub 
    AND sub.Status < 7 
  LEFT OUTER JOIN ReservationAddressXtab resAddAtabMain WITH (NOLOCK) ON resAddAtabMain.REFERENCENUMBER = Reservations.ReferenceNumber
    and resAddAtabMain.GuestNumber = 0
    and resAddAtabMain.AddressTypeNumber = ReservationAddressXtab.AddressTypeNumber
  LEFT OUTER JOIN ReservationAddress resaddMain WITH (NOLOCK) ON resaddMain.AddressNumber = resAddAtabMain.AddressNumber
  LEFT OUTER JOIN Customer readcustMain WITH (NOLOCK) ON readcustMain.CustomerNumber = resaddMain.Link
  WHERE 1=1
  AND ((ISNULL(@DebugCustomerNumber, -1) = -1) OR (ISNULL(ReservationAddress.Link, dbo.GetMainReservationLinkNumber (Reservations.ReferenceNumber, ReservationAddress.AddressType)) = @DebugCustomerNumber) or (isnull(ReservationAddress.ContactpersonCustomerNumber, -1) = @DebugCustomerNumber))
  AND ((ISNULL(@DebugReferenceNumber, -1) = -1) OR (Reservations.ReferenceNumber = @DebugReferenceNumber))
  AND ((ISNULL(@DebugGuestNumber, -1) = -1) OR (Reservations.GuestNumber = @DebugGuestNumber))
  AND ISNULL(ReservationAddress.Link, dbo.GetMainReservationLinkNumber (Reservations.ReferenceNumber, ReservationAddress.AddressType)) > 0
  AND (ISNULL(FK_ReferenceNumber, 0) = 0 OR @MainCourceResNotInclMIS_OrderBook = 0)
  AND ISNULL(readcustMain.CustomerNumber, 0) > 0
OPEN ExtraCur

FETCH NEXT FROM ExtraCur INTO @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @LReferenceNumber, @LGuestNumber, @LSegment, @LStatus, @LCustomerNumber, @LContactPersonCustomerNumber, @LHotelCustomerNumber
			 
WHILE (@@FETCH_STATUS<>-1)
BEGIN
  IF ISNULL(@LSegment, 0) = 0 
    SET @LSegment = @DefaultOrdrebookSegment
  IF @TotalExtraOnDay <> 0
  BEGIN
    IF @WareType = 1
    BEGIN
      -- Store other Extra *****
      INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
      VALUES (@LCustomerNumber, @LSegment, @ExtraOnDay, 0, 0, 0, 0, @TotalExtraOnDay, 0, 0, 0, 0, 0, 0, @LHotelCustomerNumber, 0, @LStatus, @LReferenceNumber, NULL, NULL, 0, 2, @WareType, @LContactPersonCustomerNumber, @LGuestNumber, 0)
    END
    ELSE IF @WareType = 2
    BEGIN
      -- Store restaurant Extra *****
      INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
      VALUES (@LCustomerNumber, @LSegment, @ExtraOnDay, 0, 0, 0, @TotalExtraOnDay, 0, 0, 0, 0, 0, 0, 0, @LHotelCustomerNumber, 0, @LStatus, @LReferenceNumber, NULL, NULL, 0, 2, @WareType, @LContactPersonCustomerNumber, @LGuestNumber, 0)
    END
    ELSE IF @WareType = 0
    BEGIN
      IF @WarePayment = 7 -- ManualRoom
      BEGIN
        INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverHalls, NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
        VALUES (@LCustomerNumber, @LSegment, @ExtraOnDay, 0, 0, 0, 0, 0, @TotalExtraOnDay, 0, 0, 0, 0, 0, @LHotelCustomerNumber, 0, @LStatus, @LReferenceNumber, NULL, NULL, 0, 2, @WareType, @LContactPersonCustomerNumber, @LGuestNumber, 0)
      END
      ELSE IF @WarePayment = 8 -- ManualHalls
      BEGIN
        INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber, DateForValue, TurnOverHalls, NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
        VALUES (@LCustomerNumber, @LSegment, @ExtraOnDay, @TotalExtraOnDay, 0, 0, 0, 0,0,0,0,0,0,0, @LHotelCustomerNumber, 0, @LStatus, @LReferenceNumber, NULL, NULL, 0, 2, @WareType, @LContactPersonCustomerNumber, @LGuestNumber, 0)
      END
    END
  END
  FETCH NEXT FROM ExtraCur INTO @TotalExtraOnDay, @ExtraOnDay, @WareType, @WarePayment, @LReferenceNumber, @LGuestNumber, @LSegment, @LStatus, @LCustomerNumber, @LContactPersonCustomerNumber, @LHotelCustomerNumber
END
	         
CLOSE ExtraCur
DEALLOCATE ExtraCur
--******* Extras END   ***********

--******* Transactions Section ***********
CREATE TABLE #AutoUsers( [Number] [int] not null) 
Insert into #AutoUsers SELECT UserIdNumber FROM Personel  WITH (NOLOCK) WHERE UserTypeNumber = 3 or UserTypeNumber = 4

Declare @TransactionNumber Int --For debug

Declare TransCur Cursor Fast_Forward READ_ONLY For 
  Select distinct
    Transactions.DateStamp,  --OriginalDate, 
    IsNull(Reservations.Status, 0), 
    RESERVATIONS.ReferenceNumber, 
    Transactions.FolioNumber, 
    (SELECT TOP 1 I.BillNumber FROM dbo.Invoice I (NOLOCK) 
    INNER JOIN dbo.InvoiceTransactionXTab ITX (NOLOCK) ON I.PkInvoice = ITX.FkInvoice
    WHERE ITX.FkTransaction = Transactions.TransactionNumber AND I.CancelDate IS NULL AND I.ReceiptType <> 0
    ORDER BY I.PkInvoice DESC), 
    case when /*Transactions.MovedDeleted = 1 and*/ F.ReferenceNumber = FOLIOS.ReferenceNumber and Transactions.UserIDNumber not in (select * from #AutoUsers WITH (NOLOCK)) then 1 else 0 end AS InternalRefMove,
    case when Transactions.MovedDeleted = 1 then 1 else 0 end AS OrderBookCorrection,
    case when Transactions.MovedDeleted = 0 and Transactions.MovedFolioNr > 0 then 1 else 0 end AS OrderBookMovedTo,
    Case when Transactions.Debit=0 then transactions.Priceoverwrite*-1 else transactions.Priceoverwrite end AS TotalSum, 
    case when Reservations.MarketSegment is null then Customer.SegmentNumber else Reservations.MarketSegment end,
    --Reservations.MarketSegment, 
    isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, 0)), 
    RESERVATIONADDRESS.ContactpersonCustomerNumber, 
    WareGroups.Payment,   --@WarePayment
    WareGroups.WareType,  --@WareType
    Transactions.HotelCustomerNumber, 
    transactions.ProductNumber,
    isnull(Transactions.PAXadult,0),
    isnull(Transactions.PAXchild1,0),
    isnull(Transactions.PAXchild2,0),
    Transactions.Pieces,
    case when Transactions.UserIDNumber not in (select * from #AutoUsers WITH (NOLOCK)) then 1 else 0 end AS ManuelUser,
    Transactions.MovedFolioNr,
    Transactions.TransactionNumber,  --For debug
    Transactions.GuestNumber
  from transactions  WITH (NOLOCK) 
  inner join Folios  WITH (NOLOCK) on Folios.FolioNumber = Transactions.FolioNumber
  inner join RESERVATIONADDRESS  WITH (NOLOCK) on RESERVATIONADDRESS.AddressNumber = Folios.ReservationAddressNumber
  left outer join Reservations  WITH (NOLOCK) on Folios.ReferenceNumber  = Reservations.ReferenceNumber AND Folios.GuestNumber  = Reservations.GuestNumber and Reservations.Status>=5
  inner join Ware  WITH (NOLOCK) on Ware.WareNumber = Transactions.WareNumber
  inner join WareGroups  WITH (NOLOCK) on WareGroups.WareGroupNumber = Ware.WareGroupNumber
  LEFT OUTER JOIN FOLIOS AS F  WITH (NOLOCK) ON F.FolioNumber = Transactions.MovedFolioNr
  LEFT OUTER JOIN Customer WITH (NOLOCK) ON Customer.CustomerNumber = isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, 0))
  LEFT OUTER JOIN ReservationReservationXtab resX WITH (NOLOCK) on resx.FK_ReferenceNumber = reservations.ReferenceNumber 
  LEFT OUTER JOIN reservations sub WITH (NOLOCK) on sub.ReferenceNumber = resx.FK_ReferenceNumberSub and sub.Status < 7 
  where 
  (transactions.Showonbillflag = 1) and (isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, 0)) > 0)--AND (RESERVATIONADDRESS.Link > 0) 
  AND NOT(WareGroups.Payment in (1) OR (@IncludeProvisionbackward=0 AND WareGroups.Payment=5)) 
  AND ((ISNULL(@DebugCustomerNumber, -1) = -1) OR (isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (RESERVATIONS.ReferenceNumber, 0)) = @DebugCustomerNumber) or (isnull(RESERVATIONADDRESS.ContactpersonCustomerNumber,-1) = @DebugCustomerNumber))  
  AND (ISNULL(FK_ReferenceNumber, 0) = 0 OR @MainCourceResNotInclMIS_OrderBook = 0)
  AND CAST(Transactions.DateStamp AS DATE) <= @SystemDateDT
  AND CAST(Transactions.DateStamp AS DATE) >= @TodayDateDT
Open TransCur

Fetch Next From TransCur into @TransDateDT, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @InternalRefMove, @OrderBookCorrection, @OrderBookMovedTo, @Totalsum, @SegmentNumber, @CustomerNumberInTab, @ContactpersonCustomerNumber, @WarePayment, @WareType, @HotelCustomerNumber, @ProductNumber,@Adults, @Children1, @Children2, @Pieces, @ManuelUser, @MovedFolioNumber, @TransactionNumber, @GuestNumber

WHILE (@@FETCH_STATUS<>-1)
Begin
  SET @TransDate = CONVERT(CHAR(8), @TransDateDT, 112)
  if isnull(@HotelCustomerNumber, -1) = -1 and @MainHotelCustomerNumber <> -1 SET @HotelCustomerNumber = @MainHotelCustomerNumber --of
  if isnull(@SegmentNumber,0)=0 SET @SegmentNumber = @DefaultOrdrebookSegment
  if isnull(@WareType,-1)=-1 SET @WareType = 1

  IF ISNULL(@Status, -1) = -1
    SET @Status = -1

  -- Store Transactions in CustomerOrdreBook *****
  if ((ISNULL(@DebugCustomerNumber, -1) = -1) or ((@DebugCustomerNumber = @CustomerNumberInTab) or (@DebugCustomerNumber = @ContactpersonCustomerNumber)))
  begin
    Declare @RefNoForFolio int
    Declare @RefNoForMovedFolio int
    select @RefNoForFolio      = ReferenceNumber FROM FOLIOS WITH (NOLOCK) WHERE FolioNumber=@FolioNumber
    select @RefNoForMovedFolio = ReferenceNumber FROM FOLIOS WITH (NOLOCK) WHERE FolioNumber=@MovedFolioNumber
    -- HotelSetup "EnableOrderBookWithTransactions" = 1: Moved payments from transactions included.
    -- Correction (moved transaction): Don't include the original transaction.
    -- When moving between linked customers (from company to guest or from guest to company), no transaction is included
   		
    if @WarePayment = 2 and (  -- auto rooms
      (@EnableOrderBookWithTransactions = 1 and (@RefNoForFolio <> @RefNoForMovedFolio)) 
      or (@OrderBookCorrection=1 and IsNull(@MovedFolioNumber, 0) = 0 and (@ManuelUser = 1)) --deleted. Only manual user because the records marked correction and nightAudit originates from the reservation
      or (@OrderBookCorrection=1 and @ManuelUser = 1)  --Moved from
      or (@OrderBookMovedTo=1 and @ManuelUser = 1))    --Moved to
    begin
      if (@InternalRefMove = 1)
      begin
        -- if internal ref move and folio has a different customernumber then the turnover must be written.
        if not Exists (
          select Top 1 
          isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (Folios.Referencenumber, 0)) as CustomerNumber 
          from Folios WITH (NOLOCK)  
          inner join RESERVATIONADDRESS WITH (NOLOCK) on RESERVATIONADDRESS.AddressNumber = Folios.ReservationAddressNumber
          where FolioNumber = @MovedFolioNumber and isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (Folios.Referencenumber, 0)) = @CustomerNumberInTab
        ) 
        Set @InternalRefMove = 0				
      end		
      if (@InternalRefMove = 1)
      begin
				-- If Auto Room transaction moved from one folio to another on the same reference number, then ignore and don´t store in orderbook. The
				-- turnover is allready written from the reservation.
        GOTO Skip
      end
      else
      begin
        -- If Auto Rooms, then only consider turnover. Pcs, Pax, stays, cxl, NoShow are 0.
        INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
        VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate, @Totalsum, 0,0,0,0,0,0,0,0,0,0,0,0, 0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
      end
    end
    else if (@WarePayment = 7) -- ManualRooms
    begin
      SET @Pieces = isnull(@Pieces, 0)
      if (@ProductNumber <= 0)
      begin
        SET @Adults = 0
        SET @Children1 = 0 
        SET @Children2 = 0
        SET @Pieces = 0			
      end
      INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
      VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate, @Totalsum, @Pieces,@Pieces*(@Adults+@Children1+@Children2),@Pieces,0,0,0,0,0,0,0,0,0, 0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, @GuestNumber, 0)
    end
    else if @WarePayment = 3 and (  -- auto halls
      (@EnableOrderBookWithTransactions = 1 and (@RefNoForFolio <> @RefNoForMovedFolio)) 
      or (@OrderBookCorrection=1 and IsNull(@MovedFolioNumber, 0) = 0 and (@ManuelUser = 1)) --deleted. Only manual user because the records marked correction and nightAudit originates from the reservation
      or (@OrderBookCorrection=1 and @ManuelUser = 1)
      or (@OrderBookMovedTo=1 and @ManuelUser = 1))
      or (@WarePayment = 8 /*ManualHalls*/ 
    )
    begin
      if (@InternalRefMove = 1)
      begin
        -- if internal ref move and folio has a different customernumber then the turnover must be written.
        if not Exists (
          select Top 1 
          isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber(Folios.Referencenumber, 0)) as CustomerNumber 
          from Folios WITH (NOLOCK)  
          inner join RESERVATIONADDRESS WITH (NOLOCK) on RESERVATIONADDRESS.AddressNumber = Folios.ReservationAddressNumber
          where FolioNumber = @MovedFolioNumber and isnull(RESERVATIONADDRESS.Link , dbo.GetMainReservationLinkNumber (Folios.Referencenumber, 0)) = @CustomerNumberInTab
        ) 
          Set @InternalRefMove = 0				
      end		
      if (@InternalRefMove = 1)
      begin
        -- If Auto Hall transaction moved from one folio to another on the same reference number, then ignore and don´t store in orderbook. The
        -- turnover is allready written from the reservation.
        GOTO Skip
      end 
      else
      begin
        SET @Pieces = isnull(@Pieces, 0)
        if (@WarePayment = 3) -- If Auto Halls, then only consider turnover. Reset pax and pieces.
        begin
          SET @FixedPrice = 0
          SET @Adults = 0
          SET @Children1 = 0 
          SET @Children2 = 0
          SET @Pieces = 0			
        end
        if (@ProductNumber <= 0)
        begin
          SET @FixedPrice = 0
          SET @Adults = 0
          SET @Children1 = 0 
          SET @Children2 = 0
          SET @Pieces = 0
        end
        else
          Select @FixedPrice=FixedPrice from Products  WITH (NOLOCK) where ProductNumber = @ProductNumber
                     
        if @FixedPrice = 0	-- Daymeetings
        begin
          -- When Daymeeting, Pieces is the same as Pax * stay, therefore to find Number of stay we must divide with pax
          Set @NumberOfStay = 0 
          Set @NumberOfPax = @Pieces
          if (@Adults+@Children1+@Children2) > 0
            Set @NumberOfStay = @Pieces/(@Adults+@Children1+@Children2)
          INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
          VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate, 0,0,0,0,0,0, @Totalsum,@NumberOfPax,@NumberOfStay,0,0,0,0, 0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, null, 0)			
        end
        else
        begin	-- Halls
          Set @NumberOfHalls = @Pieces
          Set @NumberOfPax = @Pieces*(@Adults+@Children1+@Children2)			
          INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
          VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate, 0,0,0,0,0,0,0,0,0, @Totalsum,@NumberOfHalls,@NumberOfPax,0, 0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, null, 0)
        end
      end
    end
    else if @WarePayment = 5 And @IncludeProvisionbackward = 1 And @WareType <> 0 --Provisions, discount
    begin
      --MISType på Provision varegruppen bestemmer, hvor rabat gemmes
      Declare @TORestaurant Money, @TOOther Money
      If @WareType = 1
      Begin
        Set @TORestaurant = 0
        Set @TOOther = @TotalSum
      End
      If @WareType = 2
      Begin
        Set @TORestaurant = @TotalSum
        Set @TOOther = 0
      End
      INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, 
        NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, 
        WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
      VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @TORestaurant, @TOOther, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, null, 0)
    end 
    else if (@WareType = 1) -- Other
    begin 
      INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue,TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
      VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate,0,0,0,0,0,0,0,0,0,0,0,0,0, @Totalsum, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, null, 0)
    end 
    else if (@WareType = 2) -- Restaurant
    begin 
      INSERT INTO CustomerOrdreBook (CustomerNumber, SegmentNumber,DateForValue, TurnOverRooms, NumberOfNightRooms, NumberOfPaxRooms, NumberOfStaysRooms, NumberOfCXLRooms, NumberOfNoShowRooms, TurnOverDaymeetings, NumberOfPaxDaymeetings, NumberOfStaysDaymeetings, TurnOverHalls,  NumberOfHalls, NumberOfPaxHalls, TurnOverRestaurant, TurnOverOther, HotelCustomerNumber, BonusPoints, ReservationStatus, ReferenceNumber, FolioNumber, InvoiceNumber, Correction, WarePayment, WareType, ContactpersonCustomerNumber, GuestNumber, ReadOnly)
      VALUES (@CustomerNumberInTab, @SegmentNumber, @TransDate, 0,0,0,0,0,0,0,0,0,0,0,0, @Totalsum, 0, @HotelCustomerNumber, 0, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @OrderBookCorrection, @WarePayment, @WareType, @ContactpersonCustomerNumber, null, 0)
    end 
  end
  -- *****************
  Skip:
  Fetch Next From TransCur Into @TransDateDT, @Status, @ReferenceNumber, @FolioNumber, @InvoiceNumber, @InternalRefMove, @OrderBookCorrection, @OrderBookMovedTo, @Totalsum, @SegmentNumber, @CustomerNumberInTab, @ContactpersonCustomerNumber, @WarePayment, @WareType, @HotelCustomerNumber, @ProductNumber, @Adults, @Children1, @Children2, @Pieces, @ManuelUser, @MovedFolioNumber, @TransactionNumber, @GuestNumber
End 

Close TransCur
Deallocate TransCur

Drop TABLE #AutoUsers
DROP TABLE #PacketInfo
if @NightAuditRunning = 1
  Update Hotelsetup set KeyValue = @SystemDateStr where Searchkey = 'LastOrderBookUpdate'