CREATE PROCEDURE [dbo].[GenerateTurnoverMIS] @DayProduct BIT, @SameVAT BIT, @GetVATFrom SMALLINT, @CalcMISFromDate CHAR(8) = '', @DebugReferenceNumber INT = - 1, @CalcSystemDateOnly BIT = 0
AS
SET NOCOUNT ON

/*
  Uses sp:
	- GetVatValueAndAccountNumbers
	- ProductPricesDay
	- CalcPacketPriceAccExt
	- GetVatValueFromVatValueNumber
	- UpdateMISTable
	- MisStoreLogiAndCalcDiscount
	- MisUpdateProductWareLinkNumbers
	- GenerateMISTotals

   Changes:
    SG 20160901: Discount on package
    SG 20160829: Get POS and Segment from customer, when there is no reservation
    SG 20150904: Exec GenerateMISTotals
    SG 20150904: Format using Notepad++, Poor Man's T-SQL formatter
    SG 20150427: Added distinct in Transaction section
    SG 20150331: Main course reservations may not be included (hotelSetup)
    SG 20130911: ProductNumber not set to null even if folio.ReferenceNumber is NULL (eg. when moving to a common folio)
	             This and the ** resets the changes of (OF 20120926). Don't understand the reason?
	SG 20130528: CR 059071, 059428: Input @CalcSystemDateOnly = NULL was not handled
	KJ/SG: 20130515: CalcMISFromDate wrong if running from nightaudit. Case #CR059084
	SG 20130225: Back to version dated 20130208.
	SG 20130208: Error in no. of parameters to CalcPacketPriceAccExt
	SG 20130124: ProductNumber on moved transactions not set to null. **
	SG 20130124: ReservationRoomline.BookedTypeNumber has precedence over Rooms.RoomTypeNumber as in reservation (KA decision).
	SG 20130124: Room-package on departure day comes from transaction and should not be included from reservation.
	SG 20130111, CR 048541 and CR 051014: Transactions, all ProductNumber was set to null.	
	SG 20130107, CR 048684: @TmpProductNumber reset in each loop. When ProductNumber was NULL, we got the value from the previous record with a value not NULL.
	SG 20121228, CR 047175: Parameter PriceOverwritten was missing in calls to CalcPacketPriceAccExt. Param @PriceOverwrittenValue for one room. 
	SG CR 050510: Linking of product and package on SystemDate changed (also MisUpdateProductWareLinkNumbers). 
	OF 20120921: Ext: To many hall lines where produced.
	OF 20120926: Bug: Corrections back in time cannot have productnumbers.
	OF 20120907: Ext: No need to handle extras back in time from reservations.
	OF 20120824: Ext: ProductNumber added to pieces/pax record in transaction part
   	OF 20120806: Ext: Discount trial.
	OF 20120808: Ext: ProductNumber added to mis
 	KJ 20120713: Ext: Forecast calculation is removed.
  	OF 20120712: Ext: Performancetuning on real vat calculation of productprices.
   	OF 20120710: Bug: Addons accidentially landed in actual.
	OF 20120706: Ext: New mis attempt rev. 1
	OF 20120531: Bug: Figures arround system date bug fixed.
	OF 20120530: Ext: SystemDate reintroduced for LastMisUpdate
 	OF 20120502: Ext: OwnerReservation included.
	OF 20120425: Ext: MisTable is now used as detail view for MIS Detail viewer.
	OF 20120419: Bug: Missing arrangementlines. Landed on wrong hotel.
	OF 20120417: Ext: Primary keys removed and detailed mis introduced.
*/
DECLARE @cnt INT

SET @DayProduct = 1 -- always include conferencereservations  

DECLARE @GenerateDayProduct BIT
DECLARE @DateStamp CHAR(8)
DECLARE @SegmentNumber INTEGER
DECLARE @PointOfSaleNumber INTEGER
DECLARE @RoomTypeNumber INTEGER
DECLARE @HallTypeNumber INTEGER
DECLARE @BookedNumberOfRooms INTEGER
DECLARE @Adults INTEGER
DECLARE @Children1 INTEGER
DECLARE @Children2 INTEGER
DECLARE @Pieces INTEGER
DECLARE @Debit BIT
DECLARE @PaysAdults INTEGER
DECLARE @PaysChildren1 INTEGER
DECLARE @PaysChildren2 INTEGER
DECLARE @TotalAdults INTEGER
DECLARE @TotalChildren1 INTEGER
DECLARE @TotalChildren2 INTEGER
DECLARE @CurrentDateStr CHAR(8)
DECLARE @TempCurrentDateStr CHAR(8)
DECLARE @CurrentDate DATETIME
DECLARE @SystemDateStr CHAR(8)
DECLARE @FormatedStartDate CHAR(8)
DECLARE @SystemDate DATETIME
DECLARE @AllocatedTypeNumber INTEGER
DECLARE @Room_HallType TINYINT
-- Declare Reservation Roomline Fields  
DECLARE @LINENUMBER INT
DECLARE @ConferenceLineOnRes BIT
DECLARE @BookedTypeNumber INT
DECLARE @RoomNumber INT
DECLARE @NumberOfRooms SMALLINT
DECLARE @ArrivalDate CHAR(8)
DECLARE @ArrivalTime CHAR(5)
DECLARE @DepartureDate CHAR(8)
DECLARE @DepartureTime CHAR(5)
DECLARE @ProductNumber INT
DECLARE @TmpProductNumber INT
DECLARE @ProductNumberPacket INT
DECLARE @Price MONEY
DECLARE @TotalPrice MONEY
DECLARE @PriceOverwritten BIT
DECLARE @PriceOverwrittenValue MONEY;
DECLARE @Status SMALLINT
DECLARE @WarePrice REAL
DECLARE @ResultAccountNumber INT
DECLARE @ResultAccountNumber_ForDiscount INT
DECLARE @ResultAccountPackage INT
DECLARE @ResultAccountNumberExtras INT
DECLARE @ResultAccountNumberExtras_ForDiscount INT
DECLARE @DepartmentNumber SMALLINT
DECLARE @DepartmentNumberPackage SMALLINT
DECLARE @DepartmentNumberExtras SMALLINT
DECLARE @GlobalTransactionNumber INT
DECLARE @TransactionNumber INT
DECLARE @VatValueWare FLOAT
DECLARE @VatByPacketValue FLOAT
DECLARE @PackagePrice FLOAT
DECLARE @PackagePriceVatOf FLOAT
DECLARE @PackagePriceSum FLOAT
DECLARE @PackagePriceVatOfSum FLOAT
DECLARE @PacketWarePrice FLOAT
DECLARE @VatOfPacketWarePrice FLOAT
DECLARE @PacketNumber INT
DECLARE @PacketNumberReservation INT
DECLARE @TotalPriceDay MONEY
DECLARE @TotalPriceDay_ForDiscount MONEY
DECLARE @TotalPriceDay_ForDiscountVat MONEY
DECLARE @ProductPriceDate DATETIME
DECLARE @VatValueRoomProduct1 FLOAT
DECLARE @VatValueRoomProduct2 FLOAT
DECLARE @VatValueRoomProduct3 FLOAT
DECLARE @VatValueRoomProduct4 FLOAT
DECLARE @PriceProduct1 MONEY
DECLARE @PriceProduct2 MONEY
DECLARE @PriceProduct3 MONEY
DECLARE @PriceProduct4 MONEY
DECLARE @PackagePriceProduct1 MONEY
DECLARE @PackagePriceProduct2 MONEY
DECLARE @PackagePriceProduct3 MONEY
DECLARE @PackagePriceProduct4 MONEY
DECLARE @VatByPacketValueProduct1 MONEY
DECLARE @VatByPacketValueProduct2 MONEY
DECLARE @VatByPacketValueProduct3 MONEY
DECLARE @VatByPacketValueProduct4 MONEY
DECLARE @FirstFetch BIT
DECLARE @ReferenceNumber INT
DECLARE @FolioNumber INT
DECLARE @GuestNumber INTEGER
DECLARE @GuestNumberExtras INT
DECLARE @PrevLineNumber INTEGER
DECLARE @PrevReferenceNumber INT
DECLARE @PrevGuestNumber INTEGER
DECLARE @SmallestArrivalDate CHAR(8)
DECLARE @BiggestDepartureDate CHAR(8)
DECLARE @Day2 SMALLINT
DECLARE @Day3 SMALLINT
DECLARE @Day4 SMALLINT
DECLARE @ProductNumber2 INTEGER
DECLARE @ProductNumber3 INTEGER
DECLARE @ProductNumber4 INTEGER
DECLARE @PriceOverwritten2 BIT
DECLARE @PriceOverwritten3 BIT
DECLARE @PriceOverwritten4 BIT
DECLARE @FirstPrice1 MONEY
DECLARE @FirstPrice2 MONEY
DECLARE @FirstPrice3 MONEY
DECLARE @FirstPrice4 MONEY
DECLARE @StarProduct BIT
DECLARE @ProductStartDate DATETIME
DECLARE @ProductEndDate DATETIME
DECLARE @TmpProductStartDate DATETIME
DECLARE @TmpProductEndDate DATETIME
DECLARE @TableCount SMALLINT
DECLARE @EnviromentFee MONEY
DECLARE @GetVatValueFromProduct2 BIT
DECLARE @GetVatValueFromProduct3 BIT
DECLARE @GetVatValueFromProduct4 BIT
DECLARE @TotalPackagePrice MONEY
DECLARE @TotalVatByPacketValue MONEY
DECLARE @WareNumber INTEGER
DECLARE @WareNumberExtras INTEGER
DECLARE @WareGroupNumber INTEGER
DECLARE @WareName VARCHAR(50)
/* Never used but needed for  SP GetVatValueAndAccountnumbers */
DECLARE @BalanceAccountNumber INTEGER
DECLARE @VATAccountNumber INTEGER
DECLARE @WareText VARCHAR(30)
DECLARE @Addon MONEY
DECLARE @VatOfAddon MONEY
DECLARE @Addon1 MONEY
DECLARE @Addon2 MONEY
DECLARE @Addon3 MONEY
DECLARE @Addon4 MONEY
DECLARE @BillTextProduct VARCHAR(50)
DECLARE @BillTextAddOnProduct VARCHAR(50)
DECLARE @FixedPrice BIT
DECLARE @VATProduct BIT
DECLARE @SpecifiedDepartureAddOn BIT
DECLARE @VatOfPacket MONEY
DECLARE @VatOfPrice MONEY
DECLARE @AddonIfPriceOverwritten BIT
DECLARE @ValueType TINYINT
DECLARE @ValueTypeExtra TINYINT
DECLARE @MisData BIT
DECLARE @Arr24 CHAR(5)
DECLARE @ArrArrivalTime CHAR(5)
DECLARE @ArrDepartureTime CHAR(5)
DECLARE @OldSegmentNumber INT
DECLARE @TotalExtra MONEY
DECLARE @TotalExtra_ForDiscount MONEY
DECLARE @TotalExtra_ForDiscountVat MONEY
DECLARE @VATOfTotalExtra MONEY
DECLARE @DefaultMISPointOfSale INT
DECLARE @DefaultMISSegment INT
DECLARE @NameListSetting TINYINT
DECLARE @NameListSettingHotelSetup TINYINT
DECLARE @MisType INT
DECLARE @WareType INT
DECLARE @WarePayment SMALLINT
DECLARE @Correction BIT
DECLARE @ManuelUser BIT
DECLARE @Totalsum MONEY
DECLARE @TotalsumVat MONEY
DECLARE @TransDate CHAR(8)
DECLARE @tmpTransdate CHAR(8)
DECLARE @OnePersonPaysForAll BIT
DECLARE @IncludeTentative BIT
DECLARE @MinArrivalDate CHAR(8)
DECLARE @MaxDepartureDate CHAR(8)
DECLARE @IncludeProvisionbackward BIT
DECLARE @IncludeDayroomsInSoldRooms BIT
DECLARE @DayroomsLaterThanTime CHAR(5)
DECLARE @ConflineOnMainRes BIT
DECLARE @NightAuditRunning BIT
DECLARE @OneDayBack BIT
DECLARE @HotelCustomerNumber INT
DECLARE @CentralBookingType SMALLINT
DECLARE @LastMISUpdate DATETIME
DECLARE @LatestDeletedBefore CHAR(8)
DECLARE @Plenum BIT
DECLARE @PackageSameDayAsLogi BIT
DECLARE @CurrentDateStrDeparturePackage CHAR(8)
DECLARE @tmpUpdateType TINYINT
DECLARE @tmpSameDayAsLogi BIT
DECLARE @CampaignCode SMALLINT
DECLARE @ProjectCode SMALLINT
DECLARE @StaffID INT
DECLARE @IsPackage BIT
DECLARE @ProductWareLinkNumber INT
DECLARE @ProductWareLinkNumberMis INT
DECLARE @ProductWareLinkNumberTrans INT
DECLARE @PackageStored BIT
DECLARE @tmpProductWareLinkNumberTrans INT
DECLARE @tmpProductWareLinkNumberMis INT
DECLARE @ShowOnBillFlag BIT
DECLARE @ForceLodgingChargeOfZeroPrice BIT
DECLARE @InhouseDebitor BIT
DECLARE @UserTypeNumber SMALLINT
DECLARE @TransactionMoved BIT
DECLARE @TransactionDeleted BIT
DECLARE @Text VARCHAR(100)
DECLARE @OwnerReservation BIT
DECLARE @OrderBookBudgetCalcDiscount BIT
DECLARE @CalcDiscount BIT
DECLARE @DiscountWareNumber INT
DECLARE @DiscountAsNettoPrice BIT
DECLARE @ChargeDiscountAsProduct BIT
DECLARE @DiscountResultAccountNumber INT
DECLARE @DiscountVatValueWare FLOAT
DECLARE @SplitBillNumber INT
--DECLARE @DiscountSpec BIT
DECLARE @InternalCourseProduction BIT --Allow Main reservation. Always a record in ReservationReservationXtab when 1
DECLARE @MainCourceResNotInclMIS_OrderBook BIT --Main course reservation not included in MIS and order book
 --Populated by CalcPacketPriceAccExt
