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

/*
  Changes:
    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 Integer
Declare @EnviromentFee Money
Declare @AllocatedTypeNumber Integer
Declare @BookedTypeNumber Integer

Declare @ProductStartDate DateTime
Declare @ProductEndDate   DateTime

Declare @StarProduct Bit

Declare @CustomerNumberInTab int
Declare @CustomerNumber int
Declare @MainHotelCustomerNumber int

Declare @FixedPrice Bit

Declare @PrevLineNumber int

Declare @PriceOverwritten Bit
Declare @Price Money
Declare @TotalPriceDay Money
Declare @FirstPrice1 Money
Declare @ProductNumber Integer

Declare @PriceOverwritten2 Bit
Declare @FirstPrice2 Money
Declare @Day2 SmallInt
Declare @ProductNumber2 Integer

Declare @PriceOverwritten3 Bit
Declare @FirstPrice3 Money
Declare @Day3 SmallInt
Declare @ProductNumber3 Integer

Declare @PriceOverwritten4 Bit
Declare @FirstPrice4 Money
Declare @Day4 SmallInt
Declare @ProductNumber4 Integer

Declare @TempSegmentNumber 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 @CustomerTypeNumber 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  @TempReferenceNumber int
Declare  @TempGuestNumber 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 @SomeCanceledRes bit
Declare @SomeNotCanceledRes bit
Declare @NumberOfStayHasBeenSet bit

Declare @ContactpersonCustomerNumber int

Declare @PrevStatus smallint

Declare @AddonIfPriceOverwritten bit

Declare @TotalRestExtraOnDay money
Declare @TotalOtherExtraOnDay money

Declare @TotalExtraOnDay money

Declare @RESERVATIONCONFLINENUMBER int

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 Integer

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 @CentralBookingType smallint

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 --Main course reservation not included in MIS and order book

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

if (@CalcOrderBookFromDate is null) SET @CalcOrderBookFromDate	= '' 
if (@DebugCustomerNumber is null)	SET @DebugCustomerNumber	= -1
if (@DebugReferenceNumber is null)	SET @DebugReferenceNumber	= -1
if (@DebugGuestNumber is null)		SET @DebugGuestNumber		= -1

Select @EnableOrderBookWithTransactions = KeyValue from HotelSetUp  WITH (NOLOCK) Where SearchKey='EnableOrderBookWithTransactions' --SG 20121128
Set @EnableOrderBookWithTransactions = IsNull(@EnableOrderBookWithTransactions, 0);
  
Select @CentralBookingType = Convert(Integer,isnull(KeyValue,0)) from HotelSetup  WITH (NOLOCK) where searchkey like '%CentralBookingType%'
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
if isnull(@NightAuditRunning,0)=0 SET @NightAuditRunning = 0

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

if isnull(@IncludeDayroomsInSoldRooms,0) = 0 SET @IncludeDayroomsInSoldRooms = 0


if ((@DayroomsLaterThanTime = '') OR (@DayroomsLaterThanTime is null))  SET @DayroomsLaterThanTime = '13:00' -- hvis empty skal sættes til 13:00

Select @OnePersonPaysForAll = CONVERT(Bit,KeyValue) from HotelSetUp  WITH (NOLOCK)  Where  SearchKey='OnePersonPaysForAll'
if isnull(@OnePersonPaysForAll,0)=0 SET @OnePersonPaysForAll=0

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

Select @DefaultOrdrebookSegment = CONVERT(Integer,KeyValue) from HotelSetUp  WITH (NOLOCK)  Where  SearchKey='DefaultOrdrebookSegment'
if isnull(@DefaultOrdrebookSegment,0)=0 SET @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  -- Only one record
SET @SystemDateDT = CONVERT(DATE, @SystemDateStr, 112)

If @CalcOrderBookFromDate = '' 
Begin
  If @NightAuditRunning = 0
  Begin
    SET @TodayDateStr = @SystemDateStr
  End 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
    Begin
      insert into Hotelsetup (Searchkey,KeyValue) values ('LastOrderBookUpdate',@SystemDateStr)
    End 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
      Begin
        SET @TodayDateStr = Convert(Char(8), @NextDay, 112)
      End  
    End
  End
End Else
Begin
  SET @TodayDateStr = @CalcOrderBookFromDate
End
-- Limit the recalculation date 
exec dbo.GetLatestDeletedBefore @LatestDeletedBefore OUTPUT
if @TodayDateStr < @LatestDeletedBefore
  set @TodayDateStr = @LatestDeletedBefore

SET @TodayDateDT = CONVERT(DATE, @TodayDateStr, 112) 

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'
if isnull(@AddonIfPriceOverwritten,0)=0 SET @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 ReferenceNumber,
   RESERVATIONS.GuestNumber,
   RESERVATIONS.MARKETSEGMENT,
   CASE WHEN RESERVATIONS.GuestNumber=0  THEN Res2.Status ELSE RESERVATIONS.Status END as Status,
   isnull(RESERVATIONADDRESS.Link , resaddMain.LINK) as Link11,
   --RESERVATIONADDRESS.ADDRESSTYPE,
   RESERVATIONADDRESS.ContactpersonCustomerNumber,
   RESERVATIONROOMLINEXTAB.LineNumber,
   Case when RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER>0 then 1 else 0 end,
   isnull(Customer.CustomerNumber,-1)
FROM RESERVATIONADDRESSXTAB  WITH (NOLOCK)
 INNER JOIN RESERVATIONADDRESS  WITH (NOLOCK) ON RESERVATIONADDRESSXTAB.ADDRESSNUMBER = RESERVATIONADDRESS.AddressNumber
 INNER JOIN RESERVATIONS  WITH (NOLOCK) ON RESERVATIONADDRESSXTAB.REFERENCENUMBER = RESERVATIONS.ReferenceNumber 
   AND RESERVATIONADDRESSXTAB.GUESTNUMBER = RESERVATIONS.GuestNumber
   AND RESERVATIONS.Referencenumber > 0 
   AND RESERVATIONS.DepartureDate >= @TodayDateStr 
 INNER JOIN RESERVATIONROOMLINEXTAB  WITH (NOLOCK) ON RESERVATIONS.ReferenceNumber = RESERVATIONROOMLINEXTAB.ReferenceNumber AND Reservations.GuestNumber = RESERVATIONROOMLINEXTAB.GuestNumber
 INNER JOIN RESERVATIONROOMLINE WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.LINENUMBER = RESERVATIONROOMLINE.LINENUMBER
 
 INNER JOIN RESERVATIONS Res2 WITH (NOLOCK) on res2.GuestNumber = RESERVATIONROOMLINEXTAB.GuestNumber and Res2.ReferenceNumber = RESERVATIONROOMLINEXTAB.ReferenceNumber
 
 INNER JOIN RESERVATIONMAIN  WITH (NOLOCK) ON RESERVATIONMAIN.Referencenumber =  RESERVATIONS.ReferenceNumber 
 INNER JOIN Customer RealCust WITH (NOLOCK) ON RealCust.CustomerNumber = RESERVATIONADDRESS.LINK
 Left Outer Join RESERVATIONCONFERENCELINE  WITH (NOLOCK) ON RESERVATIONS.ReferenceNumber=RESERVATIONCONFERENCELINE.ReferenceNumber 
 LEFT OUTER JOIN dbo.Rooms  WITH (NOLOCK) ON ReservationRoomLine.RoomNumber = Rooms.RoomNumber
 LEFT OUTER JOIN dbo.RoomTypes  WITH (NOLOCK) ON ReservationRoomLine.BookedTypeNumber = RoomTypes.RoomTypeNumber
 Left outer join Customer WITH (NOLOCK) ON isnull(RoomTypes.HotelNumber, RESERVATIONMAIN.HOTELNUMBER) = Customer.HotelNumber AND Customer.HotelNumber >= 0 AND Customer.CustomerTypeNumber = 7 AND @CentralBookingType = 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 
 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
  ((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                 --not a main course res.
              OR @MainCourceResNotInclMIS_OrderBook = 0) --incl main course res.

  AND ISNULL(readcustMain.CustomerNumber, 0) > 0
  --EventsEnableCommonNamelist: Common namelist between Halls and Rooms. Currently only Maersk Svendborg (2015-04-14)    
  AND (RESERVATIONS.GuestNumber = RESERVATIONROOMLINEXTAB.GuestNumber or (RESERVATIONS.GuestNumber = 0 AND dbo.GetHotelSetupKeyValue ('EventsEnableCommonNamelist', isnull(Customer.CustomerNumber,-1)) = 1))
    
Order by  RESERVATIONS.ReferenceNumber,
          Link11,--isnull(RESERVATIONADDRESS.Link , resaddMain.LINK),
          RESERVATIONS.GUESTNUMBER, 
          RESERVATIONROOMLINEXTAB.LineNumber, 
          CASE WHEN RESERVATIONS.GuestNumber=0  THEN Res2.Status ELSE RESERVATIONS.Status END--, 
          --RESERVATIONADDRESS.ADDRESSTYPE

Open ReservationCur

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

While (@@FETCH_STATUS <> -1)
Begin
  Set @Status = IsNull(@Status, 0)
  SET @TotalRestExtraOnDay = 0
  SET @TotalOtherExtraOnDay = 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
    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
    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)) --SG 20140709: CR 074196 
  
  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 @NumberOfStayHasBeenSet = 0
      SET @SomeNotCanceledRes = 0
    end 

    if (@LinkedGuest=0)  AND ((@PrevReferenceNumber <> @ReferenceNumber) OR (@PrevGuestNumber <> @GuestNumber))
      SET @PrevStatus = -1

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

    SET @TempReferenceNumber = @ReferenceNumber 
    SET @TempGuestNumber = @GuestNumber
    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 @TempGuestNumber>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 @TempGuestNumber>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)
			   begin
			     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 (@CurrentDateStr = @DepartureDate) AND (@DepartureDate <> @ArrivalDate)
				   SET @PriceProduct1 = 0
			     else
			     begin
				   if @AddonIfPriceOverwritten = 1
				   begin
	  --                   exec CalcAddonPrice 0, @CurrentDate, 1, @Adults, @Children1, @Children2, @ProductNumber, @AllocatedTypeNumber, @Addon1 OUTPUT
				     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 -- StartProduct
		     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

			   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
				     Set @ProductStartDate   = Convert (DATETIME, @ArrivalDate)+@Day2-1
				     Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)

				     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
			  end
			  else
			  Begin
			    if ((@CurrentDate>=(Convert (DATETIME, @ArrivalDate)+@Day2-1)) AND (@CurrentDate<(Convert (DATETIME, @ArrivalDate)+@Day3-1))) AND (@CurrentDate <> CONVERT(DATETIME, @DepartureDate))
			    Begin
				  if (@PriceOverWritten2=0) 
				  Begin
				    Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day2-1
				    Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day3-1

				    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
				  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
					  Set @ProductStartDate   = (Convert (DATETIME,@ArrivalDate)+ @Day3-1)
					  Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)

					  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
			    end
			    else
			    begin
				  if ((@CurrentDate>=(Convert (DATETIME,@ArrivalDate)+ @Day3-1)) AND (@CurrentDate<(Convert (DATETIME,@ArrivalDate)+ @Day4-1))) AND (@CurrentDate <> CONVERT(DATETIME, @DepartureDate))
				  begin
				    if (@PriceOverWritten3=0)
				    begin
					  Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day3-1
					  Set @ProductEndDate   = Convert (DATETIME, @ArrivalDate)+@Day4-1

					  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


				  if ((@CurrentDate>=(Convert (DATETIME,@ArrivalDate)+ @Day4-1)) AND (@CurrentDate<(Convert (DATETIME,@DepartureDate))))
				  begin
				    if (@PriceOverWritten4=0) 
				    begin
					  Set @ProductStartDate = Convert (DATETIME, @ArrivalDate)+@Day4-1
					  Set @ProductEndDate   = Convert (DATETIME, @DepartureDate)

					  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
			  --SG SET @NumberOfNight = @NumberOfRooms -- Linked guest must also have rooms in orderbook. So always include.
			  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
		  begin
			SET @NumberOfStay = @NumberOfRooms	-- Only set number of stays when processing first day.  
		  end	     
		end

		if isnull(@RESERVATIONCONFLINENUMBER,0)=0 
		  SET @RESERVATIONCONFLINENUMBER=0
		
		--print '@ReferenceNumber=' + convert(varchar, @ReferenceNumber)

		-- 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 @CentralBookingType = 7 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)
		SET @TotalRestExtraOnDay = 0
		SET @TotalOtherExtraOnDay = 0
	  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 @CentralBookingType = 7 and @MainHotelCustomerNumber <> -1 SET @HotelCustomerNumber = @MainHotelCustomerNumber --of
			
			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 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 (((@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.		 
			  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
	  SET @PrevStatus = @Status

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

  Fetch Next From ReservationCur Into @ReferenceNumber,@GuestNumber, @SegmentNumber, @Status, @CustomerNumberInTab, 
  --@CustomerTypeNumber,
  @ContactpersonCustomerNumber, @LineNumber, @RESERVATIONCONFLINENUMBER, @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.ADDRESSTYPE,
  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 @CentralBookingType = 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 (Tablebooking=0 or Tablebooking is null)
  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                 --not a main course res.
              OR @MainCourceResNotInclMIS_OrderBook = 0) --incl main course res.

order by RESERVATIONS.ReferenceNumber, 
         Reservations.GuestNumber, RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER,RESERVATIONADDRESS.ADDRESSTYPE;

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

SET @PrevLineNumber = 0
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

    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 IsNull(@BookedConferenceRoomTypeNumber,0)=0  SET @BookedConferenceRoomTypeNumber = 0

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

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

    if (@CurrentDateStr <= @DepartureDate)
    Begin
       SET @PrevLineNumber=@LineNumber

       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 @CentralBookingType = 7 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?
			  begin	
				  SET @NumberOfStay = @NumberOfRooms -- Only set number of stays when processing first day.     
			  end             
		   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
           -- Store Halls/Daymeeting data in CustomerOrdreBook section 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
			   --AND ArrangementLines.Date = @CurrentDateStr
	         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)
  end -- if (@Status< 7)    rsCancelled,rsNoShow 
    
  SET @PrevReferenceNumber = @ReferenceNumber
      
  Fetch Next From ReservationCur
  Into @ReferenceNumber,@GuestNumber, @SegmentNumber, @Status, @CustomerNumberInTab, @CustomerTypeNumber, @ContactpersonCustomerNumber, @LineNumber, @HotelCustomerNumber, @Plenum, @LinkLineNumber
end

Close ReservationCur
Deallocate ReservationCur

--******* 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                 --not a main course res.
              OR @MainCourceResNotInclMIS_OrderBook = 0) --incl main course res.
  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 @CentralBookingType = 7 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
			  begin
                Select @FixedPrice=FixedPrice from Products  WITH (NOLOCK) where ProductNumber = @ProductNumber
              end
                     
			  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) and (@ManuelUser = 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) and (@ManuelUser = 1) -- 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'
  