CREATE TABLE #PacketWareTable ([ResultAccountNumber] [int] NULL, [DepartmentNumber] [smallint] NULL, [PacketWarePrice] [float] NULL, [VatOfPacketWarePrice] [float] NULL, [WareGroupNumber] [float] NULL, [WareName] [varchar](50) NULL, [ProductWareLinkNumber] INT NULL, [ProductNumber] INT NULL)

CREATE TABLE #ReservationsCrossDate ([ReferenceNumber] [int] NOT NULL)

CREATE TABLE #FoliosCrossDate ([FolioNumber] [int] NOT NULL)

-- For discount calculation
SELECT @OrderBookBudgetCalcDiscount = CONVERT(BIT, KeyValue)
FROM HotelSetUp WITH (NOLOCK)
WHERE SearchKey = 'OrderBookBudgetCalcDiscount'

SET @OrderBookBudgetCalcDiscount = ISNULL(@OrderBookBudgetCalcDiscount, 0)

SELECT @DiscountAsNettoPrice = ISNULL(KeyValue, 0)
FROM HotelSetup WITH (NOLOCK)
WHERE Searchkey = 'DiscountAsNettoPrice'

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

IF ISNULL(@ChargeDiscountAsProduct, 0) = 0
	SET @ChargeDiscountAsProduct = 0

SELECT @DiscountWareNumber = DiscountWareNumber, @DiscountResultAccountNumber = DiscountResultAccountNumber, @DiscountVatValueWare = DiscountVatValueWare
FROM dbo.GetDiscountWareInfo()

-- For discount calculation end
SELECT @CentralBookingType = Convert(INTEGER, isnull(KeyValue, 0))
FROM HotelSetup WITH (NOLOCK)
WHERE searchkey LIKE '%CentralBookingType%'

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 Upper(SearchKey) = Upper('IncludeDayroomsInSoldRooms')

SELECT @DayroomsLaterThanTime = KeyValue
FROM HotelSetup WITH (NOLOCK)
WHERE Upper(SearchKey) = Upper('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

SELECT @NameListSettingHotelSetup = Convert(INTEGER, KeyValue)
FROM Hotelsetup WITH (NOLOCK)
WHERE Searchkey = 'NameListReservationPerPerson'

SELECT @IncludeTentative = Convert(BIT, KeyValue)
FROM Hotelsetup WITH (NOLOCK)
WHERE Searchkey = 'IncludeTentativeInMISAndOrderbook'

IF isnull(@IncludeTentative, 0) = 0
	SET @IncludeTentative = 0

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

SET @PackageSameDayAsLogi = ISNULL(@PackageSameDayAsLogi, 0)

SELECT @ForceLodgingChargeOfZeroPrice = Convert(BIT, KeyValue)
FROM HotelSetup WITH (NOLOCK)
WHERE Upper(SearchKey) = Upper('ForceLodgingChargeOfZeroPrice')

SET @ForceLodgingChargeOfZeroPrice = ISNULL(@ForceLodgingChargeOfZeroPrice, 0)

SELECT @InternalCourseProduction = Convert(BIT, KeyValue)
FROM HotelSetup WITH (NOLOCK)
WHERE SearchKey = 'InternalCourseProduction'

SET @InternalCourseProduction = ISNULL(@InternalCourseProduction, 0);

IF @InternalCourseProduction = 1
BEGIN
	SELECT @MainCourceResNotInclMIS_OrderBook = Convert(BIT, KeyValue)
	FROM HotelSetup WITH (NOLOCK)
	WHERE SearchKey = 'MainCourceResNotInclMIS_OrderBook'

	SET @MainCourceResNotInclMIS_OrderBook = ISNULL(@MainCourceResNotInclMIS_OrderBook, 1);
END
ELSE
BEGIN
	SET @MainCourceResNotInclMIS_OrderBook = 0
END

SET @FirstFetch = 1
SET @TableCount = 0 -- 0 = Roomline og 1=Confline   

-- Check if StartDate or EndDate before Systemdate -> change!   
SELECT @OldSegmentNumber = Number
FROM SEGMENTS WITH (NOLOCK)
WHERE TEXT = 'Old system'

IF isnull(@OldSegmentNumber, 0) = 0
	SET @OldSegmentNumber = 0

SELECT @SystemDateStr = SYSTEMDATE
FROM System WITH (NOLOCK)
WHERE NUMBER = 1

SET @SystemDate = Convert(DATETIME, @SystemDateStr)

SELECT @LastMISUpdate = Convert(DATETIME, Keyvalue)
FROM HotelSetup WITH (NOLOCK)
WHERE Searchkey = 'LastMISUpdate'

SET @CalcMISFromDate = ISNULL(@CalcMISFromDate, '')
SET @CalcSystemDateOnly = ISNULL(@CalcSystemDateOnly, 0)

IF @CalcMISFromDate = '' -- Normal update from Marketing or NightAudit
BEGIN
	IF @NightAuditRunning = 1
		SET @FormatedStartDate = Convert(CHAR(8), isnull(Convert(DATETIME, @LastMISUpdate), @SystemDate - 1), 112) -- decrease FormatedStartDate with one or more for getting latest posted transaction. This is important specially when updating from nightaudit.
	ELSE
		SET @FormatedStartDate = Convert(CHAR(8), isnull(Convert(DATETIME, @LastMISUpdate) - 1, @SystemDate - 1), 112) -- decrease FormatedStartDate with one or more for getting latest posted transaction. This is important specially when updating from nightaudit.
END
ELSE
BEGIN
	SET @FormatedStartDate = @CalcMISFromDate
END

IF @CalcSystemDateOnly = 1
	SET @FormatedStartDate = @SystemDateStr

-- Get reference numbers crossing the @FormatedStartDate Reservations are deleted and recalculated as whole reservations. From arrivaldate to departure date always.
IF @CalcSystemDateOnly = 0
BEGIN
	INSERT INTO #ReservationsCrossDate
	SELECT DISTINCT ReferenceNumber
	FROM RESERVATIONS WITH (NOLOCK)
	WHERE ArrivalDate <= @FormatedStartDate
		AND DepartureDate >= @FormatedStartDate
		AND ReferenceNumber IS NOT NULL
	
	UNION ALL
	
	SELECT DISTINCT ReferenceNumber
	FROM RESERVATIONCONFERENCELINE WITH (NOLOCK)
	WHERE ArrivalDate <= @FormatedStartDate
		AND DepartureDate >= @FormatedStartDate
		AND ReferenceNumber IS NOT NULL
END

-- Get Folio numbers crossing the @FormatedStartDate Folios are deleted and recalculated as whole Folios.
INSERT INTO #FoliosCrossDate
SELECT DISTINCT t1.FolioNumber
FROM Transactions t1 WITH (NOLOCK)
WHERE (Convert(CHAR(8), t1.DateStamp, 112) >= @FormatedStartDate)

--Delete data 
IF @CalcSystemDateOnly = 0
BEGIN
	DELETE
	FROM MISTable
	WHERE ReadOnly = 0
		AND (
			DateStamp >= @FormatedStartDate
			OR (
				(
					MISTable.ReferenceNumber IN (
						SELECT *
						FROM #ReservationsCrossDate WITH (NOLOCK)
						)
					AND MisTable.FolioNumber = - 1
					)
				OR -- Pure reservations
				MISTable.FolioNumber IN (
					SELECT *
					FROM #FoliosCrossDate WITH (NOLOCK)
					)
				)
			)
END
ELSE
BEGIN
	DELETE
	FROM MISTable
	WHERE ReadOnly = 0
		AND MISTable.FolioNumber IN (
			SELECT *
			FROM #FoliosCrossDate WITH (NOLOCK)
			)
END

--
SELECT @Arr24 = KeyValue
FROM HotelSetUp WITH (NOLOCK)
WHERE SearchKey = 'Arr24HoursStarts'

SELECT @AddonIfPriceOverwritten = CONVERT(BIT, KeyValue)
FROM HotelSetUp WITH (NOLOCK)
WHERE SearchKey = 'AddonIfPriceOverwritten'

IF isnull(@AddonIfPriceOverwritten, 0) = 0
	SET @AddonIfPriceOverwritten = 0

SELECT @DefaultMISPointOfSale = CONVERT(INT, KeyValue)
FROM HotelSetUp WITH (NOLOCK)
WHERE Upper(SearchKey) = Upper('DefaultMISPos')

SET @DefaultMISPointOfSale = isnull(@DefaultMISPointOfSale, - 1)

SELECT @DefaultMISSegment = CONVERT(INT, KeyValue)
FROM HotelSetUp WITH (NOLOCK)
WHERE Upper(SearchKey) = Upper('DefaultMISSegment')

SET @DefaultMISSegment = isnull(@DefaultMISSegment, - 1)

SELECT @IncludeProvisionbackward = CONVERT(BIT, KeyValue)
FROM HotelSetUp WITH (NOLOCK)
WHERE SearchKey = 'IncludeProvisionbackwardInMIS'

IF isnull(@IncludeProvisionbackward, 0) = 0
	SET @IncludeProvisionbackward = 0

SELECT @ProductWareLinkNumberMis = MAX(ProductWareLinkNumber) + 1
FROM MisTable WITH (NOLOCK)

SELECT @ProductWareLinkNumberTrans = MAX(ProductWareLinkNumber) + 1
FROM Transactions WITH (NOLOCK)

SET @ProductWareLinkNumberMis = isnull(@ProductWareLinkNumberMis, 0)
SET @ProductWareLinkNumberTrans = isnull(@ProductWareLinkNumberTrans, 0)
SET @ProductWareLinkNumber = @ProductWareLinkNumberTrans

IF @ProductWareLinkNumberMis > @ProductWareLinkNumberTrans
	SET @ProductWareLinkNumber = @ProductWareLinkNumberMis + 100000 -- Be sure not to conflict when calculating mis on systemdate only. We need a range of pwln's for posted transactions on day.
SET @ProductWareLinkNumber = ISNULL(@ProductWareLinkNumber, 1)

CREATE TABLE #ReferenceExtrasTable (ReferenceNumber INT NOT NULL, CurrentDate CHAR(8))

IF @CalcSystemDateOnly = 0
BEGIN
	WHILE (@TableCount <= @DayProduct)
	BEGIN
		SET @TableCount = @TableCount + 1

		IF @TableCount = 1 -- Roomline   
		BEGIN
			SET @ValueType = 1
			SET @PrevLineNumber = 0
			SET @GenerateDayProduct = 0
			SET @PrevGuestNumber = 0

			DECLARE ReservationCur CURSOR FAST_FORWARD READ_ONLY
			FOR
			SELECT DISTINCT -- Fjerner dubletter (linenumber) 
				Cast(0 AS TINYINT) AS Room_HallType, RESERVATIONROOMLINE.LINENUMBER,
				--isnull(Rooms.Roomtypenumber, RESERVATIONROOMLINE.BookedTypeNumber), 
				isnull(RESERVATIONROOMLINE.BookedTypeNumber, Rooms.Roomtypenumber), --SG/20130124, KA decision
				RESERVATIONROOMLINE.RoomNumber, RESERVATIONROOMLINEXTAB.ReferenceNumber AS ReferenceNumber, RESERVATIONROOMLINEXTAB.GuestNumber AS GuestNumber, isnull(RESERVATIONS.STATUS, - 1), RESERVATIONS.MARKETSEGMENT, RESERVATIONS.POINTOFSALE, RESERVATIONROOMLINE.ArrivalDate AS ArrivalDate, RESERVATIONROOMLINE.DepartureDate AS DepartureDate, RESERVATIONROOMLINE.DepartureTime, RESERVATIONROOMLINE.Adults, RESERVATIONROOMLINE.Children1, RESERVATIONROOMLINE.Children2, RESERVATIONROOMLINE.Adults, RESERVATIONROOMLINE.Children1, RESERVATIONROOMLINE.Children2, RESERVATIONROOMLINE.ProductNumber, RESERVATIONROOMLINE.NumberOfRooms, RESERVATIONROOMLINE.PriceOverwritten, RESERVATIONROOMLINE.Price, RESERVATIONROOMLINE.FirstPrice1, RESERVATIONROOMLINE.PriceOverwritten2, RESERVATIONROOMLINE.FirstPrice2, RESERVATIONROOMLINE.Day2, RESERVATIONROOMLINE.ProductNumber2, RESERVATIONROOMLINE.PriceOverwritten3, RESERVATIONROOMLINE.FirstPrice3, RESERVATIONROOMLINE.Day3, RESERVATIONROOMLINE.ProductNumber3, RESERVATIONROOMLINE.PriceOverwritten4, 
				RESERVATIONROOMLINE.FirstPrice4, RESERVATIONROOMLINE.Day4, RESERVATIONROOMLINE.ProductNumber4, CASE 
					WHEN RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER > 0
						THEN 1
					ELSE 0
					END, CASE 
					WHEN RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER > 0
						THEN 1
					ELSE 0
					END, isnull(Customer.CustomerNumber, - 1), isnull(RESERVATIONROOMLINE.NameListSetting, 0), 1, -- Plenum 
				isnull(RESERVATIONS.FK_CampaignCode, - 1) AS Campaign, isnull(RESERVATIONMAIN.FK_ProjectCode, - 1) AS Project, isnull(RESERVATIONMAIN.StaffID, - 1) AS StaffID, CASE 
					WHEN (
							(
								Rooms.CustomerNumber IS NOT NULL
								AND RESERVATIONADDRESS.LINK IS NOT NULL
								)
							AND Rooms.CustomerNumber = RESERVATIONADDRESS.LINK
							)
						THEN 1
					ELSE 0
					END AS OwnerReservation, RESERVATIONS.SplitBill
			FROM RESERVATIONROOMLINE WITH (NOLOCK)
			INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LINENUMBER
				AND RESERVATIONROOMLINEXTAB.Referencenumber > 0
				AND (
					RESERVATIONROOMLINEXTAB.Referencenumber IN (
						SELECT *
						FROM #ReservationsCrossDate WITH (NOLOCK)
						)
					OR RESERVATIONROOMLINE.DepartureDate >= @FormatedStartDate
					)
				AND RESERVATIONROOMLINEXTAB.GuestNumber = 0
				AND (
					(RESERVATIONROOMLINE.DepartureDate <> RESERVATIONROOMLINE.ArrivalDate)
					OR (
						RESERVATIONROOMLINE.DepartureDate = RESERVATIONROOMLINE.ArrivalDate
						AND @IncludeDayroomsInSoldRooms = 1
						)
					)
			INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber
				AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
				AND (
					(
						@IncludeTentative = 0
						AND RESERVATIONS.STATUS IN (
							0
							,1
							,2
							,3
							,5
							,6
							)
						)
					OR (
						@IncludeTentative = 1
						AND RESERVATIONS.STATUS IN (
							0
							,1
							,2
							,3
							,4
							,5
							,6
							)
						)
					)
			LEFT OUTER JOIN RESERVATIONCONFERENCELINE WITH (NOLOCK) ON RESERVATIONS.ReferenceNumber = RESERVATIONCONFERENCELINE.ReferenceNumber
			INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.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, 0) = Customer.HotelNumber
				AND Customer.HotelNumber >= 0
				AND Customer.CustomerTypeNumber = 7
				AND @CentralBookingType = 7
				AND ISNULL(Customer.MarkAsDeleted, 0) = 0
			LEFT JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = RESERVATIONS.ReferenceNumber
				AND ReservationAddressXTab.GuestNumber = RESERVATIONS.GuestNumber
				AND ReservationAddressXTab.AddressTypeNumber = 1
			LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
				AND ReservationAddress.AddressType = 1
			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 (
					ISNULL(@DebugReferenceNumber, - 1) = - 1
					OR RESERVATIONROOMLINEXTAB.Referencenumber = @DebugReferenceNumber
					)
				AND (
					@InternalCourseProduction = 0 --normal
					OR (
						@InternalCourseProduction = 1
						AND @MainCourceResNotInclMIS_OrderBook = 0
						) --incl main course res.
					OR (
						@InternalCourseProduction = 1
						AND isnull(FK_ReferenceNumber, 0) = 0
						) --not a main res
					)
			
			UNION ALL
			
			SELECT DISTINCT -- Fjerner dubletter (linenumber)
				Cast(0 AS TINYINT) AS Room_HallType, RESERVATIONROOMLINE.LINENUMBER,
				--isnull(Rooms.Roomtypenumber, RESERVATIONROOMLINE.BookedTypeNumber),
				isnull(RESERVATIONROOMLINE.BookedTypeNumber, Rooms.Roomtypenumber), --SG/20130124, KA decision
				RESERVATIONROOMLINE.RoomNumber, RESERVATIONS.ReferenceNumber AS ReferenceNumber, RESERVATIONS.GuestNumber AS GuestNumber, ISNULL(RESERVATIONS.STATUS, - 1), RESERVATIONS.MARKETSEGMENT, RESERVATIONS.POINTOFSALE, RESERVATIONS.ArrivalDate AS ArrivalDate, RESERVATIONS.DepartureDate AS DepartureDate, RESERVATIONS.DepartureTime, RESERVATIONS.Adults, RESERVATIONS.Children1, RESERVATIONS.Children2, RESERVATIONS.PaysAdults, RESERVATIONS.PaysChildren1, RESERVATIONS.PaysChildren2, RESERVATIONS.ProductNumber, RESERVATIONROOMLINE.NumberOfRooms, RESERVATIONS.PriceOverwritten, RESERVATIONS.Price, RESERVATIONS.FirstPrice1, RESERVATIONS.PriceOverwritten2, RESERVATIONS.FirstPrice2, RESERVATIONS.Day2, RESERVATIONS.ProductNumber2, RESERVATIONS.PriceOverwritten3, RESERVATIONS.FirstPrice3, RESERVATIONS.Day3, RESERVATIONS.ProductNumber3, RESERVATIONS.PriceOverwritten4, RESERVATIONS.FirstPrice4, RESERVATIONS.Day4, RESERVATIONS.ProductNumber4, 0, CASE 
					WHEN RESERVATIONCONFERENCELINE.RESERVATIONCONFLINENUMBER > 0
						THEN 1
					ELSE 0
					END, isnull(Customer.CustomerNumber, - 1), isnull(RESERVATIONROOMLINE.NameListSetting, 0), 1, -- Plenum
				isnull(RESERVATIONS.FK_CampaignCode, - 1) AS Campaign, isnull(RESERVATIONMAIN.FK_ProjectCode, - 1) AS Project, isnull(RESERVATIONMAIN.StaffID, - 1) AS StaffID, CASE 
					WHEN (
							(
								Rooms.CustomerNumber IS NOT NULL
								AND RESERVATIONADDRESS.LINK IS NOT NULL
								)
							AND Rooms.CustomerNumber = RESERVATIONADDRESS.LINK
							)
						THEN 1
					ELSE 0
					END AS OwnerReservation, RESERVATIONS.SplitBill
			FROM RESERVATIONROOMLINE WITH (NOLOCK)
			INNER JOIN RESERVATIONROOMLINEXTAB WITH (NOLOCK) ON RESERVATIONROOMLINE.LINENUMBER = RESERVATIONROOMLINEXTAB.LINENUMBER
				AND RESERVATIONROOMLINEXTAB.Referencenumber > 0
				AND RESERVATIONROOMLINEXTAB.GuestNumber > 0
			INNER JOIN RESERVATIONS WITH (NOLOCK) ON RESERVATIONROOMLINEXTAB.ReferenceNumber = RESERVATIONS.ReferenceNumber
				AND RESERVATIONROOMLINEXTAB.GuestNumber = RESERVATIONS.GuestNumber
				AND (
					(
						RESERVATIONS.Referencenumber IN (
							SELECT *
							FROM #ReservationsCrossDate WITH (NOLOCK)
							)
						OR RESERVATIONS.DepartureDate >= @FormatedStartDate
						)
					AND (
						(
							@IncludeTentative = 0
							AND RESERVATIONS.STATUS IN (
								0
								,1
								,2
								,3
								,5
								,6
								)
							)
						OR (
							@IncludeTentative = 1
							AND RESERVATIONS.STATUS IN (
								0
								,1
								,2
								,3
								,4
								,5
								,6
								)
							)
						)
					AND RESERVATIONS.GuestNumber > 0
					AND (
						(RESERVATIONS.Adults + RESERVATIONS.Children1 + RESERVATIONS.Children2 > 0)
						OR ((RESERVATIONS.PaysAdults + RESERVATIONS.PaysChildren1 + RESERVATIONS.PaysChildren2) > 0)
						)
					)
				AND (
					(RESERVATIONS.DepartureDate <> RESERVATIONS.ArrivalDate)
					OR (
						RESERVATIONS.DepartureDate = RESERVATIONS.ArrivalDate
						AND @IncludeDayroomsInSoldRooms = 1
						)
					)
			LEFT OUTER JOIN RESERVATIONCONFERENCELINE WITH (NOLOCK) ON RESERVATIONS.ReferenceNumber = RESERVATIONCONFERENCELINE.ReferenceNumber
			INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.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, 0) = Customer.HotelNumber
				AND Customer.HotelNumber >= 0
				AND Customer.CustomerTypeNumber = 7
				AND @CentralBookingType = 7
				AND ISNULL(Customer.MarkAsDeleted, 0) = 0
			LEFT JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = RESERVATIONS.ReferenceNumber
				AND ReservationAddressXTab.GuestNumber = RESERVATIONS.GuestNumber
				AND ReservationAddressXTab.AddressTypeNumber = 1
			LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
				AND ReservationAddress.AddressType = 1
			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 (
					ISNULL(@DebugReferenceNumber, - 1) = - 1
					OR RESERVATIONROOMLINEXTAB.Referencenumber = @DebugReferenceNumber
					)
				AND (
					@InternalCourseProduction = 0 --normal
					OR (
						@InternalCourseProduction = 1
						AND @MainCourceResNotInclMIS_OrderBook = 0
						) --incl main course res.
					OR (
						@InternalCourseProduction = 1
						AND isnull(FK_ReferenceNumber, 0) = 0
						) --not a main res
					)
			ORDER BY ReferenceNumber, RESERVATIONROOMLINE.linenumber, ArrivalDate, DepartureDate DESC, GuestNumber

			OPEN ReservationCur

			FETCH NEXT
			FROM ReservationCur
			INTO @Room_HallType, @LINENUMBER, @BookedTypeNumber, @RoomNumber, @ReferenceNumber, @GuestNumber, @Status, @SegmentNumber, @PointOfSaleNumber, @ArrivalDate, @DepartureDate, @DepartureTime, @Adults, @Children1, @Children2, @PaysAdults, @PaysChildren1, @PaysChildren2, @ProductNumber, @NumberOfRooms, @PriceOverwritten, @Price, @FirstPrice1, @PriceOverwritten2, @FirstPrice2, @Day2, @ProductNumber2, @PriceOverwritten3, @FirstPrice3, @Day3, @ProductNumber3, @PriceOverwritten4, @FirstPrice4, @Day4, @ProductNumber4, @ConferenceLineOnRes, @ConflineOnMainRes, @HotelCustomerNumber, @NameListSetting, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber
		END
		ELSE -- Confline   
		BEGIN
			SET @ConferenceLineOnRes = 1
			SET @GenerateDayProduct = 1

			DECLARE ReservationCur CURSOR FAST_FORWARD READ_ONLY
			FOR
			SELECT DISTINCT Cast(1 AS TINYINT) AS Room_HallType, RESERVATIONConferenceLINE.BookedConferenceRoomTypeNumber, RESERVATIONConferenceLINE.ReservationConfLineNumber, RESERVATIONConferenceLINE.ConferenceRoomNumber, RESERVATIONConferenceLINE.ArrivalDate, RESERVATIONConferenceLINE.DepartureDate, RESERVATIONConferenceLINE.ProductNumber, RESERVATIONConferenceLINE.NumberOfRooms, ISNULL(RESERVATIONS.STATUS, - 1), RESERVATIONConferenceLINE.PriceOverWritten, RESERVATIONConferenceLINE.Adults, RESERVATIONConferenceLINE.Children1, RESERVATIONConferenceLINE.Children2, RESERVATIONConferenceLINE.Price, RESERVATIONConferenceLINE.ReferenceNumber, RESERVATIONConferenceLINE.PackageNumber, RESERVATIONConferenceLINE.ArrivalTime, RESERVATIONConferenceLINE.DepartureTime, isnull(Customer.CustomerNumber, - 1), ISNULL(ReservationConferenceLine.Plenum, 0), ISNULL(RESERVATIONS.FK_CampaignCode, - 1), ISNULL(RESERVATIONMAIN.FK_ProjectCode, - 1), ISNULL(RESERVATIONMAIN.StaffID, - 1), 0 AS OwnerReservation, RESERVATIONS.SplitBill
			FROM RESERVATIONConferenceLINE WITH (NOLOCK)
			INNER JOIN Reservations WITH (NOLOCK) ON Reservations.ReferenceNumber = RESERVATIONConferenceLINE.ReferenceNumber --AND Reservations.GuestNumber = 0 
				AND (
					RESERVATIONConferenceLINE.Referencenumber IN (
						SELECT *
						FROM #ReservationsCrossDate WITH (NOLOCK)
						)
					OR RESERVATIONConferenceLINE.DepartureDate >= @FormatedStartDate
					)
				AND (
					(
						@IncludeTentative = 0
						AND RESERVATIONS.STATUS IN (
							0
							,1
							,2
							,3
							,5
							,6
							)
						)
					OR (
						@IncludeTentative = 1
						AND RESERVATIONS.STATUS IN (
							0
							,1
							,2
							,3
							,4
							,5
							,6
							)
						)
					)
				--AND (TableBooking = 0 OR TableBooking is null) 
				AND RESERVATIONS.ReferenceNumber > 0 /*  ny fra kent  */
				AND Reservations.GuestNumber = ISNULL(RESERVATIONConferenceLINE.GuestNo, 0)
			INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.ReferenceNumber
			LEFT OUTER JOIN Customer WITH (NOLOCK) ON isnull(RESERVATIONMAIN.HotelNumber, 0) = Customer.HotelNumber
				AND Customer.HotelNumber >= 0
				AND Customer.CustomerTypeNumber = 7
				AND @CentralBookingType = 7
				AND ISNULL(Customer.MarkAsDeleted, 0) = 0
			LEFT OUTER JOIN ConferenceRooms WITH (NOLOCK) ON RESERVATIONConferenceLINE.Conferenceroomnumber = ConferenceRooms.Conferenceroomnumber
			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 (
					ISNULL(@DebugReferenceNumber, - 1) = - 1
					OR RESERVATIONS.ReferenceNumber = @DebugReferenceNumber
					)
				AND (
					@InternalCourseProduction = 0 --normal
					OR (
						@InternalCourseProduction = 1
						AND @MainCourceResNotInclMIS_OrderBook = 0
						) --incl main course res.
					OR (
						@InternalCourseProduction = 1
						AND isnull(FK_ReferenceNumber, 0) = 0
						) --not a main res
					)
			ORDER BY RESERVATIONConferenceLINE.ReferenceNumber, RESERVATIONConferenceLINE.ReservationConfLineNumber

			OPEN ReservationCur

			FETCH NEXT
			FROM ReservationCur
			INTO @Room_HallType, @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms, @Status, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber
		END

		SET @PrevLineNumber = 0
		SET @PrevReferenceNumber = 0
		SET @GetVatValueFromProduct2 = 0
		SET @GetVatValueFromProduct3 = 0
		SET @GetVatValueFromProduct4 = 0

		WHILE (@@FETCH_STATUS <> - 1)
		BEGIN
			BEGIN
				SET @TmpProductNumber = NULL;

				IF isnull(@LINENUMBER, 0) = 0
					SET @LINENUMBER = 0
				SET @StarProduct = 0

				IF IsNull(@ROOMNUMBER, 0) = 0
					SET @ROOMNUMBER = 0
				SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

				IF @TableCount = 2
				BEGIN
					SET @guestnumber = 0
					SET @ConflineOnMainRes = 0

					SELECT @SegmentNumber = MarketSegment, @PointOfSaleNumber = PointOfSale
					FROM Reservations WITH (NOLOCK)
					WHERE ReferenceNumber = @ReferenceNumber

					SET @AllocatedTypeNumber = @BookedTypeNumber

					IF isNull(@BookedTypeNumber, 0) = 0
						SET @DepartureDate = Convert(CHAR(8), convert(DATETIME, @DepartureDate) - 1, 112)

					IF IsNull(@AllocatedTypeNumber, 0) = 0
						SET @AllocatedTypeNumber = 0

					IF (@ArrDepartureTime < @Arr24)
						AND (@BookedTypeNumber > 0)
						SET @DepartureDate = Convert(CHAR(8), convert(DATETIME, @DepartureDate) - 1, 112)

					IF @ArrArrivalTime < @Arr24
						SET @ArrivalDate = Convert(CHAR(8), convert(DATETIME, @ArrivalDate) - 1, 112)
				END
				ELSE
				BEGIN
					SET @AllocatedTypeNumber = @BookedTypeNumber

					IF IsNull(@Price, 0) = 0
						SET @Price = 0

					IF IsNull(@TotalPrice, 0) = 0
						SET @TotalPrice = 0

					IF IsNull(@Day2, 0) = 0
						SET @Day2 = 0

					IF IsNull(@Day3, 0) = 0
						SET @Day3 = 0

					IF IsNull(@Day4, 0) = 0
						SET @Day4 = 0

					IF IsNull(@ProductNumber, 0) = 0
						SET @ProductNumber = 0

					IF IsNull(@ProductNumber2, 0) = 0
						SET @ProductNumber2 = 0

					IF IsNull(@ProductNumber3, 0) = 0
						SET @ProductNumber3 = 0

					IF IsNull(@ProductNumber4, 0) = 0
						SET @ProductNumber4 = 0

					IF IsNull(@AllocatedTypeNumber, 0) = 0
						SET @AllocatedTypeNumber = 0

					IF ((@Day2 + @Day3 + @Day4) > 0)
					BEGIN
						SET @StarProduct = 1

						IF @NameListSetting = 0
							SET @NameListSetting = @NameListSettingHotelSetup
					END
					ELSE
					BEGIN
						IF @ProductNumber > 0
						BEGIN
							IF @GuestNumber = 0
								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
							SET @NameListSetting = @NameListSettingHotelSetup
					END
				END

				IF IsNull(@NumberOfRooms, 1) = 1
					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

				IF (
						(
							(@FirstFetch = 1)
							AND (@SameVAT = 1)
							)
						OR (@SameVAT = 0)
						) -- Find warenumber and acccountnumber for product   
				BEGIN
					IF (@GetVATFrom = 0) -- Get Vat From Segment   
						EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @SegmentNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT
					ELSE IF (@GetVATFrom = 1) -- Get Vat From POS   
						EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @PointOfSaleNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT
					ELSE IF (@GetVATFrom = 2) -- Get Vat From Roomtype -- TODO ConferenceRoom if DayProduct   
						EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @BookedTypeNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT
					ELSE IF (@GetVATFrom = 3) -- Get Vat From Producttype   
						EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct1 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT
				END

				IF IsNull(@VatValueRoomProduct1, 0) = 0
					SET @VatValueRoomProduct1 = 0
				SET @CurrentDateStr = @ArrivalDate
				SET @CurrentDate = Convert(DATETIME, @CurrentDateStr)
				SET @CurrentDateStrDeparturePackage = CONVERT(CHAR(8), @CurrentDate - 1, 112)

				IF (@GuestNumber > 0)
					AND (@NameListSetting = 0)
				BEGIN
					SET @PaysAdults = @Adults
					SET @PaysChildren1 = @Children1
					SET @PaysChildren2 = @Children2
				END

				WHILE @CurrentDateStr <= @DepartureDate
				BEGIN
					SET @EnviromentFee = 0
					SET @VatByPacketValue = 0
					SET @PackagePrice = 0
					SET @VatValueRoomProduct2 = 0
					SET @VatValueRoomProduct3 = 0
					SET @VatValueRoomProduct4 = 0
					SET @PackagePriceProduct1 = 0
					SET @PackagePriceProduct2 = 0
					SET @PackagePriceProduct3 = 0
					SET @PackagePriceProduct4 = 0
					SET @VatByPacketValueProduct1 = 0
					SET @VatByPacketValueProduct2 = 0
					SET @VatByPacketValueProduct3 = 0
					SET @VatByPacketValueProduct4 = 0
					SET @PriceProduct1 = 0
					SET @PriceProduct2 = 0
					SET @PriceProduct3 = 0
					SET @PriceProduct4 = 0
					SET @Addon1 = 0
					SET @Addon2 = 0
					SET @Addon3 = 0
					SET @Addon4 = 0
					SET @ProductPriceDate = @CurrentDate

					DELETE
					FROM #PacketWareTable -- Clear #PacketWareTable

					IF @Status IN (
							0
							,1
							,2
							,3
							,4
							,5
							,6
							) -- NOT CPG -- Booked  -- NB Skal først få Booked til at virke !!! * product?   
					BEGIN
						IF (@TableCount = 1) --not Dayproduct   
						BEGIN
							SET @TotalPackagePrice = 0
							SET @TotalVatByPacketValue = 0
		                                        Declare @AddressType tinyInt
		                                        Declare @DiscountRate float;
		                                        EXEC FindFolioNumber @ReferenceNumber, @GuestNumber, 0, @WareNumber, @SplitbillNumber, 0, @FolioNumber OUTPUT, @AddressType OUTPUT
		                                        EXEC GetDiscountRate @ReferenceNumber, @GuestNumber, @AddressType, 1, @DiscountRate OUTPUT

							IF (@StarProduct = 0) -- Calc for not-+product   
							BEGIN
								SET @ProductStartDate = Convert(DATETIME, @ArrivalDate)
								SET @ProductEndDate = Convert(DATETIME, @DepartureDate)

								EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

								SET @TmpProductNumber = @ProductNumber

								IF (@PriceOverWritten = 1)
								BEGIN
									IF (@CurrentDateStr <> @DepartureDate)
										OR (@ArrivalDate = @DepartureDate)
									BEGIN
										SET @PriceProduct1 = @Price * @NumberOfRooms
										SET @PriceOverwrittenValue = @Price;

										IF @NameListSetting = 1
											AND @OnePersonPaysForAll = 0
										BEGIN
											SET @PriceProduct1 = @PriceProduct1 * (@Adults + @Children1 + @Children2)
											SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
										END
									END
									ELSE
									BEGIN
										SET @PriceOverwrittenValue = 0;
									END

									IF (@AddonIfPriceOverwritten = 0)
										SET @Addon1 = 0
								END

								IF (@CurrentDateStr <> @DepartureDate)
									OR (@ArrivalDate = @DepartureDate)
									SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

								IF @PacketNumber > 0
									EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber
							END
							ELSE -- StarProduct = +product   
							BEGIN
								SET @TmpProductStartDate = Convert(DATETIME, @ArrivalDate)
								SET @TmpProductEndDate = Convert(DATETIME, @ArrivalDate) + @Day2 - 1

								IF (@CurrentDate <= @TmpProductEndDate) -- ProductNumber incl afrejse pakke    
								BEGIN
									SET @ProductStartDate = @TmpProductStartDate
									SET @ProductEndDate = @TmpProductEndDate

									EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

									SET @TmpProductNumber = @ProductNumber

									IF (@PriceOverWritten = 1)
									BEGIN
										IF (@ProductStartDate <> @ProductEndDate)
											AND (@CurrentDate <> @ProductEndDate)
										BEGIN
											SET @PriceProduct1 = @FirstPrice1 * @NumberOfRooms
											SET @PriceOverwrittenValue = @FirstPrice1;

											IF @NameListSetting = 1
												AND @OnePersonPaysForAll = 0
											BEGIN
												SET @PriceProduct1 = @PriceProduct1 * (@Adults + @Children1 + @Children2)
												SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2)
											END
										END
										ELSE
										BEGIN
											SET @PriceOverwrittenValue = 0;
										END

										IF (@AddonIfPriceOverwritten = 0)
											SET @Addon1 = 0
									END

									IF (@ProductStartDate <> @ProductEndDate)
										AND (@CurrentDate <> @ProductEndDate)
										SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

									EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber
								END

								IF (@Day3 = 0)
								BEGIN
									SET @TmpProductStartDate = Convert(DATETIME, @ArrivalDate) + @Day2 - 1
									SET @TmpProductEndDate = Convert(DATETIME, @DepartureDate)

									IF (@CurrentDate >= @TmpProductStartDate)
									BEGIN
										SET @ProductStartDate = @TmpProductStartDate
										SET @ProductEndDate = @TmpProductEndDate

										EXEC ProductPricesDay @ProductNumber2, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon2 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct2 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

										SET @TmpProductNumber = @ProductNumber2

										IF (@PriceOverWritten2 = 1)
										BEGIN
											IF (@ProductStartDate <> @ProductEndDate)
												AND (@CurrentDate <> @ProductEndDate)
											BEGIN
												SET @PriceProduct2 = @FirstPrice2 * @NumberOfRooms
												SET @PriceOverwrittenValue = @FirstPrice2;

												IF @NameListSetting = 1
													AND @OnePersonPaysForAll = 0
												BEGIN
													SET @PriceProduct2 = @PriceProduct2 * (@Adults + @Children1 + @Children2)
													SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2);
												END
											END
											ELSE
											BEGIN
												SET @PriceOverwrittenValue = 0;
											END

											IF (@AddonIfPriceOverwritten = 0)
												SET @Addon2 = 0
										END

										IF (@ProductStartDate <> @ProductEndDate)
											AND (@CurrentDate <> @ProductEndDate)
											SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

										EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber2, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten2, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber

										EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber2, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct2 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

										SET @GetVatValueFromProduct2 = 1
									END
								END
								ELSE
								BEGIN
									SET @TmpProductStartDate = Convert(DATETIME, @ArrivalDate) + @Day2 - 1
									SET @TmpProductEndDate = Convert(DATETIME, @ArrivalDate) + @Day3 - 1

									IF (@CurrentDate >= @TmpProductStartDate)
										AND (@CurrentDate <= @TmpProductEndDate)
									BEGIN
										SET @ProductStartDate = @TmpProductStartDate
										SET @ProductEndDate = @TmpProductEndDate

										EXEC ProductPricesDay @ProductNumber2, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon2 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct2 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

										SET @TmpProductNumber = @ProductNumber2

										IF (@PriceOverWritten2 = 1)
										BEGIN
											IF (@ProductStartDate <> @ProductEndDate)
												AND (@CurrentDate <> @ProductEndDate)
											BEGIN
												SET @PriceProduct2 = @FirstPrice2 * @NumberOfRooms
												SET @PriceOverwrittenValue = @FirstPrice2;

												IF @NameListSetting = 1
													AND @OnePersonPaysForAll = 0
												BEGIN
													SET @PriceProduct2 = @PriceProduct2 * (@Adults + @Children1 + @Children2)
													SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2);
												END
											END
											ELSE
											BEGIN
												SET @PriceOverwrittenValue = 0;
											END

											IF (@AddonIfPriceOverwritten = 0)
												SET @Addon2 = 0
										END

										IF (@ProductStartDate <> @ProductEndDate)
											AND (@CurrentDate <> @ProductEndDate)
											SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

										EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber2, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct2 OUTPUT, @VatByPacketValueProduct2 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten2, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber

										EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber2, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct2 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

										SET @GetVatValueFromProduct2 = 1
									END

									IF (@Day4 = 0)
									BEGIN
										SET @TmpProductStartDate = Convert(DATETIME, @ArrivalDate) + @Day3 - 1
										SET @TmpProductEndDate = Convert(DATETIME, @DepartureDate)

										IF (@CurrentDate >= @TmpProductStartDate)
										BEGIN
											SET @ProductStartDate = @TmpProductStartDate
											SET @ProductEndDate = @TmpProductEndDate

											EXEC ProductPricesDay @ProductNumber3, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon3 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct3 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

											SET @TmpProductNumber = @ProductNumber3

											IF (@PriceOverWritten3 = 1)
											BEGIN
												IF (@ProductStartDate <> @ProductEndDate)
													AND (@CurrentDate <> @ProductEndDate)
												BEGIN
													SET @PriceProduct3 = @FirstPrice3 * @NumberOfRooms
													SET @PriceOverwrittenValue = @FirstPrice3;

													IF @NameListSetting = 1
														AND @OnePersonPaysForAll = 0
													BEGIN
														SET @PriceProduct3 = @PriceProduct3 * (@Adults + @Children1 + @Children2)
														SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2);
													END
												END
												ELSE
												BEGIN
													SET @PriceOverwrittenValue = 0;
												END

												IF (@AddonIfPriceOverwritten = 0)
													SET @Addon3 = 0
											END

											IF (@ProductStartDate <> @ProductEndDate)
												AND (@CurrentDate <> @ProductEndDate)
												SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

											EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber3, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten3, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber

											EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber3, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct3 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

											SET @GetVatValueFromProduct3 = 1
										END
									END
									ELSE
									BEGIN
										SET @TmpProductStartDate = Convert(DATETIME, @ArrivalDate) + @Day3 - 1
										SET @TmpProductEndDate = Convert(DATETIME, @ArrivalDate) + @Day4 - 1

										IF (@CurrentDate >= @TmpProductStartDate)
											AND (@CurrentDate <= @TmpProductEndDate)
										BEGIN
											SET @ProductStartDate = @TmpProductStartDate
											SET @ProductEndDate = @TmpProductEndDate

											EXEC ProductPricesDay @ProductNumber3, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon3 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct3 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

											SET @TmpProductNumber = @ProductNumber3

											IF (@PriceOverWritten3 = 1)
											BEGIN
												IF (@ProductStartDate <> @ProductEndDate)
													AND (@CurrentDate <> @ProductEndDate)
												BEGIN
													SET @PriceProduct3 = @FirstPrice3 * @NumberOfRooms
													SET @PriceOverwrittenValue = @FirstPrice3;

													IF @NameListSetting = 1
														AND @OnePersonPaysForAll = 0
													BEGIN
														SET @PriceProduct3 = @PriceProduct3 * (@Adults + @Children1 + @Children2)
														SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2);
													END
												END
												ELSE
												BEGIN
													SET @PriceOverwrittenValue = 0;
												END

												IF (@AddonIfPriceOverwritten = 0)
													SET @Addon3 = 0
											END

											IF (@ProductStartDate <> @ProductEndDate)
												AND (@CurrentDate <> @ProductEndDate)
												SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

											EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber3, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct3 OUTPUT, @VatByPacketValueProduct3 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten3, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber

											EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber3, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct3 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

											SET @GetVatValueFromProduct3 = 1
										END

										SET @TmpProductStartDate = Convert(DATETIME, @ArrivalDate) + @Day4 - 1
										SET @TmpProductEndDate = Convert(DATETIME, @DepartureDate)

										IF (@CurrentDate >= @TmpProductStartDate)
											AND (@CurrentDate <= @TmpProductEndDate)
										BEGIN
											SET @ProductStartDate = @TmpProductStartDate
											SET @ProductEndDate = @TmpProductEndDate

											EXEC ProductPricesDay @ProductNumber4, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @PaysAdults, @PaysChildren1, @PaysChildren2, @Addon4 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct4 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT, @NameListSetting, @OnePersonPaysForAll

											SET @TmpProductNumber = @ProductNumber4

											IF (@PriceOverWritten4 = 1)
											BEGIN
												IF (@ProductStartDate <> @ProductEndDate)
													AND (@CurrentDate <> @ProductEndDate)
												BEGIN
													SET @PriceProduct4 = @FirstPrice4 * @NumberOfRooms
													SET @PriceOverwrittenValue = @FirstPrice4;

													IF @NameListSetting = 1
														AND @OnePersonPaysForAll = 0
													BEGIN
														SET @PriceProduct4 = @PriceProduct4 * (@Adults + @Children1 + @Children2)
														SET @PriceOverwrittenValue = @PriceOverwrittenValue * (@Adults + @Children1 + @Children2);
													END
												END
												ELSE
												BEGIN
													SET @PriceOverwrittenValue = 0;
												END

												IF (@AddonIfPriceOverwritten = 0)
													SET @Addon4 = 0
											END

											IF (@ProductStartDate <> @ProductEndDate)
												AND (@CurrentDate <> @ProductEndDate)
												SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1

											EXEC CalcPacketPriceAccExt 0, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber4, @PaysAdults, @PaysChildren1, @PaysChildren2, 1, @HotelCustomerNumber, @PackagePriceProduct4 OUTPUT, @VatByPacketValueProduct4 OUTPUT, @NameListSetting, @OnePersonPaysForAll, 0, @PriceOverwritten4, 0, 1, @Referencenumber, @GuestNumber, @PriceOverwrittenValue, 1, @DiscountRate, @ProductWareLinkNumber

											EXEC GetVatValueAndAccountnumbers @GenerateDayProduct, @GetVatFrom, @ProductNumber4, @WareNumber OUTPUT, @BalanceAccountNumber OUTPUT, @ResultAccountNumber OUTPUT, @VATAccountNumber OUTPUT, @VatValueRoomProduct4 OUTPUT, @WareText OUTPUT, @WareGroupNumber OUTPUT

											SET @GetVatValueFromProduct4 = 1
										END
									END
								END
							END -- END *-product   
						END -- end Not DayProduct   
						ELSE -- Dayproduct   
						BEGIN
							SET @ProductStartDate = Convert(DATETIME, @ArrivalDate) --SG/20121218
							SET @ProductEndDate = Convert(DATETIME, @DepartureDate) --SG/20121218

							IF (
									(@PriceOverWritten = 0)
									AND (@ProductNumber > 0)
									)
							BEGIN
								EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT

								SET @TmpProductNumber = @ProductNumber

								IF (@PacketNumber > 0)
									EXEC CalcPacketPriceAccExt 1, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @Adults, @Children1, @Children2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, 1 /*NameListSetting must be 1*/, 0, 0, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceProduct1, 1, 0, @ProductWareLinkNumber
								ELSE
								BEGIN
									SET @PackagePriceProduct1 = 0
									SET @VatByPacketValueProduct1 = 0
								END
							END
							ELSE
							BEGIN
								IF @ProductNumber > 0
								BEGIN
									EXEC ProductPricesDay @ProductNumber, @ProductStartDate, @ProductEndDate, @ProductPriceDate, @AllocatedTypeNumber, @NumberOfRooms, @Adults, @Children1, @Children2, @Addon1 OUTPUT, @BillTextProduct OUTPUT, @BillTextAddOnProduct OUTPUT, @PriceProduct1 OUTPUT, @PacketNumber OUTPUT, @EnviromentFee OUTPUT, @FixedPrice OUTPUT, @VATProduct OUTPUT, @SpecifiedDepartureAddOn OUTPUT

									SET @TmpProductNumber = @ProductNumber

									IF @FixedPrice = 1
									BEGIN
										IF (@PriceOverWritten = 1)
										BEGIN
											IF isnull(@Price, 0) = 0
												SET @Price = 0
											SET @PriceProduct1 = @Price * @NumberOfRooms
										END
									END
									ELSE
									BEGIN
										IF (@PriceOverWritten = 1)
										BEGIN
											IF isnull(@Price, 0) = 0
												SET @Price = 0
											SET @PriceProduct1 = (Convert(MONEY, (@Price * @Adults)) + Convert(MONEY, (@Price * @Children1)) + Convert(MONEY, (@Price * @Children2))) * @NumberOfRooms
										END
									END

									IF (@PacketNumber > 0)
										EXEC CalcPacketPriceAccExt 1, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumber, @ProductNumber, @Adults, @Children1, @Children2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, 1 /*NameListSetting must be 1*/, 0, 0, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceProduct1, 1, 0, @ProductWareLinkNumber
									ELSE
									BEGIN
										SET @PackagePriceProduct1 = 0
										SET @VatByPacketValueProduct1 = 0
									END
								END
								ELSE --    
								BEGIN
									SET @FixedPrice = 0
									SET @PriceProduct1 = @Price * @NumberOfRooms * (@Adults + @Children1 + @Children2)
									SET @PacketNumber = @PacketNumberReservation

									IF (@PacketNumberReservation > 0)
										EXEC CalcPacketPriceAccExt 1, @AllocatedTypeNumber, @CurrentDateStr, @PacketNumberReservation, @ProductNumber, @Adults, @Children1, @Children2, 1, @HotelCustomerNumber, @PackagePriceProduct1 OUTPUT, @VatByPacketValueProduct1 OUTPUT, 1 /*NameListSetting must be 1*/, 0, 0, @PriceOverwritten, 0, 1, @Referencenumber, @GuestNumber, @PriceProduct1, 1, 0, @ProductWareLinkNumber
									ELSE
									BEGIN
										SET @PackagePriceProduct1 = 0
										SET @VatByPacketValueProduct1 = 0
									END
								END
							END

							IF @FixedPrice = 0
								SET @ValueType = 3
							ELSE
								SET @ValueType = 2
						END -- End DayProduct   
					END -- END Booked values   

					IF (@CurrentDateStr = @DepartureDate)
						AND (@ArrivalDate <> @DepartureDate)
						AND (@TableCount = 1)
					BEGIN
						IF (
								(@IncludeDayroomsInSoldRooms = 1)
								AND (@DepartureTime > @DayroomsLaterThanTime)
								)
							AND (@CurrentDateStr < @SystemDateStr)
						BEGIN
							IF @PrevLineNumber = @LineNumber
								AND (@PrevReferenceNumber = @ReferenceNumber)
								AND (@PrevGuestNumber <> @GuestNumber)
								AND @TableCount = 1
								AND (@SmallestArrivalDate <= @CurrentDateStr)
								AND (
									(
										(@BiggestDepartureDate >= @CurrentDateStr)
										AND (@DepartureDate <= @BiggestDepartureDate)
										)
									OR (
										(@BiggestDepartureDate > @CurrentDateStr)
										AND (@DepartureDate > @BiggestDepartureDate)
										)
									)
								AND @ArrivalDate >= @SmallestArrivalDate
							BEGIN
								SET @BookedNumberOfRooms = 0
							END
							ELSE
								SET @BookedNumberOfRooms = @NumberOfRooms

							SET @TotalAdults = @Adults * @NumberOfRooms
							SET @TotalChildren1 = @Children1 * @NumberOfRooms
							SET @TotalChildren2 = @Children2 * @NumberOfRooms
						END
						ELSE
						BEGIN
							SET @TotalAdults = 0
							SET @TotalChildren1 = 0
							SET @TotalChildren2 = 0
							SET @BookedNumberOfRooms = 0
						END

						SET @PriceProduct1 = 0
						SET @PriceProduct2 = 0
						SET @PriceProduct3 = 0
						SET @PriceProduct4 = 0

						IF @StarProduct = 0
						BEGIN
							SET @PackagePrice = @PackagePriceProduct1 * @NumberOfRooms
							SET @VatOfPacket = @VatByPacketValueProduct1 * @NumberOfRooms
							SET @VatOfPrice = @PriceProduct1 * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))
							SET @VatOfAddon = @Addon1 * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))
						END
						ELSE
						BEGIN
							SET @VatOfPrice = (((@PriceProduct1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@PriceProduct2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@PriceProduct3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@PriceProduct4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))
							SET @PackagePrice = (@PackagePriceProduct1 + @PackagePriceProduct2 + @PackagePriceProduct3 + @PackagePriceProduct4) * @NumberOfRooms
							SET @VatOfPacket = (@VatByPacketValueProduct1 + @VatByPacketValueProduct2 + @VatByPacketValueProduct3 + @VatByPacketValueProduct4) * @NumberOfRooms
							SET @VatOfAddon = (((@Addon1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@Addon2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@Addon3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@Addon4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))
						END
					END
					ELSE
					BEGIN
						IF @PrevLineNumber = @LineNumber
							AND (@PrevReferenceNumber = @ReferenceNumber)
							AND (@PrevGuestNumber <> @GuestNumber)
							AND @TableCount = 1
							AND (@SmallestArrivalDate <= @CurrentDateStr)
							AND (
								(
									(@BiggestDepartureDate >= @CurrentDateStr)
									AND (@DepartureDate <= @BiggestDepartureDate)
									)
								OR (
									(@BiggestDepartureDate > @CurrentDateStr)
									AND (@DepartureDate > @BiggestDepartureDate)
									)
								)
							AND @ArrivalDate >= @SmallestArrivalDate
						BEGIN
							SET @BookedNumberOfRooms = 0
						END
						ELSE
							SET @BookedNumberOfRooms = @NumberOfRooms

						IF ISNULL(@PriceProduct1, 0) = 0
							SET @PriceProduct1 = 0

						IF ISNULL(@PriceProduct2, 0) = 0
							SET @PriceProduct2 = 0

						IF ISNULL(@PriceProduct3, 0) = 0
							SET @PriceProduct3 = 0

						IF ISNULL(@PriceProduct4, 0) = 0
							SET @PriceProduct4 = 0

						IF isnull(@Addon1, 0) = 0
							SET @Addon1 = 0

						IF isnull(@Addon2, 0) = 0
							SET @Addon2 = 0

						IF isnull(@Addon3, 0) = 0
							SET @Addon3 = 0

						IF isnull(@Addon4, 0) = 0
							SET @Addon4 = 0

						IF ISNULL(@NumberOfRooms, 0) = 0
							SET @NumberOfRooms = 1

						IF (
								(@TableCount = 2)
								OR (
									(@StarProduct = 0)
									AND (@TableCount = 1)
									)
								) --not Dayproduct
						BEGIN
							SET @PackagePrice = @PackagePriceProduct1 * @NumberOfRooms
							SET @VatOfPacket = @VatByPacketValueProduct1 * @NumberOfRooms
							SET @VatOfPrice = ((@PriceProduct1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))) --* @NumberOfRooms
							SET @VatOfAddon = @Addon1 * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1))))
						END
						ELSE
						BEGIN
							SET @VatOfPrice = (((@PriceProduct1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@PriceProduct2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@PriceProduct3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@PriceProduct4 + @Addon4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1)))))) --* @NumberOfRooms
							SET @PackagePrice = (@PackagePriceProduct1 + @PackagePriceProduct2 + @PackagePriceProduct3 + @PackagePriceProduct4) * @NumberOfRooms
							SET @VatOfPacket = (@VatByPacketValueProduct1 + @VatByPacketValueProduct2 + @VatByPacketValueProduct3 + @VatByPacketValueProduct4) * @NumberOfRooms
							SET @VatOfAddon = (((@Addon1) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct1 / 100) + 1)))) + (@Addon2) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct2 / 100) + 1)))) + (@Addon3) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct3 / 100) + 1)))) + (@Addon4) * (1 - (1 / CONVERT(FLOAT, ((@VatValueRoomProduct4 / 100) + 1))))))
						END

						SET @TotalAdults = @Adults * @NumberOfRooms
						SET @TotalChildren1 = @Children1 * @NumberOfRooms
						SET @TotalChildren2 = @Children2 * @NumberOfRooms
					END

					IF isnull(@SegmentNumber, 0) = 0
						SET @SegmentNumber = 0

					IF (@SegmentNumber = 0)
						SELECT @SegmentNumber = Number
						FROM Segments WITH (NOLOCK)
						WHERE (
								(MarkAsDeleted = '0')
								OR (MarkAsDeleted IS NULL)
								)

					IF isnull(@PointOfSaleNumber, 0) = 0
						SET @PointOfSaleNumber = 0

					IF (@PointOfSaleNumber = 0)
						SELECT @PointOfSaleNumber = Number
						FROM PointOfSales WITH (NOLOCK)
						WHERE (
								(MarkAsDeleted = '0')
								OR (MarkAsDeleted IS NULL)
								)

					SET @TotalPriceDay = @PriceProduct1 + @PriceProduct2 + @PriceProduct3 + @PriceProduct4 -- + @Addon1 + @Addon2 + @Addon3 + @Addon4
					SET @Addon = @Addon1 + @Addon2 + @Addon3 + @Addon4
					SET @tmpProductWareLinkNumberMis = @ProductWareLinkNumber

					IF (
							(@Status = 6)
							OR (@Status = 5)
							)
						AND (@CurrentDate < @SystemDate) -- Only resolve pieces and pax when outofhouse and inhouse reservation before systemdate and on systemdate
					BEGIN
						SET @TotalPriceDay = 0
						SET @VatOfPrice = 0
						SET @Addon = 0
						SET @VatOfAddon = 0
						--set @TmpProductNumber = null
						SET @tmpProductWareLinkNumberMis = - 1
					END

					IF (@CurrentDate < @SystemDate - 1)
						DELETE
						FROM #PacketWareTable

					--*** Extras start
					SELECT @cnt = COUNT(*)
					FROM #ReferenceExtrasTable(NOLOCK)
					WHERE ReferenceNumber = @ReferenceNumber
						AND CurrentDate = @CurrentDateStr

					IF (ISNULL(@cnt, 0) = 0)
						AND (@CurrentDateStr >= @SystemDateStr)
					BEGIN
						EXEC MisStoreExtrasAndCalcDiscount @OrderBookBudgetCalcDiscount, @DiscountAsNettoPrice, @ChargeDiscountAsProduct, @DiscountVatValueWare, @Room_HallType, @ReferenceNumber, @FolioNumber, @CurrentDateStr, @SegmentNumber, @PointOfSaleNumber, @AllocatedTypeNumber, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @DiscountResultAccountNumber

						INSERT INTO #ReferenceExtrasTable
						VALUES (@ReferenceNumber, @CurrentDateStr)
					END

					--**** Extras end
					IF (@CurrentDateStr < @SystemDateStr)
					BEGIN
						IF (@Plenum = 0)
							SET @tmpUpdateType = 1
						ELSE
							SET @tmpUpdateType = 2
					END
					ELSE
					BEGIN
						IF (@Plenum = 0)
							SET @tmpUpdateType = 3
						ELSE
							SET @tmpUpdateType = 4
					END

					IF @TableCount = 1
						AND @PackageSameDayAsLogi = 1
						AND @CurrentDateStr = @DepartureDate
						SET @tmpSameDayAsLogi = 1
					ELSE
						SET @tmpSameDayAsLogi = 0

					-- Store Logi
					SELECT TOP 1 @DepartmentNumber = PK_Department
					FROM Departments d WITH (NOLOCK)
					INNER JOIN ReservationMain r WITH (NOLOCK) ON d.HotelNumber = r.HotelNumber
						AND AutoCharge = 1
						AND ISNULL(MarkAsDeleted, 0) = 0
						AND ReferenceNumber = @ReferenceNumber

					SET @DepartmentNumber = isnull(@DepartmentNumber, - 1)
					SET @ResultAccountNumber = isnull(@ResultAccountNumber, - 1)

					EXEC MisStoreLogiAndCalcDiscount @Room_HallType, @OrderBookBudgetCalcDiscount, @DiscountAsNettoPrice, @ChargeDiscountAsProduct, @DiscountVatValueWare, @SplitBillNumber, @FixedPrice, @tmpUpdateType, @tmpSameDayAsLogi, @ValueType, @BookedNumberOfRooms, @TotalAdults, @TotalChildren1, @TotalChildren2, @ReferenceNumber, @GuestNumber, @FolioNumber, @SystemDateStr, @CurrentDateStr, @CurrentDateStrDeparturePackage, @SegmentNumber, @PointOfSaleNumber, @AllocatedTypeNumber, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @WareGroupNumber, @WareNumber, @OwnerReservation, @DepartmentNumber, @tmpProductWareLinkNumberMis, @ResultAccountNumber, @DiscountResultAccountNumber, @TotalPriceDay, @VatOfPrice, @PackagePrice, @VatOfPacket, @TmpProductNumber

					-- Store addons
					IF (
							@Addon <> 0
							OR @VatOfAddon <> 0
							)
					BEGIN
						SET @TempCurrentDateStr = @CurrentDateStr

						IF @Room_HallType = 0
							IF (@CurrentDateStr = @DepartureDate)
								SET @TempCurrentDateStr = CONVERT(CHAR(8), @CurrentDate - 1, 112)

						EXEC UpdateMISTable @SystemDateStr, @Room_HallType, @ReferenceNumber, @GuestNumber, - 1, @tmpUpdateType, @tmpSameDayAsLogi, 0 /*@BookedNumberOfRooms*/, 0 /*@TotalAdults*/, 0 /*@TotalChildren1*/, 0 /* @TotalChildren2*/, @Addon, @VatOfAddon, 0, 0, @TempCurrentDateStr, @CurrentDateStrDeparturePackage, @SegmentNumber, @PointOfSaleNumber, @AllocatedTypeNumber, @ValueType, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, - 1, 0, '', @OwnerReservation, @TmpProductNumber
					END

					-- Store Packages
					IF (@CurrentDate < @SystemDate - 1)
					BEGIN
						IF (@Plenum = 0)
							SET @tmpUpdateType = 1
						ELSE
							SET @tmpUpdateType = 2
					END
					ELSE
					BEGIN
						IF (@Plenum = 0)
							SET @tmpUpdateType = 3
						ELSE
							SET @tmpUpdateType = 4
					END

					DECLARE PacketWareCur CURSOR FAST_FORWARD READ_ONLY
					FOR
					SELECT *
					FROM #PacketWareTable WITH (NOLOCK)

					OPEN PacketWareCur

					FETCH NEXT
					FROM PacketWareCur
					INTO @ResultAccountPackage, @DepartmentNumberPackage, @PacketWarePrice, @VatOfPacketWarePrice, @WareGroupNumber, @WareName, @ProductWareLinkNumberMis, @ProductNumberPacket

					IF (@CurrentDate >= @SystemDate)
					BEGIN
						SET @PackageStored = 0

						IF (@@FETCH_STATUS <> - 1)
							SET @PackageStored = 1

						WHILE (@@FETCH_STATUS <> - 1)
						BEGIN
							--				if (@CurrentDate = @ProductEndDate) and (@CurrentDate = @SystemDate)
							IF (@CurrentDate = @SystemDate)
							BEGIN
								IF @TableCount = 2
									OR @SystemDate < @ProductEndDate -- SG/20121219
									SET @ProductWareLinkNumberMis = - 200 -- Later in MisUpdateProductWareLinkNumbers this packet will be pared with product that is already posted in actual
								ELSE
									SET @ProductWareLinkNumberMis = - 100 -- SG/20130124: Room-package on departure day comes from transaction and should not be included here.
							END

							SET @DepartmentNumberPackage = isnull(@DepartmentNumberPackage, - 1)
							SET @ResultAccountPackage = isnull(@ResultAccountPackage, - 1)

							IF (@PacketWarePrice <> 0)
								OR (@VatOfPacketWarePrice <> 0)
							BEGIN
								SET @PacketWarePrice = @PacketWarePrice * @NumberOfRooms
								SET @VatOfPacketWarePrice = @VatOfPacketWarePrice * @NumberOfRooms

								IF @ProductWareLinkNumberMis <> - 100 -- SG/20130124: See above
								BEGIN
									EXEC UpdateMISTable @SystemDateStr, @Room_HallType, @ReferenceNumber, @GuestNumber, - 1, @tmpUpdateType, @tmpSameDayAsLogi, 0, 0, 0, 0, 0, 0, @VatOfPacketWarePrice, @PacketWarePrice, @CurrentDateStr, @CurrentDateStrDeparturePackage, @SegmentNumber, @PointOfSaleNumber, @AllocatedTypeNumber, @ValueType, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @WareGroupNumber, @ResultAccountPackage, @DepartmentNumberPackage, @ProductWareLinkNumberMis, 1, @WareName, @OwnerReservation, @ProductNumberPacket
								END
							END

							FETCH NEXT
							FROM PacketWareCur
							INTO @ResultAccountPackage, @DepartmentNumberPackage, @PacketWarePrice, @VatOfPacketWarePrice, @WareGroupNumber, @WareName, @ProductWareLinkNumberMis, @ProductNumberPacket
						END
					END

					IF (@TableCount <> 1)
					BEGIN -- DayProduct
						SET @ProductWareLinkNumber = @ProductWareLinkNumber + 1
					END

					CLOSE PacketWareCur

					DEALLOCATE PacketWareCur

					SET @CurrentDate = @CurrentDate + 1
					SET @CurrentDateStr = Convert(CHAR(8), @CurrentDate, 112)
					SET @CurrentDateStrDeparturePackage = CONVERT(CHAR(8), @CurrentDate - 1, 112)
				END -- End While   
			END -- End @PrevLineNumber<>@LINENUMBER   

			SET @OneDayBack = 0

			IF @LINENUMBER = @PrevLineNumber
			BEGIN
				IF @ArrivalDate < @SmallestArrivalDate
					SET @SmallestArrivalDate = @ArrivalDate

				IF @BiggestDepartureDate < @DepartureDate
					SET @BiggestDepartureDate = @DepartureDate
			END
			ELSE
			BEGIN
				SET @SmallestArrivalDate = @ArrivalDate
				SET @BiggestDepartureDate = @DepartureDate
			END

			SET @PrevLineNumber = @LINENUMBER
			SET @PrevReferenceNumber = @ReferenceNumber

			IF (@TableCount = 1)
			BEGIN
				SET @PrevGuestNumber = @GuestNumber

				FETCH NEXT
				FROM ReservationCur
				INTO @Room_HallType, @LINENUMBER, @BookedTypeNumber, @RoomNumber, @ReferenceNumber, @GuestNumber, @Status, @SegmentNumber, @PointOfSaleNumber, @ArrivalDate, @DepartureDate, @DepartureTime, @Adults, @Children1, @Children2, @PaysAdults, @PaysChildren1, @PaysChildren2, @ProductNumber, @NumberOfRooms, @PriceOverwritten, @Price, @FirstPrice1, @PriceOverwritten2, @FirstPrice2, @Day2, @ProductNumber2, @PriceOverwritten3, @FirstPrice3, @Day3, @ProductNumber3, @PriceOverwritten4, @FirstPrice4, @Day4, @ProductNumber4, @ConferenceLineOnRes, @ConflineOnMainRes, @HotelCustomerNumber, @NameListSetting, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber
			END
			ELSE
			BEGIN
				FETCH NEXT
				FROM ReservationCur
				INTO @Room_HallType, @BookedTypeNumber, @LINENUMBER, @RoomNumber, @ArrivalDate, @DepartureDate, @ProductNumber, @NumberOfRooms, @Status, @PriceOverWritten, @Adults, @Children1, @Children2, @Price, @ReferenceNumber, @PacketNumberReservation, @ArrArrivalTime, @ArrDepartureTime, @HotelCustomerNumber, @Plenum, @CampaignCode, @ProjectCode, @StaffID, @OwnerReservation, @SplitBillNumber
			END
		END -- Fetch   

		CLOSE ReservationCur

		DEALLOCATE ReservationCur
	END -- END WHILE  
END

-- ***************** Transaction section ************************
Print '***************** Transaction section ************************'

IF (@CalcSystemDateOnly = 1)
	SET @FormatedStartDate = @SystemDateStr

-- New part that consider Sales and invoice folios
DECLARE TransCur CURSOR FAST_FORWARD READ_ONLY
FOR
SELECT DISTINCT Convert(CHAR(8), Transactions.DateStamp, 112) AS OriginalDate, Isnull(Folios.Referencenumber, - 1) AS FolioNumber, Folios.FolioNumber, CASE 
		WHEN Transactions.Debit = 0
			THEN transactions.Priceoverwrite
		ELSE (Transactions.Priceoverwrite * - 1)
		END AS SumTotal, 
		
		CASE WHEN (IsNull(Reservations.MarketSegment, 0) = 0)
		  THEN IsNull(customer.SegmentNumber, 0)
		  ELSE Reservations.MarketSegment
		END AS MarketSegment, 
		
		CASE WHEN (IsNull(Reservations.PointOfSale, 0) = 0)
		  THEN IsNull(customer.PointOfSaleNumber, 0)
		  ELSE Reservations.PointOfSale
		END AS PointOfSale, 
		
		WareGroups.WareType AS MISType, WareGroups.Payment, transactions.VATValue, Transactions.HotelCustomerNumber, ISNULL(CAST(Reservations.STATUS AS INT), - 1) AS ReservationStatus, ISNULL(RESERVATIONS.FK_CampaignCode, - 1) AS CampaignCode, ISNULL(RESERVATIONMAIN.FK_ProjectCode, - 1) AS ProjectCode, Transactions.UserIDNumber AS StaffID, CASE 
		WHEN (Transactions.MovedDeleted = 1)
			THEN 1
		ELSE 0
		END AS Correction, CASE 
		WHEN PERSONEL.UserTypeNumber NOT IN (
				3
				,4
				)
			THEN 1
		ELSE 0
		END AS ManuelUser, CASE 
		WHEN isnull(Transactions.PackageNumber, - 1) > 0
			AND transactions.Showonbillflag = 0
			AND Transactions.ProductWareLinkNumber > 0
			AND WareGroups.Payment NOT IN (
				2
				,3
				)
			THEN 1
		ELSE 0
		END AS IsPackage, WareGroups.SortNumber AS WareGroupNumber, Transactions.GlobalTransactionNumber, Transactions.TransactionNumber, isnull(Transactions.PAXadult, 0) AS PAXAdult, isnull(Transactions.PAXchild1, 0) AS PAXchild1, isnull(Transactions.PAXchild2, 0) AS PAXchild2, Transactions.Pieces, Transactions.Debit, Transactions.ProductNumber, isnull(Transactions.ProductWareLinkNumber, - 1) AS PWLN, Transactions.AccountNumber, Transactions.ShowOnBillFlag, Transactions.FK_DepartmentNumber, isnull(Transactions.GuestNumber, 0) AS GuestNumber, Products.FixedPrice, Products.DayProduct, CASE 
		WHEN Accounts.Balance = 2
			AND Accounts.AccountType IN (5)
			THEN 1
		ELSE 0
		END AS InhouseDebitor, PERSONEL.UserTypeNumber, CASE 
		WHEN (
				Transactions.MovedDeleted = 1
				AND Transactions.MovedFolioNr IS NOT NULL
				)
			THEN 1
		ELSE 0
		END AS Moved, CASE 
		WHEN (
				Transactions.MovedDeleted = 1
				AND Transactions.MovedFolioNr IS NULL
				)
			THEN 1
		ELSE 0
		END AS Deleted
FROM transactions WITH (NOLOCK)
INNER JOIN Folios WITH (NOLOCK) ON Folios.FolioNumber = Transactions.FolioNumber
LEFT OUTER JOIN FolioRestResTableChairsXTab WITH (NOLOCK) ON FolioRestResTableChairsXTab.FolioNumber = Folios.FolioNumber
LEFT OUTER JOIN RESERVATIONADDRESS WITH (NOLOCK) ON RESERVATIONADDRESS.AddressNumber = Folios.ReservationAddressNumber -- altered

LEFT OUTER JOIN customer WITH (NOLOCK) ON RESERVATIONADDRESS.link = customer.CustomerNumber

LEFT OUTER JOIN Reservations WITH (NOLOCK) ON Folios.ReferenceNumber = Reservations.ReferenceNumber
	AND Folios.GuestNumber = Reservations.GuestNumber
LEFT OUTER JOIN RESERVATIONMAIN WITH (NOLOCK) ON Folios.ReferenceNumber = RESERVATIONMAIN.ReferenceNumber
INNER JOIN Ware WITH (NOLOCK) ON Ware.WareNumber = Transactions.WareNumber
INNER JOIN WareGroups WITH (NOLOCK) ON WareGroups.WareGroupNumber = Ware.WareGroupNumber
LEFT OUTER JOIN Accounts WITH (NOLOCK) ON Accounts.AccountNumber = Transactions.AccountNumber
LEFT OUTER JOIN Products WITH (NOLOCK) ON Products.ProductNumber = Transactions.ProductNumber
LEFT OUTER JOIN PERSONEL WITH (NOLOCK) ON PERSONEL.UserIDNumber = Transactions.UserIDNumber
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 (
		Accounts.Balance = 1
		AND Accounts.AccountType NOT IN (
			1
			,2
			)
		)
	AND -- Accounts transactions
	(
		(
			Folios.FolioNumber IN (
				SELECT *
				FROM #FoliosCrossDate WITH (NOLOCK)
				)
			AND (Convert(CHAR(8), Transactions.DateStamp, 112) <= @SystemDateStr)
			)
		AND WareGroups.Payment NOT IN (1)
		AND --Waregroup type Payment is not included.
		(
			ISNULL(@DebugReferenceNumber, - 1) = - 1
			OR Folios.Referencenumber = @DebugReferenceNumber
			)
		)
	AND (
		@InternalCourseProduction = 0 --normal
		OR (
			@InternalCourseProduction = 1
			AND @MainCourceResNotInclMIS_OrderBook = 0
			) --incl main course res.
		OR (
			@InternalCourseProduction = 1
			AND isnull(FK_ReferenceNumber, 0) = 0
			) --not a main res
		)
ORDER BY Isnull(Folios.Referencenumber, - 1), isnull(Transactions.ProductWareLinkNumber, - 1), Convert(CHAR(8), Transactions.DateStamp, 112)

OPEN TransCur

FETCH NEXT
FROM TransCur
INTO @tmpTransdate, @ReferenceNumber, @FolioNumber, @Totalsum, @SegmentNumber, @PointOfSaleNumber, @MisType, @WarePayment, @VatValueWare, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @Correction, @ManuelUser, @IsPackage, @WareGroupNumber, @GlobalTransactionNumber, @TransactionNumber, @Adults, @Children1, @Children2, @Pieces, @Debit, @ProductNumber, @ProductWareLinkNumber, @ResultAccountNumber, @ShowOnBillFlag, @DepartmentNumber, @GuestNumber, @FixedPrice, @DayProduct, @InhouseDebitor, @UserTypeNumber, @TransactionMoved, @TransactionDeleted

SET @tmpProductWareLinkNumberTrans = - 1
SET @Room_HallType = 0

WHILE (@@FETCH_STATUS <> - 1)
BEGIN
	IF @PackageSameDayAsLogi = 1
	BEGIN
		IF @ProductWareLinkNumber <= 0
			SET @TransDate = @tmpTransDate -- Do nothing
		ELSE IF (@ProductWareLinkNumber > 0)
			AND (@tmpProductWareLinkNumberTrans <> @ProductWareLinkNumber)
			SET @TransDate = @tmpTransdate -- Get the first date in the serie of a ProductWareLinkNumber	
		SET @tmpProductWareLinkNumberTrans = @ProductWareLinkNumber
	END
	ELSE
		SET @TransDate = @tmpTransdate

	IF isnull(@PointOfSaleNumber, 0) = 0
		SET @PointOfSaleNumber = @DefaultMISPointOfSale

	IF isnull(@SegmentNumber, 0) = 0
		SET @SegmentNumber = @DefaultMISSegment

	IF @ProductWareLinkNumber = 0
		SET @ProductWareLinkNumber = - 1

	IF isnull(@MisType, - 1) = - 1
		SET @MisType = 1
	SET @PackagePrice = 0

	IF (@IsPackage = 1)
	BEGIN
		SET @PackagePrice = (@TotalSum) * convert(FLOAT, ((@VatValueWare / 100) + 1))
		SET @Totalsum = 0
	END

	-- Find roomtype here and if guest has stayed on the hotel
	SET @RoomTypeNumber = 0
	SET @ArrivalDate = NULL
	SET @DepartureDate = NULL
	SET @OwnerReservation = 0

	IF (
			(@WarePayment = 2)
			OR (@WarePayment = 7)
			)
		OR (
			(@IsPackage = 1)
			AND (@DayProduct = 0)
			) -- (AutoRoom or ManualRooms) or (if package and nigthproduct)
	BEGIN
		SELECT @RoomTypeNumber = ISNULL(Rooms.RoomTypeNumber /*allocated roomtype*/, ISNULL(RoomTypes.RoomTypeNumber /*booked roomtype*/, 0)), @ArrivalDate = CASE RESERVATIONS.GuestNumber
				WHEN 0
					THEN CASE ISNULL(RESERVATIONROOMLINE.LineNumber, 0)
							WHEN 0
								THEN RESERVATIONS.ArrivalDate
							ELSE RESERVATIONROOMLINE.ArrivalDate
							END
				ELSE RESERVATIONS.ArrivalDate
				END, @DepartureDate = CASE RESERVATIONS.GuestNumber
				WHEN 0
					THEN CASE ISNULL(RESERVATIONROOMLINE.LineNumber, 0)
							WHEN 0
								THEN RESERVATIONS.DepartureDate
							ELSE RESERVATIONROOMLINE.DepartureDate
							END
				ELSE RESERVATIONS.DepartureDate
				END, @OwnerReservation = CASE 
				WHEN (
						(
							Rooms.CustomerNumber IS NOT NULL
							AND RESERVATIONADDRESS.LINK IS NOT NULL
							)
						AND Rooms.CustomerNumber = RESERVATIONADDRESS.LINK
						)
					THEN 1
				ELSE 0
				END
		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
		INNER JOIN RESERVATIONMAIN WITH (NOLOCK) ON RESERVATIONMAIN.ReferenceNumber = RESERVATIONS.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 JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.ReferenceNumber = RESERVATIONS.ReferenceNumber
			AND ReservationAddressXTab.GuestNumber = RESERVATIONS.GuestNumber
			AND ReservationAddressXTab.AddressTypeNumber = 1
		LEFT JOIN ReservationAddress WITH (NOLOCK) ON ReservationAddress.AddressNumber = ReservationAddressXTab.AddressNumber
			AND ReservationAddress.AddressType = 1
		WHERE (
				RESERVATIONS.ReferenceNumber = @ReferenceNumber
				AND RESERVATIONS.GuestNumber = @GuestNumber
				)
	END

	SET @Adults = 0
	SET @Children1 = 0
	SET @Children2 = 0
	SET @Pieces = 0

	IF (@MisType = 1) -- Other
		SET @ValueType = 5 -- Other
	ELSE IF (@MisType = 2) -- Restaurant
		SET @ValueType = 4 -- Restaurant

	IF (@WarePayment = 2)
		OR (@WarePayment = 7) -- AutoRoom or ManualRooms. Must not follow any mistype. Allways include in mis.
	BEGIN
		SET @ValueType = 1

		GOTO Store
	END
	ELSE IF (@WarePayment = 3)
		OR (@WarePayment = 8) -- AutoHall or ManualHalls. Must not follow any mistype. Allways include in mis.
	BEGIN
		IF (@ProductNumber <= 0)
		BEGIN
			SET @FixedPrice = 0
		END

		IF @FixedPrice = 0 -- Daymeetings
			SET @ValueType = 3
		ELSE
			SET @ValueType = 2 -- Halls

		GOTO Store
	END

	IF (
			@MisType IN (
				1
				,2
				)
			)
		GOTO Store

	GOTO Skip

	Store:

	IF (@IsPackage = 1) -- Packages must follow the Rooms/Daymeeting/Halls category.
	BEGIN
		IF (@DayProduct = 0)
			SET @ValueType = 1
		ELSE
		BEGIN
			IF (@FixedPrice = 0) -- Daymeetings
				SET @ValueType = 3
			ELSE
				SET @ValueType = 2 -- Halls
		END
	END

	IF (
			@ValueType IN (
				2
				,3
				)
			)
		SET @RoomTypeNumber = 0 -- Catch and remove any roomtypes on halls and daymeetings

	IF (@ShowOnBillFlag = 0 /*and @InhouseDebitor = 0*/)
	BEGIN
		SET @Totalsum = (@Totalsum) * convert(FLOAT, ((@VatValueWare / 100) + 1))

		IF (@Debit = 1)
			SET @Pieces = @Pieces * - 1 -- of

		IF (@TransDate < @SystemDateStr)
		BEGIN
			-- Actual	
			INSERT INTO MISTABLE (DateStamp, ReferenceNumber, FolioNumber, SegmentNumber, PointOfSaleNumber, RoomTypeNumber, BookedAdult, BookedChildren1, BookedChildren2, BookedNumberOfRooms, BookedPrice, BookedVatOfPrice, BookedPackage, BookedVatOfPackage, ActualAdult, ActualChildren1, ActualChildren2, ActualNumberOfRooms, ActualPrice, ActualVatOfPrice, ActualPackage, ActualVatOfPackage, ValueType, HotelCustomerNumber, ReservationStatus, CampaignCode, ProjectCode, StaffID, AccountNumber, MisData, DepartmentNumber, ProductWareLinkNumber, IsPackage, GuestNumber, Room_HallType, CorrectionMoved, CorrectionDeleted, TEXT, WareGroupNumber, OwnerReservation, ProductNumber)
			VALUES (@TransDate, @ReferenceNumber, @FolioNumber, @SegmentNumber, @PointOfSaleNumber, @RoomTypeNumber, 0, 0, 0, 0, 0, 0, 0, 0, @Adults, @Children1, @Children2, @Pieces, @Totalsum, (@Totalsum * ((1 - (1 / convert(FLOAT, ((@VatValueWare / 100) + 1)))))), @PackagePrice, @PackagePrice * ((1 - (1 / convert(FLOAT, ((@VatValueWare / 100) + 1))))), @ValueType, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @ResultAccountNumber, 1, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @GuestNumber, @Room_HallType, @TransactionMoved, @TransactionDeleted, @Text, @WareGroupNumber, @OwnerReservation, @ProductNumber)
		END
	END

	Skip:

	FETCH NEXT
	FROM TransCur
	INTO @tmpTransdate, @ReferenceNumber, @FolioNumber, @Totalsum, @SegmentNumber, @PointOfSaleNumber, @MisType, @WarePayment, @VatValueWare, @HotelCustomerNumber, @Status, @CampaignCode, @ProjectCode, @StaffID, @Correction, @ManuelUser, @IsPackage, @WareGroupNumber, @GlobalTransactionNumber, @TransactionNumber, @Adults, @Children1, @Children2, @Pieces, @Debit, @ProductNumber, @ProductWareLinkNumber, @ResultAccountNumber, @ShowOnBillFlag, @DepartmentNumber, @GuestNumber, @FixedPrice, @DayProduct, @InhouseDebitor, @UserTypeNumber, @TransactionMoved, @TransactionDeleted
END

CLOSE TransCur

DEALLOCATE TransCur

DROP TABLE #ReferenceExtrasTable

DROP TABLE #PacketWareTable

EXEC MisUpdateProductWareLinkNumbers

DELETE
FROM MISTABLEPackSum

INSERT INTO MISTABLEPackSum
SELECT *
FROM MISPackagesSum()

IF @NightAuditRunning = 1
	UPDATE Hotelsetup
	SET KeyValue = @SystemDateStr
	WHERE Searchkey = 'LastMISUpdate'

DECLARE @Faktor FLOAT
DECLARE @BookedPrice MONEY
DECLARE @BookedVatOfPrice MONEY
DECLARE @PackageSum MONEY
DECLARE @PackageVatOfSum MONEY
DECLARE @BookedAdult INT
DECLARE @BookedChildren1 INT
DECLARE @BookedChildren2 INT
DECLARE @BookedPackage MONEY
DECLARE @BookedVatOfPackage MONEY
DECLARE @ActualAdult INT
DECLARE @ActualChildren1 INT
DECLARE @ActualChildren2 INT
DECLARE @ActualPackage MONEY
DECLARE @ActualVatOfPackage MONEY
DECLARE @ActualNumberOfRooms INT
DECLARE @ActualPrice MONEY
DECLARE @ActualVatOfPrice MONEY
DECLARE @ReadOnly BIT
DECLARE @ReservationStatus INT
DECLARE @AccountNumber INT
DECLARE @CorrectionMoved BIT
DECLARE @CorrectionDeleted BIT

-- Calc of real vat of Product price. MisTable
DECLARE VatOfPriceCur CURSOR STATIC
FOR
SELECT Room_HallType, MISTABLE.ReferenceNumber, GuestNumber, FolioNumber, DateStamp, SegmentNumber, PointOfSaleNumber, RoomTypeNumber, BookedAdult, BookedChildren1, BookedChildren2, BookedNumberOfRooms, BookedPrice, BookedVatOfPrice, BookedPackage, BookedVatOfPackage, ActualAdult, ActualChildren1, ActualChildren2, ActualNumberOfRooms, ActualPrice, ActualVatOfPrice, ActualPackage, ActualVatOfPackage, ValueType, HotelCustomerNumber, ReadOnly, ReservationStatus, CampaignCode, ProjectCode, StaffID, CorrectionMoved, CorrectionDeleted, WareGroupNumber, AccountNumber, DepartmentNumber, MISTABLE.ProductWareLinkNumber, IsPackage, TEXT, OwnerReservation, ProductNumber, isnull(MISTABLEPackSum.PackageSum, 0), isnull(MISTABLEPackSum.PackageVatOfSum, 0)
FROM MISTABLE WITH (NOLOCK)
LEFT JOIN MISTABLEPackSum WITH (NOLOCK) ON MISTABLEPackSum.ProductWareLinkNumber = MISTABLE.ProductWareLinkNumber
WHERE MISTABLE.ProductWareLinkNumber >= 0
	AND MISTABLE.IsPackage = 0
	AND MISTABLE.DateStamp >= @SystemDateStr

OPEN VatOfPriceCur

DELETE
FROM MISTABLE
WHERE MISTABLE.ProductWareLinkNumber >= 0
	AND MISTABLE.IsPackage = 0
	AND MISTABLE.DateStamp >= @SystemDateStr

FETCH NEXT
FROM VatOfPriceCur
INTO @Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @RoomTypeNumber, @BookedAdult, @BookedChildren1, @BookedChildren2, @BookedNumberOfRooms, @BookedPrice, @BookedVatOfPrice, @BookedPackage, @BookedVatOfPackage, @ActualAdult, @ActualChildren1, @ActualChildren2, @ActualNumberOfRooms, @ActualPrice, @ActualVatOfPrice, @ActualPackage, @ActualVatOfPackage, @ValueType, @HotelCustomerNumber, @ReadOnly, @ReservationStatus, @CampaignCode, @ProjectCode, @StaffID, @CorrectionMoved, @CorrectionDeleted, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @Text, @OwnerReservation, @ProductNumber, @PackageSum, @PackageVatOfSum

WHILE (@@FETCH_STATUS <> - 1)
BEGIN
	SET @Faktor = 0

	IF (@BookedPrice <> 0)
	BEGIN
		SET @Faktor = CONVERT(FLOAT, @BookedVatOfPrice / @BookedPrice)
		SET @BookedVatOfPrice = ((@BookedPrice - @PackageSum) * @Faktor) + @PackageVatOfSum
	END
	ELSE
		SET @BookedVatOfPrice = 0

	INSERT INTO MISTABLE (Room_HallType, ReferenceNumber, GuestNumber, FolioNumber, DateStamp, SegmentNumber, PointOfSaleNumber, RoomTypeNumber, BookedAdult, BookedChildren1, BookedChildren2, BookedNumberOfRooms, BookedPrice, BookedVatOfPrice, BookedPackage, BookedVatOfPackage, ActualAdult, ActualChildren1, ActualChildren2, ActualNumberOfRooms, ActualPrice, ActualVatOfPrice, ActualPackage, ActualVatOfPackage, ValueType, HotelCustomerNumber, ReadOnly, ReservationStatus, CampaignCode, ProjectCode, StaffID, CorrectionMoved, CorrectionDeleted, WareGroupNumber, AccountNumber, DepartmentNumber, ProductWareLinkNumber, IsPackage, TEXT, OwnerReservation, ProductNumber)
	VALUES (@Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @RoomTypeNumber, @BookedAdult, @BookedChildren1, @BookedChildren2, @BookedNumberOfRooms, @BookedPrice, @BookedVatOfPrice, @BookedPackage, @BookedVatOfPackage, @ActualAdult, @ActualChildren1, @ActualChildren2, @ActualNumberOfRooms, @ActualPrice, @ActualVatOfPrice, @ActualPackage, @ActualVatOfPackage, @ValueType, @HotelCustomerNumber, @ReadOnly, @ReservationStatus, @CampaignCode, @ProjectCode, @StaffID, @CorrectionMoved, @CorrectionDeleted, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @Text, @OwnerReservation, @ProductNumber)

	FETCH NEXT
	FROM VatOfPriceCur
	INTO @Room_HallType, @ReferenceNumber, @GuestNumber, @FolioNumber, @DateStamp, @SegmentNumber, @PointOfSaleNumber, @RoomTypeNumber, @BookedAdult, @BookedChildren1, @BookedChildren2, @BookedNumberOfRooms, @BookedPrice, @BookedVatOfPrice, @BookedPackage, @BookedVatOfPackage, @ActualAdult, @ActualChildren1, @ActualChildren2, @ActualNumberOfRooms, @ActualPrice, @ActualVatOfPrice, @ActualPackage, @ActualVatOfPackage, @ValueType, @HotelCustomerNumber, @ReadOnly, @ReservationStatus, @CampaignCode, @ProjectCode, @StaffID, @CorrectionMoved, @CorrectionDeleted, @WareGroupNumber, @ResultAccountNumber, @DepartmentNumber, @ProductWareLinkNumber, @IsPackage, @Text, @OwnerReservation, @ProductNumber, @PackageSum, @PackageVatOfSum
END

CLOSE VatOfPriceCur

DEALLOCATE VatOfPriceCur

DROP TABLE #ReservationsCrossDate
DROP TABLE #FoliosCrossDate

Declare @StartDate DateTime
SET @StartDate = CONVERT(DateTime,@FormatedStartDate)

EXEC GenerateMISTotals @StartDate