<!-- edited with XML Spy v4.4 U (http://www.xmlspy.com) by Andrea Martinotti (OmniTicket Network Administration) -->
<root>
	<StoredProcedureList>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>34</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2]
	@BatchDate Date,
	@Transactions varchar(500),
	@RRTransDateType Integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT
	DECLARE @AccountConfigID INT
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &amp;#62; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))
        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END


	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1
	
select TOP 1	@SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
					@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
					@SuspendPrice = COA_CNF_AccountConfig.Price,
					@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

		--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[attributeids]
				   ,[PaymentID])				    
						select distinct COA.COAAccountId, 
								p.RevenueRecognitionRuleId,		   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								0 as ConfigPrice,
								100 as ConfigPercentage,
								0 RemainingValues,	
								ABS( case when (data_payment.PaymentAmount) &amp;#60;&amp;#62; 0 then (data_payment.PaymentAmount) else (DATA_Payment.AdvancedPaymentAmount) end
								    -
							     (case when data_payment.paymentid = (select top 1 paymentid
																		from data_payment WITH(NOLOCK)
																			where data_payment.paymentstatus = 1 
																			and transactionid = RR_DATA_REVENUE.Transactionid
																			Order by paymenttype)
								then (select sum(Change) *-1
																								from data_transaction WITH(NOLOCK)
																								where data_transaction.transactionid = RR_DATA_REVENUE.Transactionid)
								else 0
							end ))
							as RevenueAmount,
							RR_DATA_REVENUE.Accountingtype,
							   p.RRCalcTypeTrigger,
							   p.RRPercentage,
							   p.Days,
							   RR_DATA_REVENUE.attributeids,
							   data_payment.PaymentId

					from RR_DATA_REVENUE WITH(NOLOCK)
									INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN (select '1' as PCOAAccountid, 
													   coa_cnf_accountConfig.Siteid, 
													   RR_CNF_RevenueRecognitionRule.Enabled, 
													   RR_CNF_RevenueRecognitionRule.FromDate, 
													   RR_CNF_RevenueRecognitionRule.ToDate,
													   COA_CNF_AccountConfig.RemainingValues,
													   coa_cnf_account.coaaccountid,
													   COA_CNF_AccountConfig.Price,
													   COA_CNF_AccountConfig.Percentage,
													   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
													   RR_CNF_RevenueRecognitionRule.code,		   
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
													   COA_CNF_AccountConfig.COAAccountConfigId,
													   coa_cnf_account.COAAccountTypeId,
													   coa_cnf_account.Code as accountcode,
													   coa_cnf_accountconfig.Accountingtype,
													   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
													   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
													   RR_CNF_RevenueRecognitionRule.Days	

													from RR_CNF_RevenueRecognitionRule	 WITH(NOLOCK)
													INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account	 WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
													INNER JOIN COA_CNF_AccountType	 WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
												where  RR_CNF_RevenueRecognitionRule.Enabled = 1
												and coa_cnf_account.coaaccountid in (@ACCPaymentMethod)) p				on p.COAAccountid = rr_data_revenue.coaaccountid 
							INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid
																										and DATA_Payment.PaymentId = RR_DATA_Revenue.PaymentID
							left  JOIN DATA_PaymentCard	 WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
							left JOIN CNF_PaymentCard	WITH(NOLOCK)					on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
							INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
							INNER JOIN COA_CNF_Account COA	WITH(NOLOCK)				on COA.COAAccountid = ISNULL(cnf_paymentcard.coaaccountid, CNF_PaymentMethod.COAAccountid)


						where data_payment.paymentstatus = 1
						and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and @BatchDate between p.FromDate and p.ToDate
						AND data_payment.Transactionid in (select transactionid
													from rr_Data_Revenue WITH(NOLOCK)
													where rr_data_revenue.transactionid = data_payment.Transactionid
													  and coaaccountid in (@ACCPaymentMethod)
													   and fcalcdate = @BatchDate
													)

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE WITH(NOLOCK)

							INNER JOIN data_transaction WITH(NOLOCK)		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment WITH(NOLOCK)			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod WITH(NOLOCK)	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver	WITH(NOLOCK)		on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA	WITH(NOLOCK) on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue WITH(NOLOCK)
																	INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &amp;#60;&amp;#62; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate



				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.Siteid as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   data_payment.paymentfee as RevenueAmount,
						   case when data_payment.paymentfee &amp;#62;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE WITH(NOLOCK)												
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue WITH(NOLOCK)
											INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and data_payment.paymentfee &amp;#60;&amp;#62; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid not in (select transactionid
												from rr_Data_Revenue WITH(NOLOCK)
												where rr_data_revenue.transactionid = data_payment.Transactionid
													  and coaaccountid in (select FeeCOAAccountId
																			from cnf_paymentmethod CP
																			  where FeeCOAAccountId is not null
																		)
												)
					AND data_payment.Transactionid in (select transactionid
												from rr_Data_Revenue WITH(NOLOCK)
												where rr_data_revenue.transactionid = data_payment.Transactionid
													  and coaaccountid in (@ACCPaymentMethod)
												)


							


		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])				    					
				   select COAAccountId, 
						   Max(RevenueRecognitionRuleId),	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   0,
						   0,
						   0,						
						   0,
						   0,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
				           case when accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   AttributeIDs
						   from (
							select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,	   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									  p.COAAccountTypeId,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.RevenueAmount *-1  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_Revenue.AttributeIDs,
									   rr_data_Revenue.RevenueRecognitionDataId
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select distinct saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype
													  from RR_DATA_Revenue WITH(NOLOCK)
														INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid and p.accountingtype = rr_data_revenue.AccountingType
									INNER JOIN DATA_Transaction WITH(NOLOCK)			on data_transaction.transactionid = rr_data_revenue.transactionid
							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
							  and RR_DATA_Revenue.PaymentID is not null
							  and rr_data_Revenue.coaAccountID &amp;#60;&amp;#62; @ACCPaymentMethod
							  and rr_data_Revenue.TransactionId  in (select transactionid
							                                            from rr_data_revenue RR WITH(NOLOCK)
																	where RR.transactionid = rr_data_Revenue.Transactionid
													  and RR.coaaccountid in (select coaaccountid
																			 from cnf_paymentmethod
																			 where coaaccountid is not null
																			union all
																		   select coaaccountid
																			 from cnf_paymentcard
																			 where coaaccountid is not null
																		  ))
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,					
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType, 
									   AttributeIDs


---  Returned Checks
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct 
							COA.COAAccountId, 
						   @SuspendRRRId,	   
						   @SuspendRRCalcTypeWhere,
						   @SuspendRRCalcTypeMethod,	   
						   @SuspendCOAAccountConfigId,
						   COA.COAAccountTypeId,
						   DATA_Transaction.Transactionid as Transactionid,
						   DATA_Transaction.saleid as Saleid,
						   DATA_Transaction.Siteid as SiteID,
						   DATA_Transaction.OperatingAreaId as OperatingAreaID,
						   DATA_Transaction.Workstationid as Workstationid,
						   DATA_Transaction.UserGroupid as UserGroupID,
						   DATA_Transaction.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						  ABS(data_transaction.tip) as RevenueAmount,
							2 accountingtype,		
							 @SuspendRRCalcTypeTrigger,
							100,
							0

						from  DATA_Transaction	 WITH(NOLOCK)					
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = DATA_Transaction.transactionid
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						
						
						where  data_payment.paymentstatus = 1
						  and DATA_Transaction.TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &amp;#60;&amp;#62; 0
															and ((@RRTransDateType = 0 and convert(date, DATA_Transaction.fTransactionDate) = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, DATA_Transaction.TransactionDate) = @BatchDate))
							

--COA for Donations
	INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					    ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])	
						select distinct COA_CNF_Account.COAAccountId, 
							   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
							   RR_DATA_REVENUE.RRCalcTypeWhere,
							   RR_DATA_REVENUE.RRCalcTypeMethod,	   
							   1,
							   COA_CNF_Account.COAAccountTypeId,
							   RR_DATA_REVENUE.Transactionid as Transactionid,
							   RR_DATA_REVENUE.saleid as Saleid,
							   RR_DATA_REVENUE.Siteid as SiteID,
							   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
							   RR_DATA_REVENUE.Workstationid as Workstationid,
							   RR_DATA_REVENUE.UserGroupid as UserGroupID,
							   RR_DATA_REVENUE.UserId as userID,
							   @BatchDate as batchdate,
							   0 as Quantity,
							   0 as GrossAmount,
							   0 as NetAmount,
							   0 as Price,
							   100 as Percentage,
							   0 as RemainingValue, 	
							   abs(data_payment.donationamount),
							   2,		
							   RR_DATA_REVENUE.RRCalcTypeTrigger,
							   RR_DATA_REVENUE.RRPercentage,
							   RR_DATA_REVENUE.RRDays
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
								INNER JOIN CNF_DonationForm						on CNF_DonationForm.donationformid = data_payment.donationformid
								INNER JOIN COA_CNF_Account   					on COA_CNF_Account.COAAccountid = CNF_DonationForm.COAAccountid

							where data_payment.donationamount &amp;#60;&amp;#62; 0
							and DATA_Transaction.TransactionType in (select transactionid
																	from #TransactionIDs)
								and RR_DATA_REVENUE.coaaccountid = 2
								and RR_DATA_REVENUE.fcalcdate = @BatchDate			
								

----Normal Sale with TIPS
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA_CNF_Account.COAAccountId, 
						   1,	   
						   1,
						   1,	   
						   1,
						   COA_CNF_Account.COAAccountTypeId,
						   data_transaction.Transactionid as Transactionid,
						   data_transaction.saleid as Saleid,
						   data_transaction.Siteid as SiteID,
						   data_transaction.OperatingAreaId as OperatingAreaID,
						   data_transaction.Workstationid as Workstationid,
						   data_transaction.UserGroupid as UserGroupID,
						   data_transaction.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   ABS(data_payment.TipsAmount) as RevenueAmount,
						   case when data_payment.TipsAmount &amp;#62;= 0 then 2
						        else 1
							end accountingtype,		
						   1,
						   100,
						   0

				from data_payment WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)							on data_transaction.transactionid = data_payment.transactionid
					inner join cnf_paymentmethod WITH(NOLOCK)							ON cnf_paymentmethod.PaymentMethodId = data_payment.PaymentMethodID
					inner join COA_CNF_Account WITH(NOLOCK)								ON coa_cnf_account.COAAccountId = cnf_paymentmethod.TipsCOAAccountID
						

					where data_payment.paymentstatus = 1
				  and ISNULL(data_payment.TipsAmount, 0) &amp;#60;&amp;#62; 0
					and DATA_Transaction.TransactionType in (select transactionid
 															   from #TransactionIDs)
					and data_payment.fpaymentdate = @BatchDate



		End

</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>ED96283D7E2A498B8E16A6D2753E1DDD</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE"><Name>AccountListByDmgCategoryCode</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>Create PROCEDURE [dbo].[AccountListByDmgCategoryCode]
	-- Add the parameters for the stored procedure here
	@DmgCatCode varchar(MAx)
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)


select @cols = STUFF((SELECT ',' + QUOTENAME(DM.FieldName + '_' + cast(DM.ObjType as varchar(MAX))) 
from
  CNF_DmgCategory2Mask as C2M with(nolock)
  inner join CNF_DataMask as DM with(nolock) on (DM.MaskId=C2M.MaskId)
  where C2M.dmgcategoryid = (select dmgcategoryid from CNF_DmgCategory where DmgCategoryAK = @DmgcatCode)
                              FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')
		print @cols

set @query = N'SELECT BOSId, Barcode, DataCreazione, ' + @cols + N' from 
             (
select
  AC.AccountId as BOSId,
  MI.IdentifierCode as Barcode,
  AC.InsDateTime as DataCreazione,
  DM.FieldName + ''_'' + cast(DM.ObjType as varchar(MAX)) as ColumnName,
  case when DM.masktableid is null then 
  case when (DM.ObjType not in(1,3,6,8,9,10,11,12,13,14,15,21,55,56,57,549,31)) then DD.MaskData
       when (DM.ObjType = 1) then AC.FirstName
       when (DM.ObjType = 3) then AC.SurName
       when (DM.ObjType = 6) then AC.Address1
       when (DM.ObjType = 8) then AC.City
       when (DM.ObjType = 9) then AC.State
       when (DM.ObjType = 10) then AC.ZipCode
       when (DM.ObjType = 11) then AC.Country
       when (DM.ObjType = 12) then AC.HomePhone
       when (DM.ObjType = 13) then AC.BusinessPhone
       when (DM.ObjType = 14) then AC.Fax
       when (DM.ObjType = 15) then AC.MobilePhone
       when (DM.ObjType = 21) then AC.EmailAddress1
       when (DM.ObjType = 55) then AC.ExternalCode1
       when (DM.ObjType = 56) then AC.DisplayField1
       when (DM.ObjType = 57) then AC.DisplayField2
       when (DM.ObjType = 549) then AC.Password
       when (DM.ObjType = 31) then AC.CompanyName end 
	   else (SELECT Itemdescription from CNF_MaskTableItem where CNF_MaskTableItem.MaskTableId = DM.masktableid and CNF_MaskTableItem.ItemCode = 
  case when (DM.ObjType not in(1,3,6,8,9,10,11,12,13,14,15,21,55,56,57,549,31)) then DD.MaskData
       when (DM.ObjType = 1) then AC.FirstName
       when (DM.ObjType = 3) then AC.SurName
       when (DM.ObjType = 6) then AC.Address1
       when (DM.ObjType = 8) then AC.City
       when (DM.ObjType = 9) then AC.State
       when (DM.ObjType = 10) then AC.ZipCode
       when (DM.ObjType = 11) then AC.Country
       when (DM.ObjType = 12) then AC.HomePhone
       when (DM.ObjType = 13) then AC.BusinessPhone
       when (DM.ObjType = 14) then AC.Fax
       when (DM.ObjType = 15) then AC.MobilePhone
       when (DM.ObjType = 21) then AC.EmailAddress1
       when (DM.ObjType = 55) then AC.ExternalCode1
       when (DM.ObjType = 56) then AC.DisplayField1
       when (DM.ObjType = 57) then AC.DisplayField2
       when (DM.ObjType = 549) then AC.Password
       when (DM.ObjType = 31) then AC.CompanyName end ) end as Value
from
  CNF_DmgCategory2Mask as C2M with(nolock)
  inner join CNF_DataMask as DM with(nolock) on (DM.MaskId=C2M.MaskId)
  inner join DATA_Account as AC with(nolock) on (AC.DmgCategoryId=C2M.DmgCategoryId)
  left join DATA_Ticket as TI with(nolock) on (AC.AccountId=TI.AccountId)
  left join DATA_ticket2Media as T2M on (TI.TicketId=T2M.TicketId)
  left join DATA_MediaIdentifier as MI with(nolock) on (MI.MediaId=T2M.MediaId)
  left join DATA_DmgData as DD with(nolock)  on (DD.ObjType=DM.ObjType and DD.FKey=AC.AccountId and DD.DmgType = 1 and DD.ObjType not in (1,3,6,8,9,10,11,12,13,14,15,21,55,56,57,549,31))
  where AC.dmgcategoryid = (select dmgcategoryid from CNF_DmgCategory where DmgCategoryAK = '''+@DmgcatCode+''')

            ) x
            pivot 
            (
                max(value)
                for ColumnName in (' + @cols + N')
            ) p order by DataCreazione'

exec sp_executesql @query;


END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>1</ExecuteOnCreate><SqlScriptAK>8A2DDB0CDFFC41B4997D766709636AC3</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AccountRestrictionsConversion_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE Procedure otn_sp_AccountRestrictionsConversion_Performance(@AccountRestrictionID int)  

AS    
BEGIN
DECLARE @NEWAccountRestrictionID int


	DECLARE Restriction_Cursor CURSOR LOCAL FOR
			select AccountRestrictionID
				from CNF_AccountRestriction				

	OPEN Restriction_Cursor

	FETCH NEXT FROM Restriction_Cursor INTO
						@AccountRestrictionID
						

	WHILE @@FETCH_STATUS = 0
	BEGIN
				
					INSERT INTO [dbo].[CNF_AccountRestriction2Performance]
							   ([AccountRestrictionId]
							   ,[PerformanceID]
							   ,[Last_UserId_Log]
							   ,[Last_WorkstationId_Log]
							   ,[Last_DateTime_Log])
					select distinct @AccountRestrictionID,									
									PerformanceID,
									1,
									1,
									getdate()
					from CNF_Performance
					where CNF_Performance.salerestrictionID = @AccountRestrictionID



					INSERT INTO [dbo].[CNF_AccountRestriction2Performance]
							   ([AccountRestrictionId]
							   ,[PerformanceID]
							   ,[Last_UserId_Log]
							   ,[Last_WorkstationId_Log]
							   ,[Last_DateTime_Log])
					select distinct @AccountRestrictionID,									
									EventId,
									1,
									1,
									getdate()
					from cnf_Event
					where cnf_Event.salerestrictionID = @AccountRestrictionID


		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID


	END	
	
	CLOSE Restriction_Cursor;
	DEALLOCATE Restriction_Cursor;

RETURN;
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>1</ExecuteOnCreate><SqlScriptAK>D551AFCC93364DDE92A386313CE86FE0</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_B2BOwner_Matrixcell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_B2BOwner_Matrixcell]        (
														  @GUID        varchar(100), 
													          @SalesId     int,
                                                          @ShopCartType int,                                                         														    @PreventSale int OUTPUT,
														  @RejectReasonErrorCode int OUTPUT,
														  @RejectType int OUTPUT,
														  @RejectRestrictionDescription varchar(100) OUTPUT,
														  @RejectRemainingAmount int OUTPUT
														) 
-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                 
                                                                                                  
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
	DECLARE @AccountType int = 2
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 
	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  B2B_Owner,
				Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund

		from data_shopcartitemlimit Res_Table WITH(NOLOCK)
			INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																					         (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))
			LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.B2B_Owner)
			                                                                           and (cnf_AccountRestriction2Account.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.B2B_Owner))																							
																						and (cnf_AccountRestriction2DMGCategory.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell. AccountRestrictionId


	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.B2B_Owner is not null
		   and Limit is not null
		   and cnf_AccountRestriction.AccountType = @AccountType
		   and B2B_Owner &amp;#60;&amp;#62; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0
		    and (((Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY B2B_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 cnf_AccountRestriction.ReleaseQuotaOnRefund

		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0)
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  
				    @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				where MatrixCellID in (select matrixcellid
											from (
														select MatrixcellId 
														from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
														where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

														union all

														select matrixcellid
															from cnf_matrixcell WITH(NOLOCK)
														where enabled = 1
															and 1 = (select 1 
																		from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																	where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																		and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
															and matrixcellid in (select matrixcellid 
																					from data_shopcartitemlimit WITH(NOLOCK)
																					where (((Res_Table.ShopCartGuid = @GUID))
																							or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																			)

												)p
											where matrixcellid is not null
										)
				and B2B_Owner = @AccountID
				and ISNULL(PerformanceID, 0) = 0
				and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin			  
				if @CountofMatrixCells = 1 						
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)						 
					end
				end
			end
			else
			begin
			    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END	
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
			begin
			       DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID 
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>03C0D5D6171B4ECDB195100E815B26E4</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_B2BOwner_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_B2BOwner_Performance]  (
                                                      @GUID        varchar(100),
													  @SalesId		int,
                                                      @ShopCartType int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
                                                  
                                                    
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
	DECLARE @AccountType int = 2
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 
	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   B2B_Owner,
							Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.Limit,
				            cnf_AccountRestriction.ReleaseQuotaOnRefund,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																									 (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))


				INNER JOIN CNF_AccountRestriction2Performance WITH(NOLOCK)							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID
				                                                                           and CNF_AccountRestriction2Performance.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.B2B_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.B2B_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId


			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.B2B_Owner is not null
				and Limit is not null
				and B2B_Owner &amp;#60;&amp;#62; 0
		        and cnf_AccountRestriction.AccountType = @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY B2B_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.Limit,
							cnf_AccountRestriction.ReleaseQuotaOnRefund,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			order by cnf_AccountRestriction.AccountRestrictionID


	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &amp;#60;&amp;#62; @PerformanceID))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),   @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				where PerformanceID = @PerformanceID 	
					and MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						where (((Res_Table.ShopCartGuid = @GUID))
																								or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)
					and B2B_Owner = @AccountID
					and (((Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
			    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
			begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
			     
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID 
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   B2B_Owner,
								Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
				                cnf_AccountRestriction.Limit,
				                cnf_AccountRestriction.ReleaseQuotaOnRefund,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
					INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																									 (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))

					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID
																								and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.B2B_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.B2B_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.B2B_Owner is not null
				and Limit is not null
				and Res_Table.B2B_Owner &amp;#60;&amp;#62; 0
		        and cnf_AccountRestriction.AccountType =  @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			    and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				GROUP BY B2B_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 cnf_AccountRestriction.ReleaseQuotaOnRefund,
								Res_Table.PerformanceID,
								RES_Table.Eventid

			order by cnf_AccountRestriction.AccountRestrictionID

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
						    @ReleaseQuotaOnRefund,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &amp;#60;&amp;#62; @PerformanceID))
			BEGIN 

				SET @Prevent = 0;

				select @FullQuantity = sum(Quantity),   @CountofMatrixCells = Count(*) 
					from data_shopcartitemlimit Res_Table WITH(NOLOCK)
					where PerformanceID = @PerformanceID
						and MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						   where (((Res_Table.ShopCartGuid = @GUID))
																								 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)					
						and B2B_Owner = @AccountID
					   and (((Res_Table.ShopCartGuid = @GUID))
							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

					
				if @FullQuantity &amp;#62; 0
				Begin
					if @CountofMatrixCells = 1 
						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
				begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
						    @ReleaseQuotaOnRefund,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>334EBC27BB1E40C6BE5F6ACFED216A2A</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_BillOwner_Matrixcell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>9</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_BillOwner_Matrixcell]      (
														  @GUID        varchar(100), 
													          @SalesId     int,
                                                          @ShopCartType int,                                                       														    @PreventSale int OUTPUT,
														  @RejectReasonErrorCode int OUTPUT,
														  @RejectType int OUTPUT,
														  @RejectRestrictionDescription varchar(100) OUTPUT,
														  @RejectRemainingAmount int OUTPUT
														) 
-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                 
                                                                                                  
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
	DECLARE @AccountType int = 3
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 
	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  Billing_Owner,
				Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund

		from data_shopcartitemlimit Res_Table WITH(NOLOCK)
			INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																					         (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))
			LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Billing_Owner)
			                                                                           and (cnf_AccountRestriction2Account.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Billing_Owner))																							
																						and (cnf_AccountRestriction2DMGCategory.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell. AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Billing_Owner is not null
		   and Limit is not null
		   and cnf_AccountRestriction.AccountType = @AccountType
		   and Billing_Owner &amp;#60;&amp;#62; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0
		   and (((Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY Billing_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 cnf_AccountRestriction.ReleaseQuotaOnRefund

		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0)
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  
				    @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				where MatrixCellID in (select matrixcellid
											from (
														select MatrixcellId 
														from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
														where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

														union all

														select matrixcellid
															from cnf_matrixcell WITH(NOLOCK)
														where enabled = 1
															and 1 = (select 1 
																		from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																	where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																		and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
															and matrixcellid in (select matrixcellid 
																					from data_shopcartitemlimit WITH(NOLOCK)
																				   where (((Res_Table.ShopCartGuid = @GUID))
																						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																			)

												)p
											where matrixcellid is not null
										)
				and Billing_Owner = @AccountID
				and ISNULL(PerformanceID, 0) = 0
				and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin			  
				if @CountofMatrixCells = 1 						
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)						 
					end
				end
			end
			else
			begin
			   DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
			begin
				 DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>07AD879F03534E8AB944080D943CD706</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_BillOwner_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_BillOwner_Performance]  (
                                                      @GUID        varchar(100), 
													  @SalesId	int,
                                                      @ShopCartType int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
                                                    
-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
                                                 
                                                    
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
	DECLARE @AccountType int = 3
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 
	
	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Billing_Owner,
							Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																									 (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))


				INNER JOIN CNF_AccountRestriction2Performance WITH(NOLOCK)							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID
				                                                                           and CNF_AccountRestriction2Performance.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Billing_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Billing_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Billing_Owner is not null
				and Limit is not null
				and Billing_Owner &amp;#60;&amp;#62; 0
		        and cnf_AccountRestriction.AccountType = @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY Billing_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
        					 cnf_AccountRestriction.Limit,
							 cnf_AccountRestriction.ReleaseQuotaOnRefund,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &amp;#60;&amp;#62; @PerformanceID))
		BEGIN 
			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),   @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				where PerformanceID = @PerformanceID 
				  and MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						where (((Res_Table.ShopCartGuid = @GUID))
																							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)				
					and Billing_Owner = @AccountID
					and (((Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
			    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
			begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Billing_Owner,
								Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
							    cnf_AccountRestriction.ReleaseQuotaOnRefund,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
					INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																									 (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))

					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID
																								and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Billing_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Billing_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Billing_Owner is not null
				and Limit is not null
				and Res_Table.Billing_Owner &amp;#60;&amp;#62; 0
		        and cnf_AccountRestriction.AccountType =  @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
					and (((Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				GROUP BY Billing_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
								cnf_AccountRestriction.Limit,
							    cnf_AccountRestriction.ReleaseQuotaOnRefund,
								Res_Table.PerformanceID,
								RES_Table.Eventid

			order by cnf_AccountRestriction.AccountRestrictionID


		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
                            @ReleaseQuotaOnRefund,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &amp;#60;&amp;#62; @PerformanceID))
			BEGIN 

				SET @Prevent = 0;

				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*)
					from data_shopcartitemlimit Res_Table WITH(NOLOCK)
					where PerformanceID = @PerformanceID	
						and MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						where (((Res_Table.ShopCartGuid = @GUID))
																						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)
						and Billing_Owner = @AccountID
					and (((Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				if @FullQuantity &amp;#62; 0
				Begin
					if @CountofMatrixCells = 1 
						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
				begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
                            @ReleaseQuotaOnRefund,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>627CE85F4B3C4109B349BB12AB42AB69</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="DELETED"><Name>otn_sp_AR_ReservationOwner_Matrixcell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE PROCEDURE [otn_sp_AR_ReservationOwner_Matrixcell]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Resevation_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0
	SET @OLD_Resevation_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select  Reservation_Owner,
		        Ticket_Owner,
				Res_Table.MatrixCellID,
				sum(Quantity) as Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.ReservationAccountLimit,
				cnf_AccountRestriction.TicketAccountLimit

		  from @Restriction_Check Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                                                                       and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																										
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                                                                       and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Reservation_Owner is not null
		   and ReservationAccountLimit is not null
		   and Reservation_Owner &amp;#60;&amp;#62; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0

			 GROUP BY Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit
		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @Reservation_Owner &amp;#60;&amp;#62; @OLD_Resevation_Owner and (@PreventSale = 0)
		BEGIN 
			If @ReservationAccountLimit &amp;#62; 0 
				set @ReservationorTicket = 1

			SET @Prevent = 0;

			if @ReservationorTicket = 1 
			BEGIN
				select @FullQuantity = sum(Quantity),  
				       @CountofMatrixCells = Count(*)
					from @Restriction_Check
					where MatrixCellID in (select MatrixcellId 
											from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
											where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)
					and Reservation_Owner = @Reservation_Owner
					and ISNULL(PerformanceID, 0) = 0

				if @FullQuantity &amp;#62; 0
				Begin			  
					if @CountofMatrixCells = 1 						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
						    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[RestrictionType]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@RestrictionType
											,@Reservation_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity
											,0)						 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin

							INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	
						end
				end
			END	
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Reservation_Owner = @OLD_Resevation_Owner and @Quantity &amp;#60; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @Reservation_Owner &amp;#60;&amp;#62; @OLD_Resevation_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[RestrictionType]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity]
									,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@RestrictionType
									,@Reservation_Owner
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,0)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Resevation_Owner = @Reservation_Owner

		FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>45A1A2AE578F4A309C158A3D46B68E6E</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_ReservationOwner_Matrixcell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>9</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_ReservationOwner_Matrixcell]  (
														  @GUID        varchar(100),
														  @SalesID int,
                                                          @ShopCartType int,
														  @PreventSale int OUTPUT,
														  @RejectReasonErrorCode int OUTPUT,
														  @RejectType int OUTPUT,
														  @RejectRestrictionDescription varchar(100) OUTPUT,
														  @RejectRemainingAmount int OUTPUT
														) 
-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                 
                                                                                                  
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
	DECLARE @AccountType int = 1
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 
	
--Reservation Owner	
	SET @RestrictionType = 1
	set @CountofMatrixCells = 0

	DECLARE Check_Cursor CURSOR LOCAL FOR
	select  Reservation_Owner,
				Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
				SaleID,
				SaleitemID,
				CheckforRestrictionOnly,
				cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund

		from data_shopcartitemlimit Res_Table WITH(NOLOCK)
			INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																					         (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))
			LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)
			                                                                           and (cnf_AccountRestriction2Account.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
																						and (cnf_AccountRestriction2DMGCategory.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell. AccountRestrictionId

	     where cnf_AccountRestriction.Enabled = 1
		   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
		   and CNF_AccountRestriction.RestrictionType = @RestrictionType
		   and Res_Table.Reservation_Owner is not null
		   and Limit is not null
		   and cnf_AccountRestriction.AccountType = @AccountType
		   and Reservation_Owner &amp;#60;&amp;#62; 0
		   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
		   and ISNULL(Res_Table.PerformanceID, 0) = 0
		   and (((Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			 GROUP BY Reservation_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 cnf_AccountRestriction.ReleaseQuotaOnRefund,
							 cnf_AccountRestriction2Account.AccountRestrictionId,
							 cnf_AccountRestriction2DMGCategory.AccountRestrictionID
		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0)
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  
				    @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
						where MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						where (((Res_Table.ShopCartGuid = @GUID))
																							 or (('0' = @GUID) and (Res_Table.SaleId = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)
				and Reservation_Owner = @AccountID
				and ISNULL(PerformanceID, 0) = 0
				and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.SaleId = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin			  
				if @CountofMatrixCells = 1 						
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														null, null, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)						 
					end
				end
			end
			else
			begin
			    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END	
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
			begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
	                    @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>E502F6A939E842DD8FAA0E364E9F458A</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_ReservationOwner_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_ReservationOwner_Performance]  (
															  @GUID        varchar(100), 
											                  @SalesId     int,
                                                              @ShopCartType int,
															  @PreventSale int OUTPUT,
															  @RejectReasonErrorCode int OUTPUT,
															  @RejectType int OUTPUT,
															  @RejectRestrictionDescription varchar(100) OUTPUT,
															  @RejectRemainingAmount int OUTPUT
															) 

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                 
                                                                                                           
                                                                                                           
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 2
	DECLARE @AccountType int = 1
	DECLARE @AccountID int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 
	
--Performance Reservation Owner Check
	Set @OldAccountRestrictionID = 99999
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																									 (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))

				INNER JOIN CNF_AccountRestriction2Performance WITH(NOLOCK)							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID
				                                                                           and CNF_AccountRestriction2Performance.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                     													and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId										
			        
				LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId


			where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and Limit is not null
				and Reservation_Owner &amp;#60;&amp;#62; 0
		        and cnf_AccountRestriction.AccountType = @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((Res_Table.ShopCartGuid = @GUID))
					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY Reservation_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund,
							Res_Table.PerformanceID,
							RES_Table.Eventid
		 order by cnf_AccountRestriction.AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Old_PerformanceID &amp;#60;&amp;#62; @PerformanceID))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*)
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				where PerformanceID = @PerformanceID 
					and MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						where (((Res_Table.ShopCartGuid = @GUID))
																							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)
												
					and Reservation_Owner = @AccountID
					and (((Res_Table.ShopCartGuid = @GUID))
						 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID,  
														@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				else
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														@PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
			    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
			begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	



			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Reservation Owner Check
	IF @PreventSale = 0
	BEGIN
		Set @OldAccountRestrictionID = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Reservation_Owner,
								Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund,
								Res_Table.PerformanceID,
								RES_Table.Eventid

				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
					INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																									 (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))

					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID
																								and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Reservation_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
					LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Reservation_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId

				where cnf_AccountRestriction.Enabled = 1
				and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
				and CNF_AccountRestriction.RestrictionType = @RestrictionType
				and Res_Table.Reservation_Owner is not null
				and Limit is not null
				and Res_Table.Reservation_Owner &amp;#60;&amp;#62; 0
		        and cnf_AccountRestriction.AccountType =  @AccountType
				and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
				and (((Res_Table.ShopCartGuid = @GUID))
						or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				GROUP BY Reservation_Owner,
								Res_Table.MatrixCellID,
								SaleID,
								SaleitemID,
								CheckforRestrictionOnly,
								cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund,
								Res_Table.PerformanceID,
								RES_Table.Eventid

		 order by cnf_AccountRestriction.AccountRestrictionID
		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
                            @ReleaseQuotaOnRefund,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) 
					or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@OLD_PerformanceID &amp;#60;&amp;#62; @PerformanceID))
			BEGIN 


				SET @Prevent = 0;


				select @FullQuantity = sum(Quantity),   @CountofMatrixCells = Count(*)
					from data_shopcartitemlimit Res_Table WITH(NOLOCK)
					where PerformanceID = @PerformanceID	
					and MatrixCellID in (select matrixcellid
													from (
																select MatrixcellId 
																from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
																where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

																union all

																select matrixcellid
																  from cnf_matrixcell WITH(NOLOCK)
																where enabled = 1
																  and 1 = (select 1 
																			 from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																			where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																			  and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
																  and matrixcellid in (select matrixcellid 
																						 from data_shopcartitemlimit WITH(NOLOCK)
																						where (((Res_Table.ShopCartGuid = @GUID))
																							 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																					)

														)p
													where matrixcellid is not null
												)
						and Reservation_Owner = @AccountID
						and (((Res_Table.ShopCartGuid = @GUID))
								or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

				if @FullQuantity &amp;#62; 0
				Begin
					if @CountofMatrixCells = 1 
						
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
				    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
					INSERT INTO [dbo].[DATA_AccountLimit]
									([AccountRestrictionId]
									,[AccountId]
									,[PerformanceId]
									,[SaleId]
									,[SaleItemId]
									,[SaleDate]
									,[ReservationAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity)	
				end
			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @Quantity &amp;#60; 0
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)	

				end 
				IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)						 
					end
				end
			END			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			SET @Old_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@AccountID,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@Limit,
                            @ReleaseQuotaOnRefund,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>7AC800DD1D174F129817FA474A17E57E</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="DELETED"><Name>otn_sp_AR_TicketOwner_Matrixcell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE PROCEDURE [otn_sp_AR_TicketOwner_Matrixcell]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN


	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

	SET @RestrictionType = 1
	Set @OldAccountRestrictionID = 99999
	SET @OLD_Ticket_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit

			from @Restriction_Check Res_Table
				INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON cnf_AccountRestriction2MatrixCell.MatrixCellID = Res_Table.MatrixCellID
					
				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)																							
					                                                                    and cnf_accountrestriction2Account.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId
																										
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                                                                    and cnf_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction2MatrixCell.AccountRestrictionId				
				
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and TicketAccountLimit is not null
			and Res_Table.Ticket_Owner &amp;#60;&amp;#62; 0
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			and ISNULL(Res_Table.PerformanceID, 0) = 0

			GROUP BY Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit
			order by Ticket_Owner, AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0)  or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@Ticket_Owner &amp;#60;&amp;#62; @OLD_Ticket_Owner))
		BEGIN 
			If @TicketAccountLimit &amp;#62; 0 
				set @ReservationorTicket = 2

			SET @Prevent = 0;

			IF @ReservationorTicket = 2
			BEGIN
				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
					from @Restriction_Check
					where MatrixCellID in (select MatrixcellId 
											from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
											where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID)	
						and Ticket_Owner = @Ticket_Owner
						and ISNULL(PerformanceID, 0) = 0

				if @FullQuantity &amp;#62; 0
				Begin				
					if @CountofMatrixCells = 1 						 																
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					ELSE
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															null, null, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[RestrictionType]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@RestrictionType
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@FullQuantity)							 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin

							INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@Quantity)	
					end
				end
			END
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Ticket_Owner = @OLD_Ticket_Owner and @Quantity &amp;#60; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	

			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @Ticket_Owner &amp;#60;&amp;#62; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[RestrictionType]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@RestrictionType
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Ticket_Owner = @Ticket_Owner

		FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>7AB3D105189C435F9AA44AC3A5A62C70</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_TicketOwner_Matrixcell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_TicketOwner_Matrixcell]  (
                                                      @GUID        varchar(100), 
													  @SalesId		int,
                                                      @ShopCartType int,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
--    The new parameter @ShopCarType is passed in the otn_sp_GetAccountRestrictions call
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                 
                                                                                                  
AS    
BEGIN


	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int = 1
        DECLARE @AccountType int = 4
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
	DECLARE @AccountRestrictionID int
	DECLARE @AccountID int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 


	Set @OldAccountRestrictionID = 99999
	SET @OLD_Ticket_Owner = 99999

	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   			Ticket_Owner,
							Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
				cnf_AccountRestriction.Limit,
				cnf_AccountRestriction.ReleaseQuotaOnRefund

		from data_shopcartitemlimit Res_Table WITH(NOLOCK)
			INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)				ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
																					         (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))
			LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)
			                                                                           and (cnf_AccountRestriction2Account.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
																						and (cnf_AccountRestriction2DMGCategory.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionid)
			INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = cnf_AccountRestriction2MatrixCell. AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and Limit is not null
			and cnf_AccountRestriction.AccountType = @AccountType
			and Res_Table.Ticket_Owner &amp;#60;&amp;#62; 0
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			and ISNULL(Res_Table.PerformanceID, 0) = 0
		    and (((Res_Table.ShopCartGuid = @GUID))
		         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			GROUP BY 
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.Limit,
							 cnf_AccountRestriction.ReleaseQuotaOnRefund

			order by Ticket_Owner, AccountRestrictionID

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0)  or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and (@AccountID &amp;#60;&amp;#62; @OLD_Ticket_Owner))
		BEGIN 

			SET @Prevent = 0;

			select @FullQuantity = sum(Quantity),  @CountofMatrixCells = Count(*) 
				from data_shopcartitemlimit Res_Table WITH(NOLOCK)
				where MatrixCellID in (select matrixcellid
											from (
														select MatrixcellId 
														from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)									
														where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID

														union all

														select matrixcellid
															from cnf_matrixcell WITH(NOLOCK)
														where enabled = 1
															and 1 = (select 1 
																		from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
																	where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
																		and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
															and matrixcellid in (select matrixcellid 
																					from data_shopcartitemlimit WITH(NOLOCK)
																				where (((Res_Table.ShopCartGuid = @GUID))
																					 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
																			)

												)p
											where matrixcellid is not null
										)
					and Ticket_Owner = @AccountID
					and ISNULL(PerformanceID, 0) = 0
					and (((Res_Table.ShopCartGuid = @GUID))
						or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))

			if @FullQuantity &amp;#62; 0
			Begin				
				if @CountofMatrixCells = 1 						 																
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														null, null, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType,  @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
				ELSE
				begin
					Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
														null, null, @SaleID, @SaleitemID, 1,@ShopCartType,  @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					set @Prevent = @PreventSale

					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

						INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity])
									VALUES
										(@AccountRestrictionID
										,@AccountID
										,@PerformanceID
										,@SaleID
										,@SaleItemID
										,@SalesDate
										,@FullQuantity)							 
					end
				end
			end
			else
			begin
			    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
				INSERT INTO [dbo].[DATA_AccountLimit]
								([AccountRestrictionId]
								,[AccountId]
								,[PerformanceId]
								,[SaleId]
								,[SaleItemId]
								,[SaleDate]
								,[ReservationAccountQuantity])
							VALUES
								(@AccountRestrictionID
								,@AccountID
								,@PerformanceID
								,@SaleID
								,@SaleItemID
								,@SalesDate
								,@Quantity)	
			end
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Ticket_Owner and @Quantity &amp;#60; 0
			begin
						DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@AccountID
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity)	

			end 
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @AccountID &amp;#60;&amp;#62; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity)						 
				end
			end
		END

		Set @OldAccountRestrictionID = @AccountRestrictionID
		SET @OLD_Ticket_Owner = @AccountID

		FETCH NEXT FROM Check_Cursor INTO
						@AccountID,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@Limit,
                        @ReleaseQuotaOnRefund

	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


RETURN;

END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>9D1A61AC25B64413AF9802FC652F92DC</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="DELETED"><Name>otn_sp_AR_TicketOwner_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE PROCEDURE [otn_sp_AR_TicketOwner_Performance]  (
                                                      @Restriction_Check         Restriction_Table READONLY,
													  @PreventSale int OUTPUT,
													  @RejectReasonErrorCode int OUTPUT,
													  @RejectType int OUTPUT,
													  @RejectRestrictionDescription varchar(100) OUTPUT,
													  @RejectRemainingAmount int OUTPUT
                                                    ) 
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @RestrictionType int
	DECLARE @Reservation_Owner int
	DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @ReservationAccountLimit int
	DECLARE @AccountRestrictionID int
	DECLARE @Ticket_Owner int
	DECLARE @MatrixCellID int
	DECLARE @Quantity int
	DECLARE @FullQuantity int
	DECLARE @PerformanceID int
	DECLARE @EventID int
	DECLARE @SaleID int
	DECLARE @SaleitemID int
	DECLARE @CheckforRestrictionOnly int
	DECLARE @TicketAccountLimit int
	DECLARE @OLD_Ticket_Owner int
	DECLARE @ReservationorTicket int = 0
	DECLARE @CountofMatrixCells int = 0
	DECLARE @Prevent int = 0
	DECLARE @Old_PerformanceID int = 0
	DECLARE @Old_EventID int = 0

	
--Performance Reservation Owner Check
	SET @RestrictionType = 2
	Set @OldAccountRestrictionID = 99999
	Set @OLD_Ticket_Owner = 99999
	
	DECLARE Check_Cursor CURSOR LOCAL FOR
		select   Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SUM(Quantity) as Quantity,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

			from @Restriction_Check Res_Table
				INNER JOIN CNF_AccountRestriction2Performance							ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID

				LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)
					                                                                        and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
					                     																								
			    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                                                                 		and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
				INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId

			where cnf_AccountRestriction.Enabled = 1
			and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			and CNF_AccountRestriction.RestrictionType = @RestrictionType
			and Res_Table.Ticket_Owner is not null
			and TicketAccountLimit is not null
			and Res_Table.Ticket_Owner &amp;#60;&amp;#62; 0
			and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))

			GROUP BY Reservation_Owner,
							Ticket_Owner,
							Res_Table.MatrixCellID,
							SaleID,
							SaleitemID,
							CheckforRestrictionOnly,
							cnf_AccountRestriction.AccountRestrictionID,
							cnf_AccountRestriction.ReservationAccountLimit,
							cnf_AccountRestriction.TicketAccountLimit,
							Res_Table.PerformanceID,
							RES_Table.Eventid

	OPEN Check_Cursor

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit,
						@PerformanceID,
						@EventID


	WHILE @@FETCH_STATUS = 0
	BEGIN
		IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and ((@Old_PerformanceID &amp;#60;&amp;#62; @PerformanceID) or (@OLD_Ticket_Owner &amp;#60;&amp;#62; @Ticket_Owner)))
		BEGIN 
			If @TicketAccountLimit &amp;#62; 0 
				set @ReservationorTicket = 2

			SET @Prevent = 0;

			IF @ReservationorTicket = 2
			BEGIN
				select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
					from @Restriction_Check
					where PerformanceID = @PerformanceID 	
						and Ticket_Owner = @Ticket_Owner
				
				if @FullQuantity &amp;#62; 0
				Begin
					if @CountofMatrixCells = 1 						 																
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
					else
					begin
						Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						set @Prevent = @PreventSale

						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[RestrictionType]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@RestrictionType
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@FullQuantity)								 
						end
					end
				end
				else
				begin
						if @Prevent = 0 and @CheckforRestrictionOnly = 0 
						begin
							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[RestrictionType]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@RestrictionType
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)	
						end
				end
			END
		END
		ELSE
		BEGIN
			IF @OldAccountRestrictionID = @AccountRestrictionID and @Ticket_Owner = @OLD_Ticket_Owner and @Quantity &amp;#60; 0
			begin
								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Reservation_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,@Quantity
												,0)	

			end 
				
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @Ticket_Owner &amp;#60;&amp;#62; @OLD_Ticket_Owner
			begin
				if @Prevent = 0 and @CheckforRestrictionOnly = 0 
				begin
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[RestrictionType]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity]
											,[TicketAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@RestrictionType
											,@Ticket_Owner
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,0
											,@Quantity)						 
				end
			end
		END
		Set @OldAccountRestrictionID = @AccountRestrictionID
		Set @OLD_Ticket_Owner = @Ticket_Owner

	FETCH NEXT FROM Check_Cursor INTO
						@Reservation_Owner,
						@Ticket_Owner,
						@MatrixCellID,
						@Quantity,
						@SaleID,
						@SaleitemID,
						@CheckforRestrictionOnly,
						@AccountRestrictionID,
						@ReservationAccountLimit,
						@TicketAccountLimit,
						@PerformanceID,
						@EventID
	END

	CLOSE Check_Cursor;
	DEALLOCATE Check_Cursor;


--Event Ticket Owner Check
	IF @PreventSale = 0
	BEGIN
		SET @RestrictionType = 2
		Set @OldAccountRestrictionID = 99999
		Set @OLD_Ticket_Owner = 99999
		DECLARE Check_Cursor CURSOR LOCAL FOR
			select   Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SUM(Quantity),
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

		
				from @Restriction_Check Res_Table
					INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)					ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID

					LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)					ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)																							
					                     														and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId	
																								
			        LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)				ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))																							
					                         													and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId	

					INNER JOIN cnf_AccountRestriction WITH(NOLOCK)							ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId


			 where cnf_AccountRestriction.Enabled = 1
			   and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
			   and CNF_AccountRestriction.RestrictionType = @RestrictionType
			   and Res_Table.Ticket_Owner is not null
			   and TicketAccountLimit is not null
			   and Res_Table.Ticket_Owner &amp;#60;&amp;#62; 0
			   and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))


			 GROUP BY Reservation_Owner,
							 Ticket_Owner,
							 Res_Table.MatrixCellID,
							 SaleID,
							 SaleitemID,
							 CheckforRestrictionOnly,
							 cnf_AccountRestriction.AccountRestrictionID,
							 cnf_AccountRestriction.ReservationAccountLimit,
							 cnf_AccountRestriction.TicketAccountLimit,
							 Res_Table.PerformanceID,
							 RES_Table.Eventid

		OPEN Check_Cursor

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID


		WHILE @@FETCH_STATUS = 0
		BEGIN
			IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID  and (@PreventSale = 0) 
			     or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0)  and ((@OLD_PerformanceID &amp;#60;&amp;#62; @PerformanceID) or (@OLD_Ticket_Owner &amp;#60;&amp;#62; @Ticket_Owner)))			  
			BEGIN 
				If @TicketAccountLimit &amp;#62; 0 
				  set @ReservationorTicket = 2

				SET @Prevent = 0;

				IF @ReservationorTicket = 2
				BEGIN
					select @FullQuantity = sum(Quantity),  @CountofMatrixCells = 1
						from @Restriction_Check
						where PerformanceID = @PerformanceID  	
						  and Ticket_Owner = @Ticket_Owner
				
					if @FullQuantity &amp;#62; 0
					Begin
						if @CountofMatrixCells = 1 						 																
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
															   @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
						else
						begin
							Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @ReservationorTicket, @RestrictionType, @Reservation_Owner, @Ticket_Owner, 
																@PerformanceID, @EventID, @SaleID, @SaleitemID, 1, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
							set @Prevent = @PreventSale

							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
							    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@FullQuantity)							 
							end
						end
					end
					else
					begin
							if @Prevent = 0 and @CheckforRestrictionOnly = 0 
							begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[RestrictionType]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@RestrictionType
													,@Ticket_Owner
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,0
													,@Quantity)	
							end
					end
				END

			END
			ELSE
			BEGIN
				IF @OldAccountRestrictionID = @AccountRestrictionID and @Ticket_Owner = @OLD_Ticket_Owner and @Quantity &amp;#60; 0
				begin
									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[RestrictionType]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@RestrictionType
													,@Reservation_Owner
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity
													,0)	

				end 
				IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @Ticket_Owner &amp;#60;&amp;#62; @OLD_Ticket_Owner
				begin
					if @Prevent = 0 and @CheckforRestrictionOnly = 0 
					begin
								DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

								INSERT INTO [dbo].[DATA_AccountLimit]
												([AccountRestrictionId]
												,[RestrictionType]
												,[AccountId]
												,[PerformanceId]
												,[SaleId]
												,[SaleItemId]
												,[SaleDate]
												,[ReservationAccountQuantity]
												,[TicketAccountQuantity])
											VALUES
												(@AccountRestrictionID
												,@RestrictionType
												,@Ticket_Owner
												,@PerformanceID
												,@SaleID
												,@SaleItemID
												,@SalesDate
												,0
												,@Quantity)						 
					end
				end
			END
			

			Set @OldAccountRestrictionID = @AccountRestrictionID
			Set @OLD_Ticket_Owner = @Ticket_Owner
			SET @OLD_EventID = @EventID
			Set @Old_PerformanceID = @PerformanceID

		FETCH NEXT FROM Check_Cursor INTO
							@Reservation_Owner,
							@Ticket_Owner,
							@MatrixCellID,
							@Quantity,
							@SaleID,
							@SaleitemID,
							@CheckforRestrictionOnly,
							@AccountRestrictionID,
							@ReservationAccountLimit,
							@TicketAccountLimit,
							@PerformanceID,
							@EventID
		END

		CLOSE Check_Cursor;
		DEALLOCATE Check_Cursor;
	END

RETURN;
END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>2E23F0079E28480DADEC3A8F4E4636DC</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_AR_TicketOwner_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_AR_TicketOwner_Performance]  (
                                                      @GUID        varchar(100), 
                                                      @SalesId      int,
                                                      @ShopCartType int,
                                                      @PreventSale int OUTPUT,
                                                      @RejectReasonErrorCode int OUTPUT,
                                                      @RejectType int OUTPUT,
                                                      @RejectRestrictionDescription varchar(100) OUTPUT,
                                                      @RejectRemainingAmount int OUTPUT
                                                    ) 

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
--    The new parameter @ShopCarType is passed in the otn_sp_GetAccountRestrictions call
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                 

                                                    
AS    
BEGIN
    DECLARE @SalesDate datetime = getdate();
    DECLARE @RestrictionType int = 2
    DECLARE @AccountType int = 4
    DECLARE @OldAccountRestrictionID int = 99999
	DECLARE @Limit int
	DECLARE @ReleaseQuotaOnRefund int 
    DECLARE @AccountRestrictionID int
    DECLARE @AccountID int
    DECLARE @MatrixCellID int
    DECLARE @Quantity int
    DECLARE @FullQuantity int
    DECLARE @PerformanceID int
    DECLARE @EventID int
    DECLARE @SaleID int
    DECLARE @SaleitemID int
    DECLARE @CheckforRestrictionOnly int
    DECLARE @OLD_Ticket_Owner int
    DECLARE @CountofMatrixCells int = 0
    DECLARE @Prevent int = 0

    DECLARE @CONST_ShopCartType_Refund int = 2 -- Linked to BOS Enum sctRefund 

    DECLARE @Old_PerformanceID int = 0
    DECLARE @Old_EventID int = 0
--Performance Reservation Owner Check
    Set @OldAccountRestrictionID = 99999
    Set @OLD_Ticket_Owner = 99999
    DECLARE Check_Cursor CURSOR LOCAL FOR
        select   
                            Ticket_Owner,
                            Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
                            SaleID,
                            SaleitemID,
                            CheckforRestrictionOnly,
                            cnf_AccountRestriction.AccountRestrictionID,
                            cnf_AccountRestriction.Limit,
				            cnf_AccountRestriction.ReleaseQuotaOnRefund,
                            Res_Table.PerformanceID,
                            RES_Table.Eventid
            from data_shopcartitemlimit Res_Table WITH(NOLOCK)
                INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)               ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
                                                                                                     (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))
                INNER JOIN CNF_AccountRestriction2Performance WITH(NOLOCK)              ON CNF_AccountRestriction2Performance.PerformanceID = Res_Table.PerformanceID
                                                                                           and CNF_AccountRestriction2Performance.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId
                LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)                   ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)                                                                                          
                                                                                            and cnf_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId                                       
                LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)               ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))                                                                                         
                                                                                            and cnf_AccountRestriction2DMGCategory.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
                INNER JOIN cnf_AccountRestriction WITH(NOLOCK)                          ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Performance.AccountRestrictionId
            where cnf_AccountRestriction.Enabled = 1
            and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
            and CNF_AccountRestriction.RestrictionType = @RestrictionType
            and Res_Table.Ticket_Owner is not null
            and Res_Table.Ticket_Owner &amp;#60;&amp;#62; 0
--          and TicketAccountLimit is not null
            and cnf_AccountRestriction.AccountType = @AccountType
            and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
            and (((Res_Table.ShopCartGuid = @GUID))
                 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
            GROUP BY 
                            Ticket_Owner,
                            Res_Table.MatrixCellID,
                            SaleID,
                            SaleitemID,
                            CheckforRestrictionOnly,
                            cnf_AccountRestriction.AccountRestrictionID,
                            cnf_AccountRestriction.Limit,
				            cnf_AccountRestriction.ReleaseQuotaOnRefund,
                            Res_Table.PerformanceID,
                            RES_Table.Eventid
         order by Ticket_Owner, cnf_AccountRestriction.AccountRestrictionID
    OPEN Check_Cursor
    FETCH NEXT FROM Check_Cursor INTO
                        @AccountID,
                        @MatrixCellID,
                        @Quantity,
                        @SaleID,
                        @SaleitemID,
                        @CheckforRestrictionOnly,
                        @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund,
                        @PerformanceID,
                        @EventID
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and (@PreventSale = 0) or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0) and ((@Old_PerformanceID &amp;#60;&amp;#62; @PerformanceID) or (@OLD_Ticket_Owner &amp;#60;&amp;#62; @AccountID)))
        BEGIN 
            SET @Prevent = 0;
            select @FullQuantity = sum(Quantity),   @CountofMatrixCells = Count(*)
                from data_shopcartitemlimit Res_Table WITH(NOLOCK)
                where PerformanceID = @PerformanceID    
                    and MatrixCellID in (select matrixcellid
                                                    from (
                                                                select MatrixcellId 
                                                                from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)                                 
                                                                where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
                                                                union all
                                                                select matrixcellid
                                                                  from cnf_matrixcell WITH(NOLOCK)
                                                                where enabled = 1
                                                                  and 1 = (select 1 
                                                                             from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
                                                                            where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
                                                                              and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
                                                                  and matrixcellid in (select matrixcellid 
                                                                                         from data_shopcartitemlimit WITH(NOLOCK)
                                                                                           where (((Res_Table.ShopCartGuid = @GUID))
                                                                                                 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
                                                                                    )
                                                        )p
                                                    where matrixcellid is not null
                                                )
                    and Ticket_Owner = @AccountID
                    and (((Res_Table.ShopCartGuid = @GUID))
                         or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
            if @FullQuantity &amp;#62; 0
            Begin
                if @CountofMatrixCells = 1                                                                                      
                    Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
                                                        @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
                else
                begin
                    Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
                                                        @PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
                    set @Prevent = @PreventSale
                    if @Prevent = 0 and @CheckforRestrictionOnly = 0 
                    begin
                        DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                        INSERT INTO [dbo].[DATA_AccountLimit]
                                        ([AccountRestrictionId]
                                        ,[AccountId]
                                        ,[PerformanceId]
                                        ,[SaleId]
                                        ,[SaleItemId]
                                        ,[SaleDate]
                                        ,[ReservationAccountQuantity])
                                    VALUES
                                        (@AccountRestrictionID
                                        ,@AccountID
                                        ,@PerformanceID
                                        ,@SaleID
                                        ,@SaleItemID
                                        ,@SalesDate
                                        ,@FullQuantity)                              
                    end
                end
            end
            else
            begin
                DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                INSERT INTO [dbo].[DATA_AccountLimit]
                                ([AccountRestrictionId]
                                ,[AccountId]
                                ,[PerformanceId]
                                ,[SaleId]
                                ,[SaleItemId]
                                ,[SaleDate]
                                ,[ReservationAccountQuantity])
                            VALUES
                                (@AccountRestrictionID
                                ,@AccountID
                                ,@PerformanceID
                                ,@SaleID
                                ,@SaleItemID
                                ,@SalesDate
                                ,@Quantity) 
            end
        END
        ELSE
        BEGIN
            IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Ticket_Owner and @Quantity &amp;#60; 0
            begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                                INSERT INTO [dbo].[DATA_AccountLimit]
                                                ([AccountRestrictionId]
                                                ,[AccountId]
                                                ,[PerformanceId]
                                                ,[SaleId]
                                                ,[SaleItemId]
                                                ,[SaleDate]
                                                ,[ReservationAccountQuantity])
                                            VALUES
                                                (@AccountRestrictionID
                                                ,@AccountID
                                                ,@PerformanceID
                                                ,@SaleID
                                                ,@SaleItemID
                                                ,@SalesDate
                                                ,@Quantity) 
            end 
            IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @AccountID &amp;#60;&amp;#62; @OLD_Ticket_Owner
            begin
                if @Prevent = 0 and @CheckforRestrictionOnly = 0 
                begin
                            DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                            INSERT INTO [dbo].[DATA_AccountLimit]
                                            ([AccountRestrictionId]
                                            ,[AccountId]
                                            ,[PerformanceId]
                                            ,[SaleId]
                                            ,[SaleItemId]
                                            ,[SaleDate]
                                            ,[ReservationAccountQuantity])
                                        VALUES
                                            (@AccountRestrictionID
                                            ,@AccountID
                                            ,@PerformanceID
                                            ,@SaleID
                                            ,@SaleItemID
                                            ,@SalesDate
                                            ,@Quantity)                      
                end
            end
        END
        Set @OldAccountRestrictionID = @AccountRestrictionID
        Set @OLD_Ticket_Owner = @AccountID
    FETCH NEXT FROM Check_Cursor INTO
                        @AccountID,
                        @MatrixCellID,
                        @Quantity,
                        @SaleID,
                        @SaleitemID,
                        @CheckforRestrictionOnly,
                        @AccountRestrictionID,
						@Limit,
						@ReleaseQuotaOnRefund,
                        @PerformanceID,
                        @EventID
    END
    CLOSE Check_Cursor;
    DEALLOCATE Check_Cursor;
--Event Ticket Owner Check
    IF @PreventSale = 0
    BEGIN
        Set @OldAccountRestrictionID = 99999
        Set @OLD_Ticket_Owner = 99999
        DECLARE Check_Cursor CURSOR LOCAL FOR
            select   
                             Ticket_Owner,
                             Res_Table.MatrixCellID,
-- In Case of partial/total refund and the quota cannot be released return the qty = 0 
    			(case when (cnf_AccountRestriction.ReleaseQuotaOnRefund = 0) and (@ShopCartType=@CONST_ShopCartType_Refund) then 
				    0
                 else 
				    sum(Quantity)
				 end	) Quantity,
                             SaleID,
                             SaleitemID,
                             CheckforRestrictionOnly,
                             cnf_AccountRestriction.AccountRestrictionID,
                            cnf_AccountRestriction.Limit,
				            cnf_AccountRestriction.ReleaseQuotaOnRefund,
                             Res_Table.PerformanceID,
                             RES_Table.Eventid
                from data_shopcartitemlimit Res_Table WITH(NOLOCK)
                    INNER JOIN cnf_AccountRestriction2MatrixCell WITH(NOLOCK)               ON ((cnf_AccountRestriction2MatrixCell.includeAllTickets = 1) or 
                                                                                                     (cnf_AccountRestriction2MatrixCell.MatrixCellid = Res_Table.MatrixCellID))
                    INNER JOIN CNF_AccountRestriction2Event WITH(NOLOCK)                    ON CNF_AccountRestriction2Event.EventID = Res_Table.EventID
                                                                                                and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2MatrixCell.AccountRestrictionId
                    LEFT JOIN cnf_AccountRestriction2Account WITH(NOLOCK)                   ON (cnf_AccountRestriction2Account.AccountID = Res_Table.Ticket_Owner)                                                                                          
                                                                                                and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2Account.AccountRestrictionId 
                    LEFT JOIN cnf_AccountRestriction2DMGCategory WITH(NOLOCK)               ON (cnf_AccountRestriction2DMGCategory.DMGCategoryID = (select DMGCategoryID from data_account WITH(NOLOCK) where data_account.accountid = Res_Table.Ticket_Owner))                                                                                         
                                                                                                and CNF_AccountRestriction2Event.AccountRestrictionId = cnf_AccountRestriction2DMGCategory.AccountRestrictionId 
                    INNER JOIN cnf_AccountRestriction WITH(NOLOCK)                          ON cnf_AccountRestriction.AccountRestrictionId = CNF_AccountRestriction2Event.AccountRestrictionId
             where cnf_AccountRestriction.Enabled = 1
               and Convert(date, GetDAte(), 120) between Convert(date, StartDateTime, 120) and Convert(date, EndDateTime, 120)
               and CNF_AccountRestriction.RestrictionType = @RestrictionType
               and Res_Table.Ticket_Owner is not null
               and Limit is not null
               and Res_Table.Ticket_Owner &amp;#60;&amp;#62; 0
               and cnf_AccountRestriction.AccountType = @AccountType
               and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
               and (((Res_Table.ShopCartGuid = @GUID))
                     or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
             GROUP BY 
                             Ticket_Owner,
                             Res_Table.MatrixCellID,
                             SaleID,
                             SaleitemID,
                             CheckforRestrictionOnly,
                             cnf_AccountRestriction.AccountRestrictionID,
                            cnf_AccountRestriction.Limit,
				            cnf_AccountRestriction.ReleaseQuotaOnRefund,
                             Res_Table.PerformanceID,
                             RES_Table.Eventid
         order by Ticket_Owner, cnf_AccountRestriction.AccountRestrictionID
        OPEN Check_Cursor
        FETCH NEXT FROM Check_Cursor INTO
                            @AccountID,
                            @MatrixCellID,
                            @Quantity,
                            @SaleID,
                            @SaleitemID,
                            @CheckforRestrictionOnly,
                            @AccountRestrictionID,
 						    @Limit,
						    @ReleaseQuotaOnRefund,
                            @PerformanceID,
                            @EventID
        WHILE @@FETCH_STATUS = 0
        BEGIN
            IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID  and (@PreventSale = 0) 
                 or ((@OldAccountRestrictionID = @AccountRestrictionID) and (@PreventSale = 0)  and ((@OLD_PerformanceID &amp;#60;&amp;#62; @PerformanceID) or (@OLD_Ticket_Owner &amp;#60;&amp;#62; @AccountID)))            
            BEGIN 
                SET @Prevent = 0;
                select @FullQuantity = sum(Quantity),   @CountofMatrixCells = Count(*)
                    from data_shopcartitemlimit Res_Table WITH(NOLOCK)
                    where PerformanceID = @PerformanceID    
                        and MatrixCellID in (select matrixcellid
                                                    from (
                                                                select MatrixcellId 
                                                                from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)                                 
                                                                where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
                                                                union all
                                                                select matrixcellid
                                                                  from cnf_matrixcell WITH(NOLOCK)
                                                                where enabled = 1
                                                                  and 1 = (select 1 
                                                                             from cnf_AccountRestriction2MatrixCell WITH(NOLOCK)
                                                                            where cnf_AccountRestriction2MatrixCell.AccountRestrictionId = @AccountRestrictionID
                                                                              and cnf_AccountRestriction2MatrixCell.IncludeAlltickets = 1)
                                                                  and matrixcellid in (select matrixcellid 
                                                                                         from data_shopcartitemlimit WITH(NOLOCK)
                                                                                           where (((Res_Table.ShopCartGuid = @GUID))
                                                                                                 or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))
                                                                                    )
                                                        )p
                                                    where matrixcellid is not null
                                                )
                        and Ticket_Owner = @AccountID
                        and (((Res_Table.ShopCartGuid = @GUID))
                             or (('0' = @GUID) and (Res_Table.Saleid = @SalesID)))  
                if @FullQuantity &amp;#62; 0
                Begin
                    if @CountofMatrixCells = 1                                                                                      
                        Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
                                                            @PerformanceID, @EventID, @SaleID, @SaleitemID, @CheckforRestrictionOnly,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
                    else
                    begin
                        Exec otn_sp_GetAccountRestrictions @AccountRestrictionID, @FullQuantity, @RestrictionType, @AccountType, @AccountID, 
                                                            @PerformanceID, @EventID, @SaleID, @SaleitemID, 1,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
                        set @Prevent = @PreventSale
                        if @Prevent = 0 and @CheckforRestrictionOnly = 0 
                        begin
                            DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                            INSERT INTO [dbo].[DATA_AccountLimit]
                                            ([AccountRestrictionId]
                                            ,[AccountId]
                                            ,[PerformanceId]
                                            ,[SaleId]
                                            ,[SaleItemId]
                                            ,[SaleDate]
                                            ,[ReservationAccountQuantity])
                                        VALUES
                                            (@AccountRestrictionID
                                            ,@AccountID
                                            ,@PerformanceID
                                            ,@SaleID
                                            ,@SaleItemID
                                            ,@SalesDate
                                            ,@FullQuantity)                          
                        end
                    end
                end
                else
                begin
                    DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                    INSERT INTO [dbo].[DATA_AccountLimit]
                                    ([AccountRestrictionId]
                                    ,[AccountId]
                                    ,[PerformanceId]
                                    ,[SaleId]
                                    ,[SaleItemId]
                                    ,[SaleDate]
                                    ,[ReservationAccountQuantity])
                                VALUES
                                    (@AccountRestrictionID
                                    ,@AccountID
                                    ,@PerformanceID
                                    ,@SaleID
                                    ,@SaleItemID
                                    ,@SalesDate
                                    ,@Quantity) 
                end
            END
            ELSE
            BEGIN
                IF @OldAccountRestrictionID = @AccountRestrictionID and @AccountID = @OLD_Ticket_Owner and @Quantity &amp;#60; 0
                begin
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                                    INSERT INTO [dbo].[DATA_AccountLimit]
                                                    ([AccountRestrictionId]
                                                    ,[AccountId]
                                                    ,[PerformanceId]
                                                    ,[SaleId]
                                                    ,[SaleItemId]
                                                    ,[SaleDate]
                                                    ,[ReservationAccountQuantity])
                                                VALUES
                                                    (@AccountRestrictionID
                                                    ,@AccountID
                                                    ,@PerformanceID
                                                    ,@SaleID
                                                    ,@SaleItemID
                                                    ,@SalesDate
                                                    ,@Quantity) 
                end 
                IF @OldAccountRestrictionID &amp;#60;&amp;#62; @AccountRestrictionID and @AccountID &amp;#60;&amp;#62; @OLD_Ticket_Owner
                begin
                    if @Prevent = 0 and @CheckforRestrictionOnly = 0 
                    begin
                                DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)
                                INSERT INTO [dbo].[DATA_AccountLimit]
                                                ([AccountRestrictionId]
                                                ,[AccountId]
                                                ,[PerformanceId]
                                                ,[SaleId]
                                                ,[SaleItemId]
                                                ,[SaleDate]
                                                ,[ReservationAccountQuantity])
                                            VALUES
                                                (@AccountRestrictionID
                                                ,@AccountID
                                                ,@PerformanceID
                                                ,@SaleID
                                                ,@SaleItemID
                                                ,@SalesDate
                                                ,@Quantity )                         
                    end
                end
            END
            Set @OldAccountRestrictionID = @AccountRestrictionID
            Set @OLD_Ticket_Owner = @AccountID
            SET @OLD_EventID = @EventID
            Set @Old_PerformanceID = @PerformanceID
        FETCH NEXT FROM Check_Cursor INTO
                            @AccountID,
                            @MatrixCellID,
                            @Quantity,
                            @SaleID,
                            @SaleitemID,
                            @CheckforRestrictionOnly,
                            @AccountRestrictionID,
						    @Limit,
						    @ReleaseQuotaOnRefund,
                            @PerformanceID,
                            @EventID
        END
        CLOSE Check_Cursor;
        DEALLOCATE Check_Cursor;
    END
RETURN;
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>21245095E471417AA241F2E7A0E1FF90</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_CalcPMPState</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>4</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_CalcPMPState](@AEnabled INT) 
AS
BEGIN
  MERGE INTO CNF_ExternalTicketRange
    USING
	 (SELECT
	    B.ExternalTicketRangeId,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.CreationType IN (4, 7)         THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPGenerate,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType     = 0               THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPSold,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType     IN (2, 205)       THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPBlocked,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType     = 204             THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPStillToBeActivate,
        ISNULL(COUNT(CASE WHEN DATA_Ticket.VoidType NOT IN (0,2, 205,204) THEN ISNULL(DATA_Ticket.TicketId, 0) END), 0) NumPMPOthers
       FROM CNF_ExternalTicketRange B WITH(NOLOCK)
       LEFT OUTER JOIN CNF_FuncListIdentifierCodeFromExternal(@AEnabled) A ON A.ExternalTicketRangeId       = B.ExternalTicketRangeId
       LEFT OUTER JOIN DATA_Ticket       WITH(NOLOCK)	                   ON (DATA_Ticket.MatrixCellId     = B.MatrixCellId)
       LEFT OUTER JOIN DATA_Ticket2Media WITH(NOLOCK)                      ON (DATA_Ticket.TicketId         = DATA_Ticket2Media.TicketId)
        INNER JOIN DATA_MediaIdentifier  WITH(NOLOCK)                      ON (DATA_MediaIdentifier.Mediaid = DATA_Ticket2Media.MediaId)
                              AND DATA_MediaIdentifier.IdentifierType IN (5, 21)
                              AND DATA_MediaIdentifier.IdentifierCode = A.IdentifierCode
		WHERE (B.ExtRangeType = 2) AND --External to Activate
			  (B.ExternalTicketRangeIdParent is null)
              --AND (B.Enabled=1)
      GROUP BY
        B.ExternalTicketRangeId) C ON C.ExternalTicketRangeId = CNF_ExternalTicketRange.ExternalTicketRangeId
WHEN MATCHED AND (CNF_ExternalTicketRange.ExtRangeType = 2 AND CNF_ExternalTicketRange.ExternalTicketRangeIdParent is null) THEN
 UPDATE SET CNF_ExternalTicketRange.NumPMPGenerate          = ISNULL(C.NumPMPGenerate,          0),
            CNF_ExternalTicketRange.NumPMPSold              = ISNULL(C.NumPMPSold,              0),
			CNF_ExternalTicketRange.NumPMPBlocked           = ISNULL(C.NumPMPBlocked,           0),
			CNF_ExternalTicketRange.NumPMPStillToBeActivate = ISNULL(C.NumPMPStillToBeActivate, 0),
			CNF_ExternalTicketRange.NumPMPOthers            = ISNULL(C.NumPMPOthers,            0);

      UPDATE CNF_ExternalTicketRange
         SET CNF_ExternalTicketRange.NumPMPGenerate          = 0,
             CNF_ExternalTicketRange.NumPMPSold              = 0,
             CNF_ExternalTicketRange.NumPMPBlocked           = 0,
             CNF_ExternalTicketRange.NumPMPStillToBeActivate = 0,
             CNF_ExternalTicketRange.NumPMPOthers            = 0
       WHERE CNF_ExternalTicketRange.ExtRangeType = 2 -- External to Activate
         AND CNF_ExternalTicketRange.UserId IS NULL
         AND CNF_ExternalTicketRange.NumPMPGenerate IS NULL
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>F610697A82CD44679839DBB4040B342F</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_CheckAccountRestrictions</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>31</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_CheckAccountRestrictions]  (
													         @GUID                      varchar(100),
													         @SalesId		    int,
                                                             @ShopCartType               int                                                                                                   )
-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount    
--    This new parameter is passed only for Ticket Owner cases for wich we can have a ChangeAccount                                                                                                            
-- 2) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund                                                                                                                  
AS    
BEGIN

	DECLARE @PreventSale int = 0
	DECLARE @RejectReasonErrorCode int = 0
	DECLARE @RejectRestrictionDescription varchar(100) = ''
	DECLARE @RejectRemainingAmount int = 0
	DECLARE @RejectType int = 0
	DECLARE @sql varchar(250) = ''
	DECLARE @B2BAccountType int = 2
	DECLARE @BillAccountType int = 3
	DECLARE @ResAccountType int = 1
	DECLARE @TicketAccountType int = 4

	DECLARE @TicketType int = 1
	DECLARE @PerformanceType int = 2


--Reservation Owner Check by Ticket
	IF EXISTS(select *
				from CNF_AccountRestriction WITH(NOLOCK)
				where Accounttype = @ResAccountType 
				  and RestrictionType = @TicketType
				  and enabled = 1 )
		exec otn_sp_AR_ReservationOwner_Matrixcell @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	

--Reservation Owner Check by Event/Performance
  	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @ResAccountType 
					  and RestrictionType = @PerformanceType
					  and enabled = 1 )
		   exec otn_sp_AR_ReservationOwner_Performance @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--B2B Owner Check by Ticket
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @B2BAccountType 
					  and RestrictionType = @TicketType
					  and enabled = 1 )
		   exec otn_sp_AR_B2BOwner_Matrixcell @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


----B2B Owner Check by Event/Performance
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @B2BAccountType 
					  and RestrictionType = @PerformanceType
					  and enabled = 1 )
		   exec otn_sp_AR_B2BOwner_Performance @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Billing Owner Check by Ticket
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @BillAccountType 
					  and RestrictionType = @TicketType
					  and enabled = 1 ) 
		   exec otn_sp_AR_BillOwner_Matrixcell @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Billing Owner Check by Event/Performance
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @BillAccountType 
					  and RestrictionType = @PerformanceType
					  and enabled = 1 )  
		   exec otn_sp_AR_BillOwner_Performance @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Ticket Owner Check by Ticket
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @TicketAccountType 
					  and RestrictionType = @TicketType
					  and enabled = 1 )  
		   exec otn_sp_AR_TicketOwner_Matrixcell @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end


--Ticket Owner Check by Event/Performance
	If @PreventSale = 0 
	Begin
		IF EXISTS(select *
					from CNF_AccountRestriction WITH(NOLOCK)
					where Accounttype = @TicketAccountType 
					  and RestrictionType = @PerformanceType
					  and enabled = 1 )  
		   exec otn_sp_AR_TicketOwner_Performance @GUID, @SalesId,@ShopCartType, @PreventSale OUTPUT, @RejectReasonErrorCode OUTPUT, @RejectType OUTPUT, @RejectRestrictionDescription OUTPUT, @RejectRemainingAmount OUTPUT
	end
    
	if @SalesID = 0 
	begin
		delete 
		  from data_shopcartitemlimit WITH(UPDLOCK)
		 where ShopCartGuid  = @GUID;
	end


	if @GUID = '0' 
	begin
		delete 
		  from data_shopcartitemlimit WITH(UPDLOCK)
		 where saleid = @SalesID;
	end


	--delete from data_shopcartitemlimit where  (((@SalesID = 0) and (data_shopcartitemlimit.ShopCartGuid = @GUID)) or (('0' = @GUID) and (data_shopcartitemlimit.Saleid = @SalesID)))

	if @GUID &amp;#60;&amp;#62; '0'
		select @PreventSale as PreventSale, 
			   @RejectReasonErrorCode as RejectReasonErrorCode, 
			   @RejectType as RejectType,
			   @RejectRestrictionDescription as RejectRestrictionDescription,
			   @RejectRemainingAmount as RejectRemainingAmount

END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>80E5521181AF4FB28816018AC7568667</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="DELETED"><Name>otn_sp_GetAccountRestrictions</Name><ScriptList><Script Type="SP"><Database>stUnknown</Database><Version>0</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_GetAccountRestrictions] 
AS
BEGIN

END
</SQL><CheckSuccess>1</CheckSuccess><SqlScriptAK>1C4E2BB5B1494F6AAD088CC3A3CF2AB7</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_GetAccountRestrictions</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>28</Version><SQL>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions]( @AccountRestrictionID int,
                                                        @Quantity int,														
														@RestrictionType int,
														@AccountType int,
														@AccountID int,
														@PerformanceID int,
														@EventID int,
														@SaleID int,
														@SaleItemID int,
														@CheckforRestrictionOnly int,
                                                                                                                @ShopCartType int,
														@PreventSale int OUTPUT,
														@RejectReasonErrorCode int OUTPUT,
														@RejectType int OUTPUT,
														@RejectRestrictionDescription varchar(100) OUTPUT,
														@RejectRemainingAmount int OUTPUT
														)  

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )

AS    
BEGIN

	DECLARE @TicketType int = 1
	DECLARE @PerformanceType int = 2

	if @PreventSale = 0 and @RestrictionType = @TicketType
	BEGIN
		Exec otn_sp_GetAccountRestrictions_Ticket       @AccountRestrictionID,
														@Quantity,														
														@RestrictionType,
														@AccountType,
														@AccountID,
														@PerformanceID,
														@EventID,
														@SaleID,
														@SaleItemID,
														@CheckforRestrictionOnly,
                                                                                                                @ShopCartType,
														@PreventSale OUTPUT,
														@RejectReasonErrorCode OUTPUT,
														@RejectType OUTPUT,
														@RejectRestrictionDescription OUTPUT,
														@RejectRemainingAmount OUTPUT
	end

	if @PreventSale = 0 and @RestrictionType = @PerformanceType
	BEGIN
		Exec otn_sp_GetAccountRestrictions_Performance   @AccountRestrictionID,
														 @Quantity,														
														 @RestrictionType,
														 @AccountType,
														 @AccountID,
														 @PerformanceID,
														 @EventID,
														 @SaleID,
														 @SaleItemID,
														 @CheckforRestrictionOnly,
                                                                                                                 @ShopCartType,
														 @PreventSale OUTPUT,
														 @RejectReasonErrorCode OUTPUT,
														 @RejectType OUTPUT,
														 @RejectRestrictionDescription OUTPUT,
														 @RejectRemainingAmount OUTPUT

	END
	
RETURN;
END</SQL><CheckSuccess>0</CheckSuccess><SqlScriptAK>FC3EBC8F2E3E4880BE1D66A5E01EDAFD</SqlScriptAK><ExecuteOnCreate>0</ExecuteOnCreate></Script></ScriptList></StoredProcedure><StoredProcedure Status="DELETED"><Name>otn_sp_GetAccountRestrictions_MatrixCell</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions_MatrixCell](  @AccountRestrictionID int,
																	@Quantity int,														
																	@ReservationorTicket int,
																	@RestrictionType int,
																	@Reservation_AccountID int,
																	@Ticket_AccountID int,
																	@PerformanceID int,
																	@EventID int,
																	@SaleID int,
																	@SaleItemID int,
																	@CheckforRestrictionOnly int,
																	@PreventSale int OUTPUT,
																	@RejectReasonErrorCode int OUTPUT,
																	@RejectType int OUTPUT,
																	@RejectRestrictionDescription varchar(100) OUTPUT,
																	@RejectRemainingAmount int OUTPUT
																	)  

AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @ReservationLimit int
	DECLARE @TicketLimit int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int
	DECLARE @TicketAccountQuantity_DayofYear int
	DECLARE @TicketAccountQuantity_WeekofYear int
	DECLARE @TicketAccountQuantity_MonthofYear int
	DECLARE @TicketAccountQuantity_QuarterofYear int
	DECLARE @TicketAccountQuantity_SemiAnnualofYear int
	DECLARE @TicketAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
	DECLARE @TicketAccountOwner int = 2
    DECLARE @Description varchar(max)
	DECLARE @CheckOnly int = 1
	DECLARE @EX_Quantity int = 0
	DECLARE @RestrictionLimit int

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET	@RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0


	if ((@PerformanceID is null) and (@EventID is null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
			select  AccountRestrictionID,
			        Description,
					ReservationAccountLimit,
					TicketAccountLimit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					case when ReservationAccountQuantity_DayofYear &amp;#62; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end ReservationAccountQuantity_DayofYear,
					case when ReservationAccountQuantity_WeekofYear &amp;#62; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end ReservationAccountQuantity_WeekofYear,
					case when ReservationAccountQuantity_MonthofYear &amp;#62; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end ReservationAccountQuantity_MonthofYear,

					case when ReservationAccountQuantity_QuarterofYear &amp;#62; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end ReservationAccountQuantity_QuarterofYear,
					case when ReservationAccountQuantity_SemiAnnualofYear &amp;#62; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end ReservationAccountQuantity_SemiAnnualofYear,


					case when ReservationAccountQuantity_Year &amp;#62; 0 then ReservationAccountQuantity_Year
						else 0
					end ReservationAccountQuantity_Year,
					case when TicketAccountQuantity_DayofYear &amp;#62; 0 then TicketAccountQuantity_DayofYear
						else 0
					end TicketAccountQuantity_DayofYear,
					case when TicketAccountQuantity_WeekofYear &amp;#62; 0 then TicketAccountQuantity_WeekofYear
						else 0
					end TicketAccountQuantity_WeekofYear,
					case when TicketAccountQuantity_MonthofYear &amp;#62; 0 then TicketAccountQuantity_MonthofYear
						else 0
					end TicketAccountQuantity_MonthofYear,

					case when TicketAccountQuantity_QuarterofYear &amp;#62; 0 then TicketAccountQuantity_QuarterofYear
						else 0
					end TicketAccountQuantity_QuarterofYear,
					case when TicketAccountQuantity_SemiAnnualofYear &amp;#62; 0 then TicketAccountQuantity_SemiAnnualofYear
						else 0
					end TicketAccountQuantity_SemiAnnualofYear,

					case when TicketAccountQuantity_Year &amp;#62; 0 then TicketAccountQuantity_Year
						else 0
					end TicketAccountQuantity_Year
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.ReservationAccountLimit,
						CNF_AccountRestriction.TicketAccountLimit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
									and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
									and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Reservation_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) ReservationAccountQuantity_Year,

						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then TicketAccountQuantity
										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) TicketAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) TicketAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) TicketAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then TicketAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) TicketAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then TicketAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) TicketAccountQuantity_SemiAnnualofYear,


						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then TicketAccountQuantity
											else 0
										end)
								from DATA_AccountLimit
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @Ticket_AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @Saleid
								and Data_accountlimit.Saleitemid &amp;#60;&amp;#62; @Saleitemid
						), 0) TicketAccountQuantity_Year

			from CNF_AccountRestriction WITH(NOLOCK)
					LEFT JOIN CNF_AccountRestriction2Account WITH(NOLOCK)			on CNF_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId
																						and CNF_AccountRestriction2Account.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionid
																						and CNF_AccountRestriction2Account.Accountid = case when @ReservationorTicket = @ReservationAccountOwner then @Reservation_AccountID
																																							  else @Ticket_AccountID
																																						  end
					LEFT JOIN CNF_AccountRestriction2DMGCategory WITH(NOLOCK)		ON CNF_AccountRestriction2DMGCategory.dmgcategoryID = (SELECT dmgcategoryid  
																																			 from data_account DA
																																			 where DA.AccountID =  case when @ReservationorTicket = @ReservationAccountOwner then @Reservation_AccountID
																																										else @Ticket_AccountID
																																									 end
																																		   )
																						and CNF_AccountRestriction2DMGCategory.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionid


				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID
					  and ((cnf_AccountRestriction2Account.accountid is not null) or (cnf_AccountRestriction2DMGCategory.dmgcategoryid is not null))
			)p
		where ((ISNULL(ReservationAccountLimit, 0) &amp;#62; 0) or (ISNULL(TicketAccountLimit, 0) &amp;#62; 0))


		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@ReservationLimit,
							@TicketLimit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year,
							@TicketAccountQuantity_DayofYear,
							@TicketAccountQuantity_WeekofYear,
							@TicketAccountQuantity_MonthofYear,
							@TicketAccountQuantity_QuarterofYear,
							@TicketAccountQuantity_SemiAnnualofYear,
							@TicketAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN
	
		IF @Quantity &amp;#60; 0  --Always Accept a negative amounts
			BEGIN
				Set @PreventSale = 0  
				If @ReservationorTicket = @ReservationAccountOwner
				BEGIN
					INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[RestrictionType]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity]
										,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@RestrictionType
									,@Reservation_AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,0)
				END
				ELSE
				BEGIN
				  If @ReservationorTicket = @TicketAccountOwner
				  BEGIN

					INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[RestrictionType]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity]
										,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@RestrictionType
									,@Reservation_AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,0
									,@Quantity)
				  END
				  ELSE
				  BEGIN
					DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

					INSERT INTO [dbo].[DATA_AccountLimit]
										([AccountRestrictionId]
										,[RestrictionType]
										,[AccountId]
										,[PerformanceId]
										,[SaleId]
										,[SaleItemId]
										,[SaleDate]
										,[ReservationAccountQuantity]
										,[TicketAccountQuantity])
								VALUES
									(@AccountRestrictionID
									,@RestrictionType
									,@Reservation_AccountID
									,@PerformanceID
									,@SaleID
									,@SaleItemID
									,@SalesDate
									,@Quantity
									,@Quantity)
					END
				END
			END


			--ReservationOwnerCheck
			If @ReservationorTicket = @ReservationAccountOwner and @ReservationLimit is not null and @PerformanceId is null 
			BEGIN
				if @Quantity &amp;#60;= @ReservationLimit
				BEGIN
					if (((@Quantity + @ReservationAccountQuantity_DayofYear) &amp;#60;= @PerDayLimit)   and
						((@Quantity + @ReservationAccountQuantity_WeekofYear) &amp;#60;= @PerWeekLimit)  and
						((@Quantity + @ReservationAccountQuantity_MonthofYear) &amp;#60;= @PerMonthLimit) and
						((@Quantity + @ReservationAccountQuantity_QuarterofYear) &amp;#60;= @PerQuarterLimit) and
						((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &amp;#60;= @PerSemiAnnualLimit) and
						((@Quantity + @ReservationAccountQuantity_Year) &amp;#60;= @PerYearLimit)) and
						 (@Quantity &amp;#60;= (@ReservationLimit - @ReservationAccountQuantity_Year))
					BEGIN
							If @CheckforRestrictionOnly &amp;#60;&amp;#62; @CheckOnly
							BEGIN
									if @Ticket_AccountID is not null and @TicketLimit is null
									BEGIN
										  select @EX_Quantity = count(*)
											from data_saleitem WITH(NOLOCK)	
												INNER JOIN DATA_SaleItem2Ticket	WITH(NOLOCK)			ON data_saleitem2ticket.SaleItemId = data_saleitem.saleitemid
												INNER JOIN data_ticket WITH(NOLOCK)						ON data_ticket.ticketid = data_saleitem2ticket.ticketid

											where data_saleitem.saleitemid = @SaleitemID
											  and data_ticket.Accountid = @Ticket_AccountID	

									END

									DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[RestrictionType]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@RestrictionType
													,@Reservation_AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity
													,@EX_Quantity)
							END
					END
					ELSE
					BEGIN
						Set @PreventSale = 1
						Set @RejectType = 1
						if @RejectReasonErrorCode = 0
						begin					    
							if ((@Quantity + @ReservationAccountQuantity_DayofYear) &amp;#62; @PerDayLimit)
							begin
								SET @RejectRemainingAmount =  (@PerDayLimit - @ReservationAccountQuantity_DayofYear)
								SET @RejectRestrictionDescription = @Description
							
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5075
								else
									Set @RejectReasonErrorCode = 5076
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_WeekofYear) &amp;#62; @PerWeekLimit)
							begin
								SET @RejectRemainingAmount =  (@PerWeekLimit - @ReservationAccountQuantity_WeekofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5077
								else
									Set @RejectReasonErrorCode = 5078
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_MonthofYear) &amp;#62; @PerMonthLimit)
							begin
								SET @RejectRemainingAmount =  (@PerMonthLimit - @ReservationAccountQuantity_MonthofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5079
								else
									Set @RejectReasonErrorCode = 5080	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_QuarterofYear) &amp;#62; @PerQuarterLimit)
							begin
								SET @RejectRemainingAmount =  (@PerQuarterLimit - @ReservationAccountQuantity_QuarterofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5090
								else
									Set @RejectReasonErrorCode = 5091	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &amp;#62; @PerSemiAnnualLimit)
							begin
								SET @RejectRemainingAmount =  (@PerSemiAnnualLimit - @ReservationAccountQuantity_SemiAnnualofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5092
								else
									Set @RejectReasonErrorCode = 5093	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &amp;#62; @PerYearLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerYearLimit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5081
								else
									Set @RejectReasonErrorCode = 5082
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &amp;#62; @ReservationLimit) 
							begin
								SET @RejectRemainingAmount =  (@ReservationLimit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5083
								else
									Set @RejectReasonErrorCode = 5084
							end
						end

					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 1
					if @RejectReasonErrorCode = 0
					begin
						SET @RejectRemainingAmount =  (@ReservationLimit - @ReservationAccountQuantity_Year)
						SET @RejectRestrictionDescription = @Description 
						if @RejectRemainingAmount &amp;#60; 0 
							SET @RejectRemainingAmount = 0

						if @RejectRemainingAmount = 0
							Set @RejectReasonErrorCode = 5085
						else
							Set @RejectReasonErrorCode = 5086
					end
				END
			END

	--TicketOwnerCheck
			if @ReservationorTicket = @TicketAccountOwner and @TicketLimit is not null and @PerformanceId is null 
			BEGIN
				if @Quantity &amp;#60;= @TicketLimit
				BEGIN
					if (((@Quantity + @TicketAccountQuantity_DayofYear) &amp;#60;= @PerDayLimit)   and
						((@Quantity + @TicketAccountQuantity_WeekofYear) &amp;#60;= @PerWeekLimit)  and
						((@Quantity + @TicketAccountQuantity_MonthofYear) &amp;#60;= @PerMonthLimit) and
						((@Quantity + @TicketAccountQuantity_QuarterofYear) &amp;#60;= @PerQuarterLimit) and
						((@Quantity + @TicketAccountQuantity_SemiAnnualofYear) &amp;#60;= @PerSemiAnnualLimit) and
						((@Quantity + @TicketAccountQuantity_Year) &amp;#60;= @PerYearLimit)) and
						(@Quantity &amp;#60;= (@TicketLimit - @TicketAccountQuantity_Year))
					BEGIN
							If @CheckforRestrictionOnly &amp;#60;&amp;#62; @CheckOnly
							BEGIN

									if @Reservation_AccountID is not null and @ReservationLimit is null
									BEGIN
										  select @EX_Quantity = count(*)
											from data_reservation

											where data_reservation.saleid = @SaleID
											  and data_reservation.Accountid = @Reservation_AccountID	

									END

									DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[RestrictionType]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity]
													,[TicketAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@RestrictionType
													,@Ticket_AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@EX_Quantity
													,@Quantity)
							END
					END
					ELSE
					BEGIN
						Set @PreventSale = 1
						Set @RejectType = 2
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_DayofYear) &amp;#62; @PerDayLimit)
							begin
								SET @RejectRemainingAmount =  (@PerDayLimit - @TicketAccountQuantity_DayofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5075
								else
									Set @RejectReasonErrorCode = 5076
							end
						end
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_WeekofYear) &amp;#62; @PerWeekLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerWeekLimit - @TicketAccountQuantity_WeekofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5077
								else
									Set @RejectReasonErrorCode = 5078
							end
						end
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_MonthofYear) &amp;#62; @PerMonthLimit) 
							Begin
								SET @RejectRemainingAmount =  (@PerMonthLimit - @TicketAccountQuantity_MonthofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5079
								else
									Set @RejectReasonErrorCode = 5080
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_QuarterofYear) &amp;#62; @PerQuarterLimit) 
							Begin
								SET @RejectRemainingAmount =  (@PerQuarterLimit - @TicketAccountQuantity_QuarterofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5090
								else
									Set @RejectReasonErrorCode = 5091
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_SemiAnnualofYear) &amp;#62; @PerSemiAnnualLimit) 
							Begin
								SET @RejectRemainingAmount =  (@PerSemiAnnualLimit - @TicketAccountQuantity_SemiAnnualofYear)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5092
								else
									Set @RejectReasonErrorCode = 5093
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_Year) &amp;#62; @PerYearLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerYearLimit - @TicketAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0
							
								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5081
								else
									Set @RejectReasonErrorCode = 5082
							end
						end
						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @TicketAccountQuantity_Year) &amp;#62; @TicketLimit) 
							begin
								SET @RejectRemainingAmount =  (@TicketLimit - @TicketAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5083
								else
									Set @RejectReasonErrorCode = 5084
							end
						end
					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 2
					if @RejectReasonErrorCode = 0
					begin
						SET @RejectRemainingAmount =  (@TicketLimit - @TicketAccountQuantity_Year)
						SET @RejectRestrictionDescription = @Description
						if @RejectRemainingAmount &amp;#60; 0 
							SET @RejectRemainingAmount = 0

						if @RejectRemainingAmount = 0		   					 
							Set @RejectReasonErrorCode = 5085
						else
							Set @RejectReasonErrorCode = 5086
					end
				END
			END





		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@ReservationLimit,
							@TicketLimit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year,
							@TicketAccountQuantity_DayofYear,
							@TicketAccountQuantity_WeekofYear,
							@TicketAccountQuantity_MonthofYear,
							@TicketAccountQuantity_QuarterofYear,
							@TicketAccountQuantity_SemiAnnualofYear,
							@TicketAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END

RETURN
END

</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>AF6BA640E861463CBF5AC95323EA5B50</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_GetAccountRestrictions_Performance</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>8</Version><SQL>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions_Performance]( @AccountRestrictionID int,
																	@Quantity int,														
																	@RestrictionType int,
																	@AccountType int,
																	@AccountID int,
																	@PerformanceID int,
																	@EventID int,
																	@SaleID int,
																	@SaleItemID int,
																	@CheckforRestrictionOnly int,
																	@ShopCartType int,
																	@PreventSale int OUTPUT,
																	@RejectReasonErrorCode int OUTPUT,
																	@RejectType int OUTPUT,
																	@RejectRestrictionDescription varchar(100) OUTPUT,
																	@RejectRemainingAmount int OUTPUT
																	)  

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )

AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @Limit int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
	DECLARE @TicketAccountOwner int = 2
        DECLARE @Description varchar(max)
 	DECLARE @CheckOnly int = 1
	DECLARE @RestrictionLimit int

        DECLARE @CONST_ShopCartType_ChangeAccount int = 1; -- Linked to BOS Enum sctChangeAccount view on BOS TWsDBAccountLimit.ExecuteSPInsert

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET @RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0





	if ((@PerformanceID is not null) and (@EventID is not null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
				select AccountRestrictionID,
			       Description,
					Limit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					(case when ReservationAccountQuantity_DayofYear &amp;#62; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end) ReservationAccountQuantity_DayofYear,
					(case when ReservationAccountQuantity_WeekofYear &amp;#62; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end) ReservationAccountQuantity_WeekofYear,
					(case when ReservationAccountQuantity_MonthofYear &amp;#62; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end) ReservationAccountQuantity_MonthofYear,
					(case when ReservationAccountQuantity_QuarterofYear &amp;#62; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end) ReservationAccountQuantity_QuarterofYear,
					(case when ReservationAccountQuantity_SemiAnnualofYear &amp;#62; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end) ReservationAccountQuantity_SemiAnnualofYear,
					(case when ReservationAccountQuantity_Year &amp;#62; 0 then ReservationAccountQuantity_Year
						else 0
					end) ReservationAccountQuantity_Year
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.Limit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit WITH(NOLOCK) 
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
									and data_accountLimit.PerformanceID = @PerformanceID
									and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
									and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit WITH(NOLOCK) 
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit WITH(NOLOCK) 
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit  WITH(NOLOCK) 
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit WITH(NOLOCK) 
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit  WITH(NOLOCK) 
												INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountLimit.PerformanceID = @PerformanceID
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_Year

				from CNF_AccountRestriction WITH(NOLOCK)
																					
				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID

				--UNION ALL

				--select distinct CNF_AccountRestriction.AccountRestrictionID,
				--        CNF_AccountRestriction.Description,
				--		CNF_AccountRestriction.Limit,
				--		ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
				--		ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
				--		ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
				--		ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
				--		ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
				--		ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
				--		ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
				--						else 0
				--					end)
				--				from DATA_AccountLimit WITH(NOLOCK) 
				--					INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
				--				where (DATA_AccountLimit.Accountid = @AccountID)
				--					and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
				--					and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
				--					and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
				--					and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
				--					and data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID
				--		), 0) ReservationAccountQuantity_DayofYear,
				--		ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
				--							else 0
				--						end)
				--				from DATA_AccountLimit WITH(NOLOCK) 
				--								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
				--				where (DATA_AccountLimit.Accountid = @AccountID)
				--				and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
				--				and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
				--				and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
				--				and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
				--				and data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID
				--		), 0) ReservationAccountQuantity_WeekofYear,
				--		ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
				--							else 0
				--						end)
				--				from DATA_AccountLimit WITH(NOLOCK) 
				--								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
				--				where (DATA_AccountLimit.Accountid = @AccountID)
				--				and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
				--				and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
				--				and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
				--				and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
				--				and data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID
				--		), 0) ReservationAccountQuantity_MonthofYear,

				--		ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
				--													CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
				--														 else 0
				--													end
				--								else 0
				--							end)
				--				from DATA_AccountLimit  WITH(NOLOCK) 
				--								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
				--				where (DATA_AccountLimit.Accountid = @AccountID)
				--				and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
				--				and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
				--				and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
				--				and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
				--				and data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID
				--		), 0) ReservationAccountQuantity_QuarterofYear,

				--		ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
				--											CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
				--															else 2
				--													end) =
				--													(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
				--															else 2
				--													end))  then ReservationAccountQuantity
				--												else 0
				--											end 

				--						else 0
				--					end)
				--				from DATA_AccountLimit  WITH(NOLOCK) 
				--								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
				--				where (DATA_AccountLimit.Accountid = @AccountID)
				--				and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
				--				and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
				--				and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
				--				and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
				--				and data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID
				--		), 0) ReservationAccountQuantity_SemiAnnualofYear,

				--		ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) = cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
				--							else 0
				--						end)
				--				from DATA_AccountLimit WITH(NOLOCK) 
				--								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
				--				where (DATA_AccountLimit.Accountid = @AccountID)
				--				and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
				--				and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
				--				and data_accountLimit.PerformanceID in (select performanceid from cnf_performance where Eventid =  @EventId)
				--				and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
				--				and data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID
				--		), 0) ReservationAccountQuantity_Year

				--from CNF_AccountRestriction WITH(NOLOCK)
																					
				--where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID

			)p

		where (ISNULL(Limit, 0) &amp;#62; 0)



		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN	
			if @Limit is not null and @PerformanceId is not null 
			BEGIN
				if @Quantity &amp;#60;= @Limit and @Quantity &amp;#60;= (@Limit - @ReservationAccountQuantity_Year)
				BEGIN
					If @CheckforRestrictionOnly &amp;#60;&amp;#62; @CheckOnly
					BEGIN
							DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

							INSERT INTO [dbo].[DATA_AccountLimit]
											([AccountRestrictionId]
											,[AccountId]
											,[PerformanceId]
											,[SaleId]
											,[SaleItemId]
											,[SaleDate]
											,[ReservationAccountQuantity])
										VALUES
											(@AccountRestrictionID
											,@AccountID
											,@PerformanceID
											,@SaleID
											,@SaleItemID
											,@SalesDate
											,@Quantity)
					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 3
					if (@PerformanceID is not null) and (@EventID is not null)
					BEGIN
						if @RejectReasonErrorCode = 0
						begin
							SET @RejectRemainingAmount =  (@Limit - @ReservationAccountQuantity_Year)
							SET @RejectRestrictionDescription = @Description
							if @RejectRemainingAmount &amp;#60; 0 
								SET @RejectRemainingAmount = 0

							if @RejectRemainingAmount = 0	   						 
								Set @RejectReasonErrorCode = 5087
							else
								Set @RejectReasonErrorCode = 5088
						end
					END
				END			
			END


		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END	

RETURN
END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>9E9BDDAA24FF47598CDC93A6DDC65BD0</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_GetAccountRestrictions_Ticket</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>6</Version><SQL>CREATE Procedure [dbo].[otn_sp_GetAccountRestrictions_Ticket](	@AccountRestrictionID int,
																@Quantity int,														
																@AccountType int,
																@RestrictionType int,
																@AccountID int,
																@PerformanceID int,
																@EventID int,
																@SaleID int,
																@SaleItemID int,
																@CheckforRestrictionOnly int,
																@ShopCartType int,
																@PreventSale int OUTPUT,
																@RejectReasonErrorCode int OUTPUT,
																@RejectType int OUTPUT,
																@RejectRestrictionDescription varchar(100) OUTPUT,
																@RejectRemainingAmount int OUTPUT
																)  

-- History Changes
-- 1) D.S. 28/06/2023 WEBPGA-320
--    Added the parameter @ShopCartType in order skip some Check in case of ChangeAccount ( more Ticket with same SaleItemId )
-- 2) F.C. 26/01/2024 IDBOS-8894
--	  
AS    
BEGIN

	DECLARE @SalesDate datetime = getdate();
	DECLARE @Limit Int
	DECLARE	@PerDayLimit int
	DECLARE	@PerWeekLimit int
	DECLARE	@PerMonthLimit int
	DECLARE	@PerQuarterLimit int
	DECLARE	@PerSemiAnnualLimit int
	DECLARE	@PerYearLimit int
	DECLARE @ReservationAccountQuantity_DayofYear int
	DECLARE @ReservationAccountQuantity_WeekofYear int
	DECLARE @ReservationAccountQuantity_MonthofYear int
	DECLARE @ReservationAccountQuantity_QuarterofYear int
	DECLARE @ReservationAccountQuantity_SemiAnnualofYear int
	DECLARE @ReservationAccountQuantity_Year int

	DECLARE @RestrictLimit int = 99999
	DECLARE @ReservationAccountOwner int = 1
    DECLARE @Description varchar(max)
	DECLARE @CheckOnly int = 1
	DECLARE @RestrictionLimit int
        
    DECLARE @CONST_ShopCartType_ChangeAccount int = 1; -- Linked to BOS Enum sctChangeAccount view on BOS TWsDBAccountLimit.ExecuteSPInsert

	SET @PreventSale = 0  
	SET @RejectReasonErrorCode = 0
	SET @RejectType = 0
	SET @RejectRestrictionDescription = ''
	SET @RejectRemainingAmount = 0


	if ((@PerformanceID is null) and (@EventID is null))
	BEGIN
		DECLARE Restriction_Cursor CURSOR LOCAL FOR
			select  AccountRestrictionID,
			        Description,
					Limit,
					PerDayLimit,
					PerWeekLimit,
					PerMonthLimit,
					PerQuarterLimit,
					PerSemiAnnualLimit,
					PerYearLimit,
					case when ReservationAccountQuantity_DayofYear &amp;#62; 0 then ReservationAccountQuantity_DayofYear
						else 0
					end ReservationAccountQuantity_DayofYear,
					case when ReservationAccountQuantity_WeekofYear &amp;#62; 0 then ReservationAccountQuantity_WeekofYear
						else 0
					end ReservationAccountQuantity_WeekofYear,
					case when ReservationAccountQuantity_MonthofYear &amp;#62; 0 then ReservationAccountQuantity_MonthofYear
						else 0
					end ReservationAccountQuantity_MonthofYear,

					case when ReservationAccountQuantity_QuarterofYear &amp;#62; 0 then ReservationAccountQuantity_QuarterofYear
						else 0
					end ReservationAccountQuantity_QuarterofYear,
					case when ReservationAccountQuantity_SemiAnnualofYear &amp;#62; 0 then ReservationAccountQuantity_SemiAnnualofYear
						else 0
					end ReservationAccountQuantity_SemiAnnualofYear,
					case when ReservationAccountQuantity_Year &amp;#62; 0 then ReservationAccountQuantity_Year
						else 0
					end ReservationAccountQuantity_Year
				
		from (
				select distinct CNF_AccountRestriction.AccountRestrictionID,
				        CNF_AccountRestriction.Description,
						CNF_AccountRestriction.Limit,
						ISNULL(CNF_AccountRestriction.PerDayLimit, @RestrictLimit) as PerDayLimit,
						ISNULL(CNF_AccountRestriction.PerWeekLimit, @RestrictLimit) as PerWeekLimit,
						ISNULL(CNF_AccountRestriction.PerMonthLimit, @RestrictLimit) as PerMonthLimit,
						ISNULL(CNF_AccountRestriction.PerQuarterLimit, @RestrictLimit) as PerQuarterLimit,
						ISNULL(CNF_AccountRestriction.PerSemiAnnualLimit, @RestrictLimit) as PerSemiAnnualLimit,
						ISNULL(CNF_AccountRestriction.PerYearLimit, @RestrictLimit) as PerYearLimit,
						ISNULL((select sum(case when cast(saledate as date) = cast(@SalesDate as date) then ReservationAccountQuantity
										else 0
									end)
								from DATA_AccountLimit WITH(NOLOCK) 
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
									and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
									and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
									and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
									and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_DayofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(wk, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(wk, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit WITH(NOLOCK) 
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_WeekofYear,
						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4)) + '-' + cast(datepart(mm, saledate) as varchar(2))) = cast(datepart(yy, @SalesDate) as varchar(4)) + '-' + cast(datepart(mm, @SalesDate) as varchar(2)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit WITH(NOLOCK) 
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_MonthofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
																	CASE when (DATEPART(QUARTER, SaleDate) = DATEPART(QUARTER, @SalesDate)) then ReservationAccountQuantity
																		 else 0
																	end
												else 0
											end)
								from DATA_AccountLimit WITH(NOLOCK) 
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_QuarterofYear,

						ISNULL((select sum(case when (DATEPART(year, SaleDate) = DATEPART(year, @SalesDate)) then 
															CASE WHEN ((CASE when DATEPART(QUARTER, SaleDate) in (1, 2) then 1
																			else 2
																	end) =
																	(CASE when DATEPART(QUARTER, @SalesDate) in (1, 2) then 1
																			else 2
																	end))  then ReservationAccountQuantity
																else 0
															end 

										else 0
									end)
								from DATA_AccountLimit WITH(NOLOCK) 
									INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_SemiAnnualofYear,

						ISNULL((select sum(case when (cast(datepart(yy, saledate) as varchar(4))) &amp;#60;= cast(datepart(yy, @SalesDate) as varchar(4)) then ReservationAccountQuantity
											else 0
										end)
								from DATA_AccountLimit WITH(NOLOCK) 
								INNER JOIN data_account WITH(NOLOCK)				ON data_account.accountid = data_accountlimit.accountid
								where (DATA_AccountLimit.Accountid = @AccountID)
								and DATA_AccountLimit.AccountRestrictionID = CNF_AccountRestriction.AccountRestrictionId
								and DATA_AccountLimit.SaleDate &amp;#62;= CNF_AccountRestriction.StartDateTime
								and data_accountlimit.Saleid &amp;#60;&amp;#62; @SaleID
								and ((data_accountlimit.Saleitemid &amp;#60;&amp;#62; @SaleitemID) or (@ShopCartType=@CONST_ShopCartType_ChangeAccount))
						), 0) ReservationAccountQuantity_Year


			from CNF_AccountRestriction WITH(NOLOCK)
				where CNF_AccountRestriction.AccountRestrictionID = @AccountRestrictionID

			)p
		where (ISNULL(Limit, 0) &amp;#62; 0)


		OPEN Restriction_Cursor

		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		WHILE @@FETCH_STATUS = 0
		BEGIN
	
			If @Limit is not null and @PerformanceId is null 
			BEGIN
				if @Quantity &amp;#60;= @Limit
				BEGIN
					if (((@Quantity + @ReservationAccountQuantity_DayofYear) &amp;#60;= @PerDayLimit)   and
						((@Quantity + @ReservationAccountQuantity_WeekofYear) &amp;#60;= @PerWeekLimit)  and
						((@Quantity + @ReservationAccountQuantity_MonthofYear) &amp;#60;= @PerMonthLimit) and
						((@Quantity + @ReservationAccountQuantity_QuarterofYear) &amp;#60;= @PerQuarterLimit) and
						((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &amp;#60;= @PerSemiAnnualLimit) and
						((@Quantity + @ReservationAccountQuantity_Year) &amp;#60;= @PerYearLimit)) and
						 (@Quantity &amp;#60;= (@Limit - @ReservationAccountQuantity_Year))
					BEGIN
							If @CheckforRestrictionOnly &amp;#60;&amp;#62; @CheckOnly
							BEGIN								
									DELETE FROM data_accountlimit WHERE saleid = @SaleID and saleitemid = @Saleitemid and ISNULL(PerformanceID, 0) = ISNULL(@PerformanceID, 0)

									INSERT INTO [dbo].[DATA_AccountLimit]
													([AccountRestrictionId]
													,[AccountId]
													,[PerformanceId]
													,[SaleId]
													,[SaleItemId]
													,[SaleDate]
													,[ReservationAccountQuantity])
												VALUES
													(@AccountRestrictionID
													,@AccountID
													,@PerformanceID
													,@SaleID
													,@SaleItemID
													,@SalesDate
													,@Quantity)
							END
					END
					ELSE
					BEGIN
						Set @PreventSale = 1
						Set @RejectType = 1
						if @RejectReasonErrorCode = 0
						begin					    
							if ((@Quantity + @ReservationAccountQuantity_DayofYear) &amp;#62; @PerDayLimit)
							begin
								SET @RejectRemainingAmount =  (@PerDayLimit - @ReservationAccountQuantity_DayofYear)
								SET @RejectRestrictionDescription = @Description
							
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5075
								else
									Set @RejectReasonErrorCode = 5076
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_WeekofYear) &amp;#62; @PerWeekLimit)
							begin
								SET @RejectRemainingAmount =  (@PerWeekLimit - @ReservationAccountQuantity_WeekofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5077
								else
									Set @RejectReasonErrorCode = 5078
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_MonthofYear) &amp;#62; @PerMonthLimit)
							begin
								SET @RejectRemainingAmount =  (@PerMonthLimit - @ReservationAccountQuantity_MonthofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5079
								else
									Set @RejectReasonErrorCode = 5080	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_QuarterofYear) &amp;#62; @PerQuarterLimit)
							begin
								SET @RejectRemainingAmount =  (@PerQuarterLimit - @ReservationAccountQuantity_QuarterofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5090
								else
									Set @RejectReasonErrorCode = 5091	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_SemiAnnualofYear) &amp;#62; @PerSemiAnnualLimit)
							begin
								SET @RejectRemainingAmount =  (@PerSemiAnnualLimit - @ReservationAccountQuantity_SemiAnnualofYear) 
								SET @RejectRestrictionDescription = @Description
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0   							 
									Set @RejectReasonErrorCode = 5092
								else
									Set @RejectReasonErrorCode = 5093	
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &amp;#62; @PerYearLimit) 
							begin
								SET @RejectRemainingAmount =  (@PerYearLimit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5081
								else
									Set @RejectReasonErrorCode = 5082
							end
						end

						if @RejectReasonErrorCode = 0
						begin
							if ((@Quantity + @ReservationAccountQuantity_Year) &amp;#62; @Limit) 
							begin
								SET @RejectRemainingAmount =  (@Limit - @ReservationAccountQuantity_Year)
								SET @RejectRestrictionDescription = @Description 
								if @RejectRemainingAmount &amp;#60; 0 
								   SET @RejectRemainingAmount = 0

								if @RejectRemainingAmount = 0
									Set @RejectReasonErrorCode = 5083
								else
									Set @RejectReasonErrorCode = 5084
							end
						end

					END
				END
				ELSE
				BEGIN
					Set @PreventSale = 1
					Set @RejectType = 1
					if @RejectReasonErrorCode = 0
					begin
						SET @RejectRemainingAmount =  (@Limit - @ReservationAccountQuantity_Year)
						SET @RejectRestrictionDescription = @Description 
						if @RejectRemainingAmount &amp;#60; 0 
							SET @RejectRemainingAmount = 0

						if @RejectRemainingAmount = 0
							Set @RejectReasonErrorCode = 5085
						else
							Set @RejectReasonErrorCode = 5086
					end
				END
			END


		FETCH NEXT FROM Restriction_Cursor INTO
							@AccountRestrictionID, 
							@Description,
							@Limit,
							@PerDayLimit,
							@PerWeekLimit,
							@PerMonthLimit,
							@PerQuarterLimit,
							@PerSemiAnnualLimit,
							@PerYearLimit,
							@ReservationAccountQuantity_DayofYear,
							@ReservationAccountQuantity_WeekofYear,
							@ReservationAccountQuantity_MonthofYear,
							@ReservationAccountQuantity_QuarterofYear,
							@ReservationAccountQuantity_SemiAnnualofYear,
							@ReservationAccountQuantity_Year


		END	
	
		CLOSE Restriction_Cursor;
		DEALLOCATE Restriction_Cursor;
	END

RETURN
END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>F6FC5F50BBE44D22B6394E32FC04065B</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_GetLocksQtyExtended</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_GetLocksQtyExtended] 
@Context varchar(5),
@Key varchar(10),
@ExtendedKey varchar(40),
@Locked integer output,
@InUse integer output
AS
BEGIN
 select @Locked = IsNull(sum( Qty ),0)
 from SYS_LockQty with (READCOMMITTEDLOCK, ROWLOCK)
 where context = @context and [key] = @key and ExtendedKey &amp;#60;&amp;#62; @ExtendedKey

 select @InUse = IsNull(sum( Qty ),0)
 from SYS_LockQty with (READCOMMITTEDLOCK, ROWLOCK)
 where context = @context and [key] = @key and ExtendedKey = @ExtendedKey
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>24A861F6ED124025A65C0FF1610C895D</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE">
			<Name>otn_sp_HIL_CreateDDLCreateTable</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE Procedure dbo.otn_sp_HIL_CreateDDLCreateTable
AS 
BEGIN
	DECLARE @sql NVARCHAR(max),
			@SQL1 NVARCHAR(MAX)

	SET NOCOUNT ON  
	EXEC('if exists(select * from sys.triggers where name = ''ddl_trig_createTable'') DROP TRIGGER ddl_trig_createTable ON DATABASE;')

	SET @sql ='
	CREATE TRIGGER [ddl_trig_createTable]   
	ON DATABASE 
	FOR CREATE_TABLE   
	AS   
    
		DECLARE @TABLE_NAME varchar(255) 

		SET @TABLE_NAME =  EVENTDATA().value(''(/EVENT_INSTANCE/ObjectName)[1]'', ''nvarchar(100)'')

		Exec otn_sp_HIL_CreateHILTrigger @TABLE_NAME
	'
	
	EXEC(@sql)

END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>B3946243D5414350819ABD1547214A3D</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_HIL_CreateDDLDropTable</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE Procedure dbo.otn_sp_HIL_CreateDDLDropTable
AS 
BEGIN
	DECLARE @sql NVARCHAR(max),
			@SQL1 NVARCHAR(MAX)

	SET NOCOUNT ON  
	SET NOCOUNT ON  
	EXEC('if exists(select * from sys.triggers where name = ''ddl_trig_dropTable'') DROP TRIGGER ddl_trig_dropTable ON DATABASE;')

	SET @sql ='
				CREATE TRIGGER [ddl_trig_dropTable]   
				ON DATABASE 
				FOR DROP_TABLE   
				AS   
    
					DECLARE @TABLE_NAME varchar(255) 
					DECLARE @TID int  = 0


					select @TID = dbtableid
					  from cnf_dbtable
					where TableName = EVENTDATA().value(''(/EVENT_INSTANCE/ObjectName)[1]'', ''nvarchar(100)'')

					 if @TID &amp;#60;&amp;#62; 0
					 begin
					update cnf_dbtable
					set logged = 0,
						active = 0
					where DBTableId = @TID
	
					update cnf_dbcolumn
					   set Active = 0
					where DBTableId = @TID
					 end

				'
	
	EXEC(@sql)

END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>3C1BB58EAF194FCDBB07E340440746D3</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_HIL_CreateDDLTriggerAlterTable</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE Procedure dbo.otn_sp_HIL_CreateDDLTriggerAlterTable
AS 
BEGIN
	DECLARE @sql NVARCHAR(max),
			@SQL1 NVARCHAR(MAX)

	SET NOCOUNT ON  
	EXEC('if exists(select * from sys.triggers where name = ''ddl_trig_alterTable'') DROP TRIGGER ddl_trig_alterTable ON DATABASE;')

	SET @sql ='
	Create TRIGGER [ddl_trig_alterTable]   
	ON DATABASE   
	FOR ALTER_TABLE  
	AS  
	DECLARE @Data XML 
	DECLARE @TableName sysname 
	DECLARE @Command varchar(max)

	SET @Data = EventData()
	SET @TableName = @Data.value(''(/EVENT_INSTANCE/ObjectName)[1]'', ''nvarchar(200)'')
	SET @Command =  @Data.value(''(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]'', ''varchar(max)'')


	if CHARINDEX(''constraint all'' ,@Command) = 0
	begin

		INSERT INTO dbo.cnf_dbcolumn
				(DBTableId,
				ColumnName,
				Active,
				LOgged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)  
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				HT.Active,
				HT.logged,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t 
					INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
					INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
		WHERE SCHEMA_NAME(schema_id) = ''dbo''
			and t.name = @TableName
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn)


		update cnf_dbcolumn
		   set Active = 0,
			   logged = 0
		 where  ColumnName not in (SELECT c.name
									FROM sys.tables AS t 
												INNER JOIN sys.columns c				ON t.OBJECT_ID = c.OBJECT_ID 
												INNER JOIN cnf_dbtable HT               ON HT.TableName = t.name	
									WHERE SCHEMA_NAME(schema_id) = ''dbo''
										and t.name = @TableName
									)
		   and dbtableid in (select dbtableid from cnf_dbtable where tablename = @TableName)

		Exec otn_sp_HIL_CreateHILTrigger @TableName
	END
	'
	
	EXEC(@sql)

END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>56D33F07F74747C3B951667E34634D75</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_HIL_CreateHILTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>7</Version>
					<SQL>
CREATE Procedure [dbo].[otn_sp_HIL_CreateHILTrigger]
	@TABLE_NAME sysname
AS 
BEGIN
	DECLARE @Logged int
	set @Logged = 0

	IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME= 'DATA_HL_Master')
	BEGIN

		
		INSERT INTO dbo.cnf_dbtable
			   (TABLENAME,
				Active,
				Logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT @TABLE_NAME, 
				0,
				0,  
				1,
				1,
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
		where t.name = @TABLE_NAME
		  and t.name not in (select tablename from cnf_dbtable WITH(NOLOCK))	
		  	 
		INSERT INTO dbo.cnf_dbcolumn
			   (DBTableId,
				ColumnName,
				Active,
				logged,
				Last_UserId_Log,
				Last_WorkstationId_Log,
				Last_DateTime_Log)
		SELECT distinct HT.dbtableid AS tablesID, 
				c.name,
				0,
				0,
				1,
				1,  
				GetDate()
		FROM sys.tables AS t WITH(NOLOCK)
			INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
			INNER JOIN cnf_dbtable HT WITH(NOLOCK)              ON HT.TableName = t.name	

		WHERE SCHEMA_NAME(schema_id) = 'dbo'
			and t.name = @TABLE_NAME
			AND (cast(HT.dbTableID as Varchar(5000)) + c.Name) not in (select (cast(DBTableID as Varchar(5000)) + ColumnName) from cnf_dbcolumn WITH(NOLOCK))


--ACtivate logged and active
	Update cnf_dbtable
	   set Logged = 1,
	       Active = 1
	WHERE  TableName = @TABLE_NAME
	    AND TableName in (
	  						SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
						)
		AND TableName in (
							SELECT distinct t.name AS table_name
								FROM sys.tables AS t WITH(NOLOCK)
									INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
								WHERE c.name LIKE '%LAST%LOG'
									and SCHEMA_NAME(schema_id) = 'dbo'
									and ((T.name like '%ADM_%') or (t.name like '%CNF_%') or
											(t.name in ('DATA_Account', 'DATA_AccountFinancial', 'DATA_AccountRelationship', 'DATA_DmgData',
														'DATA_DmgData_Translate', 'DATA_Right')))
							)
		AND TableName NOT IN (SELECT table_name
							FROM information_schema.columns WITH(NOLOCK)
							where data_type in ('NTEXT', 'TEXT')
								AND TABLE_NAME in (
	  												SELECT distinct t.name AS table_name
														FROM sys.tables AS t WITH(NOLOCK)
															INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 	
														WHERE c.name LIKE '%LAST%LOG'
															and SCHEMA_NAME(schema_id) = 'dbo'
												))





	Update cnf_dbtable
	   set Logged = 0,
	       Active = 0
	WHERE  TableName = @TABLE_NAME
	  and TableName not in (select name
							  from sys.tables)


	Update cnf_dbcolumn
	  set Active = 1,
	      Logged = 1
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and ColumnName not in ('Last_UserID_log', 'Last_WorkstationID_LOG', 'Last_DateTime_Log', 'LastFire', 'UserLogID', 'LastLogin', 'LastUpdDate')
	  and columnName in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  

	Update cnf_dbcolumn
	  set Active = 0,
	      Logged = 0
	where DBTableid in (select dbtableid from cnf_dbtable WITH(NOLOCK) where active = 1 and logged = 1 and tablename = @TABLE_NAME)
	  and columnName not in (select c.name
							from sys.tables AS t WITH(NOLOCK)				
								INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
							where t.name = @TABLE_NAME)  


	Update cnf_dbtable
	   set Logged = 0,
		   Active = 0
	from cnf_dbtable
	where tablename = 'CNF_EnvelopeCapacity'
	  and tablename = @TABLE_NAME

	update cnf_dbtable
	   set Active = 0
	where tablename in ('CNF_Seat', 
						'CNF_SpaceStructure', 
						'SEAT_CNF_SpaceStructureSeat', 
						'CNF_SeatCategory'
					   )
	and tablename = @TABLE_NAME



	update cnf_dbcolumn
	   set Active = 0,
		   Logged = 0
	where dbtableid in (select dbtableid  
						  from cnf_dbtable
						 where TableName = 'CNF_Scheduler'
						)
	  and columnName = 'LastFire'



	update cnf_dbcolumn
	   set Active = 0,
		   Logged = 0
	where dbtableid in (select dbtableid  
						  from cnf_dbtable
						 where TableName = 'CNF_Workstation'
						)
	  and columnName = 'UserLogID'


	update cnf_dbcolumn
	   set Active = 0,
		   Logged = 0
	where dbtableid in (select dbtableid  
						  from cnf_dbtable
						 where TableName = 'CNF_User'
						)
	  and columnName = 'LastLogin'


	update cnf_dbcolumn
	   set Active = 0,
		   Logged = 0
	where dbtableid in (select dbtableid  
						  from cnf_dbtable
						 where TableName = 'CNF_Matrixcell'
						)
	  and columnName = 'LastUpdDate'




	select @Logged = Logged from cnf_dbtable WITH(NOLOCK) where tablename = @TABLE_NAME
	if @Logged = 1 
	BEGIN
		DECLARE @sql NVARCHAR(max),
				@SQL1 NVARCHAR(MAX)

		SET NOCOUNT ON  

		EXEC('IF OBJECT_ID (''' + @TABLE_NAME + '_CT'', ''TR'') IS NOT NULL DROP TRIGGER ' + @TABLE_NAME + '_CT')
		SELECT @sql = 
		'create trigger ' + @TABLE_NAME + '_CT on ' + @TABLE_NAME + ' FOR insert, update, delete
		as
		declare @TName varchar(128),
		        @TID nvarchar(max),
				@TLog int,  
				@PKC varchar(max),
				@PKV varchar(max),  
				@sql nvarchar(max), 
				@Type nvarchar(1),
				@MId nvarchar(max) = ''0'', 
				@ColumnID nvarchar(max) = ''0'',
				@CName varchar(128),
				@CValue1 nvarchar(max),
				@CValue2 nvarchar(max)

		if exists(select top 1 1 from cnf_system where ISNULL(BOSHistoryLogEnabled, 1) = 1 and offlinemode = 0)
		BEGIN
			select @TName = ''' + @TABLE_NAME + ''', @TID=dbtableid, @TLog = (case when Active = 1 and Logged = 1 then 1 else 0 end) from cnf_dbtable WITH(NOLOCK) where TableName=''' + @TABLE_NAME + '''

			if @TLog = 1
			begin
				if exists (select * from inserted)
				if exists (select * from deleted)
				select @Type = ''2''      --Update
				else
				select @Type = ''3''      --Insert
				else
				select @Type = ''1''      --Delete

				select * into #ins from inserted
				select * into #del from deleted

				select @PKC = coalesce(@PKC + '' and'', '' on'') + '' i.'' + c.COLUMN_NAME + '' = d.'' + c.COLUMN_NAME, @PKV = coalesce(@PKV+''+'','''') + ''convert(varchar(100), coalesce(i.'' + COLUMN_NAME + '',d.'' + COLUMN_NAME + ''))''
				  from INFORMATION_SCHEMA.TABLE_CONSTRAINTS p WITH(NOLOCK)
					   INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE c WITH(NOLOCK) on c.CONSTRAINT_NAME = p.CONSTRAINT_NAME and c.TABLE_NAME = p.TABLE_NAME
				 where p.TABLE_NAME=@TName and CONSTRAINT_TYPE=''PRIMARY KEY''

				DECLARE TCursor CURSOR LOCAL FOR
								select columnName,
									   dbcolumnid
								from(
								select CNF_DBColumn.ColumnName,
									CNF_DBColumn.DBColumnId,
									(case when cnf_dbcolumn.Active = 1 and cnf_dbcolumn.Logged = 1 then 1 else 0 end) Active
									from sys.tables AS t WITH(NOLOCK)				
										INNER JOIN sys.columns c WITH(NOLOCK)				ON t.OBJECT_ID = c.OBJECT_ID 
										INNER JOIN cnf_dbtable WITH(NOLOCK)					on cnf_dbtable.tablename = t.name
										INNER JOIN cnf_dbcolumn WITH(NOLOCK)				on cnf_dbcolumn.dbtableid = cnf_dbtable.dbtableid and cnf_dbcolumn.columnname = c.name
								where cnf_dbcolumn.dbtableid = @TID
								)p
								where Active = 1

				OPEN TCursor

				FETCH NEXT FROM TCursor INTO
					@CName, @ColumnID
					'
			SELECT @sql1 = '
				WHILE @@FETCH_STATUS = 0
				BEGIN

					set @sql =''Select @CValue1 = '' + @CName +'' from #ins ''
					EXEC sp_executesql @sql, N''@CValue1 nvarchar(max) OUTPUT'', @CValue1 OUTPUT

					set @sql =''Select @CValue2 = '' + @CName +'' from #del ''
					EXEC sp_executesql @sql, N''@CValue2 nvarchar(max) OUTPUT'', @CValue2 OUTPUT

					if ISNULL(@CValue1, ''&amp;#38;*()_2'') &amp;#60;&amp;#62; ISNULL(@CValue2, ''&amp;#38;*()_2'')
					begin
						if @MId = 0
						begin
							set @sql = ''insert DATA_HL_Master (OperationType, dbtableid, ReferenceId, UserId, WorkstationId, InsDateTime, DelDateTime)''
							set @sql = @sql + '' select '''''' + @Type + ''''''''												
							set @sql = @sql + '', '''''' + @TID + ''''''''		
							set @sql = @sql + '','' + @PKV		
							set @sql = @sql + '', i.Last_UserId_Log, i.Last_WorkstationId_Log, i.Last_DateTime_Log, getdate()''
							set @sql = @sql + '' from #ins i full outer join #del d ''
							set @sql = @sql + @PKC 
							set @sql = @sql + '' SELECT @MId = SCOPE_IDENTITY()''
							EXEC sp_executesql @sql, N''@MId nvarchar(max) OUTPUT'', @MId OUTPUT
						end
						if @Type &amp;#60;&amp;#62; ''3''
						BEGIN
							set @sql = ''insert data_HL_Detail (MasterId, OriginalValue, ModifiedValue, DBColumnID)''						
							set @sql = @sql + '' select convert(varchar(1000),'' + @MId + ''), convert(varchar(1000),d.'' + @CName + ''), convert(varchar(1000),i.'' + @CName + '')''				
							set @sql = @sql + '', convert(varchar(1000),'' + @ColumnID + '')  ''
							set @sql = @sql + '' from #ins i full outer join #del d '' + @PKC				
							EXEC sp_executesql @sql 																	
						END		
						
					END
					FETCH NEXT FROM TCursor INTO
					   @CName, @ColumnID
				END  --While loop
				CLOSE TCursor;
				DEALLOCATE TCursor; 
			END    --Table Check
		END	-- System Check
		'

	EXEC(@sql + @sql1)
	END	
  END
END</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>C72FD147FF6D45AFB71B69B3C2E4313A</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE"><Name>otn_sp_InsertAccountLimit</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>9</Version><SQL>Create Procedure [dbo].[otn_sp_InsertAccountLimit](@INS_SaleID  Integer,
						   @ShopCartType Integer   
												  )  

AS    
BEGIN
-- History Changes
-- 1) D.S. 29/05/2023 ISSUE IDBOS-7463 PGA - Commercial Family Change Account Delete Reservation
-- In Delete Reservation Section I added a SQL query in order to recover correctly the Ticket Owner that before was everytime zero. Search FIX001
-- 2) D.S. 28/06/2023 WEBPGA-320
--    Added parameter zero for calling otn_sp_CheckAccountRestrictions 
-- 3) S.C. 17/03/2025 OCP IDBOS-11305
--    In the parameter @ShopCartType = 2 if transaction is refund or partial refund



	Declare @NumberOfRestrictions Int = 0

	CREATE TABLE [#AccLimTemporaryTable](
			[ShopCartGuid] [varchar](38) NULL,
			[B2B_Owner] [int] NULL,
			[Billing_Owner] [int] NULL,
			[Reservation_Owner] [int] NULL,
			[Ticket_Owner] [int] NULL,
			[MatrixCellId] [int] NULL,
			[Quantity] [int] NULL,
			[PerformanceID] [int] NULL,
			[EventID] [int] NULL,
			[SaleID] [int] NULL,
			[SaleItemID] [int] NULL,
			[CheckforRestrictionOnly] [int] NULL
    )


	select @NumberOfRestrictions = Count(*)
		from CNF_AccountRestriction
		Where Enabled = 1

	if @NumberOfRestrictions &amp;#62; 0
	BEGIN
		DECLARE @status int = 0 
		DECLARE @DR_status int

		DECLARE @RestrictionType int	
			
		DECLARE @CheckforRestraintOnly int = 0


		SELECT @status=case when (select top 1 1 from data_transaction WITH(NOLOCK) where transactiontype = 5 and data_transaction.saleid = data_sale.saleid order by TransactionDate) = 1 then 0
												else 1
											end 
				FROM data_sale WITH(NOLOCK) 
		where saleid = @INS_SaleID
		  and StatusCode = 1


		if @status = 0 
		begin
			SELECT @DR_status = case when (select top 1 1 from data_transaction WITH(NOLOCK) where transactiontype = 5 and data_transaction.saleid = data_sale.saleid order by TransactionDate) = 1 then 1
							else 0
						end
			  FROM data_sale WITH(NOLOCK) 
		     where saleid = @INS_SaleID
		end


		if @status = 1
		begin
--Reservation Account
			Insert into #AccLimTemporaryTable
			select *
			from(
					select  data_sale.saleid,
							0 as B2B,
							0 as  Billing,
							ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
							0 TicketAccountID,
							data_saleitem.Matrixcellid,
							data_saleitem.Quantity,
							case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
														else 9999999
							end PerformanceID ,
							case when cnf_performance.Eventid is not null then cnf_performance.Eventid
														else  9999999
							end EventID,
							data_sale.saleid SaleID2,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																then ISNULL((select top 1 1
																				from data_transaction WITH(NOLOCK)
																				where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																					and data_transaction.saleid = data_sale.saleid), 0)
								when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																then 1
									else 0
								end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						LEFT JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

						where data_sale.saleid = @INS_SaleID
			)p
			where PerformanceID &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0

--B2B Account
			Insert into #AccLimTemporaryTable
			select *
			from (select  data_sale.saleid,
						ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
						0 as  Billing,
						0 as ReservationAccountID,
						0 TicketAccountID,
						data_saleitem.Matrixcellid,
						data_saleitem.Quantity,
						case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
													else 9999999
						end PerformanceID,
						case when cnf_performance.Eventid is not null then cnf_performance.Eventid
													else  9999999
						end EventID,
						data_sale.saleid SaleID2,
						data_saleitem.saleitemid,
						case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																	from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																		and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

															then ISNULL((select top 1 1
																			from data_transaction WITH(NOLOCK)
																			where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																				and data_transaction.saleid = data_sale.saleid), 0)
							when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																	from data_accountlimit WITH(NOLOCK)
																	where data_accountlimit.saleid = ODS.Saleid
																		and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

															then 1
								else 0
							end as UsageCheck

				from data_sale WITH(NOLOCK)
					LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
					INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
					LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
					LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
					left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
					left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

					where data_sale.saleid = @INS_SaleID
						and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0

--Billing Account
			Insert into #AccLimTemporaryTable
			select *
			from(
					select  data_sale.saleid,
							0 as B2B,
							ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
							0 as ReservationAccountID,
							0 TicketAccountID,
							data_saleitem.Matrixcellid,
							data_saleitem.Quantity,
							case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
														else 9999999
							end PerformanceID,
							case when cnf_performance.Eventid is not null then cnf_performance.Eventid
														else  9999999
							end EventID,
							data_sale.saleid Saleid2,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																then ISNULL((select top 1 1
																				from data_transaction WITH(NOLOCK)
																				where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																					and data_transaction.saleid = data_sale.saleid), 0)
								when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																then 1
									else 0
								end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

						where data_sale.saleid = @INS_SaleID
							and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0


--Ticket Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								0 as B2B,
								0 as BillingAccountId,
								0 as ReservationAccountID,
								DATA_SaleItem2Account.accountid TicketAccountID,
								data_saleitem.Matrixcellid,
								case when data_saleitem.Quantity &amp;#60; 0 then -1 else 1 end as Quantity,
								case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
															else 9999999
								end PerformanceID,
								case when cnf_performance.Eventid is not null then cnf_performance.Eventid
															else  9999999
								end EventID,
								data_sale.saleid SaleiD2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

							from data_sale WITH(NOLOCK)
								LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
								INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
								--LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
								INNER  JOIN DATA_SaleItem2Account WITH(NOLOCK)				on DATA_SaleItem2Account.saleitemid = data_saleitem.saleitemid
								LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
								LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
--								LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
								left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
								left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
--							and data_ticket.accountid is not null	
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0

--Reservation Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								0 as B2B,
								0 as  Billing,
								ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								0 PerformanceID,
								0 EventID,
								data_sale.saleid Saleid2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
			)p
			where Quantity &amp;#60;&amp;#62; 0

--B2B Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
								0 as  Billing,
								0 as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								0 PerformanceID,
								0 EventID,
								data_sale.saleid Saleid2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
			)p
			where Quantity &amp;#60;&amp;#62; 0

--Billing Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								0 as B2B,
								ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
								0 as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								0 PerformanceID,
								0 EventID,
								data_sale.saleid Saleid2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
			)p
			where Quantity &amp;#60;&amp;#62; 0

--Ticket Account
			Insert into #AccLimTemporaryTable
			select *
			from(
					select  data_sale.saleid,
							0 as B2B,
							0 as BillingAccountId,
							0 as ReservationAccountID,
							DATA_SaleItem2Account.accountid TicketAccountID,
							data_saleitem.Matrixcellid,
							case when data_saleitem.Quantity &amp;#60; 0 then -1 else 1 end as Quantity,
							0 PerformanceID,
							0 EventID,
							data_sale.saleid SAleid2,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																then ISNULL((select top 1 1
																				from data_transaction WITH(NOLOCK)
																				where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																					and data_transaction.saleid = data_sale.saleid), 0)
								when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																then 1
									else 0
								end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							INNER JOIN DATA_SaleItem2Account WITH(NOLOCK)				on DATA_SaleItem2Account.saleitemid = data_saleitem.saleitemid
							--LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
							--LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid


						where data_sale.saleid = @INS_SaleID
--							and data_ticket.accountid is not null	
			)p
			where Quantity &amp;#60;&amp;#62; 0
		END

--Reservation Deletes
		if @DR_status = 1
		begin
		--Reservation Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								0 as B2B,
								0 as  Billing,
								ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
															else 9999999
								end PerformanceID,
								case when cnf_performance.Eventid is not null then cnf_performance.Eventid
															else  9999999
								end EventID,
								data_sale.saleid Saleid2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
							LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and data_saleitem.quantity &amp;#60; 0
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0

--B2B Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
								0 as  Billing,
								0 as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
															else 9999999
								end PerformanceID,
								case when cnf_performance.Eventid is not null then cnf_performance.Eventid
															else  9999999
								end EventID,
								data_sale.saleid Saleid2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
							LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
								and data_saleitem.quantity &amp;#60; 0
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0

--Billing Account
			Insert into #AccLimTemporaryTable
			select *
			from(
					select  data_sale.saleid,
							0 as B2B,
							ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
							0 as ReservationAccountID,
							0 TicketAccountID,
							data_saleitem.Matrixcellid,
							data_saleitem.Quantity,
							case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
														else 9999999
							end PerformanceID,
							case when cnf_performance.Eventid is not null then cnf_performance.Eventid
														else  9999999
							end Eventid,
							data_sale.saleid Saleid2,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																then ISNULL((select top 1 1
																				from data_transaction WITH(NOLOCK)
																				where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																					and data_transaction.saleid = data_sale.saleid), 0)
								when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																then 1
									else 0
								end as UsageCheck

					from data_sale WITH(NOLOCK)
						LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
						LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
						LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
						left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
						left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

						where data_sale.saleid = @INS_SaleID
							and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
							and data_saleitem.quantity &amp;#60; 0
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0

--Ticket Account
			Insert into #AccLimTemporaryTable
			select *
			from(
					select  data_sale.saleid,
							0 as B2B,
							0 as BillingAccountId,
							0 as ReservationAccountID,
						    CASE WHEN (data_ticket.accountid is not null) THEN data_ticket.accountid --FIX001
							   ELSE (SELECT TOP 1
										AccountId 
										 FROM 
											DATA_Ticket TI_A WITH(NOLOCK)
											INNER JOIN DATA_SaleItem2Ticket S2T_A WITH(NOLOCK) ON (S2T_A.TicketId = TI_A.TicketId)
											INNER JOIN DATA_SaleItem SI_A WITH(NOLOCK) ON (SI_A.SaleItemId = S2T_A.SaleItemId)
										WHERE
											SI_A.SaleItemId = data_saleitem.OrigSaleItemId) 
							END as TicketAccountID,							
							data_saleitem.Matrixcellid,
							case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &amp;#60; 0 then -1 else 1 end
											else data_saleitem.Quantity
										end Quantity,
							case when cnf_performance.PerformanceID is not null then cnf_performance.PerformanceID
														else 9999999
							end PerformanceID,
							case when cnf_performance.Eventid is not null then cnf_performance.Eventid
														else  9999999
							end EventID,
							data_sale.saleid Saleid2,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																then ISNULL((select top 1 1
																				from data_transaction WITH(NOLOCK)
																				where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																					and data_transaction.saleid = data_sale.saleid), 0)
								when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																then 1
									else 0
								end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
							LEFT  JOIN data_saleitem2Performance WITH(NOLOCK)			on data_saleitem2performance.saleitemid = data_saleitem.saleitemid
							LEFT  JOIN cnf_performance WITH(NOLOCK)						on cnf_Performance.performanceid = data_saleitem2performance.performanceid
							LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

						where data_sale.saleid = @INS_SaleID
						    --FIX001
							and (data_ticket.accountid is not null or (
									SELECT TOP 1
										AccountId 
										 FROM 
											DATA_Ticket TI_A WITH(NOLOCK)
											INNER JOIN DATA_SaleItem2Ticket S2T_A WITH(NOLOCK) ON (S2T_A.TicketId = TI_A.TicketId)
											INNER JOIN DATA_SaleItem SI_A WITH(NOLOCK) ON (SI_A.SaleItemId = S2T_A.SaleItemId)
										WHERE
											SI_A.SaleItemId = data_saleitem.OrigSaleItemId) is not null )
							and data_saleitem.quantity &amp;#60; 0
			)p
			where Performanceid &amp;#60;&amp;#62; 9999999
			  and Quantity &amp;#60;&amp;#62; 0


--Reservation Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								0 as B2B,
								0 as  Billing,
								ISNULL(data_reservation.accountid, ODR.AccountID) as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								0 PerformanceID,
								0 EventID,
								data_sale.saleid SaleID2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and data_saleitem.quantity &amp;#60; 0
			)p
			where Quantity &amp;#60;&amp;#62; 0


--B2B Account
			Insert into #AccLimTemporaryTable
			Select *
			from(
						select  data_sale.saleid,
								ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) as B2B,
								0 as  Billing,
								0 as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								0 PerformanceID,
								0 EventID,
								data_sale.saleid SaleiD2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and ISNULL(data_reservation.B2BAccountID, ODR.B2BAccountID) is not null
								and data_saleitem.quantity &amp;#60; 0
			)p
			where Quantity &amp;#60;&amp;#62; 0

--Billing Account
			Insert into #AccLimTemporaryTable
			select *
			from(
						select  data_sale.saleid,
								0 as B2B,
								ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) as BillingAccountId,
								0 as ReservationAccountID,
								0 TicketAccountID,
								data_saleitem.Matrixcellid,
								data_saleitem.Quantity,
								0 PerformanceID,
								0 EventID,
								data_sale.saleid Saleid2,
								data_saleitem.saleitemid,
								case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																	then ISNULL((select top 1 1
																					from data_transaction WITH(NOLOCK)
																					where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																						and data_transaction.saleid = data_sale.saleid), 0)
									when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																			from data_accountlimit WITH(NOLOCK)
																			where data_accountlimit.saleid = ODS.Saleid
																				and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																	then 1
										else 0
									end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

							where data_sale.saleid = @INS_SaleID
								and ISNULL(data_reservation.BillingAccountId, ODR.BillingAccountId) is not null
								and data_saleitem.quantity &amp;#60; 0
			)p
			where Quantity &amp;#60;&amp;#62; 0			


--Ticket Account
			Insert into #AccLimTemporaryTable
			select *
			from(
					select  data_sale.saleid,
							0 as B2B,
							0 as BillingAccountId,
							0 as ReservationAccountID,
							data_ticket.accountid TicketAccountID,
							data_saleitem.Matrixcellid,
							case when data_ticket.ticketid is not null then case when data_saleitem.Quantity &amp;#60; 0 then -1 else 1 end
											else data_saleitem.Quantity
										end Quantity,
							0 PerformanceID,
							0 EventiD,
							data_sale.saleid Saleid2,
							data_saleitem.saleitemid,
							case when data_saleitem.Quantity &amp;#60; 0 and (select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId) = 1

																then ISNULL((select top 1 1
																				from data_transaction WITH(NOLOCK)
																				where data_transaction.transactiontype in (17, 18, 20, 22, 40, 47)
																					and data_transaction.saleid = data_sale.saleid), 0)
								when data_saleitem.Quantity &amp;#60; 0 and ISNULL((select top 1 1 
																		from data_accountlimit WITH(NOLOCK)
																		where data_accountlimit.saleid = ODS.Saleid
																			and data_accountlimit.saleitemid = data_saleitem.OrigSaleItemId), 0) &amp;#60;&amp;#62; 1

																then 1
									else 0
								end as UsageCheck

						from data_sale WITH(NOLOCK)
							LEFT JOIN data_reservation WITH(NOLOCK)						on data_reservation.saleid = data_sale.saleid
							INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
							LEFT  JOIN data_saleitem2ticket WITH(NOLOCK)				on data_saleitem2ticket.saleitemid = data_saleitem.saleitemid
							LEFT  JOIN data_ticket WITH(NOLOCK)							on data_ticket.ticketid = data_saleitem2ticket.ticketid
							left  join data_sale ODS WITH(NOLOCK)						on ODS.Saleid = data_saleitem.Basesaleid
							left  join data_reservation ODR WITH(NOLOCK)				on ODR.saleid = ODS.Saleid

						where data_sale.saleid = @INS_SaleID
							and data_ticket.accountid is not null	
							and data_saleitem.quantity &amp;#60; 0
			)p
			where Quantity &amp;#60;&amp;#62; 0


		end

		Insert into DATA_ShopCartItemLimit WITH(UPDLOCK)
			select *
			from #AccLimTemporaryTable

		drop table #AccLimTemporaryTable
		Exec otn_sp_CheckAccountRestrictions '0', @INS_SaleID, @ShopCartType

	end
RETURN
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>7A56E8D31C4D4C7BBC38278CD8F3E20B</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_Insert_Report_Categories</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>
Create Procedure [dbo].[otn_sp_Insert_Report_Categories](
			 @AddedSuccesfully int OUTPUT
	 )  	 
AS 
BEGIN


	Declare @DocTemplateName nvarchar(100)
	Declare @DocTemplateCode nvarchar(100)
	Declare @ParentCategoryID Integer
	Declare @ParentName nvarchar(100)
	Declare @RecursiveName nvarchar(100)
	Declare @AdminID Integer
	Declare @WorkstationID Integer
	Declare @DMGAK nvarchar(100)
	Declare @CategoryID Integer = 0             --     0 = Does not Exist   &amp;#62; 0 = Does Exist
	Declare @CategoryDescription nvarchar(100)            --     0 = Does not Exist   &amp;#62; 0 = Does Exist
	Declare @CategoryCount Integer = 0
	Declare @FMCat int = 0

	Declare @DocTemplateID Integer
	Declare @Category nvarchar(100)
	Declare @DmgCategoryID Integer
	set @AddedSuccesfully = 0   --False


	select @FMCat = dmgcategoryid from cnf_dmgcategory where dmgcategorycode = 'F &amp;#38; M_RPT'
	update cnf_doctemplate
	   set dmgcategoryid = null
	where dmgcategoryid = @FMCat
	delete from cnf_dmgcategory where dmgcategoryid = @FMCat

	select top 1 @WorkstationID = WorkstationID
	from cnf_workstation
	where enabled = 1

	select top 1 @AdminID = Userid
	from CNF_User
	where UserCode = 'Admin'

	select @ParentName = cnf_dmgcategory.Description + ' &amp;#187; '
		from cnf_dmgcategory
		where cnf_dmgcategory.DmgType = 11
		  and cnf_dmgcategory.DmgCategoryCode = 'DUMMY'

	select @ParentCategoryID = cnf_dmgcategory.DmgCategoryID
		from cnf_dmgcategory
		where cnf_dmgcategory.DmgType = 11
		  and cnf_dmgcategory.DmgCategoryCode = 'DUMMY'

	if @ParentCategoryID is not null 
	BEGIN
				Declare @Temp table (  DocTemplateCode nvarchar(10),
									   DocTemplateName nvarchar(100)
									)

				INSERT INTO @Temp (
									DocTemplateCode,
									DocTemplateName 
								  ) 
						select Distinct SUBSTRING(DocTemplateName, 1, 5) + 
										case when LEN(SUBSTRING(DocTemplateName, 1, (CHARINDEX('-', DocTemplateName) - 2))) &amp;#62; 6 then SUBSTRING(DocTemplateName, (CHARINDEX('-', DocTemplateName) - 2), 1) 
											 else ''
										end + '_RPT' as CategoryCode,
										SUBSTRING(DocTemplateName, 1, (CHARINDEX('-', DocTemplateName) - 2)) as CategoryDescription

						from  cnf_doctemplate
						where cnf_doctemplate.doccntxtype = 5
						  and cnf_doctemplate.systemTemplate = 1
						  and cnf_doctemplate.DocTemplateType = 8
									  and CHARINDEX('-', DocTemplateName) &amp;#60;&amp;#62; 0
                          
                          
				Declare @RPTTemp table (  DocTemplateID Integer, 
										  Category nvarchar(100)
									   )

				INSERT INTO @RPTTemp (
									DocTemplateID, 
									Category
								  ) 
						select DocTemplateID,  
							   SUBSTRING(DocTemplateName, 1, (CHARINDEX('-', DocTemplateName) - 2)) as Category
						from cnf_doctemplate
						where cnf_doctemplate.doccntxtype = 5
						  and cnf_doctemplate.systemTemplate = 1
						  and cnf_doctemplate.DocTemplateType = 8
						  and cnf_doctemplate.DmgCategoryID is null
									  and CHARINDEX('-', DocTemplateName) &amp;#60;&amp;#62; 0
                          
						Order by cnf_doctemplate.doctemplatename

				DECLARE Category_Cursor CURSOR LOCAL FOR
							select * from @Temp

				OPEN Category_Cursor

				FETCH NEXT FROM Category_Cursor INTO	@DocTemplateCode, @DocTemplateName

				WHILE @@FETCH_STATUS = 0
				BEGIN
					Set @CategoryID = 0

					Set @RecursiveName = @ParentName + @DocTemplateName

					select @CategoryID = cnf_dmgcategory.DmgCategoryID
					  from cnf_dmgcategory
					 where cnf_dmgcategory.DmgType = 11
					  and cnf_dmgcategory.Description = @DocTemplateName
					  and cnf_dmgcategory.SystemCategory = 1


					IF @CategoryID = 0 
					Begin

						INSERT INTO [dbo].[CNF_DmgCategory]
								(
									 [DmgParentId]
									,[DmgCategoryAK]
									,[DmgCategoryCode]
									,[Description]
									,[DmgType]
									,[RecursiveName]
									,[DmgSubType]
									,[LinkedDmgCat]
									,[Last_UserId_Log]
									,[Last_WorkstationId_Log]
									,[Last_DateTime_Log]
									,[SystemCategory]
								)
						 VALUES
							   (
									@ParentCategoryID
								   ,@DocTemplateCode
								   ,@DocTemplateCode
								   ,@DocTemplateName
								   ,11
								   ,@RecursiveName
								   ,null
								   ,null
								   ,@AdminID
								   ,@WorkstationID
								   ,GetDate()
								   ,1
							   )


					End
					FETCH NEXT FROM Category_Cursor INTO	@DocTemplateCode, @DocTemplateName

				end
	
				CLOSE Category_Cursor;
				DEALLOCATE Category_Cursor;

				select top 1 @DMGAK = SiteCode + '.DMGCAT'
				  from CNF_Site
				order by SiteID

				Declare @RPTTemp1 table (
				                          dmgcategoryID Integer
									   )
			
				INSERT INTO @RPTTemp1 (
									dmgcategoryID
								  ) 
							select dmgcategoryID
							  from cnf_dmgcategory
							  where dmgtype = 11
							    and DMGParentID is not null
								and systemcategory = 1

				DECLARE Category_Cursor CURSOR LOCAL FOR
							select * from @RPTTemp1

				OPEN Category_Cursor

				FETCH NEXT FROM Category_Cursor INTO @CategoryID

				WHILE @@FETCH_STATUS = 0
				BEGIN
					select @CategoryCount = (Counter + 1)
					  from data_counter
					 where countertype = 9
					
					update cnf_dmgcategory
					   set DMGCategoryAK = @DMGAK + cast(@CategoryCount as varchar(max))
					 where dmgcategoryID = @CategoryID

					Update data_counter
						set Counter = @CategoryCount
					 where countertype = 9 


					FETCH NEXT FROM Category_Cursor INTO @CategoryID
				END
	
				CLOSE Category_Cursor;
				DEALLOCATE Category_Cursor;
 

				set @AddedSuccesfully = 1
	end
	IF @AddedSuccesfully = 1
	BEGIN
		
		DECLARE Category_Cursor CURSOR LOCAL FOR
							select dmgcategoryID, Description
							  from cnf_dmgcategory
							  where dmgtype = 11
							    and DMGParentID is not null
								and systemcategory = 1

		OPEN Category_Cursor

		FETCH NEXT FROM Category_Cursor INTO @CategoryID, @CategoryDescription

		WHILE @@FETCH_STATUS = 0
		BEGIN
			
			Update CNF_DocTemplate
			  set dmgcategoryID = @CategoryID
			where dmgcategoryID is null
			  and systemtemplate = 1
			  and DocCntxType = 5
			  and DocTemplateType = 8
			  and SUBSTRING(DocTemplateName, 1, (CHARINDEX('-', DocTemplateName) - 2)) = @CategoryDescription



			FETCH NEXT FROM Category_Cursor INTO @CategoryID, @CategoryDescription
		END
		CLOSE Category_Cursor;
		DEALLOCATE Category_Cursor;



	END

	select @AddedSuccesfully as AddedSuccesfully
End</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>905DD58F62574783B658433B786A57DE</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_DeleteUnbalanced</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>3</Version><SQL>create Procedure [dbo].[otn_sp_RR_DeleteUnbalanced] 
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
SET NOCOUNT ON

update rr_data_revenue
   set rr_data_revenue.OOBflag = 1
where TransactionId in (
select TransactionId
from(
		select p1.transactionid,
	   data_transaction.saleid,
	   transactiontype,

	   ftransactiondate,
       round(sum(balance), 2) balance,
	   transactionstatus

from(
				select  Siteid, sitename, RevenueRecognitionDataid,
						RevenueRecognitionRuleid, 
						coaAccountid, 
						rrcode,
						matrixcellid,
						ExternalCode,
      						case when transactionid is not null then 'Tran'
							 else 'Tick'
						end as Type, 
						ISNULL(transactionid, 0) as transactionid,
						coaaccountcode, 
						Debit as debit,
						(Credit) as Credit,
						fcalcdate, 
						RemaningValues,
						AccountingType,
						description,
						ticketid,
						(ISNULL(Debit, 0) - ISNULL(credit, 0)) Balance
				from(
				select rr_data_revenue.Siteid,
					   cnf_site.sitename,
					   RevenueRecognitionDataid,
						   rr_data_revenue.RevenueRecognitionRuleid, 
						   rr_data_revenue.coaAccountid, 
						   RR_CNF_RevenueRecognitionRule.code as rrcode, 
						   rr_data_revenue.transactionid,  
						   COA_CNF_Account.code as coaaccountcode,
						   case when rr_data_revenue.AccountingType = 1 then Convert(decimal(19,4), revenueamount)
								else null
							end Debit,
						   case when rr_data_revenue.AccountingType = 2 then Convert(decimal(19,4), revenueamount)
								else null
							end Credit,
						   fcalcdate, 
						   matrixsheetid, 
						   matrixcellid, 
						   saleitemid, 
						   RemaningValues,
						   COA_CNF_Account.ExternalCode,
						   COA_CNF_AccountConfig.AccountingType,
						   ticketid,
								   CASE when rr_data_revenue.RRCalcTypeTrigger = 2 then 'On Ticket Usage'
										when rr_data_revenue.RRCalcTypeTrigger = 3 then 'Ticket Expiration'
										when rr_data_revenue.RRCalcTypeTrigger = 4 then 'Time Period'
										else CNF_Lookup.Description   
									end description		   
	   
					from rr_data_revenue WITH(NOLOCK)
						LEFT JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK) on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_data_revenue.RevenueRecognitionRuleId 
						LEFT JOIN COA_CNF_AccountConfig	WITH(NOLOCK)	     on COA_CNF_AccountConfig.COAAccountConfigId = rr_data_revenue.COAAccountConfigId
						LEFT JOIN COA_CNF_Account WITH(NOLOCK)				 on COA_CNF_Account.COAAccountId = rr_data_revenue.COAAccountId
						left JOIN DATA_Transaction WITH(NOLOCK)				 on data_transaction.transactionid = rr_data_revenue.transactionid
						left join CNF_LookUp	WITH(NOLOCK)				 on cnf_lookup.itemid = data_transaction.transactiontype and cnf_lookup.lookupTableid = 3
						LEFT JOIN CNF_SITE WITH(NOLOCK)                      on cnf_site.siteid = rr_data_revenue.siteid	
	  
				)p
			)p1
			inner join data_transaction					on data_transaction.transactionid = p1.transactionid
			where FCalcDate = @BatchDate
			group by p1.transactionid,
					 transactiontype,
					 transactionstatus,
					 ftransactiondate,
					 data_transaction.userid,
		 				   data_transaction.saleid

			having round(sum(balance), 2) &amp;#60;&amp;#62; 0

		)p6
		
)
end
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>E05FB8713668400981C4C4897FF46020</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_BalanceVoidedTickets</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>8</Version><SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_BalanceVoidedTickets]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

declare @RevenueRecognitionRuleId int 
declare @COAAccountType int

select @RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
from RR_CNF_RevenueRecognitionRule
where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 22


if @RevenueRecognitionRuleId is not null
begin
	INSERT INTO dbo.rr_data_revenue
				   (COAAccountId,
					RevenueRecognitionRuleId,
					RRCalcTypeWhere,
					RRCalcTypeMethod,
					COAAccountConfigId,
					COAAccountType,
					TransactionId,
					SaleId,
					SaleItemId,
					MatrixCellId,
					UsageId,
					TicketId,
					SiteId,
					LocationId,
					OperatingAreaId,
					WorkstationId,
					UserGroupId,
					UserId,
					FCalcDate,
					Quantity,
					UnitAmount,
					GrossAmount,
					NetAmount,
					Price,
					Percentage,
					RemaningValues,
					RevenueAmount,
					RRCalcTypeTrigger,
					RRPercentage,
					RRDays,
					MatrixSheetId,
					AccountingType,
					AttributeIDs,
					SaleItemTaxId,
					SaleItemRuleID,
					Encoded,
					JournalEntryByAccount,
					LinkedJournalAccountId,
					TimePeriod,
					Forecasted,
					OOBflag)

		select  
				    COA_CNF_Account.COAAccountId,
					RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
					COA_CNF_AccountConfig.COAAccountConfigId,
					COA_CNF_Account.COAAccountTypeId COAAccountType,
					RR_DATA_Revenue.TransactionId,
					RR_DATA_Revenue.SaleId,
					RR_DATA_Revenue.SaleItemId,
					RR_DATA_Revenue.MatrixCellId,
					RR_DATA_Revenue.UsageId,
					RR_DATA_Revenue.TicketId,
					RR_DATA_Revenue.SiteId,
					RR_DATA_Revenue.LocationId,
					RR_DATA_Revenue.OperatingAreaId,
					RR_DATA_Revenue.WorkstationId,
					RR_DATA_Revenue.UserGroupId,
					RR_DATA_Revenue.UserId,
					@BatchDate FcalcDate,
					RR_DATA_Revenue.Quantity,
					RR_DATA_Revenue.UnitAmount,
					RR_DATA_Revenue.GrossAmount,
					RR_DATA_Revenue.NetAmount,
					RR_DATA_Revenue.Price,
					RR_DATA_Revenue.Percentage,
					RR_DATA_Revenue.RemaningValues,
					RR_DATA_Revenue.RevenueAmount,			
					RR_DATA_Revenue.RRCalcTypeTrigger,
					RR_DATA_Revenue.RRPercentage,
					RR_DATA_Revenue.RRDays,
					RR_DATA_Revenue.MatrixSheetId,
					2 AccountingType,
					RR_DATA_Revenue.AttributeIDs,
					RR_DATA_Revenue.SaleItemTaxId,
					RR_DATA_Revenue.SaleItemRuleID,
					RR_DATA_Revenue.Encoded,
					0 JournalEntryByAccount,
					RR_DATA_Revenue.LinkedJournalAccountId,
					RR_DATA_Revenue.TimePeriod,
					RR_DATA_Revenue.Forecasted,
					rr_data_revenue.OOBflag

		from rr_data_revenue WITH(NOLOCK)
			inner join data_saleitem WITH(NOLOCK)							on data_saleitem.saleitemid = rr_data_revenue.saleitemid
			cross join RR_CNF_RevenueRecognitionRule
			 left join COA_CNF_AccountConfig WITH(NOLOCK)					on COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleID
			 left join COA_CNF_Account WITH(NOLOCK)							on 	COA_CNF_Account.coaaccountid = COA_CNF_Accountconfig.coaaccountid	
			 left join data_ticket WITH(NOLOCK)								on data_ticket.ticketid = rr_data_revenue.ticketid
		
		where data_saleitem.ProductType = 1
		and ((rr_data_revenue.ticketid is null) or (data_ticket.voidtype in (104, 125)))
		and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = @RevenueRecognitionRuleId
		and rr_data_revenue.RRCalcTypeTrigger = 1
		and rr_data_revenue.AccountingType = 2
		and rr_data_revenue.COAAccountId in (1)
		and rr_data_revenue.SaleItemTaxId is null
		and rr_data_revenue.SaleItemRuleID is null
		and rr_data_revenue.FCalcDate = @batchdate
		and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)


end

END



</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>30CB58773BF548368A9ACCE5DF2593D4</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_batchJob</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>136</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_batchJob] 
	@FromDate Date,
	@ToDate Date
AS 
BEGIN
SET NOCOUNT ON
	select'Begin Batch', getdate()

	declare @CurrentdatabaseName varchar(100) 
	declare @CurrentHostName varchar(100)

	delete from RR_DATA_Revenue
	where fcalcdate between @FromDate and @ToDate
		and ISNULL(JournalEntryByAccount, 0) = 0

	delete from RR_DATA_Revenue
	where ISNULL(forecasted, 0) = 1

	delete from RR_DATA_Revenue_totals
	 where fcalcdate between @FromDate and @ToDate

	Declare @BatchDate Date
	Declare @RRTransDateType Integer

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer
	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer

	Declare @TaxRRRId Integer
	Declare @TaxCOAAccountId Integer
	Declare @TaxRRCalcTypeTrigger Integer
	Declare @TaxRRCalcTypeWhere Integer
	Declare @TaxRRCalcTypeMethod Integer
	Declare @TaxCOAAccountConfigId Integer
	Declare @TaxCOAAccountTypeId Integer
	Declare @TaxPercentage float
	Declare @TaxDays Integer
	Declare @TaxPrice float
	Declare @TaxCOAAccount_Percentage Float
	Declare @TaxRemainingValues Integer
	Declare @TaxRRCOAAccountingType Integer
	Declare @TaxAccountingType Integer

	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	Declare @DepositRRRId Integer
	Declare @DepositCOAAccountId Integer
	Declare @DepositRRCalcTypeTrigger Integer
	Declare @DepositRRCalcTypeWhere Integer
	Declare @DepositRRCalcTypeMethod Integer
	Declare @DepositCOAAccountConfigId Integer
	Declare @DepositCOAAccountTypeId Integer
	Declare @DepositPercentage float
	Declare @DepositDays Integer
	Declare @DepositPrice float
	Declare @DepositCOAAccount_Percentage Float
	Declare @DepositRemainingValues Integer
	Declare @DepositRRCOAAccountingType Integer
	Declare @DepositAccountingType Integer


	Declare @TicketRRRId Integer
	Declare @TicketCOAAccountId Integer
	Declare @TicketRRCalcTypeTrigger Integer
	Declare @TicketRRCalcTypeWhere Integer
	Declare @TicketRRCalcTypeMethod Integer
	Declare @TicketCOAAccountConfigId Integer
	Declare @TicketCOAAccountTypeId Integer
	Declare @TicketPercentage float
	Declare @TicketDays Integer
	Declare @TicketPrice float
	Declare @TicketCOAAccount_Percentage Float
	Declare @TicketRemainingValues Integer
	Declare @TicketRRCOAAccountingType Integer
	Declare @TicketAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select @TicketRRRId = RevenueRecognitionRuleId
	  from RR_CNF_RevenueRecognitionRule
	  where rrcalctypeTrigger = 21


	select @RRTransDateType = RRTransDateType
      from cnf_system

	select TOP 1	@DepositRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@DepositRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@DepositRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@DepositRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@DepositCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@DepositCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@DepositCOAAccountId = coa_cnf_account.COAAccountId,
					@DepositPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@DepositDays = RR_CNF_RevenueRecognitionRule.Days,
					@DepositPrice = COA_CNF_AccountConfig.Price,
					@DepositCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@DepositRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@DepositRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 5
	  and RR_CNF_RevenueRecognitionRule.Enabled = 1


	if @DepositRRRId is null
	Begin
				select TOP 1	@DepositRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
									@DepositRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									@DepositRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									@DepositRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									@DepositCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
									@DepositCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
									@DepositCOAAccountId = coa_cnf_account.COAAccountId,
									@DepositPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
									@DepositDays = RR_CNF_RevenueRecognitionRule.Days,
									@DepositPrice = COA_CNF_AccountConfig.Price,
									@DepositCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
									@DepositRemainingValues = COA_CNF_AccountConfig.RemainingValues,
									@DepositRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
					from coa_cnf_account WITH(NOLOCK)
						INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
						INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
						INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
					where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 1
					  and RR_CNF_RevenueRecognitionRule.Enabled = 1





	END
	select TOP 1	@SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
					@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
					@SuspendPrice = COA_CNF_AccountConfig.Price,
					@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	select TOP 1	@PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
					@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
					@PaymentPrice = COA_CNF_AccountConfig.Price,
					@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @ACCPaymentMethod

	select TOP 1	@TaxRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@TaxRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@TaxRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@TaxRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@TaxCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@TaxCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@TaxCOAAccountId = coa_cnf_account.COAAccountId,
					@TaxPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@TaxDays = RR_CNF_RevenueRecognitionRule.Days,
					@TaxPrice = COA_CNF_AccountConfig.Price,
					@TaxCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@TaxRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@TaxRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @TaxAccountID


	select TOP 1	@DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
					@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
					@DiscountPrice = COA_CNF_AccountConfig.Price,
					@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID


select TOP 1	    @TicketRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@TicketRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@TicketRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@TicketRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@TicketCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@TicketCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@TicketCOAAccountId = coa_cnf_account.COAAccountId,
					@TicketPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@TicketDays = RR_CNF_RevenueRecognitionRule.Days,
					@TicketPrice = COA_CNF_AccountConfig.Price,
					@TicketCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@TicketRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@TicketRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	
	where RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = @TicketRRRId
	  and coa_cnf_account.Enabled = 1
	  and COA_CNF_AccountConfig.Enabled = 1


	Declare @Temp table (BatchDate date)
	
	INSERT INTO @Temp (
						BatchDate
					  ) 	
	select distinct date
		  from(
					SELECT  TOP (DATEDIFF(DAY, @FromDate, @ToDate) + 1) 
						Date = DATEADD(DAY, ROW_NUMBER() OVER(ORDER BY a.object_id) - 1, @FromDate)
						FROM    sys.all_objects a
								CROSS JOIN sys.all_objects b
			)p
			left join DATA_Transaction WITH(NOLOCK)				ON p.Date = DATA_Transaction.FTransactionDate


	DECLARE date_Cursor CURSOR LOCAL FOR
				select * from @Temp order by 1

	OPEN date_Cursor

	FETCH NEXT FROM date_Cursor INTO
		@BatchDate

	WHILE @@FETCH_STATUS = 0
	BEGIN

	    if @TicketCOAAccountId is not null 
		begin
		        --Tickets that are paid for but NOT encoded.
						INSERT INTO [dbo].[RR_DATA_Revenue]
										([COAAccountId]
										,[RevenueRecognitionRuleId]
										,[RRCalcTypeWhere]
										,[RRCalcTypeMethod]
										,[COAAccountConfigId]
										,[COAAccountType]
										,[TransactionId]
										,[SaleId]
										,[SaleItemId]
										,[MatrixCellId]
										,[MatrixSheetID]
										,[SiteId]
										,[TicketID]
										,[OperatingAreaId]
										,[WorkstationId]
										,[UserGroupId]
										,[UserId]
										,[FCalcDate]
										,[Quantity]
										,[UnitAmount]
										,[GrossAmount]
										,[NetAmount]
										,[Price]
										,[Percentage]
										,[RemaningValues]
										,[RevenueAmount]
										,[AccountingType]
										,[RRCalcTypeTrigger]
										,[RRPercentage]
										,[AttributeIDS])
									select distinct *
									from (
											 select @TicketCOAAccountId COAID,
													@TicketRRRId RRID,
													@TicketRRCalcTypeWhere RRWHERE,
													@TicketRRCalcTypeMethod RRMETHOD,
													@TicketCOAAccountConfigId RRCONFIG,
													@TicketCOAAccountTypeId COATYPE,
													data_transaction.transactionid, 
													data_transaction.saleid,
													DATA_SaleItem.saleitemid,
													DATA_SaleItem.Matrixcellid,
													CNF_MatrixCell.MatrixSheetid,
													data_transaction.Siteid,
													null TicketID,
													data_transaction.OperatingAreaId,
													data_transaction.Workstationid,
													data_transaction.UserGroupid,
													data_transaction.UserId,
													@BatchDate BatchDate,
													data_saleitem.quantity,
													DATA_SaleItem.UnitPrice,
													ISNULL(DATA_SaleItem.totalamount, 0) Grossamount,
													ISNULL(DATA_SaleItem.totalamount - DATA_SaleItem.totaltaxes, 0) NetAmount,
													@TicketPrice Price,
													@TicketCOAAccount_Percentage  Percentage,
													@TicketRemainingValues RValues,				
													ABS((DATA_SaleItem.UnitrawPrice * data_saleitem.quantity) - case when data_saleitem.ProductTaxType = 1 then (data_saleitem.unittaxes * data_saleitem.quantity)
													                                                                 else 0
																												 end) as revenueamount,
													case when data_saleitem.quantity &amp;#60; 0 then 1
														 else @SuspendRRCOAAccountingType 
													  end Accountingtype,
													@TicketRRCalcTypeTrigger  RTRIGGER,
													@TicketPercentage PERC,
													CNF_AttributeSet.Attributeids
	   
											from DATA_Sale WITH(NOLOCK)
												inner join data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId =  DATA_Sale.PaidTransactionId
												left join data_transaction Encd_Trans WITH(NOLOCK)	 on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
												left join DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
												left join CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
												left join CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
												left join CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

											WHERE DATA_Sale.Paid = 1
											  and ((DATA_Sale.Encoded = 0) or
											         ((data_sale.PaidTransactionId &amp;#60;&amp;#62; data_sale.EncodedTransactionId)  and 
													   (Encd_Trans.FTransactionDate &amp;#60;&amp;#62; data_transaction.FTransactionDate))													 													 
													 )
											  and DATA_Sale.saleid in (select saleid from data_saleitem where producttype = 1 and data_saleitem.saleid = data_sale.saleid)
											  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
											  and ((data_transaction.transactiontype in (7, 9, 14, 16, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7, 9, 14, 16, 123))))
											  and DATA_SaleItem.Quantity &amp;#62; 0
											  and DATA_SaleItem.UnitRecharge = 0
											  and DATA_Transaction.TransactionStatus not in (40)
											  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
												OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))

											UNION ALL

											 select @TicketCOAAccountId COAID,
													@TicketRRRId RRID,
													@TicketRRCalcTypeWhere RRWHERE,
													@TicketRRCalcTypeMethod RRMETHOD,
													@TicketCOAAccountConfigId RRCONFIG,
													@TicketCOAAccountTypeId COATYPE,
													data_transaction.transactionid, 
													data_transaction.saleid,
													DATA_SaleItem.saleitemid,
													DATA_SaleItem.Matrixcellid,
													CNF_MatrixCell.MatrixSheetid,
													data_transaction.Siteid,
													null TicketID,
													data_transaction.OperatingAreaId,
													data_transaction.Workstationid,
													data_transaction.UserGroupid,
													data_transaction.UserId,
													@BatchDate BatchDate,
													data_saleitem.quantity,
													DATA_SaleItem.UnitPrice,
													ISNULL(DATA_SaleItem.totalamount, 0) Grossamount,
													ISNULL(DATA_SaleItem.totalamount - DATA_SaleItem.totaltaxes, 0) NetAmount,
													@TicketPrice Price,
													@TicketCOAAccount_Percentage  Percentage,
													@TicketRemainingValues RValues,				
													ABS((DATA_SaleItem.UnitrawPrice * data_saleitem.quantity) - case when data_saleitem.ProductTaxType = 1 then (data_saleitem.unittaxes * data_saleitem.quantity)
													                                                                 else 0
																												 end) as revenueamount,
													case when data_saleitem.quantity &amp;#60; 0 then 1
														 else @SuspendRRCOAAccountingType 
													  end Accountingtype,
													@TicketRRCalcTypeTrigger  RTRIGGER,
													@TicketPercentage PERC,
													CNF_AttributeSet.Attributeids
	   
											from DATA_Sale WITH(NOLOCK)
												inner join data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId =  ISNULL(DATA_Sale.voidTransactionId, DATA_Sale.paidTransactionId)												
												left join data_transaction Encd_Trans WITH(NOLOCK)	 on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
												left join DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
												left join CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
												left join CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
												left join CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

											WHERE DATA_Sale.Paid = 1
											  and ((DATA_Sale.Encoded = 0) or
											         ((data_sale.PaidTransactionId &amp;#60;&amp;#62; data_sale.EncodedTransactionId)  and 
													   (Encd_Trans.FTransactionDate &amp;#60;&amp;#62; data_transaction.FTransactionDate))													 													 
													 )
											  and DATA_Sale.saleid in (select saleid from data_saleitem where producttype = 1 and data_saleitem.saleid = data_sale.saleid)
											  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
											  and ((data_transaction.transactiontype in (5, 7, 30)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (5, 7, 30))))
											  and DATA_SaleItem.Quantity &amp;#60; 0
											  and DATA_SaleItem.UnitRecharge = 0
											  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
												OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			union all


						select @TicketCOAAccountId COAID,
								@TicketRRRId RRID,
								@TicketRRCalcTypeWhere RRWHERE,
								@TicketRRCalcTypeMethod RRMETHOD,
								@TicketCOAAccountConfigId RRCONFIG,
								@TicketCOAAccountTypeId COATYPE,
								data_transaction.transactionid, 
								data_transaction.saleid,
								DATA_SaleItem.saleitemid,
								DATA_SaleItem.Matrixcellid,
								CNF_MatrixCell.MatrixSheetid,
								data_transaction.Siteid,
								null TicketID,
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate BatchDate,
								data_saleitem.quantity,
								DATA_SaleItem.UnitPrice,
								ISNULL(DATA_SaleItem.unitrecharge, 0) Grossamount,
								ISNULL(DATA_SaleItem.unitrecharge - DATA_SaleItem.totaltaxes, 0) NetAmount,
								@TicketPrice Price,
								@TicketCOAAccount_Percentage  Percentage,
								@TicketRemainingValues RValues,				
								ABS((DATA_SaleItem.unitrecharge * data_saleitem.quantity) - case when data_saleitem.ProductTaxType = 1 then (data_saleitem.unitrecharge * data_saleitem.quantity)
													                                                else 0
																								end) as revenueamount,
								case when data_saleitem.quantity &amp;#60; 0 then 1
										else @SuspendRRCOAAccountingType 
									end Accountingtype,
								@TicketRRCalcTypeTrigger  RTRIGGER,
								@TicketPercentage PERC,
								CNF_AttributeSet.Attributeids
	   
							from DATA_Sale WITH(NOLOCK)
								inner JOIN data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
								left join data_transaction Encd_Trans WITH(NOLOCK)	 on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
								inner JOIN DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
								inner JOIN CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
								inner JOIN CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								inner JOIN CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId

					
							WHERE DATA_Sale.Paid = 1
									and ((DATA_Sale.Encoded = 0) or
											((data_sale.PaidTransactionId &amp;#60;&amp;#62; data_sale.EncodedTransactionId)  and 
											(Encd_Trans.FTransactionDate &amp;#60;&amp;#62; data_transaction.FTransactionDate))													 													 
											)
									and DATA_Sale.saleid in (select saleid from data_saleitem where producttype = 1 and data_saleitem.saleid = data_sale.saleid)
									and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
									and ((data_transaction.transactiontype in (7, 9, 14, 16, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7, 9, 14, 16, 123))))
									and DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; 0
									and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))


							)p
							where revenueamount &amp;#60;&amp;#62; 0

			end

-- Unit Recharge ONLY
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[TicketID]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
					select distinct *
					from (
						select		@SuspendCOAAccountId COAID,
									@SuspendRRRId RRID,
									@SuspendRRCalcTypeWhere RRWHERE,
									@SuspendRRCalcTypeMethod RRMETHOD,
									@SuspendCOAAccountConfigId RRCONFIG,
									@SuspendCOAAccountTypeId COATYPE,
									data_transaction.transactionid, 
									data_transaction.saleid,
									DATA_SaleItem.saleitemid,
									DATA_SaleItem.Matrixcellid,
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									p.ticketid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate BatchDate,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
									ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
									ISNULL(DATA_SaleItem.UnitRecharge, 0) charge,
									ISNULL(DATA_SaleItem.UnitRecharge, 0) charge2,
									@SuspendPrice Price,
									@SuspendCOAAccount_Percentage  Percentage,
									@SuspendRemainingValues RValues,				
									ABS(case when p.TicketID is not null then ABS(ISNULL(DATA_SaleItem.UnitRecharge, 0)) 
									     else ABS(ISNULL(DATA_SaleItem.UnitRecharge, 0)) * data_saleitem.quantity
									 end) as revenueamount,
									case when data_saleitem.quantity &amp;#60; 0 then 1
									     else @SuspendRRCOAAccountingType 
									  end Accountingtype,
									@SuspendRRCalcTypeTrigger  RTRIGGER,
									@SuspendPercentage PERC,
									1 rrdays,
									CNF_AttributeSet.Attributeids
	   
							from DATA_Sale WITH(NOLOCK)
								inner JOIN data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
								inner JOIN DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
								inner JOIN CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
								inner JOIN CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								inner JOIN CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
								LEFT  JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
											   from data_saleitem2ticket WITH(NOLOCK)
												INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
												where data_saleitem2ticket.operationtype = 1
												--  and data_ticket.voidtype not in (104, 125)
											) p									on p.S2TSaleitemid = data_saleitem.saleitemid

					
					where DATA_Sale.Paid = 1
						and (((1 = case  when data_transaction.transactiontype in (9, 10, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
								when data_transaction.transactiontype in (18, 20, 22, 123) then 1
								when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
								when data_transaction.transactiontype in (7, 13, 34) then 1
								else 0
						end) and (DATA_Sale.Encoded = 1)) or ((DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)))
						or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)))												
						)  
						and DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; 0
						and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
						and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
							OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
						and ((data_transaction.transactionid in (select data_payment.transactionid
																   from data_payment WITH(NOLOCK)
																  where PaymentStatus = 1
																    and DATA_Payment.TransactionId = DATA_Transaction.transactionid
																))
						     or (data_transaction.totalamount &amp;#60;&amp;#62; 0))

					UNION ALL

						select		@SuspendCOAAccountId COAID,
										@SuspendRRRId RRID,
										@SuspendRRCalcTypeWhere RRWHERE,
										@SuspendRRCalcTypeMethod RRMETHOD,
										@SuspendCOAAccountConfigId RRCONFIG,
										@SuspendCOAAccountTypeId COATYPE,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										p.ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate BatchDate,
										ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
										DATA_SaleItem.UnitPrice,
										DATA_SaleItem.UnitRecharge charge,
										DATA_SaleItem.UnitRecharge charge2,
										@SuspendPrice Price,
										@SuspendCOAAccount_Percentage  Percentage,
										@SuspendRemainingValues RValues,				
										ABS(case when p.TicketID is not null then ABS(ISNULL(DATA_SaleItem.UnitRecharge, 0)) 
											 else ABS(ISNULL(DATA_SaleItem.UnitRecharge, 0)) * data_saleitem.quantity
										end) as revenueamount,
										case when data_saleitem.quantity &amp;#60; 0 then 1
											 else @SuspendRRCOAAccountingType 
										  end Accountingtype,
										@SuspendRRCalcTypeTrigger  RTRIGGER,
										@SuspendPercentage PERC,
										1 rrdays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale WITH(NOLOCK)
									inner JOIN data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId = DATA_Sale.voidTransactionId
									inner JOIN DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
									inner JOIN CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									inner JOIN CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
									inner JOIN CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
									inner JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
												   from data_saleitem2ticket WITH(NOLOCK)
													INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
													where data_saleitem2ticket.operationtype = 1
													--  and data_ticket.voidtype not in (104, 125)
												) p									on p.S2TSaleitemid = data_saleitem.saleitemid

					
						where DATA_Sale.Paid = 1
							and 1 = case  when data_transaction.transactiontype in (5, 30) and data_saleitem.quantity &amp;#60; 0 then 1
										  else 0
									 end 
							and DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; 0
							and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
							and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							and ((data_transaction.transactionid in (select data_payment.transactionid
																	   from data_payment WITH(NOLOCK)
																	  where PaymentStatus = 1
																	    and DATA_Payment.TransactionId = DATA_Transaction.transactionid
																	))
							       or (data_transaction.totalamount &amp;#60;&amp;#62; 0))


					)p


----Refund/Void on tickets in contract	
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[ticketid]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select *
		  from (
				select  @SuspendCOAAccountId as SuspendCOAAccountId,
						@SuspendRRRId as SuspendRRRId,
						@SuspendRRCalcTypeWhere as SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId as SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId as SuspendCOAAccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_Ticket.ticketid,
						DATA_SaleItem.saleitemid,
						CNF_MatrixCell.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as BatchDate,
						1 as Quantity,
						ISNULL(DATA_Ticket.price, 0) as UnitAmount,
						ISNULL(DATA_Ticket.Price, 0) as GrossAmount,
						ISNULL((DATA_Ticket.Price - data_ticket.taxes), 0) as netprice,
						@SuspendPrice as SuspendPrice,
						@SuspendCOAAccount_Percentage as SuspendCOAAccount_Percentage,
						@SuspendRemainingValues as SuspendRemainingValues,
						ISNULL(case when dr1.accountingtype = 1 and ISNULL((DATA_Ticket.Price - data_ticket.taxes) - sum(dr1.revenueamount), 0) &amp;#60;&amp;#62; 0 then DATA_Ticket.Price - data_ticket.taxes
								when dr1.accountingtype = 2 then (select sum(revenueamount) from RR_DATA_Revenue where RR_DATA_Revenue.ticketid = dr1.ticketid and accountingtype = 2)			   
								when (data_saleitem.producttaxtype in (3, 4)) and (data_saleitem.ProductTaxType = 1) then ((DATA_SaleItem.UnitPrice))			      
							    when (data_saleitem.ProductTaxType &amp;#60;&amp;#62; 1) and (DATA_SaleItem.UnitrawPrice is not null) and isnull((DATA_SaleItem.UnitrawPrice), 0) &amp;#60;&amp;#62; 0 then ((DATA_SaleItem.UnitrawPrice  + data_saleitem.unitRecharge))
							    when (data_saleitem.ProductTaxType = 1) and isnull((DATA_SaleItem.UnitrawPrice *  DATA_SaleItem.Quantity), 0) &amp;#60;&amp;#62; 0 then ((DATA_SaleItem.UnitrawPrice - DATA_SaleItem.unittaxes + data_saleitem.unitRecharge))
							    when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge = 0 then 0
							    when (DATA_SaleItem.UnitPrice is not null) and isnull((DATA_SaleItem.UnitPrice *  DATA_SaleItem.Quantity), 0) = 0 and data_saleitem.unitRecharge &amp;#60;&amp;#62; 0 then data_saleitem.unitRecharge
							    when isnull((data_transaction.TotalAmount), 0) &amp;#60;&amp;#62; 0 then data_transaction.TotalAmount
							    when isnull((DATA_Sale.TotalAmount), 0) &amp;#60;&amp;#62; 0 then DATA_Sale.TotalAmount
							    else (data_transaction.Revenue)
						end, 0) as revenueamount,
						1 Accountingtype,
						@SuspendRRCalcTypeTrigger as SuspendRRCalcTypeTrigger,
						@SuspendPercentage as SuspendPercentage,
						@SuspendDays as SuspendDays

				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)			on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																			or (data_transaction.Saleid = DATA_Sale.Saleid))
					INNER JOIN data_saleitem WITH(NOLOCK)				on data_saleitem.saleid = data_sale.saleid	
					Left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT JOIN DATA_TICKET WITH(NOLOCK)					on data_ticket.saleitemid = data_saleitem.saleitemid
					left join RR_DATA_Revenue DR1 WITH(NOLOCK)			on dr1.ticketid = DATA_Ticket.ticketid and accountingtype = 1

				where ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactiontype  in (46, 47)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and data_saleitem.quantity &amp;#60;&amp;#62; 0
				  and data_saleitem.totalamount &amp;#60;&amp;#62; 0
														
				Group by	data_transaction.transactionid, 
							data_transaction.saleid,
							DATA_Ticket.ticketid,
							DATA_SALEITEM.saleitemid,
							CNF_MatrixCell.Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							data_transaction.fTransactionDate,
							data_transaction.TransactionDate,
							DATA_Ticket.price,
							DATA_Ticket.Price,
							data_ticket.taxes,
							dr1.accountingtype,
							dr1.ticketid,
							data_saleitem.saleitemid,
							data_saleitem.producttaxtype,
							data_saleitem.ProductTaxType,
							data_saleitem.unitprice,
							data_saleitem.quantity,
							DATA_SaleItem.UnitrawPrice,
							data_transaction.TransactionType,
							DATA_SaleItem.UnitTaxes,
							data_saleitem.UnitRecharge,
							data_transaction.TotalAmount,
							DATA_Sale.TotalAmount,
							data_transaction.Revenue
		)P 
		where revenueamount &amp;#60;&amp;#62; 0

INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[ticketid]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select *
		  from (
				select @SuspendCOAAccountId as SuspendCOAAccountId,
						@SuspendRRRId as SuspendRRRId,
						@SuspendRRCalcTypeWhere as SuspendRRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as SuspendRRCalcTypeMethod,
						@SuspendCOAAccountConfigId as SuspendCOAAccountConfigId,
						@SuspendCOAAccountTypeId as SuspendCOAAccountTypeId,
						data_transaction.transactionid, 
						data_transaction.saleid,
						DATA_Ticket.ticketid,
						DATA_SaleItem.saleitemid,
						CNF_MatrixCell.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as BatchDate,
						1 as Quantity,
						ISNULL(DATA_Ticket.price, 0) as UnitAmount,
						ISNULL(DATA_Ticket.Price, 0) as GrossAmount,
						ISNULL((DATA_Ticket.Price - data_ticket.taxes), 0) as netprice,
						@SuspendPrice as SuspendPrice,
						@SuspendCOAAccount_Percentage as SuspendCOAAccount_Percentage,
						@SuspendRemainingValues as SuspendRemainingValues,
						case when (select sum(revenueamount)
										from rr_data_revenue RR WITH(NOLOCK)
									  where RR.ticketid = data_ticket.ticketid
										and RR.rrcalctypetrigger in (2, 3, 4, 17)
										and RR.AccountingType = 1) &amp;#60;&amp;#62; 0 then DATA_Ticket.Price - data_ticket.taxes -  (select sum(revenueamount)
										from rr_data_revenue RR WITH(NOLOCK)
									  where RR.ticketid = data_ticket.ticketid
										and RR.rrcalctypetrigger in (2, 3, 4, 17)
										and RR.AccountingType = 1)
							 else DATA_Ticket.Price - data_ticket.taxes
						  end REvenueamount,
						1 Accountingtype,
						@SuspendRRCalcTypeTrigger as SuspendRRCalcTypeTrigger,
						@SuspendPercentage as SuspendPercentage,
						@SuspendDays as SuspendDays

				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)			on  ((data_transaction.TransactionId = ISNULL(data_sale.voidtransactionid, DATA_Sale.PaidTransactionId)) 
																			or (data_transaction.Saleid = DATA_Sale.Saleid))
					INNER JOIN data_saleitem WITH(NOLOCK)				on data_saleitem.saleid = data_sale.saleid	
					Left join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT JOIN DATA_TICKET WITH(NOLOCK)					on data_ticket.saleitemid = data_saleitem.saleitemid
					left join rr_data_revenue DR1 WITH(NOLOCK)			on dr1.ticketid = DATA_Ticket.ticketid and accountingtype = 1

				where ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactiontype  in (51)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and data_saleitem.quantity &amp;#60;&amp;#62; 0
				  and data_saleitem.totalamount &amp;#60;&amp;#62; 0

															

				Group by	data_transaction.transactionid, 
							data_transaction.saleid,
							DATA_Ticket.ticketid,
							DATA_SALEITEM.saleitemid,
							CNF_MatrixCell.Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							data_transaction.fTransactionDate,
							data_transaction.TransactionDate,
							DATA_Ticket.price,
							DATA_Ticket.Price,
							data_ticket.taxes,
							dr1.accountingtype,
							dr1.ticketid,
							data_saleitem.saleitemid,
							data_saleitem.producttaxtype,
							data_saleitem.ProductTaxType,
							data_saleitem.unitprice,
							data_saleitem.quantity,
							DATA_SaleItem.UnitrawPrice,
							data_transaction.TransactionType,
							DATA_SaleItem.UnitTaxes,
							data_saleitem.UnitRecharge,
							data_transaction.TotalAmount,
							DATA_Sale.TotalAmount,
							data_transaction.Revenue
		)P 
		where revenueamount &amp;#60;&amp;#62; 0
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
					select  @SuspendCOAAccountId,
							@SuspendRRRId,
							@SuspendRRCalcTypeWhere,
							@SuspendRRCalcTypeMethod,
							@SuspendCOAAccountConfigId,
							@SuspendCOAAccountTypeId,
							data_transaction.transactionid, 
							data_transaction.saleid,
							null saleitemid,
							null Matrixcellid,
							null MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							@BatchDate,
							1,
							ISNULL(data_transaction.Revenue, 0)  UnitPrice,
							ISNULL(data_transaction.Revenue, 0) GrossAmount,
							ISNULL(data_transaction.Revenue, 0) as NetAmount,
							@SuspendPrice,
							@SuspendCOAAccount_Percentage,
							@SuspendRemainingValues,
							ISNULL(data_transaction.Revenue, 0) Revenue,
							case when @SuspendRRCOAAccountingType = 1 then 2
								 when @SuspendRRCOAAccountingType = 2 then 1
								 else @SuspendRRCOAAccountingType
							end Accountingtype,
							@SuspendRRCalcTypeTrigger,
							@SuspendPercentage,
							@SuspendDays,
							null Attributeids
	   
					from DATA_Sale WITH(NOLOCK)
						inner join data_transaction WITH(NOLOCK)			on data_transaction.Saleid = DATA_Sale.Saleid

					where data_transaction.transactiontype in (8)
					  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
						  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
					  and data_transaction.transactionid in (select data_payment.transactionid
															   from data_payment WITH(NOLOCK)
															  where PaymentStatus = 1
																and PaymentAmount &amp;#60;&amp;#62; 0
																and DATA_Payment.TransactionId = DATA_Transaction.transactionid
					 										)




----No Tickets on Reservation Deposits
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select  @SuspendCOAAccountId,
				@SuspendRRRId,
				@SuspendRRCalcTypeWhere,
				@SuspendRRCalcTypeMethod,
				@SuspendCOAAccountConfigId,
				@SuspendCOAAccountTypeId,
				data_transaction.transactionid, 
				data_transaction.saleid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate,
				0 Quantity,
				data_transaction.revenue TotalAmount,
				data_transaction.revenue NetAmount,
				@SuspendPrice,
				@SuspendCOAAccount_Percentage,
				@SuspendRemainingValues,
				abs(data_transaction.revenue) revenue,
				ISNULL(case when data_transaction.revenue &amp;#60; 0 then 1
				     else @SuspendRRCOAAccountingType
				 end, 0) ,
				@SuspendRRCalcTypeTrigger,
				@SuspendPercentage,
				@SuspendDays
	   
		from DATA_Sale WITH(NOLOCK)
			inner join data_transaction WITH(NOLOCK)			on data_transaction.saleid = DATA_Sale.saleid

		where data_transaction.transactiontype in (12, 15)
		  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
			  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
		  and data_transaction.transactionid in (select data_payment.transactionid
												   from data_payment WITH(NOLOCK)
												  where PaymentStatus = 1
													and PaymentAmount &amp;#60;&amp;#62; 0
													and DATA_Payment.TransactionId = DATA_Transaction.transactionid
												)

--TODO Leaving for more time
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  COAAccountId,
						RevenueRecognitionRuleId,
						RRCalcTypeWhere,
						RRCalcTypeMethod,
						COAAccountConfigId,
						COAAccountType,
						transactionid, 
						saleid,
						Ticketid,
						saleitemid,
						Matrixcellid,
						MatrixSheetid,
						Siteid,
						OperatingAreaId,
						Workstationid,
						UserGroupid,
						UserId,
						calcdate,
						Quantity,
						UnitPrice,
						totalamount,
						NetAmount,
						suspendprice,
						percentage,
						remainingValues,
						Revenueamount,
						Accountingtype,
						rrTrigger,
						suspercentage,
						suspendday,
						Attributeids
		  from (
----14
			select distinct 
				         @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
					ABS(ISNULL((case when DATA_Transaction.TransactionType IN (13, 34) then DATA_Transaction.Revenue
						
								when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType in (3, 4) and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitPrice))) 
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2 and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitrawPrice) - DATA_SaleItem.UnitTaxes)) 

								when data_ticket.ticketid is not null then
										ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
															from data_saleitemrule WITH(NOLOCK)
																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								
								else (data_saleitem.totalamount - data_saleitem.totaltaxes)   - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)

								end), 0)) as Revenueamount,
						case when DATA_Transaction.TransactionType IN (13) then 1
						     when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = DATA_Sale.PaidTransactionId
					left join data_transaction Encd_Trans WITH(NOLOCK)		on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
					LEFT  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					LEFT  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					LEFT  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					LEFT  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid															
								)data_ticket			on data_ticket.saleitemid = data_saleitem.saleitemid 
															and 1 = case when data_transaction.transactiontype in (18, 20, 22) and data_ticket.OperationType in (2) then 1
																			when data_transaction.transactiontype in (9) and data_ticket.OperationType in (15)  then 1
																			when data_transaction.transactiontype in (9, 14, 16, 122, 5, 13, 34) and data_ticket.OperationType in (1, 11)  then 1																							 
																			else 0
																	end 

				where DATA_Sale.Paid = 1
				  and (((1 = case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
								when data_transaction.transactiontype in (18, 20, 22, 123) then 1
								when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
								when data_transaction.transactiontype in (13, 34) then 1
								else 0
						end) and (DATA_Sale.Encoded = 1)) or ((DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38, 119)))
						  or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									)
						  
						  )												
						) 
				  and 1 = case when data_sale.encoded = 1 and data_sale.PaidTransactionId = data_sale.EncodedTransactionId then 1
							   when data_sale.encoded = 1 and Encd_Trans.FTransactionDate = data_transaction.FTransactionDate then 1
				               when data_sale.encoded = 1 and (Encd_Trans.FTransactionDate &amp;#62; data_transaction.FTransactionDate) then 0
							   when (DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)) then 1
							   when (DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									) then 1
								else 0
							end
				  and DATA_Transaction.TransactionType not in (5, 30, 18, 20, 22, 123)
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and ((data_transaction.transactiontype in (9, 13, 14, 16, 18, 20, 22, 34, 38, 119, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (9, 14, 16, 18, 20, 22, 119, 123))))
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and (data_transaction.transactionid in (select transactionid
																  from data_payment WITH(NOLOCK)
																 where PaymentStatus = 1
																   and data_transaction.transactionid = DATA_Payment.transactionid
																))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)) or (DATA_Transaction.TransactionType in (13, 34)))

					and ((data_saleitem.saleitemid in (select saleitemid
														from (select PaidTransactionId,
																	saleitemid,
																	transactiontype,
																	abs(data_saleitem.quantity) quantity,
																	(select count(*)
																		from data_saleitem2ticket WITH(NOLOCK)
																		where data_saleitem2ticket.saleitemid = data_saleitem.saleitemid) TicketCount

															from data_saleitem WITH(NOLOCK)
																inner join DATA_Sale  WITH(NOLOCK)					on data_sale.saleid = data_saleitem.saleid
																inner join DATA_Transaction  WITH(NOLOCK)			on data_transaction.transactionid = DATA_Sale.PaidTransactionId

															where data_sale.Encoded = 1
																and data_saleitem.ProductType = 1
																and data_sale.StatusCode = 1
																and data_transaction.transactiontype not in (5)
														--		and data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where data_payment.TransactionId = DATA_Transaction.transactionid and data_payment.paymentstatus = 1 and data_payment.paymentamount &amp;#60;&amp;#62; 0)
														)p
														where quantity = ticketcount
													)) or (data_sale.statuscode &amp;#60;&amp;#62; 1) or (data_saleitem.ProductType &amp;#60;&amp;#62; 1) or (data_transaction.transactiontype in (13, 34)))
		UNION ALL
		select distinct 
				         @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ABS(ISNULL((case when DATA_Transaction.TransactionType IN (13, 34) then DATA_Transaction.Revenue
						
								when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType in (3, 4) and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitPrice))) 

								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2 and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitrawPrice) - DATA_SaleItem.UnitTaxes)) 

								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType = 2
							   							then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes))  - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) 
							 
							 
								when data_ticket.ticketid is not null then
										ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
															from data_saleitemrule WITH(NOLOCK)
																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								
								else (data_saleitem.totalamount - data_saleitem.totaltaxes)   - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)

								end), 0)) as Revenueamount,
						case when DATA_Transaction.TransactionType IN (13) then 1
						     when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = DATA_Sale.PaidTransactionId
					left join data_transaction Encd_Trans WITH(NOLOCK)		on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
					LEFT  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					LEFT  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					LEFT  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					LEFT  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid															
											where DATA_Ticket.VoidType not in (104, 125)
								)data_ticket			on data_ticket.saleitemid = data_saleitem.saleitemid 
															and 1 = case when data_transaction.transactiontype in (18, 20, 22) and data_ticket.OperationType in (2) then 1
																			when data_transaction.transactiontype in (9) and data_ticket.OperationType in (15)  then 1
																			when data_transaction.transactiontype in (9, 14, 16, 122, 5, 13, 34) and data_ticket.OperationType in (1, 11)  then 1																							 
																			else 0
																	end 

				where DATA_Sale.Paid = 1
				  and (((1 = case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
								when data_transaction.transactiontype in (18, 20, 22, 123) then 1
								when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
								when data_transaction.transactiontype in (13, 34) then 1
								else 0
						end) and (DATA_Sale.Encoded = 1)) or ((DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)))
						  or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									)
						  
						  )												
						)
					and 1 = case when data_sale.encoded = 1 and data_sale.PaidTransactionId = data_sale.EncodedTransactionId then 1
					             when data_sale.encoded = 1 and Encd_Trans.FTransactionDate = data_transaction.FTransactionDate then 1
				               when data_sale.encoded = 1 and (Encd_Trans.FTransactionDate &amp;#62; data_transaction.FTransactionDate) then 0
							   when (DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)) then 1
							   when (DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									) then 1
								else 0
							end						
				  and DATA_Transaction.TransactionType not in (5, 30, 18, 20, 22, 123)
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and ((data_transaction.transactiontype in (9, 13, 14, 16, 18, 20, 22, 34, 38, 119, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (9, 14, 16, 18, 20, 22, 119, 123))))
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and (data_transaction.transactionid in (select transactionid
																  from data_payment WITH(NOLOCK)
																 where PaymentStatus = 1
																   and data_transaction.transactionid = DATA_Payment.transactionid
																))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)) or (DATA_Transaction.TransactionType in (13, 34)))

					and data_saleitem.saleitemid in (select saleitemid
														from (select PaidTransactionId,
																	saleitemid,
																	transactiontype,
																	abs(data_saleitem.quantity) quantity,
																	(select count(*)
																		from data_saleitem2ticket WITH(NOLOCK)
																		where data_saleitem2ticket.saleitemid = data_saleitem.saleitemid) TicketCount

															from data_saleitem WITH(NOLOCK)
																inner join DATA_Sale  WITH(NOLOCK)					on data_sale.saleid = data_saleitem.saleid
																inner join DATA_Transaction  WITH(NOLOCK)			on data_transaction.transactionid = DATA_Sale.PaidTransactionId

															where data_sale.Encoded = 1
																and data_saleitem.ProductType = 1
																and data_sale.StatusCode = 1
																and data_transaction.transactiontype not in (5)
															--	and data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where data_payment.TransactionId = DATA_Transaction.transactionid and data_payment.paymentstatus = 1 and data_payment.paymentamount &amp;#60;&amp;#62; 0)
														)p
														where quantity &amp;#60;&amp;#62; ticketcount
													)

		)p  
		where RevenueAmount &amp;#60;&amp;#62; 0

		

----PaymentMethod for Normal Payments
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[PaymentID])
				select  coaaccountid,
						RRID,
						TypeWhere,
						method,
						Configid,
						AccountType,
						transactionid, 
						saleid,
						Siteid,
						OperatingAreaId,
						WorkstationID,
						UserGroupid,
						UserId,
						BatchDate,
						Qty,
						Gross,
						net,
						price,
						percentage,
						RemaningValue,
						ISNULL(abs(RevenueAmount), 0) RevenueAmount,
						Accountingtype,
						TypeTrigger,
						PaymentPercentage,
						RRDays,
						paymentID
				  from (
						select  coaaccountid,
								RRID,
								TypeWhere,
								method,
								Configid,
								AccountType,
								transactionid, 
								saleid,
								Siteid,
								OperatingAreaId,
								WorkstationID,
								UserGroupid,
								UserId,
								BatchDate,
								Qty,
								Gross,
								net,
								price,
								percentage,
								RemaningValue,
								case when Rownumber = 1 then RevenueAmount + Change 
									 else RevenueAmount 
								 end RevenueAmount,
								Accountingtype,
								TypeTrigger,
								PaymentPercentage,
								RRDays,
								paymentID
						from (
								select  @PaymentCOAAccountId as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										@PaymentCOAAccountTypeId as AccountType,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										case when (Payment.PaymentAmount) &amp;#60;&amp;#62; 0 then (Payment.PaymentAmount) 
											 else Payment.AdvancedPaymentAmount
										end as RevenueAmount,
										case when Payment.paymentamount &amp;#60;  0 then 2
											 when Payment.paymentamount &amp;#62;= 0 then 1
										end Accountingtype,
										data_transaction.Change,
										Payment.ChangeAmount,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays,
										ISNULL((select sum(FeeAmount) as FeeAmount
												 from DATA_PaymentPlan2Transaction	
													INNER JOIN DATA_PaymentPlan			on data_paymentplan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
												 where DATA_PaymentPlan2Transaction.Transactionid = data_transaction.transactionid
												   and DATA_PaymentPlan2Transaction.flexpaymentstatus &amp;#60;&amp;#62; 5
												), 0) as fee,
										Row_Number ()  OVER (PARTITION BY data_transaction.transactionid order by data_transaction.transactionid, Payment.PaymentType, Payment.Paymentamount desc)  as Rownumber,
										paymentID
		  
								from DATA_Sale WITH(NOLOCK)
									INNER join data_transaction WITH(NOLOCK)								on data_transaction.saleid = DATA_Sale.saleid
									INNER JOIN (select data_payment.paymentID, data_transaction.saleid, data_payment.transactionid, data_payment.PaymentAmount, DATA_Payment.ChangeAmount, DATA_Payment.PaymentStatus, data_payment.PaymentFee,
													  data_transaction.transactiontype, data_payment.paymenttype, data_payment.AdvancedPaymentAmount
												 from data_payment WITH(NOLOCK)
													INNER JOIN data_transaction WITH(NOLOCK)		ON data_transaction.transactionid = data_payment.transactionid
												where data_payment.Paymentstatus = 1
											  ) Payment						ON payment.saleid = DATA_Sale.saleid 
											   and payment.Transactionid = data_transaction.Transactionid
			
								where Payment.PaymentStatus = 1
								  and data_transaction.transactionstatus in (5, 30, 35)
								  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
									  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  and ((DATA_Sale.paid = 1) or (data_transaction.transactiontype in (12, 15)))
													
						)p
		)r
		where RevenueAmount &amp;#60;&amp;#62; 0
							

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  COAAccountId,
						RevenueRecognitionRuleId,
						RRCalcTypeWhere,
						RRCalcTypeMethod,
						COAAccountConfigId,
						COAAccountType,
						transactionid, 
						saleid,
						Ticketid,
						saleitemid,
						Matrixcellid,
						MatrixSheetid,
						Siteid,
						OperatingAreaId,
						Workstationid,
						UserGroupid,
						UserId,
						calcdate,
						Quantity,
						UnitPrice,
						totalamount,
						NetAmount,
						suspendprice,
						percentage,
						remainingValues,
						Revenueamount,
						Accountingtype,
						rrTrigger,
						suspercentage,
						suspendday,
						Attributeids
		  from (
----18
			select distinct 
				         @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
					    ABS(ISNULL((case when DATA_Transaction.TransactionType IN (13, 34) then DATA_Transaction.Revenue
						when DATA_Transaction.TransactionType IN (18, 20, 22) and data_ticket.ticketid IS not null and ISNULL((select abs((debit - credit))
																from( select sum(case when AccountingType = 1 then RevenueAmount else 0 end) debit,
																		   sum(case when AccountingType = 2 then RevenueAmount else 0 end) credit
																					   from RR_DATA_Revenue WITH(NOLOCK)
																					   where coaaccountid not in (1, 2, 3, 4)
																					   and saleitemtaxid is null
																					   and paymentid is null
																					   and ISNULL(oobflag, 0) = 0
																					   and saleitemruleid is null
																					   and coaaccountid not in (209)
																					   and RRCalcTypeTrigger in (1, 2, 3, 4, 17)
																					   and RR_DATA_Revenue.TicketId = data_ticket.ticketid
						)p), 0)	 &amp;#60;&amp;#62; 0 then
										ISNULL((select abs((debit - credit))
																from( select sum(case when AccountingType = 1 then RevenueAmount else 0 end) debit,
																		   sum(case when AccountingType = 2 then RevenueAmount else 0 end) credit
																					   from RR_DATA_Revenue WITH(NOLOCK)
																					   where coaaccountid not in (1, 2, 3, 4)
																					   and saleitemtaxid is null
																					   and paymentid is null
																					   and ISNULL(oobflag, 0) = 0
																					   and saleitemruleid is null
																					   and coaaccountid not in (209)
																					   and RRCalcTypeTrigger in (1, 2, 3, 4, 17)
																					   and RR_DATA_Revenue.TicketId = data_ticket.ticketid
																					 )p), 0)									
								when data_saleitem.ProductType &amp;#60;&amp;#62; 1 and data_transaction.transactiontype = 123 and ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0
																																	and data_saleitemrule.promotiontype = 3), 0) &amp;#60;&amp;#62; 0
														then 0

								when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType in (3, 4) and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitPrice))) 
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2 and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitrawPrice) - DATA_SaleItem.UnitTaxes)) 

								when data_ticket.ticketid is not null and DATA_SaleItem.UnitRawPrice &amp;#60;&amp;#62; DATA_SaleItem.unitprice then
										ABS((DATA_SaleItem.UnitRawPrice) - DATA_SaleItem.UnitTaxes)
								when data_ticket.ticketid is not null then
										ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
															from data_saleitemrule WITH(NOLOCK)
																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								
								else (data_saleitem.totalamount - data_saleitem.totaltaxes)   + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)

								end), 0)) as Revenueamount,

						case when DATA_Transaction.TransactionType IN (13) then 1
						     when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = DATA_Sale.PaidTransactionId
					left join data_transaction Encd_Trans WITH(NOLOCK)		on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
					LEFT  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					LEFT  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					LEFT  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					LEFT  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid	
											where operationtype &amp;#60;= 20
								
								)data_ticket			on data_ticket.saleitemid = data_saleitem.saleitemid 
															and 1 = case when data_transaction.transactiontype in (18, 20, 22) and data_ticket.OperationType in (2) then 1
																			when data_transaction.transactiontype in (9) and data_ticket.OperationType in (15)  then 1
																			when data_transaction.transactiontype in (9, 14, 16, 122, 5, 13, 34) and data_ticket.OperationType in (1, 11)  then 1																							 
																			else 0
																	end 
						
				where DATA_Sale.Paid = 1
				  and (((1 = case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
								when data_transaction.transactiontype in (18, 20, 22, 123) then 1
								when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
								when data_transaction.transactiontype in (13, 34) then 1
								else 0
						end) and (DATA_Sale.Encoded = 1)) or ((DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38, 119)))
						  or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									)
						  
						  )												
						) 
				  and 1 = case when data_sale.encoded = 1 and data_sale.PaidTransactionId = data_sale.EncodedTransactionId then 1
							   when data_sale.encoded = 1 and Encd_Trans.FTransactionDate = data_transaction.FTransactionDate then 1
				               when data_sale.encoded = 1 and (Encd_Trans.FTransactionDate &amp;#62; data_transaction.FTransactionDate) then 0
							   when (DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)) then 1
							   when (DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									) then 1
								else 0
							end
				  and DATA_Transaction.TransactionType not in (5, 30, 34, 38, 9, 14, 16, 122, 13, 34, 7, 9)
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_saleitem.Quantity &amp;#60;&amp;#62; 0
				  and ((data_transaction.transactiontype in (9, 13, 14, 16, 18, 20, 22, 34, 38, 119, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (9, 14, 16, 18, 20, 22, 119, 123))))
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and (data_transaction.transactionid in (select transactionid
																  from data_payment WITH(NOLOCK)
																 where PaymentStatus = 1
																   and data_transaction.transactionid = DATA_Payment.transactionid
																))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)) or (DATA_Transaction.TransactionType in (13, 34)))

					and ((data_saleitem.saleitemid in (select saleitemid
														from (select PaidTransactionId,
																	saleitemid,
																	transactiontype,
																	abs(data_saleitem.quantity) quantity,
																	(select count(*)
																		from data_saleitem2ticket WITH(NOLOCK)
																		where data_saleitem2ticket.saleitemid = data_saleitem.saleitemid) TicketCount

															from data_saleitem WITH(NOLOCK)
																inner join DATA_Sale  WITH(NOLOCK)					on data_sale.saleid = data_saleitem.saleid
																inner join DATA_Transaction  WITH(NOLOCK)			on data_transaction.transactionid = DATA_Sale.PaidTransactionId

															where data_sale.Encoded = 1
																and data_saleitem.ProductType = 1
																and data_sale.StatusCode = 1
																and data_transaction.transactiontype not in (5)
														--		and data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where data_payment.TransactionId = DATA_Transaction.transactionid and data_payment.paymentstatus = 1 and data_payment.paymentamount &amp;#60;&amp;#62; 0)
														)p
														where quantity = ticketcount
													)) or (data_sale.statuscode &amp;#60;&amp;#62; 1) or (data_saleitem.ProductType &amp;#60;&amp;#62; 1) or (data_transaction.transactiontype in (34)))
		UNION ALL
		select distinct 
				         @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ABS(ISNULL((case when DATA_Transaction.TransactionType IN (13, 34) then DATA_Transaction.Revenue
						when DATA_Transaction.TransactionType IN (18, 20, 22) and data_ticket.ticketid IS not null and ISNULL((select abs((debit - credit))
																from( select sum(case when AccountingType = 1 then RevenueAmount else 0 end) debit,
																		   sum(case when AccountingType = 2 then RevenueAmount else 0 end) credit
																					   from RR_DATA_Revenue WITH(NOLOCK)
																					   where coaaccountid not in (1, 2, 3, 4)
																					   and saleitemtaxid is null
																					   and paymentid is null
																					   and ISNULL(oobflag, 0) = 0
																					   and saleitemruleid is null
																					   and coaaccountid not in (209)
																					   and RRCalcTypeTrigger in (1, 2, 3, 4, 17)
																					   and RR_DATA_Revenue.TicketId = data_ticket.ticketid
						)p), 0)	 &amp;#60;&amp;#62; 0 then
										ISNULL((select abs((debit - credit))
																from( select sum(case when AccountingType = 1 then RevenueAmount else 0 end) debit,
																		   sum(case when AccountingType = 2 then RevenueAmount else 0 end) credit
																					   from RR_DATA_Revenue WITH(NOLOCK)
																					   where coaaccountid not in (1, 2, 3, 4)
																					   and saleitemtaxid is null
																					   and paymentid is null
																					   and ISNULL(oobflag, 0) = 0
																					   and saleitemruleid is null
																					   and coaaccountid not in (209)
																					   and RRCalcTypeTrigger in (1, 2, 3, 4, 17)
																					   and RR_DATA_Revenue.TicketId = data_ticket.ticketid
																					 )p), 0)		
									when DATA_Transaction.TransactionType IN (18, 20, 22) and data_ticket.ticketid IS not null and ISNULL((select sum(revenueamount) 
										   from RR_DATA_Revenue WITH(NOLOCK)
										   where coaaccountid not in (1, 2, 3, 4)
										   and saleitemtaxid is null
										   and paymentid is null
										   and ISNULL(oobflag, 0) = 0
										   and saleitemruleid is null
										   and RRCalcTypeTrigger = 1
										   and AccountingType = 2
										   and RR_DATA_Revenue.TicketId = data_ticket.ticketid), 0)	 = 0 then
										ISNULL((select sum(revenueamount) 
										   from RR_DATA_Revenue WITH(NOLOCK)
										   where coaaccountid in (1)
										   and saleitemtaxid is null
										   and ISNULL(oobflag, 0) = 0
										   and paymentid is null
										   and saleitemruleid is null
										   and RRCalcTypeTrigger = 1
										   and AccountingType = 2
										   and RR_DATA_Revenue.TicketId = data_ticket.ticketid), 0)
								when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType in (3, 4) and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitPrice))) 

								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2 and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitrawPrice) - DATA_SaleItem.UnitTaxes)) 

								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType = 2
							   							then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes))  + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) 
							 
							 
								when data_ticket.ticketid is not null then
										ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
															from data_saleitemrule WITH(NOLOCK)
																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								
								else (data_saleitem.totalamount - data_saleitem.totaltaxes)   + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)

								end), 0)) as Revenueamount,
						case when DATA_Transaction.TransactionType IN (13) then 1
						     when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = DATA_Sale.PaidTransactionId
					left join data_transaction Encd_Trans WITH(NOLOCK)		on Encd_Trans.TransactionId =  DATA_Sale.EncodedTransactionId
					LEFT  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					LEFT  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					LEFT  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					LEFT  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid															
											where DATA_Ticket.VoidType not in (104, 125)
											and  operationtype &amp;#60;= 20
								)data_ticket			on data_ticket.saleitemid = data_saleitem.saleitemid 
															and 1 = case when data_transaction.transactiontype in (18, 20, 22) and data_ticket.OperationType in (2) then 1
																			when data_transaction.transactiontype in (9) and data_ticket.OperationType in (15)  then 1
																			when data_transaction.transactiontype in (9, 14, 16, 122, 5, 13, 34) and data_ticket.OperationType in (1, 11)  then 1																							 
																			else 0
																	end 

				where DATA_Sale.Paid = 1
				  and (((1 = case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
								when data_transaction.transactiontype in (18, 20, 22, 123) then 1
								when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
								when data_transaction.transactiontype in (13, 34) then 1
								else 0
						end) and (DATA_Sale.Encoded = 1)) or ((DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)))
						  or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									)
						  
						  )												
						)
					and 1 = case when data_sale.encoded = 1 and data_sale.PaidTransactionId = data_sale.EncodedTransactionId then 1
					             when data_sale.encoded = 1 and Encd_Trans.FTransactionDate = data_transaction.FTransactionDate then 1
				               when data_sale.encoded = 1 and (Encd_Trans.FTransactionDate &amp;#62; data_transaction.FTransactionDate) then 0
							   when (DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)) then 1
							   when (DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
												when data_transaction.transactiontype in (18, 20, 22, 123) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
												when data_transaction.transactiontype in (13, 34) then 1
												else 0
											 end)
									) then 1
								else 0
							end						
				  and DATA_Transaction.TransactionType not in (5, 30, 34, 38, 9, 14, 16, 122, 13, 34, 7, 9)
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_saleitem.Quantity &amp;#60;&amp;#62; 0
				  and ((data_transaction.transactiontype in (9, 13, 14, 16, 18, 20, 22, 34, 38, 119, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (9, 14, 16, 18, 20, 22, 119, 123))))
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and (data_transaction.transactionid in (select transactionid
																  from data_payment WITH(NOLOCK)
																 where PaymentStatus = 1
																   and data_transaction.transactionid = DATA_Payment.transactionid
																))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)) or (DATA_Transaction.TransactionType in (13, 34)))

					and data_saleitem.saleitemid in (select saleitemid
														from (select PaidTransactionId,
																	saleitemid,
																	transactiontype,
																	abs(data_saleitem.quantity) quantity,
																	(select count(*)
																		from data_saleitem2ticket WITH(NOLOCK)
																		where data_saleitem2ticket.saleitemid = data_saleitem.saleitemid) TicketCount

															from data_saleitem WITH(NOLOCK)
																inner join DATA_Sale  WITH(NOLOCK)					on data_sale.saleid = data_saleitem.saleid
																inner join DATA_Transaction  WITH(NOLOCK)			on data_transaction.transactionid = DATA_Sale.PaidTransactionId

															where data_sale.Encoded = 1
																and data_saleitem.ProductType = 1
																and data_sale.StatusCode = 1
																and data_transaction.transactiontype not in (5)
															--	and data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where data_payment.TransactionId = DATA_Transaction.transactionid and data_payment.paymentstatus = 1 and data_payment.paymentamount &amp;#60;&amp;#62; 0)
														)p
														where quantity &amp;#60;&amp;#62; ticketcount
													)

		)p  
		where RevenueAmount &amp;#60;&amp;#62; 0




		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  COAAccountId,
						RevenueRecognitionRuleId,
						RRCalcTypeWhere,
						RRCalcTypeMethod,
						COAAccountConfigId,
						COAAccountType,
						transactionid, 
						saleid,
						Ticketid,
						saleitemid,
						Matrixcellid,
						MatrixSheetid,
						Siteid,
						OperatingAreaId,
						Workstationid,
						UserGroupid,
						UserId,
						calcdate,
						Quantity,
						UnitPrice,
						totalamount,
						NetAmount,
						suspendprice,
						percentage,
						remainingValues,
						Revenueamount,
						Accountingtype,
						rrTrigger,
						suspercentage,
						suspendday,
						Attributeids
		  from (
----30
		select distinct 
				        @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ISNULL((case when data_ticket.TicketId IS null and data_saleitem.ProductType = 1
													then ABS((DATA_SaleItem.UnitPrice  - DATA_SaleItem.UnitTaxes)  * DATA_SaleItem.Quantity)
						
						
							when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
						     when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; 0  
							   						then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 
							 
							 
							 
							 
							 
							 
							 
							 
							else ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))

							end), 0) as Revenueamount,
						case when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = data_sale.voidtransactionid
					left  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					left  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid	
											where DATA_Ticket.ticketid in (select ticketid from RR_DATA_Revenue rr WITH(NOLOCK) where rr.ticketid = data_ticket.ticketid)
											)data_ticket
								on data_ticket.saleitemid = ISNULL(data_saleitem.origSAleitemid, data_saleitem.saleitemid ) 
									and 1 = case when data_transaction.transactiontype in (5, 30) and data_ticket.OperationType in (1, 2, 11)  then 1																							 
												 else 0
										     end 

				where DATA_Sale.Paid = 1
				  and ((DATA_Sale.Encoded = 1)
							or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)))	)	
				  and DATA_SaleItem.Quantity &amp;#60;&amp;#62; 0
				  and data_transaction.TransactionType IN (5, 30)
				  and data_saleitem.ItemTransactionType IN (5, 30)
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and ((data_transaction.transactionid in (select transactionid
														  from data_payment WITH(NOLOCK)
														 where PaymentStatus = 1
														   and data_transaction.transactionid = DATA_Payment.transactionid
														)))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)))
				  and DATA_Transaction.saleid not in (select SaleId
														from DATA_Transaction DT WITH(NOLOCK)
														where DT.SaleId = DATA_Transaction.SaleId
														  and DT.TransactionType in (12, 15)
													)

								and ((data_saleitem.saleitemid in (select saleitemid
														from (select PaidTransactionId,
																	saleitemid,
																	transactiontype,
																	abs(data_saleitem.quantity) quantity,
																	(select count(*)
																		from data_saleitem2ticket WITH(NOLOCK)
																		where data_saleitem2ticket.saleitemid = data_saleitem.saleitemid) TicketCount

															from data_saleitem WITH(NOLOCK)
																inner join DATA_Sale  WITH(NOLOCK)					on data_sale.saleid = data_saleitem.saleid
																inner join DATA_Transaction  WITH(NOLOCK)			on data_transaction.transactionid = DATA_Sale.PaidTransactionId

															where data_sale.Encoded = 1
																and data_saleitem.ProductType = 1
																and data_sale.StatusCode = 1
																and data_transaction.transactiontype not in (5)
														--		and data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where data_payment.TransactionId = DATA_Transaction.transactionid and data_payment.paymentstatus = 1 and data_payment.paymentamount &amp;#60;&amp;#62; 0)
														)p
														where quantity = ticketcount
													)) or (data_sale.statuscode &amp;#60;&amp;#62; 1) or (data_saleitem.ProductType &amp;#60;&amp;#62; 1) or (data_transaction.transactiontype in (34)))

						and data_sale.saleid in (
								select saleid
									from(
									select data_transaction.saleid, sum(paymentamount)Paymentamount, ISNULL((select sum(discountamount)
																										from data_saleitem WITH(NOLOCK)
																											inner join DATA_SaleItemRule WITH(NOLOCK)				on data_saleitemrule.saleitemid = data_saleitem.saleitemid
																											where data_saleitem.saleid = data_transaction.saleid
																											and data_saleitem.ItemTransactionType = 5
																									group by data_saleitem.saleid
																									having sum(discountamount) &amp;#60;&amp;#62; 0), 0) DiscountAmount
																from data_transaction WITH(NOLOCK)
																	INNER JOIN data_payment WITH(NOLOCK)					on data_payment.transactionid = data_transaction.transactionid
																where data_transaction.saleid = data_sale.saleid
																	and data_payment.PaymentStatus = 1
																	and data_transaction.transactiontype not in (5, 30)
																group by data_transaction.saleid
								)p
								where (Paymentamount + Discountamount) &amp;#60;&amp;#62; 0

								)

		UNION ALL
		select distinct 
				        @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ISNULL((case when data_ticket.TicketId IS null and data_saleitem.ProductType = 1
													then ABS((DATA_SaleItem.UnitPrice  - DATA_SaleItem.UnitTaxes)  * DATA_SaleItem.Quantity)
						
						
							when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
						     when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; 0  
							   						then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 
							 
							 
							 
							 
							 
							 
							 
							 
							else ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))

							end), 0) as Revenueamount,
						case when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = data_sale.voidtransactionid
					left  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					left  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid	
										where DATA_Ticket.ticketid in (select ticketid from RR_DATA_Revenue rr WITH(NOLOCK) where rr.ticketid = data_ticket.ticketid)
										  and VoidType not in (104, 125)	
											)data_ticket
								on data_ticket.saleitemid = ISNULL(data_saleitem.origSAleitemid, data_saleitem.saleitemid ) 
									and 1 = case when data_transaction.transactiontype in (5, 30) and data_ticket.OperationType in (1, 2, 11)  then 1																							 
												 else 0
										     end 

				where DATA_Sale.Paid = 1
				  and ((DATA_Sale.Encoded = 1)
							or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)))	)	
				  and DATA_SaleItem.Quantity &amp;#60;&amp;#62; 0
				  and data_transaction.TransactionType IN (5, 30)
				  and data_saleitem.ItemTransactionType IN (5, 30)
				  
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and ((data_transaction.transactionid in (select transactionid
														  from data_payment WITH(NOLOCK)
														 where PaymentStatus = 1
														   and data_transaction.transactionid = DATA_Payment.transactionid
														)))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)))
				  and DATA_Transaction.saleid not in (select SaleId
														from DATA_Transaction DT WITH(NOLOCK)
														where DT.SaleId = DATA_Transaction.SaleId
														  and DT.TransactionType in (12, 15)
													)
				  and data_saleitem.saleitemid in (select saleitemid
														from (select PaidTransactionId,
																	saleitemid,
																	transactiontype,
																	abs(data_saleitem.quantity) quantity,
																	(select count(*)
																		from data_saleitem2ticket WITH(NOLOCK)
																		where data_saleitem2ticket.saleitemid = data_saleitem.saleitemid) TicketCount

															from data_saleitem WITH(NOLOCK)
																inner join DATA_Sale  WITH(NOLOCK)					on data_sale.saleid = data_saleitem.saleid
																inner join DATA_Transaction  WITH(NOLOCK)			on data_transaction.transactionid = DATA_Sale.PaidTransactionId

															where data_sale.Encoded = 1
																and data_saleitem.ProductType = 1
																and data_sale.StatusCode = 1
																and data_transaction.transactiontype not in (5)
															--	and data_transaction.transactionid in (select transactionid from data_payment WITH(NOLOCK) where data_payment.TransactionId = DATA_Transaction.transactionid and data_payment.paymentstatus = 1 and data_payment.paymentamount &amp;#60;&amp;#62; 0)
														)p
														where quantity &amp;#60;&amp;#62; ticketcount
													)
						and data_sale.saleid in (
								select saleid
									from(
									select data_transaction.saleid, sum(paymentamount)Paymentamount, ISNULL((select sum(discountamount)
																										from data_saleitem WITH(NOLOCK)
																											inner join DATA_SaleItemRule WITH(NOLOCK)				on data_saleitemrule.saleitemid = data_saleitem.saleitemid
																											where data_saleitem.saleid = data_transaction.saleid
																											and data_saleitem.ItemTransactionType = 5
																									group by data_saleitem.saleid
																									having sum(discountamount) &amp;#60;&amp;#62; 0), 0)DiscountAmount
																from data_transaction WITH(NOLOCK)
																	INNER JOIN data_payment WITH(NOLOCK)					on data_payment.transactionid = data_transaction.transactionid
																where data_transaction.saleid = data_sale.saleid
																	and data_payment.PaymentStatus = 1
																	and data_transaction.transactiontype not in (5, 30)
																group by data_transaction.saleid
								)p
								where (Paymentamount + Discountamount) &amp;#60;&amp;#62; 0

								)
		UNION ALL
select distinct 
				         @DepositCOAAccountId as COAAccountId,
						@DepositRRRId as RevenueRecognitionRuleId,
						@DepositRRCalcTypeWhere as RRCalcTypeWhere,
						@DepositRRCalcTypeMethod as RRCalcTypeMethod,
						@DepositCOAAccountConfigId as COAAccountConfigId,
						@DepositCOAAccountTypeId as COAAccountType,
						data_transaction.transactionid, 
						data_transaction.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						data_transaction.Siteid,
						data_transaction.OperatingAreaId,
						data_transaction.Workstationid,
						data_transaction.UserGroupid,
						data_transaction.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@DepositPrice as Depositprice,
						@DepositCOAAccount_Percentage as percentage,
						@DepositRemainingValues as remainingValues,
						ISNULL((case when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
													then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
						     when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; 0  
							   						then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 
							 
							 
							 
							 
							 
							 
							 
							 
							else ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
														from data_saleitemrule WITH(NOLOCK)
															LEFT  JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															LEFT  JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															LEFT  JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 

							end), 0) as Revenueamount,
						case when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @DepositRRCOAAccountingType 
						 end Accountingtype,
						@DepositRRCalcTypeTrigger as rrTrigger,
						@DepositPercentage as suspercentage,
						@DepositDays as Depositday,
						null Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = data_sale.voidtransactionid
					left  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					left  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid	
										--where DATA_Ticket.VoidType not in (104, 125)
											)data_ticket
								on data_ticket.saleitemid = ISNULL(data_saleitem.origSAleitemid, data_saleitem.saleitemid ) 
									and 1 = case when data_transaction.transactiontype in (5) and data_ticket.OperationType in (1, 2, 11)  then 1																							 
												 else 0
										     end  

				where DATA_Sale.Paid = 1
				  and DATA_Sale.Encoded = 1
				  and DATA_SaleItem.Quantity &amp;#60;&amp;#62; 0
				  and data_transaction.TransactionType IN (5)
				  and data_saleitem.ItemTransactionType IN (5)					
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactionstatus in (5, 30, 35)
				  and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				  and ((data_transaction.transactionid in (select transactionid
														  from data_payment WITH(NOLOCK)
														 where PaymentStatus = 1
														   and data_transaction.transactionid = DATA_Payment.transactionid
														)))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)))
				and DATA_Transaction.saleid in (select DT.saleid
														from DATA_Transaction DT WITH(NOLOCK)
														  where DT.saleid = DATA_Transaction.saleid
															and TransactionType in (12, 15))
				and DATA_Transaction.TransactionId &amp;#60;&amp;#62; DATA_Sale.paidtransactionid
			
		)p  
		where RevenueAmount &amp;#60;&amp;#62; 0

												
----Reversing the payment method for installment billing.  When ticket 79425 if done we should be able to remove this section.	
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleitemRuleid]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select  coaaccountid,
				RRID,
				TypeWhere,
				method,
				Configid,
				AccountType,
				transactionid, 
				SaleitemRuleid,
				saleid,
				Siteid,
				OperatingAreaId,
				WorkstationID,
				UserGroupid,
				UserId,
				BatchDate,
				Qty,
				Gross,
				net,
				price,
				percentage,
				RemaningValue,
				ISNULL(sum(abs(RevenueAmount)), 0),
				Accountingtype,
				TypeTrigger,
				PaymentPercentage,
				RRDays
		  from (
				select  coaaccountid,
						RRID,
						TypeWhere,
						method,
						Configid,
						AccountType,
						transactionid,
						1 saleitemruleid,
						saleid,
						Siteid,
						OperatingAreaId,
						WorkstationID,
						UserGroupid,
						UserId,
						BatchDate,
						Qty,
						Gross,
						net,
						price,
						percentage,
						RemaningValue,
						(TotalPaid - payment) RevenueAmount,
						Accountingtype,
						TypeTrigger,
						PaymentPercentage,
						RRDays
				  from (
						select distinct	@PaymentCOAAccountId as coaaccountid,
								@PaymentRRRId as RRID,
								@PaymentRRCalcTypeWhere as TypeWhere,
								@PaymentRRCalcTypeMethod as method,
								@PaymentCOAAccountConfigId as Configid,
								@PaymentCOAAccountTypeId as AccountType,
								case when (ABS(data_payment.paymentamount) &amp;#62; ISNULL(Item.feeamount, PF.feeamount)) then  ISNULL((Item.Amount), (PF.Amount) )
								     else ISNULL((Item.Amount- Item.feeamount), (PF.Amount - PF.feeamount) ) 
								 end as amount, 
								ISNULL(Item.refundablefeeamount, PF.refundablefeeamount)  feeamount,
								data_transaction.transactionid,
								data_transaction.saleid,
								data_transaction.siteid, 
								data_transaction.OperatingAreaId,
								data_transaction.Workstationid,
								data_transaction.UserGroupid,
								data_transaction.UserId,
								@BatchDate as BatchDate,
								0 as Qty,
								0 as Gross,
								0 as net,
								0 as price,
								100 as percentage,
								0 as RemaningValue,
								 ISNULL((select SUM(PaymentAmount) 
																						from data_payment WITH(NOLOCK) 
																					   where data_payment.paymentstatus = 1
																					     and DATA_Payment.TransactionId in (select TransactionId
																						                                      from DATA_Transaction DT
																															  where DT.SaleId = data_transaction.SaleId)
																					     and data_payment.paymentmethodid in (select top 1 PAYMENTMETHODID															
																																from  CNF_PaymentMethod WITH(NOLOCK)	
																																	inner join cnf_dRIVER WITH(NOLOCK)				ON CNF_DRIVER.DRIVERID = CNF_PAYMENTMETHOD.DRIVERID
																																WHERE CNF_DRIVER.dRIVERak = 'TPayTpFlex'
																																	and CNF_PaymentMethod.enabled = 1
																															 )
																					 ), 0)
																					
								 TotalPaid,
								2 Accountingtype,
								@PaymentRRCalcTypeTrigger as TypeTrigger,
								@PaymentPercentage as PaymentPercentage,
								@PaymentDays as RRDays,
								max(Item.saleitemid) SaleitemID,
								data_transaction.Change,
								ISNULL((select sum(paymentamount)
									from DATA_Payment WITH(NOLOCK)
									where DATA_Payment.TransactionId in (select DT.TransactionId 
									                                       from DATA_Transaction DT WITH(NOLOCK) 
																		  where DT.SaleId = DATA_Transaction.saleid and TransactionType in (33)) 
									and data_payment.paymentstatus = 1	
								), 0) as payment

							from data_transaction WITH(NOLOCK)
								LEFT  JOIN (select max(data_saleitem.saleitemid) Saleitemid,
								                   DATA_PaymentFlex.flexcontractID,
												   DATA_PaymentFlex.feeamount,
												   (DATA_PaymentFlex.Amount + DownpaymentAmount) Amount,
												   data_paymentflex.refundablefeeamount,
												   data_saleitem.saleid,
												   DATA_PaymentFlex.Paymentid
												 

								              from  data_saleitem WITH(NOLOCK)	
													LEFT  JOIn data_Paymentflex2saleitem WITH(NOLOCK)		on data_Paymentflex2saleitem.saleitemid = data_saleitem.saleitemid
													LEFT  JOIN DATA_PaymentFlex WITH(NOLOCK)				on data_paymentflex.paymentid = data_Paymentflex2saleitem.paymentid

												where DATA_PaymentFlex.Amount is not null
												
											  group by   DATA_PaymentFlex.flexcontractID,
												   DATA_PaymentFlex.feeamount,
												   DATA_PaymentFlex.Amount,
												   data_paymentflex.refundablefeeamount,
												   data_saleitem.saleid,
												   DATA_PaymentFlex.Paymentid,
												   DownpaymentAmount
											)Item						ON Item.saleid = data_transaction.saleid
								LEFT  JOIN CNF_FlexContract WITH(NOLOCK)				on cnf_flexContract.FlexContractId = ITEM.flexcontractID
								LEFT  JOIn data_transaction DT WITH(NOLOCK)				on DT.saleid = data_transaction.saleid and DT.transactiontype in (9, 14, 16)
								LEFT  JOIN data_payment WITH(NOLOCK)					on data_payment.transactionid = DT.transactionid
																							and data_payment.paymentmethodid in (select Paymentmethodid
																																   from CNF_PaymentMethod
																																   where DriverId in (select driverID
																																                        from CNF_Driver
																																						where DriverAk = 'TPayTpFlex'
																																					)
																																 )
								LEFT  JOIN data_payment RevPayment WITH(NOLOCK)			on RevPayment.transactionid = data_transaction.transactionid
																							
								LEFT  JOIN DATA_PaymentFlex PF WITH(NOLOCK)				on PF.paymentid = data_payment.paymentid
								LEFT  JOIN CNF_FlexContract CF WITH(NOLOCK)				on CF.FlexContractId = PF.flexcontractID 

						  where data_transaction.transactiontype in (46, 47)
						     and data_transaction.transactiontype &amp;#60;&amp;#62; 6
							 and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
									
						group by    ITEM.Amount,
									data_transaction.transactionid,
									ITEM.Paymentid,
									data_transaction.saleid,
									data_transaction.siteid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									data_transaction.TransactionDate,
									data_transaction.fTransactionDate,
									data_transaction.Change,
									data_transaction.transactiontype,
									ITEM.refundablefeeamount,
									ITEM.feeamount,
									PF.Amount,
									PF.feeamount,
									PF.refundablefeeamount,
									PF.Paymentid,
									data_payment.PaymentAmount,
									RevPayment.paymentID
						)p
				)r
		group by 	coaaccountid,
					RRID,
					TypeWhere,
					method,
					Configid,
					AccountType,
					transactionid, 
					saleid,
					Siteid,
					OperatingAreaId,
					Workstationid,
					UserGroupid,
					UserId,
					BatchDate,
					Qty,
					Gross,
					net,
					price,
					percentage,
					RemaningValue,
					Accountingtype,
					TypeTrigger,
					PaymentPercentage,
					RRDays,
					SaleitemRuleid
		Having sum(abs(RevenueAmount)) &amp;#60;&amp;#62; 0
		
		

----Taxes 
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[Saleitemid]
								,[Matrixcellid]
								,[Ticketid]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[AttributeIDs]
								,[SaleitemtaxID])
								select distinct coaid,
								       rrid,
									   rrWhere,
									   rrmethod,
									   configid,
									   typeid,
									   transactionid,
									   saleid,
									   siteid,
									   saleitemid,
									   matrixcellid,
									   ticketid,
									   operatingareaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   quantity,
									   grossamount,
									   netamount,
									   price,
									   perc,
									   rmvvalues,
									   ISNULL(revenueamount, 0) revenueamount,
									   accountingtype,
									   rrtrigger,
									   taxperc,
									   days,
									   Attributes,
									   SaleitemTaxID
								from (	
								select distinct @TaxCOAAccountId as coaid,
										@TaxRRRId as rrid,
										@TaxRRCalcTypeWhere as rrWhere,
										@TaxRRCalcTypeMethod as rrmethod,
										@TaxCOAAccountConfigId as configid,
										@TaxCOAAccountTypeId as typeid,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_saleitem.saleitemid,
										data_saleitem.matrixcellid,
										null as ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 Quantity,
										0 Grossamount,
										0 NetAmount,
										0 Price,
										100 Perc,
										0 RMVValues,
										ABS(DATA_SaleItemTax.taxamount * data_saleitem.quantity)  revenueamount,
										case when DATA_SaleItem.Quantity &amp;#62; 0 then 2
										     else 1										         
									    end Accountingtype,
										@TaxRRCalcTypeTrigger as rrtrigger,
										@TaxPercentage as taxperc,
										@TaxDays as days,
										null Attributes,
										data_saleitemtax.saleitemtaxid
		   
							from Data_Sale WITH(NOLOCK)
								inner join data_transaction WITH(NOLOCK)					on data_transaction.transactionid = DATA_Sale.PaidTransactionId
								inner join DATA_SaleItem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid
								inner join DATA_SaleItemTax WITH(NOLOCK)					on data_saleitemtax.saleitemid = data_saleitem.saleitemid
								inner JOIN CNF_Tax WITH(NOLOCK)								on cnf_tax.taxid = data_saleitemtax.taxid

							where data_transaction.TransactionType not IN (5, 30, 33, 45, 12, 15, 46, 47)
							  and DATA_SaleItem.ItemTransactionType not IN (5, 30, 33, 45, 12, 15, 46, 47)
							  and 1 = case when data_transaction.transactiontype in (9, 14, 16, 38, 119) and data_saleitem.quantity &amp;#62; 0 then 1
							               when data_transaction.transactiontype in (18, 20, 22, 123) and data_saleitem.quantity &amp;#60; 0 then 1
										   when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9, 119) then 1
										   when (transactiontype = 4) and (DATA_SaleItem.producttype = 6) then 1
										   when data_transaction.transactiontype in (7)  then 1
							             else 0
									end 
							   and Data_Sale.paid = 1
							   and DATA_SaleItem.Quantity &amp;#60;&amp;#62; 0
							   and transactionstatus in (5, 30, 35)
							   and DATA_SaleItem.TotalTaxes &amp;#60;&amp;#62; 0
							   and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							   and data_transaction.transactionid in (select distinct transactionid
								                                           from data_payment WITH(NOLOCK)
																		   where data_payment.paymentstatus = 1
																			UNION ALL
																			select transactionid
																			from data_transaction
																			where transactiontype = 7
																				and saleid  in (select saleid
																								from data_saleitem WITH(NOLOCK)
																									inner join data_saleitemrule WITH(NOLOCK)				ON data_saleitemrule.saleitemid = data_saleitem.saleitemid
																								where data_saleitemrule.Code = 'Flat Upgrade Discount'
																							)
																		)
								and ((DATA_SaleItem.SaleItemId in (select SaleItemId
																	 from DATA_TransactionItem WITH(NOLOCK)
																			inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
																	where DATA_TransactionItem.TransactionId in (select TransactionId
																													from DATA_Transaction DT WITH(NOLOCK)
																												  where DT.saleid = DATA_Transaction.saleid
																												)
																	)) or (DATA_SaleItem.SaleItemId is null))

							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate,
												DATA_SaleItem.totalamount,
												data_saleitem.saleitemid,
												data_saleitem.matrixcellid,
												cnf_tax.taxid,
												data_sale.StatusCode,
												DATA_Sale.saleid,
												DATA_SaleItem.producttype,
												DATA_SaleItem.OrigSaleItemID,
												taxamount,
												data_saleitemtax.saleitemtaxid,
												data_transaction.transactionstatus,
												data_saleitem.ProductTaxType,
												DATA_SaleItem.Quantity


								UNION ALL

								select distinct @TaxCOAAccountId as coaid,
										@TaxRRRId as rrid,
										@TaxRRCalcTypeWhere as rrWhere,
										@TaxRRCalcTypeMethod as rrmethod,
										@TaxCOAAccountConfigId as configid,
										@TaxCOAAccountTypeId as typeid,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_saleitem.saleitemid,
										data_saleitem.matrixcellid,
										null as ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 Quantity,
										0 Grossamount,
										0 NetAmount,
										0 Price,
										100 Perc,
										0 RMVValues,
										ABS(DATA_SaleItemTax.taxamount * data_saleitem.quantity) revenueamount,
										case when DATA_SaleItem.Quantity &amp;#62; 0 then 2
										     else 1										         
									    end Accountingtype,
										@TaxRRCalcTypeTrigger as rrtrigger,
										@TaxPercentage as taxperc,
										@TaxDays as days,
										null Attributes,
										data_saleitemtax.saleitemtaxid
		   
							from Data_Sale WITH(NOLOCK)
								inner join data_transaction WITH(NOLOCK)					on data_transaction.transactionid =  data_sale.voidtransactionid
								left join DATA_SaleItem WITH(NOLOCK)						on data_saleitem.saleid = data_sale.saleid								
								left join DATA_SaleItemTax WITH(NOLOCK)						on data_saleitemtax.saleitemid = data_saleitem.saleitemid
								left JOIN CNF_Tax WITH(NOLOCK)								on cnf_tax.taxid = data_saleitemtax.taxid

							where  data_transaction.TransactionType IN (5, 30)
							  and 1 = case when data_transaction.transactiontype in (5, 30)  and data_saleitem.ItemTransactionType IN (5, 30) then 1
							             else 0
									end 
							   and Data_Sale.paid = 1
							   and DATA_SaleItem.Quantity &amp;#60;&amp;#62; 0
							   and transactionstatus in (5, 30, 35)
							   and DATA_SaleItem.TotalTaxes &amp;#60;&amp;#62; 0
								and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								  and data_transaction.transactionid in (select distinct transactionid
								                                           from data_payment WITH(NOLOCK)
																		   where data_payment.paymentstatus = 1
																			UNION ALL
																			select transactionid
																			from data_transaction
																			where transactiontype = 7
																				and saleid  in (select saleid
																								from data_saleitem WITH(NOLOCK)
																									inner join data_saleitemrule WITH(NOLOCK)				ON data_saleitemrule.saleitemid = data_saleitem.saleitemid
																								where data_saleitemrule.Code = 'Flat Upgrade Discount'
																							)
																		)
								and ((DATA_SaleItem.SaleItemId in (select SaleItemId
																	 from DATA_TransactionItem WITH(NOLOCK)
																			inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
																																			--and DATA_Transaction.TransactionStatus in (5, 30)
																	where DATA_TransactionItem.TransactionId in (select TransactionId
																													from DATA_Transaction DT WITH(NOLOCK)
																												  where DT.saleid = DATA_Transaction.saleid
																												)
																	)) or (DATA_SaleItem.SaleItemId is null))
							and data_sale.saleid in (
								select saleid
									from(
									select data_transaction.saleid, sum(paymentamount)Paymentamount, ISNULL((select sum(discountamount)
																										from data_saleitem WITH(NOLOCK)
																											inner join DATA_SaleItemRule WITH(NOLOCK)				on data_saleitemrule.saleitemid = data_saleitem.saleitemid
																											where data_saleitem.saleid = data_transaction.saleid
																											and data_saleitem.ItemTransactionType = 5
																									group by data_saleitem.saleid
																									having sum(discountamount) &amp;#60;&amp;#62; 0), 0) DiscountAmount
																from data_transaction WITH(NOLOCK)
																	INNER JOIN data_payment WITH(NOLOCK)					on data_payment.transactionid = data_transaction.transactionid
																where data_transaction.saleid = data_sale.saleid
																	and data_payment.PaymentStatus = 1
																	and data_transaction.transactiontype not in (5, 30)
																group by data_transaction.saleid
								)p
								where (Paymentamount + Discountamount) &amp;#60;&amp;#62; 0

								)

							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate,
												DATA_SaleItem.totalamount,
												data_saleitem.saleitemid,
												data_saleitem.matrixcellid,
												cnf_tax.taxid,
												data_sale.StatusCode,
												DATA_Sale.saleid,
												DATA_SaleItem.producttype,
												DATA_SaleItem.OrigSaleItemID,
												taxamount,
												data_saleitemtax.saleitemtaxid,
												data_transaction.transactionstatus,
												data_saleitem.ProductTaxType,
												DATA_SaleItem.Quantity


								UNION ALL

								select distinct @TaxCOAAccountId as coaid,
										@TaxRRRId as rrid,
										@TaxRRCalcTypeWhere as rrWhere,
										@TaxRRCalcTypeMethod as rrmethod,
										@TaxCOAAccountConfigId as configid,
										@TaxCOAAccountTypeId as typeid,
										data_transaction.transactionid, 
										data_transaction.saleid,
										data_transaction.Siteid,
										data_saleitem.saleitemid,
										data_saleitem.matrixcellid,
										null as ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 Quantity,
										0 Grossamount,
										0 NetAmount,
										0 Price,
										100 Perc,
										0 RMVValues,
										ABS(DATA_SaleItemTax.taxamount * data_saleitem.quantity)  revenueamount,
										case    when @TaxRRCOAAccountingType = 1 then 2
												when @TaxRRCOAAccountingType = 2 then 1
												else @TaxRRCOAAccountingType
									    end Accountingtype,
										@TaxRRCalcTypeTrigger as rrtrigger,
										@TaxPercentage as taxperc,
										@TaxDays as days,
										null Attributes,
										data_saleitemtax.saleitemtaxid
		   
								from Data_Sale WITH(NOLOCK)
								INNER JOIN DATA_Transaction WITH(NOLOCK)					on data_transaction.saleid = Data_Sale.saleid 															                                                     
								left join DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.saleid = data_transaction.saleid
								left join DATA_SaleItemTax WITH(NOLOCK)						on data_saleitemtax.saleitemid = data_saleitem.saleitemid
								left JOIN CNF_Tax WITH(NOLOCK)								on cnf_tax.taxid = data_saleitemtax.taxid

							where transactiontype IN (46, 47)
							   and DATA_SaleItem.TotalAmount &amp;#60;&amp;#62; 0
							   and DATA_SaleItem.TotalTaxes &amp;#60;&amp;#62; 0
							   and Data_Sale.paid = 1
							   and DATA_SaleItem.Quantity &amp;#60;&amp;#62; 0
							   and transactionstatus in (5, 30, 35)
							   and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))

							group by 			data_transaction.transactionid, 
												data_transaction.saleid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												Data_Transaction.TransactionDate,
												TransactionType,
												fTransactionDate,
												DATA_SaleItem.totalamount,
												data_saleitem.saleitemid,
												data_saleitem.matrixcellid,
												cnf_tax.taxid,
												data_sale.StatusCode,
												DATA_Sale.saleid,
												DATA_SaleItem.producttype,
												DATA_SaleItem.OrigSaleItemID,
												taxamount,
												data_saleitemtax.saleitemtaxid,
												ABS(DATA_SaleItemTax.taxamount * data_saleitem.quantity)

								--having case when (data_sale.StatusCode &amp;#60;&amp;#62; 1 and sum(DATA_SaleItem.Quantity) &amp;#60; 0)  then 0									
								--		    else sum(taxamount * DATA_SaleItem.Quantity)
								--		end  &amp;#60;&amp;#62; 0
								)p
								where RevenueAmount &amp;#60;&amp;#62; 0


							
	
----Discount
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[Saleitemid]
								,[Ticketid]
								,[Matrixcellid]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[SaleitemRuleID]
								)

							select  @DiscountCOAAccountId,
										@DiscountRRRId,
										@DiscountRRCalcTypeWhere,
										@DiscountRRCalcTypeMethod,
										@DiscountCOAAccountConfigId,
										@DiscountCOAAccountTypeId,
										data_transaction.transactionid, 
										data_transaction.saleid,
										p.Saleitemid,
										p.Ticketid,
										p.Matrixcellid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										0,
										case when PromotionType = 7 then ABS(p.GLAmount) else 0 end,
										case when PromotionType = 7 then ABS(p.GLAmount) else 0 end,
										0,
										100,
										0,
										ISNULL(ABS(p.GLAmount), 0) RevenueAmount,
										
										
										case  	when data_transaction.transactiontype in (18, 20, 22) and promotiontype IN (301) and p.Quantity &amp;#60; 0 then 2
												
												when data_transaction.transactiontype     in (5, 18, 20, 22, 30, 123) and promotiontype IN (3, 5, 6, 7, 10, 200) then 1
												when data_transaction.transactiontype not in (5, 7, 18, 20, 22, 30, 123) and promotiontype IN (3, 5, 6, 7, 10, 200) then 2

												when data_transaction.transactiontype in (5, 18, 20, 22, 30, 123) then 2

												when data_transaction.transactiontype     in (7) and promotiontype IN (3, 5, 6, 7, 10, 200) and p.Quantity &amp;#62; 0  then 2
												when data_transaction.transactiontype not in (7) and promotiontype IN (3, 5, 6, 7, 10, 200) and p.Quantity &amp;#62; 0  then 1

												when data_transaction.transactiontype not in (7, 14, 16) and promotiontype IN (1, 2, 6, 100, 101, 301) and p.Quantity &amp;#60; 0 then 2
												when data_transaction.transactiontype not in (7, 14, 16) and promotiontype IN (1, 2, 6, 100, 101, 301) and p.Quantity &amp;#62; 0 then 1


												
												when data_transaction.transactiontype in (7) and p.Quantity &amp;#62; 0 and PromotionType in (1) then 1
												when data_transaction.transactiontype in (7) and p.Quantity &amp;#60; 0 and PromotionType in (1) then 2

												when data_transaction.transactiontype in (7) and p.Quantity &amp;#62; 0 and PromotionType in (3) then 2
												when data_transaction.transactiontype in (7) and p.Quantity &amp;#60; 0 and PromotionType in (3) then 1

											    when data_transaction.transactiontype in (7) and p.Quantity &amp;#62; 0 and PromotionType not IN (3, 101) then 1
												when data_transaction.transactiontype in (7) and p.Quantity &amp;#60; 0 and PromotionType not IN (3, 101) then 2

												when data_transaction.transactiontype in (7) and p.Quantity &amp;#62; 0  and discountamount &amp;#60; 0 and PromotionType IN (101) then 1

												when data_transaction.transactiontype in (7) and GLAmount &amp;#62; 0  and PromotionType IN (101) then 1
												when data_transaction.transactiontype in (7) and GLAmount &amp;#60; 0  and PromotionType IN (101) then 2

												when data_transaction.transactiontype in (122) and p.Quantity &amp;#60; 0  and PromotionType IN (4) then 2

												when (discountamount) &amp;#62; 0 then 2
												when (glamount)       &amp;#62; 0 then 1
												else @DiscountRRCOAAccountingType
									    end Accountingtype,										
										@DiscountRRCalcTypeTrigger,
										@DiscountPercentage,
										@DiscountDays,
										SaleitemRuleID
							FROM
							(
								SELECT distinct DATA_SaleItem.Saleitemid,
												case when CNF_Promotion.PromotionType = 7 then DATA_SaleItem.matrixcellid else null end as matrixcellid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE data_transaction.saleid = DATA_Sale.saleid
													AND data_transaction.transactiontype in (14, 16, 7)
													AND data_transaction.paid = 1
												) AS tester,
												Null as ticketid,
												DATA_Transaction.Transactionid, 


												CASE WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price &amp;#60;&amp;#62; 0 and max(data_saleitemrule.perc) &amp;#60;&amp;#62; 0 then ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))  
												      WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price &amp;#60;&amp;#62; DATA_SaleItem.UnitPrice then ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))  
													  WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price &amp;#60;&amp;#62; 0 THEN  ((CNF_MatrixCell.Price) * ISNULL(DATA_SaleItem.Quantity, 1))
												      WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price = 0 THEN ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))
													   
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount/case when DATA_SaleItemRule.ApplyToQty = 0 then 1
													                                                              else DATA_SaleItemRule.ApplyToQty
																											  end) &amp;#60; 0 AND transactiontype IN (20, 22, 30, 7, 5, 40, 46, 47) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 	
																
																	  THEN Sum(case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end * ABS(DATA_SaleItemRule.DiscountAmount)/case when DATA_SaleItemRule.ApplyToQty = 0 then 1
																																											   else DATA_SaleItemRule.ApplyToQty
																																											end)	
																  when CNF_Promotion.PromotionType IN (1) and DATA_SaleItem.UnitPrice = 0 and DATA_SaleItem.UnitTaxes &amp;#60;&amp;#62; 0 then sum((Data_SaleItemRule.DiscountAmount - DATA_SaleItem.UnitTaxes) * case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end)
																  when CNF_Promotion.PromotionType IN (1) and DATA_SaleItem.Unitrawprice = 0 and DATA_SaleItem.UnitPrice &amp;#60;&amp;#62; 0 and DATA_SaleItem.UnitTaxes &amp;#60;&amp;#62; 0 then sum((Data_SaleItemRule.DiscountAmount - DATA_SaleItem.UnitTaxes) * case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end)
															--	  when CNF_Promotion.PromotionType IN (1) and DATA_SaleItem.Unitrawprice = 0 and DATA_SaleItem.UnitPrice &amp;#60;&amp;#62; 0 and DATA_SaleItem.UnitTaxes &amp;#60;&amp;#62; 0 then sum((Data_SaleItemRule.DiscountAmount - DATA_SaleItem.UnitTaxes) * case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end)
																  ELSE sum(Data_SaleItemRule.DiscountAmount * case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end)
															END
												END AS GLAmount,
												CNF_Promotion.PromotionType,
												CNF_PromotionItemRule.NewProduct,
												DATA_SaleItemRule.discountamount/case when DATA_SaleItemRule.ApplyToQty = 0 then 1
																					  else DATA_SaleItemRule.ApplyToQty * case when DATA_SaleItem.Quantity &amp;#60;0 then -1
																					                                           else 1
																															end
																				  end as discountamount,
										        DATA_SaleItemRule.saleitemruleid,
												DATA_SaleItem.quantity

								FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
									LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
									LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
									LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID 
									LEFT JOIN DATA_Transaction		    WITH (NOLOCK) ON DATA_Transaction.TransactionId = data_sale.paidtransactionid
									LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
								WHERE  DATA_Sale.Paid = 1
								  and DATA_Transaction.Transactiontype not in (5, 30, 12, 15, 33, 45, 46, 47, 115) 
								  and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0
								  and data_saleitemrule.ApplyToQty &amp;#60;&amp;#62; 0								  
								  and data_transaction.transactionstatus in (5, 30, 35)
								  and (((data_transaction.transactionstatus in (30, 35)) and (DATA_SaleItem.ItemTransactionType = DATA_Transaction.TransactionType)) or (DATA_Transaction.TransactionStatus = 5) or ((data_transaction.transactiontype in (122)) and (DATA_SaleItem.ItemTransactionType in (5, 14, 16, 7))))								 								  
								  and  ((@RRTransDateType = 0 and DATA_Transaction.fTransactionDate = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, DATA_Transaction.TransactionDate) = @BatchDate)
										or (data_transaction.approved = 1 and data_transaction.paid = 0))
								   and ((DATA_Transaction.saleid in (
																	SELECT ff.saleid 
																	  FROM DATA_Transaction ff WITH (NOLOCK) 
																		inner JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																	 WHERE  ((@RRTransDateType = 0 and ff.fTransactionDate = @BatchDate)
																		OR (@RRTransDateType = 1 and convert(date, ff.TransactionDate) = @BatchDate))
																	   AND ((DATA_PAyment.PaymentStatus NOT in (0,2,3)) or (data_payment.paymentid is null)) 
																	   AND (TransactionType not in (12, 15)) 
																	   AND ff.PAid = 1
																	   and ff.SaleId = DATA_Transaction.saleid
																	     --and PaymentAmount &amp;#60;&amp;#62; 0
																 )) or ((data_transaction.transactiontype in (7)) and (data_transaction.Revenue = 0)) )
								 and data_transaction.TotalAmount = case when transactiontype = 5 then data_transaction.Revenue
								                                         else data_transaction.TotalAmount 
																	end 
								 AND (((DATA_SaleItem.quantity &amp;#62; 0) AND (transactiontype NOT IN (18, 20, 22, 30, 5, 40, 46, 47, 40, 123)) )
								        OR ((DATA_SaleItem.quantity &amp;#60; 0) AND (transactiontype IN (4, 18, 20, 22, 30, 7, 5, 40, 46, 47, 40, 122, 123))))
								and 1 = case when data_transaction.transactiontype = 7 and ISNULL(data_transaction.saleid, 0) in (select saleid
																																		from data_transaction DTT
																																		where DTT.saleid in (
																																							select saleid
																																								from data_transaction DT
																																							where DT.transactiontype = 30
																																							  and dt.saleid = DATA_Transaction.saleid
																																						))
																			          and data_saleitem.ItemTransactionType = 7
											then 1
											when data_transaction.transactiontype = 7 and ISNULL(data_transaction.saleid, 0) in (select saleid
																																		from data_transaction
																																		where saleid in (
																																							select saleid
																																								from data_transaction
																																							where transactiontype = 30
																																						))																					
																					and data_saleitem.ItemTransactionType &amp;#60;&amp;#62; 7
											then 0
											else 1
											end
         
								group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 DATA_SaleItem.Quantity,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_DmgCategory.DmgCategoryCode,
										 CNF_Promotion.PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_DmgCategory.Description,
										 DATA_SaleItemRule.discountamount,
										 DATA_SaleItemRule.saleitemruleid,
										 data_saleitem.Itemticketid, 
										 data_saleitem.Ticketid,
										 DATA_SaleItemRule.ApplyToQty,
										 DATA_SaleItem.UnitPrice,
										 data_saleitem.UnitTaxes,
										 data_saleitemrule.PromotionType,
										 data_saleitemrule.price,
										 data_saleitem.UnitRawPrice,
										 data_transaction.transactionstatus,
										 data_sale.StatusCode 

							UNION ALL

							SELECT distinct DATA_SaleItem.Saleitemid,
												case when CNF_Promotion.PromotionType = 7 then DATA_SaleItem.matrixcellid else null end as matrixcellid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE saleid = DATA_Sale.saleid
													AND transactiontype in (14, 16, 7)
													AND paid = 1
												) AS tester,
												Null as ticketid,
												DATA_Transaction.Transactionid, 
												CASE WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price &amp;#60;&amp;#62; 0 and max(data_saleitemrule.perc) &amp;#60;&amp;#62; 0 then ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))  
												      WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price &amp;#60;&amp;#62; DATA_SaleItem.UnitPrice then ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))  
													  WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price &amp;#60;&amp;#62; 0 THEN  ((CNF_MatrixCell.Price) * ISNULL(DATA_SaleItem.Quantity, 1))
												      WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 and DATA_SaleItemRule.DiscountAmount &amp;#60;&amp;#62; 0 and CNF_MatrixCell.Price = 0 THEN ((DATA_SaleItem.UnitPrice - data_saleitem.UnitTaxes ) * ISNULL(DATA_SaleItem.Quantity, 1))
													   
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount/case when DATA_SaleItemRule.ApplyToQty = 0 then 1
													                                                              else DATA_SaleItemRule.ApplyToQty
																											  end) &amp;#60; 0 AND transactiontype IN (20, 22, 30, 7, 5, 40, 46, 47) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 	
																
																	  THEN Sum(case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end * ABS(DATA_SaleItemRule.DiscountAmount)/case when DATA_SaleItemRule.ApplyToQty = 0 then 1
																																											   else DATA_SaleItemRule.ApplyToQty
																																											end)		            	                  
																 ELSE sum(Data_SaleItemRule.DiscountAmount * case when DATA_SaleItem.Quantity &amp;#60; 0 then -1 else 1 end)
															END
												END AS GLAmount,
												CNF_Promotion.PromotionType,
												CNF_PromotionItemRule.NewProduct,
												DATA_SaleItemRule.discountamount/case when DATA_SaleItemRule.ApplyToQty = 0 then 1
																					  else DATA_SaleItemRule.ApplyToQty * case when DATA_SaleItem.Quantity &amp;#60;0 then -1
																					                                           else 1
																															end
																				  end as discountamount,
										        DATA_SaleItemRule.saleitemruleid,
												DATA_SaleItem.quantity






								FROM dbo.DATA_SaleItemRule				WITH (NOLOCK)
									LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN dbo.CNF_DmgCategory		WITH (NOLOCK) ON CNF_DmgCategory.DmgCategoryId = CNF_Promotion.DmgCategoryId
									LEFT JOIN dbo.DATA_SaleItem			WITH (NOLOCK) ON DATA_SaleItem.SaleItemId = DATA_SaleItemRule.SaleItemId
									LEFT JOIN dbo.DATA_Sale				WITH (NOLOCK) ON DATA_Sale.SaleID = DATA_SaleItem.SaleID 
									LEFT JOIN DATA_Transaction		    WITH (NOLOCK) ON DATA_Transaction.TransactionId = ISNULL(data_sale.voidTransactionId, data_sale.paidtransactionid)
									LEFT JOIN CNF_MatrixCell			WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId

 
								WHERE  DATA_Sale.Paid = 1
								  and DATA_Transaction.Transactiontype in (5, 30) 
								  and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0
								  and data_saleitemrule.ApplyToQty &amp;#60;&amp;#62; 0								  
								  and data_transaction.transactionstatus in (5, 30, 35)
								  and  ((@RRTransDateType = 0 and DATA_Transaction.fTransactionDate = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, DATA_Transaction.TransactionDate) = @BatchDate)
										or (data_transaction.approved = 1 and data_transaction.paid = 0))
								   and ((DATA_Transaction.saleid in (
																	SELECT ff.saleid 
																	  FROM DATA_Transaction ff WITH (NOLOCK) 
																		inner JOIN Data_Payment WITH (NOLOCK) on (ff.Transactionid = Data_Payment.Transactionid) 
																	 WHERE  ((@RRTransDateType = 0 and ff.fTransactionDate = @BatchDate)
																		OR (@RRTransDateType = 1 and convert(date, ff.TransactionDate) = @BatchDate))
																	   AND ((DATA_PAyment.PaymentStatus NOT in (0,2,3)) or (data_payment.paymentid is null)) 
																	   AND (TransactionType not in (12, 15)) 
																	   AND ff.PAid = 1
																	   and ff.SaleId = DATA_Transaction.saleid
																	     --and PaymentAmount &amp;#60;&amp;#62; 0
																 )) or ((data_transaction.transactiontype in (7)) and (data_transaction.Revenue = 0)) )

								 AND (((DATA_SaleItem.quantity &amp;#62; 0) AND (transactiontype NOT IN (18, 20, 22, 30, 5, 40, 46, 47, 40, 123)) )
								        OR ((DATA_SaleItem.quantity &amp;#60; 0) AND (transactiontype IN (4, 18, 20, 22, 30, 7, 5, 40, 46, 47, 40, 122, 123))))
								and data_saleitem.ItemTransactionType in (5, 30)
								and 1 = case when data_transaction.transactiontype = 7 and ISNULL(data_transaction.saleid, 0) in (select saleid
																																		from data_transaction DTT
																																		where DTT.saleid in (
																																							select saleid
																																								from data_transaction DT
																																							where DT.transactiontype = 30
																																							  and dt.saleid = DATA_Transaction.saleid
																																						))
																			          and data_saleitem.ItemTransactionType = 7
											then 1
											when data_transaction.transactiontype = 7 and ISNULL(data_transaction.saleid, 0) in (select saleid
																																		from data_transaction
																																		where saleid in (
																																							select saleid
																																								from data_transaction
																																							where transactiontype = 30
																																						))																					
																					and data_saleitem.ItemTransactionType &amp;#60;&amp;#62; 7
											then 0
											else 1
											end
         
								group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 DATA_SaleItem.Quantity,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_DmgCategory.DmgCategoryCode,
										 CNF_Promotion.PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_DmgCategory.Description,
										 DATA_SaleItemRule.discountamount,
										 DATA_SaleItemRule.saleitemruleid,
										 data_saleitem.Itemticketid, 
										 data_saleitem.Ticketid,
										 DATA_SaleItemRule.ApplyToQty,
										 DATA_SaleItem.UnitPrice,
										 data_saleitem.UnitTaxes,
										 data_saleitemrule.PromotionType,
										 data_saleitemrule.price,
										 data_saleitem.UnitRawPrice,
										 data_transaction.transactionstatus,
										 data_sale.StatusCode 



							)p
								LEFT JOIN data_transaction WITH (NOLOCK) on data_transaction.transactionid = p.transactionid

							WHERE ((p.TransactionType not in (5, 115)) or (Tester is not null))
							  AND data_transaction.transactionid is not null
							  and p.GLAmount &amp;#60;&amp;#62; 0
					


		exec otn_sp_RR_RevenueData_OnEncodedTickets @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnDepositTrigger @BatchDate, @RRTransDateType	
		
		exec otn_sp_RR_RevenueData_BalanceVoidedTickets  @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnSaleTrigger @BatchDate, @RRTransDateType				

		exec otn_sp_RR_RevenueData_OnMoneyCardLoad @BatchDate, @RRTransDateType						

		exec otn_sp_RR_RevenueData_OnMoneyCardCashOut @BatchDate, @RRTransDateType				

		exec otn_sp_RR_RevenueData_OnCreditWriteoff @BatchDate, @RRTransDateType					

		exec otn_sp_RR_RevenueData_OnMoneyRefundTrigger @BatchDate, @RRTransDateType					
		
		exec otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger @BatchDate, @RRTransDateType					
		 		 		
		exec otn_sp_RR_RevenueData_OnFlexContractCancel @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnCreditSettlementTrigger @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_SettleUpSuspendAccount @BatchDate, @RRTransDateType
		 
		exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType, 1
		  
		exec otn_sp_RR_RevenueData_OnTimePeriodTrigger @BatchDate, @RRTransDateType
		  		  
		exec otn_sp_RR_RevenueData_OnUpgradeTrigger @BatchDate, @RRTransDateType
		  
		exec otn_sp_RR_RevenueData_OnTicketUsageTrigger @BatchDate, @RRTransDateType, 7
		 
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '4, 5, 7, 9, 10, 14, 18, 20, 22, 16, 30, 31, 33, 38, 41, 42, 43, 45, 46, 47, 48, 49, 52, 101, 102, 103, 104, 105, 119, 122, 123,',  @RRTransDateType 
	   
	    exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts2 @BatchDate, '6, 8, 12, 13, 15, 34, 116,', @RRTransDateType
		
		exec otn_sp_RR_RevenueData_OnEventTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnTicketExpiredTrigger @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnRefunds @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_SettleUpgradeSuspendAccount @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_OnMoneyCardUsage @BatchDate, @RRTransDateType
		
		exec otn_sp_RR_RevenueData_SplitAmtbyChildren @BatchDate, @RRTransDateType

		exec otn_sp_RR_RevenueData_CompleteFlags @BatchDate

		exec otn_sp_RR_RevenueData_CalculateCOATotals @BatchDate, @RRTransDateType

		FETCH NEXT FROM date_Cursor INTO @BatchDate
	end

	delete from RR_DATA_Revenue where FCalcDate &amp;#62; @ToDate and JournalEntryByAccount &amp;#60;&amp;#62; 0

	CLOSE date_Cursor;
	DEALLOCATE date_Cursor;

End</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>7053542EC1D0419D935FADC0887D3044</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_CalculateCOATotals</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>9</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_CalculateCOATotals]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

		if not exists(select * from RR_Data_Revenue_Totals)
		Begin
			INSERT INTO [dbo].[RR_Data_Revenue_Totals]
					   ([FCalcDate]
					   ,[Siteid]
					   ,[COAAccountID]
					   ,[Debit]
					   ,[Credit])
					select fcalcdate,
					        Siteid,
							coaaccountid,
							sum(debit) as debit,
							sum(credit) as credit
					from (
						select fcalcdate, 
						       Siteid,
								coaaccountid, 
								accountingtype,
								case when accountingtype = 1 then sum(revenueamount)
									else 0 
								end debit,
								case when accountingtype = 2 then sum(revenueamount)
									else 0 
								end Credit
	   
						from rr_data_revenue
						where ISNULL(OOBflag, 0) = 0
						  and ISNULL(forecasted, 0) = 0
						group by fcalcdate, 
									coaaccountid,
									Siteid,
									accountingtype
					)p
					group by fcalcdate,
					         Siteid,
							 coaaccountid

		end
		else
		begin
			INSERT INTO [dbo].[RR_Data_Revenue_Totals]
					   ([FCalcDate]
					   ,[Siteid]
					   ,[COAAccountID]
					   ,[Debit]
					   ,[Credit])
					select fcalcdate,
					       Siteid,
							coaaccountid,
							sum(debit) as debit,
							sum(credit) as credit
					from (
						select fcalcdate, 
							   Siteid,
								coaaccountid, 
								accountingtype,
								case when accountingtype = 1 then sum(revenueamount)
									else 0 
								end debit,
								case when accountingtype = 2 then sum(revenueamount)
									else 0 
								end Credit
	   
						from rr_data_revenue
						where fcalcdate = @BatchDate
						  and  ISNULL(OOBflag, 0) = 0
						  and ISNULL(forecasted, 0) = 0
						group by fcalcdate, 
									Siteid,
									coaaccountid,
									accountingtype

					)p
					group by fcalcdate,
					         Siteid,
							 coaaccountid

	end




END



</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>857093BFBE8C4DF9A00BF40F41393F37</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_CompleteFlags</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>5</Version><SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_CompleteFlags] 
	@BatchDate Date
AS 
BEGIN
SET NOCOUNT ON
select GETDATE()


update RR_DATA_Revenue
   set OOBflag = 0
where FCalcDate = @BatchDate

update rr_data_revenue
   set rr_data_revenue.OOBflag = 1
where TransactionId in (
select TransactionId
from(
		select p1.transactionid,
	   data_transaction.saleid,
	   transactiontype,

	   ftransactiondate,
       round(sum(balance), 4) balance,
	   transactionstatus

from(
				select  Siteid, sitename, RevenueRecognitionDataid,
						RevenueRecognitionRuleid, 
						coaAccountid, 
						rrcode,
						matrixcellid,
						ExternalCode,
      						case when transactionid is not null then 'Tran'
							 else 'Tick'
						end as Type, 
						ISNULL(transactionid, 0) as transactionid,
						coaaccountcode, 
						Debit as debit,
						(Credit) as Credit,
						fcalcdate, 
						RemaningValues,
						AccountingType,
						description,
						ticketid,
						(ISNULL(Debit, 0) - ISNULL(credit, 0)) Balance
				from(
				select rr_data_revenue.Siteid,
					   cnf_site.sitename,
					   RevenueRecognitionDataid,
						   rr_data_revenue.RevenueRecognitionRuleid, 
						   rr_data_revenue.coaAccountid, 
						   RR_CNF_RevenueRecognitionRule.code as rrcode, 
						   rr_data_revenue.transactionid,  
						   COA_CNF_Account.code as coaaccountcode,
						   case when rr_data_revenue.AccountingType = 1 then Convert(decimal(19,4), revenueamount)
								else null
							end Debit,
						   case when rr_data_revenue.AccountingType = 2 then Convert(decimal(19,4), revenueamount)
								else null
							end Credit,
						   fcalcdate, 
						   matrixsheetid, 
						   matrixcellid, 
						   saleitemid, 
						   RemaningValues,
						   COA_CNF_Account.ExternalCode,
						   COA_CNF_AccountConfig.AccountingType,
						   ticketid,
								   CASE when rr_data_revenue.RRCalcTypeTrigger = 2 then 'On Ticket Usage'
										when rr_data_revenue.RRCalcTypeTrigger = 3 then 'Ticket Expiration'
										when rr_data_revenue.RRCalcTypeTrigger = 4 then 'Time Period'
										else CNF_Lookup.Description   
									end description		   
	   
					from rr_data_revenue WITH(NOLOCK)
						LEFT JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK) on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_data_revenue.RevenueRecognitionRuleId 
						LEFT JOIN COA_CNF_AccountConfig	WITH(NOLOCK)	     on COA_CNF_AccountConfig.COAAccountConfigId = rr_data_revenue.COAAccountConfigId
						LEFT JOIN COA_CNF_Account WITH(NOLOCK)				 on COA_CNF_Account.COAAccountId = rr_data_revenue.COAAccountId
						left JOIN DATA_Transaction WITH(NOLOCK)				 on data_transaction.transactionid = rr_data_revenue.transactionid
						left join CNF_LookUp	WITH(NOLOCK)				 on cnf_lookup.itemid = data_transaction.transactiontype and cnf_lookup.lookupTableid = 3
						LEFT JOIN CNF_SITE WITH(NOLOCK)                      on cnf_site.siteid = rr_data_revenue.siteid	
	  
				)p
			)p1
			inner join data_transaction					on data_transaction.transactionid = p1.transactionid
			where FCalcDate = @BatchDate
			group by p1.transactionid,
					 transactiontype,
					 transactionstatus,
					 ftransactiondate,
					 data_transaction.userid,
		 				   data_transaction.saleid

			having ((round(sum(balance), 4) &amp;#62; 0.02) or (round(sum(balance), 4) &amp;#60; -0.02))

		)p6
		
)


update rr_data_revenue
   set rr_data_revenue.Forecasted = 1
where FCalcDate &amp;#62;= CAST(getdate() as date)

end
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>7B8E6653348F4DF88C93B0E5CADAE62C</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>15</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnAdvancedPaymentTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnAdvancePaymentTrigger Integer = 7

	select @SuspendID = COAACCOUNTID
	from COA_CNF_Account
	where Code = 'SUSPENSE'
	and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	from COA_CNF_Account
	where Code = 'TAXES'
	and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	from COA_CNF_Account
	where Code = 'PYMTMETHOD'
	and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	from COA_CNF_Account
	where Code = 'DISCOUNTS'
	and SystemAccount = 1

	BEGIN	

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select *
		  from (
				select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,	   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) 
								      then  
										  Case when p.Price &amp;#62; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											   else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																											  from data_saleitemTax
																											 where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
										   end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								case when DATA_Transaction.Revenue &amp;#60; 0 then 1 
								     else p.Accountingtype
								 end  Accountingtype,
								p.RRCalcTypeTrigger,
								p.rrPercentage,
								p.Days						
						
						
				  from RR_DATA_REVENUE WITH(NOLOCK)
					INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
					INNER JOIN (select '1' as PCOAAccountid, 
										coa_cnf_accountConfig.Siteid, 
										RR_CNF_RevenueRecognitionRule.Enabled, 
										RR_CNF_RevenueRecognitionRule.FromDate, 
										RR_CNF_RevenueRecognitionRule.ToDate,
										COA_CNF_AccountConfig.RemainingValues,
										coa_cnf_account.coaaccountid,
										COA_CNF_AccountConfig.Price,
										COA_CNF_AccountConfig.Percentage,
										RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
										RR_CNF_RevenueRecognitionRule.code,		   
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
										COA_CNF_AccountConfig.COAAccountConfigId,
										coa_cnf_account.COAAccountTypeId,
										coa_cnf_account.Code as accountcode,
										coa_cnf_accountconfig.Accountingtype,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
										RR_CNF_RevenueRecognitionRule.Days	

								  from RR_CNF_RevenueRecognitionRule	WITH(NOLOCK)
										INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
										INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
										INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
								 where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnAdvancePaymentTrigger
								   and RR_CNF_RevenueRecognitionRule.Enabled = 1
								   and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
								) p																	on p.PCOAAccountid = rr_data_revenue.coaaccountid 

				 where transactiontype in (34, 126)													 
				   and p.Enabled = 1
				   and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
				   and @BatchDate between p.FromDate and p.ToDate
				   and p.RemainingValues &amp;#60;&amp;#62; 1
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
			)r 
			where r.revenueAmount &amp;#60;&amp;#62; 0


		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays])
		select *
		 from (
				select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) 
								     then																																													 
										ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
										ISNULL((select ABS(sum(RevenueAmount))
												  from RR_DATA_Revenue rrd WITH(NOLOCK)
												 where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
												   and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												   and rrd.transactionid = RR_DATA_REVENUE.transactionid
												), 0)) 
									else 0
								end RevenueAmount,
								case when DATA_Transaction.Revenue &amp;#60; 0 then 1 
								     else p.Accountingtype
								 end  Accountingtype,
								p.RRCalcTypeTrigger,
								p.rrPercentage,
								p.Days						
												
				  from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN (select '1' as PCOAAccountid, 
											coa_cnf_accountConfig.Siteid, 
											RR_CNF_RevenueRecognitionRule.Enabled, 
											RR_CNF_RevenueRecognitionRule.FromDate, 
											RR_CNF_RevenueRecognitionRule.ToDate,
											COA_CNF_AccountConfig.RemainingValues,
											coa_cnf_account.coaaccountid,
											COA_CNF_AccountConfig.Price,
											COA_CNF_AccountConfig.Percentage,
											RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
											RR_CNF_RevenueRecognitionRule.code,		   
											RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
											RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
											COA_CNF_AccountConfig.COAAccountConfigId,
											coa_cnf_account.COAAccountTypeId,
											coa_cnf_account.Code as accountcode,
											coa_cnf_accountconfig.Accountingtype,
											RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
											RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
											RR_CNF_RevenueRecognitionRule.Days	

									  from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	
											INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
											INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
											INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
									 where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnAdvancePaymentTrigger
									   and RR_CNF_RevenueRecognitionRule.Enabled = 1
									   and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
									) p																	on p.PCOAAccountid = rr_data_revenue.coaaccountid 

				  where transactiontype in (34, 126)													 
					and p.Enabled = 1
					and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
					and @BatchDate between p.FromDate and p.ToDate
					and p.RemainingValues = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate		
		      )r 
		      where r.revenueAmount &amp;#60;&amp;#62; 0

	end
END


</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>AF60740FBDCF4A228B09727D5D6583B4</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnChangeValiditydateTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>12</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnChangeValiditydateTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN


	Declare @ChangeValidityTrigger Integer = 18	
	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1


				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1

		)p
		
			
	BEGIN
		--Normal TicketExpired No Remaining Value
			 	INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[Ticketid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
				   select COA_CNF_AccountConfig.COAAccountId, 
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   p.Ticketid as Ticketid,
												   p.Matrixcellid as Matrixcell,
												   p.MatrixSheetId as MatrixSheetID,
												   p.Siteid as SiteID,
												   @BatchDate as BatchDate,
												   1 as Quantity,
												   0 as GrossAmount,
												   0 as NetAmount,
												   COA_CNF_AccountConfig.Price as ConfigPrice,
												   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
												   COA_CNF_AccountConfig.RemainingValues,									   
												p.RevenueAmount as revenueamount,
									
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage,
												   RR_CNF_RevenueRecognitionRule.Days,
												   p.AttributeIDs

				  from RR_CNF_RevenueRecognitionRule
					   INNER JOIN @Matrixcells MatrixcellID 			ON MatrixcellID.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
					   INNER JOIN COA_CNF_AccountConfig					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
					   INNER JOIN COA_CNF_Account						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
					   INNER JOIN (select	distinct CNF_MatrixCell.matrixcellid, DATA_Ticket.price, DATA_Ticket.rawprice, DATA_Ticket.ticketid, CNF_MatrixCell.AttributeSetId, CNF_AttributeSet.AttributeIDs,
											CNF_MatrixCell.Code, CNF_MatrixCell.MatrixSheetId, DATA_Ticket.siteid, DAta_Ticket.ActiveTo, (data_ticket.price - data_ticket.taxes) NetPrice,
											OldTicket.TicketId OldTicketID, rr_data_revenue.RevenueAmount
											from DATA_Ticket WITH(NOLOCK)
											INNER JOIN CNF_MatrixCell WITH(NOLOCK)					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_AttributeSet	WITH(NOLOCK)				on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
											INNER JOIN DATA_Transaction2Ticket WITH(NOLOCK)			on data_transaction2ticket.ticketid = data_ticket.ticketid
											INNER JOIN DATA_Transaction WITH(NOLOCK)					on data_transaction.transactionid = data_transaction2ticket.transactionid and DATA_Transaction.transactiontype = 115
											INNER JOIN DATA_TransactionItem WITH(NOLOCK)				on Data_TransactionItem.transactionid = data_transaction.transactionid
											INNER JOIN data_Saleitem NewItem WITH(NOLOCK)			on NewItem.saleitemid = Data_TransactionItem.saleitemid
											INNER JOIN data_saleitem OldItem WITH(NOLOCK)			on OldItem.Saleitemid = NewItem.OrigSaleItemId	
											INNER JOIN data_ticket OldTicket WITH(NOLOCK)			on OldTicket.Saleitemid = OldItem.SaleItemid
											INNER JOIN RR_DATA_Revenue					on rr_data_revenue.Ticketid = OldTicket.Ticketid													
										
											where DATA_Ticket.VoidType = 0
											and cast(data_ticket.activeto as date) = @batchDate
									)p  on						(p.matrixcellid   = MatrixcellID.matrixcellid) 
				where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @ChangeValidityTrigger
				  and rr_cnf_revenuerecognitionRule.Enabled = 1
				  and COA_CNF_AccountConfig.Enabled = 1
				)p
				where RevenueAmount &amp;#60;&amp;#62; 0  
	end

END</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>7FC1699A96B04310A1CF776A8499C8C7</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnCreditSettlementTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>20</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnCreditSettlementTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @OnCreditSettlementTrigger Integer = 8

	BEGIN
		--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]				   				 
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
								RevenueRecognitionRuleId,	   
								RRCalcTypeWhere,
								RRCalcTypeMethod,	   
								COAAccountConfigId,
								COAAccountTypeId,
								Transactionid,
								Saleid,
								SiteID,
								OperatingAreaID,
								Workstationid,
								UserGroupID,
								userID,
								BatchDate,
								Quantity,
								GrossAmount,
								NetAmount,
								ConfigPrice,
								ConfigPercentage,
								RemainingValues,
								RevenueAmount,
								    Accountingtype,
									RRCalcTypeTrigger,
									Percentage,
									Days
				   from (
					select distinct COA_CNF_AccountConfig.COAAccountId, 
									COA_CNF_AccountConfig.RevenueRecognitionRuleId,		   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									COA_CNF_Account.COAAccountTypeId,
									COA_CNF_Account.Code as accountcode,
									DATA_Transaction.Transactionid as Transactionid,
									DATA_Transaction.saleid as Saleid,
									DATA_Transaction.Siteid as SiteID,
									DATA_Transaction.OperatingAreaId as OperatingAreaID,
									DATA_Transaction.Workstationid as Workstationid,
									DATA_Transaction.UserGroupid as UserGroupID,
									DATA_Transaction.UserId as userID,
									@BatchDate as BatchDate,
									0 as Quantity,
									0 as GrossAmount,
									0 as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,
									case when data_payment.paymentamount &amp;#60;&amp;#62; 0 then isnull(DATA_Payment.paymentAmount + data_transaction.change, 0) 
											else ISNULL(data_payment.AdvancedPaymentAmount, 0)
										end as RevenueAmount,
									COA_CNF_AccountConfig.Accountingtype accountingtype,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,

									DATA_Payment.paymentid
										
						from DATA_Transaction WITH(NOLOCK)					
							INNER JOIN DATA_Payment	WITH(NOLOCK)						on data_payment.transactionid = DATA_Transaction.transactionid
							Cross Join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					
							Left  Join COA_CNF_AccountConfig WITH(NOLOCK)				on COA_CNF_AccountConfig.RevenueRecognitionRuleID = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleID
							Left  Join COA_CNF_Account WITH(NOLOCK)						on coa_cnf_Account.CoaAccountid = COA_CNF_AccountConfig.coaAccountid

							where DATA_Transaction.transactiontype = 6
							    and COA_CNF_AccountConfig.AccountingType &amp;#60;&amp;#62; 1
								and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditSettlementTrigger
								and RR_CNF_RevenueRecognitionRule.Enabled = 1
								and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
								and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
								and DATA_Transaction.ftransactiondate = @BatchDate					
								and COA_CNF_AccountConfig.enabled = 1
								and DATA_Transaction.TransactionId in (select TransactionId
																			 from DATA_Payment WITH(NOLOCK)
																			where DATA_Payment.TransactionId = data_transaction.TransactionId
																			  and DATA_Payment.PaymentStatus = 1
																			  and (DATA_Payment.PaymentAmount + ISNULL(data_payment.advancedpaymentamount, 0)) &amp;#60;&amp;#62; 0
																		  )
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0

			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]				   				 
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
								RevenueRecognitionRuleId,	   
								RRCalcTypeWhere,
								RRCalcTypeMethod,	   
								COAAccountConfigId,
								COAAccountTypeId,
								Transactionid,
								Saleid,
								SiteID,
								OperatingAreaID,
								Workstationid,
								UserGroupID,
								userID,
								BatchDate,
								Quantity,
								GrossAmount,
								NetAmount,
								ConfigPrice,
								ConfigPercentage,
								RemainingValues,
								RevenueAmount,
								    Accountingtype,
									RRCalcTypeTrigger,
									Percentage,
									Days
				   from (
					select  COA_CNF_AccountConfig.COAAccountId, 
								COA_CNF_AccountConfig.RevenueRecognitionRuleId,		   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								COA_CNF_AccountConfig.COAAccountConfigId,
								COA_CNF_Account.COAAccountTypeId,
								COA_CNF_Account.Code as accountcode,
								DATA_Transaction.Transactionid as Transactionid,
								DATA_Transaction.saleid as Saleid,
								DATA_Transaction.Siteid as SiteID,
								DATA_Transaction.OperatingAreaId as OperatingAreaID,
								DATA_Transaction.Workstationid as Workstationid,
								DATA_Transaction.UserGroupid as UserGroupID,
								DATA_Transaction.UserId as userID,
								@BatchDate as BatchDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								COA_CNF_AccountConfig.Price as ConfigPrice,
								COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								COA_CNF_AccountConfig.RemainingValues,
								case when sum(OLDDP.PaymentAmount) &amp;#60;&amp;#62; 0 then sum(OLDDP.PaymentAmount)
								     else ISNULL(sum(data_payment.AdvancedPaymentAmount), 0)
								 end as RevenueAmount,
								    COA_CNF_AccountConfig.Accountingtype accountingtype,
									--98 accountingtype,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,

									DATA_Payment.paymentid
										
						from DATA_Transaction WITH(NOLOCK)					
							LEFT JOIN DATA_Payment	WITH(NOLOCK)						on data_payment.transactionid = DATA_Transaction.transactionid
							LEFT join DATA_PaymentCredit WITH(NOLOCK)					ON DATA_PaymentCredit.SettleTransactionId = DATA_Transaction.transactionid
							LEFT  JOIN DATA_Payment OLDDP WITH(NOLOCK)					ON OLDDP.PaymentId = DATA_PaymentCredit.paymentID
							Cross Join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					
							Left  Join COA_CNF_AccountConfig WITH(NOLOCK)				on COA_CNF_AccountConfig.RevenueRecognitionRuleID = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleID
							Left  Join COA_CNF_Account WITH(NOLOCK)						on coa_cnf_Account.CoaAccountid = COA_CNF_AccountConfig.coaAccountid

							where (DATA_Transaction.transactiontype = 6)
								and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditSettlementTrigger
								and RR_CNF_RevenueRecognitionRule.Enabled = 1
								and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
								and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
								and DATA_Transaction.ftransactiondate = @BatchDate					
								and COA_CNF_AccountConfig.enabled = 1
								and DATA_Transaction.TransactionId not in (select TransactionId
																			from DATA_Payment WITH(NOLOCK)
																			where DATA_Payment.TransactionId = data_transaction.TransactionId
																			  and DATA_Payment.PaymentStatus = 1
																			  and (DATA_Payment.PaymentAmount + ISNULL(data_payment.advancedpaymentamount, 0)) &amp;#60;&amp;#62; 0
																		)

						 Group by	COA_CNF_AccountConfig.COAAccountId, 
									COA_CNF_AccountConfig.RevenueRecognitionRuleId,		   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									COA_CNF_Account.COAAccountTypeId,
									COA_CNF_Account.Code,
									DATA_Transaction.Transactionid,
									DATA_Transaction.saleid,
									DATA_Transaction.Siteid,
									DATA_Transaction.OperatingAreaId,
									DATA_Transaction.Workstationid,
									DATA_Transaction.UserGroupid ,
									DATA_Transaction.UserId,
									COA_CNF_AccountConfig.Price,
									COA_CNF_AccountConfig.Percentage,
									COA_CNF_AccountConfig.RemainingValues,
									COA_CNF_AccountConfig.Accountingtype,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,
									DATA_Payment.paymentid
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0



	--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select COAAccountId, 
								RevenueRecognitionRuleId,		   
								RRCalcTypeWhere,
								RRCalcTypeMethod,	   
								COAAccountConfigId,
								COAAccountTypeId,
								Transactionid,
								Saleid,
								SiteID,
								OperatingAreaID,
								Workstationid,
								UserGroupID,
								userID,
								BatchDate,
								Quantity,
								GrossAmount,
								NetAmount,
								ConfigPrice,
								ConfigPercentage,
								RemainingValues,
								RevenueAmount,
								    Accountingtype,
									RRCalcTypeTrigger,
									Percentage,
									Days
				   from (
					select distinct COA_CNF_AccountConfig.COAAccountId, 
								COA_CNF_AccountConfig.RevenueRecognitionRuleId,
								COA_CNF_Account.code,		   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								COA_CNF_AccountConfig.COAAccountConfigId,
								COA_CNF_Account.COAAccountTypeId,
								DATA_Transaction.Transactionid as Transactionid,
								DATA_Transaction.saleid as Saleid,
								DATA_Transaction.Siteid as SiteID,
								DATA_Transaction.OperatingAreaId as OperatingAreaID,
								DATA_Transaction.Workstationid as Workstationid,
								DATA_Transaction.UserGroupid as UserGroupID,
								DATA_Transaction.UserId as userID,
								@BatchDate as BatchDate,
								0 as Quantity,
								0 as GrossAmount,
								0 as NetAmount,
								COA_CNF_AccountConfig.Price as ConfigPrice,
								COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								COA_CNF_AccountConfig.RemainingValues,
								case when (data_payment.PaymentAmount) &amp;#60;&amp;#62; 0 then (data_payment.PaymentAmount)
								     else ISNULL(data_payment.AdvancedPaymentAmount, 0)
								 end as RevenueAmount,
								    COA_CNF_AccountConfig.Accountingtype,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,	
									data_payment.paymentid
							from DATA_Transaction					
								INNER JOIN data_paymentcredit					on data_paymentcredit.SettleTransactionId = DATA_Transaction.TransactionId
								INNER JOIN DATA_Payment							on data_payment.paymentid = data_paymentcredit.paymentID
								Cross Join RR_CNF_RevenueRecognitionRule					
								Left  Join COA_CNF_AccountConfig				on COA_CNF_AccountConfig.RevenueRecognitionRuleID = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleID
								Left  Join COA_CNF_Account						on coa_cnf_Account.CoaAccountid = COA_CNF_AccountConfig.coaAccountid

							where (DATA_Transaction.transactiontype = 6)
								and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditSettlementTrigger											 
								and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
								and COA_CNF_AccountConfig.RemainingValues = 1
								and RR_CNF_RevenueRecognitionRule.Enabled = 1
								and DATA_Transaction.ftransactiondate = @BatchDate
								and COA_CNF_AccountConfig.enabled = 1	
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0

	end
END


</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>94F1AF4ED4A64A4081B23F112574C2EA</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnCreditWriteoff</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>15</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnCreditWriteoff]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnCreditWriteoff Integer = 9

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	
BEGIN	
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,	   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &amp;#62; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax WITH(NOLOCK)
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								p.Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE WITH(NOLOCK)
								INNER JOIN DATA_Transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditWriteoff
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (8)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &amp;#60;&amp;#62; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd WITH(NOLOCK)
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								p.Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE  with(nolock)
								INNER JOIN DATA_Transaction with(nolock)						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnCreditWriteoff
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (8)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0

	end
END

</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>B0DFCD376D6345ADB1E83BFA8BAC33CD</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnDepositTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>16</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnDepositTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @DepositTrigger Integer = 5

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	BEGIN																			
	--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,	   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &amp;#62; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax WITH(NOLOCK)
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								rr_data_revenue.AccountingType,
							
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE WITH(NOLOCK)
								INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	WITH(NOLOCK)
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @DepositTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (12, 15)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &amp;#60;&amp;#62; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,	   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd WITH(NOLOCK)
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								rr_data_revenue.AccountingType,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @DepositTrigger
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (12, 15)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0	

	end	
END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>B63C809560ED4130836237E89D1CB094</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnEventTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>30</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnEventTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @OnEventTrigger Integer = 17
	Declare @TicketUsageTrigger Integer = 2
	Declare @TicketExpiredTrigger Integer = 3
	Declare @OnSaleTrigger Integer = 1
	Declare @MatrixCount integer = 0

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product with(nolock)
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger 

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell with(nolock)				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product with(nolock)
					INNER JOIN CNF_AttributeSetDetail with(nolock)					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell with(nolock)							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger
		)p

	select @MatrixCount = COUNT(*)
	  from @Matrixcells


	BEGIN
		if @MatrixCount &amp;#62; 0
		BEGIN																		  
					--Normal Transaction No Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[Ticketid]
						   ,[TransactionID]
						   ,[SaleID]
						   ,[Saleitemid]
						   ,[MatrixCellid]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[FCalcDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]
						   ,[RRDays]
						   ,[AttributeIDs])
						   select *
						   from(
							select	COA_CNF_AccountConfig.COAAccountId, 
									RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									coa_cnf_account.COAAccountTypeId,
									p.Ticketid as Ticketid,
									p.TransactionID,
									p.saleid,
									p.SaleitemID as SaleitemID,
									p.Matrixcellid as Matrixcell,
									p.MatrixSheetId as MatrixSheetID,
									p.TicketSite as SiteID,
									@BatchDate as BatchDate,
									1 as Quantity,
									p.TotalAmount as GrossAmount,
									P.NetAmount1 as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,	
									ABS(ISNULL(Case when COA_CNF_AccountConfig.Price &amp;#62; 0 and ISNULL(p.NetAmount1, 0) &amp;#60;&amp;#62; ISNULL(rdata.totalused, 0)  and (p.NetAmount1 - rdata.totalused) &amp;#62; 0 then (COA_CNF_AccountConfig.Price)
										 else
											 case when p.NetAmount1 &amp;#62; 0 then 
													Case when ISNULL(p.NetAmount1, 0) &amp;#60;&amp;#62; ISNULL(rdata.totalused, 0)  and (ISNULL(p.NetAmount1, 0) - ISNULL(rdata.totalused, 0)) &amp;#62; 0 then
															ABS((ISNULL(p.NetAmount1, 0) - ISNULL(rdata.totalused, 0)) * COA_CNF_AccountConfig.Percentage/100)
													 else 0
													END
												else 0
												end
									end, 0)) as RevenueAmount,
									COA_CNF_AccountConfig.AccountingType,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,
									p.AttributeIDs

						  from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
							   INNER JOIN @Matrixcells MatrixcellID 						ON MatrixcellID.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
							   INNER JOIN COA_CNF_AccountConfig	 WITH(NOLOCK)				ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
							   INNER JOIN COA_CNF_Account WITH(NOLOCK)						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
							   INNER JOIN (	select distinct *, (NetAmount) as NetAmount1
												from
												(
													select data_saleitem.saleid,
														   (select paidtransactionid from data_sale WITH(NOLOCK)
																	INNER JOIN data_transaction WITH(NOLOCK)			on data_transaction.transactionid = data_sale.paidtransactionid
																	where data_sale.saleid = data_saleitem.saleid 
																	  and data_transaction.transactionstatus in (5, 30)) TransactionID,
														   data_saleitem.saleitemid, 
															data_saleitem.matrixcellid, 
															cnf_matrixcell.matrixSheetid, 
															data_saleitem.TotalAmount + ISNULL((select sum(discountamount/(case when data_saleitemrule.ApplytoQty = 0 then 1 else data_saleitemrule.ApplytoQty end))*-1 
															from data_saleitemrule WITH(NOLOCK) 
																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																								
															 where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															   and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) TotalAmount, 																																																																																												
															(select SUM(revenueamount)
																   from RR_DATA_Revenue
																  where RRCalcTypeTrigger = 1
																	and AccountingType = 2
																	and RR_DATA_Revenue.TicketId = data_ticket.ticketid
																	and COAAccountId not in (1, 2, 3, 4)
																	and SaleItemTaxId is null
																	and SaleItemRuleID is null
																	and ISNULL(JournalEntryByAccount, 0) = 0
																) NetAmount,
															cast(cnf_performance.PerfDateTime as date) as PerfDateTime, 
															(select top 1 siteid from data_transaction where data_transaction.saleid = data_saleitem.saleid) as SaleSite,
															data_ticket.Siteid as TicketSite,
															data_ticket.ticketID,
															cnf_matrixcell.AttributeSetId,
															CNF_AttributeSet.AttributeIDs

													from data_ticket WITH(NOLOCK)
																INNER JOIN data_saleitem2ticket WITH(NOLOCK)					ON data_saleitem2ticket.ticketid = data_ticket.ticketid
																																	and data_saleitem2ticket.OperationType = 1
																	INNER JOIN data_saleitem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_saleitem2ticket.saleitemid
																	INNER JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.SaleId
																	LEFT join DATA_SaleItem ORIG WITH(NOLOCK)						on ORIG.SaleItemId = DATA_SaleItem.OrigSaleItemId
																	INNER JOIN data_saleitem2performance WITH(NOLOCK)				on data_saleitem2performance.Saleitemid = data_saleitem.saleitemid
																																		and data_saleitem2performance.SaleItem2PerformanceId = 
																																							(select min(DSP.SaleItem2PerformanceId)
																																								from data_saleitem2performance DSP with(nolock)
																																								where DSP.SaleItemId = data_saleitem.saleitemid
																																								)    
																	INNER JOIN cnf_performance WITH(NOLOCK)							on cnf_performance.PerformanceId = data_saleitem2performance.performanceid
																	INNER JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid
																	INNER JOIN CNF_AttributeSet	WITH(NOLOCK)						on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
													where cast(cnf_performance.PerfDateTime as date) = @BatchDate
													  and DATA_Sale.Paid = 1
													  and ((data_ticket.voidtype &amp;#60;= 99) or (DATA_Ticket.TicketId in 
																(select RR_DATA_Revenue.ticketid 
																   from RR_DATA_Revenue
																	inner join DATA_Ticket			on DATA_Ticket.TicketId = RR_DATA_Revenue.TicketId
																  where RR_DATA_Revenue.TicketId = DATA_Ticket.TicketId
																	and DATA_Ticket.VoidType not in (107, 111))																																		
																))
													  and DATA_Ticket.VoidType not in (104, 125)
													  and data_saleitem.saleid in (select saleid from data_transaction WITH(NOLOCK) where transactiontype in (14, 16, 7, 41, 122) and DATA_Transaction.SaleId = data_saleitem.saleid)
													  and data_saleitem.quantity &amp;#62;0
													  and data_ticket.MatrixCellId in (select matrixcellid from @Matrixcells)
													  and DATA_Ticket.TicketId not in (select rr_data_revenue.TicketId 
																						 from rr_data_revenue WITH(NOLOCK) 
																						 inner join DATA_Transaction WITH(NOLOCK) on rr_data_revenue.TransactionId = DATA_Transaction.TransactionId
																							where  DATA_Transaction.TransactionType in (18, 20, 22, 5)
																							  and DATA_Transaction.FTransactionDate &amp;#60;= @batchdate
																							  and DATA_Ticket.TicketId = rr_data_revenue.ticketid
																						)
												)p1	
											)p  on						(p.matrixcellid   = MatrixcellID.matrixcellid) 
									 left join (select *
															from 
															(
																select rr_data_revenue.ticketid, 	   
																	   accountingtype, 
																	   sum(revenueamount) as TotalUsed
																from rr_data_revenue WITH(NOLOCK)
																where rr_data_revenue.RRCalcTypeTrigger in (@TicketUsageTrigger, @TicketExpiredTrigger, @OnEventTrigger)
																group by rr_data_revenue.ticketid, 
																		 accountingtype
															)p1
												)rdata ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType

						where p.NetAmount1 &amp;#60;&amp;#62; 0
						  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger
						  and rr_cnf_revenuerecognitionRule.Enabled = 1
						  and COA_CNF_AccountConfig.Enabled = 1
						  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
						  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
						  AND P.TICKETID not IN (
											select rr_data_revenue.ticketid
												from rr_data_revenue WITH(NOLOCK)
													INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
												where rr_data_revenue.RRCalcTypeTrigger in  (@TicketUsageTrigger, @TicketExpiredTrigger)
												  and rr_data_revenue.TicketId = P.TICKETID
												group by rr_data_revenue.ticketid, accountingtype,  NetAmount
											)
						  and p.TicketId in (select ticketid
												 from(
															select TicketId,
																   SUM(case when accountingtype = 1 then revenueamount
																			else 0
																		end) Debit,
																   SUM(case when accountingtype = 2 then revenueamount
																			else 0
																		end) credit

															  from RR_DATA_Revenue WITH(NOLOCK)
															 where coaaccountid not in (1, 2, 3, 4)
															   and RR_DATA_Revenue.SaleItemTaxId is null
															   and RR_DATA_Revenue.SaleItemRuleID is null
															   and RR_DATA_Revenue.ticketid = p.Ticketid
															   Group by TicketId
														)p

														where (Debit - Credit) &amp;#60; 0
													)									
						AND p.TransactionID not in (select TransactionID from DATA_Transaction WITH(NOLOCK) where DATA_Transaction.TransactionId = p.TransactionID and DATA_Transaction.TransactionStatus = 6)
						)p
						where RevenueAmount &amp;#60;&amp;#62; 0 



				--Normal onEvent with Remaining Value
					INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]				   
						   ,[Ticketid]
						   ,[TransactionId]
						   ,[SaleID]
						   ,[Saleitemid]
						   ,[MatrixCellid]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[FCalcDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]
						   ,[RRDays]
						   ,[AttributeIDs])
						   select *
						   from(
						   select	COA_CNF_AccountConfig.COAAccountId, 
									RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
									RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									COA_CNF_AccountConfig.COAAccountConfigId,
									coa_cnf_account.COAAccountTypeId,
									p.Ticketid as Ticketid,
									p.TransactionID,
									p.Saleid as Saleid,
									p.Saleitemid as saleitemid,
									p.Matrixcellid as Matrixcell,
									p.MatrixSheetId as MatrixSheetID,
									p.TicketSite as SiteID,
									@BatchDate as BatchDate,
									1 as Quantity,
									0 as GrossAmount,
									0 as NetAmount,
									COA_CNF_AccountConfig.Price as ConfigPrice,
									COA_CNF_AccountConfig.Percentage as ConfigPercentage,
									COA_CNF_AccountConfig.RemainingValues,
							
									ISNULL(case when ISNULL(p.NetAmount1, 0) &amp;#60;&amp;#62; ISNULL(rdata.totalused, 0) and (p.NetAmount1 - ISNULL(rdata.totalused, 0)) &amp;#62; 0  
													 then ABS((p.NetAmount1 - ISNULL(rdata.totalused, 0))) 
													 else 0
												  END
											, 0) as RevenueAmount,


									COA_CNF_AccountConfig.AccountingType,
									RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									RR_CNF_RevenueRecognitionRule.Percentage,
									RR_CNF_RevenueRecognitionRule.Days,
									p.AttributeIDs

					  from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
							   INNER JOIN @Matrixcells MatrixcellID 						ON MatrixcellID.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
							   INNER JOIN COA_CNF_AccountConfig	WITH(NOLOCK)				ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
							   INNER JOIN COA_CNF_Account WITH(NOLOCK)						on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
							   INNER JOIN (	select distinct *, (NetAmount) as NetAmount1
												from
												(
												select data_saleitem.saleid,
														   (select paidtransactionid from data_sale WITH(NOLOCK)
																	INNER JOIN data_transaction WITH(NOLOCK)			on data_transaction.transactionid = data_sale.paidtransactionid
																	where data_sale.saleid = data_saleitem.saleid 
																	  and data_transaction.transactionstatus in (5, 30)) TransactionID,
														   data_saleitem.saleitemid, 
															data_saleitem.matrixcellid, 
															cnf_matrixcell.matrixSheetid, 
															data_saleitem.TotalAmount + ISNULL((select sum(discountamount/(case when data_saleitemrule.ApplytoQty = 0 then 1 else data_saleitemrule.ApplytoQty end))*-1 
																								from data_saleitemrule WITH(NOLOCK) 
																								INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																								INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																								INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																								where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																									and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) TotalAmount, 
															(select SUM(revenueamount)
																   from RR_DATA_Revenue
																  where RRCalcTypeTrigger = 1
																	and AccountingType = 2
																	and RR_DATA_Revenue.TicketId = data_ticket.ticketid
																	and COAAccountId not in (1, 2, 3, 4)
																	and SaleItemTaxId is null
																	and SaleItemRuleID is null
																	and ISNULL(JournalEntryByAccount, 0) = 0
																) NetAmount,
															cast(cnf_performance.PerfDateTime as date) as PerfDateTime, 
															(select top 1 siteid from data_transaction where data_transaction.saleid = data_saleitem.saleid) as SaleSite,
															data_ticket.Siteid as TicketSite,
															data_ticket.ticketID,
															cnf_matrixcell.AttributeSetId,
															CNF_AttributeSet.AttributeIDs

													from data_ticket WITH(NOLOCK)
																INNER JOIN data_saleitem2ticket WITH(NOLOCK)					ON data_saleitem2ticket.ticketid = data_ticket.ticketid
																																	and data_saleitem2ticket.OperationType = 1
																	INNER JOIN data_saleitem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_saleitem2ticket.saleitemid
																	INNER JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.SaleId
																	LEFT join DATA_SaleItem ORIG WITH(NOLOCK)						on ORIG.SaleItemId = DATA_SaleItem.OrigSaleItemId
																	INNER JOIN data_saleitem2performance WITH(NOLOCK)				on data_saleitem2performance.Saleitemid = data_saleitem.saleitemid
																																		and data_saleitem2performance.SaleItem2PerformanceId = 
																																							(select min(DSP.SaleItem2PerformanceId)
																																								from data_saleitem2performance DSP with(nolock)
																																								where DSP.SaleItemId = data_saleitem.saleitemid
																																								)    
																	INNER JOIN cnf_performance WITH(NOLOCK)							on cnf_performance.PerformanceId = data_saleitem2performance.performanceid
																	INNER JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid
																	INNER JOIN CNF_AttributeSet	WITH(NOLOCK)						on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
													where cast(cnf_performance.PerfDateTime as date) = @BatchDate
													  and DATA_Sale.Paid = 1
													  and ((data_ticket.voidtype &amp;#60;= 99) or (DATA_Ticket.TicketId in 
																(select RR_DATA_Revenue.ticketid 
																   from RR_DATA_Revenue
																	inner join DATA_Ticket			on DATA_Ticket.TicketId = RR_DATA_Revenue.TicketId
																  where RR_DATA_Revenue.TicketId = DATA_Ticket.TicketId
																	and DATA_Ticket.VoidType not in (107, 111))																																	
																))
													  and DATA_Ticket.VoidType not in (104, 125)
													  and data_saleitem.saleid in (select saleid from data_transaction WITH(NOLOCK) where transactiontype in (14, 16, 7, 41, 122) and DATA_Transaction.SaleId = data_saleitem.saleid)
													  and data_saleitem.quantity &amp;#62;0
													  and DATA_Ticket.TicketId not in (select rr_data_revenue.TicketId 
																						 from rr_data_revenue WITH(NOLOCK) 
																						 inner join DATA_Transaction WITH(NOLOCK) on rr_data_revenue.TransactionId = DATA_Transaction.TransactionId
																							where  DATA_Transaction.TransactionType in (18, 20, 22, 5)
																							  and DATA_Transaction.FTransactionDate &amp;#60;= @batchdate
																							  and DATA_Ticket.TicketId = rr_data_revenue.ticketid
																						)
												)p1	
											)p  on						(p.matrixcellid   = MatrixcellID.matrixcellid) 
											left join (select *
															from 
															(
																select rr_data_revenue.ticketid, accountingtype, sum(revenueamount) as TotalUsed
																from rr_data_revenue WITH(NOLOCK)
																where rr_data_revenue.RRCalcTypeTrigger  in (@TicketUsageTrigger, @TicketExpiredTrigger, @OnEventTrigger)
																group by rr_data_revenue.ticketid, accountingtype
															)p1
									)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType
						where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnEventTrigger
						  and rr_cnf_revenuerecognitionRule.Enabled = 1
						  and COA_CNF_AccountConfig.Enabled = 1
						  and COA_CNF_AccountConfig.RemainingValues = 1
						  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
						  AND P.TICKETID IN (
											select rr_data_revenue.ticketid
												from rr_data_revenue WITH(NOLOCK)
													INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
												where rr_data_revenue.RevenueRecognitionRuleId = 1
												 and rr_data_revenue.TicketId = P.TICKETID
												group by rr_data_revenue.ticketid, accountingtype,  NetAmount
											)
						  and p.TicketId in (select ticketid
												 from(
															select TicketId,
																   SUM(case when accountingtype = 1 then revenueamount
																			else 0
																		end) Debit,
																   SUM(case when accountingtype = 2 then revenueamount
																			else 0
																		end) credit

															  from RR_DATA_Revenue
															 where coaaccountid not in (1, 2, 3, 4)
															   and RR_DATA_Revenue.SaleItemTaxId is null
															   and RR_DATA_Revenue.SaleItemRuleID is null
															   and RR_DATA_Revenue.ticketid = p.Ticketid
															   Group by TicketId
														)p

														where (Debit - Credit) &amp;#60; 0
													)
							AND p.TransactionID not in (select TransactionID from DATA_Transaction WITH(NOLOCK) where DATA_Transaction.TransactionId = p.TransactionID and DATA_Transaction.TransactionStatus = 6)
						)p
						where revenueamount &amp;#60;&amp;#62; 0

			End
			
		End
END</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>60869235BD65478C87FA6F3D5A739531</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>8</Version>
					<SQL>Create Procedure dbo.otn_sp_RR_RevenueData_OnExternalMoneyCardCashOut
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 11
	Declare @OnExtMoneyCardCashOut Integer = 16

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and cnf_matrixcell.matrixcellid not in (select rr_cnf_product.matrixcellid
															from rr_cnf_product
															where rr_cnf_product.matrixcellid is not null
															  and rr_cnf_Product.Enabled = 1)


				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and CNF_MatrixCell.matrixcellid not in (select CNF_MatrixCell.matrixcellid
															from rr_cnf_product
																INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
															where rr_cnf_product.matrixsheetid is not null
															  and rr_cnf_Product.Enabled = 1
															  and cnf_matrixcell.matrixcellid not in (select rr_cnf_product.matrixcellid
																										from rr_cnf_product
																										where rr_cnf_product.matrixcellid is not null
																										  and rr_cnf_Product.Enabled = 1))
		)p

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								    RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
										Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax WITH(NOLOCK)
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs
		   
							from RR_DATA_REVENUE WITH(NOLOCK)
									inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
									inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31, 48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								    RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr WITH(NOLOCK)
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   COA_CNF_AccountConfig.Accountingtype Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE WITH(NOLOCK)
								inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
								inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account		WITH(NOLOCK)				on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31, 48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0

	end
END</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>D2A8A45DEE4E446F99776179EDF3A443</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnExternalMoneyCardLoad</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>4</Version>
					<SQL>CREATE Procedure dbo.otn_sp_RR_RevenueData_OnExternalMoneyCardLoad
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 15

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			--Normal Transaction No Remaining Values
	INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
										 else (ISNULL(((ABS((select (unitrecharge * Quantity)
															   from data_saleitem
															  where saleitemid = RR_DATA_REVENUE.saleitemid
										))) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,
								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)

							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and ((TransactionType in (42, 43, 49)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																									 from data_transaction
																										Inner join data_saleitem   on data_saleitem.saleid = data_transaction.saleid
																									where data_transaction.transactiontype in (14, 16, 5)
																									  and data_saleitem.unitrecharge &amp;#60;&amp;#62; 0
																								 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE
									inner join rr_cnf_Product						ON ((RR_DATA_REVENUE.MATRIXCELLID = rr_cnf_Product.MATRIXCELLID) 
                                                      or (RR_DATA_REVENUE.MatrixSheetId = rr_cnf_Product.MatrixSheetId)
													  or (rr_cnf_product.Attributeid in (select top 1 Attributeid
																							from rr_cnf_product
																							where Attributeid in (select Value
																													from dbo.split((select rr.Attributeids
																																	from rr_data_revenue rr
																																	where rr.revenuerecognitiondataid = RR_DATA_REVENUE.revenuerecognitiondataid), '.')
																												   )
																					    )
															))
													  and rr_cnf_Product.Enabled = 1
								inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = rr_cnf_Product.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (42, 43, 49)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0


		
		exec otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts @BatchDate, '42, 43, 49,', @OnMoneyCardCashOut, @RRTransDateType										

	end
	--select '@OnExternalMoneyCardLoad' as TriggerType, @BatchDate as RunDate
END</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>640A8A64D5A349E7979735BBC03C0C39</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnFlexContractCancel</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>47</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnFlexContractCancel]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1
	Declare @RevenueType Integer

	Declare @PaymentRRRId Integer
	Declare @PaymentCOAAccountId Integer
	Declare @PaymentRRCalcTypeTrigger Integer
	Declare @PaymentRRCalcTypeWhere Integer
	Declare @PaymentRRCalcTypeMethod Integer
	Declare @PaymentCOAAccountConfigId Integer
	Declare @PaymentCOAAccountTypeId Integer

	Declare @PaymentPercentage float
	Declare @PaymentDays Integer
	Declare @PaymentPrice float
	Declare @PaymentCOAAccount_Percentage Float
	Declare @PaymentRemainingValues Integer
	Declare @PaymentRRCOAAccountingType Integer
	Declare @PaymentAccountingType Integer

	Declare @DiscountRRRId Integer
	Declare @DiscountCOAAccountId Integer
	Declare @DiscountRRCalcTypeTrigger Integer
	Declare @DiscountRRCalcTypeWhere Integer
	Declare @DiscountRRCalcTypeMethod Integer
	Declare @DiscountCOAAccountConfigId Integer
	Declare @DiscountCOAAccountTypeId Integer
	Declare @DiscountPercentage float
	Declare @DiscountDays Integer
	Declare @DiscountPrice float
	Declare @DiscountCOAAccount_Percentage Float
	Declare @DiscountRemainingValues Integer
	Declare @DiscountRRCOAAccountingType Integer
	Declare @DiscountAccountingType Integer

	select @RevenueType = coaaccounttypeid
	  from COA_CNF_AccountType
	  where code = 'REVENUE'



	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1

		)p


	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select TOP 1 @PaymentRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
				@PaymentRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
				@PaymentRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
				@PaymentRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
				@PaymentCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
				@PaymentCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
				@PaymentCOAAccountId = coa_cnf_account.COAAccountId,
				@PaymentPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
				@PaymentDays = RR_CNF_RevenueRecognitionRule.Days,
				@PaymentPrice = COA_CNF_AccountConfig.Price,
				@PaymentCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
				@PaymentRemainingValues = COA_CNF_AccountConfig.RemainingValues,
				@PaymentRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
		from coa_cnf_account
			INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
			INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
			INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
		where coa_cnf_account.COAAccountID = @ACCPaymentMethod

	select TOP 1 @DiscountRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@DiscountRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@DiscountRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@DiscountRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@DiscountCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@DiscountCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@DiscountCOAAccountId = coa_cnf_account.COAAccountId,
			@DiscountPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@DiscountDays = RR_CNF_RevenueRecognitionRule.Days,
			@DiscountPrice = COA_CNF_AccountConfig.Price,
			@DiscountCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@DiscountRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@DiscountRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account
		INNER JOIN COA_CNF_AccountType				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @DiscountAccountID

	BEGIN
																		  

																		  
---Scheduled and Manual Payments
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])
								select  coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										sum(abs(RevenueAmount)),
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select  coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										(TotalPaid) + Change RevenueAmount,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select	isnull(Coa_cnf_account.COAAccountId, @PaymentCOAAccountId) as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										ISNULL(Coa_cnf_account.COAAccountTypeId, @PaymentCOAAccountTypeId)  as AccountType,
										data_transaction.transactionid,
										data_transaction.saleid,
										data_transaction.siteid, 
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										ISNULL((select sum(paymentamount)
										         from data_payment
												 where data_payment.paymentstatus = 1
												   and data_payment.transactionid = data_transaction.transactionid), 0) 												 										
										- ISNULL((select sum(FeeAmount) as FeeAmount
																			from DATA_PaymentPlan2Transaction	
																				INNER JOIN DATA_PaymentPlan			on data_paymentplan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
																			where DATA_PaymentPlan2Transaction.Transactionid = data_transaction.transactionid
																			  and DATA_PaymentPlan2Transaction.flexpaymentstatus &amp;#60;&amp;#62; 5), 0) 		 
												 
												 
												 
												 as TotalPaid,	
										2 as Accountingtype,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays,
										max(data_saleitem.saleitemid) SaleitemID,
										data_transaction.Change

								from data_transaction
									inner join data_sale WITH(NOLOCK)			on data_sale.saleid = data_transaction.saleid
									Left  JOIN data_saleitem				on data_saleitem.saleid = data_transaction.saleid									
									Left JOIN data_paymentPlan2Transaction on data_paymentplan2transaction.transactionid = data_transaction.transactionid									
									CROSS APPLY CNF_PaymentMethod			
									Left  join COA_CNF_Account				on COA_CNF_Account.coaaccountid = CNF_PaymentMethod.coaaccountid

								where transactiontype in (33, 45)
								    and data_sale.paid = 1
									and CNF_PaymentMethod.enabled = 1
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
								    and CNF_PaymentMethod.paymentmethodid in (select DATA_PaymentPlan.paymentmethodid
																				from DATA_PaymentPlan2Transaction
																				INNER JOIN DATA_PaymentPlan			on DATA_PaymentPlan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
																				INNER JOIN DATA_PaymentFlex PF		on PF.PaymentId = DATA_PaymentPlan.PaymentID
																				where PF.PaymentID in 	(select paymentid 
																				                           from data_payment
																										   where data_payment.transactionid = data_transaction.transactionid)

																				and  DATA_PaymentPlan.paymentmethodid is not null
																				and DATA_PaymentPlan2Transaction.transactionid = data_transaction.transactionid
																				union all
																				select PAYMENTMETHODID
																				from  CNF_PaymentMethod	
																					inner join cnf_dRIVER				ON CNF_DRIVER.DRIVERID = CNF_PAYMENTMETHOD.DRIVERID
																				WHERE CNF_DRIVER.dRIVERak = 'TPayTpFlex')
									and data_transaction.transactionid in (select transactionid from data_payment where data_payment.transactionid = data_transaction.transactionid and data_payment.paymentstatus = 1)
								group by
										 data_transaction.transactionid,
										 data_transaction.saleid,
										 data_transaction.siteid,
										 data_transaction.OperatingAreaId,
										 data_transaction.Workstationid,
										 data_transaction.UserGroupid,
										 data_transaction.UserId,
										 data_transaction.Change,
										 Coa_cnf_account.COAAccountTypeId,
										 Coa_cnf_account.Code,
										 coa_cnf_account.coaaccountid
							)p
							where coaaccountid is not null
							)r
							group by 	coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										Workstationid,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
						Having sum(abs(RevenueAmount)) &amp;#60;&amp;#62; 0

--  Reverse out the tickets
 INSERT INTO [dbo].[RR_DATA_Revenue]
											   ([COAAccountId]
											   ,[RevenueRecognitionRuleId]
											   ,[RRCalcTypeWhere]
											   ,[RRCalcTypeMethod]
											   ,[COAAccountConfigId]
											   ,[COAAccountType]
											   ,[TransactionId]
											   ,[SaleId]											   
											   ,[ticketid]
											   ,[Saleitemid]
											   ,[SiteId]
											   ,[OperatingAreaId]
											   ,[WorkstationId]
											   ,[UserGroupId]
											   ,[UserId]
											   ,[FCalcDate]
											   ,[Quantity]
											   ,[GrossAmount]
											   ,[NetAmount]
											   ,[Price]
											   ,[Percentage]
											   ,[RemaningValues]
											   ,[RevenueAmount]
											   ,[AccountingType]
											   ,[RRCalcTypeTrigger]
											   ,[RRPercentage]
											   ,[RRDays])
											   select *
											   from (
									select distinct  coa_cnf_account.coaaccountid as coaaccountid, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   ISNULL(COA_CNF_AccountConfig.coaaccountconfigid, 1) as coaaccountconfigid,
								   ISNULL(p.COAAccountType,	coa_cnf_account.COAAccountTypeId) as COAAccountType,							   
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   rr_data_revenue.ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,								
								   RR_DATA_REVENUE.revenueamount as revenueamount,
								   1 Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

							from RR_DATA_REVENUE
									inner join @Matrixcells	as Matrixcellid			ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									inner join data_sale WITH(NOLOCK)			on data_sale.saleid = data_transaction.saleid
									LEFT JOIN (select	ticketid,
														COAAccountId, 
														COAAccountType, 
													
														sum(Revenuamount) as revenueamount
												from (
												select ticketid, 
														COAAccountId, 
														COAAccountConfigId, 
														COAAccountType, 

														accountingtype, 
														case when accountingtype = 1 then revenueamount*-1 else revenueamount end as revenuamount
												from rr_data_revenue dr1
												where revenuerecognitionruleid &amp;#60;&amp;#62; 1
												)p1
												group by ticketid,
														COAAccountId, 
														COAAccountType)p      on p.ticketid = rr_data_revenue.ticketid and p.coaaccountid = coa_cnf_account.coaaccountid
									INNER JOIN DATA_Ticket							on data_ticket.ticketid = rr_data_revenue.ticketid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and data_sale.paid = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (46, 47)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid

								) p

								where revenueamount &amp;#60;&amp;#62; 0


----Reverse the fees out this is a completely fictional line 
INSERT INTO [dbo].[RR_DATA_Revenue]
											   ([COAAccountId]
											   ,[RevenueRecognitionRuleId]
											   ,[RRCalcTypeWhere]
											   ,[RRCalcTypeMethod]
											   ,[COAAccountConfigId]
											   ,[COAAccountType]
											   ,[TransactionId]
											   ,[SaleId]											   
											   ,[ticketid]
											   ,[Saleitemid]
											   ,[SiteId]
											   ,[OperatingAreaId]
											   ,[WorkstationId]
											   ,[UserGroupId]
											   ,[UserId]
											   ,[FCalcDate]
											   ,[Quantity]
											   ,[GrossAmount]
											   ,[NetAmount]
											   ,[Price]
											   ,[Percentage]
											   ,[RemaningValues]
											   ,[RevenueAmount]
											   ,[AccountingType]
											   ,[RRCalcTypeTrigger]
											   ,[RRPercentage]
											   ,[RRDays])
											   select *
											   from (
								
								select distinct  coa_cnf_account.coaaccountid as coaaccountid, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   ISNULL(COA_CNF_AccountConfig.coaaccountconfigid, 1) as coaaccountconfigid,
								   ISNULL(p.COAAccountType,	coa_cnf_account.COAAccountTypeId) as COAAccountType,							   
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   rr_data_revenue.ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,	
								   DATA_Ticket.Price - data_ticket.taxes - 
								   ISNULL((select sum(revenueamount)
										from rr_data_revenue RR WITH(NOLOCK)
									  where RR.ticketid = data_ticket.ticketid
										and RR.coaaccountid = coa_cnf_account.coaaccountid
										and RR.rrcalctypetrigger in (2, 3, 4, 17)
										and RR.AccountingType = COA_CNF_AccountConfig.AccountingType), 0) revenueamount,
								   1 AccountingType,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days

							from RR_DATA_REVENUE
									inner join @Matrixcells	as Matrixcellid			ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
									inner join RR_CNF_RevenueRecognitionRule		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId 
																						and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId 
																						and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
									inner join data_sale WITH(NOLOCK)			on data_sale.saleid = data_transaction.saleid
									LEFT JOIN (select	ticketid,
														COAAccountId, 
														COAAccountType, 
													
														sum(Revenuamount) as revenueamount
												from (
												select ticketid, 
														COAAccountId, 
														COAAccountConfigId, 
														COAAccountType, 

														accountingtype, 
														case when accountingtype = 1 then revenueamount*-1 else revenueamount end as revenuamount
												from rr_data_revenue dr1
												where revenuerecognitionruleid &amp;#60;&amp;#62; 1
												)p1
												group by ticketid,
														COAAccountId, 
														COAAccountType)p      on p.ticketid = rr_data_revenue.ticketid and p.coaaccountid = coa_cnf_account.coaaccountid
									INNER JOIN DATA_Ticket							on data_ticket.ticketid = rr_data_revenue.ticketid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and data_sale.paid = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (51)
							  and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = (case when (1 = (select top 1 1 from RR_DATA_Revenue WITH(NOLOCK) where rr_data_revenue.ticketid = data_ticket.ticketid and RRCalcTypeTrigger in (2, 3, 4, 17))) then 4
							                                                              else 1
																					  end)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid

								) p

								where revenueamount &amp;#60;&amp;#62; 0


----Reverse the fees out this is a completely fictional line 
	INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
					select distinct COA.COAAccountId, 
						   1,	   
						   1,
						   1,	   
						   1,
						   COA.COAAccountTypeId,
						   DATA_Transaction.Transactionid,
						   DATA_Transaction.saleid,
						   DATA_Transaction.Siteid,
						   DATA_Transaction.OperatingAreaId,
						   DATA_Transaction.Workstationid,
						   DATA_Transaction.UserGroupid,
						   DATA_Transaction.UserId,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   r1.FeeAmount as RevenueAmount,
						   1 accountingtype,
						   1, 
						   100,
						   0

					from DATA_Transaction
					inner join data_sale WITH(NOLOCK)			on data_sale.saleid = data_transaction.saleid
					inner JOIN data_payment							on data_payment.transactionid = DATA_Transaction.transactionid
					inner JOIN CNF_PaymentMethod					    on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
					inner JOIN (select distinct DATA_PaymentFlex.paymentid, data_saleitem.saleid, (DATA_PaymentFlex.DownpaymentRefundableFeeAmount + data_paymentflex.RefundableFeeAmount) as FeeAmount,  CNF_Promotion.COAAccountId
								from data_saleitem
									INNER JOIn data_Paymentflex2saleitem	on data_Paymentflex2saleitem.saleitemid = data_saleitem.saleitemid
									INNER JOIN DATA_PaymentFlex				on data_paymentflex.paymentid = data_Paymentflex2saleitem.paymentid
									INNER JOIN CNF_FlexContract				on cnf_flexContract.FlexContractId = DATA_PaymentFlex.flexcontractID
									INNER JOIN CNF_FlexContractFee			on CNF_FlexContractFee.FlexContractId = CNF_FlexContract.flexcontractID
									INNER JOIN CNF_Promotion				on CNF_Promotion.promotionID = CNF_FlexContractFee.promotionID

								where CNF_Promotion.COAAccountId is not null
									and  (DATA_PaymentFlex.DownpaymentRefundableFeeAmount + data_paymentflex.RefundableFeeAmount) &amp;#60;&amp;#62; 0)r1				on r1.saleid = DATA_Transaction.saleid
					inner JOIN COA_CNF_Account COA					on COA.COAAccountid = R1.COAAccountId
					where DATA_Transaction.TransactionType in (46, 47)
					  and ISNULL(data_payment.paymentstatus, 1) = 1
					  and data_sale.paid = 1
					and ((data_payment.paymentfee &amp;#60;&amp;#62; 0) or (r1.FeeAmount &amp;#60;&amp;#62; 0))
					and DATA_Transaction.ftransactiondate = @BatchDate
					AND data_payment.Transactionid in (select distinct transactionid
														from rr_Data_Revenue
														where coaaccountid in (@ACCPaymentMethod)
														)
					and data_transaction.transactionid not in (select transactionid
					                                             from rr_data_revenue rr
																	INNER JOIN RR_CNF_RevenueRecognitionRule RRR     on rr.RevenueRecognitionRuleId = rrr.RevenueRecognitionRuleId
																 where rrr.RevenueRecognitionRuleId not in (@SuspendID, @TaxAccountID, @DiscountAccountID, @ACCPaymentMethod)
																   and AccountingType = 1
																   and rr.COAAccountId in (select coaaccountid
																							from CNF_FlexContractFee
																							INNER JOIN CNF_Promotion				on CNF_Promotion.promotionID = CNF_FlexContractFee.promotionID
																							where coaaccountid is not null
																						  )
																)


--Reversing the payment method for installment billing.  When ticket 79425 if done we should be able to remove this section.	
					INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])
							select  ISNULL(coaaccountid, @PaymentCOAAccountId),
										ISNULL(RRID, @PaymentRRRId),
										TypeWhere,
										method,
										Configid,
										ISNULL(AccountType, @PaymentCOAAccountTypeId),
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										sum(abs(RevenueAmount)),
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select  coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										RevenueAmount,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select	coa_cnf_account.COAAccountId as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										Coa_cnf_account.COAAccountTypeId as AccountType,
										data_transaction.transactionid,
										data_transaction.saleid,
										data_transaction.siteid, 
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate as BatchDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										RR_DATA_Revenue.RevenueAmount,																								
										2 as Accountingtype,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays,
										null SaleitemID,
										data_transaction.Change,
										data_transaction.transactiontype

								from RR_DATA_Revenue WITH(NOLOCK)
									INNER  JOIN DATA_Transaction WITH(NOLOCK)				on DATA_Transaction.TransactionId = RR_DATA_Revenue.TransactionId
									INNER  JOIN DATA_Sale WITH(NOLOCK)						on DATA_Sale.SaleId = RR_DATA_Revenue.saleid
									INNER  JOIN data_payment WITH(NOLOCK)					on data_payment.transactionid = DATA_Sale.paidtransactionID	
																								and DATA_Payment.PaymentMethodId in (select PAYMENTMETHODID
																																		from  CNF_PaymentMethod WITH(NOLOCK)	
																																			inner join cnf_dRIVER WITH(NOLOCK)				ON CNF_DRIVER.DRIVERID = CNF_PAYMENTMETHOD.DRIVERID
																																		WHERE CNF_DRIVER.dRIVERak = 'TPayTpFlex'
																																		  and CNF_PaymentMethod.enabled = 1
																																	   )
									INNER  JOIN CNF_PaymentMethod WITH(NOLOCK)				on CNF_PaymentMethod.PaymentMethodId = DATA_Payment.PaymentMethodId
									INNER  join COA_CNF_Account								on COA_CNF_Account.coaaccountid = CNF_PaymentMethod.coaaccountid

								where  data_transaction.transactiontype in (46, 47)
									and RR_DATA_Revenue.SaleItemRuleID = 1
									and CNF_PaymentMethod.enabled = 1
									and data_payment.PaymentStatus = 1
									and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
							)p
							where RevenueAmount &amp;#60;&amp;#62; 0
							)r
							group by 	coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										Workstationid,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
						Having sum(abs(RevenueAmount)) &amp;#60;&amp;#62; 0
	
	
					
----Reverse the Discount for flex contracts
INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[Saleitemid]
								,[Matrixcellid]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays]
								,[saleitemruleid])

								select  ISNULL(p.COAAccountId, @DiscountAccountID) Coaaccountid,
										@DiscountRRRId,
										@DiscountRRCalcTypeWhere,
										@DiscountRRCalcTypeMethod,
										@DiscountCOAAccountConfigId,
										@DiscountCOAAccountTypeId,
										data_transaction.transactionid, 
										data_transaction.saleid,
										p.Saleitemid,
										p.Matrixcellid,
										data_transaction.Siteid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate,
										0,
										case when PromotionType = 7 then ABS(p.GLAmount) else 0 end,
										case when PromotionType = 7 then ABS(p.GLAmount) else 0 end,
										0,
										100,
										0,
										ABS(p.GLAmount) RevenueAmount,
										Accountingtype,
										@DiscountRRCalcTypeTrigger,
										@DiscountPercentage,
										@DiscountDays,
										saleitemruleid
							FROM
							(
					SELECT distinct DATA_SaleItem.Saleitemid,
												CNF_Matrixcell.matrixcellid as matrixcellid,
												DATA_Sale.saleid AS SAleid,
      											DATA_Transaction.TransactionType,
      											( SELECT top 1 transactionid
													FROM data_transaction		WITH (NOLOCK)
												   WHERE saleid = DATA_Sale.saleid
													AND transactiontype in (14, 16)
													AND paid = 1
												) AS tester,

												CASE WHEN DATA_Transaction.TransactionId IN (
																							  SELECT TR.TransactionID
																								FROM DATA_Transaction TR			WITH (NOLOCK)
																									LEFT JOIN DATA_Payment DP		WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
																							  WHERE TR.SaleId = DATA_Sale.SaleId
																								AND TR.Paid = 1
																								AND DP.PaymentStatus NOT IN (0, 2, 3)
																							)
      
															THEN DATA_Transaction.Transactionid
													 ELSE (
															  SELECT MIN(TR.TransactionID)
																FROM DATA_Transaction TR				WITH (NOLOCK)
																	LEFT JOIN DATA_Payment DP			WITH (NOLOCK) ON TR.TransactionId = DP.TransactionId
															   WHERE TR.SaleId = DATA_Sale.saleid
																 AND TR.TransactionType = 16
																 AND TR.Paid = 1
																 AND DP.PaymentStatus NOT IN (0, 2, 3)
														  )
												END Transactionid, 
												 CASE WHEN CNF_Promotion.PromotionType IN (1, 3, 5, 7, 200) AND CNF_PromotionItemRule.NewProduct = 1 THEN  (SUM(DATA_SaleItemRule.DiscountAmount))
													  ELSE  CASE WHEN sum(1*data_saleItemRule.DiscountAmount) &amp;#60; 0 AND transactiontype IN(46, 47) AND
																																								(SELECT Count(*) 
																																								   FROM data_transaction WITH (NOLOCK)
																																								  WHERE saleid = data_sale.saleid
																																								 ) = 1 					  					  					  										  
																	  THEN Sum(1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &amp;#60; 0 THEN	Sum(-1 * DATA_SaleItemRule.DiscountAmount)
																 WHEN sum(1*data_saleItemRule.DiscountAmount) &amp;#62; 0 AND transactiontype IN(46, 47) THEN Sum(-1 * DATA_SaleItemRule.DiscountAmount)		            	                  
																 ELSE sum(1*Data_SaleItemRule.DiscountAmount)
															END
												END AS GLAmount,
												case when sum(Data_SaleItemRule.DiscountAmount) &amp;#62; 0 then 1
														 else 2 
													end as accountingtype,
												CNF_Promotion.PromotionType,
												CNF_PromotionItemRule.NewProduct,
												CNF_Promotion.COAAccountId,
												DATA_SaleItemRule.saleitemruleid

								FROM dbo.data_transaction				    WITH (NOLOCK)
									LEFT JOIN dbo.DATA_Sale					WITH (NOLOCK) ON DATA_Sale.SaleID = data_transaction.SaleID
									LEFT JOIN dbo.DATA_SaleItem				WITH (NOLOCK) ON DATA_SaleItem.Saleid = DATA_Sale.Saleid
									LEFT JOIN dbo.DATA_SaleItemRule			WITH (NOLOCK) ON DATA_SaleItemRule.saleitemid = DATA_SaleItem.SaleitemID
									LEFT JOIN dbo.CNF_PromotionItemRule		WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
									LEFT JOIN dbo.CNF_PromotionItem			WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
									LEFT JOIN dbo.CNF_Promotion				WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
									LEFT JOIN CNF_MatrixCell			    WITH (NOLOCK) ON CNF_MatrixCell.MatrixCellId =  DATA_SaleItem.MatrixCellId
 
								WHERE data_transaction.transactiontype  in (46, 47)
								 AND DATA_Sale.Paid = 1
								 and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
										 OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate)) 
         
												group BY DATA_SaleItem.Saleitemid,
										 DATA_Sale.saleid,
										 Data_transaction.Paid,
										 Data_Transaction.Transactionid,
										 Data_Transaction.fTransactionDate,
										 Data_Saleitem.Matrixcellid,
										 CNF_Promotion.PromotionType,
										 CNF_PromotionItemRule.NewProduct,
										 CNF_MatrixCell.Price,
										 transactiontype,
										 CNF_Matrixcell.matrixcellid,
										 CNF_Promotion.COAAccountId,
												DATA_SaleItemRule.saleitemruleid

							)p
							LEFT JOIN data_transaction				WITH (NOLOCK) on data_transaction.transactionid = p.transactionid
							LEFT JOIN COA_CNF_Account				WITH (NOLOCK) ON COA_CNF_Account.COAAccountId = p.COAAccountId

							WHERE data_transaction.transactionid is not null
							and p.GLAmount &amp;#60;&amp;#62; 0

	INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[Saleitemid]
				   ,[matrixcellid]
				   ,[matrixsheetid]
				   ,[Ticketid]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,	   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   siteid,
									   saleitemid,
									   matrixcellid,
									   matrixsheetid,
									   Ticketid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									   Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       COA_CNF_Account.COAAccountId, 
									   rr_data_Revenue.RevenueRecognitionRuleId,	   
									   rr_data_Revenue.RRCalcTypeWhere,
									   rr_data_Revenue.RRCalcTypeMethod,	   
									   rr_data_Revenue.COAAccountConfigId,
									   COA_CNF_Account.COAAccountTypeId,
									   RR_DATA_REVENUE.Saleitemid,
									   RR_DATA_REVENUE.matrixcellid,
									   RR_DATA_REVENUE.matrixsheetid,
									   RR_DATA_REVENUE.TicketID,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       1 as Accountingtype,			
									   rr_data_Revenue.RRCalcTypeTrigger,
									   rr_data_Revenue.RRPercentage,
									   rr_data_Revenue.RRDays
							FROM rr_data_Revenue   				        WITH (NOLOCK)
									INNER JOIN data_transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER  join data_saleitemtax WITH(NOLOCK)					ON data_saleitemtax.saleitemtaxid = rr_data_revenue.SaleItemTaxId
									INNER  join cnf_tax WITH(NOLOCK)								ON cnf_tax.taxid = data_saleitemtax.TaxId
									INNER  join COA_CNF_Account WITH(NOLOCK)						ON COA_CNF_Account.COAAccountId = cnf_tax.COAAccountId

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and DATA_Transaction.TransactionType in (46)
							  and rr_data_Revenue.coaaccountid in (3)
								
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,	   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType,
									   Saleitemid,
									   TicketID,
									   matrixcellid,
									   matrixsheetid


--Reverse out the Paymentmethod paid
	INSERT INTO [dbo].[RR_DATA_Revenue]
								([COAAccountId]
								,[RevenueRecognitionRuleId]
								,[RRCalcTypeWhere]
								,[RRCalcTypeMethod]
								,[COAAccountConfigId]
								,[COAAccountType]
								,[TransactionId]
								,[SaleId]
								,[SiteId]
								,[OperatingAreaId]
								,[WorkstationId]
								,[UserGroupId]
								,[UserId]
								,[FCalcDate]
								,[Quantity]
								,[GrossAmount]
								,[NetAmount]
								,[Price]
								,[Percentage]
								,[RemaningValues]
								,[RevenueAmount]
								,[AccountingType]
								,[RRCalcTypeTrigger]
								,[RRPercentage]
								,[RRDays])
							select  ISNULL(coaaccountid, @PaymentCOAAccountId),
										ISNULL(RRID, @PaymentRRRId),
										TypeWhere,
										method,
										Configid,
										ISNULL(AccountType, @PaymentCOAAccountTypeId),
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										sum(abs(RevenueAmount)),
										AccountingType,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select  coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										WorkstationID,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
									RevenueAmount,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
								from (
								select	@PaymentCOAAccountId as coaaccountid,
										@PaymentRRRId as RRID,
										@PaymentRRCalcTypeWhere as TypeWhere,
										@PaymentRRCalcTypeMethod as method,
										@PaymentCOAAccountConfigId as Configid,
										@PaymentCOAAccountTypeId as AccountType,	
										RR_DATA_Revenue.transactionid,
										RR_DATA_Revenue.saleid,
										RR_DATA_Revenue.siteid, 
										RR_DATA_Revenue.OperatingAreaId,
										RR_DATA_Revenue.Workstationid,
										RR_DATA_Revenue.UserGroupid,
										RR_DATA_Revenue.UserId,
										@BatchDate as BatchDate,
										0 as Qty,
										0 as Gross,
										0 as net,
										0 as price,
										100 as percentage,
										0 as RemaningValue,
										RR_DATA_Revenue.RevenueAmount,
								
										1 as Accountingtype,
										@PaymentRRCalcTypeTrigger as TypeTrigger,
										@PaymentPercentage as PaymentPercentage,
										@PaymentDays as RRDays

								from RR_DATA_Revenue WITH(NOLOCK)
									inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = RR_DATA_Revenue.transactionid
									inner join DATA_Sale WITH(NOLOCK)							on DATA_Sale.SaleId = DATA_Transaction.saleid
								
								where RR_DATA_REVENUE.fcalcdate = @BatchDate
								    and data_transaction.transactiontype in (46, 47)
									and data_sale.paid = 1
									and RR_DATA_Revenue.COAAccountId in (select coaaccountid
																				from  CNF_PaymentMethod WITH(NOLOCK)	
																					inner join cnf_dRIVER WITH(NOLOCK)				ON CNF_DRIVER.DRIVERID = CNF_PAYMENTMETHOD.DRIVERID
																				WHERE CNF_DRIVER.dRIVERak = 'TPayTpFlex'
																				  and CNF_PaymentMethod.enabled = 1
																			   )
								)p	
							)r
							group by 	coaaccountid,
										RRID,
										TypeWhere,
										method,
										Configid,
										AccountType,
										transactionid, 
										saleid,
										Siteid,
										OperatingAreaId,
										Workstationid,
										UserGroupid,
										UserId,
										BatchDate,
										Qty,
										Gross,
										net,
										price,
										percentage,
										RemaningValue,
										Accountingtype,
										TypeTrigger,
										PaymentPercentage,
										RRDays
						Having sum(abs(RevenueAmount)) &amp;#60;&amp;#62; 0																																																																																																							
		
		
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[Saleitemid]
				   ,[matrixcellid]
				   ,[matrixsheetid]
				   ,[Ticketid]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				      select  COAAccountId, 
									   RevenueRecognitionRuleId,		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   siteid,
									   saleitemid,
									   matrixcellid,
									   matrixsheetid,
									   Ticketid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
									   ABS(sum(RevenueAmount))  as RevenueAmount,
									   Accountingtype,	
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays
					  from (		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,	   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   RR_DATA_REVENUE.Saleitemid,
									   RR_DATA_REVENUE.matrixcellid,
									   RR_DATA_REVENUE.matrixsheetid,
									   RR_DATA_REVENUE.TicketID,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   rr_data_Revenue.Siteid siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
									   data_transaction.transactiontype,
								       case when rr_data_Revenue.Accountingtype = 2 then 1
									        else 2											
										end as Accountingtype,			
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_revenue.AttributeIDs,
									   rr_data_revenue.SaleItemTaxId
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select distinct saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, RR_DATA_Revenue.COAAccountId, 
																RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, COA_CNF_Account.COAAccountTypeId
																from RR_DATA_Revenue WITH(NOLOCK)
																	INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																where COA_CNF_Account.coaAccountID = @TaxAccountID	
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									INNER JOIN data_transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and TransactionType in (46, 47, 51)
							  and rr_data_Revenue.coaaccountid in (select coaaccountid
						                                             from cnf_tax WITH(NOLOCK)
																    where coaaccountid is not null
															      )
								
							)p
							group by   COAAccountId, 
									   RevenueRecognitionRuleId,	   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountConfigId,
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   siteid,
									   OperatingAreaid,
									   workstationid,
									   usergroupid,
									   userid,
									   batchdate,
									   Quantity,
									   grossamount,
									   netamount,
									   price,
									   percentage,
									   tax,
								       Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays,
									   TransactionType,
									   Saleitemid,
									   TicketID,
									   matrixcellid,
									   matrixsheetid
		
		
		
		End

END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>D5534D22C3C54F3F84D6F80E94F31B77</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnMoneyCardCashOut</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>15</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnMoneyCardCashOut]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardCashOut Integer = 11
	Declare @OnExtMoneyCardCashOut Integer = 16

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product with(nolock)
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger in (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut) 

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell with(nolock)				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger in (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut)

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product with(nolock)
					INNER JOIN CNF_AttributeSetDetail with(nolock)					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell	 with(nolock)						on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger in (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut)
		)p

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN

			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
							select coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								    RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									(CASE WHEN coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then  
										Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
												else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																										from data_saleitemTax WITH(NOLOCK)
																										where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * COA_CNF_AccountConfig.Percentage/100), 0))
										end 																		                                                                                                                                                                                              
									end)  as RevenueAmount,

								   COA_CNF_AccountConfig.Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs
		   
							from RR_DATA_REVENUE WITH(NOLOCK)
									inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
									inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31, 48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
						
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0

				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								    RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   RR_DATA_REVENUE.Quantity as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr WITH(NOLOCK)
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   COA_CNF_AccountConfig.Accountingtype Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE WITH(NOLOCK)
								inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
								inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account		WITH(NOLOCK)				on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (31, 48, 52)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardCashOut, @OnExtMoneyCardCashOut)
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0

	end
END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>EC21B81B85754497A13D0B3868A5C755</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnMoneyCardLoad</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>22</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnMoneyCardLoad]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	
	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnMoneyCardLoad Integer = 10
	Declare @OnExtMoneyCardLoad Integer = 15
	Declare @OnSaleTrigger integer = 1

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product with(nolock)
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger in (@OnMoneyCardLoad, @OnSaleTrigger, @OnExtMoneyCardLoad)

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product with(nolock)
					INNER JOIN CNF_MatrixCell with(nolock)				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger in (@OnMoneyCardLoad, @OnSaleTrigger, @OnExtMoneyCardLoad)

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail with(nolock)					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell	 with(nolock)						on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule with(nolock)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger in (@OnMoneyCardLoad, @OnSaleTrigger, @OnExtMoneyCardLoad)
		)p

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1


		BEGIN
			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   1 as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,																		
									Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price) 									     
										 else (ISNULL((ABS(RR_DATA_Revenue.RevenueAmount) * COA_CNF_AccountConfig.Percentage/100), 0))																		                                                                                                                                                                                              
									end  as RevenueAmount,
								   case when (TransactionType in (5, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1) OR (ISNULL(DATA_SaleItem.Quantity, 1) &amp;#62; 0) then 2
								        when (TransactionType in (5, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2) OR (ISNULL(DATA_SaleItem.Quantity, 1) &amp;#60; 0) then 1										
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

							from RR_DATA_REVENUE WITH(NOLOCK)
									inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
									inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
									INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
									INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
									INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
									INNER JOIN DATA_Transaction WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
									LEFT  JOIN DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid									

							where  ((RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardLoad, @OnExtMoneyCardLoad)) or
							((RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger) and 
							   (RR_DATA_Revenue.matrixcellid not IN(select Matrixcellid 
							                                          from @Matrixcells Matrixcellid1
																	  inner join RR_CNF_RevenueRecognitionRule RR WITH(NOLOCK)		ON RR.RevenueRecognitionRuleId = Matrixcellid1.RevenueRecognitionRuleId and RR.enabled = 1  
																	  where RR.RRCalcTypeTrigger IN (@OnMoneyCardLoad, @OnExtMoneyCardLoad)
																	)
								)
							)
						 )
						 )
							  and RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and 1 = case when (RR_DATA_REVENUE.Ticketid Is null and rr_data_revenue.RevenueAmount = (select ABS(unitrecharge * quantity)
															         from data_saleitem WITH(NOLOCK)
															        where saleitemid = RR_DATA_REVENUE.saleitemid)) then 1
									       when (RR_DATA_REVENUE.Ticketid Is not null and rr_data_revenue.RevenueAmount = (select ABS(unitrecharge)
															         from data_saleitem WITH(NOLOCK)
															        where saleitemid = RR_DATA_REVENUE.saleitemid)) then 1	 
										   else 0	
										end
							  and ((TransactionType in (10, 20, 18, 22, 42, 43, 49)) or (RR_DATA_REVENUE.transactionid in (select transactionid
																															 from data_transaction WITH(NOLOCK)
																																Inner join data_saleitem WITH(NOLOCK)   on data_saleitem.saleid = data_transaction.saleid
																															where ((data_transaction.transactiontype in (14, 16, 5, 7))
																																	 or ((data_transaction.transactiontype in (122)) and (DATA_SaleItem.ItemTransactionType in (14, 16, 5, 7))))
																															  and data_saleitem.unitrecharge &amp;#60;&amp;#62; 0
																																and ((@RRTransDateType = 0 and data_transaction.fTransactionDate = @BatchDate)
																																	OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
																														 )
																))
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
							  and RR_DATA_REVENUE.RRDays &amp;#60;&amp;#62; ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
						
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[TicketID]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs])
				   select *
				   from(
						select distinct coa_cnf_account.COAAccountId, 
								   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								   COA_CNF_AccountConfig.COAAccountConfigId,
								   coa_cnf_account.COAAccountTypeId,
								   RR_DATA_REVENUE.Transactionid as Transactionid,
								   RR_DATA_REVENUE.saleid as Saleid,
								   RR_DATA_REVENUE.Ticketid,
								   RR_DATA_REVENUE.SaleitemID as SaleitemID,
								   RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								   RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								   RR_DATA_REVENUE.Siteid as SiteID,
								   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								   RR_DATA_REVENUE.Workstationid as Workstationid,
								   RR_DATA_REVENUE.UserGroupid as UserGroupID,
								   RR_DATA_REVENUE.UserId as userID,
								   @BatchDate as BatchDate,
								   1 as Quantity,
								   RR_DATA_REVENUE.GrossAmount as GrossAmount,
								   RR_DATA_REVENUE.NetAmount as NetAmount,
								   COA_CNF_AccountConfig.Price as ConfigPrice,
								   COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								   COA_CNF_AccountConfig.RemainingValues,							 
								   ISNULL((RR_DATA_REVENUE.RevenueAmount - (select ISNULL(sum(revenueamount), 0)
								                            from RR_DATA_Revenue rr WITH(NOLOCK)
												              where rr.saleitemid = RR_DATA_REVENUE.SaleitemID
												        and rr.COAAccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
												 )
									), 0)
									as RevenueAmount,
								   case when TransactionType in (5,18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
								        when TransactionType in (5, 18, 20, 22, 30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1
								        else COA_CNF_AccountConfig.Accountingtype
									end Accountingtype,
								   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								   RR_CNF_RevenueRecognitionRule.Percentage,
								   RR_CNF_RevenueRecognitionRule.Days,
								   RR_DATA_REVENUE.AttributeIDs

						from RR_DATA_REVENUE WITH(NOLOCK)
								inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
								inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
								INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
								INNER JOIN coa_cnf_account WITH(NOLOCK)						on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
								INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
								INNER JOIN DATA_Transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid
								LEFT  join DATA_Ticket	WITH(NOLOCK)						on data_ticket.ticketid = rr_data_revenue.ticketid

							where RR_CNF_RevenueRecognitionRule.Enabled = 1
							  and coa_cnf_account.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and TransactionType in (10, 20, 18, 22, 5, 42, 43, 49)
							  and rr_data_revenue.RevenueAmount = (select ABS(unitrecharge)
															         from data_saleitem WITH(NOLOCK)
															        where saleitemid = RR_DATA_REVENUE.saleitemid)
							  and ((coa_cnf_accountConfig.Siteid = RR_DATA_REVENUE.SiteId) or (coa_cnf_accountConfig.Siteid is null))
							  and  ((RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnMoneyCardLoad, @OnExtMoneyCardLoad)) or
							((RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger) and 
							   (RR_DATA_Revenue.matrixcellid not IN(select Matrixcellid 
							                                          from @Matrixcells Matrixcellid1
																	  inner join RR_CNF_RevenueRecognitionRule RR WITH(NOLOCK)		ON RR.RevenueRecognitionRuleId = Matrixcellid1.RevenueRecognitionRuleId and RR.enabled = 1  
																	  where RR.RRCalcTypeTrigger IN (@OnMoneyCardLoad, @OnExtMoneyCardLoad)
																	)
								)
							)
						 )
						 )
							  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							  and COA_CNF_AccountConfig.RemainingValues = 1
							  and RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and RR_DATA_REVENUE.coaaccountid = @suspendid
							  and RR_DATA_REVENUE.RRDays &amp;#60;&amp;#62; ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
					)p
					where RevenueAmount &amp;#60;&amp;#62; 0				
	end

END

</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>A4E339AA2AB1429793FC79AA7FAD6753</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_OnMoneyCardUsage</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>10</Version><SQL>create Procedure [dbo].[otn_sp_RR_RevenueData_OnMoneyCardUsage]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @MoneyCardUsageTrigger Integer = 19

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																						and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyCardUsageTrigger

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyCardUsageTrigger

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyCardUsageTrigger
		)p

	BEGIN

		--Normal TicketExpired No Remaining Value
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[SaleId]
				   ,[UsageID]
				   ,[Ticketid]
				   ,[saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]			
				   ,[RRDays]
				   ,[AttributeIDs])
				   select distinct coa_cnf_account.COAAccountId, 
							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
							COA_CNF_AccountConfig.COAAccountConfigId,
							coa_cnf_account.COAAccountTypeId,
							p.saleid as Saleid,
							p.Usageid,
							p.Ticketid,
							p.saleitemid,
							p.Matrixcellid as Matrixcell,
							p.MatrixSheetId as MatrixSheetID,
							p.SaleSite as SiteID,
							p.OperatingAreaId as OperatingAreaID,
							p.Workstationid as Workstationid,
							p.UserId as userID,
							@BatchDate as BatchDate,
							1 as Quantity,
							ABS(ISNULL((p.optionValue), 0)) as grossamount,
							ABS(ISNULL(p.optionValue, 0)) as NetAmount,
							COA_CNF_AccountConfig.Price as ConfigPrice,
							COA_CNF_AccountConfig.Percentage as ConfigPercentage,
							COA_CNF_AccountConfig.RemainingValues,							
							ABS(p.optionValue) as RevenueAmount,
							COA_CNF_AccountConfig.AccountingType,
							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
							RR_CNF_RevenueRecognitionRule.Percentage,
							RR_CNF_RevenueRecognitionRule.Days,
							AttributeIDs
						from (			
							select  data_ticketusage.ticketid,
								        max(data_ticketusage.usageid) as usageid,
										1 as Quantity, 
										sum(cast(data_ticketusageoption.optionValue as float))*-1 optionValue,
										DATA_Ticket.Price as GrossAmount,
										DATA_Ticket.voidtype,
										CNF_MatrixCell.matrixcellid, 
										CNF_MatrixCell.code,
										CNF_MatrixCell.matrixsheetid, 
										DATA_Ticket.Siteid SaleSite,	  
										cnf_workstation.OperatingAreaId,
										cnf_workstation.workstationid,
										(select top 1 DATA_Sale.userid
											from data_saleitem
											INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as userid,
										(select top 1 data_saleitem.saleid
											from data_saleitem
											where data_saleitem.saleitemid = data_ticket.saleitemid
										) as Saleid,
										CNF_AttributeSet.AttributeIDs,
										CNF_AttributeSet.AttributeSetId,
										DATA_Ticket.saleitemid
							
							from data_ticketusage WITH(NOLOCK)
								    INNER  JOIN data_ticketusageoption WITH(NOLOCK)								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 5
									INNER JOIN DATA_Ticket	WITH(NOLOCK)										on DATA_Ticket.ticketid = data_ticketusage.ticketid
									LEFT  JOIN data_saleitem WITH(NOLOCK)										ON data_saleitem.saleitemid = data_ticket.saleitemid
									INNER JOIN CNF_MatrixCell	WITH(NOLOCK)									on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
									INNER JOIN CNF_AttributeSet	WITH(NOLOCK)									on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
									INNER JOIN CNF_Workstation	WITH(NOLOCK)									on cnf_workstation.workstationid = data_ticket.WorkstationId
													
								where data_ticketusage.validateResult &amp;#60;=99
								and data_ticketusage.UsageType =30					
								and cast(fusagedate as date) = @batchdate
								and cast(data_ticketusage.usagedate as date) &amp;#62;= cast(data_ticket.PrintDateTime as date)
								and data_ticket.FEncodeDate &amp;#62;= (select cast(rrstartdate as date) from CNF_System)

								group by data_ticketusage.ticketid,
										data_ticketusageoption.OptionValue,
										DATA_Ticket.Price,
										CNF_MatrixCell.matrixcellid, 
										CNF_MatrixCell.code,
										CNF_MatrixCell.matrixsheetid, 
										DATA_Ticket.Siteid,	  
										cnf_workstation.OperatingAreaId,
										cnf_workstation.workstationid,
										(DATA_Ticket.Price),
										CNF_AttributeSet.AttributeIDs,
										CNF_AttributeSet.AttributeSetId,
										data_ticket.producttaxtype,
										data_ticket.saleitemid,
										data_ticket.ticketid,
										data_saleitem.unitprice,
										DATA_Ticket.voidtype
								having sum(cast(data_ticketusageoption.optionValue as float))*-1 &amp;#62; 0
						)p 
						inner join @Matrixcells	Matrixcellid							ON Matrixcellid.matrixcellid = p.matrixcellid
						INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyCardUsageTrigger
						INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
						INNER JOIN COA_CNF_Account WITH(NOLOCK)							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid

						
						
						where RR_CNF_RevenueRecognitionRule.Enabled = 1
							and coa_cnf_account.Enabled = 1
							and p.VoidType = 0
							and COA_CNF_AccountConfig.Enabled = 1
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							and ((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1)
							    or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
							and p.usageid not in (select Usageid from rr_data_revenue rr where rr.FCalcDate = @BatchDate and Usageid is not null)
					
	END

END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>DDBC141413F6414FB5703371FD67A592</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnMoneyRefundTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>11</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnMoneyRefundTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @MoneyRefund Integer = 6

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	
		BEGIN

			--Normal Transaction No Remaining Values
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,	   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								(CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then   --Accounts not Tax not PaymentMethods 
									Case when p.Price &amp;#62; 0 then (p.Price * RR_DATA_REVENUE.Quantity) 
											else (ISNULL((((ABS(RR_DATA_REVENUE.RevenueAmount)) - ISNULL((select (ABS((sum(TaxAmount) * RR_DATA_REVENUE.Quantity)))
																									from data_saleitemTax WITH(NOLOCK)
																									where saleitemid = RR_DATA_REVENUE.SaleitemID), 0)) * p.Percentage/100), 0))
									end 																		                                                                                                                                                                                              
								end)  as RevenueAmount,
								1 Accountingtype,
								p.RRCalcTypeTrigger,
								p.rrPercentage,
								p.Days						
						
						
							from RR_DATA_REVENUE WITH(NOLOCK)
								INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_account.Code as accountcode,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyRefund
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (13)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues &amp;#60;&amp;#62; 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0


				--Normal Transaction with Remaining Values
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Saleitemid]
				   ,[MatrixCellid]
				   ,[MatrixSheetid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])
				   select *
				   from (
					select distinct p.COAAccountId, 
								p.RevenueRecognitionRuleId,	   
								p.RRCalcTypeWhere,
								p.RRCalcTypeMethod,	   
								p.COAAccountConfigId,
								p.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								RR_DATA_REVENUE.NetAmount as NetAmount,
								p.Price as ConfigPrice,
								p.Percentage as ConfigPercentage,
								p.RemainingValues,
								CASE WHEN p.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID) then																																													 
							    ABS(ABS(RR_DATA_REVENUE.RevenueAmount) -					 
								ISNULL((select ABS(sum(RevenueAmount))
										from RR_DATA_Revenue rrd WITH(NOLOCK)
									    where rrd.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId
										and rrd.RevenueRecognitionRuleId not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
										and rrd.transactionid = RR_DATA_REVENUE.transactionid
								), 0)) 
								else 0
								end RevenueAmount,
								1 Accountingtype,
									p.RRCalcTypeTrigger,
									p.rrPercentage,
									p.Days						
						
						
							from RR_DATA_REVENUE WITH(NOLOCK)
								INNER JOIN DATA_Transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN (select '1' as PCOAAccountid, 
												   coa_cnf_accountConfig.Siteid, 
												   RR_CNF_RevenueRecognitionRule.Enabled, 
												   RR_CNF_RevenueRecognitionRule.FromDate, 
												   RR_CNF_RevenueRecognitionRule.ToDate,
												   COA_CNF_AccountConfig.RemainingValues,
												   coa_cnf_account.coaaccountid,
												   COA_CNF_AccountConfig.Price,
												   COA_CNF_AccountConfig.Percentage,
												   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
												   RR_CNF_RevenueRecognitionRule.code,		   
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
												   COA_CNF_AccountConfig.COAAccountConfigId,
												   coa_cnf_account.COAAccountTypeId,
												   coa_cnf_accountconfig.Accountingtype,
												   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
												   RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
												   RR_CNF_RevenueRecognitionRule.Days	

												from RR_CNF_RevenueRecognitionRule	WITH(NOLOCK)
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid and coa_cnf_account.Enabled = 1
												INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
											where  RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @MoneyRefund
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.coaaccountid not in (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)) p				on p.PCOAAccountid = rr_data_revenue.coaaccountid 

							where transactiontype in (13)													 
								and p.Enabled = 1
								and ((p.Siteid = RR_DATA_REVENUE.Siteid) or (p.Siteid is null))
								and @BatchDate between p.FromDate and p.ToDate
								and p.RemainingValues = 1
								and RR_DATA_REVENUE.fcalcdate = @BatchDate		
					)r 
					where r.revenueAmount &amp;#60;&amp;#62; 0

	end
END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>B15EBE0F4F65423D95C50DE9335D8E81</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnSaleTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>57</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnSaleTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1
	Declare @DepositTrigger int = 5
	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnSaleTrigger

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnSaleTrigger

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnSaleTrigger
		)p


	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	 where Code = 'SUSPENSE'
	   and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	 where Code = 'TAXES'
	   and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	 where Code = 'PYMTMETHOD'
	   and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	 where Code = 'DISCOUNTS'
	   and SystemAccount = 1


	BEGIN
																		  
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs]
						,[JournalEntryByAccount])
		select *
		  from(
				select distinct coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								COA_CNF_AccountConfig.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid,
								RR_DATA_REVENUE.OperatingAreaId,
								RR_DATA_REVENUE.Workstationid,
								RR_DATA_REVENUE.UserGroupid,
								RR_DATA_REVENUE.UserId,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity,
								RR_DATA_REVENUE.GrossAmount,
								RR_DATA_REVENUE.NetAmount,
								COA_CNF_AccountConfig.Price,
								COA_CNF_AccountConfig.Percentage,
								COA_CNF_AccountConfig.RemainingValues,								
								Case when RR_DATA_REVENUE.ticketid is null and data_saleitem.ProductType = 1 then 0
								     when RR_DATA_REVENUE.ticketid is not null and data_saleitem.ProductType = 1 and 
									        (select voidtype from data_ticket WITH(NOLOCK) where data_ticket.ticketid = RR_DATA_Revenue.ticketid) in (104, 125)
									 																 
									 then 0
								     when COA_CNF_AccountConfig.Price &amp;#62; 0 and COA_CNF_AccountConfig.Price &amp;#60; rr_data_revenue.RevenueAmount then ABS((COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity))								     
									 when COA_CNF_AccountConfig.Price &amp;#62; 0 and COA_CNF_AccountConfig.Price &amp;#62; rr_data_revenue.RevenueAmount then ABS((rr_data_revenue.RevenueAmount * RR_DATA_REVENUE.Quantity))								     
									 
									 else ISNULL(ABS(((RR_DATA_REVENUE.RevenueAmount) * COA_CNF_AccountConfig.percentage)/100), 0)									
								end 																		                                                                                                                                                                                              
								as RevenueAmount,
								RR_DATA_Revenue.Accountingtype,								
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage rrPercentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs,
								0 as Journal
		
				  from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid						
						INNER JOIN DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid

				 where  RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and coa_cnf_account.Enabled = 1
				   and COA_CNF_AccountConfig.Enabled = 1
				   and ((data_transaction.transactiontype in (9, 14, 16, 38, 119)) or ((data_transaction.transactiontype in (122)) 
				         and (DATA_SaleItem.ItemTransactionType  in (14, 16, 119))))
				   and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid 
				   and RR_DATA_REVENUE.Quantity &amp;#62; 0
				   and RR_DATA_REVENUE.RRDays = ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
			)p
			where RevenueAmount &amp;#60;&amp;#62; 0

			INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs]
						,[JournalEntryByAccount])
		select *
		from(
				select distinct coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,							   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								COA_CNF_AccountConfig.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								COA_CNF_AccountConfig.Price as ConfigPrice,
								COA_CNF_AccountConfig.Percentage as ConfigPercentage,
								COA_CNF_AccountConfig.RemainingValues,
								case when RR_DATA_REVENUE.ticketid is null and data_saleitem.ProductType = 1 then 0
								     when TransactionType = 5 and paidtransactionid = null then 0
									 when ISNULL(
																							abs(ISNULL((select sum(revenueamount)
																										  from rr_data_revenue rdr1 WITH(NOLOCK)
																										 where rdr1.ticketid = RR_DATA_REVENUE.ticketid
																										   and rdr1.transactionid = RR_DATA_REVENUE.transactionid
																										   and rdr1.FCalcDate = rr_data_revenue.FCalcDate
																										   and rdr1.coaaccountid = @SuspendID
																									   ), 0))
																							-															  								  								  					
																							ISNULL((select ABS(sum(RevenueAmount))
																									  from RR_Data_Revenue rdr WITH(NOLOCK)
																									  where rdr.ticketid = RR_DATA_REVENUE.ticketid
																										and rdr.transactionid = rr_data_revenue.transactionid
																										and rdr.FCalcDate = rr_data_revenue.FCalcDate
																										and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
																									), 0)
																						, RR_DATA_REVENUE.revenueamount) &amp;#60; 0 then 0
								     when RR_DATA_REVENUE.ticketid is not null then ISNULL(
																							abs(ISNULL((select sum(revenueamount)
																										  from rr_data_revenue rdr1 WITH(NOLOCK)
																										 where rdr1.ticketid = RR_DATA_REVENUE.ticketid
																										   and rdr1.transactionid = RR_DATA_REVENUE.transactionid
																										   and rdr1.FCalcDate = rr_data_revenue.FCalcDate
																										   and rdr1.coaaccountid = @SuspendID
																									   ), 0))
																							-															  								  								  					
																							ISNULL((select ABS(sum(RevenueAmount))
																									  from RR_Data_Revenue rdr WITH(NOLOCK)
																									  where rdr.ticketid = RR_DATA_REVENUE.ticketid
																										and rdr.transactionid = rr_data_revenue.transactionid
																										and rdr.FCalcDate = rr_data_revenue.FCalcDate
																										and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
																									), 0)
																						, RR_DATA_REVENUE.revenueamount)
									else ISNULL(
																							abs(ISNULL((select sum(revenueamount)
																										  from rr_data_revenue rdr1 WITH(NOLOCK)
																										 where rdr1.saleitemid = RR_DATA_REVENUE.saleitemid
																										   and rdr1.transactionid = RR_DATA_REVENUE.transactionid 
																										   and rdr1.coaaccountid = @SuspendID
																										   and rdr1.SaleItemRuleID is null
																										   and rdr1.FCalcDate = rr_data_revenue.FCalcDate
																										   and rdr1.SaleItemTaxId is null
																									   ), 0))
																							-															  								  								  					
																							ISNULL((select ABS(sum(RevenueAmount))
																									  from RR_Data_Revenue rdr WITH(NOLOCK)
																									  where rdr.saleitemid = RR_DATA_REVENUE.saleitemid
																										and rdr.transactionid = rr_data_revenue.transactionid
																										and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
																										and rdr.SaleItemRuleID is null
																										and rdr.FCalcDate = rr_data_revenue.FCalcDate
																										and rdr.SaleItemTaxId is null
																									), 0)
																						, RR_DATA_REVENUE.revenueamount)
								end
								as RevenueAmount,
								RR_DATA_Revenue.Accountingtype,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs,
								0 journal

				  from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	as Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN COA_CNF_AccountConfig	WITH(NOLOCK)			on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
						INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_Sale WITH(NOLOCK)							on DATA_Sale.SaleId = RR_DATA_REVENUE.SaleId
						INNER JOIN DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid


				 where RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and coa_cnf_account.Enabled = 1
				   and COA_CNF_AccountConfig.Enabled = 1
				   and ((data_transaction.transactiontype in (9, 14, 16, 119)) or ((data_transaction.transactiontype in (122)) 
				         and (DATA_SaleItem.ItemTransactionType  in (14, 16, 119))))
				   and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and COA_CNF_AccountConfig.RemainingValues = 1
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid	
				   and RR_DATA_REVENUE.RRDays = ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
		 )p
		 where RevenueAmount &amp;#60;&amp;#62; 0


	--INSERT INTO [dbo].[RR_DATA_Revenue]
	--					([COAAccountId]
	--					,[RevenueRecognitionRuleId]
	--					,[RRCalcTypeWhere]
	--					,[RRCalcTypeMethod]
	--					,[COAAccountConfigId]
	--					,[COAAccountType]
	--					,[TransactionId]
	--					,[SaleId]
	--					,[TicketID]
	--					,[UnitAmount]
	--					,[Saleitemid]
	--					,[MatrixCellid]
	--					,[MatrixSheetid]
	--					,[SiteId]
	--					,[OperatingAreaId]
	--					,[WorkstationId]
	--					,[UserGroupId]
	--					,[UserId]
	--					,[FCalcDate]
	--					,[Quantity]
	--					,[GrossAmount]
	--					,[NetAmount]
	--					,[Price]
	--					,[Percentage]
	--					,[RemaningValues]
	--					,[RevenueAmount]
	--					,[AccountingType]
	--					,[RRCalcTypeTrigger]
	--					,[RRPercentage]
	--					,[RRDays]
	--					,[AttributeIDs]
	--					,[JournalEntryByAccount])
	--	select *
	--	  from(
	--			select distinct coa_cnf_account.COAAccountId, 
	--							RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
	--							RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
	--							RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
	--							COA_CNF_AccountConfig.COAAccountConfigId,
	--							coa_cnf_account.COAAccountTypeId,
	--							RR_DATA_REVENUE.Transactionid,
	--							RR_DATA_REVENUE.saleid,
	--							RR_DATA_REVENUE.TicketID,
	--							RR_DATA_Revenue.UnitAmount,
	--							RR_DATA_REVENUE.SaleitemID as SaleitemID,
	--							RR_DATA_REVENUE.Matrixcellid as Matrixcell,
	--							RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
	--							RR_DATA_REVENUE.Siteid as SiteID,
	--							RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
	--							RR_DATA_REVENUE.Workstationid as Workstationid,
	--							RR_DATA_REVENUE.UserGroupid as UserGroupID,
	--							RR_DATA_REVENUE.UserId as userID,
	--							@BatchDate as BatchDate,
	--							RR_DATA_REVENUE.Quantity,
	--							RR_DATA_REVENUE.GrossAmount,
	--							RR_DATA_REVENUE.NetAmount,
	--							COA_CNF_AccountConfig.Price,
	--							COA_CNF_AccountConfig.Percentage,
	--							COA_CNF_AccountConfig.RemainingValues,								
	--							Case when RR_DATA_REVENUE.ticketid is null and data_saleitem.ProductType = 1 then 0
	--							     when COA_CNF_AccountConfig.Price &amp;#62; 0 then ABS((COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity))
	--							     else ISNULL(ABS(((RR_DATA_REVENUE.RevenueAmount) * COA_CNF_AccountConfig.percentage)/100), 0)									 
	--							end as RevenueAmount,
	--							RR_DATA_REVENUE.Accountingtype,
	--							RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
	--							RR_CNF_RevenueRecognitionRule.Percentage RRPercentage,
	--							RR_CNF_RevenueRecognitionRule.Days,
	--							RR_DATA_Revenue.AttributeIDs,
	--							0 Journal
		
	--			  from RR_DATA_REVENUE WITH(NOLOCK)
	--					inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
	--					inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
	--					INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
	--					INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
	--					INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
	--					INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid						
	--					INNER JOIN DATA_SaleItem WITH(NOLOCK)						on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid


	--			 where  RR_CNF_RevenueRecognitionRule.Enabled = 1
	--			   and coa_cnf_account.Enabled = 1
	--			   and COA_CNF_AccountConfig.Enabled = 1
	--			   and ((data_transaction.transactiontype in (5))
	--			   and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
	--			   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
	--			   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
	--			   and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
	--			   and RR_DATA_REVENUE.fcalcdate = @BatchDate
	--			   and RR_DATA_REVENUE.coaaccountid = @suspendid 
	--			   and RR_DATA_REVENUE.Quantity &amp;#60; 0
	--			   and RR_DATA_REVENUE.RRDays = ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
	--		)p
	--		where RevenueAmount &amp;#60;&amp;#62; 0

		-- 	INSERT INTO [dbo].[RR_DATA_Revenue]
		--				([COAAccountId]
		--				,[RevenueRecognitionRuleId]
		--				,[RRCalcTypeWhere]
		--				,[RRCalcTypeMethod]
		--				,[COAAccountConfigId]
		--				,[COAAccountType]
		--				,[TransactionId]
		--				,[SaleId]
		--				,[TicketID]
		--				,[UnitAmount]
		--				,[Saleitemid]
		--				,[MatrixCellid]
		--				,[MatrixSheetid]
		--				,[SiteId]
		--				,[OperatingAreaId]
		--				,[WorkstationId]
		--				,[UserGroupId]
		--				,[UserId]
		--				,[FCalcDate]
		--				,[Quantity]
		--				,[GrossAmount]
		--				,[NetAmount]
		--				,[Price]
		--				,[Percentage]
		--				,[RemaningValues]
		--				,[RevenueAmount]
		--				,[AccountingType]
		--				,[RRCalcTypeTrigger]
		--				,[RRPercentage]
		--				,[RRDays]
		--				,[AttributeIDs]
		--				,[JournalEntryByAccount])
		--select *
		--  from(
		--		select distinct coa_cnf_account.COAAccountId, 
		--						RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
		--						RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		--						RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		--						COA_CNF_AccountConfig.COAAccountConfigId,
		--						coa_cnf_account.COAAccountTypeId,
		--						RR_DATA_REVENUE.Transactionid as Transactionid,
		--						RR_DATA_REVENUE.saleid as Saleid,
		--						rr_data_revenue.Ticketid,
		--						RR_DATA_Revenue.UnitAmount,
		--						RR_DATA_REVENUE.SaleitemID as SaleitemID,
		--						RR_DATA_REVENUE.Matrixcellid as Matrixcell,
		--						RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
		--						RR_DATA_REVENUE.Siteid as SiteID,
		--						RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
		--						RR_DATA_REVENUE.Workstationid as Workstationid,
		--						RR_DATA_REVENUE.UserGroupid as UserGroupID,
		--						RR_DATA_REVENUE.UserId as userID,
		--						@BatchDate as BatchDate,
		--						RR_DATA_REVENUE.Quantity as Quantity,
		--						RR_DATA_REVENUE.GrossAmount as GrossAmount,
		--						ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
		--						COA_CNF_AccountConfig.Price as ConfigPrice,
		--						COA_CNF_AccountConfig.Percentage as ConfigPercentage,
		--						COA_CNF_AccountConfig.RemainingValues,								
		--						ABS(case when ISNULL(COA_CNF_AccountConfig.Price, 0) &amp;#60;&amp;#62; 0 then .COA_CNF_AccountConfig.Price								
		--						     else RR_DATA_REVENUE.RevenueAmount
			
		--							 * (COA_CNF_AccountConfig.Percentage/100)
		--						end) RevenueAmount,																
		--						case when RR_DATA_Revenue.Accountingtype = 1 and RR_DATA_REVENUE.Quantity &amp;#60; 0 then 1
		--							 when RR_DATA_Revenue.Accountingtype = 2 and RR_DATA_REVENUE.Quantity &amp;#62; 0 then 2
		--						     when COA_CNF_AccountConfig.Accountingtype = 1 then 2
		--							 when COA_CNF_AccountConfig.Accountingtype = 2 then 1									
		--							 else COA_CNF_AccountConfig.Accountingtype
		--						end Accountingtype,
		--						--99 accounting,
		--						RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		--						RR_CNF_RevenueRecognitionRule.Percentage,
		--						RR_CNF_RevenueRecognitionRule.Days,
		--						RR_DATA_Revenue.AttributeIDs,
		--						0 journal
		



		--		  from RR_DATA_REVENUE WITH(NOLOCK)
		--				inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
		--				inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
		--				INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
		--				INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
		--				INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
		--				INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid

		--		 where  RR_CNF_RevenueRecognitionRule.Enabled = 1
		--		   and coa_cnf_account.Enabled = 1
		--		   and COA_CNF_AccountConfig.Enabled = 1
		--		   and (data_transaction.transactiontype in (30))
		--		   and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
		--		   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
		--		   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
		--		   and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
		--		   and RR_DATA_REVENUE.fcalcdate = @BatchDate
		--		   and RR_DATA_REVENUE.coaaccountid = @suspendid 
		--		   and RR_DATA_REVENUE.Quantity &amp;#62; 0
		--		   and RR_DATA_REVENUE.RRDays = ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
		--	)p
		--	where RevenueAmount &amp;#60;&amp;#62; 0

		--INSERT INTO [dbo].[RR_DATA_Revenue]
		--				([COAAccountId]
		--				,[RevenueRecognitionRuleId]
		--				,[RRCalcTypeWhere]
		--				,[RRCalcTypeMethod]
		--				,[COAAccountConfigId]
		--				,[COAAccountType]
		--				,[TransactionId]
		--				,[SaleId]
		--				,[TicketID]
		--				,[UnitAmount]
		--				,[Saleitemid]
		--				,[MatrixCellid]
		--				,[MatrixSheetid]
		--				,[SiteId]
		--				,[OperatingAreaId]
		--				,[WorkstationId]
		--				,[UserGroupId]
		--				,[UserId]
		--				,[FCalcDate]
		--				,[Quantity]
		--				,[GrossAmount]
		--				,[NetAmount]
		--				,[Price]
		--				,[Percentage]
		--				,[RemaningValues]
		--				,[RevenueAmount]
		--				,[AccountingType]
		--				,[RRCalcTypeTrigger]
		--				,[RRPercentage]
		--				,[RRDays]
		--				,[AttributeIDs]
		--				,[JournalEntryByAccount])
		--select *
		--from(
		--		select distinct coa_cnf_account.COAAccountId, 
		--						RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,							   
		--						RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		--						RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		--						COA_CNF_AccountConfig.COAAccountConfigId,
		--						coa_cnf_account.COAAccountTypeId,
		--						RR_DATA_REVENUE.Transactionid as Transactionid,
		--						RR_DATA_REVENUE.saleid as Saleid,
		--						RR_DATA_REVENUE.TicketID,
		--						RR_DATA_Revenue.UnitAmount,
		--						RR_DATA_REVENUE.SaleitemID as SaleitemID,
		--						RR_DATA_REVENUE.Matrixcellid as Matrixcell,
		--						RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
		--						RR_DATA_REVENUE.Siteid as SiteID,
		--						RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
		--						RR_DATA_REVENUE.Workstationid as Workstationid,
		--						RR_DATA_REVENUE.UserGroupid as UserGroupID,
		--						RR_DATA_REVENUE.UserId as userID,
		--						@BatchDate as BatchDate,
		--						RR_DATA_REVENUE.Quantity as Quantity,
		--						RR_DATA_REVENUE.GrossAmount as GrossAmount,
		--						ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
		--						COA_CNF_AccountConfig.Price as ConfigPrice,
		--						COA_CNF_AccountConfig.Percentage as ConfigPercentage,
		--						COA_CNF_AccountConfig.RemainingValues,
		--						case when TransactionType = 5 and paidtransactionid = null then 0
		--						     when RR_DATA_REVENUE.ticketid is not null then ISNULL(
		--																					abs(ISNULL((select sum(revenueamount)
		--																								  from rr_data_revenue rdr1 WITH(NOLOCK)
		--																								 where rdr1.ticketid = RR_DATA_REVENUE.ticketid
		--																								   and rdr1.transactionid = RR_DATA_REVENUE.transactionid 
		--																								   and rdr1.coaaccountid = @SuspendID
		--																							   ), 0))
		--																					-															  								  								  					
		--																					ISNULL((select ABS(sum(RevenueAmount))
		--																							  from RR_Data_Revenue rdr WITH(NOLOCK)
		--																							  where rdr.ticketid = RR_DATA_REVENUE.ticketid
		--																								and rdr.transactionid = rr_data_revenue.transactionid
		--																								and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
		--																							), 0)
		--																				, RR_DATA_REVENUE.revenueamount)
		--							else ISNULL(
		--																					abs(ISNULL((select sum(revenueamount)
		--																								  from rr_data_revenue rdr1 WITH(NOLOCK)
		--																								 where rdr1.saleitemid = RR_DATA_REVENUE.saleitemid
		--																								   and rdr1.transactionid = RR_DATA_REVENUE.transactionid 
		--																								   and rdr1.coaaccountid = @SuspendID
		--																								   and rdr1.SaleItemRuleID is null
		--																								   and rdr1.SaleItemTaxId is null
		--																							   ), 0))
		--																					-															  								  								  					
		--																					ISNULL((select ABS(sum(RevenueAmount))
		--																							  from RR_Data_Revenue rdr WITH(NOLOCK)
		--																							  where rdr.saleitemid = RR_DATA_REVENUE.saleitemid
		--																								and rdr.transactionid = rr_data_revenue.transactionid
		--																								and rdr.COAAccountid NOT in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
		--																								and rdr.SaleItemRuleID is null
		--																								and rdr.SaleItemTaxId is null
		--																							), 0)
		--																				, RR_DATA_REVENUE.revenueamount)
		--						end
		--						as RevenueAmount,
		--						case when DATA_Transaction.TransactionType in (30) and RR_DATA_Revenue.Accountingtype = 1 and RR_DATA_REVENUE.Quantity &amp;#60; 0 then 1
		--							 when DATA_Transaction.TransactionType in (30) and RR_DATA_Revenue.Accountingtype = 2 and RR_DATA_REVENUE.Quantity &amp;#62; 0 then 2
		--						     when DATA_Transaction.TransactionType in (30) and COA_CNF_AccountConfig.Accountingtype = 1 then 2
		--							 when DATA_Transaction.TransactionType in (30) and COA_CNF_AccountConfig.Accountingtype = 2 then 1									
		--							 else COA_CNF_AccountConfig.Accountingtype
		--						end Accountingtype,
		--						RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		--						RR_CNF_RevenueRecognitionRule.Percentage,
		--						RR_CNF_RevenueRecognitionRule.Days,
		--						RR_DATA_Revenue.AttributeIDs,
		--						0 journal

		--		  from RR_DATA_REVENUE WITH(NOLOCK)
		--				inner join @Matrixcells	as Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
		--				inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
		--				INNER JOIN COA_CNF_AccountConfig	WITH(NOLOCK)			on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
		--				INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
		--				INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 
		--				INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
		--				INNER JOIN DATA_Sale WITH(NOLOCK)							on DATA_Sale.saleid = rr_data_revenue.saleid

		--		 where RR_CNF_RevenueRecognitionRule.Enabled = 1
		--		   and coa_cnf_account.Enabled = 1
		--		   and COA_CNF_AccountConfig.Enabled = 1
		--		   and (data_transaction.transactiontype in (30))  
		--		   and ((coa_cnf_accountConfig.Siteid = RR_Data_Revenue.SiteId) or (coa_cnf_accountConfig.Siteid is null))
		--		   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
		--		   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
		--		   and COA_CNF_AccountConfig.RemainingValues = 1
		--		   and RR_DATA_REVENUE.fcalcdate = @BatchDate
		--		   and RR_DATA_REVENUE.coaaccountid = @suspendid	
		--		   and RR_DATA_REVENUE.RRDays = ISNULL(RR_CNF_RevenueRecognitionRule.Days, 0)
		-- )p
		-- where RevenueAmount &amp;#60;&amp;#62; 0

--Reverse of a Deposit 
		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select distinct RR_DATA_REVENUE.COAAccountId, 
						RR_DATA_REVENUE.RevenueRecognitionRuleId,   
						RR_DATA_REVENUE.RRCalcTypeWhere,
						RR_DATA_REVENUE.RRCalcTypeMethod,	   
						RR_DATA_REVENUE.COAAccountConfigId,
						RR_DATA_REVENUE.COAAccountType,
						p.Transactionid as Transactionid,					
						ISNULL(p.saleid, RR_DATA_REVENUE.saleid) as Saleid,
						p.Siteid as SiteID,
						p.OperatingAreaId as OperatingAreaID,
						p.Workstationid as Workstationid,
						p.UserGroupid as UserGroupID,
						p.UserId as userID,
						@BatchDate as BatchDate,
						RR_DATA_REVENUE.Quantity as Quantity,
						RR_DATA_REVENUE.GrossAmount as GrossAmount,
						RR_DATA_REVENUE.NetAmount as NetAmount,
						RR_DATA_REVENUE.Price as ConfigPrice,
						RR_DATA_REVENUE.Percentage as ConfigPercentage,
						RR_DATA_REVENUE.RemaningValues, 
						RR_DATA_REVENUE.revenueamount  as RevenueAmount,
						case when RR_DATA_REVENUE.accountingtype = 1 then 2
							 else 1
						end as Accountingtype,
						RR_DATA_REVENUE.RRCalcTypeTrigger,
						RR_DATA_REVENUE.rrPercentage,
						RR_DATA_REVENUE.rrDays,
						RR_DATA_REVENUE.attributeids
										
		from RR_DATA_REVENUE WITH(NOLOCK)
			INNER JOIN DATA_Transaction	 WITH(NOLOCK)							on data_transaction.transactionid = rr_data_revenue.transactionid
			INNER JOIN (select distinct RR_DATA_REVENUE.Accountingtype, 
			                            rr_data_revenue.siteid, 
										rr_data_revenue.transactionid, 
										rr_data_revenue.saleid, 
										rr_data_revenue.Operatingareaid, 
										rr_data_revenue.workstationid, 
										rr_data_revenue.usergroupid, 
										rr_data_revenue.userid,
										rr_data_revenue.fcalcdate,
										DATA_Transaction.transactiontype
						  from rr_data_revenue WITH(NOLOCK)
							   INNER JOIN DATA_Transaction WITH(NOLOCK)			on data_transaction.transactionid = rr_data_revenue.transactionid
						 where  DATA_Transaction.transactiontype = 16  
						   and data_transaction.paid = 1
					   )p														on p.saleid = rr_data_revenue.saleid

		 where DATA_Transaction.transactiontype in (12, 15)
		   and rrcalctypetrigger &amp;#60;&amp;#62; @suspendid
		   and rr_data_revenue.coaaccountid not in (select coaaccountid
													  from cnf_paymentMethod
													 where coaaccountid is not null
													Union all
													select coaaccountid
													  from cnf_paymentcard
													 where coaaccountid is not null
													Union all 
													select coaaccountid
													  from cnf_tax
													 where coaaccountid is not null
													Union all 
													select coaaccountid
													  from cnf_promotion
													 where coaaccountid is not null
												   )											  										
		  and p.fcalcdate = @BatchDate
		  and RR_DATA_REVENUE.coaaccountid not in  (@ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
														   										   																																																																																																			
	End
END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>3B3C35AE21784556956BEB2864514EC6</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnTicketExpiredTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>36</Version>
					<SQL>create Procedure [dbo].[otn_sp_RR_RevenueData_OnTicketExpiredTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @TicketUsageTrigger Integer = 2	
	Declare @OnTimePeriodTrigger Integer = 4
	Declare @OnEventTriger Integer = 17
	Declare @TicketExpiredTrigger Integer = 3
	Declare @MoneyCardUsageTrigger integer = 19
	Declare @MatrixCount integer = 0

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product WITH(NOLOCK)
					INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																								and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger 

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product WITH(NOLOCK)
					INNER JOIN CNF_MatrixCell WITH(NOLOCK)									on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																									and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger 

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product WITH(NOLOCK)
					INNER JOIN CNF_AttributeSetDetail WITH(NOLOCK)					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell WITH(NOLOCK)	 						on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)			on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																						and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger 
		)p
	
	
	select @MatrixCount = COUNT(*)
	  from @Matrixcells

	BEGIN
		if @MatrixCount &amp;#62; 0
		BEGIN
					--Normal TicketExpired No Remaining Value
						INSERT INTO [dbo].[RR_DATA_Revenue]
							   ([COAAccountId]
							   ,[RevenueRecognitionRuleId]
							   ,[RRCalcTypeWhere]
							   ,[RRCalcTypeMethod]
							   ,[COAAccountConfigId]
							   ,[COAAccountType]
							   ,[Ticketid]
							   ,[SaleitemID]
							   ,[SaleID]
							   ,[TransactionID]
							   ,[MatrixCellid]
							   ,[MatrixSheetid]
							   ,[SiteId]
							   ,[FCalcDate]
							   ,[Quantity]
							   ,[GrossAmount]
							   ,[NetAmount]
							   ,[Price]
							   ,[Percentage]
							   ,[RemaningValues]
							   ,[RevenueAmount]
							   ,[AccountingType]
							   ,[RRCalcTypeTrigger]
							   ,[RRPercentage]
							   ,[RRDays]
							   ,[AttributeIDs]
							   ,[oobflag])
							   select *
							   from(
							select COA_CNF_AccountConfig.COAAccountId, 
										RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
										COA_CNF_AccountConfig.COAAccountConfigId,
										coa_cnf_account.COAAccountTypeId,
										data_ticket.Ticketid as Ticketid,
										data_saleitem.Saleitemid,
										data_saleitem.saleid,
										data_sale.PaidTransactionId transactionid,
										CNF_MatrixCell.Matrixcellid as Matrixcell,
										CNF_MatrixCell.MatrixSheetId as MatrixSheetID,
										DATA_Ticket.Siteid as SiteID,
										@BatchDate as BatchDate,
										1 as Quantity,
										0 as GrossAmount,
										0 as NetAmount,
										COA_CNF_AccountConfig.Price as ConfigPrice,
										COA_CNF_AccountConfig.Percentage as ConfigPercentage,
										COA_CNF_AccountConfig.RemainingValues,							
										ABS(ISNULL(Case when COA_CNF_AccountConfig.Price &amp;#62; 0 and ISNULL(p.NetPrice, 0) &amp;#60;&amp;#62; ISNULL(rdata.totalused, 0)  and (p.NetPrice - ISNULL(rdata.totalused, 2)) &amp;#62; 0  then (COA_CNF_AccountConfig.Price)
											 else
												 case when p.NetPrice &amp;#62; 0 then 
														Case when ISNULL(p.NetPrice, 0) &amp;#60;&amp;#62; ISNULL(rdata.totalused, 0)  and (p.NetPrice - ISNULL(rdata.totalused, 2))  &amp;#62; 0 then
																ABS((p.NetPrice - ISNULL(rdata.totalused, 0)) * COA_CNF_AccountConfig.Percentage/100)
														 else 0
														END
													else 0
													end
										end, 0)) as RevenueAmount,
						 	
										COA_CNF_AccountConfig.AccountingType,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage,
										RR_CNF_RevenueRecognitionRule.Days,
										null AttributeIDs,
										0 oobflag

							from DATA_Ticket WITH(NOLOCK)
								INNER JOIN data_saleitem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_ticket.saleitemid
								INNER JOIN data_sale WITH(NOLOCK)								ON data_sale.saleid = ISNULL(data_saleitem.BaseSaleId, data_saleitem.saleid)
																									and data_sale.Paid = 1							 
								INNER JOIN @Matrixcells MatrixcellID 							ON MatrixcellID.MatrixcellID = DATA_Ticket.MatrixcellID
								INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)			ON MatrixcellID.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																									and	RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
																									and rr_cnf_revenuerecognitionRule.Enabled = 1
								INNER JOIN COA_CNF_AccountConfig	WITH(NOLOCK)				ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
																									and COA_CNF_AccountConfig.Enabled = 1
																									and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
								INNER JOIN COA_CNF_Account		WITH(NOLOCK)					on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
								INNER JOIN CNF_MatrixCell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = MatrixcellID.matrixcellid
							 
									LEFT JOIN (select rr_data_revenue.ticketid, AccountingType, ABS(sum(revenueamount)) as TotalUsed
												from rr_data_revenue WITH(NOLOCK)
													inner join DATA_Ticket WITH(NOLOCK)				on DATA_Ticket.TicketId = RR_DATA_Revenue.ticketid
												where CAST(activeto as date) = @batchdate
												and rr_data_revenue.RRCalcTypeTrigger in (@TicketUsageTrigger, @OnTimePeriodTrigger, @OnEventTriger)
												and isnull(oobflag, 0) = 0
												group by rr_data_revenue.ticketid, AccountingType
												)rdata									ON rdata.ticketid = data_ticket.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType	
									LEFT JOIN (select data_ticket.ticketid, SUM(revenueamount) NetPrice
																	   from RR_DATA_Revenue WITH(NOLOCK)
																			inner join DATA_Ticket WITH(NOLOCK)				on DATA_Ticket.TicketId = data_ticket.ticketid
								where CAST(activeto as date) = @batchdate
								and RRCalcTypeTrigger = 1
								and AccountingType = 2
								and RR_DATA_Revenue.TicketId = data_ticket.ticketid
								and COAAccountId not in (1, 2, 3, 4)
								and SaleItemTaxId is null
								and SaleItemRuleID is null
								and paymentID is null
								and isnull(oobflag, 0) = 0
								and ISNULL(JournalEntryByAccount, 0) = 0
												group by data_ticket.ticketid
												)p									ON p.ticketid = data_ticket.ticketid	









						where cast(data_ticket.activeto as date) = @batchdate
						and ((data_ticket.VoidType &amp;#60;= 99) or (data_ticket.VoidType = 203) or
													((data_ticket.VoidType in (109, 102, 125)) and
													(select top 1  DATA_Transaction.FTransactionDate
														from data_transaction2ticket WITH(NOLOCK)
															INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																															and DATA_Transaction.TransactionType in (18, 20, 22)
														where data_transaction2ticket.TicketId = data_ticket.ticketid
													) &amp;#62; @batchdate

												))
							and data_ticket.FEncodeDate &amp;#62;= (select cast(rrstartdate as date) from CNF_System WITH(NOLOCK))
							)p
							where RevenueAmount &amp;#60;&amp;#62; 0 



					--Normal TicketExpired with Remaining Value
						INSERT INTO [dbo].[RR_DATA_Revenue]
							   ([COAAccountId]
							   ,[RevenueRecognitionRuleId]
							   ,[RRCalcTypeWhere]
							   ,[RRCalcTypeMethod]
							   ,[COAAccountConfigId]
							   ,[COAAccountType]
							   ,[Ticketid]
							   ,[SaleItemid]
							   ,[SaleID]
							   ,[TransactionID]
							   ,[MatrixCellid]
							   ,[MatrixSheetid]
							   ,[SiteId]
							   ,[FCalcDate]
							   ,[Quantity]
							   ,[GrossAmount]
							   ,[NetAmount]
							   ,[Price]
							   ,[Percentage]
							   ,[RemaningValues]
							   ,[RevenueAmount]
							   ,[AccountingType]
							   ,[RRCalcTypeTrigger]
							   ,[RRPercentage]
							   ,[RRDays]
							   ,[AttributeIDs]
							   ,[oobflag])
							   select *
							   from(
								 select COA_CNF_AccountConfig.COAAccountId, 
										RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
										RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
										COA_CNF_AccountConfig.COAAccountConfigId,
										coa_cnf_account.COAAccountTypeId,
										data_ticket.Ticketid as Ticketid,
										data_saleitem.Saleitemid,
										data_saleitem.saleid,
										DATA_Sale.PaidTransactionId transactionid,
										CNF_MatrixCell.Matrixcellid as Matrixcell,
										CNF_MatrixCell.MatrixSheetId as MatrixSheetID,
										data_ticket.Siteid as SiteID,
										@BatchDate as BatchDate,
										1 as Quantity,
										0 as GrossAmount,
										0 as NetAmount,
										COA_CNF_AccountConfig.Price as ConfigPrice,
										COA_CNF_AccountConfig.Percentage as ConfigPercentage,
										COA_CNF_AccountConfig.RemainingValues,	
										ABS(ISNULL(Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price)
											 else
												 case when p.NetPrice &amp;#62; 0 then 
														Case when ISNULL(p.NetPrice, 0) &amp;#60;&amp;#62; ISNULL(rdata.totalused, 0)  and (p.NetPrice - ISNULL(rdata.totalused, 2)) &amp;#62; 0 then
																ABS((p.NetPrice - ISNULL(rdata.totalused, 0)) * COA_CNF_AccountConfig.Percentage/100)
														 else 0
														END
													else 0
													end
										end, 0)) as RevenueAmount,
										COA_CNF_AccountConfig.AccountingType,
										RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
										RR_CNF_RevenueRecognitionRule.Percentage,
										RR_CNF_RevenueRecognitionRule.Days,
										null AttributeIDs,
										0 as oobflag

							from DATA_Ticket WITH(NOLOCK)
								INNER JOIN data_saleitem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_ticket.saleitemid
								INNER JOIN data_sale WITH(NOLOCK)								ON data_sale.saleid = ISNULL(data_saleitem.BaseSaleId, data_saleitem.saleid)
																									and data_sale.Paid = 1							 
								INNER JOIN @Matrixcells MatrixcellID 							ON MatrixcellID.MatrixcellID = DATA_Ticket.MatrixcellID
								INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)			ON MatrixcellID.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																									and	RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
																									and rr_cnf_revenuerecognitionRule.Enabled = 1
								INNER JOIN COA_CNF_AccountConfig	WITH(NOLOCK)				ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId 
																									and COA_CNF_AccountConfig.Enabled = 1
																									and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
								INNER JOIN COA_CNF_Account		WITH(NOLOCK)					on coa_cnf_account.COAAccountId = COA_CNF_AccountConfig.coaaccountid and  COA_CNF_Account.enabled = 1
								INNER JOIN CNF_MatrixCell WITH(NOLOCK)							on cnf_matrixcell.matrixcellid = MatrixcellID.matrixcellid
							 
									LEFT JOIN (select rr_data_revenue.ticketid, AccountingType, ABS(sum(revenueamount)) as TotalUsed
												from rr_data_revenue WITH(NOLOCK)
													inner join DATA_Ticket WITH(NOLOCK)				on DATA_Ticket.TicketId = RR_DATA_Revenue.ticketid
												where CAST(activeto as date) = @batchdate
												and rr_data_revenue.RRCalcTypeTrigger in (@TicketUsageTrigger, @OnTimePeriodTrigger, @OnEventTriger)
												and isnull(oobflag, 0) = 0
												group by rr_data_revenue.ticketid, AccountingType
												)rdata									ON rdata.ticketid = data_ticket.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType	
									LEFT JOIN (select data_ticket.ticketid, SUM(revenueamount) NetPrice
																	   from RR_DATA_Revenue WITH(NOLOCK)
																			inner join DATA_Ticket WITH(NOLOCK)				on DATA_Ticket.TicketId = data_ticket.ticketid
																	  where CAST(activeto as date) = @batchdate
																	    and RRCalcTypeTrigger = 1
																		and AccountingType = 2
																		and RR_DATA_Revenue.TicketId = data_ticket.ticketid
																		and COAAccountId not in (1, 2, 3, 4)
																		and SaleItemTaxId is null
																		and SaleItemRuleID is null
																		and paymentID is null
																		and isnull(oobflag, 0) = 0
																		and ISNULL(JournalEntryByAccount, 0) = 0
												group by data_ticket.ticketid
												)p									ON p.ticketid = data_ticket.ticketid	

							where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketExpiredTrigger
							  and rr_cnf_revenuerecognitionRule.Enabled = 1
							  and COA_CNF_AccountConfig.Enabled = 1
							  and COA_CNF_AccountConfig.RemainingValues = 1
							and ((data_ticket.VoidType &amp;#60;= 99) or (data_ticket.VoidType = 203) or
													((data_ticket.VoidType in (109, 102, 125)) and
													(select top 1  DATA_Transaction.FTransactionDate
														from data_transaction2ticket WITH(NOLOCK)
															INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																															and DATA_Transaction.TransactionType in (18, 20, 22)
														where data_transaction2ticket.TicketId = data_ticket.ticketid
													) &amp;#62; @batchdate

												))
							)p
							where RevenueAmount &amp;#60;&amp;#62; 0 
		end

	end
END
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>206A7FF3843142F28C6382FE2EEB614E</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnTicketUsageTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>43</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnTicketUsageTrigger]
	@BatchDate Date,
	@RRTransDateType Integer,
	@TransType Integer
AS 
BEGIN

	Declare @TicketUsageTrigger Integer = 2	
	Declare @OnTimePeriodTrigger Integer = 4
	Declare @OnEventTriger Integer = 17
	Declare @TicketExpiredTrigger Integer = 3
	Declare @MatrixCount integer = 0

	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger  

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
		)p

	select @MatrixCount = COUNT(*)
	  from @Matrixcells

	BEGIN
		if @MatrixCount &amp;#62; 0
		BEGIN	

				--Normal No Remaining Value
					INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[TransactionID]
						   ,[SaleId]
						   ,[UsageID]
						   ,[Ticketid]
						   ,[saleitemid]
						   ,[MatrixCellid]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]			
						   ,[RRDays]
						   ,[AttributeIDs]
						   )
						   select *
						   from (
							 select distinct  coa_cnf_account.COAAccountId, 
											 RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,		   
											 RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
											 RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
											 COA_CNF_AccountConfig.COAAccountConfigId,
											 coa_cnf_account.COAAccountTypeId,
											 p.PaidTransactionId,
											 p.saleid,
											 p.Usageid,
											 p.Ticketid,
											 p.saleitemid,
											 p.Matrixcellid as Matrixcell,
											 p.MatrixSheetId as MatrixSheetID,
											 CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.SaleSite 
												  else p.AdmSiteid
											 end as SiteID,
											 p.OperatingAreaId as OperatingAreaID,
											 p.Workstationid as Workstationid,
											 p.UserId as userID,
											 @BatchDate as BatchDate,
											 1 as Quantity,
											 ISNULL((p.NetPrice), 0) as grossamount,
											 ISNULL(p.NetPrice, 0) as NetAmount,
											 COA_CNF_AccountConfig.Price as ConfigPrice,
											 COA_CNF_AccountConfig.Percentage as ConfigPercentage,
											 COA_CNF_AccountConfig.RemainingValues,							
													Case when COA_CNF_AccountConfig.Price &amp;#62; 0 and ((p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62; 0) then (COA_CNF_AccountConfig.Price) 
														else 									
														case when p.NetPrice &amp;#62; 0 then
															case when (RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 3)												
																 then
																	case  when (((p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62; 0) and (p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62;= p.OptionValue) 			
																				then (((p.OptionValue * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)


																			else ( ((p.NetPrice - ISNULL(TotalUsed, 0)) *  COA_CNF_AccountConfig.Percentage)/100)
																		end


																 when (((p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62; 0) and (p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62;= (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)) 
																		then (((p.NetPrice * RR_CNF_RevenueRecognitionRule.Percentage)/100 * COA_CNF_AccountConfig.Percentage)/100)
																	else p.NetPrice - ISNULL(TotalUsed, 0)
																end
															else 0
															end
													end as RevenueAmount,
											 COA_CNF_AccountConfig.AccountingType,
											 RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
											 RR_CNF_RevenueRecognitionRule.Percentage,
											 RR_CNF_RevenueRecognitionRule.Days,
											 AttributeIDs
									from (	select  data_ticketusage.ticketid,
													max(data_ticketusage.usageid) as usageid,
													1 as Quantity, 
													(select SUM(revenueamount)
													   from RR_DATA_Revenue
													  where RRCalcTypeTrigger = 1
														and AccountingType = 2
														and RR_DATA_Revenue.TicketId = data_ticketusage.ticketid
														and COAAccountId not in (1, 2, 3, 4)
														and SaleItemTaxId is null
														and SaleItemRuleID is null
														and ISNULL(JournalEntryByAccount, 0) = 0
													) NetPrice,

													data_ticketusageoption.OptionValue,
													DATA_Ticket.Price as GrossAmount,
													DATA_Ticket.voidtype,
													CNF_MatrixCell.matrixcellid, 
													CNF_MatrixCell.code,
													CNF_MatrixCell.matrixsheetid, 
													DATA_Ticket.Siteid SaleSite,	  
													cnf_workstation.OperatingAreaId,
													cnf_workstation.workstationid,
													(select top 1 DATA_Sale.userid
														from data_saleitem
														INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
														where data_saleitem.saleitemid = data_ticket.saleitemid
													) as userid,
													(select top 1 data_saleitem.saleid
														from data_saleitem
														where data_saleitem.saleitemid = data_ticket.saleitemid
													) as Saleid,
													CNF_AttributeSet.AttributeIDs,
													CNF_AttributeSet.AttributeSetId,
													DATA_Ticket.saleitemid,
													DATA_Sale.PaidTransactionId,
													min(CNF_Location.Siteid) as AdmSiteid
							
													from data_ticketusage WITH(NOLOCK)
														LEFT  JOIN data_ticketusageoption WITH(NOLOCK)								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 7
														INNER JOIN DATA_Ticket	WITH(NOLOCK)										on DATA_Ticket.ticketid = data_ticketusage.ticketid
														LEFT  JOIN data_saleitem WITH(NOLOCK)										ON data_saleitem.saleitemid = data_ticket.saleitemid
														LEFT  JOIN DATA_Sale WITH(NOLOCK)											ON DATA_Sale.SaleId = DATA_SaleItem.SaleId
														INNER JOIN CNF_MatrixCell	WITH(NOLOCK)									on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
														INNER JOIN CNF_AttributeSet	WITH(NOLOCK)									on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
														INNER JOIN CNF_Workstation	WITH(NOLOCK)									on cnf_workstation.workstationid = data_ticket.WorkstationId
														INNER JOIN ADM_Gate	WITH(NOLOCK)											on ADM_Gate.gateid = data_ticketusage.gateid
														INNER JOIN CNF_Location	WITH(NOLOCK)										on CNF_Location.locationid = ADM_Gate.locationid

									where data_ticketusage.validateResult &amp;#60;=99
									and data_ticketusage.UsageType = 1							
									and cast(fusagedate as date) = @batchdate
									and cast(data_ticketusage.usagedate as date) &amp;#62;= cast(data_ticket.PrintDateTime as date)
									and data_ticket.FEncodeDate &amp;#62;= (select cast(rrstartdate as date) from CNF_System)
									group by data_ticketusage.ticketid,
											data_ticketusageoption.OptionValue,
											DATA_Ticket.Price,
											CNF_MatrixCell.matrixcellid, 
											CNF_MatrixCell.code,
											CNF_MatrixCell.matrixsheetid, 
											DATA_Ticket.Siteid,	  
											cnf_workstation.OperatingAreaId,
											cnf_workstation.workstationid,
											(DATA_Ticket.Price),
											CNF_AttributeSet.AttributeIDs,
											CNF_AttributeSet.AttributeSetId,
											data_ticket.producttaxtype,
											data_ticket.saleitemid,
											data_ticket.ticketid,
											data_saleitem.unitprice,
											DATA_Ticket.voidtype,
											PaidTransactionId
												)p 
						inner join @Matrixcells	Matrixcellid							ON Matrixcellid.matrixcellid = p.matrixcellid
						INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
						INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
						INNER JOIN COA_CNF_Account WITH(NOLOCK)							ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
						LEFT JOIN (select ticketid, AccountingType, sum(revenueamount) as TotalUsed
									from rr_data_revenue WITH(NOLOCK)
									where rr_data_revenue.RRCalcTypeTrigger in (@TicketUsageTrigger, @OnTimePeriodTrigger, @OnEventTriger)
									group by ticketid, AccountingType
									)rdata									ON rdata.ticketid = p.ticketid	and rdata.AccountingType = coa_cnf_accountconfig.AccountingType
						where  p.NetPrice &amp;#60;&amp;#62; 0
							and RR_CNF_RevenueRecognitionRule.Enabled = 1
							and coa_cnf_account.Enabled = 1
							and COA_CNF_AccountConfig.Enabled = 1
							and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
							and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
							and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
							or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null))) 
							and p.usageid not in (select Usageid from rr_data_revenue rr where rr.FCalcDate = @BatchDate and Usageid is not null)
							AND P.TICKETID IN (
									select rr_data_revenue.ticketid
										from rr_data_revenue WITH(NOLOCK)
											INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
										where rr_data_revenue.RevenueRecognitionRuleId = 1
											and P.TICKETID = rr_data_revenue.ticketid
										group by rr_data_revenue.ticketid, accountingtype,  NetAmount
									)	
							AND P.TICKETID not IN (
									select rr_data_revenue.ticketid
										from rr_data_revenue WITH(NOLOCK)
											INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
										where rr_data_revenue.RRCalcTypeTrigger in  (@OnEventTriger, @TicketExpiredTrigger, @OnTimePeriodTrigger)
											and rr_data_revenue.TicketId = P.TICKETID
										group by rr_data_revenue.ticketid, accountingtype,  NetAmount
									)	
								AND (((@TransType = 1) and ((p.Voidtype &amp;#60;&amp;#62; 107) 
																	and (p.ticketid NOT in (select ticketid
																						from data_transaction2ticket WITH(NOLOCK)
																							INNER JOIN data_transaction WITH(NOLOCK)			ON data_transaction.transactionid = data_transaction2ticket.transactionid
																						where data_transaction.transactiontype = 7
																						and data_transaction2ticket.ticketid = p.ticketid 
																						)
																		)
														)
								)   OR
									((@TransType = 7)
																	and (p.ticketid in (select ticketid
																						from data_transaction2ticket WITH(NOLOCK)
																							INNER JOIN data_transaction WITH(NOLOCK)			ON data_transaction.transactionid = data_transaction2ticket.transactionid
																						where data_transaction.transactiontype = 7
																						and data_transaction2ticket.ticketid = p.ticketid 
																						)
																		)
														))
								)k
								where RevenueAmount &amp;#60;&amp;#62; 0




				--Normal TicketExpired with Remaining Value
						INSERT INTO [dbo].[RR_DATA_Revenue]
						   ([COAAccountId]
						   ,[RevenueRecognitionRuleId]
						   ,[RRCalcTypeWhere]
						   ,[RRCalcTypeMethod]
						   ,[COAAccountConfigId]
						   ,[COAAccountType]
						   ,[TransactionID]
						   ,[SaleId]
						   ,[UsageID]
						   ,[Ticketid]
						   ,[Saleitemid]
						   ,[MatrixCellid]
						   ,[MatrixSheetid]
						   ,[SiteId]
						   ,[OperatingAreaId]
						   ,[WorkstationId]
						   ,[UserId]
						   ,[FCalcDate]
						   ,[Quantity]
						   ,[GrossAmount]
						   ,[NetAmount]
						   ,[Price]
						   ,[Percentage]
						   ,[RemaningValues]
						   ,[RevenueAmount]
						   ,[AccountingType]
						   ,[RRCalcTypeTrigger]
						   ,[RRPercentage]
						   ,[RRDays]
						   ,[AttributeIDs])
						   select *
						   from (
								select   distinct	coa_cnf_account.COAAccountId, 
											RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
											RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
											RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
											COA_CNF_AccountConfig.COAAccountConfigId,
											coa_cnf_account.COAAccountTypeId,
											p.PaidTransactionId,
											p.saleid as Saleid,
											p.Usageid,
											p.Ticketid,
											p.Saleitemid,
											p.Matrixcellid as Matrixcell,
											p.MatrixSheetId as MatrixSheetID,
											CASE When RR_CNF_RevenueRecognitionRule.rrCalcTypeWhere = 1 then p.SaleSite 
											else p.AdmSiteid
											end as SiteID,
											p.OperatingAreaId as OperatingAreaID,
											p.Workstationid as Workstationid,
											p.UserId as userID,
											@BatchDate as BatchDate,
											1 as Quantity,
											ISNULL((p.GrossAmount - p.discountamount), 0) as GrossAmount,
											ISNULL(p.NetPrice, 0) as NetAmount,
											COA_CNF_AccountConfig.Price as ConfigPrice,
											COA_CNF_AccountConfig.Percentage as ConfigPercentage,
											COA_CNF_AccountConfig.RemainingValues,
											case when p.NetPrice &amp;#62; 0 then
											case when RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 3 then
													case when (((p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62; 0) and ((
																	((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
																		((p.NetPrice *  (select sum(percentage)
																																			from coa_cnf_accountconfig AC WITH(NOLOCK)
																																			where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																			and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																			)
																		)/100)) &amp;#60;= (p.OptionValue - ISNULL(TotalUsed, 0)))) and p.NetPrice &amp;#62;= P.OptionValue

														then p.optionValue
														when ((p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62; 0) and (p.optionValue * (select sum(percentage)
																																			from coa_cnf_accountconfig AC WITH(NOLOCK)
																																			where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																			and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																			))/100 = (select sum(RR.revenueamount)
																															  from rr_data_revenue RR
																															  where RR.ticketid = p.ticketid
																																and RR.Usageid = p.Usageid
																																and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																															) 
												
												
																			  and (p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62;= (( (p.NetPrice - ISNULL(TotalUsed, 0)) *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																			from coa_cnf_accountconfig AC WITH(NOLOCK)
																																			where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																			and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																			)
																		/100
															  then   p.optionValue - (p.optionValue *  (select sum(percentage)
																																			from coa_cnf_accountconfig AC WITH(NOLOCK)
																																			where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																			and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																			)
																		/100)


														else  
												
												
														ISNULL((((select sum(RR.revenueamount)
																															  from rr_data_revenue RR WITH(NOLOCK)
																															  where RR.ticketid = p.ticketid
																																and RR.Usageid = p.Usageid
																																and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																															) /  case when (select sum(percentage)
																																				from rr_data_revenue RR WITH(NOLOCK)
																																				where RR.ticketid = p.ticketid
																																				and RR.Usageid = p.Usageid
																																				and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																																			) = 0 then 1 
																																		else (select sum(percentage)
																																		from rr_data_revenue RR WITH(NOLOCK)
																																		where RR.ticketid = p.ticketid
																																		and RR.Usageid = p.Usageid
																																		and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																																	) end

																 )*100 ) - (select sum(RR.revenueamount)
																															  from rr_data_revenue RR WITH(NOLOCK)
																															  where RR.ticketid = p.ticketid
																																and RR.Usageid = p.Usageid
																																and rr.accountingtype = coa_cnf_accountconfig.accountingtype
																															), case when (p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62;= p.optionvalue then p.optionvalue 
																																	else  (p.NetPrice - ISNULL(TotalUsed, 0))
																																	end)
														end		
												
												
												
												
												
												
																	
											 when (((p.NetPrice - ISNULL(TotalUsed, 0)) &amp;#62; 0) and ((
												((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  
													((
													((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																														from coa_cnf_accountconfig AC WITH(NOLOCK)
																														where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																														and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																														)
													)/100)) &amp;#60;= (p.NetPrice - ISNULL(TotalUsed, 0))))
														then 
														(((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) -  (((p.NetPrice *  RR_CNF_RevenueRecognitionRule.Percentage)/100) * (select sum(percentage)
																																from coa_cnf_accountconfig AC WITH(NOLOCK)
																																where AC.revenuerecognitionruleid = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																and ac.accountingtype = coa_cnf_accountconfig.accountingtype
																																))/100)
													else p.NetPrice - ISNULL(TotalUsed, 0)
													end
													else 0
												end  RevenueAmount,

											COA_CNF_AccountConfig.AccountingType,
											RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
											RR_CNF_RevenueRecognitionRule.Percentage,
											RR_CNF_RevenueRecognitionRule.Days,
											AttributeIDs
										from (			
												select  data_ticketusage.ticketid,
												max(data_ticketusage.usageid) as usageid,
												1 as Quantity, 
																						(select SUM(revenueamount)
													   from RR_DATA_Revenue
													  where RRCalcTypeTrigger = 1
														and AccountingType = 2
														and RR_DATA_Revenue.TicketId = data_ticketusage.ticketid
														and COAAccountId not in (1, 2, 3, 4)
														and SaleItemTaxId is null
														and SaleItemRuleID is null
														and ISNULL(JournalEntryByAccount, 0) = 0
													) NetPrice,
												ISNULL((select sum(discountamount)/sum(applytoqty)  
												   from data_saleitemrule 
												  where data_saleitemrule.saleitemid = data_ticket.saleitemid
													and data_saleitemrule.discountamount &amp;#60; 0 ),0) as discountamount,


												data_ticketusageoption.OptionValue,
												DATA_Ticket.Price as GrossAmount,
												CNF_MatrixCell.matrixcellid, 
												CNF_MatrixCell.code,
												CNF_MatrixCell.matrixsheetid, 
												DATA_Ticket.Siteid SaleSite,	  
												cnf_workstation.OperatingAreaId,
												cnf_workstation.workstationid,
												(select top 1 DATA_Sale.userid
													from data_saleitem
													INNER JOIN DATA_Sale		on data_sale.saleid = data_saleitem.saleid
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as userid,
												(select top 1 data_saleitem.saleid
													from data_saleitem
													where data_saleitem.saleitemid = data_ticket.saleitemid
												) as Saleid,
												case when (DATA_Ticket.Price) &amp;#60;&amp;#62; 0 then (data_ticket.Price)
													 else r1.netamount
												 end as TicketPrice,
												CNF_AttributeSet.AttributeIDs,
												CNF_AttributeSet.AttributeSetId,
												DATA_Ticket.saleitemid,
												data_ticket.Voidtype,
												DATA_Sale.PaidTransactionId,
												min(CNF_Location.Siteid) as AdmSiteid
							
									from data_ticketusage WITH(NOLOCK)
											LEFT  JOIN data_ticketusageoption WITH(NOLOCK)								on data_ticketusageoption.usageid = data_ticketusage.usageid and data_ticketusageoption.optiontype = 7
											INNER JOIN DATA_Ticket	WITH(NOLOCK)										on DATA_Ticket.ticketid = data_ticketusage.ticketid
											LEFT  JOIN data_saleitem WITH(NOLOCK)										ON data_saleitem.saleitemid = data_ticket.saleitemid
											LEFT  JOIN DATA_Sale WITH(NOLOCK)											ON DATA_Sale.SaleId = DATA_SaleItem.saleid
											INNER JOIN CNF_MatrixCell	WITH(NOLOCK)									on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
											INNER JOIN CNF_AttributeSet	WITH(NOLOCK)									on cnf_attributeset.AttributeSetId = CNF_MatrixCell.AttributeSetId
											INNER JOIN CNF_Workstation	WITH(NOLOCK)									on cnf_workstation.workstationid = data_ticket.WorkstationId
											INNER JOIN ADM_Gate	WITH(NOLOCK)											on ADM_Gate.gateid = data_ticketusage.gateid
											INNER JOIN CNF_Location	WITH(NOLOCK)										on CNF_Location.locationid = ADM_Gate.locationid
											LEFT  JOIN (select ticketid,
														   max(Netamount) netamount,
														   sum(revenueamount) revenueamount,
															max(saleitemid) as saleitemid	   
													from (
													select ticketid, 
														   netamount  as netamount,
														   ABS((select sum(discountamount) from data_saleitemrule where data_saleitemrule.saleitemid = rr_data_revenue.saleitemid)) Discount,
															rr_data_revenue.saleitemid, 
														   revenueamount 
													from rr_data_revenue WITH(NOLOCK)
													where rrcalctypetrigger = 1
														and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
													)p1
													group by ticketid)r1    on r1.ticketid = data_ticket.ticketid
											LEFT JOIN (select data_saleitem.saleitemid, case when data_saleitem.unittaxes &amp;#60;&amp;#62; 0 then data_saleitem.unittaxes
																					  else ORIGSI.UnitTaxes
																				  end Taxes
														 from data_saleitem WITH(NOLOCK)
															LEFT JOin data_saleitem ORIGSI WITH(NOLOCK)			ON ORIGSI.saleitemid = data_saleitem.OrigSaleItemId
													  ) Taxes    on			Taxes.SaleItemId = DATA_Ticket.saleitemid
										where data_ticketusage.validateResult &amp;#60;=99
										and data_ticketusage.UsageType = 1
										and cast(fusagedate as date) = @batchdate
										and cast(data_ticketusage.usagedate as date) &amp;#62;= cast(data_ticket.PrintDateTime as date)
										and data_ticket.FEncodeDate &amp;#62;= (select cast(rrstartdate as date) from CNF_System)
										group by data_ticketusage.ticketid,
												data_ticketusageoption.OptionValue,
												DATA_Ticket.Price,
												CNF_MatrixCell.matrixcellid, 
												CNF_MatrixCell.code,
												CNF_MatrixCell.matrixsheetid, 
												DATA_Ticket.Siteid,	  
												cnf_workstation.OperatingAreaId,
												cnf_workstation.workstationid,
												(DATA_Ticket.Price),
												CNF_AttributeSet.AttributeIDs,
												CNF_AttributeSet.AttributeSetId,
												data_ticket.producttaxtype,
												Taxes.taxes,
												data_ticket.saleitemid,
												r1.RevenueAmount,
												r1.netamount,
												data_ticket.ticketid,
												data_ticket.Voidtype,
												DATA_Sale.PaidTransactionId
										)p 
										INNER join @Matrixcells	Matrixcellid							ON Matrixcellid.matrixcellid = p.matrixcellid
										INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)			ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @TicketUsageTrigger
										INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)					ON COA_CNF_AccountConfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
										INNER JOIN COA_CNF_Account	WITH(NOLOCK)						ON COA_CNF_Account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
										LEFT JOIN (select ticketid, accountingtype, sum(revenueamount) as TotalUsed
													from rr_data_revenue WITH(NOLOCK)
													where rr_data_revenue.RRCalcTypeTrigger in (@TicketUsageTrigger, @OnTimePeriodTrigger, @OnEventTriger, @TicketExpiredTrigger)
													group by ticketid, accountingtype
													)rdata									ON rdata.ticketid = p.ticketid	and rdata.accountingtype = COA_CNF_AccountConfig.accountingtype
										where p.TicketPrice &amp;#60;&amp;#62; 0
											and RR_CNF_RevenueRecognitionRule.Enabled = 1
											and coa_cnf_account.Enabled = 1
											and COA_CNF_AccountConfig.Enabled = 1
											and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
											and COA_CNF_AccountConfig.RemainingValues = 1
											and (((RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 1) and ((coa_cnf_accountConfig.Siteid = p.AdmSiteid) or (coa_cnf_accountConfig.Siteid is null)))
											or (RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere = 2) and ((coa_cnf_accountConfig.Siteid = p.SaleSite) or (coa_cnf_accountConfig.Siteid is null)))
										AND P.TICKETID IN (
											select rr_data_revenue.ticketid
												from rr_data_revenue WITH(NOLOCK)
													INNER JOIN data_ticket with(nolock)    on data_ticket.ticketid = rr_data_revenue.ticketid
												where rr_data_revenue.RevenueRecognitionRuleId = 1
												and rr_data_revenue.TicketId = P.TICKETID
												group by rr_data_revenue.ticketid, accountingtype,  NetAmount
											)	
										AND (((@TransType = 1) and ((p.Voidtype &amp;#60;&amp;#62; 107) 
																		 and (p.ticketid NOT in (select ticketid
																								from data_transaction2ticket WITH(NOLOCK)
																									INNER JOIN data_transaction WITH(NOLOCK)			ON data_transaction.transactionid = data_transaction2ticket.transactionid
																								where data_transaction.transactiontype = 7
																								and data_transaction2ticket.ticketid = p.ticketid 
																								)
																			  )
																)
										)   OR
										 ((@TransType = 7)
																		 and (p.ticketid in (select ticketid
																								from data_transaction2ticket WITH(NOLOCK)
																									INNER JOIN data_transaction WITH(NOLOCK)			ON data_transaction.transactionid = data_transaction2ticket.transactionid
																								where data_transaction.transactiontype = 7
																								and data_transaction2ticket.ticketid = p.ticketid 
																								)
																			  )
																))

								)k
								where RevenueAmount &amp;#60;&amp;#62; 0
		end
	end

END



</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>CCF526080FC6462BA54FCFE75B33B785</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnTimePeriodTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>42</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnTimePeriodTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendID Integer
	Declare @OnTimePeriodTrigger Integer = 4
	Declare @TicketExpiredTrigger Integer = 3
	Declare @TicketUsageTrigger Integer = 2
	Declare @RRMethod Integer = 0
	Declare @MatrixCount integer = 0

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1	
		
	create table #RulesToRun
	(
		RRID int
	)

	Declare @TodayDayofWeek Int
	Declare @TodaySpecificDay Int
	Declare @TodayMonthlyWeek Int
	Declare @TodayMonth Int
	Declare @TodayDay Int

	select @TodayDayofWeek   = datePart(weekday, cast(@BatchDate as date)),
		   @TodayMonth       = datePart(mm, cast(@BatchDate as date)),
		   @TodaySpecificDay = datePart(dd, cast(@BatchDate as date)),
		   @TodayMonthlyWeek = (datepart(week, @Batchdate)/ datepart(month, @batchdate)) + 1

	insert into #RulesToRun
	select	distinct RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
		from RR_CNF_RevenueRecognitionRuleSchedule WITH(NOLOCK)
			INNER JOIN RR_CNF_RevenueRecognitionRule					ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRuleSchedule.RevenueRecognitionRuleId

	where RR_CNF_RevenueRecognitionRule.Enabled = 1
	  and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
	  and ((PeriodOption = 1)
			  or ((PeriodOption = 2) and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
											or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
											or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
											or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
											or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
											or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1))
										)))
			 or ((PeriodOption = 3) and ((SpecificDay = @TodaySpecificDay) 
										  or ((WeekOption = @TodayMonthlyWeek and     (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1)))
																				)))) 
			 or ((LastDayOptionDay = 1) and (EOMONTH(@batchdate) = @BatchDate))																				
			 or ((PeriodOption = 4) and (((SpecificDay = @TodaySpecificDay) and (MonthOption = @TodayMonth))  
										   or ((WeekOption = @TodayMonthlyWeek and (((@TodayDayofWeek = 1) and (ActiveSunday = 1))
																					or ((@TodayDayofWeek = 2) and (ActiveMonday = 1))
																					or ((@TodayDayofWeek = 3) and (ActiveTuesday = 1))
																					or ((@TodayDayofWeek = 4) and (ActiveWednesday = 1))
																					or ((@TodayDayofWeek = 5) and (ActiveThursday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 6) and (ActiveFriday = 1))
																					or ((@TodayDayofWeek = 7) and (ActiveSaturday = 1)))
																				)))
																				and (MonthOption = @TodayMonth))


	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnTimePeriodTrigger
				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnTimePeriodTrigger

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnTimePeriodTrigger
		)p

	select @MatrixCount = COUNT(*)
	  from @Matrixcells



	if exists(select * from #RulesToRun)
	begin

		if @MatrixCount &amp;#62; 0
		BEGIN
			select @RRMethod = COUNT(*) from RR_CNF_RevenueRecognitionRule WITH(NOLOCK) where RRCalcTypeTrigger = 4 and rrcalctypeMethod not in (4, 5)

			if @RRMethod &amp;#62; 0 
			begin
							INSERT INTO [dbo].[RR_DATA_Revenue]
										   ([COAAccountId]
										   ,[RevenueRecognitionRuleId]
										   ,[RRCalcTypeWhere]
										   ,[RRCalcTypeMethod]
										   ,[COAAccountConfigId]
										   ,[COAAccountType]
										   ,[TransactionID]
										   ,[SaleId]
										   ,[Ticketid]
										   ,[SaleItemID]
										   ,[MatrixCellid]
										   ,[MatrixSheetid]
										   ,[SiteId]
										   ,[OperatingAreaId]
										   ,[WorkstationId]
										   ,[Usergroupid]
										   ,[UserId]
										   ,[FCalcDate]
										   ,[Quantity]
										   ,[GrossAmount]
										   ,[NetAmount]
										   ,[Price]
										   ,[Percentage]
										   ,[RemaningValues]
										   ,[RevenueAmount]
										   ,[AccountingType]
										   ,[RRCalcTypeTrigger]
										   ,[RRPercentage]			
										   ,[RRDays]
										   ,[AttributeIDs]
										   ,[oobflag]
										   )
										   select *
										   from (
											select distinct p.COAAccountId, 
												   p.RevenueRecognitionRuleId,		   
												   p.RRCalcTypeWhere,
												   p.RRCalcTypeMethod,	   
												   p.COAAccountConfigId,
												   p.COAAccountTypeId,
												   DATA_Sale.PaidTransactionId,
												   DATA_SaleItem.saleid as Saleid,
												   ISNULL(rdata.Ticketid, data_ticket.Ticketid) TicketID,
												   DATA_SaleItem.saleitemid, 
												   DATA_SaleItem.Matrixcellid,
												   cnf_matrixcell.MatrixSheetId,
												   DATA_Ticket.Siteid,
												   CNF_OperatingArea.OperatingAreaId,
												   DATA_Ticket.Workstationid,
												   RR_DATA_REVENUE.UserGroupid,
												   RR_DATA_REVENUE.UserId,
												   @BatchDate as BatchDate,
												   1 as Quantity,
												   ISNULL(case when DATA_Ticket.Price &amp;#60;&amp;#62; 0 then data_ticket.price
														else OLDTic.price
													end, 0) as GrossAmount,
												   isnull(((case when DATA_Ticket.Price &amp;#60;&amp;#62; 0 then data_ticket.price
														else OLDTic.price
													end) - (case when DATA_Ticket.taxes &amp;#60;&amp;#62; 0 then data_ticket.taxes
														else OLDTic.taxes
													end) ), 0) as NetAmount,
												   p.Price as ConfigPrice,
												   p.Percentage as ConfigPercentage,
												   p.RemainingValues,																		
												 abs(round(Case when p.Price &amp;#62; 0 then
																							 case when ((DATA_SaleItem.unitprice - data_saleitem.unittaxes) - ISNULL(rdata.totalused, 0)) &amp;#62;= p.Price then p.Price
																								  when ((DATA_SaleItem.unitprice - data_saleitem.unittaxes) - ISNULL(rdata.totalused, 0)) &amp;#60; p.Price then ((DATA_SaleItem.unitprice - data_saleitem.unittaxes) - ISNULL(rdata.totalused, 0))
																								  else 0
																								  end 
													   else case when (((ISNULL((case when DATA_SaleItem.unitprice &amp;#60;&amp;#62; 0 then DATA_SaleItem.unitprice
																						else OLDTic.price
																					end)  - (case when DATA_SaleItem.unitprice &amp;#60;&amp;#62; 0 then DATA_SaleItem.unitprice
																						else OLDTic.taxes
																					end), 0) *  p.rrPercentage)/100) * (select sum(COA_CNF_AccountConfig.percentage)
																															from RR_CNF_RevenueRecognitionRule
																																INNER JOIN COA_CNF_AccountConfig   on coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																										and accountingtype = 1
																															where RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId))/100
									   
																												&amp;#60; 
																												(select ISNULL((sum(ISNULL(TotalT, 0)) - sum(isnull(TotalU, 0))), 0) totalleft
																														from 
																														(
																														select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																															and rr_data_revenue.coaaccountid in (select coaaccountid from coa_cnf_accountconfig where RevenueRecognitionRuleId = p.RevenueRecognitionRuleId and accountingtype = p.AccountingType)
																															and accountingtype = p.AccountingType
																															group by accountingtype

																														Union ALL

																														select 0 as TotalT, sum(ISNULL(revenueamount, 0)) as TotalU
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																															and rr_data_revenue.coaaccountid  in (select coaaccountid from coa_cnf_accountconfig where RevenueRecognitionRuleId = p.RevenueRecognitionRuleId and accountingtype = p.AccountingType)
																															and accountingtype = p.AccountingType
																															group by accountingtype
																														)n)
																															
																then (ISNULL(((((case when DATA_SaleItem.unitprice &amp;#60;&amp;#62; 0 then DATA_SaleItem.unitprice
																						else OLDTic.price
																					end)  - (case when DATA_Ticket.taxes &amp;#60;&amp;#62; 0 then data_ticket.taxes
																									when OLDTic.taxes is null and data_ticket.taxes is not null then data_ticket.taxes
																						else OLDTic.taxes
																					end)) *  p.rrPercentage)/100), 0) * (select sum(COA_CNF_AccountConfig.percentage)
																															from RR_CNF_RevenueRecognitionRule
																																INNER JOIN COA_CNF_AccountConfig   on coa_cnf_accountconfig.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId
																																										and accountingtype = 1
																															where RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = p.RevenueRecognitionRuleId))/100
													  
																 when (DATA_SaleItem.unitprice - data_saleitem.unittaxes)  - (select ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																														from 
																														(
																														select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																															and RR_DATA_Revenue.RRCalcTypeTrigger IN (@OnTimePeriodTrigger, @TicketExpiredTrigger, @TicketUsageTrigger)
																															and accountingtype = p.AccountingType
																															group by accountingtype
																										
																														)n) &amp;#62; 0 and (DATA_SaleItem.unitprice - data_saleitem.unittaxes) *(p.RRPercentage /100) &amp;#60;= (DATA_SaleItem.unitprice - data_saleitem.unittaxes)  - (select ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																														from 
																														(
																														select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																															and RR_DATA_Revenue.RRCalcTypeTrigger in (@OnTimePeriodTrigger, @TicketExpiredTrigger, @TicketUsageTrigger)
																															and accountingtype = p.AccountingType
																															group by accountingtype
																										
																														)n) 
																										
																		then (DATA_SaleItem.unitprice - data_saleitem.unittaxes) *(p.RRPercentage /100)

																		when DATA_SaleItem.unitprice = 0 and (select sum(ISNULL(revenueamount, 0))as TotalT
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = data_ticket.Ticketid
																															and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																															and accountingtype = 2
																															and COAAccountId not in (1,2 , 3, 4)
																															and SaleItemTaxId is null
																															and SaleItemRuleID is null
																															)  &amp;#62; 0 
																									and 
																														ISNULL((select SUM(TotalT) - SUM(TotalSpend)
																														from(
																														(select sum(ISNULL(revenueamount, 0))as TotalT, 0 TotalSpend
																																	from rr_data_revenue
																																	where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																																		and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																																		and accountingtype = 2
																																		and COAAccountId not in (1,2 , 3, 4)
																																		and SaleItemTaxId is null
																																		and SaleItemRuleID is null)
																															UNION ALL																								 
																														(select 0, ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																																from 
																																(
																																select sum(ISNULL(revenueamount, 0))as TotalT
																																from rr_data_revenue
																																where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																																	and RR_DATA_Revenue.RRCalcTypeTrigger IN (@OnTimePeriodTrigger, @TicketExpiredTrigger, @TicketUsageTrigger)
																																	and accountingtype = 1
																																	group by accountingtype
																										
																																)n)
																														)p), 0)
																														&amp;#62;= ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
																																				from rr_data_revenue
																																				where rr_data_revenue.ticketid = data_ticket.Ticketid
																																					and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																																					and accountingtype = 2
																																					and COAAccountId not in (1,2 , 3, 4)
																																					and SaleItemTaxId is null
																																					and SaleItemRuleID is null
																																					), 0)
															
																																*(p.percentage /100)*(p.RRPercentage /100)
																											
																		then ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
																																				from rr_data_revenue
																																				where rr_data_revenue.ticketid = data_ticket.Ticketid
																																					and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																																					and accountingtype = 2
																																					and COAAccountId not in (1, 2, 3, 4)
																																					and SaleItemTaxId is null
																																					and SaleItemRuleID is null
																																					), 0)
															
																			 *(p.percentage /100)*(p.RRPercentage /100)
	
																	when DATA_SaleItem.unitprice = 0 and ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = data_ticket.Ticketid
																															and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																															and accountingtype = 2
																															and COAAccountId not in (1,2 , 3, 4)
																															and SaleItemTaxId is null
																															and SaleItemRuleID is null
																															), 0) - (select ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																														from 
																														(
																														select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																														from rr_data_revenue
																														where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																															and RR_DATA_Revenue.RRCalcTypeTrigger IN (@OnTimePeriodTrigger, @TicketExpiredTrigger, @TicketUsageTrigger)
																															and accountingtype = 1
																															group by accountingtype
																										
																														)n)  &amp;#62; 0 
																		then
																			(select ISNULL(SUM(TotalT), 0) - ISNULL(SUM(TotalSpend), 0)
																					from(
																					(select sum(ISNULL(revenueamount, 0))as TotalT, 0 TotalSpend
																																															from rr_data_revenue
																																															where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																																																and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																																																and accountingtype = 2
																																																and COAAccountId not in (1,2 , 3, 4)
																																																and SaleItemTaxId is null
																																																and SaleItemRuleID is null)
																						UNION ALL																								 
																					(select 0, ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																																																		from 
																																																		(
																																																		select sum(ISNULL(revenueamount, 0))as TotalT
																																																		from rr_data_revenue
																																																		where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																																																			and RR_DATA_Revenue.RRCalcTypeTrigger IN (@OnTimePeriodTrigger, @TicketExpiredTrigger, @TicketUsageTrigger)
																																																			and accountingtype = 1
																																																			group by accountingtype
																										
																																																		)n)
																					)p1)
																else 0
													  
																	 end
												   end, 2)) as RevenueAmount,
												 --  99 accountingtype, 
												   p.Accountingtype as accountingtype,
												   p.RRCalcTypeTrigger,
												   p.RRPercentage,
												   p.Days,
												   RR_DATA_REVENUE.AttributeIDs,
												   rr_data_revenue.oobflag

											from DATA_Ticket WITH(NOLOCK)	
												INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.SaleItemId = DATA_Ticket.saleitemid
												INNER  JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.saleid
												LEFT  JOIN data_ticket OLDTic WITH(NOLOCK)						on OLDTic.ticketid = data_saleitem.itemticketid
												LEFT  JOIN (select max(saleid) as saleid, 
																   max(ticketid) as Ticketid,
																   max(Userid) as Userid, 
																   (select max(usergroupid) from data_transaction where data_transaction.saleid = rr_data_revenue.saleid) as usergroupid,
																   max(rr_data_revenue.AttributeIDs) as AttributeIDs,
																   Max(rr_data_revenue.RevenueRecognitionRuleId) as RevenueRecognitionRuleId,
																   MAX(oobflag) oobflag

															from rr_data_revenue
															where RevenueRecognitionRuleId &amp;#60;&amp;#62; 1

															group by rr_data_revenue.saleid) as rr_data_revenue							on data_ticket.ticketid = RR_DATA_REVENUE.ticketid and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
												LEFT  JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_Matrixcell.matrixcellid = data_ticket.matrixcellid
												left  join cnf_workstation WITH(NOLOCK)							on CNF_Workstation.workstationid = data_ticket.workstationid
												LEFT  JOIN CNF_OperatingArea WITH(NOLOCK)						on CNF_OperatingArea.OperatingAreaId = CNF_Workstation.OperatingAreaId															
												INNER JOIN (  
														select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
																		RR_CNF_RevenueRecognitionRule.Days,
																		RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
																		RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
																		FromDate,
																		ToDate,
																		RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
																		RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
																		COA_CNF_AccountConfig.CoaAccountid,
																		COA_CNF_AccountConfig.AccountingType,
																		COA_CNF_AccountConfig.Price,
																		COA_CNF_AccountConfig.Percentage,
																		COA_CNF_AccountConfig.RemainingValues,
																		COA_CNF_AccountConfig.SiteID,
																		coa_cnf_account.code as AccountCode,
																		COA_CNF_AccountType.Code as AccountTypeCode,
																		COA_CNF_AccountType.COAAccountTypeId,
																		Matrixcellid.matrixcellid,
																		COA_CNF_AccountConfig.COAAccountConfigId,
																		RR_CNF_RevenueRecognitionRule.usagetime

																from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
																	inner join @Matrixcells	Matrixcellid						ON Matrixcellid.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId									
																	INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
																	INNER JOIN coa_cnf_account	 WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
																	INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

																where COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
																  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnTimePeriodTrigger
																  and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod not in (4, 5)
																  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
																																   from #RulesToRun)

													)p   ON (data_ticket.MATRIXCELLID = p.MATRIXCELLID) 

												   LEFT JOIN (select ticketid, accountingtype, sum(totalused) as totalused
																from (
																select rr_data_revenue.ticketid, AccountingType, sum(revenueamount) as TotalUsed
																from rr_data_revenue WITH(NOLOCK)
																inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID

																where rr_data_revenue.ticketid is not null
																	and coaaccountid not in (@suspendid)
																	and rrcalctypetrigger &amp;#60;&amp;#62; 1
																group by rr_data_revenue.ticketid, AccountingType

																UNION ALL

																select DATA_TICKET.ticketid, AccountingType, sum(revenueamount) as TotalUsed
																from DATA_TICKET WITH(NOLOCK) 
																	LEFT  JOIN DATA_SaleItem WITH(NOLOCK)				on data_saleitem.saleitemid = data_ticket.saleitemid
																	LEFT  JOIN rr_data_revenue RD1 WITH(NOLOCK) 		on rd1.ticketid = data_saleitem.ticketid

																where DATA_TICKET.ticketid is not null
																	and coaaccountid not in (@suspendid)
																	and rrcalctypetrigger &amp;#60;&amp;#62; 1
																group by DATA_TICKET.ticketid, AccountingType

																)p1
																group by ticketid, accountingtype
																)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                         
									where cast(data_ticket.FEncodeDate as date) &amp;#60;= @BatchDate
									   and cast(data_ticket.PrintDateTime as date) &amp;#60;= @BatchDate			  
									   and cast(data_ticket.FEncodeDate as date) &amp;#62;= (select CNF_System.RRStartDate from CNF_System)
									   and @BatchDate &amp;#62;= case when p.UsageTime = 0 then @BatchDate
															  else data_ticket.activeFrom
														  END

											and ((data_ticket.VoidType &amp;#60;= 99) or (data_ticket.VoidType = 203) or
													((data_ticket.VoidType in (109, 102, 125)) and
													(select top 1  DATA_Transaction.FTransactionDate
														from data_transaction2ticket WITH(NOLOCK)
															INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																															and DATA_Transaction.TransactionType in (18, 20, 22)
														where data_transaction2ticket.TicketId = data_ticket.ticketid
													) &amp;#62; @batchdate

												))
										and ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#62; 0
										and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
												from rr_data_revenue
												where rr_data_revenue.ticketid = DATA_Ticket.ticketid
												and RR_DATA_Revenue.RRCalcTypeTrigger = 1
												and accountingtype = 2
												and COAAccountId not in (1, 2, 3, 4)
												and SaleItemTaxId is null
												and SaleItemRuleID is null), 0)) &amp;#62; 0
									)p
									where Round(RevenueAmount, 12) &amp;#60;&amp;#62; 0 

								INSERT INTO [dbo].[RR_DATA_Revenue]
									   ([COAAccountId]
									   ,[RevenueRecognitionRuleId]
									   ,[RRCalcTypeWhere]
									   ,[RRCalcTypeMethod]
									   ,[COAAccountConfigId]
									   ,[COAAccountType]
									   ,[TransactionID]
									   ,[SaleId]
									   ,[Ticketid]
									   ,[Saleitemid]
									   ,[MatrixCellid]
									   ,[MatrixSheetid]
									   ,[SiteId]
									   ,[OperatingAreaId]
									   ,[WorkstationId]
									   ,[Usergroupid]
									   ,[UserId]
									   ,[FCalcDate]
									   ,[Quantity]
									   ,[GrossAmount]
									   ,[NetAmount]
									   ,[Price]
									   ,[Percentage]
									   ,[RemaningValues]
									   ,[RevenueAmount]
									   ,[AccountingType]
									   ,[RRCalcTypeTrigger]
									   ,[RRPercentage]			
									   ,[RRDays]
									   ,[AttributeIDs]
									   ,[oobflag]
									   )
									   select *
									   from (
										select distinct p.COAAccountId, 
											   p.RevenueRecognitionRuleId,		   
											   p.RRCalcTypeWhere,
											   p.RRCalcTypeMethod,	   
											   p.COAAccountConfigId,
											   p.COAAccountTypeId,
											   data_sale.PaidTransactionId,
											   RR_DATA_REVENUE.saleid as Saleid,
											   ISNULL(rdata.Ticketid, data_ticket.Ticketid) as ticketID, 
											   RR_DATA_REVENUE.Saleitemid,
											   RR_DATA_REVENUE.Matrixcellid,
											   RR_DATA_REVENUE.MatrixSheetId,
											   RR_DATA_REVENUE.Siteid,
											   RR_DATA_REVENUE.OperatingAreaId,
											   RR_DATA_REVENUE.Workstationid,
											   RR_DATA_REVENUE.UserGroupid,
											   RR_DATA_REVENUE.UserId as userID,
											   @BatchDate as BatchDate,
											   RR_DATA_REVENUE.Quantity as Quantity,
											   RR_DATA_REVENUE.GrossAmount as GrossAmount,
											   RR_DATA_REVENUE.NetAmount as NetAmount,
											   p.Price as ConfigPrice,
											   p.Percentage as ConfigPercentage,
											   p.RemainingValues,																		
												abs(round(case when ((((DATA_SaleItem.unitprice - data_saleitem.unittaxes) - ISNULL(TotalUsed, 0)) &amp;#62; 0) and ((
																								(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  
																									((
																									(((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) * (select sum(percentage)
																																										from coa_cnf_accountconfig AC WITH(NOLOCK)
																																										where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																										and ac.accountingtype = p.accountingtype
																																										)
																									)/100)) &amp;#60;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(TotalUsed, 0))))

																	then 
																	((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.rrPercentage)/100) -  ((((DATA_Ticket.Price - DATA_Ticket.taxes) *  p.RRPercentage)/100) * (select sum(percentage)
																																			from coa_cnf_accountconfig AC WITH(NOLOCK)
																																			where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																			and ac.accountingtype = p.accountingtype
																																			))/100)
															 when DATA_Ticket.Price = 0 then
																		ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
																													from rr_data_revenue
																													where rr_data_revenue.ticketid = data_ticket.Ticketid
																														and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																														and accountingtype = 2
																														and COAAccountId not in (1,2 , 3, 4)
																														and SaleItemTaxId is null
																														and SaleItemRuleID is null
																														), 0)
															
																		*(p.percentage /100)*(p.RRPercentage /100)
																else (DATA_Ticket.Price - DATA_Ticket.taxes) - TotalUsed
															end, 2)) as RevenueAmount,
											   p.Accountingtype,
											   p.RRCalcTypeTrigger,
											   p.RRPercentage,
												p.Days,
											   RR_DATA_REVENUE.AttributeIDs,
											   rr_data_revenue.OOBflag

										from RR_DATA_REVENUE WITH(NOLOCK)
											INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
											INNER  JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.saleid
											INNER JOIN DATA_Ticket WITH(NOLOCK)								on data_ticket.SaleItemId = data_saleitem.SaleItemId
											INNER JOIN (  
													select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
													RR_CNF_RevenueRecognitionRule.Days,
													RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
													RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
													FromDate,
													ToDate,
													RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
													RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
													COA_CNF_AccountConfig.CoaAccountid,
													COA_CNF_AccountConfig.AccountingType,
													COA_CNF_AccountConfig.Price,
													COA_CNF_AccountConfig.Percentage,
													COA_CNF_AccountConfig.RemainingValues,
													COA_CNF_AccountConfig.SiteID,
													coa_cnf_account.code as AccountCode,
													COA_CNF_AccountType.Code as AccountTypeCode,
													COA_CNF_AccountType.COAAccountTypeId,
													Matrixcellid.MatrixcellID,
													COA_CNF_AccountConfig.COAAccountConfigId,
													RR_CNF_RevenueRecognitionRule.UsageTime

											from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
												inner join @Matrixcells	Matrixcellid						ON Matrixcellid.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId		
												INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
												INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
												INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

											where COA_CNF_AccountConfig.RemainingValues = 1
											  and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod not in (4, 5)
											  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
																											   from #RulesToRun)

											)p   ON (RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) 
											   LEFT JOIN (select rr_data_revenue.ticketid, AccountingType, sum(revenueamount) as TotalUsed
															from rr_data_revenue WITH(NOLOCK)
															inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
															where rr_data_revenue.ticketid is not null
															  and coaaccountid not in (@suspendid)
															  and rrcalctypetrigger &amp;#60;&amp;#62; 1
															group by rr_data_revenue.ticketid, AccountingType, coaaccountid, AttributeIDs
															)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_saleitem.ticketid)	and rdata.AccountingType = p.AccountingType 
																									   and p.coaaccountid = p.coaaccountid
											where cast(data_ticket.FEncodeDate as date) &amp;#60;= @BatchDate
											and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
													from rr_data_revenue
													where rr_data_revenue.ticketid = DATA_Ticket.ticketid
													and RR_DATA_Revenue.RRCalcTypeTrigger = 1
													and accountingtype = 2
													and COAAccountId not in (1, 2, 3, 4)
													and SaleItemTaxId is null
													and SaleItemRuleID is null), 0)) &amp;#62; 0
											 and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
														from rr_data_revenue
														where rr_data_revenue.ticketid = DATA_Ticket.ticketid
														and RR_DATA_Revenue.RRCalcTypeTrigger = 1
														and accountingtype = 2
														and COAAccountId not in (1, 2, 3, 4)
														and SaleItemTaxId is null
														and SaleItemRuleID is null), 0)) &amp;#62; 0
											and cast(data_ticket.PrintDateTime as date) &amp;#60;= @BatchDate
											  and cast(data_ticket.FEncodeDate as date) &amp;#62;= (select CNF_System.RRStartDate from CNF_System)
											  and @BatchDate &amp;#62;= case when p.UsageTime = 0 then @BatchDate
																	  else data_ticket.activeFrom
																  END
											  and DATA_Ticket.VoidType not in (104, 125)
											  and ((data_ticket.VoidType &amp;#60;= 99) or (data_ticket.VoidType = 203) or
												  ((data_ticket.VoidType in (109, 102, 125)) and
												  (select top 1  DATA_Transaction.FTransactionDate
													from data_transaction2ticket WITH(NOLOCK)
														INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																														and DATA_Transaction.TransactionType in (18, 20, 22)
													where data_transaction2ticket.TicketId = data_ticket.ticketid
												) &amp;#62; @batchdate

											))
											)r
											where Round(RevenueAmount, 12) &amp;#60;&amp;#62; 0 
						end


			set @RRMethod = 0

			select @RRMethod = COUNT(*) from RR_CNF_RevenueRecognitionRule WITH(NOLOCK) where RRCalcTypeTrigger = 4 and rrcalctypeMethod = 4

			if @RRMethod &amp;#62; 0 
			begin
				--RRCalcTypeMethod = 4   --Exclusive of last day   --Percentages.
				INSERT INTO [dbo].[RR_DATA_Revenue]
										   ([COAAccountId]
										   ,[RevenueRecognitionRuleId]
										   ,[RRCalcTypeWhere]
										   ,[RRCalcTypeMethod]
										   ,[COAAccountConfigId]
										   ,[COAAccountType]
										   ,[TransactionID]
										   ,[SaleId]
										   ,[Ticketid]
										   ,[SaleItemID]
										   ,[MatrixCellid]
										   ,[MatrixSheetid]
										   ,[SiteId]
										   ,[OperatingAreaId]
										   ,[WorkstationId]
										   ,[Usergroupid]
										   ,[UserId]
										   ,[FCalcDate]
										   ,[Quantity]
										   ,[GrossAmount]
										   ,[NetAmount]
										   ,[Price]
										   ,[Percentage]
										   ,[RemaningValues]
										   ,[RevenueAmount]
										   ,[AccountingType]
										   ,[RRCalcTypeTrigger]
										   ,[RRPercentage]			
										   ,[RRDays]
										   ,[AttributeIDs]
										   ,[TimePeriod]
										   ,[oobflag]
										   )
										   select *
										   from (
											select distinct p.COAAccountId, 
												   p.RevenueRecognitionRuleId,		   
												   p.RRCalcTypeWhere,
												   p.RRCalcTypeMethod,	   
												   p.COAAccountConfigId,
												   p.COAAccountTypeId,
												   data_sale.PaidTransactionId,
												   DATA_SaleItem.saleid as Saleid,
												   ISNULL(rdata.Ticketid, data_ticket.Ticketid) TicketID,
												   DATA_SaleItem.saleitemid, 
												   DATA_SaleItem.Matrixcellid,
												   cnf_matrixcell.MatrixSheetId,
												   DATA_Ticket.Siteid,
												   CNF_OperatingArea.OperatingAreaId,
												   DATA_Ticket.Workstationid,
												   RR_DATA_REVENUE.UserGroupid,
												   RR_DATA_REVENUE.UserId,
												   @BatchDate as BatchDate,
												   1 as Quantity,
												   ISNULL(case when DATA_Ticket.Price &amp;#60;&amp;#62; 0 then data_ticket.price
														else OLDTic.price
													end, 0) as GrossAmount,
												   isnull(((case when DATA_Ticket.Price &amp;#60;&amp;#62; 0 then data_ticket.price
														else OLDTic.price
													end) - (case when DATA_Ticket.taxes &amp;#60;&amp;#62; 0 then data_ticket.taxes
														else OLDTic.taxes
													end) ), 0) as NetAmount,
												   p.Price as ConfigPrice,
												   p.Percentage as ConfigPercentage,
												   p.RemainingValues,
													abs(round(Case when p.Price &amp;#62; 0 then
																							 case when ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#62;= p.Price then p.Price
																								  when ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#60; p.Price then ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0))
																								  else 0
																							  end 									  									  
													  else case when ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#62; (((DATA_Ticket.Price - data_ticket.taxes)/
																	case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
																		 else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
																	  end )
													  * (p.Percentage/100))
																			then (((DATA_Ticket.Price - data_ticket.taxes)/case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
																																								 else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
																																							  end ) * (p.Percentage/100))

																when (DATA_Ticket.Price - data_ticket.taxes) - (select ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																											from 
																											(
																											select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																											from rr_data_revenue
																											where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																												and rr_data_revenue.coaaccountid in (select coaaccountid from coa_cnf_accountconfig where RevenueRecognitionRuleId = p.RevenueRecognitionRuleId and accountingtype = p.AccountingType)
																												and accountingtype = p.AccountingType
																												group by accountingtype
																										
																											)n) &amp;#62; 0 then		
																										


																											((DATA_Ticket.Price - data_ticket.taxes))*(p.percentage /100)												
																else 0
															end
												   end, 2)) as RevenueAmount,
												   p.Accountingtype as accountingtype,
												   p.RRCalcTypeTrigger,
												   p.RRPercentage,
												   p.Days,
												   RR_DATA_REVENUE.AttributeIDs,
													case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
															else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
													end  TimePeriod,
													rr_data_revenue.oobflag
								

											from DATA_Ticket WITH(NOLOCK)	
												INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.SaleItemId = DATA_Ticket.saleitemid
												INNER  JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.saleid
												LEFT  JOIN data_ticket OLDTic WITH(NOLOCK)						on OLDTic.ticketid = data_saleitem.itemticketid
												LEFT  JOIN (select max(saleid) as saleid, 
																   max(ticketid) as Ticketid,
																   max(Userid) as Userid, 
																   (select max(usergroupid) from data_transaction where data_transaction.saleid = rr_data_revenue.saleid) as usergroupid,
																   max(rr_data_revenue.AttributeIDs) as AttributeIDs,
																   Max(rr_data_revenue.RevenueRecognitionRuleId) as RevenueRecognitionRuleId,
																   MAX(oobflag) oobflag
															from rr_data_revenue
															where RevenueRecognitionRuleId &amp;#60;&amp;#62; 1

															group by rr_data_revenue.saleid) as rr_data_revenue							on data_ticket.ticketid = RR_DATA_REVENUE.ticketid and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
												LEFT  JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_Matrixcell.matrixcellid = data_ticket.matrixcellid
												left  join cnf_workstation WITH(NOLOCK)							on CNF_Workstation.workstationid = data_ticket.workstationid
												LEFT  JOIN CNF_OperatingArea WITH(NOLOCK)						on CNF_OperatingArea.OperatingAreaId = CNF_Workstation.OperatingAreaId															
												INNER JOIN (  
														select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
																		RR_CNF_RevenueRecognitionRule.Days,
																		RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
																		RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
																		FromDate,
																		ToDate,
																		RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
																		RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
																		COA_CNF_AccountConfig.CoaAccountid,
																		COA_CNF_AccountConfig.AccountingType,
																		COA_CNF_AccountConfig.Price,
																		COA_CNF_AccountConfig.Percentage,
																		COA_CNF_AccountConfig.RemainingValues,
																		COA_CNF_AccountConfig.SiteID,
																		coa_cnf_account.code as AccountCode,
																		COA_CNF_AccountType.Code as AccountTypeCode,
																		COA_CNF_AccountType.COAAccountTypeId,
																		Matrixcellid.matrixcellid,
																		COA_CNF_AccountConfig.COAAccountConfigId,
																		RR_CNF_RevenueRecognitionRule.usagetime

																from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
																	inner join @Matrixcells	Matrixcellid						ON Matrixcellid.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId									
																	INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
																	INNER JOIN coa_cnf_account	 WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
																	INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

																where COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
																  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnTimePeriodTrigger
																  and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 4
																  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
																																   from #RulesToRun)

													)p   ON (data_ticket.MATRIXCELLID = p.MATRIXCELLID) 

												   LEFT JOIN (select ticketid, accountingtype, sum(totalused) as totalused
																from (
																select rr_data_revenue.ticketid, AccountingType, sum(revenueamount) as TotalUsed
																from rr_data_revenue WITH(NOLOCK)
																inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
																where rr_data_revenue.ticketid is not null
																	and coaaccountid not in (@suspendid)
																	and rrcalctypetrigger &amp;#60;&amp;#62; 1
																	and rr_data_revenue.FCalcDate &amp;#60;= @BatchDate
																group by rr_data_revenue.ticketid, AccountingType

																UNION ALL

																select DATA_TICKET.ticketid, AccountingType, sum(revenueamount) as TotalUsed
																from DATA_TICKET WITH(NOLOCK) 
																	LEFT  JOIN DATA_SaleItem WITH(NOLOCK)				on data_saleitem.saleitemid = data_ticket.saleitemid
																	LEFT  JOIN rr_data_revenue RD1 WITH(NOLOCK) 		on rd1.ticketid = data_saleitem.ticketid

																where DATA_TICKET.ticketid is not null
																	and coaaccountid not in (@suspendid)
																	and rrcalctypetrigger &amp;#60;&amp;#62; 1
																	and RD1.FCalcDate &amp;#60;= @BatchDate
																group by DATA_TICKET.ticketid, AccountingType
																)p1
																group by ticketid, accountingtype
																)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                         
									where @BatchDate between DATA_Ticket.ActiveFrom and dateadd(dd, 1, DATA_Ticket.ActiveTo)
									   and @BatchDate &amp;#62;= case when p.UsageTime = 0 then @BatchDate
															  else data_ticket.activeFrom
														  END
										and DATA_Ticket.VoidType not in (104, 125)
										and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
												from rr_data_revenue
												where rr_data_revenue.ticketid = DATA_Ticket.ticketid
												and RR_DATA_Revenue.RRCalcTypeTrigger = 1
												and accountingtype = 2
												and COAAccountId not in (1, 2, 3, 4)
												and SaleItemTaxId is null
												and SaleItemRuleID is null), 0)) &amp;#62; 0
										and ((data_ticket.VoidType &amp;#60;= 99) or 
													((data_ticket.VoidType in (109, 102, 125)) and
													(select top 1  DATA_Transaction.FTransactionDate
														from data_transaction2ticket WITH(NOLOCK)
															INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																															and DATA_Transaction.TransactionType in (18, 20, 22)
														where data_transaction2ticket.TicketId = data_ticket.ticketid
													) &amp;#62; @batchdate

												))
									)p
									where Round(RevenueAmount, 12) &amp;#60;&amp;#62; 0 


				--RRCalcTypeMethod = 4 --Exclusive of last day   -NOT Remaining Values
									INSERT INTO [dbo].[RR_DATA_Revenue]
										   ([COAAccountId]
										   ,[RevenueRecognitionRuleId]
										   ,[RRCalcTypeWhere]
										   ,[RRCalcTypeMethod]
										   ,[COAAccountConfigId]
										   ,[COAAccountType]
										   ,[TransactionID]
										   ,[SaleId]
										   ,[Ticketid]
										   ,[Saleitemid]
										   ,[MatrixCellid]
										   ,[MatrixSheetid]
										   ,[SiteId]
										   ,[OperatingAreaId]
										   ,[WorkstationId]
										   ,[Usergroupid]
										   ,[UserId]
										   ,[FCalcDate]
										   ,[Quantity]
										   ,[GrossAmount]
										   ,[NetAmount]
										   ,[Price]
										   ,[Percentage]
										   ,[RemaningValues]
										   ,[RevenueAmount]
										   ,[AccountingType]
										   ,[RRCalcTypeTrigger]
										   ,[RRPercentage]			
										   ,[RRDays]
										   ,[AttributeIDs]
										   ,[TimePeriod]
										   ,[oobflag]
										   )
										   select *
										   from (
											select distinct p.COAAccountId, 
												   p.RevenueRecognitionRuleId,		   
												   p.RRCalcTypeWhere,
												   p.RRCalcTypeMethod,	   
												   p.COAAccountConfigId,
												   p.COAAccountTypeId,
												   data_sale.PaidTransactionId,
												   RR_DATA_REVENUE.saleid as Saleid,
												   ISNULL(rdata.Ticketid, data_ticket.Ticketid) as ticketID, 
												   RR_DATA_REVENUE.Saleitemid,
												   RR_DATA_REVENUE.Matrixcellid,
												   RR_DATA_REVENUE.MatrixSheetId,
												   RR_DATA_REVENUE.Siteid,
												   RR_DATA_REVENUE.OperatingAreaId,
												   RR_DATA_REVENUE.Workstationid,
												   max(RR_DATA_REVENUE.UserGroupid) UserGroupid,
												   max(RR_DATA_REVENUE.UserId) as userID,
												   @BatchDate as BatchDate,
												   RR_DATA_REVENUE.Quantity as Quantity,
												   RR_DATA_REVENUE.GrossAmount as GrossAmount,
												   RR_DATA_REVENUE.NetAmount as NetAmount,
												   p.Price as ConfigPrice,
												   p.Percentage as ConfigPercentage,
												   p.RemainingValues,
								   
											abs(round(case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &amp;#62; 0) and								                 												
																		((((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
																						else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
																				end )
																				)
																				))  &amp;#62; rdataLEFT.TotalLeft )
																			then rdataLEFT.TotalLeft
								  
								  
								  
								  
								  
								  
								  
																		when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)) &amp;#62; 0) and 								        
																									((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
																																			else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
																																	end )) - ISNULL(rdata.TotalUsed, 0) &amp;#60;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - ISNULL(rdata.TotalUsed, 0)))
																																																								
																		then 
																		((((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
																																			else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
																																	end )))  -  ((((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
																																			else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
																																	end )))  * (select sum(percentage)
																																				from coa_cnf_accountconfig AC WITH(NOLOCK)
																																				where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																				and ac.accountingtype = p.accountingtype
																																				))/100)
																	else (DATA_Ticket.Price - DATA_Ticket.taxes) - rdata.TotalUsed
																end, 2)) as RevenueAmount,
												   p.Accountingtype,
												   p.RRCalcTypeTrigger,
												   p.RRPercentage,
												   p.Days,
												   max(RR_DATA_REVENUE.AttributeIDs) AttributeIDs,
												   case when DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) = 0 then 1
															else DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo)
													end TimePeriod,
													rr_data_revenue.oobflag

											from RR_DATA_REVENUE WITH(NOLOCK)
												INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
												INNER JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.saleid
												INNER JOIN DATA_Ticket WITH(NOLOCK)								on data_ticket.SaleItemId = data_saleitem.SaleItemId
												INNER JOIN (  
														select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
														RR_CNF_RevenueRecognitionRule.Days,
														RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
														RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
														FromDate,
														ToDate,
														RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
														RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
														COA_CNF_AccountConfig.CoaAccountid,
														COA_CNF_AccountConfig.AccountingType,
														COA_CNF_AccountConfig.Price,
														COA_CNF_AccountConfig.Percentage,
														COA_CNF_AccountConfig.RemainingValues,
														COA_CNF_AccountConfig.SiteID,
														coa_cnf_account.code as AccountCode,
														COA_CNF_AccountType.Code as AccountTypeCode,
														COA_CNF_AccountType.COAAccountTypeId,
														Matrixcellid.MatrixcellID,
														COA_CNF_AccountConfig.COAAccountConfigId,
														RR_CNF_RevenueRecognitionRule.UsageTime

												from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
													inner join @Matrixcells	Matrixcellid						ON Matrixcellid.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId		
													INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
													INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

												where COA_CNF_AccountConfig.RemainingValues = 1
												  and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 4
												  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
																												   from #RulesToRun)

												)p   ON (RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) 
												LEFT JOIN (select rr_data_revenue.ticketid, coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
																from rr_data_revenue WITH(NOLOCK)
																inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
																where rr_data_revenue.ticketid is not null
																  and coaaccountid not in (@suspendid)
																  and rrcalctypetrigger &amp;#60;&amp;#62; 1
																  and rr_data_revenue.FCalcDate &amp;#60;= @BatchDate
																group by rr_data_revenue.ticketid, AccountingType, coaaccountid
																)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_saleitem.ticketid)	
																											and rdata.AccountingType = p.AccountingType 
																											 and p.COAAccountId = rdata.coaaccountid

												LEFT JOIN (select rr_data_revenue.ticketid, AccountingType, (DATA_TICKET.price - DATA_TICKET.taxes) - sum(revenueamount) as TotalLeft
																from rr_data_revenue WITH(NOLOCK)
																inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
																where rr_data_revenue.ticketid is not null
																  and coaaccountid not in (@suspendid)
																  and rrcalctypetrigger &amp;#60;&amp;#62; 1
																  and rr_data_revenue.FCalcDate &amp;#60;= @BatchDate
																group by rr_data_revenue.ticketid, AccountingType, (DATA_TICKET.price - DATA_TICKET.taxes)
																)rdataLEFT									ON rdataLEFT.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_saleitem.ticketid)	
																											and rdataLEFT.AccountingType = p.AccountingType 

												where  RR_DATA_REVENUE.COAAccountId not in (1, 2, 3, 4)
												  and RR_DATA_REVENUE.RRCalcTypeTrigger in (4)
													and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
															from rr_data_revenue
															where rr_data_revenue.ticketid = DATA_Ticket.ticketid
															and RR_DATA_Revenue.RRCalcTypeTrigger = 1
															and accountingtype = 2
															and COAAccountId not in (1, 2, 3, 4)
															and SaleItemTaxId is null
															and SaleItemRuleID is null), 0)) &amp;#62; 0
												  and @BatchDate between DATA_Ticket.ActiveFrom and dateadd(dd, 1, DATA_Ticket.ActiveTo)
												  and @BatchDate &amp;#62;= case when p.UsageTime = 0 then @BatchDate
																		  else data_ticket.activeFrom
																	  END
													and DATA_Ticket.VoidType not in (104, 125)
													and ((data_ticket.VoidType &amp;#60;= 99) or 
																((data_ticket.VoidType in (109, 102, 125)) and
																(select top 1  DATA_Transaction.FTransactionDate
																	from data_transaction2ticket WITH(NOLOCK)
																		INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																																		and DATA_Transaction.TransactionType in (18, 20, 22)
																	where data_transaction2ticket.TicketId = data_ticket.ticketid
																) &amp;#62; @batchdate

															))
												group by p.COAAccountId, 
												   p.RevenueRecognitionRuleId,		   
												   p.RRCalcTypeWhere,
												   p.RRCalcTypeMethod,	   
												   p.COAAccountConfigId,
												   p.COAAccountTypeId,
												   RR_DATA_REVENUE.saleid,
												   ISNULL(rdata.Ticketid, data_ticket.Ticketid), 
												   RR_DATA_REVENUE.Saleitemid,
												   RR_DATA_REVENUE.Matrixcellid,
												   RR_DATA_REVENUE.MatrixSheetId,
												   RR_DATA_REVENUE.Siteid,
												   RR_DATA_REVENUE.OperatingAreaId,
												   RR_DATA_REVENUE.Workstationid,
												   RR_DATA_REVENUE.Quantity,
												   RR_DATA_REVENUE.GrossAmount,
												   RR_DATA_REVENUE.NetAmount,
												   p.Price,
												   p.Percentage,
												   p.RemainingValues,
												   p.Accountingtype,
												   p.RRCalcTypeTrigger,
												   p.RRPercentage,
												   p.Days,
												   DATA_Ticket.Price,
												   DATA_Ticket.taxes,
												   DATA_Ticket.ActiveFrom,
												   DATA_Ticket.ActiveTo,
												   rdata.TotalUsed,
												   rdataLEFT.TotalLeft,
												   data_sale.PaidTransactionId,
												   rr_data_revenue.oobflag
												)r
												where Round(RevenueAmount, 12) &amp;#60;&amp;#62; 0 
			END

			set @RRMethod = 0

			select @RRMethod = COUNT(*) from RR_CNF_RevenueRecognitionRule WITH(NOLOCK) where RRCalcTypeTrigger = 4 and rrcalctypeMethod = 5

			if @RRMethod &amp;#62; 0 
				begin
					--RRCalcTypeMethod = 5   --Exclusive of last day   --Percentages.
					INSERT INTO [dbo].[RR_DATA_Revenue]
											   ([COAAccountId]
											   ,[RevenueRecognitionRuleId]
											   ,[RRCalcTypeWhere]
											   ,[RRCalcTypeMethod]
											   ,[COAAccountConfigId]
											   ,[COAAccountType]
											   ,[TransactionID]
											   ,[SaleId]
											   ,[Ticketid]
											   ,[SaleItemID]
											   ,[MatrixCellid]
											   ,[MatrixSheetid]
											   ,[SiteId]
											   ,[OperatingAreaId]
											   ,[WorkstationId]
											   ,[Usergroupid]
											   ,[UserId]
											   ,[FCalcDate]
											   ,[Quantity]
											   ,[GrossAmount]
											   ,[NetAmount]
											   ,[Price]
											   ,[Percentage]
											   ,[RemaningValues]
											   ,[RevenueAmount]
											   ,[AccountingType]
											   ,[RRCalcTypeTrigger]
											   ,[RRPercentage]			
											   ,[RRDays]
											   ,[AttributeIDs]
											   ,[TimePeriod]
											   ,[oobflag]
											   )
											   select *
											   from (
												select distinct p.COAAccountId, 
													   p.RevenueRecognitionRuleId,		   
													   p.RRCalcTypeWhere,
													   p.RRCalcTypeMethod,	   
													   p.COAAccountConfigId,
													   p.COAAccountTypeId,
													   DATA_Sale.PaidTransactionId,
													   DATA_SaleItem.saleid as Saleid,
													   ISNULL(rdata.Ticketid, data_ticket.Ticketid) TicketID,
													   DATA_SaleItem.saleitemid, 
													   DATA_SaleItem.Matrixcellid,
													   cnf_matrixcell.MatrixSheetId,
													   DATA_Ticket.Siteid,
													   CNF_OperatingArea.OperatingAreaId,
													   DATA_Ticket.Workstationid,
													   (RR_DATA_REVENUE.UserGroupid) UserGroupid,
													   (RR_DATA_REVENUE.UserId) UserId,
													   @BatchDate as BatchDate,
													   1 as Quantity,
													   ISNULL(case when DATA_Ticket.Price &amp;#60;&amp;#62; 0 then data_ticket.price
															else OLDTic.price
														end, 0) as GrossAmount,
													   isnull(((case when DATA_Ticket.Price &amp;#60;&amp;#62; 0 then data_ticket.price
															else OLDTic.price
														end) - (case when DATA_Ticket.taxes &amp;#60;&amp;#62; 0 then data_ticket.taxes
															else OLDTic.taxes
														end) ), 0) as NetAmount,
													   p.Price as ConfigPrice,
													   p.Percentage as ConfigPercentage,
													   p.RemainingValues,
											 abs(round(Case when p.Price &amp;#62; 0 then
																								 case when ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#62;= p.Price then p.Price
																									  when ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#60; p.Price then ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0))
																									  else 0
																								  end 									  									  
														  else case when ((DATA_Ticket.Price - data_ticket.taxes) - ISNULL(rdata.totalused, 0)) &amp;#62; (((DATA_Ticket.Price - data_ticket.taxes)/
																		case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																			 else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
																		  end )
														  * (p.Percentage/100))
																				then (((DATA_Ticket.Price - data_ticket.taxes)/case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																																									 else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
																																								  end ) * (p.Percentage/100))

																	when (DATA_Ticket.Price - DATA_Ticket.Taxes)  - (select ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																												from 
																												(
																												select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																												from rr_data_revenue
																												where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																													and rr_data_revenue.coaaccountid in (select coaaccountid from coa_cnf_accountconfig where RevenueRecognitionRuleId = p.RevenueRecognitionRuleId and accountingtype = p.AccountingType)
																													and accountingtype = p.AccountingType
																													group by accountingtype
																										
																												)n) &amp;#62; 0 then		
																										


																												((DATA_Ticket.Price - DATA_Ticket.Taxes) - (select ISNULL((sum(ISNULL(TotalT, 0))), 0) totalleft
																												from 
																												(
																												select sum(ISNULL(revenueamount, 0))as TotalT, 0 as TotalU
																												from rr_data_revenue
																												where rr_data_revenue.ticketid = ISNULL(rdata.Ticketid, data_ticket.Ticketid)
																													and rr_data_revenue.coaaccountid in (select coaaccountid from coa_cnf_accountconfig where RevenueRecognitionRuleId = p.RevenueRecognitionRuleId and accountingtype = p.AccountingType)
																													and accountingtype = p.AccountingType
																													group by accountingtype
																										
																															)n))*(p.percentage /100)												
																	else 0
																end
													   end, 2)) as RevenueAmount,
													   p.Accountingtype as accountingtype,
													   p.RRCalcTypeTrigger,
													   p.RRPercentage,
													   p.Days,
													   RR_DATA_REVENUE.AttributeIDs,
														case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
														end  TimePeriod,
														rr_data_revenue.oobflag
								

												from DATA_Ticket WITH(NOLOCK)	
													INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.SaleItemId = DATA_Ticket.saleitemid
													INNER  JOIN DATA_Sale WITH(NOLOCK)								ON DATA_Sale.SaleId = DATA_SaleItem.saleid
													LEFT  JOIN data_ticket OLDTic WITH(NOLOCK)						on OLDTic.ticketid = data_saleitem.itemticketid
													LEFT  JOIN (select max(saleid) as saleid, 
																	   max(ticketid) as Ticketid,
																	   max(Userid) as Userid, 
																	   (select max(usergroupid) from data_transaction where data_transaction.saleid = rr_data_revenue.saleid) as usergroupid,
																	   max(rr_data_revenue.AttributeIDs) as AttributeIDs,
																	   Max(rr_data_revenue.RevenueRecognitionRuleId) as RevenueRecognitionRuleId,
																	   max(oobflag) oobflag
																from rr_data_revenue
																where RevenueRecognitionRuleId &amp;#60;&amp;#62; 1

																group by rr_data_revenue.saleid) as rr_data_revenue							on data_ticket.ticketid = RR_DATA_REVENUE.ticketid and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
													LEFT  JOIN cnf_matrixcell WITH(NOLOCK)							on cnf_Matrixcell.matrixcellid = data_ticket.matrixcellid
													left  join cnf_workstation WITH(NOLOCK)							on CNF_Workstation.workstationid = data_ticket.workstationid
													LEFT  JOIN CNF_OperatingArea WITH(NOLOCK)						on CNF_OperatingArea.OperatingAreaId = CNF_Workstation.OperatingAreaId															
													INNER JOIN (  
															select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
																			RR_CNF_RevenueRecognitionRule.Days,
																			RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
																			RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
																			FromDate,
																			ToDate,
																			RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
																			RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
																			COA_CNF_AccountConfig.CoaAccountid,
																			COA_CNF_AccountConfig.AccountingType,
																			COA_CNF_AccountConfig.Price,
																			COA_CNF_AccountConfig.Percentage,
																			COA_CNF_AccountConfig.RemainingValues,
																			COA_CNF_AccountConfig.SiteID,
																			coa_cnf_account.code as AccountCode,
																			COA_CNF_AccountType.Code as AccountTypeCode,
																			COA_CNF_AccountType.COAAccountTypeId,
																			Matrixcellid.matrixcellid,
																			COA_CNF_AccountConfig.COAAccountConfigId,
																			RR_CNF_RevenueRecognitionRule.usagetime

																	from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
																		inner join @Matrixcells	Matrixcellid						ON Matrixcellid.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId									
																		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
																		INNER JOIN coa_cnf_account	 WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
																		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

																	where COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
																	  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnTimePeriodTrigger
																	  and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 5
																	  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
																																	   from #RulesToRun)

														)p   ON (data_ticket.MATRIXCELLID = p.MATRIXCELLID) 

													   LEFT JOIN (select ticketid, accountingtype, sum(totalused) as totalused
																	from (
																	select rr_data_revenue.ticketid, AccountingType, sum(revenueamount) as TotalUsed
																	from rr_data_revenue WITH(NOLOCK)
																	inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
																	where rr_data_revenue.ticketid is not null
																		and coaaccountid not in (@suspendid)
																		and rrcalctypetrigger &amp;#60;&amp;#62; 1
																		and rr_data_revenue.FCalcDate &amp;#60;= @BatchDate
																	group by rr_data_revenue.ticketid, AccountingType

																	UNION ALL

																	select DATA_TICKET.ticketid, AccountingType, sum(revenueamount) as TotalUsed
																	from DATA_TICKET WITH(NOLOCK) 
																		LEFT  JOIN DATA_SaleItem WITH(NOLOCK)				on data_saleitem.saleitemid = data_ticket.saleitemid
																		LEFT  JOIN rr_data_revenue RD1 WITH(NOLOCK) 		on rd1.ticketid = data_saleitem.ticketid

																	where DATA_TICKET.ticketid is not null
																		and coaaccountid not in (@suspendid)
																		and rrcalctypetrigger &amp;#60;&amp;#62; 1
																		and RD1.FCalcDate &amp;#60;= @BatchDate
																	group by DATA_TICKET.ticketid, AccountingType
																	)p1
																	group by ticketid, accountingtype
																	)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_ticket.ticketid)	and rdata.AccountingType = p.AccountingType 
												                                         
										where  @BatchDate between DATA_Ticket.ActiveFrom and dateadd(dd, 2, DATA_Ticket.ActiveTo)
										   and @BatchDate &amp;#62;= case when p.UsageTime = 0 then @BatchDate
																  else data_ticket.activeFrom
															  END
											and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
													from rr_data_revenue
													where rr_data_revenue.ticketid = DATA_Ticket.ticketid
													and RR_DATA_Revenue.RRCalcTypeTrigger = 1
													and accountingtype = 2
													and COAAccountId not in (1, 2, 3, 4)
													and SaleItemTaxId is null
													and SaleItemRuleID is null), 0)) &amp;#62; 0
										and DATA_Ticket.VoidType not in (104, 125)
										and (data_ticket.VoidType &amp;#60;= 99) or 
													((data_ticket.VoidType in (109, 102, 125)) and
													(select top 1  DATA_Transaction.FTransactionDate
														from data_transaction2ticket WITH(NOLOCK)
															INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																															and DATA_Transaction.TransactionType in (18, 20, 22)
														where data_transaction2ticket.TicketId = data_ticket.ticketid
													) &amp;#62; @batchdate

												)
										)p
										where Round(RevenueAmount, 12) &amp;#60;&amp;#62; 0 


					--RRCalcTypeMethod = 5 --Exclusive of last day   -NOT Remaining Values
										INSERT INTO [dbo].[RR_DATA_Revenue]
											   ([COAAccountId]
											   ,[RevenueRecognitionRuleId]
											   ,[RRCalcTypeWhere]
											   ,[RRCalcTypeMethod]
											   ,[COAAccountConfigId]
											   ,[COAAccountType]
											   ,[TransactionID]
											   ,[SaleId]
											   ,[Ticketid]
											   ,[Saleitemid]
											   ,[MatrixCellid]
											   ,[MatrixSheetid]
											   ,[SiteId]
											   ,[OperatingAreaId]
											   ,[WorkstationId]
											   ,[Usergroupid]
											   ,[UserId]
											   ,[FCalcDate]
											   ,[Quantity]
											   ,[GrossAmount]
											   ,[NetAmount]
											   ,[Price]
											   ,[Percentage]
											   ,[RemaningValues]
											   ,[RevenueAmount]
											   ,[AccountingType]
											   ,[RRCalcTypeTrigger]
											   ,[RRPercentage]			
											   ,[RRDays]
											   ,[AttributeIDs]
											   ,[TimePeriod]
											   ,[oobflag]
											   )
											   select *
											   from (
									select distinct max(p.COAAccountId) COAAccountId, 
													   max(p.RevenueRecognitionRuleId) RevenueRecognitionRuleId,		   
													   max(p.RRCalcTypeWhere) RRCalcTypeWhere,
													   max(p.RRCalcTypeMethod) RRCalcTypeMethod,	   
													   max(p.COAAccountConfigId) COAAccountConfigId,
													   max(p.COAAccountTypeId) COAAccountTypeId,
													   max(paidtransactionid) paidtransactionid,
													   max(RR_DATA_REVENUE.saleid) as Saleid,
													   ISNULL(rdata.Ticketid, data_ticket.Ticketid) as ticketID, 
													   (RR_DATA_REVENUE.Saleitemid) Saleitemid,
													   max(RR_DATA_REVENUE.Matrixcellid) Matrixcellid,
													   max(RR_DATA_REVENUE.MatrixSheetId) MatrixSheetId,
													   max(RR_DATA_REVENUE.Siteid) Siteid,
													   max(RR_DATA_REVENUE.OperatingAreaId) OperatingAreaId,
													   max(RR_DATA_REVENUE.Workstationid) Workstationid,
													   max(RR_DATA_REVENUE.UserGroupid) UserGroupid,
													   max(RR_DATA_REVENUE.UserId) as userID,
													   @BatchDate as BatchDate,
													   max(RR_DATA_REVENUE.Quantity) as Quantity,
													   max(RR_DATA_REVENUE.GrossAmount) as GrossAmount,
													   max(RR_DATA_REVENUE.NetAmount) as NetAmount,
													   max(p.Price) as ConfigPrice,
													   max(p.Percentage) as ConfigPercentage,
													   (p.RemainingValues) RemainingValues,
								   
												abs(round(case when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - max(ISNULL(rdata.TotalUsed, 0))) &amp;#62; 0) and								                 												
																			((((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																							else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
																					end )
																					)
																					))  &amp;#62; max(rdataLEFT.TotalLeft) )
																				then max(rdataLEFT.TotalLeft)
								  
								  
								  
								  
								  
								  
								  
																			when ((((DATA_Ticket.Price - DATA_Ticket.taxes) - max(ISNULL(rdata.TotalUsed, 0))) &amp;#62; 0) and 								        
																										((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																																				else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
																																		end )) - max(ISNULL(rdata.TotalUsed, 0)) &amp;#60;= ((DATA_Ticket.Price - DATA_Ticket.taxes) - max(ISNULL(rdata.TotalUsed, 0))))
																																																								
																			then 
																			((((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																																				else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
																																		end )))  -  ((((DATA_Ticket.Price - DATA_Ticket.taxes)/(case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																																				else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
																																		end )))  * (select sum(percentage)
																																					from coa_cnf_accountconfig AC WITH(NOLOCK)
																																					where AC.revenuerecognitionruleid = p.RevenueRecognitionRuleId
																																					and ac.accountingtype = p.accountingtype
																																					))/100)
																		else (DATA_Ticket.Price - DATA_Ticket.taxes) - max(rdata.TotalUsed)
																	end, 2)) as RevenueAmount,
													   p.Accountingtype,
													   max(p.RRCalcTypeTrigger) RRCalcTypeTrigger,
													   max(p.RRPercentage) RRPercentage,
													   max(p.days) days,
													   max(RR_DATA_REVENUE.AttributeIDs) AttributeIDs,
													   case when (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1) = 0 then 1
																else (DATEDIFF(dd, DATA_Ticket.ActiveFrom, DATA_Ticket.ActiveTo) + 1)
														end TimePeriod,
														MAX(RR_DATA_REVENUE.oobflag) oobflag

												from RR_DATA_REVENUE WITH(NOLOCK)
													INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.SaleItemId		   = rr_data_revenue.saleitemid
													INNER JOIN DATA_Sale WITH(NOLOCK)								on DATA_Sale.SaleId = DATA_SaleItem.saleid
													INNER JOIN DATA_Ticket WITH(NOLOCK)								on data_ticket.SaleItemId = data_saleitem.SaleItemId
													INNER JOIN (  
															select  RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid, 
															RR_CNF_RevenueRecognitionRule.Days,
															RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
															RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,
															FromDate,
															ToDate,
															RR_CNF_RevenueRecognitionRule.rrCalcTypeTrigger,
															RR_CNF_RevenueRecognitionRule.Percentage as RRPercentage,
															COA_CNF_AccountConfig.CoaAccountid,
															COA_CNF_AccountConfig.AccountingType,
															COA_CNF_AccountConfig.Price,
															COA_CNF_AccountConfig.Percentage,
															COA_CNF_AccountConfig.RemainingValues,
															COA_CNF_AccountConfig.SiteID,
															coa_cnf_account.code as AccountCode,
															COA_CNF_AccountType.Code as AccountTypeCode,
															COA_CNF_AccountType.COAAccountTypeId,
															Matrixcellid.MatrixcellID,
															COA_CNF_AccountConfig.COAAccountConfigId,
															RR_CNF_RevenueRecognitionRule.UsageTime

													from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
														inner join @Matrixcells	Matrixcellid						ON Matrixcellid.RevenueRecognitionRuleId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId		
														INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
														INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
														INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

													where COA_CNF_AccountConfig.RemainingValues = 1
													  and RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod = 5
													  and RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId in (select RRID 
																																	   from #RulesToRun)

													)p   ON (RR_DATA_REVENUE.MATRIXCELLID = p.MATRIXCELLID) 
													LEFT JOIN (select rr_data_revenue.ticketid, coaaccountid, AccountingType, sum(revenueamount) as TotalUsed
																	from rr_data_revenue WITH(NOLOCK)
																	inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
																	where rr_data_revenue.ticketid is not null
																	  and coaaccountid not in (@suspendid)
																	  and rrcalctypetrigger &amp;#60;&amp;#62; 1
																	  and rr_data_revenue.FCalcDate &amp;#60;= @BatchDate
																	group by rr_data_revenue.ticketid, AccountingType, coaaccountid
																	)rdata									ON rdata.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_saleitem.ticketid)	
																												and rdata.AccountingType = p.AccountingType 
																												 and p.COAAccountId = rdata.coaaccountid

													LEFT JOIN (select rr_data_revenue.ticketid, AccountingType, (DATA_TICKET.price - DATA_TICKET.taxes) - sum(revenueamount) as TotalLeft
																	from rr_data_revenue WITH(NOLOCK)
																	inner join DATA_TICKET WITH(NOLOCK) ON DATA_TICKET.TICKETID = RR_DATA_REVENUE.TICKETID
																	where rr_data_revenue.ticketid is not null
																	  and coaaccountid not in (@suspendid)
																	  and rrcalctypetrigger &amp;#60;&amp;#62; 1
																	  and rr_data_revenue.FCalcDate &amp;#60;= @BatchDate
																	group by rr_data_revenue.ticketid, AccountingType, (DATA_TICKET.price - DATA_TICKET.taxes)
																	)rdataLEFT									ON rdataLEFT.ticketid = ISNULL(RR_DATA_REVENUE.ticketid, data_saleitem.ticketid)	
																												and rdataLEFT.AccountingType = p.AccountingType 

													where RR_DATA_REVENUE.COAAccountId not in (1, 2, 3, 4)
														and p.RRCalcTypeTrigger = 4
														and (select ISNULL((select sum(ISNULL(revenueamount, 0))as TotalT
																from rr_data_revenue
																where rr_data_revenue.ticketid = DATA_Ticket.ticketid
																and RR_DATA_Revenue.RRCalcTypeTrigger = 1
																and accountingtype = 2
																and COAAccountId not in (1, 2, 3, 4)
																and SaleItemTaxId is null
																and SaleItemRuleID is null), 0)) &amp;#62; 0
														and p.RRCalcTypeMethod in (5)
														and @BatchDate between DATA_Ticket.ActiveFrom and dateadd(dd, 2, DATA_Ticket.ActiveTo)
														and @BatchDate &amp;#62;= case when p.UsageTime = 0 then @BatchDate
																				else data_ticket.activeFrom
																			END
														and DATA_Ticket.VoidType not in (104, 125)
														and (data_ticket.VoidType &amp;#60;= 99) or 
																	((data_ticket.VoidType in (109, 102, 125)) and
																	(select top 1  DATA_Transaction.FTransactionDate
																		from data_transaction2ticket WITH(NOLOCK)
																			INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Transaction2Ticket.TransactionId
																																			and DATA_Transaction.TransactionType in (18, 20, 22)
																		where data_transaction2ticket.TicketId = data_ticket.ticketid
																	) &amp;#62; @batchdate

																)
													group by ISNULL(rdata.Ticketid, data_ticket.Ticketid),
															 RR_DATA_REVENUE.Saleitemid,
															 p.RemainingValues,
															 DATA_Ticket.ActiveFrom,
															 DATA_Ticket.ActiveTo,
															 p.RevenueRecognitionRuleid,
															 p.AccountingType,
															 DATA_Ticket.Price,
															 DATA_Ticket.taxes
													)r
													where Round(RevenueAmount, 12) &amp;#60;&amp;#62; 0  
							end
			end
	END
END</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>C0C3E2B609CF43BF91359551F915096F</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_OnUpgradeTrigger</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>67</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnUpgradeTrigger]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer

	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1
	Declare @TicketUsageTrigger Integer = 2
	Declare @OnTimePeriodTrigger Integer = 4
	Declare @DepositTrigger int = 5
	Declare @OnEventTrigger Integer = 17
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	--Declare @MatrixcellsUV1 table (Matrixcells Integer)
	--Declare @MatrixcellsUV2 table (Matrixcells Integer)
	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnSaleTrigger

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnSaleTrigger

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1
				  and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = @OnSaleTrigger

		)p

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1


	  select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

 BEGIN
----Upgrades moving all money to Suspense to new account 
INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[TransactionId]
				,[SaleId]
				,[Ticketid]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
				select SusCoaId,
				RRRID,
				RRWhere,
				RRMethod,
				ConfigID,
				CoaTypeID,
				transactionid, 
				saleid,
				ticketid,
				saleitemid,
				Matrixcellid,
				MatrixSheetid,
				Siteid,
				OperatingAreaId,
				Workstationid,
				UserGroupid,
				UserId,
				BatchDate,
				Quantity,
				UnitPrice,
				GrossAmount,
				NetAmount,
				SusPrice,
				SusPerc,
				0,
				ISNULL(ABS(RevenueAmount), 0),
				case when revenueamount &amp;#60; 0 then 1
				     else Accountingtype
				end Accountingtype,
				SusTrigger,
				SusPerc2,
				SusDays

				from (
				select distinct
							@SuspendCOAAccountId as SusCoaId,
							@SuspendRRRId as RRRID,
							@SuspendRRCalcTypeWhere as RRWhere,
							@SuspendRRCalcTypeMethod as RRMethod,
							@SuspendCOAAccountConfigId as ConfigID,
							@SuspendCOAAccountTypeId as CoaTypeID,
							data_transaction.transactionid, 
							data_transaction.saleid,
							data_ticket.ticketid,
							DATA_SaleItem.saleitemid as Saleitemid,
							DATA_SaleItem.Matrixcellid as Matrixcellid,
							CNF_MatrixCell.MatrixSheetid,
							data_transaction.Siteid,
							data_transaction.OperatingAreaId,
							data_transaction.Workstationid,
							data_transaction.UserGroupid,
							data_transaction.UserId,
							@BatchDate as BatchDate,
							1 as Quantity,
							ISNULL(DATA_SaleItem.UnitPrice, 0) as Unitprice,
							ISNULL(DATA_SaleItem.UnitPrice, 0) as GrossAmount,
							ISNULL((DATA_SaleItem.UnitPrice - DATA_SaleItem.UnitTaxes), 0)  as NetAmount,					
							@SuspendPrice as SusPrice,
							@SuspendCOAAccount_Percentage as SusPerc,
							@SuspendRemainingValues as SusRMV,
							ABS(ISNULL((case when data_saleitem.ProductType &amp;#60;&amp;#62; 1 and data_saleitem.quantity &amp;#62; 0
												then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
											when data_saleitem.ProductType &amp;#60;&amp;#62; 1 and data_saleitem.quantity &amp;#60; 0
												then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) + ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)
																																)
											
											when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType in (3, 4) and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitPrice))) 


										when (data_ticket.ticketid is not null) and producttaxtype in (3, 4) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2
							   										then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes)) + ABS(ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))

											when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2
							   										then ABS(((DATA_SaleItem.UnitrawPrice) - DATA_SaleItem.UnitTaxes)) 

											when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType = 2
							   										then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes))  - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																																			from data_saleitemrule WITH(NOLOCK)
																																				INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																				INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																				INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																			where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																				and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) 
							 
							 
											else ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																		from data_saleitemrule WITH(NOLOCK)
																			INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																			INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																			INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																		where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																			and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 


								end), 0)) as Revenueamount,
							case when data_saleitem.Quantity &amp;#60; 0 then 1
								 else 2					
							end Accountingtype,
							@SuspendRRCalcTypeTrigger as SusTrigger,
							@SuspendPercentage as SusPerc2,
							@SuspendDays as SusDays,
							case when DATA_SaleItem.ticketid  is not null then DATA_SaleItem.matrixcellid
								 else 
								 (select top 1 matrixcellid from data_saleitem SI where si.saleid = data_transaction.saleid and si.ticketid = DATA_SALEITEM.itemticketid)
							end as matrixcell
	   
			from data_transaction WITH(NOLOCK)
					Inner join data_sale WITH(NOLOCK)					on data_sale.saleid = data_transaction.saleid 
					left  join DATA_SaleItem	WITH(NOLOCK)		    on DATA_SaleItem.saleid = data_sale.saleid
					left  join data_saleitem2ticket WITH(NOLOCK)		on (data_saleitem2ticket.saleitemid = DATA_SaleItem.saleitemid) 
					left  join CNF_MatrixCell WITH(NOLOCK)				on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT  join CNF_MatrixSheet WITH(NOLOCK)				on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					LEFT  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid															
											where DATA_Ticket.VoidType not in (104, 125)
								)data_ticket		on data_ticket.saleitemid = data_saleitem.saleitemid 
															and data_ticket.OperationType in (1, 2, 11)
							
		where (((1 = case   when data_transaction.transactiontype in (7) and data_saleitem.itemtransactiontype in (7) then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (7) then 1				                
								else 0
						end) and (DATA_Sale.Encoded = 1))
						  or ((DATA_Sale.Encoded = 0) and (data_saleitem.ProductType not in (1)) and (data_transaction.saleid not in (select saleid from data_saleitem where producttype = 1))  
								and (1 = (case  when data_transaction.transactiontype in (7)  then 1
												when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (7) then 1				                
												else 0
											 end)
									)
						  
						  )												
						)
		    and DATA_Sale.Paid = 1
			and data_transaction.transactionstatus in (5, 30, 35)
			and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
			and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
			and ((data_transaction.transactiontype in (7)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7))))
			and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
			   OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
			and (data_transaction.transactionid in (select transactionid
													   from data_payment WITH(NOLOCK)
													  where PaymentStatus = 1
														and data_payment.transactionid = data_transaction.transactionid										
												     )
						or data_transaction.totalamount = 0
				   )
	)p
	where RevenueAmount &amp;#60;&amp;#62; 0

		
------Upgrades and Downgrades move to 
INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[TransactionId]
				,[SaleId]
				,[Ticketid]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
			select SusCoaId,
				RRRID,
				RRWhere,
				RRMethod,
				ConfigID,
				CoaTypeID,
				transactionid, 
				saleid,
				ticketid,
				saleitemid,
				Matrixcellid,
				MatrixSheetid,
				Siteid,
				OperatingAreaId,
				Workstationid,
				UserGroupid,
				UserId,
				BatchDate,
				Quantity,
				UnitPrice,
				GrossAmount,
				NetAmount,
				ConfigPrice,
				ConfigPercentage,
				RemainingValues,
				ISNULL(ABS(RevenueAmount), 0),
				Accountingtype,
				RRCalcTypeTrigger,
				percentage,
				Days

				from (
			select ISNULL(BackoutRec.COAAccountId, coa_cnf_account.coaaccountid)  as SusCoaId,
				RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId as RRRID,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere as RRWhere,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod as RRMethod,
				COA_CNF_AccountConfig.COAAccountConfigId as ConfigID,
				ISNULL(BackoutRec.COAAccountType, coa_cnf_account.COAAccountTypeId) as CoaTypeID,
				data_transaction.transactionid, 
				data_transaction.saleid,
				RR_DATA_REVENUE.ticketid,
				ISNULL(BackoutRec.saleitemid, rr_data_revenue.saleitemid) as Saleitemid,
				ISNULL(BackoutRec.Matrixcellid, rr_data_revenue.matrixcellid) as Matrixcellid,
				rr_data_revenue.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate as BatchDate,
				1 as Quantity,
				ISNULL(BackoutRec.netamount, rr_data_revenue.unitamount) as Unitprice,
				coalesce(BackoutRec.grossamount, rr_data_revenue.GrossAmount, 0) as GrossAmount,
				coalesce(BackoutRec.netamount, rr_data_revenue.netamount, 0 ) as NetAmount,
				COA_CNF_AccountConfig.Price as ConfigPrice,
				COA_CNF_AccountConfig.Percentage as ConfigPercentage,
				0 RemainingValues,																	
				abs(ISNULL(BackoutRec.RevenueAmount, 
				ISNULL((Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
									 else ISNULL(ABS((RR_DATA_REVENUE.RevenueAmount * COA_CNF_AccountConfig.percentage)/100), 0)
								end), 0))) RevenueAmount,
				RR_DATA_REVENUE.AccountingType,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			    RR_CNF_RevenueRecognitionRule.Percentage,
				RR_CNF_RevenueRecognitionRule.Days
			from RR_DATA_REVENUE WITH(NOLOCK)
				INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
				LEFT join (
						   select distinct Backout.COAAccountId,
								Backout.COAAccountType,
								T2.ticketid,
								DATA_SaleItem.saleitemid as Saleitemid,
								DATA_SaleItem.Matrixcellid as Matrixcellid,
								CNF_MatrixCell.MatrixSheetid,
								CNF_MatrixCell.Membership,
								OLD_CELL.MatrixSheetid as Old_Sheetid,
								Backout.netamount as Unitprice,
								Backout.grossamount as GrossAmount,
								Backout.netamount  as NetAmount,																	
								Backout.totalamount RevenueAmount,
								case when DATA_SaleItem.ticketid  is not null then DATA_SaleItem.matrixcellid
									 else (select top 1 matrixcellid from data_saleitem SI where si.saleid = data_transaction.saleid and si.ticketid = DATA_SALEITEM.itemticketid)
								end as matrixcell

											from data_transaction WITH(NOLOCK)
											left JOIN (select data_transaction2ticket.Transactionid,
																data_transaction2ticket.operationtype,
																data_Ticket.*
														from data_transaction2ticket WITH(NOLOCK)  
															left join data_ticket WITH(NOLOCK)              on data_ticket.ticketid = data_transaction2ticket.ticketid
														) T2			on T2.transactionid = data_transaction.transactionid  and T2.printdatetime is not null
											left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.ticketid = T2.ticketid and data_saleitem2ticket.operationtype = 1
											left join DATA_SaleItem	WITH(NOLOCK)		    on DATA_SaleItem.saleitemid = data_saleitem2ticket.saleitemid
											left join data_ticket OLD_SI WITH(NOLOCK)		on OLD_SI.ticketid = data_saleitem.ticketid
											LEFT JOIN cnf_matrixcell OLD_CELL WITH(NOLOCK)  on OLD_Cell.MatrixcellID = OLD_SI.matrixcellid
											left join data_sale WITH(NOLOCK)				on data_sale.saleid = data_transaction.saleid 
											left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
											left join (select COAACCOUNTID,
																	saleitemid,
																	COAAccountType,
																	Ticketid,
																	matrixcellid,
																	grossamount,
																	netamount,
																	SUM(debit) Debit,
																	sum(credit) credit,
																	ROUND(SUM(debit),2) - Round(sum(credit), 2) totalamount
										from (
										select  RR_DATA_Revenue.COAACCOUNTID,
																	DATA_SaleItem.saleitemid,
																	RR_DATA_Revenue.COAAccountType,
																	RR_DATA_Revenue.Ticketid,
																	RR_DATA_Revenue.matrixcellid,
																	RR_DATA_Revenue.grossamount,
																	RR_DATA_Revenue.netamount,
																	case when accountingtype = 1 then sum(revenueamount)
																			else 0
																		end debit,
																	case when accountingtype = 2 then sum(revenueamount)
																			else 0
																		end credit

															from data_ticket WITH(NOLOCK)
																INNER JOIN DATA_SaleItem WITH(NOLOCK)			on data_saleitem.saleitemid = data_ticket.saleitemid
																INNER JOIN RR_DATA_Revenue WITH(NOLOCK)			on rr_data_revenue.ticketid = ISNULL(DATA_SaleItem.ticketid, data_ticket.ticketid)  and data_saleitem.saleitemid = rr_data_revenue.saleitemid

															where RR_DATA_Revenue.coaaccountid not in (1, 2, 3, 4)
															  and RR_DATA_Revenue.RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
															group by   RR_DATA_Revenue.COAACCOUNTID,
																		RR_DATA_Revenue.Ticketid,
																		RR_DATA_Revenue.COAAccountType,
																		RR_DATA_Revenue.matrixcellid,
																		RR_DATA_Revenue.grossamount,
																		RR_DATA_Revenue.netamount,
																		DATA_SaleItem.saleitemid,
																		RR_DATA_Revenue.accountingtype

						)p

						Group by COAACCOUNTID,
																	saleitemid,
																	COAAccountType,
																	Ticketid,
																	matrixcellid,
																	grossamount,
																	netamount

						having ROUND(SUM(debit),2) - Round(sum(credit), 2) &amp;#60;&amp;#62; 0)  Backout				on Backout.Ticketid = T2.ticketid
																									


					where  DATA_Sale.Paid = 1
						and (((data_transaction.transactiontype in (7)) and (data_saleitem.ItemTransactionType in (7))) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7))))
						and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
							OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
						and  (data_transaction.transactionid in (select transactionid
																from data_payment WITH(NOLOCK)
																where PaymentStatus = 1	
																  and DATA_Payment.TransactionId = data_transaction.transactionid
																))
												)BackoutRec			on backoutrec.ticketid = rr_data_revenue.ticketid 

					inner join @Matrixcells	Matrixcellid						ON (ISNULL(Backoutrec.matrixcell, rr_data_revenue.matrixcellid) = Matrixcellid.MATRIXCELLID) 
					inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
					INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId 
																					and COA_CNF_AccountConfig.Enabled = 1																																			
					INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid					
					INNER JOIN DATA_SaleItem WITH(NOLOCK)						ON DATA_SaleItem.SaleItemId = ISNULL(BackoutRec.saleitemid, rr_data_revenue.saleitemid)

			where  coa_cnf_account.Enabled = 1
					and (data_transaction.transactiontype in (7))
					and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and RR_DATA_REVENUE.coaaccountid = @suspendid
					and ISNULL(RR_DATA_Revenue.RRDays, 0) = 0
					
			UNION ALL

			select ISNULL(BackoutRec.COAAccountId, coa_cnf_account.coaaccountid)  as SusCoaId,
				RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId as RRRID,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere as RRWhere,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod as RRMethod,
				COA_CNF_AccountConfig.COAAccountConfigId as ConfigID,
				ISNULL(BackoutRec.COAAccountType, coa_cnf_account.COAAccountTypeId) as CoaTypeID,
				data_transaction.transactionid, 
				data_transaction.saleid,
				RR_DATA_REVENUE.ticketid,
				ISNULL(BackoutRec.saleitemid, rr_data_revenue.saleitemid) as Saleitemid,
				ISNULL(BackoutRec.Matrixcellid, rr_data_revenue.matrixcellid) as Matrixcellid,
				rr_data_revenue.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate as BatchDate,
				1 as Quantity,
				ISNULL(BackoutRec.netamount, rr_data_revenue.unitamount) as Unitprice,
				coalesce(BackoutRec.grossamount, rr_data_revenue.GrossAmount, 0) as GrossAmount,
				coalesce(BackoutRec.netamount, rr_data_revenue.netamount, 0) as NetAmount,
				COA_CNF_AccountConfig.Price as ConfigPrice,
				COA_CNF_AccountConfig.Percentage as ConfigPercentage,
				0 RemainingValues,																	
				ISNULL(BackoutRec.RevenueAmount, 
				ISNULL((Case when COA_CNF_AccountConfig.Price &amp;#62; 0 then (COA_CNF_AccountConfig.Price * RR_DATA_REVENUE.Quantity) 
									 else ISNULL(ABS((RR_DATA_REVENUE.RevenueAmount * COA_CNF_AccountConfig.percentage)/100), 0)
								end), 0)) RevenueAmount,
				RR_DATA_REVENUE.AccountingType,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			    RR_CNF_RevenueRecognitionRule.Percentage,
				RR_CNF_RevenueRecognitionRule.Days

			from RR_DATA_REVENUE WITH(NOLOCK)
				INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
				LEFT join (
				select distinct Backout.COAAccountId,
				Backout.COAAccountType,
				T2.ticketid,
				DATA_SaleItem.saleitemid as Saleitemid,
				DATA_SaleItem.Matrixcellid as Matrixcellid,
				CNF_MatrixCell.MatrixSheetid,
				CNF_MatrixCell.Membership,
				OLD_CELL.MatrixSheetid as Old_Sheetid,
				Backout.netamount as Unitprice,
				Backout.grossamount as GrossAmount,
				Backout.netamount  as NetAmount,																	
				Backout.totalamount RevenueAmount,
				case when DATA_SaleItem.ticketid  is not null then DATA_SaleItem.matrixcellid
				     else (select top 1 matrixcellid from data_saleitem SI where si.saleid = data_transaction.saleid and si.ticketid = DATA_SALEITEM.itemticketid)
				end as matrixcell

					from data_transaction WITH(NOLOCK)
						left JOIN (select data_transaction2ticket.Transactionid,
										  data_transaction2ticket.operationtype,
										  data_Ticket.*
									from data_transaction2ticket WITH(NOLOCK)  
									   left join data_ticket WITH(NOLOCK)              on data_ticket.ticketid = data_transaction2ticket.ticketid
								  ) T2			on T2.transactionid = data_transaction.transactionid  and T2.printdatetime is not null
					left join data_saleitem2ticket WITH(NOLOCK)		on data_saleitem2ticket.ticketid = T2.ticketid and data_saleitem2ticket.operationtype = 1
					left join DATA_SaleItem	WITH(NOLOCK)		    on DATA_SaleItem.saleitemid = data_saleitem2ticket.saleitemid
					left join data_ticket OLD_SI WITH(NOLOCK)		on OLD_SI.ticketid = data_saleitem.ticketid
					LEFT JOIN cnf_matrixcell OLD_CELL WITH(NOLOCK)  on OLD_Cell.MatrixcellID = OLD_SI.matrixcellid
					left join data_sale WITH(NOLOCK)				on data_sale.saleid = data_transaction.saleid 
					left join CNF_MatrixCell WITH(NOLOCK)			on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left join (select   coaaccountid,
									   saleitemid,
									   ticketid,
									   matrixcellid,
									   COAAccountType,
									   min(grossamount) as grossamount,
									   sum(credit) credit,
									   sum(debit) debit,
									   min(netamount) netamount,
									   sum(credit) - sum(debit) as totalamount
									from (
									select  RR_DATA_Revenue.COAACCOUNTID,
											DATA_SaleItem.saleitemid,
											RR_DATA_Revenue.COAAccountType,
											RR_DATA_Revenue.Ticketid,
											RR_DATA_Revenue.matrixcellid,
											RR_DATA_Revenue.grossamount,
											RR_DATA_Revenue.netamount,
											case when accountingtype = 1 then sum(revenueamount)
													else 0
												end debit,
											case when accountingtype = 2 then sum(revenueamount)
													else 0
												end credit

									from data_ticket WITH(NOLOCK)
										INNER JOIN DATA_SaleItem WITH(NOLOCK)			on data_saleitem.saleitemid = data_ticket.saleitemid
										INNER JOIN RR_DATA_Revenue WITH(NOLOCK)			on rr_data_revenue.ticketid = ISNULL(DATA_SaleItem.ticketid, data_ticket.ticketid)  and data_saleitem.saleitemid = rr_data_revenue.saleitemid

									where RR_DATA_Revenue.coaaccountid not in (1, 2, 3, 4)
									  and RR_DATA_Revenue.RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
									group by   RR_DATA_Revenue.COAACCOUNTID,
												RR_DATA_Revenue.Ticketid,
												RR_DATA_Revenue.COAAccountType,
												RR_DATA_Revenue.matrixcellid,
												RR_DATA_Revenue.grossamount,
												RR_DATA_Revenue.netamount,
												DATA_SaleItem.saleitemid,
												RR_DATA_Revenue.accountingtype
									)Backout1
									group by coaaccountid,
											saleitemid,
											ticketid,
											COAAccountType,
											matrixcellid

									having sum(credit) - sum(debit) &amp;#60;&amp;#62; 0)  Backout				on Backout.Ticketid = T2.ticketid


			where  DATA_Sale.Paid = 1
				and (((data_transaction.transactiontype in (7)) and (data_saleitem.ItemTransactionType in (7))) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7))))
				and ((@RRTransDateType = 0 and convert(date, data_transaction.fTransactionDate) = @BatchDate)
					OR (@RRTransDateType = 1 and convert(date, data_transaction.TransactionDate) = @BatchDate))
				and  (data_transaction.transactionid in (select transactionid
														from data_payment WITH(NOLOCK)
														where PaymentStatus = 1	
														  and DATA_Payment.TransactionId = data_transaction.transactionid
														))
												)BackoutRec			on backoutrec.ticketid = rr_data_revenue.ticketid 

					inner join @Matrixcells	Matrixcellid						ON (ISNULL(Backoutrec.matrixcell, rr_data_revenue.matrixcellid) = Matrixcellid.MATRIXCELLID) 
					inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
					INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
					INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid					
					INNER JOIN DATA_SaleItem WITH(NOLOCK)						ON DATA_SaleItem.SaleItemId = ISNULL(BackoutRec.saleitemid, rr_data_revenue.saleitemid)

			where  coa_cnf_account.Enabled = 1
					and  ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7)))
					and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					and COA_CNF_AccountConfig.RemainingValues &amp;#60;&amp;#62; 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and RR_DATA_REVENUE.coaaccountid = @suspendid
					and ISNULL(RR_DATA_Revenue.RRDays, 0) = 0
)r
		
INSERT INTO [dbo].[RR_DATA_Revenue]
				([COAAccountId]
				,[RevenueRecognitionRuleId]
				,[RRCalcTypeWhere]
				,[RRCalcTypeMethod]
				,[COAAccountConfigId]
				,[COAAccountType]
				,[TransactionId]
				,[SaleId]
				,[Ticketid]
				,[SaleItemId]
				,[MatrixCellId]
				,[MatrixSheetID]
				,[SiteId]
				,[OperatingAreaId]
				,[WorkstationId]
				,[UserGroupId]
				,[UserId]
				,[FCalcDate]
				,[Quantity]
				,[UnitAmount]
				,[GrossAmount]
				,[NetAmount]
				,[Price]
				,[Percentage]
				,[RemaningValues]
				,[RevenueAmount]
				,[AccountingType]
				,[RRCalcTypeTrigger]
				,[RRPercentage]
				,[RRDays])
			select SusCoaId,
				RRRID,
				RRWhere,
				RRMethod,
				ConfigID,
				CoaTypeID,
				transactionid, 
				saleid,
				ticketid,
				saleitemid,
				Matrixcellid,
				MatrixSheetid,
				Siteid,
				OperatingAreaId,
				Workstationid,
				UserGroupid,
				UserId,
				BatchDate,
				Quantity,
				UnitPrice,
				GrossAmount,
				NetAmount,
				ConfigPrice,
				ConfigPercentage,
				RemainingValues,
				ISNULL(ABS(RevenueAmount), 0),
				case when revenueamount &amp;#60; 0 then 1
				     else Accountingtype
				end Accountingtype,
				RRCalcTypeTrigger,
				percentage,
				Days

				from (
			select coa_cnf_account.coaaccountid  as SusCoaId,
				RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId as RRRID,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere as RRWhere,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod as RRMethod,
				COA_CNF_AccountConfig.COAAccountConfigId as ConfigID,
				coa_cnf_account.COAAccountTypeId as CoaTypeID,
				data_transaction.transactionid, 
				data_transaction.saleid,
				RR_DATA_REVENUE.ticketid,
				rr_data_revenue.saleitemid as Saleitemid,
				rr_data_revenue.matrixcellid as Matrixcellid,
				rr_data_revenue.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate as BatchDate,
				1 as Quantity,
				rr_data_revenue.unitamount as Unitprice,
				ISNULL(rr_data_revenue.GrossAmount, 0) as GrossAmount,
				ISNULL(rr_data_revenue.netamount, 0) as NetAmount,
				COA_CNF_AccountConfig.Price as ConfigPrice,
				COA_CNF_AccountConfig.Percentage as ConfigPercentage,
				COA_CNF_AccountConfig.RemainingValues,																	

				rr_data_revenue.netamount + ISNULL((select SUM(discountamount)
				                               from DATA_SaleItemRule WITH(NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
												where DATA_SaleItemRule.SaleItemId = RR_DATA_Revenue.saleitemid
												--  and ISNULL(coanodiscount, 0) = 0
											), 0)
				
								-
								ISNULL((select SUM(RR)		
								from(
								select SUM(revenueamount) RR
											from RR_DATA_Revenue RR WITH(NOLOCK)
												where RR.TransactionId = RR_DATA_REVENUE.TransactionId
													and RR.ticketid = rr_data_revenue.ticketid
													and RR.COAAccountId not in (1, 2, 3, 4)
													and RR.RemaningValues = 0 
													and rr.fcalcdate = rr_data_revenue.fcalcdate
													and isnull(oobflag, 0) = 0
													and RR.AccountingType = RR_DATA_Revenue.AccountingType
													and RR.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null)
													and RR.COAAccountId not in (select COAAccountId from CNF_Promotion where COAAccountId is not null)					
											
								  )p
								  
								  
								  
								  ), 0)
				
				RevenueAmount,
				RR_DATA_REVENUE.AccountingType,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			    RR_CNF_RevenueRecognitionRule.Percentage,
				RR_CNF_RevenueRecognitionRule.Days

			from RR_DATA_REVENUE WITH(NOLOCK)
					inner join DATA_SaleItem WITH(NOLOCK)						ON DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid
					inner join @Matrixcells	Matrixcellid						ON (ISNULL(DATA_SaleItem.matrixcellID, rr_data_revenue.matrixcellid) = Matrixcellid.MATRIXCELLID) 
					inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
					INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
					INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid					
					left JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid


			where  RR_CNF_RevenueRecognitionRule.Enabled = 1
					and coa_cnf_account.Enabled = 1
					and COA_CNF_AccountConfig.Enabled = 1
					and ((data_transaction.transactiontype in (7)) and (data_saleitem.ItemTransactionType in (7)))
					and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					and COA_CNF_AccountConfig.RemainingValues = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and RR_DATA_REVENUE.coaaccountid = @suspendid

			union all

			select coa_cnf_account.coaaccountid  as SusCoaId,
				RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId as RRRID,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere as RRWhere,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod as RRMethod,
				COA_CNF_AccountConfig.COAAccountConfigId as ConfigID,
				coa_cnf_account.COAAccountTypeId as CoaTypeID,
				data_transaction.transactionid, 
				data_transaction.saleid,
				RR_DATA_REVENUE.ticketid,
				rr_data_revenue.saleitemid as Saleitemid,
				rr_data_revenue.matrixcellid as Matrixcellid,
				rr_data_revenue.MatrixSheetid,
				data_transaction.Siteid,
				data_transaction.OperatingAreaId,
				data_transaction.Workstationid,
				data_transaction.UserGroupid,
				data_transaction.UserId,
				@BatchDate as BatchDate,
				1 as Quantity,
				rr_data_revenue.unitamount as Unitprice,
				ISNULL(rr_data_revenue.GrossAmount, 0) as GrossAmount,
				ISNULL(rr_data_revenue.netamount, 0) as NetAmount,
				COA_CNF_AccountConfig.Price as ConfigPrice,
				COA_CNF_AccountConfig.Percentage as ConfigPercentage,
				COA_CNF_AccountConfig.RemainingValues,																	

				rr_data_revenue.netamount + ISNULL((select SUM(discountamount)
				                               from DATA_SaleItemRule WITH(NOLOCK)
													LEFT JOIN dbo.CNF_PromotionItemRule WITH (NOLOCK) ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
													LEFT JOIN dbo.CNF_PromotionItem		WITH (NOLOCK) ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
													LEFT JOIN dbo.CNF_Promotion			WITH (NOLOCK) ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
												where DATA_SaleItemRule.SaleItemId = RR_DATA_Revenue.saleitemid
												--  and ISNULL(coanodiscount, 0) = 0
											), 0)
				
								-
								(select SUM(RR)		
								from(
								select SUM(revenueamount) RR
											from RR_DATA_Revenue RR WITH(NOLOCK)
												where RR.TransactionId = RR_DATA_REVENUE.TransactionId
													and RR.SaleItemId = data_saleitem.OrigSaleItemId
													and RR.COAAccountId not in (1, 2, 3, 4)
													and RR.RemaningValues = 0 
													and rr.fcalcdate = rr_data_revenue.fcalcdate
													and isnull(oobflag, 0) = 0
													and RR.AccountingType = RR_DATA_Revenue.AccountingType
													and RR.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null)
													and RR.COAAccountId not in (select COAAccountId from CNF_Promotion where COAAccountId is not null)					
											union all	  
										select SUM(revenueamount)
											from RR_DATA_Revenue RR WITH(NOLOCK)
												where RR.TransactionId = RR_DATA_REVENUE.TransactionId
													and RR.SaleItemId = rr_data_revenue.saleitemid
													and RR.COAAccountId not in (1, 2, 3, 4)
													and RR.RemaningValues = 0
													and rr.fcalcdate = rr_data_revenue.fcalcdate
													and isnull(oobflag, 0) = 0
													and RR.AccountingType = RR_DATA_Revenue.AccountingType
													and RR.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null)
													and RR.COAAccountId not in (select COAAccountId from CNF_Promotion where COAAccountId is not null)		  
								  
								  )p
								  
								  
								  
								  )
				
				RevenueAmount,
				RR_DATA_REVENUE.AccountingType,
				RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			    RR_CNF_RevenueRecognitionRule.Percentage,
				RR_CNF_RevenueRecognitionRule.Days

			from RR_DATA_REVENUE WITH(NOLOCK)
					inner join DATA_SaleItem WITH(NOLOCK)						ON DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid
					inner join @Matrixcells	Matrixcellid						ON (ISNULL(DATA_SaleItem.matrixcellID, rr_data_revenue.matrixcellid) = Matrixcellid.MATRIXCELLID) 
					inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
					INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
					INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid					
					left JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid


			where  RR_CNF_RevenueRecognitionRule.Enabled = 1
					and coa_cnf_account.Enabled = 1
					and COA_CNF_AccountConfig.Enabled = 1
					and ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (7)))
					and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
					and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
					and COA_CNF_AccountConfig.RemainingValues = 1
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and RR_DATA_REVENUE.coaaccountid = @suspendid
				
)r



----------Reservation Delete when there is only a deposit on the books
	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		  from(
							select distinct r.COAAccountId, 
								   r.RevenueRecognitionRuleId,
								   r.RRCalcTypeWhere,
								   r.RRCalcTypeMethod,	   
								   r.COAAccountConfigId,
								   r.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								ISNULL(RR_DATA_REVENUE.GrossAmount, 0) as GrossAmount,
								 ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								   r.ConfigPrice,
								   r.AcctPerc,
								   r.RemainingValues,								
									ISNULL(Case when r.ConfigPrice &amp;#62; 0 then (r.ConfigPrice * RR_DATA_REVENUE.Quantity) 
											else ISNULL(ABS((RR_DATA_REVENUE.RevenueAmount * r.AcctPerc)/100), 0)
									end, 0) 																		                                                                                                                                                                                              
									as RevenueAmount,

								   case when r.Accountingtype = 1 then 2
								        when  r.Accountingtype = 2 then 1									
									end Accountingtype,
								   r.RRCalcTypeTrigger,
								   r.Percentage,
								   r.Days,
								   RR_DATA_Revenue.AttributeIDs
		   
				  from RR_DATA_REVENUE WITH(NOLOCK)
									INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
									INNER JOIN data_sale WITH(NOLOCK)							on data_sale.saleid = data_transaction.saleid
									CROSS APPLY  (
												select coa_cnf_account.COAAccountId, 
																				   RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
																				   RR_CNF_RevenueRecognitionRule.code,		   
																				   RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
																				   RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
																				   COA_CNF_AccountConfig.COAAccountConfigId,
																				   coa_cnf_account.COAAccountTypeId,
																				   coa_cnf_account.Code as AccountCode,								 
																				   @BatchDate as BatchDate,						 							
																				   COA_CNF_AccountConfig.Accountingtype,
																				   RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
																				   RR_CNF_RevenueRecognitionRule.Percentage,
																				   RR_CNF_RevenueRecognitionRule.Days,
																				   COA_CNF_AccountConfig.Price ConfigPrice,
																				   COA_CNF_AccountConfig.Percentage AcctPerc,
																				   COA_CNF_AccountConfig.RemainingValues
												from RR_CNF_RevenueRecognitionRule WITH(NOLOCK)
													INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)				on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId and COA_CNF_AccountConfig.Enabled = 1
													INNER JOIN coa_cnf_account	 WITH(NOLOCK)					on coa_cnf_account.coaaccountid = COA_CNF_AccountConfig.coaaccountid
													INNER JOIN COA_CNF_AccountType WITH(NOLOCK)					on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 

												where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@DepositTrigger)
													and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
													and RR_CNF_RevenueRecognitionRule.Enabled = 1
													and coa_cnf_account.Enabled = 1
													and COA_CNF_AccountConfig.Enabled = 1
									)r
							where  data_sale.paidtransactionid is null
							  and TransactionType in (5)
							  and rr_data_revenue.fcalcdate = @Batchdate
							  and RR_DATA_REVENUE.coaaccountid = @ACCPaymentMethod
							  and data_sale.saleid  in (select saleid from data_transaction DT where dt.transactiontype in (12, 15) and dt.saleid = data_sale.saleid)

					)p
					where RevenueAmount &amp;#60;&amp;#62; 0

	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs]
						,[JournalEntryByAccount])
		select *
		  from(
				select distinct 	 coalesce(Saleitems.COAAccountId, Tickets.COAAccountId, (select max(COAAccountId)
												from COA_CNF_Accountconfig WITH(NOLOCK)
													inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid = coa_cnf_accountconfig.RevenueRecognitionRuleId
														   where COA_CNF_Accountconfig.RevenueRecognitionRuleId in (select RevenueRecognitionRuleId from @Matrixcells MC where mc.matrixcellid = rr_data_revenue.matrixcellid)
															 and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 1
															 and RR_CNF_RevenueRecognitionRule.Enabled = 1
															 and COA_CNF_Accountconfig.AccountingType = 2))  COAAccountId,
									coalesce(Saleitems.RevenueRecognitionRuleId, (select max(RevenueRecognitionRuleId) from rr_data_revenue RR WITH(NOLOCK) where rr.ticketid = rr_data_revenue.ticketid and rr.rrcalctypetrigger = 1 having  max(RevenueRecognitionRuleId) &amp;#60;&amp;#62; 1), (select max(COA_CNF_Accountconfig.RevenueRecognitionRuleId)
												from COA_CNF_Accountconfig WITH(NOLOCK)
													inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid = coa_cnf_accountconfig.RevenueRecognitionRuleId
														   where COA_CNF_Accountconfig.RevenueRecognitionRuleId in (select RevenueRecognitionRuleId from @Matrixcells MC where mc.matrixcellid = rr_data_revenue.matrixcellid)
															 and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 1
															 and RR_CNF_RevenueRecognitionRule.Enabled = 1
															 and COA_CNF_Accountconfig.AccountingType = 2)) RevenueRecognitionRuleId,
								RR_DATA_REVENUE.RRCalcTypeWhere,
								RR_DATA_REVENUE.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								RR_DATA_REVENUE.COAAccountType,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.Ticketid,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								0 Remaining,	
								ISNULL(case when Tickets.ticketid is not null then 
											case when ABS(Tickets.REvenueAmount) &amp;#62; RR_DATA_Revenue.RevenueAmount then RR_DATA_Revenue.RevenueAmount
											     else ABS(Tickets.REvenueAmount)

											  end 
								     else ABS(Saleitems.RevenueAmount)
								 end, RR_DATA_Revenue.RevenueAmount) RevenueAmount,
								case when Saleitems.Accountingtype = 1 then 2
								     else case when data_saleitem.quantity &amp;#62; 0 then 2 else 1 end
								end Accountingtype,
								RR_DATA_REVENUE.RRCalcTypeTrigger,
								RR_DATA_REVENUE.Percentage,
								0 Days,
								RR_DATA_Revenue.AttributeIDs,
								0 journal
		
				  from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_saleitem	WITH(NOLOCK)					on data_saleitem.saleitemid = rr_data_revenue.saleitemid
						LEFT  JOIN (select saleitemid, revenuerecognitionruleid, coaaccountid, Accountingtype, sum(revenueamount) REvenueAmount
										 from rr_data_revenue WITH(NOLOCK)
										where coaaccountid not in (1, 2, 3, 4)
										  and SaleItemTaxId is null
										  and saleitemruleid is null
										  and PaymentId is null
										  and RRCalcTypeTrigger NOT IN (2, 3, 4, 17)
										  and ticketid is null
										  and COAAccountId not in (209)
										group by saleitemid, revenuerecognitionruleid, coaaccountid, Accountingtype) Saleitems				on Saleitems.saleitemid = data_saleitem.OrigSaleItemId
						LEFT  JOIN (select *, (debit - credit) Revenueamount
						              from (select TicketID, coaaccountid,  round(sum(case when accountingtype = 1 then revenueamount else 0 end), 2) debit,  round(sum(case when accountingtype = 2 then revenueamount else 0 end), 2) credit
											 from rr_data_revenue WITH(NOLOCK)
											where coaaccountid not in (1, 2, 3, 4)
											  and SaleItemTaxId is null
											  and saleitemruleid is null
											  and PaymentId is null										 										  
											  and COAAccountId not in (209)
											  and isnull(oobflag, 0) = 0
											  and ticketid in (select ticketid
																 from RR_DATA_Revenue RR WITH(NOLOCK)
																 where rr.ticketid = RR_DATA_Revenue.ticketid
																   and  coaaccountid not in (1, 2, 3, 4)
																   and SaleItemTaxId is null
																   and saleitemruleid is null
																   and PaymentId is null
																 group by ticketid
																 having round(sum(case when accountingtype = 1 then revenueamount else 0 end), 2) &amp;#60;&amp;#62; round(sum(case when accountingtype = 2 then revenueamount else 0 end), 2)
															   )
															  group by TicketID, coaaccountid

															  having round(sum(case when accountingtype = 1 then revenueamount else 0 end), 2) &amp;#60;&amp;#62; round(sum(case when accountingtype = 2 then revenueamount else 0 end), 2))p) Tickets			on Tickets.TicketID = RR_DATA_REVENUE.TicketID



				 where (data_transaction.transactiontype in (5, 30))
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid 
				  -- and RR_DATA_REVENUE.Quantity &amp;#60; 0
			)p
			where RevenueAmount &amp;#60;&amp;#62; 0
			and coaaccountid is not null
			and RevenueRecognitionRuleId is not null

end

END



</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>C6130C8A74E24B5AB16A8DE4E91380E0</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_OnUpgradeTrigger_Refund</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>28</Version><SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnUpgradeTrigger_Refund]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1
	Declare @TicketUsageTrigger Integer = 2
	Declare @OnTimePeriodTrigger Integer = 4
	Declare @OnEventTrigger Integer = 17
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @MatrixcellsUV1 table (Matrixcells Integer)
	Declare @MatrixcellsUV2 table (Matrixcells Integer)
	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1

		)p

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	  select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	 insert into @MatrixcellsUV1
					 select cells
						from (
						select isnull(cnf_matrixcell.matrixcellid, mc.matrixcellid) as cells
						from rr_cnf_product
							left join cnf_matrixcell			on cnf_matrixcell.matrixcellid = rr_cnf_product.matrixcellid
							left join cnf_matrixcell MC			on mc.matrixsheetid = rr_cnf_product.matrixsheetid
						where revenuerecognitionruleid in (
															select revenuerecognitionruleid 
															from RR_CNF_RevenueRecognitionRule
															where enabled = 1
															  and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
															  and RRCalcTypeTrigger = 1
															  and RR_CNF_RevenueRecognitionRule.upgradetype = 0
															  )
						)r
						where cells is not null

	insert into @MatrixcellsUV2
					 select cells
						from (
						select isnull(cnf_matrixcell.matrixcellid, mc.matrixcellid) as cells
						from rr_cnf_product
							left join cnf_matrixcell			on cnf_matrixcell.matrixcellid = rr_cnf_product.matrixcellid
							left join cnf_matrixcell MC			on mc.matrixsheetid = rr_cnf_product.matrixsheetid
						where revenuerecognitionruleid in (
															select revenuerecognitionruleid 
															from RR_CNF_RevenueRecognitionRule
															where enabled = 1
															  and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
															  and RRCalcTypeTrigger = 1
															  and RR_CNF_RevenueRecognitionRule.upgradetype = 1
															  )
						)r
						where cells is not null


	BEGIN


	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		  from(
			select distinct			coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								null Ticketid,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								null RemainingValues,								
								sum(Reverses.Revenueamount) 												                                                                                                                                                                                              
								as RevenueAmount,
								1 Accountingtype,
								1 RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs
		



				  from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  												 
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid					
						INNER JOIN data_saleitem WITH(NOLOCK)						ON data_saleitem.saleid = DATA_Transaction.saleid
																						and RR_DATA_REVENUE.SaleItemId = DATA_SaleItem.saleitemid
						INNER JOIN data_saleitem TSaleitemid WITH(NOLOCK)			ON TSaleitemid.SaleItemId = data_saleitem.Origsaleitemid
						Inner JOIN (select RR_DATA_Revenue.COAAccountId,
										   RR_DATA_Revenue.SaleItemId,
										   sum(RevenueAmount/DATA_SaleItem.quantity) RevenueAmount
										   
													  from RR_DATA_Revenue WITH(NOLOCK)
													  inner join DATA_SaleItem				on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid
													where RRCalcTypeTrigger in (1)
													  and AccountingType = 2
													  and RR_DATA_Revenue.COAAccountId not in (1, 2, 3, 4)
													  and RR_DATA_Revenue.SaleItemRuleID is null
													  and RR_DATA_Revenue.SaleItemTaxId is null
													  Group by  RR_DATA_Revenue.COAAccountId,
																RR_DATA_Revenue.SaleItemId
											
													 
											) Reverses			ON   (Reverses.SaleItemId = (select case when SI1.SaleItemId &amp;#62; 
																																				   (select min(SaleItemId)
																																					  from DATA_SaleItem SI WITH(NOLOCK)
																																					 where SI.SaleId = DATA_SaleItem.BaseSaleId
																																					   and SI.MatrixCellId = DATA_SaleItem.MatrixCellId
																																				   )  then (select min(SaleItemId)
																																					  from DATA_SaleItem SI WITH(NOLOCK)
																																					 where SI.SaleId = DATA_SaleItem.BaseSaleId
																																					   and SI.MatrixCellId = DATA_SaleItem.MatrixCellId
																																				   )
																																				   else SI1.SaleItemId
																																				  end 
																																			from data_saleitem SI1
																																			where saleitemid = DATA_SaleItem.saleitemid))

						INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = Reverses.coaaccountid
						INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId


				 where  RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and coa_cnf_account.Enabled = 1
				   and (data_transaction.transactiontype in (18, 20, 22)) 
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid
				   and TSaleitemid.Saleitemid not In ( select SaleitemID
				                                          from data_saleitem2ticket WITH(NOLOCK)
														 where data_saleitem2ticket.SaleitemID = TSaleitemid.Saleitemid
														)


					Group by coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid,
								RR_DATA_REVENUE.OperatingAreaId,
								RR_DATA_REVENUE.Workstationid,
								RR_DATA_REVENUE.UserGroupid,
								RR_DATA_REVENUE.UserId,
								RR_DATA_REVENUE.Quantity,
								data_transaction.transactiontype,
								RR_DATA_REVENUE.GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0),
								RR_DATA_REVENUE.Price,
								RR_DATA_REVENUE.Percentage,								
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs

			)p
			where RevenueAmount &amp;#60;&amp;#62; 0

	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		from(
				select distinct Reverses.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,							   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								0 RemainingValues,
								case when data_transaction.transactiontype = 18 then SUM(RR_DATA_REVENUE.revenueamount)
								     else (Reverses.RevenueAmount) 
								end RevenueAmount,
								1 Accountingtype,

								1 RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs

				from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	as Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_Sale WITH(NOLOCK)							on DATA_Sale.saleid = rr_data_revenue.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleitemid = RR_DATA_REVENUE.SaleItemId
						INNER JOIN (select COAAccountId,
										   SaleItemId,
										   TicketId,
										   (debit) RevenueAmount
															from (
									select COAAccountId,
										   SaleItemId,
										   TicketId,
										   SUM(debit) debit,
										   SUM(credit) credit

										   from (

								select COAAccountId,
										   SaleItemId,
										   TicketId,
										   1 rev,
										   sum(case when accountingtype = 1 then RevenueAmount end) debit,
										    sum(case when accountingtype = 2 then RevenueAmount end) credit
									  from RR_DATA_Revenue WITH(NOLOCK)

									where RRCalcTypeTrigger in (2, 3, 4, 17)
									 group by COAAccountId,
										      SaleItemId,
										      TicketId
								     UNION ALL
									 
									  select COAAccountId,
											RR_DATA_Revenue.SaleItemId,
											RR_DATA_Revenue.TicketId,
											case when max(RR_DATA_Revenue.netamount) &amp;#60;&amp;#62; 0 then max(RR_DATA_Revenue.netamount)-	sum(RevenueAmount)
											     else max(DATA_SaleItem.unitprice - DATA_SaleItem.unittaxes) -	sum(RevenueAmount)
											 end RevenueAmount,
											 sum(case when accountingtype = 1 then RevenueAmount end) debit,
										    sum(case when accountingtype = 2 then RevenueAmount end) credit

										from RR_DATA_Revenue WITH(NOLOCK)
										  inner join DATA_SaleItem WITH(NOLOCK)			on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid
									where RRCalcTypeTrigger in (4)		    
										and AccountingType = 1
										and RR_DATA_Revenue.SaleItemId in (select RR.SaleItemId
															 from RR_DATA_Revenue RR WITH(NOLOCK)

														where RR.RRCalcTypeTrigger in (4)
															and RR.AccountingType = 2
															and RR.SaleItemId = RR_DATA_Revenue.SaleitemID
														group by RR.COAAccountId,
																 RR.SaleItemId,
																 RR.TicketId
														 )
														group by COAAccountId,
																RR_DATA_Revenue.SaleItemId,
																RR_DATA_Revenue.TicketId

											)p

											group by COAAccountId,
																	SaleItemId,
																	TicketId
											Having ISNULL(SUM(debit), 0) - ISNULL(SUM(credit), 0) &amp;#60;&amp;#62; 0

											)p1
											where Credit is null)Reverses						ON (Reverses.TicketId = RR_DATA_Revenue.Ticketid)

						INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = Reverses.coaaccountid
						INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 


				 where RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and coa_cnf_account.Enabled = 1
				   and data_transaction.transactiontype in (18, 20, 22)
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (1)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid
				   and RR_DATA_REVENUE.Ticketid In (select Ticketid
				                                          from RR_DATA_Revenue RR WITH(NOLOCK)
														 where RR.Ticketid = RR_DATA_REVENUE.TicketID
														   and RR.RRCalcTypeTrigger in (2, 3, 4, 17)
														   and RR.FCalcDate &amp;#60;= @BatchDate
														)


				   Group by Reverses.COAAccountId, (Reverses.RevenueAmount),
				                data_transaction.transactiontype,
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,							   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid ,
								RR_DATA_REVENUE.OperatingAreaId ,
								RR_DATA_REVENUE.Workstationid ,
								RR_DATA_REVENUE.UserGroupid ,
								RR_DATA_REVENUE.UserId ,
								RR_DATA_REVENUE.Quantity ,
								RR_DATA_REVENUE.GrossAmount ,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0),
								RR_DATA_REVENUE.Price ,
								RR_DATA_REVENUE.Percentage ,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs
				
		 )p
		 where RevenueAmount &amp;#60;&amp;#62; 0

--Void Been used
	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		  from(
				select distinct coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.TicketID, 
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								null RemainingValues,								
								sum(coalesce(Reverses.revenueamount, Reverses2.Revenueamount, 0))	RevenueAmount,
								1 Accountingtype,
								1 RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs

				from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  						 
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT JOIN data_ticket WITH(NOLOCK)							ON data_ticket.ticketid = RR_DATA_REVENUE.ticketid
						LEFT JOIN data_saleitem WITH(NOLOCK)						ON data_saleitem.SaleItemId = RR_DATA_Revenue.saleitemid
						LEFT JOIN (select SI.SaleItemId BASESaleitemid,
						                  data_saleitem.BaseSaleId,
										  data_saleitem.Matrixcellid,
										  DATA_Ticket.TicketId,
										  sum(RevenueAmount) RevenueAmount
						             from DATA_SaleItem WITH(NOLOCK)
										inner join DATA_SaleItem SI WITH(NOLOCK)	ON SI.saleid = DATA_SaleItem.BaseSaleId
																							and SI.MatrixCellId = DATA_SaleItem.MatrixCellId
										inner join RR_DATA_Revenue WITH(NOLOCK)		on RR_DATA_Revenue.SaleItemId = SI.SaleItemId
										inner join DATA_Ticket WITH(NOLOCK)			on DATA_Ticket.SaleItemId = SI.saleitemid
									group by SI.SaleItemId,
						                  data_saleitem.BaseSaleId,
										  data_saleitem.Matrixcellid,
										  DATA_Ticket.TicketId
									)BaseSaleitemid									ON basesaleitemid.BaseSaleId = data_saleitem.basesaleid
																						and basesaleitemid.Matrixcellid = DATA_SaleItem.Matrixcellid
																						and BaseSaleitemid.TicketId = RR_DATA_Revenue.ticketid
																						
									 
						LEFT JOIN (select RR_DATA_Revenue.COAAccountId,
										   RR_DATA_Revenue.SaleItemId,
										   RR_DATA_Revenue.TicketId,
										   sum(RevenueAmount) RevenueAmount
										   
													  from RR_DATA_Revenue WITH(NOLOCK)
														inner join DATA_Ticket WITH(NOLOCK)				on data_ticket.ticketid = rr_data_revenue.ticketid
													where RRCalcTypeTrigger in (1)
													  and AccountingType = 2
													  and RR_DATA_Revenue.COAAccountId not in (1, 2, 3, 4)
													  and RR_DATA_Revenue.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null )
													  Group by  RR_DATA_Revenue.COAAccountId,
																RR_DATA_Revenue.SaleItemId,
																 RR_DATA_Revenue.TicketId
											
													 
											) Reverses			ON ( ((Reverses.TicketId = RR_DATA_Revenue.Ticketid)  and (Reverses.SaleItemId = BaseSaleitemid.BASESaleitemid))
											                          or (Reverses.TicketId = RR_DATA_Revenue.Ticketid))
											LEFT JOIN (select RR_DATA_Revenue.COAAccountId,
														   RR_DATA_Revenue.SaleItemId,
														   RR_DATA_Revenue.TicketId,
														   sum(RevenueAmount) RevenueAmount
										   
																	  from RR_DATA_Revenue WITH(NOLOCK)
																		inner join DATA_Ticket WITH(NOLOCK)				on data_ticket.ticketid = rr_data_revenue.ticketid
																	where RRCalcTypeTrigger in (1)
																	  and AccountingType = 2
																	  and RR_DATA_Revenue.COAAccountId not in (1, 2, 3, 4)
																	  and RR_DATA_Revenue.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null )
																	  Group by  RR_DATA_Revenue.COAAccountId,
																				RR_DATA_Revenue.SaleItemId,
																				 RR_DATA_Revenue.TicketId
											
													 
															) Reverses2			ON  (Reverses2.TicketId = RR_DATA_Revenue.Ticketid)  and (Reverses2.SaleItemId = BaseSaleitemid.BaseSaleitemid)
																						and Reverses2.coaaccountid = ISNULL(Reverses.COAAccountId, Reverses2.coaaccountid)

						LEFT JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = ISNULL(Reverses2.coaaccountid, Reverses.coaaccountid)
						LEFT JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId

				 where RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and (data_transaction.transactiontype in (18, 20, 22)) 
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid 
				   and RR_DATA_REVENUE.TicketID not In (select Ticketid
				                                          from RR_DATA_Revenue RR WITH(NOLOCK)
														 where RR.TicketID = RR_DATA_REVENUE.TicketID
														   and RR.RRCalcTypeTrigger in (2, 3, 4, 17)
														   and RR.FCalcDate &amp;#60;= @BatchDate
														)

						Group by coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid,
								RR_DATA_REVENUE.OperatingAreaId,
								RR_DATA_REVENUE.Workstationid,
								RR_DATA_REVENUE.UserGroupid,
								RR_DATA_REVENUE.UserId,
								RR_DATA_REVENUE.Quantity,
								RR_DATA_REVENUE.GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0),
								RR_DATA_REVENUE.Price,
								RR_DATA_REVENUE.Percentage,								
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs,
								Reverses2.RevenueAmount,
								Reverses.RevenueAmount,
								DATA_SaleItem.BaseSaleId,
								DATA_SaleItem.matrixcellid
			)p
			where RevenueAmount &amp;#60;&amp;#62; 0

	


	END
END



</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>CE8B1EA56F094EA4BD2F80155AD1AAD1</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>71</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_PaymentMethodTaxDiscounts]
	@BatchDate Date,
	@Transactions varchar(1000),
	@RRTransDateType integer
AS 
BEGIN
	 
	Create Table #TransactionIDs(
	TransactionId Int NOT NULL)

	DECLARE @DelimPosition INT
	DECLARE @AccountConfigID INT
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer


    SET @DelimPosition = CHARINDEX(',', @Transactions)

    WHILE @DelimPosition &amp;#62; 0
    BEGIN
        INSERT INTO #TransactionIDs(TransactionId)
            VALUES(CAST(RTRIM(LEFT(@Transactions, @DelimPosition - 1)) AS INT))

        SET @Transactions = right(@Transactions, len(@Transactions) - @DelimPosition)

        SET @DelimPosition = CHARINDEX(',', @Transactions)
    END

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer

	Declare @OnCreditWriteoff Integer = 9
	Declare @StartTime DateTime

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

select TOP 1	@SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
					@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
					@SuspendPrice = COA_CNF_AccountConfig.Price,
					@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

select  @AccountConfigID = coaaccountconfigid
from (
select top 1 coa_cnf_accountconfig.coaaccountconfigid
 from COA_CNF_Account WITH(NOLOCK)
	INNER JOIN coa_cnf_accountconfig WITH(NOLOCK)			on coa_cnf_accountconfig.coaaccountid = COA_CNF_Account.coaaccountid
	 where Code = 'SUSPENSE'
	  and SystemAccount = 1

	  )p

		--	--	--Normal Sale Split out the Payments to Smaller Subset.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[PaymentID])		
					select COAAccountId, 
						   RevenueRecognitionRuleId,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   Quantity,
						   GrossAmount,
						   NetAmount,
						   Price,
						   Percentage,
						   RemainingValue,
						   abs(sum(RevenueAmount)),
						   Accountingtype,
						   rrcalctypetrigger,
						   rrpercentage,
						   rrdays,
						   PaymentID
						   from(				   		    
						select distinct COA.COAAccountId, 
						   @SuspendRRRId RevenueRecognitionRuleId,		   
						   @SuspendRRCalcTypeWhere RRCalcTypeWhere,
						   @SuspendRRCalcTypeMethod RRCalcTypeMethod,	   
						   @SuspendCOAAccountConfigId COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   data_payment.paymentid,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Percentage,
						   0 as RemainingValue, 	
						   rr_data_revenue.RevenueAmount,
							RR_DATA_REVENUE.Accountingtype,
						    @SuspendRRCalcTypeTrigger rrcalctypetrigger,
						    @SuspendPercentage rrpercentage,
						    @SuspendDays rrdays,
							DATA_Transaction.transactiontype

						from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	 WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid 
																						and DATA_Payment.PaymentId = RR_DATA_Revenue.PaymentID
									                                                    and data_payment.PaymentStatus = 1
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = case when CNF_PaymentCard.paymentcardid is not null then
																														case when cnf_paymentmethod.driverid = 48 then CNF_PaymentMethod.COAAccountid
																														     when cnf_paymentcard.coaaccountid is not null then cnf_paymentcard.coaaccountid
																														     else CNF_PaymentMethod.coaaccountid
																														 end
						                                                                                       else CNF_PaymentMethod.COAAccountid
																											end

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid in (select transactionid
												        from rr_Data_Revenue WITH(NOLOCK)
												       where coaaccountid in (@ACCPaymentMethod)
													     and data_payment.Transactionid = RR_DATA_Revenue.Transactionid
													     and fcalcdate = @BatchDate
												)
					 AND RR_DATA_REVENUE.coaaccountid in (@ACCPaymentMethod)
				)P

				group by COAAccountId, 
						   RevenueRecognitionRuleId,	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   Quantity,
						   GrossAmount,
						   NetAmount,
						   Price,
						   Percentage,
						   RemainingValue,						 
						   accountingtype,
						   rrcalctypetrigger,
						   rrpercentage,
						   rrdays,
						   transactiontype,
						   paymentID



		----Normal Sale Split out the Payments to Payment Fees
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA.COAAccountId, 
						   @SuspendRRRId RevenueRecognitionRuleId,		   
						   @SuspendRRCalcTypeWhere RRCalcTypeWhere,
						   @SuspendRRCalcTypeMethod RRCalcTypeMethod,	   
						   @SuspendCOAAccountConfigId COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Perc,
						   0,  	
						   ABS(data_payment.paymentfee) as RevenueAmount,
						   case when data_payment.paymentfee &amp;#62;= 0 then 2
						        else 1
							end accountingtype,		
						    @SuspendRRCalcTypeTrigger rrcalctypetrigger,
						    @SuspendPercentage rrpercentage,
						    @SuspendDays rrdays

						from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid
																							and DATA_Payment.PaymentId = RR_DATA_Revenue.paymentID
						left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
						left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
						INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
						INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = CNF_PaymentMethod.FeeCOAAccountId

					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid from #TransactionIDs)
					and data_payment.paymentfee &amp;#60;&amp;#62; 0
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid not in (select transactionid
												from rr_Data_Revenue WITH(NOLOCK)
												where rr_Data_Revenue.transactionid = data_payment.transactionid
												  and coaaccountid in (select FeeCOAAccountId
																			from cnf_paymentmethod CP WITH(NOLOCK)
																		)
																			and transactionid is not null
												)
					AND data_payment.Transactionid in (select transactionid
												from rr_Data_Revenue WITH(NOLOCK)
													where rr_Data_Revenue.transactionid = data_payment.transactionid
												  and coaaccountid in (@ACCPaymentMethod)
												  and data_payment.Transactionid = RR_DATA_Revenue.Transactionid
												)


		---Installment Billing Fees
		INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])	
				   select *
				   from (
		select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,		   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as BatchDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Perc,
						   0 as Remaining,  	
						   ISNULL((select sum(feeamount)
								from DATA_PaymentPlan2Transaction	
								INNER JOIN DATA_PaymentPlan			on data_paymentplan.paymentplanid = DATA_PaymentPlan2Transaction.paymentplanid
								where DATA_PaymentPlan2Transaction.Transactionid = data_payment.Transactionid
								and DATA_PaymentPlan2Transaction.flexpaymentstatus &amp;#60;&amp;#62; 5), 0) as RevenueAmount,
						   case when data_payment.paymentfee &amp;#62;= 0 then 2
						        else 1
							end accountingtype,		
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays

						from RR_DATA_REVENUE
						INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
						INNER JOIN CNF_PaymentMethod					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId


						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue
											INNER JOIN COA_CNF_Account		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
										)p    on p.transactionid = 	data_payment.transactionid

						INNER JOIN (select distinct DATA_PaymentFlex.paymentid, data_saleitem.saleid, (DATA_PaymentFlex.downpaymentfeeamount + data_paymentflex.feeAmount) as FeeAmount,  CNF_Promotion.COAAccountId
									from data_saleitem
										INNER JOIn data_Paymentflex2saleitem	on data_Paymentflex2saleitem.saleitemid = data_saleitem.saleitemid
										INNER JOIN DATA_PaymentFlex				on data_paymentflex.paymentid = data_Paymentflex2saleitem.paymentid
										INNER JOIN CNF_FlexContract				on cnf_flexContract.FlexContractId = DATA_PaymentFlex.flexcontractID
										INNER JOIN CNF_FlexContractFee			on CNF_FlexContractFee.FlexContractId = CNF_FlexContract.flexcontractID
										INNER JOIN CNF_Promotion				on CNF_Promotion.promotionID = CNF_FlexContractFee.promotionID

									where CNF_Promotion.COAAccountId is not null
									  )r1				on r1.saleid = DATA_Transaction.saleid
						INNER JOIN COA_CNF_Account COA					on COA.COAAccountid = R1.COAAccountId


					where data_payment.paymentstatus = 1
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					AND data_payment.Transactionid in (select distinct transactionid
												from rr_Data_Revenue
												where coaaccountid in (@ACCPaymentMethod)
												  and RR_DATA_Revenue.TransactionId = DATA_Payment.transactionid
									
												)
					)p
					where revenueamount &amp;#60;&amp;#62; 0
 

		--	--Normal Transactions Reverse out of PaymentMethods
			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    					
					select COAAccountId, 
						   Max(RevenueRecognitionRuleId),	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   Max(COAAccountConfigId),
						   COAAccountTypeId,
						   Transactionid,
						   saleid,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   batchdate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Perc,
						   0,
						   ABS(sum(RevenueAmount)) as RevenueAmount,
						   case when accountingtype = 1 then 2
								else 1
							end Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays
						   from (
					select distinct rr_data_Revenue.coaaccountid as rrcoaaccountid,
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,	   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountTypeId,
									   rr_data_Revenue.Transactionid Transactionid,
									   rr_data_Revenue.saleid saleid,
									   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) siteid,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.RevenueAmount  as RevenueAmount,
								       p.Accountingtype,
									   transactiontype,		
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_Revenue.RevenueRecognitionDataId
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN (select saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype
													  from RR_DATA_Revenue WITH(NOLOCK)
														INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
													 where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
													)p								ON p.transactionid = 	rr_data_Revenue.transactionid and rr_data_revenue.accountingtype = p.accountingtype
									INNER JOIN DATA_Transaction WITH(NOLOCK)			on data_transaction.transactionid = rr_data_revenue.transactionid
							
							
							
							where RR_DATA_REVENUE.fcalcdate = @BatchDate							  
							  and DATA_Transaction.TransactionType in (select transactionid
																         from #TransactionIDs)
							  and RR_DATA_Revenue.PaymentID is not null
							  and rr_data_Revenue.coaaccountid in (select coaaccountid
																	 from cnf_paymentmethod WITH(NOLOCK)
																	 where coaaccountid is not null
																	union all
																   select coaaccountid
																	 from cnf_paymentcard WITH(NOLOCK)
																	 where coaaccountid is not null
																  )
						)r	
							group by	 COAAccountId, 		   
									   RRCalcTypeWhere,
									   RRCalcTypeMethod,	   
									   COAAccountTypeId,
									   Transactionid,
									   saleid,
									   Siteid,
									   OperatingAreaId,
									   Workstationid,
									   UserGroupid,
									   UserId,
									   batchdate,				
									   Accountingtype,		
									   RRCalcTypeTrigger,
									   RRPercentage,
									   RRDays, 
									   TransactionType
							

----Normal Sale Split out the Payments to returned Checks
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct 
							COA.COAAccountId, 
						   @SuspendRRRId,	   
						   @SuspendRRCalcTypeWhere,
						   @SuspendRRCalcTypeMethod,	   
						   @SuspendCOAAccountConfigId,
						   COA.COAAccountTypeId,
						   DATA_Transaction.Transactionid as Transactionid,
						   DATA_Transaction.saleid as Saleid,
						   DATA_Transaction.Siteid as SiteID,
						   DATA_Transaction.OperatingAreaId as OperatingAreaID,
						   DATA_Transaction.Workstationid as Workstationid,
						   DATA_Transaction.UserGroupid as UserGroupID,
						   DATA_Transaction.UserId as userID,
						   @BatchDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Perc,
						   0,  	
						  ABS(data_transaction.tip) as RevenueAmount,
							2 accountingtype,		
							 @SuspendRRCalcTypeTrigger,
							100,
							0

						from  DATA_Transaction	 WITH(NOLOCK)					
								INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = DATA_Transaction.transactionid
								left  JOIN DATA_PaymentCard	WITH(NOLOCK)					on data_paymentcard.paymentid = data_payment.PaymentId
								left JOIN CNF_PaymentCard WITH(NOLOCK)						on cnf_paymentcard.paymentcardid = data_paymentcard.paymentcardid
								INNER JOIN CNF_PaymentMethod WITH(NOLOCK)					on CNF_PaymentMethod.PaymentMethodId = data_payment.PaymentMethodId
								INNER JOIN COA_CNF_Account COA WITH(NOLOCK)					on COA.COAAccountid = CNF_PaymentMethod.returnedcheckcoaaccountid
						
						where  data_payment.paymentstatus = 1
						  and DATA_Transaction.TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &amp;#60;&amp;#62; 0
															and ((@RRTransDateType = 0 and convert(date, DATA_Transaction.fTransactionDate) = @BatchDate)
								 OR (@RRTransDateType = 1 and convert(date, DATA_Transaction.TransactionDate) = @BatchDate))

----Breakage for Fixed Vouchers.   The left over money.
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
					select distinct COA.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as Perc,
						   0,  	
						  ABS(DATA_Transaction.Tip) as RevenueAmount,
							2 accountingtype,		
							p.RRCalcTypeTrigger,
							p.RRPercentage,
							p.RRDays

						from RR_DATA_REVENUE WITH(NOLOCK)

							INNER JOIN data_transaction WITH(NOLOCK)		on data_transaction.transactionid = rr_data_revenue.transactionid
							INNER JOIN DATA_Payment WITH(NOLOCK)			on data_payment.transactionid = data_transaction.transactionid
							INNER JOIN CNF_PaymentMethod WITH(NOLOCK)	on cnf_paymentmethod.paymentmethodid = data_payment.paymentmethodid
							INNER JOIN CNF_Driver WITH(NOLOCK) 			on cnf_driver.driverID = cnf_paymentmethod.driverid
							INNER JOIN COA_CNF_Account COA WITH(NOLOCK)	on COA.COAAccountid = CNF_PaymentMethod.FixedVoucherCOAAccountId


							INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, 
																	RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
																	from RR_DATA_Revenue WITH(NOLOCK)
																	INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
																	where COA_CNF_Account.coaAccountID = @ACCPaymentMethod
																)p    on p.transactionid = 	data_payment.transactionid


						where data_payment.paymentstatus = 1
						  and TransactionType in (select transactionid
														from #TransactionIDs)
							and DATA_Transaction.tip &amp;#60;&amp;#62; 0
							and RR_DATA_REVENUE.fcalcdate = @BatchDate


--Normal Transaction break out Tax
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[Saleitemid]
				   ,[matrixcellid]
				   ,[matrixsheetid]
				   ,[Ticketid]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs]
				   ,[SaleItemTaxID])				    
					select distinct COA.COAAccountId, 
						   1 RevenueRecognitionRuleId,		   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
						   RR_data_revenue.Saleitemid,
						   RR_data_revenue.matrixcellid,
						   RR_data_revenue.MatrixSheetId,
						   RR_data_revenue.TicketiD,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as price,
						   100 as percentage,
						   0 RemainingVaue,
						   RR_DATA_REVENUE.revenueamount,
				           RR_DATA_REVENUE.Accountingtype,				   		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   RR_DATA_REVENUE.AttributeIDs,
						   RR_DATA_REVENUE.saleitemtaxid

					from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_saleitemtax WITH(NOLOCK)                    on data_saleitemtax.saleitemTaxid = rr_data_revenue.SaleitemTaxID
						INNER JOIN DATA_SaleItem WITH(NOLOCK)						on data_saleitem.saleitemid = data_saleitemtax.saleitemid
						INNER JOIN CNF_Tax	WITH(NOLOCK)							on cnf_tax.taxid = data_saleitemtax.taxid
						INNER JOIN coa_cnf_account coa	WITH(NOLOCK)				on coa.coaaccountid = cnf_tax.coaaccountid


					where RR_DATA_REVENUE.coaaccountid = @TaxAccountID
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					and TransactionType not in (46)
					and TransactionType in (select transactionid
														from #TransactionIDs)
					AND DATA_Transaction.Transactionid not in (select transactionid
																	from rr_Data_Revenue WITH(NOLOCK)
																	where rr_Data_Revenue.transactionid = DATA_Transaction.Transactionid
																	  and revenueamount &amp;#60;&amp;#62; 0
																	   and isnull(oobflag, 0) = 0
																	  and coaaccountid in (select coaaccountid
																								from cnf_tax WITH(NOLOCK)
																								where coaaccountid is not null
																							)
																	)
					

					
							
																															
----------Reverse Tax Out
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[Saleitemid]
				   ,[matrixcellid]
				   ,[matrixsheetid]
				   ,[Ticketid]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[AttributeIDs]
				   ,[SaleitemtaxID])		    
				             select distinct 
								       p.COAAccountId, 
									   p.RevenueRecognitionRuleId,	   
									   p.RRCalcTypeWhere,
									   p.RRCalcTypeMethod,	   
									   p.COAAccountConfigId,
									   p.COAAccountType,
									   RR_DATA_REVENUE.transactionID,
									   RR_DATA_REVENUE.SaleId,
									   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) siteid,

									   RR_DATA_REVENUE.Saleitemid,
									   RR_DATA_REVENUE.matrixcellid,
									   RR_DATA_REVENUE.matrixsheetid,
									   RR_DATA_REVENUE.TicketID,
									   rr_data_Revenue.OperatingAreaId OperatingAreaid,
									   rr_data_Revenue.Workstationid workstationid,
									   rr_data_Revenue.UserGroupid usergroupid,
									   rr_data_Revenue.UserId userid,
									   @BatchDate batchdate,
									   rr_data_Revenue.Quantity Quantity,
									   rr_data_Revenue.GrossAmount grossamount,
									   rr_data_Revenue.NetAmount netamount,
									   0 price,
									   100 percentage,
									   0 tax,
									   ABS(rr_data_Revenue.RevenueAmount)  as RevenueAmount,
								       case when rr_data_Revenue.Accountingtype = 2 then 1
									        else 2											
										end as Accountingtype,			
									   p.RRCalcTypeTrigger,
									   p.RRPercentage,
									   p.RRDays,
									   rr_data_revenue.AttributeIDs,
									   rr_data_revenue.SaleItemTaxId
							FROM rr_data_Revenue   				        WITH (NOLOCK)
								   INNER JOIN data_transaction WITH(NOLOCK)						on data_transaction.transactionid = rr_data_revenue.transactionid
								   INNER JOIN (select distinct saleid, transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, RR_DATA_Revenue.COAAccountId, 
																RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RR_DATA_Revenue.COAAccountType
																from RR_DATA_Revenue WITH(NOLOCK)																	
																where RR_DATA_REVENUE.fcalcdate = @BatchDate
																  and RR_DATA_Revenue.coaAccountID = @TaxAccountID	
													)p								ON p.Transactionid = 	rr_data_Revenue.Transactionid
									

							where RR_DATA_REVENUE.fcalcdate = @BatchDate
							  and data_transaction.TransactionType not in (46)
							  and DATA_Transaction.TransactionType in (select transactionid
																		from #TransactionIDs)
							  and rr_data_Revenue.coaaccountid in (select coaaccountid
						                                             from cnf_tax WITH(NOLOCK)
																    where coaaccountid is not null
															      )
								
						

		------		--Normal Transaction Break out the discounts
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[saleitemid]
				   ,[Ticketid]
				   ,[matrixcellid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[Saleitemruleid])
				   select COAAccountId, 
						   RevenueRecognitionRuleId,	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   Saleitemid,
						   ticketid,
						   matrixcellid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   RevenueAmount,
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   Saleitemruleid
				   from (				    
						select distinct 
						   COA.COAAccountId, 
						   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
						   RR_DATA_REVENUE.RRCalcTypeWhere,
						   RR_DATA_REVENUE.RRCalcTypeMethod,	   
						   RR_DATA_REVENUE.COAAccountConfigId,
						   COA.COAAccountTypeId,
						   RR_DATA_REVENUE.Transactionid as Transactionid,
						   RR_DATA_REVENUE.saleid as Saleid,
						   RR_DATA_REVENUE.saleitemid as saleitemid,
						   RR_DATA_REVENUE.ticketid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
						   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
						   RR_DATA_REVENUE.Workstationid as Workstationid,
						   RR_DATA_REVENUE.UserGroupid as UserGroupID,
						   RR_DATA_REVENUE.UserId as userID,
						   @BatchDate as batchdate,
						   0 as Quantity,
						   0 as GrossAmount,
						   0 as NetAmount,
						   0 as Price,
						   100 as percentage,
						   0 as remaningValues, 
						   RR_DATA_REVENUE.revenueamount,
						   RR_DATA_REVENUE.Accountingtype,		
						   RR_DATA_REVENUE.RRCalcTypeTrigger,
						   RR_DATA_REVENUE.RRPercentage,
						   RR_DATA_REVENUE.RRDays,
						   DATA_SaleItemRule.SaleItemRuleId,
						   p.matrixcellid

					from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	 WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_Sale WITH(NOLOCK)				            ON DATA_Sale.SaleID = data_transaction.SaleID
						LEFT  JOIN DATA_SaleItem	WITH(NOLOCK)		            ON DATA_SaleItem.saleitemid = RR_DATA_REVENUE.saleitemid
						LEFT JOIN DATA_SaleItemRule	WITH(NOLOCK)					ON data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid
																						and data_saleitemrule.saleitemruleid = rr_data_revenue.saleitemruleid
						LEFT JOIN CNF_PromotionItemRule	WITH(NOLOCK)				ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
						LEFT JOIN CNF_PromotionItem WITH(NOLOCK)					ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
						LEFT JOIN CNF_Promotion	 WITH(NOLOCK)						ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId	
						INNER JOIN COA_CNF_Account	COA	WITH(NOLOCK)		        ON COA.coaaccountid = CNF_Promotion.coaaccountid
						
						
						INNER JOIN (select transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, saleitemid, matrixcellid, RR_DATA_Revenue.SaleItemRuleID,
											RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount,  Accountingtype
											from RR_DATA_Revenue WITH(NOLOCK)
											INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
											where COA_CNF_Account.coaAccountID = @DiscountAccountID
										)p    on p.transactionid = 	DATA_Transaction.transactionid and p.saleitemid = rr_data_revenue.saleitemid  and p.SaleItemRuleID = DATA_SaleItemRule.SaleItemRuleId



					where ((RR_DATA_REVENUE.coaaccountid = @DiscountAccountID) or (cnf_promotion.Promotiontype in (3, 5, 7, 101, 200)))
					and RR_DATA_REVENUE.coaaccountid = @DiscountAccountID
					and DATA_Transaction.TransactionType in (select transactionid
																from #TransactionIDs)
					and RR_DATA_REVENUE.fcalcdate = @BatchDate
					 and data_transaction.transactiontype not in (46, 47, 51)

					)p
					where revenueamount &amp;#60;&amp;#62; 0	
					  and coaaccountid is not null													
																																								
		----		--Reverse out Discounts														
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[Ticketid]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[saleitemruleid])	
				   select COAAccountId, 
						   RevenueRecognitionRuleId,		   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   ticketid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   sum(RevenueAmount),
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   saleitemruleid
				   from (		    
				select distinct 				           
                           p.COAAccountId, 
						   p.RevenueRecognitionRuleId,	   
						   p.RRCalcTypeWhere,
						   p.RRCalcTypeMethod,	   
						   p.COAAccountConfigId,
						   p.COAAccountTypeId,
						   rr_data_Revenue.Transactionid,
						   rr_data_Revenue.saleid,
						   rr_data_Revenue.ticketid,
						   rr_data_Revenue.saleitemid,
						   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) Siteid,
						   rr_data_Revenue.OperatingAreaId,
						   rr_data_Revenue.Workstationid,
						   rr_data_Revenue.UserGroupid,
						   rr_data_Revenue.UserId,
						   @BatchDate batchdate,
							0 as quantity,
						   0 as grossamount,
						   0 as netamount,
						   0 as price,
						   100 as percentage,
						   0 as remaningValues,
						   rr_data_Revenue.RevenueAmount  as RevenueAmount,
						   case when p.accountingtype = 1 then 2
					        else 1
						   end Accountingtype,
						   p.RRCalcTypeTrigger,
						   p.RRPercentage,
						   p.RRDays,
						   rr_data_Revenue.matrixcellid,
 						   rr_data_Revenue.RevenueRecognitionDataId,
						   rr_data_Revenue.saleitemruleid

						  FROM rr_data_Revenue WITH(NOLOCK) 
						         INNER JOIN data_transaction  WITH(NOLOCK)       on data_transaction.transactionid = rr_data_revenue.transactionid
								   INNER JOIN (select RR_DATA_Revenue.saleid, RR_DATA_Revenue.transactionid, RevenueRecognitionRuleId, RRCalcTypeWhere, Saleitemid, RR_DATA_Revenue.COAAccountId, 
													   RRCalcTypeMethod, COAAccountConfigId, RRCalcTypeTrigger, RRPercentage, RRDays, RevenueAmount, COA_CNF_Account.COAAccountTypeId,  Accountingtype,
													   rr_data_Revenue.RevenueRecognitionDataId, saleitemruleid
													  from RR_DATA_Revenue WITH(NOLOCK)
														INNER JOIN COA_CNF_Account WITH(NOLOCK)		ON COA_CNF_Account.CoaAccountid = RR_DATA_Revenue.CoaAccountid
														INNER JOIN data_transaction WITH(NOLOCK)     on data_transaction.transactionid = RR_DATA_Revenue.transactionid 
													 where COA_CNF_Account.coaAccountID = @DiscountAccountID
													  and data_transaction.transactiontype not in (46, 47, 51)
													  and ISNULL(oobflag, 0 ) = 0
													  and revenueamount &amp;#60;&amp;#62; 0
													)p								ON p.saleid = 	rr_data_Revenue.saleid and p.saleitemid = rr_data_revenue.saleitemid and p.saleitemruleid = rr_data_revenue.saleitemruleid
								

						where  Rr_data_Revenue.coaaccountid in (select coaaccountid from cnf_promotion WITH(NOLOCK) where COAAccountId is not null)

						 and RR_DATA_REVENUE.fcalcdate = @BatchDate
						 and data_transaction.transactiontype not in (46, 47, 51)
						 and rr_data_Revenue.coaAccountID &amp;#60;&amp;#62; @DiscountAccountID
						 and DATA_Transaction.TransactionType in (select transactionid
															from #TransactionIDs)
						 and Rr_data_Revenue.Accountingtype = case when DATA_Transaction.TransactionType in (5, 17, 18, 20, 22, 30) and (select sum(discountamount) from data_saleitemrule where data_saleitemrule.saleitemid = rr_data_revenue.saleitemid  and promotiontype &amp;#60;&amp;#62; 3) &amp;#60; 0 then 1
						                                           when RR_DATA_REVENUE.Accountingtype = 2 and (select sum(discountamount) from data_saleitemrule where data_saleitemrule.saleitemid = rr_data_revenue.saleitemid) &amp;#62; 0 then 2 
						                                           when RR_DATA_REVENUE.Accountingtype = 2 and (select sum(discountamount) from data_saleitemrule where data_saleitemrule.saleitemid = rr_data_revenue.saleitemid) &amp;#60; 0 then 2
																  else 1
															   end
						)p		
						
						group by  COAAccountId, 
						   RevenueRecognitionRuleId,	   
						   RRCalcTypeWhere,
						   RRCalcTypeMethod,	   
						   COAAccountConfigId,
						   COAAccountTypeId,
						   Transactionid,
						   Saleid,
						   SiteID,
						   OperatingAreaID,
						   Workstationid,
						   UserGroupID,
						   userID,
						   batchdate,
						   quantity,
						   grossamount,
						   netamount,
						   price,
						   percentage,
						   remaningValues, 	
						   Accountingtype,		
						   RRCalcTypeTrigger,
						   RRPercentage,
						   RRDays,
						   ticketid,
						   saleitemruleid
						   
 						   																																																																																		

	--Added for COA 7.4.21
	--COA for Rounding Pennies
					INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					    ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])					   		    
							select distinct COA_CNF_Account.COAAccountId, 
							   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
							   RR_DATA_REVENUE.RRCalcTypeWhere,
							   RR_DATA_REVENUE.RRCalcTypeMethod,	   
							   @AccountConfigID,
							   COA_CNF_Account.COAAccountTypeId,
							   RR_DATA_REVENUE.Transactionid as Transactionid,
							   RR_DATA_REVENUE.saleid as Saleid,
							   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
							   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
							   RR_DATA_REVENUE.Workstationid as Workstationid,
							   ISNULL(RR_DATA_REVENUE.UserGroupid, DATA_Transaction.usergroupid) as UserGroupID,
							   RR_DATA_REVENUE.UserId as userID,
							   @BatchDate as batchdate,
							   0 as Quantity,
							   0 as GrossAmount,
							   0 as NetAmount,
							   0 as Price,
							   100 as Percentage,
							   0 as RemainingValue, 	
							   abs(DATA_Transaction.Rounding),
							   case when data_payment.paymentamount &amp;#62; 0 then case when DATA_Transaction.Rounding &amp;#60; 0 then 1 else 2 end
								    when data_payment.paymentamount &amp;#60; 0 then case when DATA_Transaction.Rounding &amp;#62; 0 and data_transaction.transactiontype in (40) then 2 else 1 end
									when data_payment.paymentamount &amp;#60; 0 then case when DATA_Transaction.Rounding &amp;#60; 0 then 2 else 1 end									
								end,		
							    RR_DATA_REVENUE.RRCalcTypeTrigger,
							    RR_DATA_REVENUE.RRPercentage,
							    RR_DATA_REVENUE.RRDays

					from RR_DATA_REVENUE WITH(NOLOCK)
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN data_payment	WITH(NOLOCK)						on data_payment.transactionid = rr_data_revenue.transactionid
						INNER JOIN CNF_Currency	WITH(NOLOCK)						on cnf_currency.CurrencyId = data_payment.CurrencyId
						INNER JOIN CNF_RoundingRule	WITH(NOLOCK)					on cnf_roundingrule.roundingruleid = cnf_currency.roundingruleid
						INNER JOIN COA_CNF_Account  WITH(NOLOCK) 					on COA_CNF_Account.COAAccountid = CNF_RoundingRule.COAAccountid

					where DATA_Transaction.Rounding &amp;#60;&amp;#62; 0
						and DATA_Transaction.TransactionType in (select transactionid
																	from #TransactionIDs)
						and RR_DATA_REVENUE.fcalcdate = @BatchDate
						and RR_DATA_REVENUE.RevenueRecognitionRuleId = @SuspendID 


--COA for Donations
	INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					    ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays])	
						select distinct COA_CNF_Account.COAAccountId, 
							   RR_DATA_REVENUE.RevenueRecognitionRuleId,	   
							   RR_DATA_REVENUE.RRCalcTypeWhere,
							   RR_DATA_REVENUE.RRCalcTypeMethod,	   
							   @AccountConfigID,
							   COA_CNF_Account.COAAccountTypeId,
							   RR_DATA_REVENUE.Transactionid as Transactionid,
							   RR_DATA_REVENUE.saleid as Saleid,
							   ISNULL(rr_data_Revenue.Siteid, DATA_Transaction.SiteId) as SiteID,
							   RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
							   RR_DATA_REVENUE.Workstationid as Workstationid,
							   RR_DATA_REVENUE.UserGroupid as UserGroupID,
							   RR_DATA_REVENUE.UserId as userID,
							   @BatchDate as batchdate,
							   0 as Quantity,
							   0 as GrossAmount,
							   0 as NetAmount,
							   0 as Price,
							   100 as Percentage,
							   0 as RemainingValue, 	
							   abs(data_payment.donationamount),
							   case when data_payment.donationamount  &amp;#62; 0 then 2
							        else 1
								end as accountingtype,		
							   RR_DATA_REVENUE.RRCalcTypeTrigger,
							   RR_DATA_REVENUE.RRPercentage,
							   RR_DATA_REVENUE.RRDays
							from RR_DATA_REVENUE
								INNER JOIN DATA_Transaction						on data_transaction.transactionid = rr_data_revenue.transactionid
								INNER JOIN data_payment							on data_payment.transactionid = rr_data_revenue.transactionid
								INNER JOIN CNF_DonationForm						on CNF_DonationForm.donationformid = data_payment.donationformid
								INNER JOIN COA_CNF_Account   					on COA_CNF_Account.COAAccountid = CNF_DonationForm.COAAccountid

							where data_payment.donationamount &amp;#60;&amp;#62; 0
							and DATA_Transaction.TransactionType in (select transactionid
																	from #TransactionIDs)
								and RR_DATA_REVENUE.coaaccountid = 2
								and RR_DATA_REVENUE.fcalcdate = @BatchDate

		
--Normal Sale with TIPS
				INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SiteId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				    ,[AccountingType]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays])				    
				select distinct COA_CNF_Account.COAAccountId, 
						   1,	   
						   1,
						   1,	   
						   1,
						   COA_CNF_Account.COAAccountTypeId,
						   data_transaction.Transactionid as Transactionid,
						   data_transaction.saleid as Saleid,
						   data_transaction.Siteid as SiteID,
						   data_transaction.OperatingAreaId as OperatingAreaID,
						   data_transaction.Workstationid as Workstationid,
						   data_transaction.UserGroupid as UserGroupID,
						   data_transaction.UserId as userID,
						   @BatchDate,
						   0,
						   0,
						   0,
						   0,
						   100,
						   0,  	
						   ABS(data_payment.TipsAmount) as RevenueAmount,
						   case when data_payment.TipsAmount &amp;#62;= 0 then 2
						        else 1
							end accountingtype,		
						   1,
						   100,
						   0

				from data_payment WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)							on data_transaction.transactionid = data_payment.transactionid
					inner join cnf_paymentmethod WITH(NOLOCK)							ON cnf_paymentmethod.PaymentMethodId = data_payment.PaymentMethodID
					inner join COA_CNF_Account WITH(NOLOCK)								ON coa_cnf_account.COAAccountId = cnf_paymentmethod.TipsCOAAccountID
						

					where data_payment.paymentstatus = 1
				  and ISNULL(data_payment.TipsAmount, 0) &amp;#60;&amp;#62; 0
					and DATA_Transaction.TransactionType in (select transactionid
 															   from #TransactionIDs)
					and data_payment.fpaymentdate = @BatchDate


		End



</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>0F4DE7602332466B82BF40FC44563B6E</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_SettleUpgradeSuspendAccount</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>24</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_SettleUpgradeSuspendAccount]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer

	Declare @TransactionID Integer
	Declare @TransactionType Integer
	Declare @FCalcDate date
	Declare @UsageID Integer
	Declare @TicketID Integer
	Declare @UsagePrice float
	Declare @AmountLeft float

	Declare @saleid Integer
	Declare @Siteid Integer
	Declare @OperatingAreaId Integer
	Declare @Workstationid Integer
	Declare @UserGroupid Integer
	Declare @UserId Integer
	Declare @Quantity Integer
	Declare @GrossAmount Float
	Declare @NetAmount Float
	Declare @RevenueAmount Float
	Declare @PaymentMethod Integer
	Declare @PaymentAmount Float
	Declare @TransDate Date
	Declare @Matrixcell Integer
	Declare @MatrixSheetId Integer 
	Declare @SaleitemID Integer
	Declare @PaymentDriver Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @UsageTrigger Integer = 2
	Declare @DepositTrigger Integer = 5
	Declare @MoneyRefund Integer = 6
	Declare @OnSaleTrigger Integer = 1
	Declare @OnAdvancePaymentTrigger Integer = 7
	Declare @SuspendRule Integer
	Declare @StartTime DateTime

	Set @StartTime = Getdate();
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @SuspendRule = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select top 1  @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
		   @SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		   @SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		   @SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		   @SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
		   @SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
		   @SuspendCOAAccountId = coa_cnf_account.COAAccountId,
		   @SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
		   @SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
		   @SuspendPrice = COA_CNF_AccountConfig.Price,
		   @SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
		   @SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
		   @SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType

	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	  and RR_CNF_RevenueRecognitionRule.enabled = 1
	  and COA_CNF_AccountConfig.enabled = 1

	--update rr_data_revenue
	--   set revenueamount = abs(revenueamount)		   
	-- where FCalcDate = @BatchDate
	--   and coaaccountid = @SuspendID

	BEGIN
		
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[TicketID]
					   ,[SiteId]
					   ,[Matrixcellid]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays]
					   ,[AttributeIDs])
				select SuspendCOAAccountId,
					   SuspendRRRId,
					   SuspendRRCalcTypeWhere,
					   SuspendRRCalcTypeMethod,
					   SuspendCOAAccountConfigId,
					   SuspendCOAAccountTypeId,
					   Transactionid,
					   saleid,
					   TicketID,
					   Siteid,
					   Matrixcellid,
					   OperatingAreaId,
					   Workstationid,
					   UserGroupid,
					   UserId,
					   BatchDate,
					   0,
					   GrossAmount,
					   NetAmount,
					   SuspendPrice,
					   percentage,
					   RemainingValues,
					   sum(ABS(RevenueAmount)),
					   case when accountingtype = 1 then 2
					        else 1
						end Accountingtype,
					   rrtrigger,
					   percentage2,
					   rrdays,
					   AttributeIDs
				from (
				select  @SuspendCOAAccountId SuspendCOAAccountId,
					   @SuspendRRRId SuspendRRRId,
					   @SuspendRRCalcTypeWhere SuspendRRCalcTypeWhere,
					   @SuspendRRCalcTypeMethod SuspendRRCalcTypeMethod,
					   @SuspendCOAAccountConfigId SuspendCOAAccountConfigId,
					   @SuspendCOAAccountTypeId SuspendCOAAccountTypeId,
					   RR_DATA_Revenue.Transactionid Transactionid,
					   RR_DATA_Revenue.saleid saleid,

					   case when rr_data_revenue.transactionid in (select transactionid from rr_data_revenue rr with(nolock) where rr.coaaccountid = 1 and rr.RevenueRecognitionRuleId = 1) and
					             rr_data_revenue.TicketID in (select TicketID from rr_data_revenue rr with(nolock) where rr.coaaccountid = 1 and rr.RevenueRecognitionRuleId = 1 and rr.TicketID = RR_DATA_Revenue.TicketID and rr.TransactionId = rr_data_revenue.transactionid) then RR_DATA_Revenue.TicketID
								 else null
						end Ticketid,

					   RR_DATA_Revenue.SaleItemid saleitemid,
					   RR_DATA_Revenue.MatrixSheetId MatrixSheetId,
					   RR_DATA_Revenue.Siteid Siteid,
					   RR_DATA_Revenue.matrixcellid,
					   RR_DATA_Revenue.OperatingAreaId OperatingAreaId,
					   RR_DATA_Revenue.Workstationid Workstationid,
					   @UserGroupid UserGroupid,
					   RR_DATA_Revenue.UserId UserId,
					   @BatchDate BatchDate,
					   0 GrossAmount,
					   0 NetAmount,
					   @SuspendPrice SuspendPrice,
					   @SuspendCOAAccount_Percentage percentage,
					   @SuspendRemainingValues RemainingValues,
					   case when RR_DATA_Revenue.RRCalcTypeTrigger = 5 then 0
					        else RevenueAmount
						end RevenueAmount, 						
					   RR_DATA_Revenue.AccountingType,
					   @SuspendRRCalcTypeTrigger rrtrigger,
					   @SuspendPercentage percentage2,
					   @SuspendDays rrdays,
					   RR_DATA_Revenue.AttributeIDs
	  
				from RR_DATA_Revenue WITH(NOLOCK)
						INNER JOIN data_transaction	 WITH(NOLOCK)				on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_SaleItem WITH(NOLOCK)					on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.SaleItemId

				   where ((TransactionType in  (5, 7, 18, 20, 22, 30, 122)) or ((TransactionType = 122) and (DATA_SaleItem.ItemTransactionType in (14, 16)))) 
				     and rr_data_revenue.fcalcdate = @BatchDate
					 and isnull(RR_DATA_REVENUE.RRDays, 0) = 0
					 and RR_DATA_Revenue.RRCalcTypeTrigger in (1, 10)
					 and rr_data_revenue.RevenueRecognitionRuleId &amp;#60;&amp;#62; @SuspendRRRId
					 and rr_data_revenue.coaaccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
					 and RR_DATA_Revenue.transactionid in (select RR.TransactionId from RR_DATA_Revenue RR WITH(NOLOCK) where RR.COAAccountId in (@suspendid) )
				)p	
				
				group by   SuspendCOAAccountId,
						   SuspendRRRId,
						   SuspendRRCalcTypeWhere,
						   SuspendRRCalcTypeMethod,
						   SuspendCOAAccountConfigId,
						   SuspendCOAAccountTypeId,
						   Transactionid,
						   saleid,
						   TicketID,
						   Siteid,
						   matrixcellid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   BatchDate,
						   GrossAmount,
						   NetAmount,
						   SuspendPrice,
						   percentage,
						   RemainingValues,
						   accountingtype,
						   rrtrigger,
						   percentage2,
					       rrdays,
						   AttributeIDs	
				having sum(ABS(RevenueAmount)) &amp;#60;&amp;#62; 0
						   
						   						  																			
	end
END



</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>E30D9842810C4B7C85512364EB0D2EC9</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_SettleUpSuspendAccount</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>38</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_SettleUpSuspendAccount]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer

	Declare @TransactionID Integer
	Declare @TransactionType Integer
	Declare @FCalcDate date
	Declare @UsageID Integer
	Declare @TicketID Integer
	Declare @UsagePrice float
	Declare @AmountLeft float
	Declare @TicketRRRId Integer

	Declare @saleid Integer
	Declare @Siteid Integer
	Declare @OperatingAreaId Integer
	Declare @Workstationid Integer
	Declare @UserGroupid Integer
	Declare @UserId Integer
	Declare @Quantity Integer
	Declare @GrossAmount Float
	Declare @NetAmount Float
	Declare @RevenueAmount Float
	Declare @PaymentMethod Integer
	Declare @PaymentAmount Float
	Declare @TransDate Date
	Declare @Matrixcell Integer
	Declare @MatrixSheetId Integer 
	Declare @SaleitemID Integer
	Declare @PaymentDriver Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @UsageTrigger Integer = 2
	Declare @DepositTrigger Integer = 5
	Declare @MoneyRefund Integer = 6
	Declare @OnSaleTrigger Integer = 1
	Declare @OnAdvancePaymentTrigger Integer = 7
	Declare @SuspendRule Integer
	Declare @StartTime DateTime

	Set @StartTime = Getdate();
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @SuspendRule = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select top 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
		   @SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
		   @SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
		   @SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
		   @SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
		   @SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
		   @SuspendCOAAccountId = coa_cnf_account.COAAccountId,
		   @SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
		   @SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
		   @SuspendPrice = COA_CNF_AccountConfig.Price,
		   @SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
		   @SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
		   @SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType

	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID
	  and RR_CNF_RevenueRecognitionRule.enabled = 1
	  and COA_CNF_AccountConfig.enabled = 1

	select @TicketRRRId = RevenueRecognitionRuleId
	  from RR_CNF_RevenueRecognitionRule
	  where rrcalctypeTrigger = 21
	  select '@TicketRRRId', @TicketRRRId
	update rr_data_revenue
	   set revenueamount = abs(revenueamount)		   
	 where FCalcDate = @BatchDate
	   and coaaccountid = @SuspendID
	   and revenueamount &amp;#60; 0

	BEGIN
		
			INSERT INTO [dbo].[RR_DATA_Revenue]
					   ([COAAccountId]
					   ,[RevenueRecognitionRuleId]
					   ,[RRCalcTypeWhere]
					   ,[RRCalcTypeMethod]
					   ,[COAAccountConfigId]
					   ,[COAAccountType]
					   ,[TransactionId]
					   ,[SaleId]
					   ,[SaleitemID]
					   ,[TicketID]
					   ,[SiteId]
					   ,[OperatingAreaId]
					   ,[WorkstationId]
					   ,[UserGroupId]
					   ,[UserId]
					   ,[FCalcDate]
					   ,[Quantity]
					   ,[GrossAmount]
					   ,[NetAmount]
					   ,[Price]
					   ,[Percentage]
					   ,[RemaningValues]
					   ,[RevenueAmount]
					   ,[AccountingType]
					   ,[RRCalcTypeTrigger]
					   ,[RRPercentage]
					   ,[RRDays]
					   ,[AttributeIDs])
				select SuspendCOAAccountId,
					   SuspendRRRId,
					   SuspendRRCalcTypeWhere,
					   SuspendRRCalcTypeMethod,
					   SuspendCOAAccountConfigId,
					   SuspendCOAAccountTypeId,
					   Transactionid,
					   saleid,
					   SaleitemID,
					   TicketID,
					   Siteid,
					   OperatingAreaId,
					   Workstationid,
					   UserGroupid,
					   UserId,
					   BatchDate,
					   0,
					   GrossAmount,
					   NetAmount,
					   SuspendPrice,
					   percentage,
					   RemainingValues,
					   sum(ABS(RevenueAmount)),
					   case when accountingtype = 1 then 2
					        else 1
						end Accountingtype,
					   rrtrigger,
					   percentage2,
					   rrdays,
					   AttributeIDs
				from (
				select distinct @SuspendCOAAccountId SuspendCOAAccountId,
					   @SuspendRRRId SuspendRRRId,
					   @SuspendRRCalcTypeWhere SuspendRRCalcTypeWhere,
					   @SuspendRRCalcTypeMethod SuspendRRCalcTypeMethod,
					   @SuspendCOAAccountConfigId SuspendCOAAccountConfigId,
					   @SuspendCOAAccountTypeId SuspendCOAAccountTypeId,
					   RR_DATA_Revenue.Transactionid Transactionid,
					   RR_DATA_Revenue.saleid,
					   RR_DATA_Revenue.SaleitemID,
					   RR_DATA_Revenue.TicketID,
					   RR_DATA_Revenue.Matrixcellid Matrixcell,
					   RR_DATA_Revenue.MatrixSheetId MatrixSheetId,
					   RR_DATA_Revenue.Siteid Siteid,
					   RR_DATA_Revenue.OperatingAreaId OperatingAreaId,
					   RR_DATA_Revenue.Workstationid Workstationid,
					   @UserGroupid UserGroupid,
					   RR_DATA_Revenue.UserId UserId,
					   @BatchDate BatchDate,
					   0 GrossAmount,
					   0 NetAmount,
					   @SuspendPrice SuspendPrice,
					   @SuspendCOAAccount_Percentage percentage,
					   @SuspendRemainingValues RemainingValues,
					   case when RR_DATA_Revenue.RRCalcTypeTrigger = 5 and data_transaction.transactiontype not in (12, 15) then 0
					        when TransactionType = 8 and RR_DATA_Revenue.AccountingType = 1 then 0
					        else RevenueAmount
						end RevenueAmount, 

					   ISNULL((select top 1 AccountingType 
								  from rr_data_revenue tt WITH(NOLOCK)
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid
									and tt.saleitemid = rr_data_revenue.saleitemid),
								(select top 1 AccountingType 
								  from rr_data_revenue tt WITH(NOLOCK)
								  where tt.COAAccountId = @SuspendID
									and tt.transactionid = rr_data_revenue.transactionid)
								)	 as Accountingtype,
					   @SuspendRRCalcTypeTrigger rrtrigger,
					   @SuspendPercentage percentage2,
					   @SuspendDays rrdays,
					   RR_DATA_Revenue.AttributeIDs,
					   rr_data_revenue.RevenueRecognitionDAtaID
	  
				from RR_DATA_Revenue WITH(NOLOCK)
						INNER JOIN data_transaction WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT  JOIN DATA_SaleItem WITH(NOLOCK)					on data_saleitem.saleid = data_transaction.saleid

				   where TransactionType in (5, 8, 9, 10, 12, 13, 14, 15, 16, 18, 31, 34, 38, 41, 42, 43, 46, 47, 48, 49, 51,  52, 119) 					 				     
				     and rr_data_revenue.fcalcdate = @BatchDate
					 and rr_data_revenue.RevenueRecognitionRuleId &amp;#60;&amp;#62; @SuspendRRRId
					 and rr_data_revenue.coaaccountid not in (@SuspendID, @ACCPaymentMethod, @TaxAccountID, @DiscountAccountID)
					 and rr_data_revenue.RRCalcTypeTrigger not in (8)
					 and 1 = case when DATA_Transaction.TransactionType IN (14, 16, 119) and RR_DATA_Revenue.AccountingType = 1 then 0
					              else 1
							  end 
					 and RR_DATA_Revenue.RevenueRecognitionRuleId &amp;#60;&amp;#62; isnull(@TicketRRRId, 0)
				)p	
				
				group by   SuspendCOAAccountId,
						   SuspendRRRId,
						   SuspendRRCalcTypeWhere,
						   SuspendRRCalcTypeMethod,
						   SuspendCOAAccountConfigId,
						   SuspendCOAAccountTypeId,
						   Transactionid,
						   saleid,
						   TicketID,
						   Siteid,
						   OperatingAreaId,
						   Workstationid,
						   UserGroupid,
						   UserId,
						   BatchDate,
						   GrossAmount,
						   NetAmount,
						   SuspendPrice,
						   percentage,
						   RemainingValues,
						   accountingtype,
						   rrtrigger,
						   percentage2,
					       rrdays,
						   AttributeIDs	,
						   SaleitemID

				having sum(ABS(RevenueAmount)) &amp;#60;&amp;#62; 0
	end
END

</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>912D3F685E794742A0FC07DBC9F1FE11</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="ACTIVE">
			<Name>otn_sp_RR_RevenueData_UpdateDateTickets</Name>
			<ScriptList>
				<Script Type="SP">
					<Database>stMsSQL2005</Database>
					<Version>6</Version>
					<SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_UpdateDateTickets]	 
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

			INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SaleItemId]
				   ,[MatrixCellId]
				   ,[UsageId]
				   ,[TicketId]
				   ,[SiteId]
				   ,[LocationId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[UnitAmount]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[MatrixSheetId]
				   ,[AccountingType]
				   ,[AttributeIDs])
			select  COAAccountId 
				   , RevenueRecognitionRuleId 
				   , RRCalcTypeWhere 
				   , RRCalcTypeMethod 
				   , COAAccountConfigId 
				   , COAAccountType 
				   , TransactionId 
				   , SaleId 
				   , rr_data_revenue.SaleItemId 
				   , rr_data_revenue.MatrixCellId 
				   , UsageId 
				   , DATA_Ticket.Ticketid 
				   , rr_data_revenue.SiteId 
				   , LocationId 
				   , OperatingAreaId 
				   , rr_data_revenue.WorkstationId 
				   , UserGroupId 
				   , UserId 
				   , FCalcDate 
				   , Quantity 
				   , UnitAmount 
				   , GrossAmount 
				   , NetAmount 
				   , rr_data_revenue.Price 
				   , Percentage 
				   , RemaningValues 
				   , isnull(UnitAmount, 0)
				   , RRCalcTypeTrigger 
				   , RRPercentage 
				   , RRDays 
				   , MatrixSheetId 
				   , accountingtype 
				   , AttributeIDs 
			from rr_data_revenue WITH(NOLOCK)
				Inner join DATA_Ticket WITH(NOLOCK)							on data_ticket.saleitemid = rr_data_revenue.Saleitemid and voidtype &amp;#60;&amp;#62; 104
			where rr_data_revenue.Saleitemid in (select distinct saleitemid
													from data_ticket WITH(NOLOCK)
													  where ticketid NOT IN (select ticketid from rr_data_revenue where ticketid is not null)
														and saleitemid in (select saleitemid from rr_data_revenue where saleitemid is not null)
														and price &amp;#62; 0)


	INSERT INTO [dbo].[RR_DATA_Revenue]
				   ([COAAccountId]
				   ,[RevenueRecognitionRuleId]
				   ,[RRCalcTypeWhere]
				   ,[RRCalcTypeMethod]
				   ,[COAAccountConfigId]
				   ,[COAAccountType]
				   ,[TransactionId]
				   ,[SaleId]
				   ,[SaleItemId]
				   ,[MatrixCellId]
				   ,[UsageId]
				   ,[TicketId]
				   ,[SiteId]
				   ,[LocationId]
				   ,[OperatingAreaId]
				   ,[WorkstationId]
				   ,[UserGroupId]
				   ,[UserId]
				   ,[FCalcDate]
				   ,[Quantity]
				   ,[UnitAmount]
				   ,[GrossAmount]
				   ,[NetAmount]
				   ,[Price]
				   ,[Percentage]
				   ,[RemaningValues]
				   ,[RevenueAmount]
				   ,[RRCalcTypeTrigger]
				   ,[RRPercentage]
				   ,[RRDays]
				   ,[MatrixSheetId]
				   ,[AccountingType]
				   ,[AttributeIDs])
			select  COAAccountId 
				   , RevenueRecognitionRuleId 
				   , RRCalcTypeWhere 
				   , RRCalcTypeMethod 
				   , COAAccountConfigId 
				   , COAAccountType 
				   , TransactionId 
				   , SaleId 
				   , rr_data_revenue.SaleItemId 
				   , rr_data_revenue.MatrixCellId 
				   , UsageId 
				   , Ticketid 
				   , rr_data_revenue.SiteId 
				   , LocationId 
				   , OperatingAreaId 
				   , rr_data_revenue.WorkstationId 
				   , UserGroupId 
				   , UserId 
				   , FCalcDate 
				   , Quantity 
				   , UnitAmount 
				   , GrossAmount 
				   , NetAmount 
				   , rr_data_revenue.Price 
				   , Percentage 
				   , RemaningValues 
				   , isnull(RevenueAmount, 0)  
				   , RRCalcTypeTrigger 
				   , RRPercentage 
				   , RRDays 
				   , MatrixSheetId 
				   , case when accountingtype = 1 then 2
				          else 1
						  end 
				   , AttributeIDs 
			from rr_data_revenue WITH(NOLOCK)
			where rr_data_revenue.Saleitemid in (select distinct saleitemid
													from data_ticket WITH(NOLOCK)
													  where ticketid NOT IN (select ticketid from rr_data_revenue where ticketid is not null)
														and saleitemid in (select saleitemid from rr_data_revenue where saleitemid is not null)
														and price &amp;#62; 0)
			  and rr_data_revenue.ticketid is null
			

End</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>92EC5A95136C4C9EB2D6265548A715AF</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</StoredProcedure>
		<StoredProcedure Status="DELETED"><Name>otn_sp_SubModel_To_DBGroup</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>create PROCEDURE [dbo].[otn_sp_SubModel_To_DBGroup]
AS
BEGIN
    Declare @SubModels varchar(max)
    Declare @DBGroupId Integer
    Declare @DBTableId integer
    Declare @DBTable2DBGroupId Integer
    Declare @SubModel varchar(Max)
    Declare @Code varchar(Max)
    Declare @SubModelID int
    Declare @Tables varchar(max)

    Declare @Temp table (Oridinal int,
	                        Value varchar(max)
                         )

    Update CNF_DBGroup set Active = 0 where SystemDefined = 1
    Update CNF_DBTable2DBGroup set Active = 0 where SystemDefined = 1

    SET @SubModels ='BOS_GRP_Attribute-91:CNF_Attribute,CNF_Attribute_SaleValidity,CNF_AttributeSet,CNF_AttributeSetDetail,CNF_AttributeTemplate;BOS_GRP_MatrixCell-92:CNF_MatrixCell,CNF_MatrixCell_QuickUpgrade,CNF_MatrixCell_Renew,CNF_MatrixCell2Delivery,CNF_MatrixCell2FlexContract,CNF_MatrixCellDocument,CNF_MatrixCellInfo,CNF_MatrixCellPermission,CNF_MatrixCellTranslation;;'

    DECLARE Model_Cursor CURSOR LOCAL FOR
                   select  substring(Value, 9, CharIndex('-', Value) - 9) as SubModel,
                           substring(Value, CharIndex('-', Value) + 1, (CharIndex(':', Value) - CharIndex('-', Value) -1)) as SubModelID,
                           substring(Value, CharIndex(':', Value) + 1, Len(Value)) as Tables,
                           UPPER(substring(Value, 1, CharIndex('-', Value) - 1)) as Code
                      from dbo.Split(@subModels, ';') test
                     where value &amp;#60;&amp;#62; ''

    OPEN Model_Cursor

    FETCH NEXT FROM Model_Cursor INTO
                    @SubModel,
                    @SubModelID,
                    @Tables,
                    @Code

    WHILE @@FETCH_STATUS = 0
    BEGIN
          SET @DBGroupId = (Select COALESCE(DBGroupId, 0) from CNF_DBGroup where SubModelId = @subModelId)

          IF @DBGroupId &amp;#62; 0
          BEGIN
             Update CNF_DBGroup set Active = 1 where SubModelId = @subModelId
          END
          ELSE
          BEGIN
             Insert Into CNF_DBGroup (SubModelId, Code, Name, SystemDefined, Enabled, Active, Last_DateTime_Log)
             VALUES (@subModelId, @Code, @SubModel, 1, 1, 1, GETDATE())

             SET @DBGroupId = SCOPE_IDENTITY()
          END

          DECLARE Table_Cursor CURSOR LOCAL FOR
              select ISNULL(CNF_DBTable.DbTableID, 0) as DBTABLEID
              from dbo.Split(@Tables, ',') test
                  LEFT JOIN CNF_DBTable                        on cnf_dbtable.tablename = Test.Value
                where value &amp;#60;&amp;#62; ''
            OPEN Table_Cursor

            FETCH NEXT FROM Table_Cursor INTO
                            @DbTableID

            WHILE @@FETCH_STATUS = 0
            BEGIN
                 IF @DBTableId &amp;#62; 0
                 BEGIN
                      SET @DBTable2DBGroupId = (Select COALESCE(DBTable2DBGroupId, 0) from CNF_DBTable2DBGroup where DBGroupId = @DBGroupId and DBTableId = @DBTableId)

                      IF @DBTable2DBGroupId &amp;#62; 0
                      BEGIN
                           Update CNF_DBTable2DBGroup set Active = 1 where DBTable2DBGroupId = @DBTable2DBGroupId
                      END
                      ELSE
                      BEGIN
                           Insert Into CNF_DBTable2DBGroup(DBTableId, DBGroupId, SystemDefined, Enabled, Active, Last_DateTime_Log)
                           VALUES (@DBTableId, @DBGroupId, 1, 1, 1, GETDATE())
                      END
                 END

                 FETCH NEXT FROM Table_Cursor INTO
                             @DbTableID

            END
            CLOSE Table_Cursor;
            DEALLOCATE Table_Cursor;

            FETCH NEXT FROM Model_Cursor INTO
                                  @SubModel,
                                  @SubModelID,
                                  @Tables,
                                  @Code
     END
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>1</ExecuteOnCreate><SqlScriptAK>E07FF73A2AAE4B2DA7BA098DF802B2FD</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_SubModel_To_DBGroup</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>4</Version><SQL>Create PROCEDURE [dbo].[otn_sp_SubModel_To_DBGroup]
AS
BEGIN
    Declare @SubModels varchar(max)
    Declare @DBGroupId Integer
    Declare @DBTableId integer
    Declare @DBTable2DBGroupId Integer
    Declare @SubModel varchar(Max)
    Declare @Code varchar(Max)
    Declare @SubModelID int
    Declare @Tables varchar(max)

    Declare @Temp table (Oridinal int,
	                        Value varchar(max)
                         )

    delete from CNF_DBTable2DBGroup where SystemDefined = 1    
    delete from CNF_DBGroup where SystemDefined = 1    

    update cnf_dbtable set groupnames = null    

    SET @SubModels ='BOS_GRP_Event-88:CNF_Event,CNF_Event_Permission,CNF_Notification,RES_CNF_Event;BOS_GRP_Performance-90:CNF_EnvelopeCapacity,CNF_Performance,CNF_Performance_Permission,CNF_Performance_SaleValidity,CNF_PerformanceFilter,CNF_SpaceStructure,SEAT_CNF_SpaceStructureSeat,CNF_Capacity,CNF_Seat,RES_CNF_Performance;BOS_GRP_Performance Events Categories-91:CNF_PerformanceCategory,CNF_PerformanceCategoryValidity;BOS_GRP_Subscription-93:CNF_Subscription,CNF_Subscription2Performance;BOS_GRP_Product Upsell-94:CNF_UpSell,CNF_UpSell_Permission,CNF_UpSell_Validity,CNF_Upsell2MatrixCell;BOS_GRP_Suggestive Sell-95:CNF_SuggestiveSell,CNF_SuggestiveSell_Permission,CNF_SuggestiveSell2Event,CNF_SuggestiveSell2EventCategory,CNF_SuggestiveSell2MatrixCell,CNF_SuggestiveSell2StatisticalGroup;BOS_GRP_Entitlement Components-96:CNF_Attribute,CNF_AttributeTemplate,CNF_Attribute_SaleValidity,CNF_AttributeSet,CNF_AttributeSetDetail;BOS_GRP_Price Lists-97:CNF_PriceList;BOS_GRP_Envelopes-98:CNF_Envelope,CNF_Envelope_Permission,CNF_EnvelopeCapacity;BOS_GRP_Seat Categories-99:CNF_SeatCategory,CNF_SeatCategory_Permission;BOS_GRP_Shopcart Validation-100:CNF_ShopCartValidation,CNF_ShopCartValidation_Permission,CNF_ShopCartValidationItem,CNF_ShopCartValidationItem2Event,CNF_ShopCartValidationItem2MatrixCell,CNF_ShopCartValidationItem2StatisticalGroup;BOS_GRP_External Ticket Ranges-102:CNF_ExternalTicketRange;BOS_GRP_Ticket Package Groups-103:CNF_TicketPackageGroup,CNF_TicketPackageGroupPermission;BOS_GRP_Payment Methods-104:CNF_PaymentMethod,CNF_MultiLanguage;BOS_GRP_Payment Cards-105:CNF_PaymentCard,CNF_PaymentCardCode,CNF_PaymentCardRange;BOS_GRP_Account Restriction-106:CNF_AccountRestriction,CNF_AccountRestriction2Account,CNF_AccountRestriction2MatrixCell;BOS_GRP_Accounts COA-107:COA_CNF_Account;BOS_GRP_Revenue Recognition Rules-108:COA_CNF_AccountConfig,RR_CNF_Product,RR_CNF_RevenueRecognitionRule,RR_CNF_RevenueRecognitionRuleSchedule;BOS_GRP_Cost Centers-109:CNF_CostCenter;BOS_GRP_Statistical Group-110:CNF_StatisticalGroup;BOS_GRP_History Log Tables-111:CNF_DBColumn,CNF_DBTable;BOS_GRP_System-112:CNF_LedgerAccount;BOS_GRP_Documents-113:CNF_DocRepository,CNF_DocTemplate,CNF_DocTemplate_Permission,CNF_DocTemplate2Device,CNF_DocTemplate2IdentifierType,CNF_DocTemplateParam,CNF_DocTemplateParamValue,CNF_DocTermsAndConditions;BOS_GRP_Rounding Rules-114:CNF_RoundingRule;BOS_GRP_Languages-115:CNF_Language;BOS_GRP_External Media Type-116:CNF_ExternalMediaType,CNF_ExternalStoredInfo;BOS_GRP_External Card Type-117:CNF_ExternalCardType,CNF_ExtCardTypePermission;BOS_GRP_Projection-118:ADM_AccessConfiguration,CNF_Location,CNF_Projection;BOS_GRP_Calendar-119:CNF_Calendar,CNF_CalendarTimeFrame,CNF_CalendarTimeFrameItem,CNF_CalendarValidity;BOS_GRP_Currency-120:CNF_Currency,CNF_CurrencyDetail;BOS_GRP_Task Scheduler-121:CNF_Scheduler;BOS_GRP_System Events-122:CNF_Trigger;BOS_GRP_Marketing Survey-123:CNF_Survey;BOS_GRP_Fund Types-124:CNF_FundType,CNF_FundCash,CNF_FundItem;BOS_GRP_Taxes-125:CNF_Tax,CNF_TaxBracket;BOS_GRP_Tax Packages-126:CNF_TaxPackage,CNF_Tax2Package;BOS_GRP_Payment Card Bin Ranges-127:CNF_PaymentCardRange;BOS_GRP_Merchant Accounts-128:CNF_Merchant,CNF_MerchantTable;BOS_GRP_Invoicing-129:CNF_Invoice;BOS_GRP_Map Views-130:CNF_Site,CNF_VenueMap,CNF_VenueMapItem;BOS_GRP_System-131:CNF_System;BOS_GRP_Sites-132:CNF_Right,CNF_Site,DATA_Right,CNF_Site_LoginPermission;BOS_GRP_Operating Area-133:CNF_OperatingArea,CNF_Right,DATA_Right;BOS_GRP_Workstations-134:CNF_Right,CNF_Workstation,CNF_WorkstationDevice,DATA_Right,ADM_AccessPoint,CNF_AccessFilter,CNF_Scheduler;BOS_GRP_Locations-135:ADM_Gate,CNF_Location,CNF_LocationMatrix,CNF_LocationMatrix2MatrixCell,CNF_LocationMatrixPrice,CNF_LocationRoute,CNF_LocationRoute2Gate,CNF_SeatLayout,CNF_SeatLayout2Template,CNF_SeatLayoutItem,CNF_SeatPerformance,CNF_SeatTemplate;BOS_GRP_Gates-136:ADM_Gate,CNF_AccessFilter,CNF_TravelMatrix,CNF_TravelTime,ADM_Gate2AccessConfiguration;BOS_GRP_Access Points-137:ADM_AccessPoint,CNF_Notification;BOS_GRP_Roles-138:CNF_Right,CNF_User2Group,CNF_UserGroup,DATA_Right;BOS_GRP_Users-139:CNF_Right,CNF_User,DATA_Right,CNF_User2Group;BOS_GRP_Requirements-140:RES_CNF_Requirement,RES_CNF_RequirementGroup,RES_CNF_RequirementTemplate,RES_CNF_RequirementTemplateItem,RES_CNF_RequirementTemplateSet;BOS_GRP_Matrixcell-141:CNF_MatrixCell,CNF_MatrixCell_QuickUpgrade,CNF_MatrixCell_Renew,CNF_MatrixCell2Delivery,CNF_MatrixCell2FlexContract,CNF_MatrixCellDocument,CNF_MatrixCellInfo,CNF_MatrixCellPermission,CNF_MatrixCellTranslation,CNF_MatrixDimension,CNF_CostCenter_Validity,CNF_AlternativeCodes,CNF_StatisticalGroupValidity,CNF_MultiLanguage,RES_CNF_MatrixCell;BOS_GRP_Accounts-142:DATA_Account,DATA_AccountFinancial,DATA_AccountRelationship,DATA_DmgData,DATA_DmgData_Translate,CNF_Commission2Account,CNF_IncentiveTicket,CNF_MultiLanguage;BOS_GRP_Matrixsheet-143:CNF_MatrixSheet,CNF_MatrixSheet_SaleValidity;BOS_GRP_Account Types-144:COA_CNF_AccountType;BOS_GRP_Exchange Rates-145:CNF_ExchangeRate;BOS_GRP_Incentive-146:CNF_PAY,CNF_Pay_MatrixCell;BOS_GRP_History Log Groups-147:CNF_DBGroup,CNF_DBTable2DBGroup;BOS_GRP_Data Mask Categories-148:CNF_DmgCategory,CNF_DmgCategory_Permission,CNF_DmgCategory2CRMTemplate,CNF_DmgCategory2Mask;BOS_GRP_Data Masks-149:CNF_DataMask,CNF_DataMaskTranslation,CNF_Mask,CNF_Mask_Utility,CNF_CRMTemplate,CNF_CRMTemplateDetail,CNF_Geo;BOS_GRP_Mask Tables-150:CNF_MaskTable,CNF_MaskTableItem,CNF_MaskTableItem_Translation;BOS_GRP_Sale Board Management-151:CNF_BoardPackage,CNF_BoardFav,ARC_Document;BOS_GRP_Device Manager-153:CNF_Device,CNF_DonationForm,CNF_Driver,CNF_Right,DATA_Right;BOS_GRP_Unit of Measure-154:STOCK_CNF_Um;BOS_GRP_Warehouse-155:STOCK_CNF_Warehouse,STOCK_CNF_WarehouseAssign;BOS_GRP_Food Merchandise-156:STOCK_CNF_Product,STOCK_CNF_ProductBarcodes,STOCK_CNF_ProductUm,STOCK_CNF_ProductCategory,STOCK_CNF_ProductCombo,STOCK_CNF_ProductComboChoice,CNF_Product,CNF_ProductLinker,CNF_ProductValidity,CNF_ProductValidity2Event;BOS_GRP_Table No longer used / Future Development-157:CNF_SaleRestriction,CNF_SaleRestriction2MatrixCell,CNF_SaleRestrictionValidity,CNF_Catalog,CNF_Catalog2Product,CNF_Category,CNF_Category2Product,CNF_Combo,CNF_CustomColor,CNF_DeliveryMode,CNF_EnvelopeRight,CNF_MembershipCard,CNF_EventFilter,CNF_FiscalYear,CNF_PerformanceSeat,CNF_Producer,CNF_SALTO_PERIPHERALS,CNF_SALTO_ZONE,CNF_SeasonalRule,CNF_TimeSlot,CNF_Upgrade,CNF_Tax2Location;BOS_GRP_License-158:CNF_License;BOS_GRP_Schedule Type-160:RES_ScheduleType,RES_CNF_ScheduleTypeAllowed;BOS_GRP_Requirements Template-161:RES_CNF_RequirementType;BOS_GRP_Promotions and Fees-162:CNF_Promotion,CNF_Promotion_Quota,CNF_PromotionAssociation,CNF_PromotionEvent,CNF_PromotionItem,CNF_PromotionItem_Quota,CNF_PromotionItemRule,CNF_PromotionPermission,CNF_PromotionProduct,CNF_PromotionProductCategory,CNF_PromotionValidity,CNF_StatisticalGroup2Promotion;BOS_GRP_Stores-163:CNF_Event,CNF_PriceTable;BOS_GRP_Delivery-164:CNF_Delivery,CNF_Delivery_Permission;BOS_GRP_Installment Plan Templates-165:CNF_FlexContract,CNF_FlexContractFee,CNF_FlexPlanTemplate,CNF_Notification;BOS_GRP_Manage Passwords Dictionary-166:CNF_PswDictionary;BOS_GRP_Renewal Plan Templates-167:CNF_RenewalContract;BOS_GRP_Resource-168:RES_CNF_Resource,RES_CNF_ResourceContract,RES_CNF_ResourcePriority,RES_CNF_ResourceRequirement,RES_CNF_ResourceRequirementAllowed,RES_CNF_ResourceType,RES_CNF_ResourceType_Requirement;;'

    DECLARE Model_Cursor CURSOR LOCAL FOR
                   select  substring(Value, 9, CharIndex('-', Value) - 9) as SubModel,
                           substring(Value, CharIndex('-', Value) + 1, (CharIndex(':', Value) - CharIndex('-', Value) -1)) as SubModelID,
                           substring(Value, CharIndex(':', Value) + 1, Len(Value)) as Tables,
                           UPPER(substring(Value, 1, CharIndex('-', Value) - 1)) as Code
                      from dbo.Split(@subModels, ';') test
                     where value &amp;#60;&amp;#62; ''

    OPEN Model_Cursor

    FETCH NEXT FROM Model_Cursor INTO
                    @SubModel,
                    @SubModelID,
                    @Tables,
                    @Code

    WHILE @@FETCH_STATUS = 0
    BEGIN
          SET @DBGroupId = (Select COALESCE(DBGroupId, 0) from CNF_DBGroup where SubModelId = @subModelId)

          IF @DBGroupId &amp;#62; 0
          BEGIN
             Update CNF_DBGroup set Active = 1 where SubModelId = @subModelId
          END
          ELSE
          BEGIN
             Insert Into CNF_DBGroup (SubModelId, Code, Name, SystemDefined, Enabled, Active, Last_DateTime_Log)
             VALUES (@subModelId, @Code, @SubModel, 1, 1, 1, GETDATE())

             SET @DBGroupId = SCOPE_IDENTITY()
          END

          DECLARE Table_Cursor CURSOR LOCAL FOR
              select ISNULL(CNF_DBTable.DbTableID, 0) as DBTABLEID
              from dbo.Split(@Tables, ',') test
                  LEFT JOIN CNF_DBTable                        on cnf_dbtable.tablename = Test.Value
                where value &amp;#60;&amp;#62; ''
                and cnf_dbtable.logged = 1
                     
            OPEN Table_Cursor

            FETCH NEXT FROM Table_Cursor INTO
                            @DbTableID

            WHILE @@FETCH_STATUS = 0
            BEGIN
                 IF @DBTableId &amp;#62; 0
                 BEGIN
                      SET @DBTable2DBGroupId = (Select COALESCE(DBTable2DBGroupId, 0) from CNF_DBTable2DBGroup where DBGroupId = @DBGroupId and DBTableId = @DBTableId)

                      IF @DBTable2DBGroupId &amp;#62; 0
                      BEGIN
                           Update CNF_DBTable2DBGroup set Active = 1 where DBTable2DBGroupId = @DBTable2DBGroupId
                      END
                      ELSE
                      BEGIN
                           Insert Into CNF_DBTable2DBGroup(DBTableId, DBGroupId, SystemDefined, Enabled, Active, Last_DateTime_Log)
                           VALUES (@DBTableId, @DBGroupId, 1, 1, 1, GETDATE())
                      END
                 END

                 update cnf_dbtable   
                    set GroupNames = (SELECT stuff((     
                      SELECT ', ' + Name             
                        from CNF_DBTable2DBGroup         
                              INNER JOIN CNF_DBGroup			on cnf_dbgroup.dbgroupid = CNF_DBTable2DBGroup.dbgroupid   
                       where dbtableid = @DbTableID        
                          FOR XML PATH('')         
                          ), 1, 2, ''))            
             
           where dbtableid = @DbTableID     
                 FETCH NEXT FROM Table_Cursor INTO
                             @DbTableID

            END
    
            CLOSE Table_Cursor;
            DEALLOCATE Table_Cursor;

            FETCH NEXT FROM Model_Cursor INTO
                                  @SubModel,
                                  @SubModelID,
                                  @Tables,
                                  @Code
     END
END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>1</ExecuteOnCreate><SqlScriptAK>74D7EF144E91412884F5ADBE5C706559</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_ui_EnableDisbleTrigger_HistoryLog</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>2</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_ui_EnableDisbleTrigger_HistoryLog] 
AS
BEGIN
  DECLARE @GlobalLogEnabled as int;
  DECLARE @TableId as int;
  DECLARE @TableName as VarChar(100);

-- Declare a cursor in order to read the current status historylog
  DECLARE cursor_System CURSOR LOCAL STATIC FORWARD_ONLY FOR
  SELECT BOSHistoryLogEnabled FROM CNF_System

  OPEN cursor_System;
  FETCH NEXT FROM cursor_System INTO @GlobalLogEnabled;
  CLOSE cursor_System;
  DEALLOCATE cursor_System;

-- declare a cursor in order to read all table with log enabled
  DECLARE cursor_DBTable CURSOR LOCAL STATIC FORWARD_ONLY FOR
  SELECT DBTableId,TableName FROM CNF_DBTable where Active = 1
  OPEN cursor_DBTable;

  FETCH NEXT FROM cursor_DBTable INTO @TableId, @TableName;

  WHILE @@FETCH_STATUS = 0
  BEGIN
    IF UPPER(@TableName) &amp;#60;&amp;#62; 'CNF_LICENSE'
      IF EXISTS (SELECT * FROM sysobjects WHERE type = 'TR' AND name = @TableName + '_CT')
        IF @GlobalLogEnabled = 0
          EXEC('DISABLE TRIGGER ' + @TableName + '_CT ON [' + @TableName + ']'); 
        ELSE
          EXEC('ENABLE TRIGGER ' + @TableName + '_CT ON [' + @TableName + ']'); 

    FETCH NEXT FROM cursor_DBTable INTO @TableId, @TableName;

  END

  CLOSE cursor_DBTable;
  DEALLOCATE cursor_DBTable;
END
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>2371ED7A0AAD490E9B780341800EC824</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_ui_GetCounter</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE PROCEDURE [dbo].[otn_sp_ui_GetCounter] 
 -- Add the parameters for the stored procedure here
 @CounterType smallint,
 @IdentifierAK varchar(32),
 @ReferenceTime varchar(32),
 @Counter integer output  
AS
BEGIN

insert into DATA_Counter (CounterType, IdentifierAK, ReferenceTime, Counter)
select @CounterType, @IdentifierAK, IsNull(@ReferenceTime,'Never'), 0
where
0 = (select count(*) 
    from DATA_Counter with (HOLDLOCK) 
    where CounterType = @CounterType and IdentifierAK = @IdentifierAK and&amp;#160;IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER'))

update DATA_Counter with (HOLDLOCK)&amp;#160;
set&amp;#160;@Counter = Counter = Counter +1&amp;#160;
where&amp;#160;CounterType = @CounterType and IdentifierAK = @IdentifierAK and&amp;#160;IsNull(@ReferenceTime,'NEVER') = IsNull(ReferenceTime,'NEVER')

END</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>071FAD0C8907424FB79BAA111DEBBEA8</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_OnEncodedTickets</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnEncodedTickets] 
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
SET NOCOUNT ON
--Take items that where encoded today and remove from Encoded and move to suspense.


    Declare @EncodedTicketsId integer = 21
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @DepositRRRId Integer
	Declare @DepositCOAAccountId Integer
	Declare @DepositRRCalcTypeTrigger Integer
	Declare @DepositRRCalcTypeWhere Integer
	Declare @DepositRRCalcTypeMethod Integer
	Declare @DepositCOAAccountConfigId Integer
	Declare @DepositCOAAccountTypeId Integer
	Declare @DepositPercentage float
	Declare @DepositDays Integer
	Declare @DepositPrice float
	Declare @DepositCOAAccount_Percentage Float
	Declare @DepositRemainingValues Integer
	Declare @DepositRRCOAAccountingType Integer
	Declare @DepositAccountingType Integer

	Declare @TicketRRRId Integer
	Declare @TicketCOAAccountId Integer
	Declare @TicketRRCalcTypeTrigger Integer
	Declare @TicketRRCalcTypeWhere Integer
	Declare @TicketRRCalcTypeMethod Integer
	Declare @TicketCOAAccountConfigId Integer
	Declare @TicketCOAAccountTypeId Integer
	Declare @TicketPercentage float
	Declare @TicketDays Integer
	Declare @TicketPrice float
	Declare @TicketCOAAccount_Percentage Float
	Declare @TicketRemainingValues Integer
	Declare @TicketRRCOAAccountingType Integer
	Declare @TicketAccountingType Integer

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	
	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	select @TicketRRRId = RevenueRecognitionRuleId
	  from RR_CNF_RevenueRecognitionRule
	  where rrcalctypeTrigger = 21


	select @RRTransDateType = RRTransDateType
      from cnf_system

	select TOP 1	@DepositRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@DepositRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@DepositRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@DepositRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@DepositCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@DepositCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@DepositCOAAccountId = coa_cnf_account.COAAccountId,
					@DepositPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@DepositDays = RR_CNF_RevenueRecognitionRule.Days,
					@DepositPrice = COA_CNF_AccountConfig.Price,
					@DepositCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@DepositRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@DepositRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 5
	  and RR_CNF_RevenueRecognitionRule.Enabled = 1


	if @DepositRRRId is null
	Begin
				select TOP 1	@DepositRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
									@DepositRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
									@DepositRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
									@DepositRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
									@DepositCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
									@DepositCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
									@DepositCOAAccountId = coa_cnf_account.COAAccountId,
									@DepositPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
									@DepositDays = RR_CNF_RevenueRecognitionRule.Days,
									@DepositPrice = COA_CNF_AccountConfig.Price,
									@DepositCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
									@DepositRemainingValues = COA_CNF_AccountConfig.RemainingValues,
									@DepositRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
					from coa_cnf_account WITH(NOLOCK)
						INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
						INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
						INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
					where RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 1
					  and RR_CNF_RevenueRecognitionRule.Enabled = 1

	END


	select TOP 1	@SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
					@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
					@SuspendPrice = COA_CNF_AccountConfig.Price,
					@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID


	select TOP 1    @TicketRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
					@TicketRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
					@TicketRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
					@TicketRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
					@TicketCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
					@TicketCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
					@TicketCOAAccountId = coa_cnf_account.COAAccountId,
					@TicketPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
					@TicketDays = RR_CNF_RevenueRecognitionRule.Days,
					@TicketPrice = COA_CNF_AccountConfig.Price,
					@TicketCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
					@TicketRemainingValues = COA_CNF_AccountConfig.RemainingValues,
					@TicketRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	
	where RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = @TicketRRRId
	  and coa_cnf_account.Enabled = 1
	  and COA_CNF_AccountConfig.Enabled = 1



BEGIN
		
	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[TicketID]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
					select distinct *
					from (
						select		@SuspendCOAAccountId COAID,
									@SuspendRRRId RRID,
									@SuspendRRCalcTypeWhere RRWHERE,
									@SuspendRRCalcTypeMethod RRMETHOD,
									@SuspendCOAAccountConfigId RRCONFIG,
									@SuspendCOAAccountTypeId COATYPE,
									data_transaction.transactionid, 
									data_transaction.saleid,
									DATA_SaleItem.saleitemid,
									DATA_SaleItem.Matrixcellid,
									CNF_MatrixCell.MatrixSheetid,
									data_transaction.Siteid,
									p.ticketid,
									data_transaction.OperatingAreaId,
									data_transaction.Workstationid,
									data_transaction.UserGroupid,
									data_transaction.UserId,
									@BatchDate BatchDate,
									ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
									ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
									ISNULL(DATA_SaleItem.UnitRecharge, 0) charge,
									ISNULL(DATA_SaleItem.UnitRecharge, 0) charge2,
									@SuspendPrice Price,
									@SuspendCOAAccount_Percentage  Percentage,
									@SuspendRemainingValues RValues,				
									ABS(ISNULL(DATA_SaleItem.UnitRecharge, 0)) as revenueamount,
									case when data_saleitem.quantity &amp;#60; 0 then 1
									     else @SuspendRRCOAAccountingType 
									  end Accountingtype,
									@SuspendRRCalcTypeTrigger  RTRIGGER,
									@SuspendPercentage PERC,
									1 rrdays,
									CNF_AttributeSet.Attributeids
	   
							from DATA_Sale WITH(NOLOCK)
								inner JOIN data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId = DATA_Sale.PaidTransactionId
								INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId
								inner JOIN DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
								inner JOIN CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
								inner JOIN CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
								inner JOIN CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
								inner JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
											   from data_saleitem2ticket WITH(NOLOCK)
												INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
												where data_saleitem2ticket.operationtype = 1
												  and data_ticket.voidtype not in (104, 125)
											) p									on p.S2TSaleitemid = data_saleitem.saleitemid

					
					where DATA_Sale.Paid = 1
					    and DATA_Sale.Encoded = 1 
					    and 1 = case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
									  when data_transaction.transactiontype in (18, 20, 22, 123) and data_saleitem.quantity &amp;#60; 0 then 1
									  when DATA_Transaction.TransactionType IN (10, 42, 43, 49, 31, 48, 52) then 1
									  when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16,  9) then 1				                
									  when data_transaction.transactiontype in (13, 34) then 1
									  else 0
							     end 
						and DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; 0
						and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
						and DATA_Sale.PaidTransactionId &amp;#60;&amp;#62; DATA_Sale.EncodedTransactionId	
						and ((@RRTransDateType = 0 and DT_Encoded.fTransactionDate = @BatchDate)
							OR (@RRTransDateType = 1 and convert(date, DT_Encoded.TransactionDate) = @BatchDate))
						and ((data_transaction.transactionid in (select data_payment.transactionid
																   from data_payment WITH(NOLOCK)
																  where PaymentStatus = 1
																    and DATA_Payment.TransactionId = DATA_Transaction.transactionid
																))
						and (data_transaction.totalamount &amp;#60;&amp;#62; 0))
						and DATA_Sale.SaleId in (select DATA_Sale.Saleid
												  from DATA_Sale WITH(NOLOCK)
													INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Sale.PaidTransactionId
													INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId

												where ((DT_Encoded.FTransactionDate = @BatchDate) and (DATA_Transaction.FTransactionDate &amp;#60;&amp;#62; @BatchDate))
												  and DATA_Sale.SaleId in (select SaleID
																			  from (select saleid, 
																						   round(sum(case when AccountingType = 1 then RevenueAmount else 0 end), 2) Debit,
																						   round(sum(case when AccountingType = 2 then RevenueAmount else 0 end), 2) credit
																					from rr_data_revenue WITH(NOLOCK)
																					where rr_data_revenue.RRCalcTypeTrigger in (@EncodedTicketsId)
																					group by saleid
																					)p
																			  where (Debit - credit) &amp;#60;&amp;#62; 0
																			)
								)

					UNION ALL

						select		@SuspendCOAAccountId COAID,
										@SuspendRRRId RRID,
										@SuspendRRCalcTypeWhere RRWHERE,
										@SuspendRRCalcTypeMethod RRMETHOD,
										@SuspendCOAAccountConfigId RRCONFIG,
										@SuspendCOAAccountTypeId COATYPE,
										data_transaction.transactionid, 
										data_transaction.saleid,
										DATA_SaleItem.saleitemid,
										DATA_SaleItem.Matrixcellid,
										CNF_MatrixCell.MatrixSheetid,
										data_transaction.Siteid,
										p.ticketid,
										data_transaction.OperatingAreaId,
										data_transaction.Workstationid,
										data_transaction.UserGroupid,
										data_transaction.UserId,
										@BatchDate BatchDate,
										ISNULL(case when ((p.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
										DATA_SaleItem.UnitPrice,
										DATA_SaleItem.UnitRecharge charge,
										DATA_SaleItem.UnitRecharge charge2,
										@SuspendPrice Price,
										@SuspendCOAAccount_Percentage  Percentage,
										@SuspendRemainingValues RValues,				
										ABS(ISNULL(DATA_SaleItem.UnitRecharge, 0)) as revenueamount,
										case when data_saleitem.quantity &amp;#60; 0 then 1
											 else @SuspendRRCOAAccountingType 
										  end Accountingtype,
										@SuspendRRCalcTypeTrigger  RTRIGGER,
										@SuspendPercentage PERC,
										1 rrdays,
										CNF_AttributeSet.Attributeids
	   
								from DATA_Sale WITH(NOLOCK)
									inner JOIN data_transaction WITH(NOLOCK)			 on data_transaction.TransactionId = DATA_Sale.voidTransactionId
									INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)	 ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId
									inner JOIN DATA_SaleItem WITH(NOLOCK)				 on data_saleitem.saleid = data_sale.saleid
									inner JOIN CNF_MatrixCell WITH(NOLOCK)				 on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
									inner JOIN CNF_MatrixSheet WITH(NOLOCK)				 on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
									inner JOIN CNF_AttributeSet WITH(NOLOCK)				 on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
									inner JOIN (select data_ticket.*, data_saleitem2ticket.saleitemid as S2TSaleitemid
												   from data_saleitem2ticket WITH(NOLOCK)
													INNER JOIN data_ticket WITH(NOLOCK)			ON data_ticket.ticketid = data_saleitem2ticket.ticketid 
													where data_saleitem2ticket.operationtype = 1
													  and data_ticket.voidtype not in (104, 125)
												) p									on p.S2TSaleitemid = data_saleitem.saleitemid

					
						where DATA_Sale.Paid = 1
							and DATA_Sale.Encoded = 1 
							and 1 = case  when data_transaction.transactiontype in (5, 30) and data_saleitem.quantity &amp;#60; 0 then 1
										  else 0
									 end 
							and DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; 0
							and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
							and DATA_Sale.PaidTransactionId &amp;#60;&amp;#62; DATA_Sale.EncodedTransactionId	
							and ((@RRTransDateType = 0 and DT_Encoded.fTransactionDate = @BatchDate)
								OR (@RRTransDateType = 1 and convert(date, DT_Encoded.TransactionDate) = @BatchDate))
							and ((data_transaction.transactionid in (select data_payment.transactionid
																	   from data_payment WITH(NOLOCK)
																	  where PaymentStatus = 1
																	    and DATA_Payment.TransactionId = DATA_Transaction.transactionid
																	))
							and (data_transaction.totalamount &amp;#60;&amp;#62; 0))
							and DATA_Sale.SaleId in (select DATA_Sale.Saleid
												  from DATA_Sale WITH(NOLOCK)
													INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Sale.PaidTransactionId
													INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId

												where ((DT_Encoded.FTransactionDate = @BatchDate) and (DATA_Transaction.FTransactionDate &amp;#60;&amp;#62; @BatchDate))
												  and DATA_Sale.SaleId in (select SaleID
																			  from (select saleid, 
																						   round(sum(case when AccountingType = 1 then RevenueAmount else 0 end), 2) Debit,
																						   round(sum(case when AccountingType = 2 then RevenueAmount else 0 end), 2) credit
																					from rr_data_revenue WITH(NOLOCK)
																					where rr_data_revenue.RRCalcTypeTrigger in (@EncodedTicketsId)
																					group by saleid
																					)p
																			  where (Debit - credit) &amp;#60;&amp;#62; 0
																			)
								)


					)p

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  COAAccountId,
						RevenueRecognitionRuleId,
						RRCalcTypeWhere,
						RRCalcTypeMethod,
						COAAccountConfigId,
						COAAccountType,
						transactionid, 
						saleid,
						Ticketid,
						saleitemid,
						Matrixcellid,
						MatrixSheetid,
						Siteid,
						OperatingAreaId,
						Workstationid,
						UserGroupid,
						UserId,
						calcdate,
						Quantity,
						UnitPrice,
						totalamount,
						NetAmount,
						suspendprice,
						percentage,
						remainingValues,
						Revenueamount,
						Accountingtype,
						rrTrigger,
						suspercentage,
						suspendday,
						Attributeids
		  from (
----14
			select distinct 
				         @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						DT_Encoded.transactionid, 
						DT_Encoded.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						DT_Encoded.Siteid,
						DT_Encoded.OperatingAreaId,
						DT_Encoded.Workstationid,
						DT_Encoded.UserGroupid,
						DT_Encoded.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ABS(ISNULL((case when DATA_Transaction.TransactionType IN (13, 34) then DATA_Transaction.Revenue
						
								when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
														then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType in (3, 4) and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitPrice))) 
								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType &amp;#60;&amp;#62; 2 and 
											ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end))
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) = 0
							   							then ABS(((DATA_SaleItem.UnitrawPrice) - DATA_SaleItem.UnitTaxes)) 

								when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; DATA_SaleItem.UnitrawPrice and DATA_SaleItem.ProductTaxType = 2
							   							then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes))  - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																																from data_saleitemrule WITH(NOLOCK)
																																	INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																	INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																	INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																																where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																	and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) 
							 
							 
								when data_ticket.ticketid is not null then
										ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
															from data_saleitemrule WITH(NOLOCK)
																INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
								
								else (data_saleitem.totalamount - data_saleitem.totaltaxes)   - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
														from data_saleitemrule WITH(NOLOCK)
															INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0) 

								end), 0)) as Revenueamount,
						case when DT_Encoded.TransactionType IN (13) then 1
						     when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = DATA_Sale.PaidTransactionId
					INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId
					LEFT  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					LEFT  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					LEFT  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					LEFT  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					LEFT  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid															
											where DATA_Ticket.VoidType not in (104, 125)
								)data_ticket			on data_ticket.saleitemid = data_saleitem.saleitemid 
															and 1 = case when data_transaction.transactiontype in (18, 20, 22) and data_ticket.OperationType in (2) then 1
																			when data_transaction.transactiontype in (9) and data_ticket.OperationType in (15)  then 1
																			when data_transaction.transactiontype in (9, 14, 16, 122, 5, 13, 34) and data_ticket.OperationType in (1, 11)  then 1																							 
																			else 0
																	end 

				where DATA_Sale.Paid = 1
				  and (((1 = case  when data_transaction.transactiontype in (9, 14, 16) and data_saleitem.quantity &amp;#62; 0 then 1
								when data_transaction.transactiontype in (18, 20, 22, 123) and data_saleitem.quantity &amp;#60; 0 then 1
								when data_transaction.transactiontype in (122) and data_saleitem.ItemTransactionType in (14, 16, 7, 9) then 1				                
								when data_transaction.transactiontype in (13, 34) then 1
								else 0
						end) and (DATA_Sale.Encoded = 1)) or ((DATA_Sale.Encoded = 0) and (data_transaction.transactiontype in (13, 18, 20, 22, 34, 38)))) 
				  and DATA_Transaction.TransactionType not in (5, 30)
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and ((data_transaction.transactiontype in (9, 13, 14, 16, 18, 20, 22, 34, 38, 119, 123)) or ((data_transaction.transactiontype in (122)) and (data_saleitem.ItemTransactionType in (9, 14, 16, 18, 20, 22, 119, 123))))
				  and data_transaction.transactionstatus in (5, 30)
				  and DATA_Sale.PaidTransactionId &amp;#60;&amp;#62; DATA_Sale.EncodedTransactionId	
				  and ((@RRTransDateType = 0 and DT_Encoded.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, DT_Encoded.TransactionDate) = @BatchDate))
				  and (data_transaction.transactionid in (select transactionid
																  from data_payment WITH(NOLOCK)
																 where PaymentStatus = 1
																   and data_transaction.transactionid = DATA_Payment.transactionid
																))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)) or (DATA_Transaction.TransactionType in (13, 34)))
													
						and DATA_Sale.SaleId in (select DATA_Sale.Saleid
												  from DATA_Sale WITH(NOLOCK)
													INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Sale.PaidTransactionId
													INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId

												where ((DT_Encoded.FTransactionDate = @BatchDate) and (DATA_Transaction.FTransactionDate &amp;#60;&amp;#62; @BatchDate))
												  and DATA_Sale.SaleId in (select SaleID
																			  from (select saleid, 
																						   round(sum(case when AccountingType = 1 then RevenueAmount else 0 end), 2) Debit,
																						   round(sum(case when AccountingType = 2 then RevenueAmount else 0 end), 2) credit
																					from rr_data_revenue WITH(NOLOCK)
																					where rr_data_revenue.RRCalcTypeTrigger in (@EncodedTicketsId)
																					group by saleid
																					)p
																			  where (Debit - credit) &amp;#60;&amp;#62; 0
																			)
								)

	
		UNION ALL


		select distinct 
				        @SuspendCOAAccountId as COAAccountId,
						@SuspendRRRId as RevenueRecognitionRuleId,
						@SuspendRRCalcTypeWhere as RRCalcTypeWhere,
						@SuspendRRCalcTypeMethod as RRCalcTypeMethod,
						@SuspendCOAAccountConfigId as COAAccountConfigId,
						@SuspendCOAAccountTypeId as COAAccountType,
						DT_Encoded.transactionid, 
						DT_Encoded.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						DT_Encoded.Siteid,
						DT_Encoded.OperatingAreaId,
						DT_Encoded.Workstationid,
						DT_Encoded.UserGroupid,
						DT_Encoded.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@SuspendPrice as suspendprice,
						@SuspendCOAAccount_Percentage as percentage,
						@SuspendRemainingValues as remainingValues,
						ISNULL((case when data_ticket.TicketId IS null and data_saleitem.ProductType = 1
													then ABS(((DATA_SaleItem.UnitPrice  - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))  * DATA_SaleItem.Quantity)
						
						
						
						
							when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
													then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
						     when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; 0  
							   						then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 
							 
							 
							 
							 
							 
							 
							 
							 
							else ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
														from data_saleitemrule WITH(NOLOCK)
															INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))

							end), 0) as Revenueamount,
						case when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @SuspendRRCOAAccountingType 
						 end Accountingtype,
						@SuspendRRCalcTypeTrigger as rrTrigger,
						@SuspendPercentage as suspercentage,
						@SuspendDays as suspendday,
						CNF_AttributeSet.Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)				on data_transaction.transactionid = data_sale.voidtransactionid
					INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId
					left  join DATA_SaleItem WITH(NOLOCK)			    	on DATA_SaleItem.saleid = data_transaction.saleid
					left  join CNF_MatrixCell WITH(NOLOCK)					on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left  join CNF_MatrixSheet WITH(NOLOCK)					on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left  join CNF_AttributeSet WITH(NOLOCK)				on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid	
										where DATA_Ticket.VoidType not in (104, 125)
											)data_ticket
								on data_ticket.saleitemid = ISNULL(data_saleitem.origSAleitemid, data_saleitem.saleitemid ) 
									and 1 = case when data_transaction.transactiontype in (5, 30) and data_ticket.OperationType in (1, 11)  then 1																							 
												 else 0
										     end 

				where DATA_Sale.Paid = 1
				  and DATA_Sale.Encoded = 1
				  and data_transaction.TransactionType IN (5, 30)
				  and data_saleitem.ItemTransactionType IN (5, 30)					
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactionstatus in (5, 30)
				  and DATA_Sale.PaidTransactionId &amp;#60;&amp;#62; DATA_Sale.EncodedTransactionId	
				  and ((@RRTransDateType = 0 and DT_Encoded.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, DT_Encoded.TransactionDate) = @BatchDate))
				  and ((data_transaction.transactionid in (select transactionid
														  from data_payment WITH(NOLOCK)
														 where PaymentStatus = 1
														   and data_transaction.transactionid = DATA_Payment.transactionid
														)))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)))
				  and DATA_Transaction.saleid not in (select SaleId
														from DATA_Transaction DT WITH(NOLOCK)
														where DT.SaleId = DATA_Transaction.SaleId
														  and DT.TransactionType in (12, 15)
													)

						and DATA_Sale.SaleId in (select DATA_Sale.Saleid
												  from DATA_Sale WITH(NOLOCK)
													INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Sale.PaidTransactionId
													INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId

												where ((DT_Encoded.FTransactionDate = @BatchDate) and (DATA_Transaction.FTransactionDate &amp;#60;&amp;#62; @BatchDate))
												  and DATA_Sale.SaleId in (select SaleID
																			  from (select saleid, 
																						   round(sum(case when AccountingType = 1 then RevenueAmount else 0 end), 2) Debit,
																						   round(sum(case when AccountingType = 2 then RevenueAmount else 0 end), 2) credit
																					from rr_data_revenue WITH(NOLOCK)
																					where rr_data_revenue.RRCalcTypeTrigger in (@EncodedTicketsId)
																					group by saleid
																					)p
																			  where (Debit - credit) &amp;#60;&amp;#62; 0
																			)
								)

		UNION ALL

		select distinct 
				         @DepositCOAAccountId as COAAccountId,
						@DepositRRRId as RevenueRecognitionRuleId,
						@DepositRRCalcTypeWhere as RRCalcTypeWhere,
						@DepositRRCalcTypeMethod as RRCalcTypeMethod,
						@DepositCOAAccountConfigId as COAAccountConfigId,
						@DepositCOAAccountTypeId as COAAccountType,
						DT_Encoded.transactionid, 
						DT_Encoded.saleid,
						data_ticket.ticketid,
						DATA_SaleItem.saleitemid,
						DATA_SaleItem.Matrixcellid,
						CNF_MatrixCell.MatrixSheetid,
						DT_Encoded.Siteid,
						DT_Encoded.OperatingAreaId,
						DT_Encoded.Workstationid,
						DT_Encoded.UserGroupid,
						DT_Encoded.UserId,
						@BatchDate as calcdate,
						ISNULL(case when ((data_ticket.ticketid is null) or (cnf_matrixsheet.producttype &amp;#60;&amp;#62; 1)) then data_saleitem.quantity else 1 end, 0) as Quantity,
						ISNULL(DATA_SaleItem.UnitPrice, 0) UnitPrice,
						ISNULL(DATA_SaleItem.UnitPrice, 0) totalamount,
						ISNULL(DATA_SaleItem.UnitPrice, 0) as NetAmount,
						@DepositPrice as Depositprice,
						@DepositCOAAccount_Percentage as percentage,
						@DepositRemainingValues as remainingValues,
						ISNULL((case when data_saleitem.ProductType &amp;#60;&amp;#62; 1 
													then ABS(((DATA_SaleItem.UnitPrice * DATA_SaleItem.Quantity) - DATA_SaleItem.TotalTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0))
						     when (data_ticket.ticketid is not null) and data_saleitem.UnitPrice &amp;#60;&amp;#62; 0  
							   						then ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
																															from data_saleitemrule WITH(NOLOCK)
																																INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
																																INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
																																INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
																															where data_saleitemrule.saleitemid = data_saleitem.saleitemid
																																and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 
							 
							 
							 
							 
							 
							 
							 
							 
							else ABS(((DATA_SaleItem.UnitPrice) - DATA_SaleItem.UnitTaxes) - ISNULL((select sum((case when discountamount &amp;#60; 0 then discountamount else discountamount *-1 end)/case when data_saleitemrule.ApplyToQty = 0 then 1 else data_saleitemrule.ApplyToQty end)
														from data_saleitemrule WITH(NOLOCK)
															INNER JOIN CNF_PromotionItemRule WITH(NOLOCK)						ON CNF_PromotionItemRule.PromotionItemRuleId = DATA_SaleItemRule.PromotionItemRuleId
															INNER JOIN CNF_PromotionItem WITH(NOLOCK)							ON CNF_PromotionItem.PromotionItemId = CNF_PromotionItemRule.PromotionItemId
															INNER JOIN CNF_Promotion WITH(NOLOCK)								ON CNF_Promotion.PromotionId = CNF_PromotionItem.PromotionId
														where data_saleitemrule.saleitemid = data_saleitem.saleitemid
															and ISNULL(CNF_Promotion.COAnoDiscount, 0) = 0), 0)) 

							end), 0) as Revenueamount,
						case when DATA_SaleItem.Quantity &amp;#60; 0 then 1
						     else @DepositRRCOAAccountingType 
						 end Accountingtype,
						@DepositRRCalcTypeTrigger as rrTrigger,
						@DepositPercentage as suspercentage,
						@DepositDays as Depositday,
						null Attributeids
	   
				from DATA_Sale WITH(NOLOCK)
					inner join data_transaction WITH(NOLOCK)					on data_transaction.transactionid = data_sale.voidtransactionid
					INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId
					left  join DATA_SaleItem WITH(NOLOCK)			    		on DATA_SaleItem.saleid = data_transaction.saleid
					left  join CNF_MatrixCell WITH(NOLOCK)						on CNF_MatrixCell.Matrixcellid = DATA_SaleItem.Matrixcellid
					left  join CNF_MatrixSheet WITH(NOLOCK)						on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.matrixsheetid
					left  join CNF_AttributeSet WITH(NOLOCK)					on CNF_AttributeSet.AttributeSetId = cnf_matrixcell.AttributeSetId
					left  join (select distinct data_ticket.ticketid, data_saleitem2ticket.saleitemid, operationtype, voidtype
										from data_saleitem2ticket WITH(NOLOCK)
											INNER JOIN data_ticket WITH(NOLOCK)				on data_ticket.ticketid = data_saleitem2ticket.ticketid	
										where DATA_Ticket.VoidType not in (104, 125)
											)data_ticket
								on data_ticket.saleitemid = ISNULL(data_saleitem.origSAleitemid, data_saleitem.saleitemid ) 
									and 1 = case when data_transaction.transactiontype in (5) and data_ticket.OperationType in (1, 11)  then 1																							 
												 else 0
										     end  

				where DATA_Sale.Paid = 1
				  and DATA_Sale.Encoded = 1
				  and data_transaction.TransactionType IN (5)
				  and data_saleitem.ItemTransactionType IN (5)					
				  and ((DATA_SaleItem.UnitRecharge &amp;#60;&amp;#62; DATA_SaleItem.totalamount) or ISNULL(DATA_SaleItem.UnitRecharge, 0) = 0)
				  and ISNULL(DATA_SaleItem.producttype, 0) &amp;#60;&amp;#62; 6
				  and data_transaction.transactionstatus in (5, 30)
				  and DATA_Sale.PaidTransactionId &amp;#60;&amp;#62; DATA_Sale.EncodedTransactionId	
				  and ((@RRTransDateType = 0 and DT_Encoded.fTransactionDate = @BatchDate)
					  OR (@RRTransDateType = 1 and convert(date, DT_Encoded.TransactionDate) = @BatchDate))
				  and ((data_transaction.transactionid in (select transactionid
														  from data_payment WITH(NOLOCK)
														 where PaymentStatus = 1
														   and data_transaction.transactionid = DATA_Payment.transactionid
														)))
				  and ((DATA_SaleItem.SaleItemId in (select SaleItemId
													 from DATA_TransactionItem WITH(NOLOCK)
															inner join DATA_Transaction WITH(NOLOCK)					on DATA_Transaction.TransactionId = DATA_TransactionItem.TransactionId
													where DATA_TransactionItem.TransactionId in (select TransactionId
																									from DATA_Transaction DT WITH(NOLOCK)
																								  where DT.saleid = DATA_Transaction.saleid
																								)
													)))
				and DATA_Transaction.saleid in (select DT.saleid
														from DATA_Transaction DT WITH(NOLOCK)
														  where DT.saleid = DATA_Transaction.saleid
															and TransactionType in (12, 15))
				and DATA_Transaction.TransactionId &amp;#60;&amp;#62; DATA_Sale.paidtransactionid
				and DATA_Sale.SaleId in (select DATA_Sale.Saleid
											from DATA_Sale WITH(NOLOCK)
											INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Sale.PaidTransactionId
											INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId

										where ((DT_Encoded.FTransactionDate = @BatchDate) and (DATA_Transaction.FTransactionDate &amp;#60;&amp;#62; @BatchDate))
											and DATA_Sale.SaleId in (select SaleID
																		from (select saleid, 
																					round(sum(case when AccountingType = 1 then RevenueAmount else 0 end), 2) Debit,
																					round(sum(case when AccountingType = 2 then RevenueAmount else 0 end), 2) credit
																			from rr_data_revenue WITH(NOLOCK)
																			where rr_data_revenue.RRCalcTypeTrigger in (@EncodedTicketsId)
																			group by saleid
																			)p
																		where (Debit - credit) &amp;#60;&amp;#62; 0
																	)
								)

			
		)p  
		where RevenueAmount &amp;#60;&amp;#62; 0




INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS])
		select  COAAccountId,
						RevenueRecognitionRuleId,
						RRCalcTypeWhere,
						RRCalcTypeMethod,
						COAAccountConfigId,
						COAAccountType,
						transactionid, 
						saleid,
						Ticketid,
						saleitemid,
						Matrixcellid,
						MatrixSheetid,
						Siteid,
						OperatingAreaId,
						Workstationid,
						UserGroupid,
						UserId,
						calcdate,
						Quantity,
						UnitAmount,
						GrossAmount,
						NetAmount,
						suspendprice,
						percentage,
						remainingValues,
						Revenueamount,
						Accountingtype,
						rrTrigger,
						suspercentage,
						suspendday,
						Attributeids
		  from (
									select distinct 
												RR_Orig.COAAccountId,
												RR_Orig.RevenueRecognitionRuleId,
												RR_Orig.RRCalcTypeWhere,
												RR_Orig.RRCalcTypeMethod,
												RR_Orig.COAAccountConfigId,
												RR_Orig.COAAccountType,
												DT_Encoded.transactionid, 
												DT_Encoded.saleid,
												null Ticketid,
												rr_data_revenue.saleitemid,
												rr_data_revenue.Matrixcellid,
												rr_data_revenue.MatrixSheetid,
												data_transaction.Siteid,
												data_transaction.OperatingAreaId,
												data_transaction.Workstationid,
												data_transaction.UserGroupid,
												data_transaction.UserId,
												@BatchDate as calcdate,
												rr_data_revenue.Quantity,
												rr_data_revenue.UnitAmount,
												rr_data_revenue.GrossAmount,
												rr_data_revenue.NetAmount,
												@SuspendPrice as suspendprice,
												@SuspendCOAAccount_Percentage as percentage,
												@SuspendRemainingValues as remainingValues,
												RR_Orig.Revenueamount,
												case when RR_Orig.accountingtype = 1 then 2 else 1 end  Accountingtype,
												@SuspendRRCalcTypeTrigger as rrTrigger,
												@SuspendPercentage as suspercentage,
												@SuspendDays as suspendday,
												null Attributeids

							  from DATA_Sale WITH(NOLOCK)
								INNER JOIN DATA_Transaction WITH(NOLOCK)					ON DATA_Transaction.TransactionId = DATA_Sale.PaidTransactionId
								INNER JOIN DATA_Transaction DT_Encoded WITH(NOLOCK)			ON DT_Encoded.TransactionId = DATA_Sale.EncodedTransactionId
								INNER JOIN rr_data_revenue WITH(NOLOCK)						ON RR_DATA_Revenue.TransactionId = DT_Encoded.TransactionId
								INNER JOIN rr_data_revenue RR_Orig WITH(NOLOCK)				ON RR_Orig.TransactionId = DATA_Transaction.TransactionId

							where ((DT_Encoded.FTransactionDate = @BatchDate) and (DATA_Transaction.FTransactionDate &amp;#60;&amp;#62; @BatchDate))
							  and DATA_Sale.PaidTransactionId &amp;#60;&amp;#62; DATA_Sale.EncodedTransactionId	
							  and rr_data_revenue.RRCalcTypeTrigger = 1
							  and rr_data_revenue.COAAccountId = 1
							  and RR_Orig.RRCalcTypeTrigger = @EncodedTicketsId
							  and DATA_Sale.SaleId in (select SaleID
														  from (select saleid, 
																	   round(sum(case when AccountingType = 1 then RevenueAmount else 0 end), 2) Debit,
																	   round(sum(case when AccountingType = 2 then RevenueAmount else 0 end), 2) credit
																from rr_data_revenue WITH(NOLOCK)
																where rr_data_revenue.RRCalcTypeTrigger in (@EncodedTicketsId)
																group by saleid
																)p
														  where (Debit - credit) &amp;#60;&amp;#62; 0
														)

			)p1
							where RevenueAmount &amp;#60;&amp;#62; 0
end
End
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>7ED993EF982F450DBF811BC4097D4F86</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_OnRefunds</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_OnRefunds]
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN

	Declare @SuspendID Integer
	Declare @TaxAccountID Integer
	Declare @DiscountAccountID Integer
	Declare @ACCPaymentMethod Integer
	Declare @OnSaleTrigger Integer = 1
	Declare @TicketUsageTrigger Integer = 2
	Declare @OnTimePeriodTrigger Integer = 4
	Declare @OnEventTrigger Integer = 17
	Declare @SuspendRRRId Integer
	Declare @SuspendCOAAccountId Integer
	Declare @SuspendRRRCode varchar(10)
	Declare @SuspendRRCalcTypeTrigger Integer
	Declare @SuspendRRCalcTypeWhere Integer
	Declare @SuspendRRCalcTypeMethod Integer
	Declare @SuspendCOAAccountConfigId Integer
	Declare @SuspendCOAAccountTypeId Integer
	Declare @SuspendCOAAccountCode varchar(10)
	Declare @SuspendPercentage float
	Declare @SuspendDays Integer
	Declare @SuspendPrice float
	Declare @SuspendCOAAccount_Percentage Float
	Declare @SuspendRemainingValues Integer
	Declare @SuspendRRCOAAccountingType Integer
	Declare @SuspendAccountingType Integer

	Declare @MatrixcellsUV1 table (Matrixcells Integer)
	Declare @MatrixcellsUV2 table (Matrixcells Integer)
	Declare @Matrixcells table (MatrixcellID Integer, RevenueRecognitionRuleId Integer)
	insert into @Matrixcells
		select distinct matrixcellid, RevenueRecognitionRuleId
		from (

				select 1 as type, rr_cnf_product.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixcellid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 2 as type, CNF_MatrixCell.matrixcellid, rr_cnf_product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixsheetid = rr_cnf_product.matrixsheetid
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.matrixsheetid is not null
				  and rr_cnf_Product.Enabled = 1

				UNION ALL

				select 3 as type, CNF_MatrixCell.matrixcellid, RR_CNF_Product.RevenueRecognitionRuleId
				from rr_cnf_product
					INNER JOIN CNF_AttributeSetDetail					on CNF_AttributeSetDetail.attributeid = rr_cnf_product.AttributeId
					INNER JOIN CNF_MatrixCell							on cnf_matrixcell.AttributeSetId = CNF_AttributeSetDetail.AttributeSetId
					INNER JOIN RR_CNF_RevenueRecognitionRule					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = RR_CNF_Product.RevenueRecognitionRuleId
																			and RR_CNF_RevenueRecognitionRule.enabled = 1
				where rr_cnf_product.AttributeId	is not null
				  and rr_cnf_Product.Enabled = 1

		)p

	select @SuspendID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'SUSPENSE'
	  and SystemAccount = 1

	select @TaxAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'TAXES'
	  and SystemAccount = 1

	select @ACCPaymentMethod = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'PYMTMETHOD'
	  and SystemAccount = 1

	select @DiscountAccountID = COAACCOUNTID
	  from COA_CNF_Account WITH(NOLOCK)
	  where Code = 'DISCOUNTS'
	  and SystemAccount = 1

	  select TOP 1 @SuspendRRRId = RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,
			@SuspendRRRCode = RR_CNF_RevenueRecognitionRule.code,
			@SuspendRRCalcTypeTrigger = RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
			@SuspendRRCalcTypeWhere = RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
			@SuspendRRCalcTypeMethod = RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
			@SuspendCOAAccountConfigId = COA_CNF_AccountConfig.COAAccountConfigId,
			@SuspendCOAAccountTypeId = COA_CNF_AccountType.COAAccountTypeId,
			@SuspendCOAAccountId = coa_cnf_account.COAAccountId,
			@SuspendPercentage = RR_CNF_RevenueRecognitionRule.Percentage,
			@SuspendDays = RR_CNF_RevenueRecognitionRule.Days,
			@SuspendPrice = COA_CNF_AccountConfig.Price,
			@SuspendCOAAccount_Percentage = COA_CNF_AccountConfig.Percentage,
			@SuspendRemainingValues = COA_CNF_AccountConfig.RemainingValues,
			@SuspendCOAAccountCode = coa_cnf_account.Code,
			@SuspendRRCOAAccountingType = COA_CNF_AccountConfig.AccountingType
	from coa_cnf_account WITH(NOLOCK)
		INNER JOIN COA_CNF_AccountType WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId
		INNER JOIN COA_CNF_AccountConfig WITH(NOLOCK)			on COA_CNF_AccountConfig.COAAccountId = coa_cnf_account.COAAccountId
		INNER JOIN RR_CNF_RevenueRecognitionRule WITH(NOLOCK)	on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = COA_CNF_AccountConfig.RevenueRecognitionRuleId
	where coa_cnf_account.COAAccountID = @SuspendID

	 insert into @MatrixcellsUV1
					 select cells
						from (
						select isnull(cnf_matrixcell.matrixcellid, mc.matrixcellid) as cells
						from rr_cnf_product
							left join cnf_matrixcell			on cnf_matrixcell.matrixcellid = rr_cnf_product.matrixcellid
							left join cnf_matrixcell MC			on mc.matrixsheetid = rr_cnf_product.matrixsheetid
						where revenuerecognitionruleid in (
															select revenuerecognitionruleid 
															from RR_CNF_RevenueRecognitionRule
															where enabled = 1
															  and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
															  and RRCalcTypeTrigger = 1
															  and RR_CNF_RevenueRecognitionRule.upgradetype = 0
															  )
						)r
						where cells is not null

	insert into @MatrixcellsUV2
					 select cells
						from (
						select isnull(cnf_matrixcell.matrixcellid, mc.matrixcellid) as cells
						from rr_cnf_product
							left join cnf_matrixcell			on cnf_matrixcell.matrixcellid = rr_cnf_product.matrixcellid
							left join cnf_matrixcell MC			on mc.matrixsheetid = rr_cnf_product.matrixsheetid
						where revenuerecognitionruleid in (
															select revenuerecognitionruleid 
															from RR_CNF_RevenueRecognitionRule
															where enabled = 1
															  and RevenueRecognitionRuleId &amp;#60;&amp;#62; 1
															  and RRCalcTypeTrigger = 1
															  and RR_CNF_RevenueRecognitionRule.upgradetype = 1
															  )
						)r
						where cells is not null


	BEGIN


	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		  from(
			select distinct			coalesce(coa_cnf_account.COAAccountId, (select max(COAAccountId)
												from COA_CNF_Accountconfig WITH(NOLOCK)
													inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid = coa_cnf_accountconfig.RevenueRecognitionRuleId
														   where COA_CNF_Accountconfig.RevenueRecognitionRuleId in (select RevenueRecognitionRuleId from @Matrixcells MC where mc.matrixcellid = rr_data_revenue.matrixcellid)
															 and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 1
															 and RR_CNF_RevenueRecognitionRule.Enabled = 1
															 and COA_CNF_Accountconfig.AccountingType = 2)) coaaccountid,
								coalesce(RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId, (select max(COA_CNF_Accountconfig.RevenueRecognitionRuleId)
												from COA_CNF_Accountconfig WITH(NOLOCK)
													inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)					on RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleid = coa_cnf_accountconfig.RevenueRecognitionRuleId
														   where COA_CNF_Accountconfig.RevenueRecognitionRuleId in (select RevenueRecognitionRuleId from @Matrixcells MC where mc.matrixcellid = rr_data_revenue.matrixcellid)
															 and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger = 1
															 and RR_CNF_RevenueRecognitionRule.Enabled = 1
															 and COA_CNF_Accountconfig.AccountingType = 2))
								RevenueRecognitionRuleId,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								ISNULL(coa_cnf_account.COAAccountTypeId, 5) COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								null Ticketid,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								null RemainingValues,
								abs(ISNULL(sum(Reverses.Revenueamount), rr_data_revenue.RevenueAmount)	
									 ) 
								as RevenueAmount,
								case when data_saleitem.quantity &amp;#62; 0 then 2 else 1 end Accountingtype,
							--	77 AccountingType,
								1 RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs
		



				  from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  												 
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid					
						INNER JOIN data_saleitem WITH(NOLOCK)						ON data_saleitem.saleid = DATA_Transaction.saleid
																						and RR_DATA_REVENUE.SaleItemId = DATA_SaleItem.saleitemid
						left  JOIN data_saleitem TSaleitemid WITH(NOLOCK)			ON TSaleitemid.SaleItemId = data_saleitem.Origsaleitemid
						left  JOIN (select COAAccountId, Saleitemid, Ticketid,  ABS(debit - credit) RevenueAmount
												from (
												select RR_DATA_Revenue.COAAccountId,
																   RR_DATA_Revenue.SaleItemId,
																   RR_DATA_Revenue.TicketId,
																   sum(case when AccountingType = 1 then RevenueAmount else 0 end) debit,
																   sum(case when AccountingType = 2 then RevenueAmount else 0 end) credit
																			  from RR_DATA_Revenue WITH(NOLOCK)
																				inner join DATA_Ticket WITH(NOLOCK)				on data_ticket.ticketid = rr_data_revenue.ticketid
																			where RRCalcTypeTrigger in (1)
																			  and RR_DATA_Revenue.COAAccountId not in (1, 2, 3, 4)
																			  and RR_DATA_Revenue.saleitemtaxid is null
																			  and isnull(oobflag, 0) = 0
																			 -- and RR_DATA_Revenue.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null )
																			Group by  RR_DATA_Revenue.COAAccountId,
																					RR_DATA_Revenue.SaleItemId,
																						RR_DATA_Revenue.TicketId
												)p
												where debit &amp;#60;&amp;#62; credit
												  and (debit &amp;#60; credit)
											
													 
											) Reverses			ON   (Reverses.SaleItemId = (select case when SI1.SaleItemId &amp;#62; 
																																				   (select min(SaleItemId)
																																					  from DATA_SaleItem SI WITH(NOLOCK)
																																					 where SI.SaleId = DATA_SaleItem.BaseSaleId
																																					   and SI.MatrixCellId = DATA_SaleItem.MatrixCellId
																																				   )  then (select min(SaleItemId)
																																					  from DATA_SaleItem SI WITH(NOLOCK)
																																					 where SI.SaleId = DATA_SaleItem.BaseSaleId
																																					   and SI.MatrixCellId = DATA_SaleItem.MatrixCellId
																																				   )
																																				   else SI1.SaleItemId
																																				  end 
																																			from data_saleitem SI1
																																			where saleitemid = DATA_SaleItem.saleitemid))

						left  JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = Reverses.coaaccountid
																								and coa_cnf_account.Enabled = 1
						left  JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId


				 where  RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and DATA_SaleItem.ProductType &amp;#60;&amp;#62; 1
				   
				   and (data_transaction.transactiontype in (18, 20, 22)) 
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid
				   and TSaleitemid.Saleitemid not In ( select SaleitemID
				                                          from data_saleitem2ticket WITH(NOLOCK)
														 where data_saleitem2ticket.SaleitemID = TSaleitemid.Saleitemid
														)


					Group by coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid,
								RR_DATA_REVENUE.OperatingAreaId,
								RR_DATA_REVENUE.Workstationid,
								RR_DATA_REVENUE.UserGroupid,
								RR_DATA_REVENUE.UserId,
								RR_DATA_REVENUE.Quantity,
								data_transaction.transactiontype,
								RR_DATA_REVENUE.GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0),
								RR_DATA_REVENUE.Price,
								RR_DATA_REVENUE.Percentage,								
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs,
								rr_data_revenue.RevenueAmount,
								data_saleitem.quantity

			)p
			where RevenueAmount &amp;#60;&amp;#62; 0

	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		from(
				select distinct Reverses.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,							   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								0 RemainingValues,
								ABS(SUM(ISNULL(Reverses.Revenueamount, RR_DATA_REVENUE.revenueamount))) 
								RevenueAmount,
								1 Accountingtype,
								1 RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs

				from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	as Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						INNER JOIN DATA_Sale WITH(NOLOCK)							on DATA_Sale.saleid = rr_data_revenue.saleid
						INNER JOIN data_saleitem WITH(NOLOCK)						on data_saleitem.saleitemid = RR_DATA_REVENUE.SaleItemId
						INNER JOIN (select COAAccountId,
										   TicketId,
										   (debit - Credit) RevenueAmount
															from (
									select COAAccountId,
										   TicketId,
										   SUM(debit) debit,
										   SUM(credit) credit

										   from (

								select COAAccountId,
										   TicketId,
										   1 rev,
										   sum(case when accountingtype = 1 then RevenueAmount else 0 end) debit,
										    sum(case when accountingtype = 2 then RevenueAmount else 0 end) credit
									  from RR_DATA_Revenue WITH(NOLOCK)

									where RRCalcTypeTrigger in (2, 3, 4, 17)
										and coaaccountid not in (1, 2, 3, 4)
										and saleitemtaxid is null
										and saleitemruleid is null
										and isnull(oobflag, 0) = 0
										and AccountingType = 2
									 group by COAAccountId,
										      TicketId
									 UNION ALL

									 select COAAccountId,
										   TicketId,
										   1 rev,
										   sum(case when accountingtype = 1 then RevenueAmount else 0 end) debit,
										    sum(case when accountingtype = 2 then RevenueAmount else 0 end) credit
									  from RR_DATA_Revenue RR WITH(NOLOCK)

									where RRCalcTypeTrigger in (1)
										and coaaccountid not in (1, 2, 3, 4)
										and saleitemtaxid is null
										and saleitemruleid is null
										and isnull(oobflag, 0) = 0
										and AccountingType = 2
										and TicketId not in (select TicketId from RR_DATA_Revenue WITH(NOLOCK) where RR_DATA_Revenue.TicketId = RR.TicketId and RRCalcTypeTrigger in (2,3, 4, 17))
									 group by COAAccountId,
										      TicketId
								     UNION ALL
									 
									  select COAAccountId,
											RR_DATA_Revenue.TicketId,
											case when max(RR_DATA_Revenue.netamount) &amp;#60;&amp;#62; 0 then max(RR_DATA_Revenue.netamount)-	sum(RevenueAmount)
											     else max(DATA_SaleItem.unitprice - DATA_SaleItem.unittaxes) -	sum(RevenueAmount)
											 end RevenueAmount,
											 sum(case when accountingtype = 1 then RevenueAmount end) debit,
										    sum(case when accountingtype = 2 then RevenueAmount end) credit

										from RR_DATA_Revenue WITH(NOLOCK)
										  inner join DATA_SaleItem WITH(NOLOCK)			on DATA_SaleItem.SaleItemId = RR_DATA_Revenue.saleitemid
									where RRCalcTypeTrigger in (4)		    
										and AccountingType = 1
										and RR_DATA_Revenue.SaleItemId in (select RR.SaleItemId
															 from RR_DATA_Revenue RR WITH(NOLOCK)

														where RR.RRCalcTypeTrigger in (4)
															and RR.AccountingType = 2
															and RR.SaleItemId = RR_DATA_Revenue.SaleitemID
														group by RR.COAAccountId,
																 RR.SaleItemId,
																 RR.TicketId
														 )
														group by COAAccountId,
																RR_DATA_Revenue.SaleItemId,
																RR_DATA_Revenue.TicketId

											)p

											group by COAAccountId,
																	TicketId
											Having ISNULL(SUM(debit), 0) - ISNULL(SUM(credit), 0) &amp;#60;&amp;#62; 0

											)p1
											)Reverses						ON (Reverses.TicketId = RR_DATA_Revenue.Ticketid)

						INNER JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = Reverses.coaaccountid
						INNER JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId 


				 where RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and coa_cnf_account.Enabled = 1
				   and data_transaction.transactiontype in (18, 20, 22)
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (1)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid
				   and RR_DATA_REVENUE.Ticketid In (select Ticketid
				                                          from RR_DATA_Revenue RR WITH(NOLOCK)
														 where RR.Ticketid = RR_DATA_REVENUE.TicketID
														   and RR.RRCalcTypeTrigger in (2, 3, 4, 17)
														   and RR.FCalcDate &amp;#60;= @BatchDate
														)


				   Group by Reverses.COAAccountId, (Reverses.RevenueAmount),
				                data_transaction.transactiontype,
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,							   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid ,
								RR_DATA_REVENUE.OperatingAreaId ,
								RR_DATA_REVENUE.Workstationid ,
								RR_DATA_REVENUE.UserGroupid ,
								RR_DATA_REVENUE.UserId ,
								RR_DATA_REVENUE.Quantity ,
								RR_DATA_REVENUE.GrossAmount ,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0),
								RR_DATA_REVENUE.Price ,
								RR_DATA_REVENUE.Percentage ,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs
				
		 )p
		 where RevenueAmount &amp;#60;&amp;#62; 0

--Void Been used
	INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[UnitAmount]
						,[Saleitemid]
						,[MatrixCellid]
						,[MatrixSheetid]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDs])
		select *
		  from(
				select distinct coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid as Transactionid,
								RR_DATA_REVENUE.saleid as Saleid,
								RR_DATA_REVENUE.TicketID, 
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID as SaleitemID,
								RR_DATA_REVENUE.Matrixcellid as Matrixcell,
								RR_DATA_REVENUE.MatrixSheetId as MatrixSheetID,
								RR_DATA_REVENUE.Siteid as SiteID,
								RR_DATA_REVENUE.OperatingAreaId as OperatingAreaID,
								RR_DATA_REVENUE.Workstationid as Workstationid,
								RR_DATA_REVENUE.UserGroupid as UserGroupID,
								RR_DATA_REVENUE.UserId as userID,
								@BatchDate as BatchDate,
								RR_DATA_REVENUE.Quantity as Quantity,
								RR_DATA_REVENUE.GrossAmount as GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0) as NetAmount,
								RR_DATA_REVENUE.Price as ConfigPrice,
								RR_DATA_REVENUE.Percentage as ConfigPercentage,
								null RemainingValues,
								sum(coalesce(Reverses.revenueamount, Reverses2.Revenueamount, 0))
								RevenueAmount,
								1 Accountingtype,
								1 RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs

				from RR_DATA_REVENUE WITH(NOLOCK)
						inner join @Matrixcells	Matrixcellid						ON Matrixcellid.matrixcellid = rr_data_revenue.matrixcellid
						inner join RR_CNF_RevenueRecognitionRule WITH(NOLOCK)		ON RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId = Matrixcellid.RevenueRecognitionRuleId and RR_CNF_RevenueRecognitionRule.enabled = 1  						 
						INNER JOIN DATA_Transaction	WITH(NOLOCK)					on data_transaction.transactionid = rr_data_revenue.transactionid
						LEFT JOIN data_ticket WITH(NOLOCK)							ON data_ticket.ticketid = RR_DATA_REVENUE.ticketid
						LEFT JOIN data_saleitem WITH(NOLOCK)						ON data_saleitem.SaleItemId = RR_DATA_Revenue.saleitemid
						LEFT JOIN (select SI.SaleItemId BASESaleitemid,
						                  data_saleitem.BaseSaleId,
										  data_saleitem.Matrixcellid,
										  DATA_Ticket.TicketId,
										  sum(RevenueAmount) RevenueAmount
						             from DATA_SaleItem WITH(NOLOCK)
										inner join DATA_SaleItem SI WITH(NOLOCK)	ON SI.saleid = DATA_SaleItem.BaseSaleId
																							and SI.MatrixCellId = DATA_SaleItem.MatrixCellId
										inner join RR_DATA_Revenue WITH(NOLOCK)		on RR_DATA_Revenue.SaleItemId = SI.SaleItemId
										inner join DATA_Ticket WITH(NOLOCK)			on DATA_Ticket.SaleItemId = SI.saleitemid
									group by SI.SaleItemId,
						                  data_saleitem.BaseSaleId,
										  data_saleitem.Matrixcellid,
										  DATA_Ticket.TicketId
									)BaseSaleitemid									ON basesaleitemid.BaseSaleId = data_saleitem.basesaleid
																						and basesaleitemid.Matrixcellid = DATA_SaleItem.Matrixcellid
																						and BaseSaleitemid.TicketId = RR_DATA_Revenue.ticketid
																						
									 
						LEFT JOIN (select COAAccountId, Saleitemid, Ticketid,  ABS(debit - credit) RevenueAmount
											from (
											select RR_DATA_Revenue.COAAccountId,
															   RR_DATA_Revenue.SaleItemId,
															   RR_DATA_Revenue.TicketId,
															   sum(case when AccountingType = 1 then RevenueAmount else 0 end) debit,
															   sum(case when AccountingType = 2 then RevenueAmount else 0 end) credit
																		  from RR_DATA_Revenue WITH(NOLOCK)
																			inner join DATA_Ticket WITH(NOLOCK)				on data_ticket.ticketid = rr_data_revenue.ticketid
																		where RRCalcTypeTrigger in (1)
																		  and RR_DATA_Revenue.COAAccountId not in (1, 2, 3, 4)
																		  and RR_DATA_Revenue.saleitemtaxid is null
																		  and isnull(oobflag, 0) = 0
																		 -- and RR_DATA_Revenue.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null )
																		Group by  RR_DATA_Revenue.COAAccountId,
																				RR_DATA_Revenue.SaleItemId,
																					RR_DATA_Revenue.TicketId
											)p
											where debit &amp;#60;&amp;#62; credit
											  and (debit &amp;#60; credit)
											) Reverses			ON ( ((Reverses.TicketId = RR_DATA_Revenue.Ticketid)  and (Reverses.SaleItemId = BaseSaleitemid.BASESaleitemid))
											                          or (Reverses.TicketId = RR_DATA_Revenue.Ticketid))
											LEFT JOIN (select RR_DATA_Revenue.COAAccountId,
														   RR_DATA_Revenue.SaleItemId,
														   RR_DATA_Revenue.TicketId,
														   sum(RevenueAmount) RevenueAmount
										   
																	  from RR_DATA_Revenue WITH(NOLOCK)
																		inner join DATA_Ticket WITH(NOLOCK)				on data_ticket.ticketid = rr_data_revenue.ticketid
																	where RRCalcTypeTrigger in (1)
																	  and AccountingType = 2
																	  and RR_DATA_Revenue.COAAccountId not in (1, 2, 3, 4)
																	  and RR_DATA_Revenue.saleitemtaxid is null
																	  and isnull(oobflag, 0) = 0
															--		  and RR_DATA_Revenue.COAAccountId not in (select COAAccountId from CNF_Tax where COAAccountId is not null )
																	  Group by  RR_DATA_Revenue.COAAccountId,
																				RR_DATA_Revenue.SaleItemId,
																				 RR_DATA_Revenue.TicketId
											
													 
															) Reverses2			ON  (Reverses2.TicketId = RR_DATA_Revenue.Ticketid)  and (Reverses2.SaleItemId = BaseSaleitemid.BaseSaleitemid)
																						and Reverses2.coaaccountid = ISNULL(Reverses.COAAccountId, Reverses2.coaaccountid)

						LEFT JOIN coa_cnf_account	WITH(NOLOCK)					on coa_cnf_account.coaaccountid = ISNULL(Reverses2.coaaccountid, Reverses.coaaccountid)
						LEFT JOIN COA_CNF_AccountType	WITH(NOLOCK)				on COA_CNF_AccountType.COAAccountTypeId = coa_cnf_account.COAAccountTypeId

				 where RR_CNF_RevenueRecognitionRule.Enabled = 1
				   and (data_transaction.transactiontype in (18, 20, 22)) 
				   and RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger IN (@OnSaleTrigger)
				   and @BatchDate between RR_CNF_RevenueRecognitionRule.FromDate and RR_CNF_RevenueRecognitionRule.ToDate
				   and RR_DATA_REVENUE.fcalcdate = @BatchDate
				   and RR_DATA_REVENUE.coaaccountid = @suspendid 
				   and RR_DATA_REVENUE.TicketID not In (select Ticketid
				                                          from RR_DATA_Revenue RR WITH(NOLOCK)
														 where RR.TicketID = RR_DATA_REVENUE.TicketID
														   and RR.RRCalcTypeTrigger in (2, 3, 4, 17)
														   and RR.FCalcDate &amp;#60;= @BatchDate
														)

						Group by coa_cnf_account.COAAccountId, 
								RR_CNF_RevenueRecognitionRule.RevenueRecognitionRuleId,	   
								RR_CNF_RevenueRecognitionRule.RRCalcTypeWhere,
								RR_CNF_RevenueRecognitionRule.RRCalcTypeMethod,	   
								RR_DATA_REVENUE.COAAccountConfigId,
								coa_cnf_account.COAAccountTypeId,
								RR_DATA_REVENUE.Transactionid,
								RR_DATA_REVENUE.saleid,
								RR_DATA_REVENUE.TicketID,
								RR_DATA_Revenue.UnitAmount,
								RR_DATA_REVENUE.SaleitemID,
								RR_DATA_REVENUE.Matrixcellid,
								RR_DATA_REVENUE.MatrixSheetId,
								RR_DATA_REVENUE.Siteid,
								RR_DATA_REVENUE.OperatingAreaId,
								RR_DATA_REVENUE.Workstationid,
								RR_DATA_REVENUE.UserGroupid,
								RR_DATA_REVENUE.UserId,
								RR_DATA_REVENUE.Quantity,
								RR_DATA_REVENUE.GrossAmount,
								ISNULL(RR_DATA_REVENUE.NetAmount, 0),
								RR_DATA_REVENUE.Price,
								RR_DATA_REVENUE.Percentage,								
								RR_CNF_RevenueRecognitionRule.RRCalcTypeTrigger,
								RR_CNF_RevenueRecognitionRule.Percentage,
								RR_CNF_RevenueRecognitionRule.Days,
								RR_DATA_Revenue.AttributeIDs,
								Reverses2.RevenueAmount,
								Reverses.RevenueAmount,
								DATA_SaleItem.BaseSaleId,
								DATA_SaleItem.matrixcellid
			)p
			where RevenueAmount &amp;#60;&amp;#62; 0

	


	END
END



</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>0C688F33EDA549DB97482CA1037B3C66</SqlScriptAK></Script></ScriptList></StoredProcedure><StoredProcedure Status="ACTIVE"><Name>otn_sp_RR_RevenueData_SplitAmtbyChildren</Name><ScriptList><Script Type="SP"><Database>stMsSQL2005</Database><Version>1</Version><SQL>
create Procedure [dbo].[otn_sp_RR_RevenueData_SplitAmtbyChildren] 
	@BatchDate Date,
	@RRTransDateType Integer
AS 
BEGIN
	SET NOCOUNT ON
	--select'Begin Batch', getdate()

	Declare @COAAccountId int = 0
	Declare	@ParentAccountId int = 0
	Declare	@Code varchar(100)
	Declare	@SiteID int = 0

	Declare @Temp table (  COAAccountId int,
						   ParentAccountId int,
						   Code varchar(100),
						   SiteID int
	                     )
	
	INSERT INTO @Temp (
						COAAccountId,
						ParentAccountId,
						Code,
						SiteID
					  ) 	
					select COAAccountId,
						   ParentAccountId,
						   Code,
						   SiteID
					from COA_CNF_Account 
					where Siteid IS NULL
					  and COAAccountId IN ( 
										select ParentAccountId 
										from COA_CNF_Account COA 
										)
					  and COAAccountId IN (select COAAccountId from CNF_Promotion WITH(NOLOCK) where COAAccountId is not null
												UNION ALL
										   select COAAccountId from CNF_PaymentMethod WITH(NOLOCK) where COAAccountId is not null
												UNION ALL
										   select COAAccountId from CNF_PaymentCard WITH(NOLOCK) where COAAccountId is not null  
 												UNION ALL
										   select COAAccountId from cnf_tax WITH(NOLOCK) where COAAccountId is not null   
										  )
					  and COAAccountId in (select COAAccountId 
					                         from RR_DATA_Revenue WITH(NOLOCK) 
											where RR_DATA_Revenue.COAAccountId = COA_CNF_Account.COAAccountId 
											  and FCalcDate = @batchdate
										   )

--select * from @Temp

	DECLARE Parent_Cursor CURSOR LOCAL FOR
				select * from @Temp order by 1

	OPEN Parent_Cursor

	FETCH NEXT FROM Parent_Cursor INTO
		@COAAccountId,
		@ParentAccountId,
		@Code,
		@SiteID

	WHILE @@FETCH_STATUS = 0
	BEGIN
		select @COAAccountId

		INSERT INTO [dbo].[RR_DATA_Revenue]
						([COAAccountId]
						,[RevenueRecognitionRuleId]
						,[RRCalcTypeWhere]
						,[RRCalcTypeMethod]
						,[COAAccountConfigId]
						,[COAAccountType]
						,[TransactionId]
						,[SaleId]
						,[TicketID]
						,[SaleItemId]
						,[MatrixCellId]
						,[MatrixSheetID]
						,[SiteId]
						,[OperatingAreaId]
						,[WorkstationId]
						,[UserGroupId]
						,[UserId]
						,[FCalcDate]
						,[Quantity]
						,[UnitAmount]
						,[GrossAmount]
						,[NetAmount]
						,[Price]
						,[Percentage]
						,[RemaningValues]
						,[RevenueAmount]
						,[AccountingType]
						,[RRCalcTypeTrigger]
						,[RRPercentage]
						,[RRDays]
						,[AttributeIDS]
						,[PaymentID]
						,[SaleitemTaxID]
						,[SaleItemRuleID])
		select *
		  from (
				select  COA_CNF_Account.COAAccountId, 
								RR_DATA_Revenue.RevenueRecognitionRuleId, 
								RR_DATA_Revenue.RRCalcTypeWhere,
								RR_DATA_Revenue.RRCalcTypeMethod, 
								RR_DATA_Revenue.COAAccountConfigId, 
								RR_DATA_Revenue.COAAccountType, 
								RR_DATA_Revenue.TransactionId, 
								RR_DATA_Revenue.SaleId, 
								RR_DATA_Revenue.TicketID, 
								RR_DATA_Revenue.SaleItemId, 
								RR_DATA_Revenue.MatrixCellId, 
								RR_DATA_Revenue.MatrixSheetID, 
								RR_DATA_Revenue.SiteId, 
								RR_DATA_Revenue.OperatingAreaId, 
								RR_DATA_Revenue.WorkstationId,
								RR_DATA_Revenue.UserGroupId, 
								RR_DATA_Revenue.UserId, 
								RR_DATA_Revenue.FCalcDate, 
								RR_DATA_Revenue.Quantity, 
								RR_DATA_Revenue.UnitAmount, 
								RR_DATA_Revenue.GrossAmount, 
								RR_DATA_Revenue.NetAmount, 
								RR_DATA_Revenue.Price, 
								RR_DATA_Revenue.Percentage, 
								RR_DATA_Revenue.RemaningValues, 
								RR_DATA_Revenue.RevenueAmount, 
								RR_DATA_Revenue.AccountingType, 
								RR_DATA_Revenue.RRCalcTypeTrigger, 
								RR_DATA_Revenue.RRPercentage, 
								RR_DATA_Revenue.RRDays, 
								RR_DATA_Revenue.AttributeIDS,
								RR_DATA_Revenue.PaymentID, 
								RR_DATA_Revenue.SaleitemTaxID, 
								RR_DATA_Revenue.SaleItemRuleID

						from RR_DATA_Revenue WITH(NOLOCK)
							INNER JOIN DATA_Transaction WITH(NOLOCK)						ON DATA_Transaction.TransactionId = RR_DATA_Revenue.TransactionID
							INNER JOIN COA_CNF_Account WITH(NOLOCK)							ON COA_CNF_Account.SiteID = DATA_Transaction.SiteId
																								and COA_CNF_Account.ParentAccountId = @COAAccountId
						where RR_DATA_Revenue.COAAccountId = @COAAccountId
						  and RR_DATA_Revenue.FCalcDate = @batchdate
						  and ((RR_DATA_Revenue.paymentID is not null) or (RR_DATA_Revenue.SaleItemTaxId is not null) or (RR_DATA_Revenue.SaleItemRuleID is not null))
			union all

			select  RR_DATA_Revenue.COAAccountId,
					RR_DATA_Revenue.RevenueRecognitionRuleId, 
					RR_DATA_Revenue.RRCalcTypeWhere,
					RR_DATA_Revenue.RRCalcTypeMethod, 
					RR_DATA_Revenue.COAAccountConfigId, 
					RR_DATA_Revenue.COAAccountType, 
					RR_DATA_Revenue.TransactionId, 
					RR_DATA_Revenue.SaleId, 
					RR_DATA_Revenue.TicketID, 
					RR_DATA_Revenue.SaleItemId, 
					RR_DATA_Revenue.MatrixCellId, 
					RR_DATA_Revenue.MatrixSheetID, 
					RR_DATA_Revenue.SiteId, 
					RR_DATA_Revenue.OperatingAreaId, 
					RR_DATA_Revenue.WorkstationId,
					RR_DATA_Revenue.UserGroupId, 
					RR_DATA_Revenue.UserId, 
					RR_DATA_Revenue.FCalcDate, 
					RR_DATA_Revenue.Quantity, 
					RR_DATA_Revenue.UnitAmount, 
					RR_DATA_Revenue.GrossAmount, 
					RR_DATA_Revenue.NetAmount, 
					RR_DATA_Revenue.Price, 
					RR_DATA_Revenue.Percentage, 
					RR_DATA_Revenue.RemaningValues, 
					RR_DATA_Revenue.RevenueAmount, 
					case when AccountingType = 1 then 2 else 1 end Accountingtype, 
					RR_DATA_Revenue.RRCalcTypeTrigger, 
					RR_DATA_Revenue.RRPercentage, 
					RR_DATA_Revenue.RRDays, 
					RR_DATA_Revenue.AttributeIDS,
					RR_DATA_Revenue.PaymentID, 
					RR_DATA_Revenue.SaleitemTaxID, 
					RR_DATA_Revenue.SaleItemRuleID

			from RR_DATA_Revenue WITH(NOLOCK)
				INNER JOIN DATA_Transaction WITH(NOLOCK)						ON DATA_Transaction.TransactionId = RR_DATA_Revenue.TransactionID
				INNER JOIN COA_CNF_Account WITH(NOLOCK)							ON COA_CNF_Account.SiteID = DATA_Transaction.SiteId
																					and COA_CNF_Account.ParentAccountId = @COAAccountId
			where RR_DATA_Revenue.COAAccountId = @COAAccountId
			  and RR_DATA_Revenue.FCalcDate = @batchdate
			  and ((RR_DATA_Revenue.paymentID is not null) or (RR_DATA_Revenue.SaleItemTaxId is not null) or (RR_DATA_Revenue.SaleItemRuleID is not null))
		)p

		FETCH NEXT FROM Parent_Cursor INTO 		
		@COAAccountId,
		@ParentAccountId,
		@Code,
		@SiteID
	end

	CLOSE Parent_Cursor;
	DEALLOCATE Parent_Cursor;

End
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>BCF6298B926A4A318CDAC15454401380</SqlScriptAK></Script></ScriptList></StoredProcedure></StoredProcedureList>
	<ViewList>
		<View Status="ACTIVE">
			<Name>AccountHistory</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[AccountHistory]
AS
SELECT
        DateOrd,
	DatePayment,
	DateCreation,                      
	ReservationAK,
	TransactionAK,
	AccountId,
	paymentamount,
	Debit,
	Credit,
	AmountDisc,
	UserName,
	Note,
	SettleCreditPayType
FROM (SELECT P.PaymentDate    AS DateOrd,
             P.FPaymentDate    AS DatePayment,
             dtcreation.trdate AS DateCreation,
             dr.ReservationAK,
             dt.TransactionAK,
			 PC.AccountId,
			 P.PaymentAmount  AS paymentamount,
             CASE WHEN p.paymentamount &amp;#62; 0 THEN p.paymentamount ELSE 0 END AS Debit,
             CASE WHEN p.paymentamount &amp;#60; 0 THEN case when dt.TransactionType &amp;#60;&amp;#62; 5 then ABS(p.paymentamount) else ABS(p.paymentamount) end ELSE 0 END AS Credit,
			 PC.AmountDisc,
             cu.UserName,
			 dn.Note,
			 (case when pc.SettleTransactionId = dt.TransactionId then '' else cl.description end) SettleCreditPayType
        FROM dbo.DATA_PaymentCredit AS PC WITH(NOLOCK)                                    --HERE
             INNER JOIN      dbo.DATA_Payment     AS  P WITH(NOLOCK) ON (P.PaymentId     = PC.PaymentId and P.PaymentStatus = 1)
             left  JOIN      dbo.DATA_Transaction AS dt WITH(NOLOCK) ON dt.TransactionId = P.TransactionId
             LEFT OUTER JOIN dbo.CNF_User         AS cu WITH(NOLOCK) ON cu.UserId        = dt.UserId
             left JOIN       dbo.DATA_Sale        AS ds WITH(NOLOCK) ON ds.SaleId        = dt.SaleId
             left JOIN       dbo.DATA_Note        AS dn WITH(NOLOCK) ON dn.NoteKey       = ds.SaleId AND dn.NoteType = 161
             left JOIN       dbo.DATA_Reservation AS dr WITH(NOLOCK) ON dr.SaleId        = ds.SaleId
             LEFT OUTER JOIN(SELECT MIN(FTransactionDate) AS trdate,
                                    SaleId
                               FROM dbo.DATA_Transaction AS dt  WITH(NOLOCK)
                             GROUP BY SaleId) AS dtcreation ON dtcreation.SaleId = ds.SaleId
             LEFT OUTER JOIN (SELECT MIN(PaymentType) AS pttype,
                              TransactionId
                                FROM dbo.DATA_Payment AS dp  WITH(NOLOCK)
                               WHERE dp.PaymentStatus = 1 --HERE
                              GROUP BY TransactionId) AS cs ON cs.TransactionId = PC.SettleTransactionId
             LEFT OUTER JOIN dbo.CNF_LookUp AS cl ON cl.ItemId = cs.pttype AND cl.LookUpTableId = 7  AND P.PaymentStatus = 1
UNION ALL
SELECT dt.TransactionDate AS DateOrd,
       dt.FTransactionDate AS DatePayment,
       dt.FTransactionDate AS DateCreation,
	   NULL AS Expr1,
	   dt.TransactionAk AS Expr2,
	   L.ReferenceId AS AccountId,
                     -- ISSUE #55399 2015 05 15
       L.EntryAmount + ISNULL(dpf.AmountFail,0) AS Expr3,
	   case when L.EntryAmount &amp;#62; 0 then L.EntryAmount else 0 end AS Debit,
                                                           -- ISSUE #55399 2015 05 15
	   case when L.EntryAmount &amp;#60; 0 then ABS(L.EntryAmount) - ISNULL(dpf.AmountFail,0) else 0 end AS Credit,
	   NULL AS Expr4,
       cu.UserName,
	   dn.Note AS Expr5,
	   cl.description SettleCreditPayType
 FROM dbo.DATA_Transaction AS dt WITH(NOLOCK)
LEFT  JOIN DATA_Note as dn WITH(NOLOCK) on  dn.NoteKey = dt.SaleId AND dn.NoteType = 161
INNER JOIN dbo.DATA_Ledger AS L WITH(NOLOCK) ON L.TransactionId = dt.TransactionId
INNER JOIN dbo.CNF_User AS cu WITH(NOLOCK) ON cu.UserId = dt.UserId
inner JOIN dbo.CNF_LedgerAccount AS LA WITH(NOLOCK) ON L.LedgerAccountId = LA.LedgerAccountId
INNER JOIN (SELECT MIN(PaymentType) AS pttype, TransactionId
              FROM dbo.DATA_Payment AS dp  WITH(NOLOCK)
            -- ISSUE #55399 2015 05 15
            WHERE  dp.PaymentStatus = 1
            GROUP BY TransactionId) AS cs_1 ON cs_1.TransactionId = dt.TransactionId
LEFT OUTER JOIN dbo.CNF_LookUp AS cl ON cl.ItemId = cs_1.pttype AND cl.LookUpTableId = 7
       --- ISSUE #55399 2015 05 15
       LEFT OUTER JOIN (SELECT SUM(ISNULL(DATA_Payment.PaymentAmount, 0)) AmountFail,
                               DATA_Payment.TransactionId
                          FROM DATA_Payment
                         WHERE DATA_Payment.PaymentStatus = 2
                         GROUP BY DATA_Payment.TransactionId) AS dpF ON dpF.TransactionId = dt.TransactionId

       --- ISSUE #55399 2015 05 15
       WHERE (dt.TransactionType in (34,6))
	   AND LA.SystemAccountId= 7
	   AND (L.ReferenceTable = 197)) AS CreditDebit
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>829231E4E6A64F7FB1EA48B36E033E11</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>CNF_MatrixCellOption</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>create view [dbo].[CNF_MatrixCellOption]
as(
select
  MC.MatrixCellId,
  5 as OptionType,
  MC.Code as OptionValue
from CNF_MatrixCell as MC

union

select
  MC.MatrixCellId,
  6 as OptionType,
  MC.Name as OptionValue
from CNF_MatrixCell as MC
union
select
  MC.MatrixCellId,
  7 as OptionType,
  MC.Description as OptionValue
from CNF_MatrixCell as MC
)</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>47B049C7EC834CDC9B3DAC2847EFAF89</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>ExportEncodedReservations</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[ExportEncodedReservations] as

	SELECT
		TR.TransactionId,
		TR.TransactionAK,
		TR.Completed,
		TR.SiteId,
		PAYTR.TransactionId PAYTrId,
		PAYTR.TransactionAK PAYTrAK,
		APPTR.TransactionId APPTrId,
		APPTR.TransactionAK APPTrAK
	FROM 
		DATA_Transaction TR With(NoLock)
		INNER JOIN DATA_Sale Sale With(NoLock) ON TR.SaleId = Sale.SaleId
		INNER JOIN DATA_Transaction PAYTR With(NoLock) ON Sale.SaleId = PAYTR.SaleId
															AND PAYTR.Paid &amp;#62; 0 
															AND PAYTR.Encoded = 0
															AND PAYTR.TransactionType = 16 --Lk_TransactionType_Reservation
		INNER JOIN DATA_Transaction APPTR With(NoLock) ON Sale.SaleId = APPTR.SaleId
															AND APPTR.Approved &amp;#62; 0 
															AND APPTR.Encoded = 0
															AND APPTR.TransactionType = 16 --Lk_TransactionType_Reservation
	WHERE 
		TR.Encoded = 1 
		AND TR.Paid = 0</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>5CB802C45EB5476495F800656AEB2E46</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>ExportNoPayTransactions</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[ExportNoPayTransactions] as
  
	SELECT
		SI.SiteCode,
		S.SaleId,
		TR.TransactionId,
		TR.Completed,
		TR.Encoded,
		0 as PaymentId,
		TR.SiteId,
		TR.TransactionAk,
		TR.FTransactionDate,
		WS.WorkstationAK,
		US.UserCode,
		OP.AreaCode,
		TR.TransactionType,
		LkTRType.Description as TransactionTypeDesc,
		0 as PaymentType,
		'NOPAY' as PaymentMethodDesc,
		TR.Revenue as TransactionAmount,
		CUR.ISOCode,
		CUR.ExchangeRate,
		'FALSE' as CREDIT,
		RES.ReservationAK,
		RES_AC.AccountId RES_AccountId,
		RES_AC.AccountAk RES_AccountAk,
		RES_DMGAC.DmgCategoryCode RES_AccountDMG
	FROM
		DATA_Transaction TR With(NoLock) 
		INNER JOIN DATA_Sale S With(NoLock) ON TR.SaleId = S.SaleId
		INNER JOIN CNF_Workstation WS With(NoLock) ON TR.WorkstationId = WS.WorkstationId
		INNER JOIN CNF_User US With(NoLock) ON TR.UserId = US.UserId
		INNER JOIN CNF_OperatingArea OP With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId
		INNER JOIN CNF_Site SI With(NoLock) ON TR.SiteId = SI.SiteId
		INNER JOIN CNF_LookUp LkTRType With(NoLock) ON TR.TransactionType = LkTRType.ItemId
														AND LkTRType.LookUpTableId = 3	--Lookup_TransactionType
		LEFT OUTER JOIN DATA_Reservation RES With(NoLock) ON TR.SaleId = RES.SaleId
		LEFT OUTER JOIN DATA_Account RES_AC With(NoLock) ON RES.AccountId = RES_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory RES_DMGAC With(NoLock) ON RES_DMGAC.DmgCategoryId = RES_AC.DmgCategoryId
		INNER JOIN CNF_Currency CUR With(NoLock) ON CUR.CurrencyType = 1
		LEFT OUTER JOIN DATA_Payment PAY With(NoLock) ON TR.TransactionId = PAY.TransactionId
	WHERE
		TR.Paid = 1
		AND S.Paid = 1
		AND PAY.PaymentId IS NULL
		AND TR.TransactionType &amp;#60;&amp;#62; 4	--Lk_TransactionType_Reissue
		AND (	
				(TR.TransactionType &amp;#60;&amp;#62; 7 AND TR.Quantity &amp;#62; 0 AND TR.Items &amp;#62; 0)	--Lk_TransactionType_UpgradeDowngrade
				OR
				(TR.TransactionType = 7 AND TR.Quantity = 0 AND TR.Items &amp;#62; 0)	--Lk_TransactionType_UpgradeDowngrade
			)</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>9311CAB9D3324A908550D4FFB30EFEE9</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>ExportTicketReissue</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[ExportTicketReissue] as

--reissue

	SELECT 
		SI.SaleItemId,
		TCK.SaleItemId AS TicketSaleItemId, 
		ABS(TI.Quantity) AS Quantity, 
		TI.ProductType,
		TR.TransactionId, 				 
		--TR.TransactionType, 	
		TR.SaleId,			 
		CNF_Site.SiteCode, 
		TR.TransactionAK, 
		TI.ItemId,
		TR.TransactionDate, 
		WS.WorkstationAK,
		US.UserCode, 
		OP.AreaCode,
		LkTRType.Description AS ActionType, --TransactionTypeDesc,
		SI.MatrixCellId AS TicketUniqueId, 
		MC.Code AS ProductCode,
		--identifiercode
		--StoredValue
		RESAC.AccountId AS AccountCode,
		RES.ReservationAK AS ReservationCode,
		DMGOP.DmgCategoryCode AS TransactionType,
		RESDMGAC.DmgCategoryCode AS AccountDMG,
		Promo.DmgCategoryCode AS PromoCategory,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (SI.UnitRawPrice * TI.Quantity)
			ELSE --(SI.UnitRawPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitRawPrice * TI.TransactionItemOperation)
				END 
		END AS GrossAmount,	 
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalAmount)
			ELSE --(SI.UnitPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitPrice * TI.TransactionItemOperation)
				END 
		END AS Amount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN ((SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity)
			ELSE --((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				END 
		END AS DiscountAmount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalTaxes)
			ELSE --(TI.UnitTaxes * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(TI.UnitTaxes * TI.TransactionItemOperation)
				END 
		END AS TaxAmount,
		SI.UnitRawPrice * TI.TransactionItemOperation AS UnitGrossAmount,
		TI.UnitPrice * TI.TransactionItemOperation AS UnitAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation AS UnitDiscountAmount,
		TI.UnitTaxes * TI.TransactionItemOperation AS UnitTaxAmount,
		(SI.UnitRawPrice * TI.Quantity) AS TotalGrossAmount,
		TI.TotalAmount AS TotalAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity AS TotalDiscountAmount,
		TI.TotalTaxes AS TotalTaxAmount,
		MultiPark.Code AS MultiParkYesNo, 
		ParkCombo.Code AS ParkCombo,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC1.Amount &amp;#60; 0 
						THEN -ISNULL(SICC1.UnitAmount, 0)
					ELSE ISNULL(SICC1.UnitAmount, 0)
				END
		END AS CC1,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC2.Amount &amp;#60; 0 
						THEN -ISNULL(SICC2.UnitAmount, 0)
					ELSE ISNULL(SICC2.UnitAmount, 0)
				END
		END AS CC2,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE	
					WHEN SICC3.Amount &amp;#60; 0 
						THEN -ISNULL(SICC3.UnitAmount, 0)
					ELSE ISNULL(SICC3.UnitAmount, 0)
				END
		END AS CC3,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC4.Amount &amp;#60; 0 
						THEN -ISNULL(SICC4.UnitAmount, 0)
					ELSE ISNULL(SICC4.UnitAmount, 0)
				END
		END AS CC4,
		TI.Quantity AS TicketQty,		
		SeasonalPass.Code AS SeasonalPassYesNo,
		TCK.ActiveTo AS TicketExpireDate,
		TCK.TicketId AS TicketId,
		SI.TicketId ReplacedTicketId,
		SI.ItemTicketId VoidedTicketId,
		TR.Completed, 
		TR.Siteid, 
		TCK.VoidType, 
		S2T.OperationType, 
		CASE 
			WHEN TCK.PrintDateTime IS NULL 
				THEN TCK.FEncodeDate 
			ELSE TCK.PrintDateTime 
		END AS EncodeDateTime, 
		TI.TransactionItemOperation, 
		TI.UnitPrice, 
		TI.UnitRecharge, 
		RESAC.AccountAk 
	FROM 
		DATA_TransactionItem TI				With(NoLock) 
		INNER JOIN DATA_Transaction TR		With(NoLock) ON TI.TransactionId = TR.TransactionId 
		INNER JOIN DATA_SaleItem SI			With(NoLock) ON TI.SaleItemId = SI.SaleItemId 
		INNER JOIN CNF_Workstation WS		With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US				With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP		With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		LEFT JOIN  CNF_DmgCategory DMGOP	With(NoLock) ON DMGOP.DmgCategoryId = OP.DmgCategoryId 
		INNER JOIN CNF_Site					With(NoLock) ON TR.SiteId = CNF_Site.SiteId 
		INNER JOIN CNF_LookUp LkTRType		With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
															AND LkTRType.LookUpTableId = 3	--Lookup_TransactionType
		INNER JOIN CNF_MatrixCell MC		With(NoLock) ON SI.MatrixCellId = MC.MatrixCellId 
		LEFT JOIN  CNF_MatrixSheet MS		With(NoLock) ON MS.MatrixSheetId = MC.MatrixSheetId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 4	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS MultiPark ON MultiPark.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 7	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS ParkCombo ON ParkCombo.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 1	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS SeasonalPass ON SeasonalPass.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  DATA_SaleItem2Ticket S2T	With(NoLock) ON SI.SaleItemId = S2T.SaleItemId
		LEFT JOIN  DATA_Ticket TCK			With(NoLock) ON TCK.TicketId = S2T.TicketId 
															AND TCK.VoidType IN (0, 1, 102, 107, 108, 109, 111)--, 125) 
															--Lk_VoidType_Active, Lk_VoidType_Inactive, Lk_VoidType_VoidByEncodingStation,
															--Lk_VoidType_UpgradeDowngrade, Lk_VoidType_BlockUnblock, Lk_VoidType_Refund,
															--Lk_VoidType_Reissue, 
															--Lk_VoidType_TransactionAbort removed
		--LEFT JOIN  DATA_SaleItem SIOriginal With(NoLock) ON TCK.SaleItemId = SIOriginal.SaleItemId
		LEFT JOIN  DATA_Reservation RES		With(NoLock) ON TR.SaleId = RES.SaleId 
															OR (RES.SaleId IN (	SELECT 
																					SaleId 
																				FROM 
																					DATA_Transaction2Ticket With(NoLock)
																					INNER JOIN DATA_Transaction With(NoLock) ON DATA_Transaction2Ticket.TransactionId = DATA_Transaction.TransactionId  
																				WHERE 
																					(DATA_Transaction2Ticket.TicketId = TCK.TicketId)
																					OR
																					(DATA_Transaction2Ticket.TicketId = SI.TicketId))
																					)  
		LEFT JOIN  DATA_Account RESAC		With(NoLock) ON RES.AccountId = RESAC.AccountId
		LEFT JOIN  CNF_DmgCategory RESDMGAC	With(NoLock) ON RESDMGAC.DmgCategoryId = RESAC.DmgCategoryId 
		LEFT JOIN  DATA_SaleItem2CostCenter SICC1	With(NoLock) ON SICC1.SaleItemId = SI.SaleItemId AND SICC1.CostCenterId = 1
		LEFT JOIN  DATA_SaleItem2CostCenter SICC2	With(NoLock) ON SICC2.SaleItemId = SI.SaleItemId AND SICC2.CostCenterId = 2
		LEFT JOIN  DATA_SaleItem2CostCenter SICC3	With(NoLock) ON SICC3.SaleItemId = SI.SaleItemId AND SICC3.CostCenterId = 3
		LEFT JOIN  DATA_SaleItem2CostCenter SICC4	With(NoLock) ON SICC4.SaleItemId = SI.SaleItemId AND SICC4.CostCenterId = 4
		OUTER APPLY  (	SELECT TOP 1
							PRDMGAC.DmgCategoryCode
						FROM
							DATA_TransactionItemRule TIR			With(NoLock) 
							LEFT JOIN  CNF_PromotionItemRule PRIR	With(NoLock) ON PRIR.PromotionItemRuleId = TIR.PromotionItemRuleId
							LEFT JOIN  CNF_PromotionItem PRI		With(NoLock) ON PRI.PromotionItemId = PRIR.PromotionItemId
							LEFT JOIN  CNF_Promotion PR				With(NoLock) ON PR.PromotionId = PRI.PromotionId
							LEFT JOIN  CNF_DmgCategory PRDMGAC		With(NoLock) ON PRDMGAC.DmgCategoryId = PR.DmgCategoryId  
						WHERE
							TIR.ItemId = TI.ItemId
					) as Promo
	WHERE 
		TR.TransactionType = 4			--Lk_TransactionType_Reissue</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>A89881E5C59B4567A1D93AA63C88DEE6</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>ExportTicketUsages</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[ExportTicketUsages] as

	SELECT       		
		TCK.FirstUsageId,
		TU.FUsageDate,
		TU.UsageType,
		--lkUT.Description AS UsageType, 
		--MC_Type.OptionValue AS CardActionType,
		MS.ProductType,
		S.SiteId, 
		S.SiteCode, 
		TR.TransactionAK,
		TR.SaleId,   
		TU.UsageId, 
		TU.UsageDate, 		
		WS.WorkstationAK, 
		'SYSTEM' AS UserCode, 
		OP.AreaCode,  
		ISNULL(lkUT.Description, '') + ' ' + ISNULL(MC_Type.OptionValue, '') AS ActionType,
		MC.MatrixCellId AS TicketUniqueId,  
		MC.Code AS ProductCode,
		MI.IdentifierCode,  
		RESAC.AccountId AS AccountCode,
		RES.ReservationAK AS ReservationCode,
		DMGOP.DmgCategoryCode AS TransactionType,
		RESDMGAC.DmgCategoryCode AS AccountDMG,
		Promo.DmgCategoryCode AS PromoCategory,
		(SI.UnitRawPrice) AS GrossAmount,	 
		(SI.UnitPrice) AS Amount,
		(SI.UnitRawPrice - SI.UnitPrice) DiscountAmount,
		(SI.UnitTaxes) TaxAmount,
		(SI.UnitRawPrice * SI.Quantity) AS TotalGrossAmount,
		(SI.TotalAmount) AS TotalAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * SI.Quantity AS TotalDiscountAmount,
		(SI.TotalTaxes) AS TotalTaxAmount,
		MultiPark.Code AS MultiParkYesNo, 
		ParkCombo.Code AS ParkCombo,
		CASE	
			WHEN SICC1.Amount &amp;#60; 0 
				THEN -ISNULL(SICC1.UnitAmount, 0)
			ELSE ISNULL(SICC1.UnitAmount, 0)
		END AS CC1,
		CASE	
			WHEN SICC2.Amount &amp;#60; 0 
				THEN -ISNULL(SICC2.UnitAmount, 0)
			ELSE ISNULL(SICC2.UnitAmount, 0)
		END AS CC2,
		CASE	
			WHEN SICC3.Amount &amp;#60; 0 
				THEN -ISNULL(SICC3.UnitAmount, 0)
			ELSE ISNULL(SICC3.UnitAmount, 0)
		END AS CC3,
		CASE	
			WHEN SICC4.Amount &amp;#60; 0 
				THEN -ISNULL(SICC4.UnitAmount, 0)
			ELSE ISNULL(SICC4.UnitAmount, 0)
		END AS CC4,
		1 AS TicketQty,
		SeasonalPass.Code AS SeasonalPassYesNo,
		TCK.ActiveTo AS TicketExpireDate,
		TCK.TicketId,
		NULL AS ReplacedTicketId, 
		TCK.Serial,  
		MC_Amount.OptionValue AS StoredValue,  
		TU.ValidateResult
	FROM            
		DATA_TicketUsage AS TU With(NoLock) 
		INNER JOIN DATA_MediaIdentifier AS MI With(NoLock) ON MI.MediaIdentifierId = TU.MediaIdentifierId 
		INNER JOIN CNF_Workstation AS WS With(NoLock) ON TU.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_OperatingArea AS OP With(NoLock) ON WS.OperatingAreaId = OP.OperatingAreaId
		LEFT JOIN  CNF_DmgCategory DMGOP	With(NoLock) ON DMGOP.DmgCategoryId = OP.DmgCategoryId 
		INNER JOIN CNF_Site AS S With(NoLock) ON WS.SiteId = S.SiteId 
		--INNER JOIN (	SELECT 
		--					MIN(UsageId) AS usageid, 
		--					TicketId,
		--					SiteId 
		--				FROM 
		--					DATA_TicketUsage
		--					INNER JOIN CNF_Workstation With(NoLock) ON CNF_Workstation.WorkstationId = DATA_TicketUsage.WorkstationId
		--				WHERE
		--					DATA_TicketUsage.UsageType = 1 --Lk_TicketUsageType_Entry
		--				GROUP BY 
		--					TicketId,
		--					SiteId) AS FTU ON FTU.TicketId = TU.TicketId 
		--										AND FTU.SiteId = Ws.SiteId 
		INNER JOIN DATA_Ticket AS TCK With(NoLock) ON TU.TicketId = TCK.TicketId 
		INNER JOIN DATA_Transaction2Ticket AS T2T With(NoLock) ON TCK.TicketId = T2T.TicketId 
																	AND T2T.OperationType = 1	--Lk_TicketOperationType_Create
		INNER JOIN DATA_Transaction AS TR With(NoLock) ON T2T.TransactionId = TR.TransactionId 
		INNER JOIN CNF_MatrixCell AS MC With(NoLock) ON TCK.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 4	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS MultiPark ON MultiPark.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 7	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS ParkCombo ON ParkCombo.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 1	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS SeasonalPass ON SeasonalPass.MatrixCellId = MC.MatrixCellId 
		INNER JOIN CNF_MatrixSheet AS MS With(NoLock) ON MC.MatrixSheetId = MS.MatrixSheetId 
		LEFT JOIN  CNF_LookUp AS lkUT With(NoLock) ON TU.UsageType = lkUT.ItemId 
															AND lkUT.LookUpTableId = 69	--Lookup_TicketUsageType
		LEFT JOIN  DATA_Reservation AS RES With(NoLock) ON TR.SaleId = RES.SaleId 
		LEFT JOIN  DATA_Account RESAC		With(NoLock) ON RES.AccountId = RESAC.AccountId
		LEFT JOIN  CNF_DmgCategory RESDMGAC	With(NoLock) ON RESDMGAC.DmgCategoryId = RESAC.DmgCategoryId 
		LEFT JOIN  DATA_TicketUsageOption AS MC_Amount With(NoLock) ON TU.UsageId = MC_Amount.UsageId 
																			AND MC_Amount.OptionType = 5	--Lk_TicketUsageOption_MoneyCardAmount
		LEFT JOIN  DATA_TicketUsageOption AS MC_Type With(NoLock) ON TU.UsageId = MC_Type.UsageId 
																			AND MC_Type.OptionType = 4		--Lk_TicketUsageOption_ProductDescription
		LEFT JOIN  DATA_SaleItem SI					With(NoLock) ON TCK.SaleItemId = SI.SaleItemId
		LEFT JOIN  DATA_SaleItem2CostCenter SICC1	With(NoLock) ON SICC1.SaleItemId = SI.SaleItemId AND SICC1.CostCenterId = 1
		LEFT JOIN  DATA_SaleItem2CostCenter SICC2	With(NoLock) ON SICC2.SaleItemId = SI.SaleItemId AND SICC2.CostCenterId = 2
		LEFT JOIN  DATA_SaleItem2CostCenter SICC3	With(NoLock) ON SICC3.SaleItemId = SI.SaleItemId AND SICC3.CostCenterId = 3
		LEFT JOIN  DATA_SaleItem2CostCenter SICC4	With(NoLock) ON SICC4.SaleItemId = SI.SaleItemId AND SICC4.CostCenterId = 4
		OUTER APPLY  (	SELECT TOP 1
							PRDMGAC.DmgCategoryCode
						FROM
							DATA_SaleItemRule SIR					With(NoLock) 
							LEFT JOIN  CNF_PromotionItemRule PRIR	With(NoLock) ON PRIR.PromotionItemRuleId = SIR.PromotionItemRuleId
							LEFT JOIN  CNF_PromotionItem PRI		With(NoLock) ON PRI.PromotionItemId = PRIR.PromotionItemId
							LEFT JOIN  CNF_Promotion PR				With(NoLock) ON PR.PromotionId = PRI.PromotionId
							LEFT JOIN  CNF_DmgCategory PRDMGAC		With(NoLock) ON PRDMGAC.DmgCategoryId = PR.DmgCategoryId  
						WHERE
							SIR.SaleItemId = SI.SaleItemId
					) as Promo
	WHERE        
		(TU.ValidateResult &amp;#60; 99)
		AND (TCK.VoidType not in (107, 111))	--Lk_VoidType_UpgradeDowngrade, Lk_VoidType_Reissue</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>91F147F5616F4BDF82E322919E70707B</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>ExportTransactionItems</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[ExportTransactionItems] AS  

	SELECT 
		SI.SaleItemId,
		TCK.SaleItemId AS TicketSaleItemId, 
		ABS(TI.Quantity) AS Quantity, 
		TI.ProductType,
		TR.TransactionId,
		--TR.TransactionType, 	
		TR.SaleId,			 
		CNF_Site.SiteCode, 
		TR.TransactionAK, 
		TI.ItemId,
		TR.TransactionDate, 
		WS.WorkstationAK,
		US.UserCode, 
		OP.AreaCode,
		LkTRType.Description AS ActionType, --TransactionTypeDesc,
		SI.MatrixCellId AS TicketUniqueId, 
		MC.Code AS ProductCode,
		--identifiercode
		--StoredValue
		RESAC.AccountId AS AccountCode,
		RES.ReservationAK AS ReservationCode,
		DMGOP.DmgCategoryCode AS TransactionType,
		RESDMGAC.DmgCategoryCode AS AccountDMG,
		Promo.DmgCategoryCode AS PromoCategory,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (SI.UnitRawPrice * TI.Quantity)
			ELSE --(SI.UnitRawPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitRawPrice * TI.TransactionItemOperation)
				END 
		END AS GrossAmount,	 
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalAmount)
			ELSE --(SI.UnitPrice * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(SI.UnitPrice * TI.TransactionItemOperation)
				END 
		END AS Amount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN ((SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity)
			ELSE --((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						((SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation)
				END 
		END AS DiscountAmount,
		CASE 
			WHEN (MS.ProductType = 2) 
			THEN (TI.TotalTaxes)
			ELSE --(TI.UnitTaxes * TI.TransactionItemOperation)
				CASE 
					WHEN (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
					THEN 0
					ELSE
						(TI.UnitTaxes * TI.TransactionItemOperation)
				END 
		END AS TaxAmount,
		SI.UnitRawPrice * TI.TransactionItemOperation AS UnitGrossAmount,
		TI.UnitPrice * TI.TransactionItemOperation AS UnitAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.TransactionItemOperation AS UnitDiscountAmount,
		TI.UnitTaxes * TI.TransactionItemOperation AS UnitTaxAmount,
		(SI.UnitRawPrice * TI.Quantity) AS TotalGrossAmount,
		TI.TotalAmount AS TotalAmount,
		(SI.UnitRawPrice - SI.UnitPrice) * TI.Quantity AS TotalDiscountAmount,
		TI.TotalTaxes AS TotalTaxAmount,
		MultiPark.Code AS MultiParkYesNo, 
		ParkCombo.Code AS ParkCombo,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC1.Amount &amp;#60; 0 
						THEN -ISNULL(SICC1.UnitAmount, 0)
					ELSE ISNULL(SICC1.UnitAmount, 0)
				END
		END AS CC1,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC2.Amount &amp;#60; 0 
						THEN -ISNULL(SICC2.UnitAmount, 0)
					ELSE ISNULL(SICC2.UnitAmount, 0)
				END
		END AS CC2,
		CASE
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE	
					WHEN SICC3.Amount &amp;#60; 0 
						THEN -ISNULL(SICC3.UnitAmount, 0)
					ELSE ISNULL(SICC3.UnitAmount, 0)
				END
		END AS CC3,
		CASE	
			WHEN (MS.ProductType &amp;#60;&amp;#62; 2) AND (TR.TransactionType &amp;#60;&amp;#62; 30) AND (TCK.TicketId IS NULL)
			THEN 0
			ELSE
				CASE
					WHEN SICC4.Amount &amp;#60; 0 
						THEN -ISNULL(SICC4.UnitAmount, 0)
					ELSE ISNULL(SICC4.UnitAmount, 0)
				END
		END AS CC4,
		TI.Quantity AS TicketQty,		
		SeasonalPass.Code AS SeasonalPassYesNo,
		TCK.ActiveTo AS TicketExpireDate,
		TCK.TicketId AS TicketId,
		SI.TicketId ReplacedTicketId,
		TR.Completed, 
		TR.Siteid, 
		TCK.VoidType, 
		S2T.OperationType, 
		CASE 
			WHEN TCK.PrintDateTime IS NULL 
				THEN TCK.FEncodeDate 
			ELSE TCK.PrintDateTime 
		END AS EncodeDateTime, 
		TI.TransactionItemOperation, 
		TI.UnitPrice, 
		TI.UnitRecharge, 
		RESAC.AccountAk 
	FROM 
		DATA_TransactionItem TI				With(NoLock) 
		INNER JOIN DATA_Transaction TR		With(NoLock) ON TI.TransactionId = TR.TransactionId 
		INNER JOIN DATA_SaleItem SI			With(NoLock) ON TI.SaleItemId = SI.SaleItemId 
		INNER JOIN CNF_Workstation WS		With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US				With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP		With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		LEFT JOIN  CNF_DmgCategory DMGOP	With(NoLock) ON DMGOP.DmgCategoryId = OP.DmgCategoryId 
		INNER JOIN CNF_Site					With(NoLock) ON TR.SiteId = CNF_Site.SiteId 
		INNER JOIN CNF_LookUp LkTRType		With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
															AND LkTRType.LookUpTableId = 3	--Lookup_TransactionType
		INNER JOIN CNF_MatrixCell MC		With(NoLock) ON SI.MatrixCellId = MC.MatrixCellId 
		LEFT JOIN  CNF_MatrixSheet MS		With(NoLock) ON MS.MatrixSheetId = MC.MatrixSheetId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 4	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS MultiPark ON MultiPark.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 7	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS ParkCombo ON ParkCombo.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  (SELECT
						SG.StatisticalGroupCode as Code,
						SGV.MatrixCellId	
					FROM
						CNF_StatisticalGroupValidity SGV With(NoLock)
						INNER JOIN CNF_StatisticalGroup SG With(NoLock) ON SG.ParentId = 1	
																			AND SG.StatisticalGroupId = SGV.StatisticalGroupId) AS SeasonalPass ON SeasonalPass.MatrixCellId = MC.MatrixCellId
		LEFT JOIN  DATA_SaleItem2Ticket S2T	With(NoLock) ON SI.SaleItemId = S2T.SaleItemId
		LEFT JOIN  DATA_Ticket TCK			With(NoLock) ON TCK.TicketId = S2T.TicketId 
															AND TCK.VoidType IN (0, 1, 102, 107, 108, 109, 111)--, 125) 
															--Lk_VoidType_Active, Lk_VoidType_Inactive, Lk_VoidType_VoidByEncodingStation,
															--Lk_VoidType_UpgradeDowngrade, Lk_VoidType_BlockUnblock, Lk_VoidType_Refund,
															--Lk_VoidType_Reissue, 
															--Lk_VoidType_TransactionAbort removed
		--LEFT JOIN  DATA_SaleItem SIOriginal With(NoLock) ON TCK.SaleItemId = SIOriginal.SaleItemId
		LEFT JOIN  DATA_Reservation RES		With(NoLock) ON TR.SaleId = RES.SaleId 
															OR (RES.SaleId IN (	SELECT 
																					SaleId 
																				FROM 
																					DATA_Transaction2Ticket With(NoLock)
																					INNER JOIN DATA_Transaction With(NoLock) ON DATA_Transaction2Ticket.TransactionId = DATA_Transaction.TransactionId  
																				WHERE 
																					DATA_Transaction2Ticket.TicketId = TCK.TicketId))  
		LEFT JOIN  DATA_Account RESAC		With(NoLock) ON RES.AccountId = RESAC.AccountId
		LEFT JOIN  CNF_DmgCategory RESDMGAC	With(NoLock) ON RESDMGAC.DmgCategoryId = RESAC.DmgCategoryId 
		LEFT JOIN  DATA_SaleItem2CostCenter SICC1	With(NoLock) ON SICC1.SaleItemId = SI.SaleItemId AND SICC1.CostCenterId = 1
		LEFT JOIN  DATA_SaleItem2CostCenter SICC2	With(NoLock) ON SICC2.SaleItemId = SI.SaleItemId AND SICC2.CostCenterId = 2
		LEFT JOIN  DATA_SaleItem2CostCenter SICC3	With(NoLock) ON SICC3.SaleItemId = SI.SaleItemId AND SICC3.CostCenterId = 3
		LEFT JOIN  DATA_SaleItem2CostCenter SICC4	With(NoLock) ON SICC4.SaleItemId = SI.SaleItemId AND SICC4.CostCenterId = 4
		OUTER APPLY  (	SELECT TOP 1
							PRDMGAC.DmgCategoryCode
						FROM
							DATA_TransactionItemRule TIR			With(NoLock) 
							LEFT JOIN  CNF_PromotionItemRule PRIR	With(NoLock) ON PRIR.PromotionItemRuleId = TIR.PromotionItemRuleId
							LEFT JOIN  CNF_PromotionItem PRI		With(NoLock) ON PRI.PromotionItemId = PRIR.PromotionItemId
							LEFT JOIN  CNF_Promotion PR				With(NoLock) ON PR.PromotionId = PRI.PromotionId
							LEFT JOIN  CNF_DmgCategory PRDMGAC		With(NoLock) ON PRDMGAC.DmgCategoryId = PR.DmgCategoryId  
						WHERE
							TIR.ItemId = TI.ItemId
					) as Promo  
	WHERE 
		TR.TransactionType &amp;#60;&amp;#62; 4			--Lk_TransactionType_Reissue</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>07D83AD76BF84F51BBAC782B59A208C7</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>ExportTransactionPayments</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[ExportTransactionPayments] AS 

	SELECT 
		SI.SiteCode, 
		TR.TransactionAk,
		TR.SaleId,  
		PAY.PaymentId, 
		PAY.FPaymentDate, 
		WS.WorkstationAK, 
		US.UserCode, 
		OP.AreaCode, 
		LkTRType.Description as TransactionTypeDesc, 
		PM.Description as PaymentMethodDesc, 
		CNFPAYC.CCName, 
		PAYC.AuthorizationCode, 
		PAYC.DevResponseCode, 
		PAY.PaymentAmount, 
		TR.Revenue as TransactionAmount,
		CASE
			WHEN PAYCR.PaymentId &amp;#62; 0
				THEN 'TRUE'
			ELSE
				'FALSE'
		END as CREDIT, 
		TR.TransactionId, 
		TR.Completed, 
		TR.Encoded, 
		TR.Items, 
		TR.TransactionType, 
		PAY.PaymentType, 
		LkPAYType.Description as PaymentTypeDesc, 
		CUR.ISOCode, 
		PAY.ExchangeRate, 
		AC.AccountId, 
		AC.AccountAk,
		DMGAC.DmgCategoryCode AccountDMG, 
		V.VoucherCode, 
		RES.ReservationAK, 
		RES_AC.AccountId RES_AccountId, 
		RES_AC.AccountAk RES_AccountAk,
		RES_DMGAC.DmgCategoryCode RES_AccountDMG, 
		DEBT.PaymentId DEBT_ID, 
		DEBT_RES.ReservationAK DEBT_ReservationAK, 
		DEBT_V.VoucherCode DEBT_VoucherCode, 
		DEBT_AC.AccountId DEBT_AccountId, 
		DEBT_AC.AccountAk DEBT_AccountAk,
		DEBT_DMGAC.DmgCategoryCode DEBT_AccountDMG,  
		V_AC.AccountId V_AccountId, 
		V_AC.AccountAk V_AccountAk,
		V_DMGAC.DmgCategoryCode V_AccountDMG,
		TR.FTransactionDate, 
		TR.SiteId
	FROM 
		DATA_Payment PAY With(NoLock) 
		INNER JOIN DATA_Transaction TR With(NoLock) ON TR.TransactionId = PAY.TransactionId 
		INNER JOIN CNF_PaymentMethod PM With(NoLock) ON PAY.PaymentMethodId = PM.PaymentMethodId 
		INNER JOIN CNF_Workstation WS With(NoLock) ON TR.WorkstationId = WS.WorkstationId 
		INNER JOIN CNF_User US With(NoLock) ON TR.UserId = US.UserId 
		INNER JOIN CNF_OperatingArea OP With(NoLock) ON TR.OperatingAreaId = OP.OperatingAreaId 
		INNER JOIN CNF_Site SI With(NoLock) ON TR.SiteId = SI.SiteId 
		INNER JOIN CNF_LookUp LkTRType With(NoLock) ON TR.TransactionType = LkTRType.ItemId 
														AND LkTRType.LookUpTableId = 3
		INNER JOIN CNF_LookUp LkPAYType With(NoLock) ON PAY.PaymentType = LkPAYType.ItemId 
														AND LkPAYType.LookUpTableId = 7
		LEFT OUTER JOIN DATA_PaymentCard PAYC With(NoLock) ON PAY.PaymentId = PAYC.PaymentId 
		LEFT OUTER JOIN CNF_PaymentCard CNFPAYC With(NoLock) ON PAYC.PaymentCardId = CNFPAYC.PaymentCardId 
		LEFT OUTER JOIN DATA_PaymentCredit PAYCR With(NoLock) ON PAY.PaymentId = PAYCR.PaymentId 
		LEFT OUTER JOIN DATA_Account AC With(NoLock) ON PAYCR.AccountId = AC.AccountId
		left outer join CNF_DmgCategory DMGAC With(NoLock) ON DMGAC.DmgCategoryId = AC.DmgCategoryId 
		LEFT OUTER JOIN DATA_Voucher V With(NoLock) ON PAYCR.EntityId = V.VoucherId 
														AND PAYCR.EntityTable = 186
		LEFT OUTER JOIN DATA_Account V_AC With(NoLock) ON V.AccountId = V_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory V_DMGAC With(NoLock) ON V_DMGAC.DmgCategoryId = V_AC.DmgCategoryId  
		LEFT OUTER JOIN DATA_Reservation RES With(NoLock) ON TR.SaleId = RES.SaleId 
		LEFT OUTER JOIN DATA_Account RES_AC With(NoLock) ON RES.AccountId = RES_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory RES_DMGAC With(NoLock) ON RES_DMGAC.DmgCategoryId = RES_AC.DmgCategoryId 
		LEFT OUTER JOIN DATA_PaymentCredit DEBT With(NoLock) ON PAY.TransactionId = DEBT.SettleTransactionId 
		LEFT OUTER JOIN DATA_Account DEBT_AC With(NoLock) ON DEBT.AccountId = DEBT_AC.AccountId
		LEFT OUTER JOIN CNF_DmgCategory DEBT_DMGAC With(NoLock) ON DEBT_DMGAC.DmgCategoryId = DEBT_AC.DmgCategoryId  
		LEFT OUTER JOIN DATA_Voucher DEBT_V With(NoLock) ON DEBT.EntityId = DEBT_V.VoucherId 
															AND DEBT.EntityTable = 186
		LEFT OUTER JOIN DATA_Payment DEBT_PAY With(NoLock) ON DEBT.PaymentId = DEBT_PAY.PaymentId 
		LEFT OUTER JOIN DATA_Transaction DEBT_TR With(NoLock) ON DEBT_PAY.TransactionId = DEBT_TR.TransactionId 
		LEFT OUTER JOIN DATA_Reservation DEBT_RES With(NoLock) ON DEBT_TR.SaleId = DEBT_RES.SaleId 
		INNER JOIN CNF_Currency CUR With(NoLock) ON PAY.CurrencyId = CUR.CurrencyId 
	WHERE 
		(DEBT_TR.TransactionType &amp;#60;&amp;#62; 22 OR DEBT_TR.TransactionType IS NULL)	--Lk_TransactionType_VoidTransaction
		AND PAY.PaymentStatus = 1	--Lk_PaymentStatus_Approved</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>5CB2CC8FE8D14ACABA2A9FB56C9A22CA</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="DELETED">
			<Name>otn_vw_0004_520106</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>CREATE VIEW [dbo].[otn_vw_0004_520106] 
AS
(

)
</SQL>
					<CheckSuccess>1</CheckSuccess>
					<SqlScriptAK>1904DDA2118546DC97F9427D0BD88D85</SqlScriptAK>
				</Script>
			</ScriptList>
		</View>
		<View Status="DELETED"><Name>otn_vw_AccountLimit</Name><ScriptList><Script Type="VW"><Database>stMsSQL2005</Database><Version>1</Version><SQL>CREATE view [dbo].[otn_vw_AccountLimit]
as

select  accountid,
		dmgcategoryID,
		AccountRestrictionId,
		PerformanceID,
		Eventid,
		PerfDateTime,
		Saledate,                   
		cast(Description as varchar(100))  as ResDescription,   
		ISNULL(Saleid, ' ') as SaleID ,             
		ISNULL(TicketName, ' ') as TicketName,               
		ISNULL(ReservationAccountQuantity,  ' ') as ReservationAccountQuantity,      
		ISNULL(TicketAccountQuantity,  ' ') as TicketAccountQuantity,         
		ISNULL(WorkstationAK,  ' ') as WorkstationAK,         
		ISNULL(UserName,  ' ') as UserName,         
		ISNULL(reservationAK,  ' ') as reservationAK         
 from (             
			  select  DATA_AccountLimit.accountid, 
			      Null dmgcategoryID,
				  CNF_AccountRestriction.AccountRestrictionId as AccountRestrictionId,     
				  CNF_AccountRestriction.StartDateTime as StartDateTime,                   
				  CNF_AccountRestriction.EndDateTime as EndDateTime,                       
				  CNF_AccountRestriction.Enabled as Enabled,                                 
				  CNF_AccountRestriction.Description as Description,                         
				  CNF_AccountRestriction.RestrictionType as RestrictionType,                   
				  CNF_AccountRestriction.ReservationAccountLimit as ReservationAccountLimit,  
				  CNF_AccountRestriction.TicketAccountLimit as TicketAccountLimit,             
				  Lookup_0.Description as RestrictionDescription,                              
				  DATA_AccountLimit.SaleDate,                                                  
				  DATA_AccountLimit.SaleID,                                                    
				  DATA_AccountLimit.SaleItemid,                                                
				  '[' + cnf_Matrixcell.code + ']' + cnf_Matrixcell.Name as TicketName,            
				  DATA_AccountLimit.ReservationAccountQuantity,                                  
				  DATA_AccountLimit.TicketAccountQuantity,                                        
				  cnf_User.username,                                                
				  cnf_workstation.workstationAK,                                                           
				  data_reservation.reservationAK as reservationAK,
				  cnf_performance.PerformanceID,
				  cnf_performance.Eventid,
				  cnf_performance.PerfDateTime

			  from CNF_AccountRestriction with (nolock)                                            
				INNER JOIN DATA_AccountLimit WITH(NOLOCK)						ON data_accountlimit.accountrestrictionid = cnf_accountrestriction.accountrestrictionid  				
				LEFT  JOIN cnf_performance WITH(NOLOCK)							ON cnf_performance.Performanceid = data_accountlimit.Performanceid
				LEFT  JOIN cnf_event WITH(NOLOCK)								ON cnf_event.eventid = cnf_performance.eventid
				INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_accountLimit.SaleitemID
				INNER JOIN data_sale WITH(NOLOCK)								ON data_sale.saleid = data_saleitem.saleid
				INNER JOIN cnf_user WITH(NOLOCK)								ON cnf_user.Userid = data_sale.Userid
				INNER JOIN cnf_Workstation WITH(NOLOCK)							ON cnf_Workstation.workstationid = data_sale.workstationid
				INNER JOIN cnf_Matrixcell WITH(NOLOCK)							ON cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid     
				LEFT  JOIN data_reservation WITH(NOLOCK)						ON data_reservation.saleid = data_accountlimit.saleid         
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId = 818)                                                     
					) AS Lookup_0											ON Lookup_0.ItemId=CNF_AccountRestriction.RestrictionType  
					
			UNION ALL

			select CNF_AccountRestriction2Account.Accountid,
			      CNF_AccountRestriction2dmgCategory.dmgcategoryid,
				  CNF_AccountRestriction.AccountRestrictionId as AccountRestrictionId,      
				  CNF_AccountRestriction.StartDateTime as StartDateTime,              
				  CNF_AccountRestriction.EndDateTime as EndDateTime,                
				  CNF_AccountRestriction.Enabled as Enabled,                        
				  data_note.Note as Description,          
				  null as RestrictionType,                                     
				  null as ReservationAccountLimit,                              
				  CNF_AccountRestriction.TicketAccountLimit as TicketAccountLimit,       
				  Lookup_0.Description as RestrictionDescription,                  
				  data_note.notedate,                                         
				  null,                                                        
				  null,                                                         
				  null,                                                         
				  null,                                                         
				  null,                                                           
				  cnf_User.username,                                                
				  cnf_workstation.workstationAK,                                    
				  null,
				  null,
				  null,
				  null

			  from                                                                
				CNF_AccountRestriction with (nolock)                              
				  left  join CNF_AccountRestriction2Account with (nolock)			ON CNF_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId       
				  left  join CNF_AccountRestriction2dmgCategory with (nolock)		ON CNF_AccountRestriction2dmgCategory.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId    
				INNER JOIN data_note WITH(NOLOCK)								on data_note.notekey = CNF_AccountRestriction.AccountRestrictionId       
												and data_note.notetype = 518               
												and data_note.note = 'Reset completed'        
				INNER JOIN cnf_User WITH(NOLOCK)                 ON cnf_User.userid = data_Note.Userid        
				INNER JOIN cnf_Workstation WITH(NOLOCK)          ON cnf_workstation.workstationid = data_note.workstationid     
				inner join (	  SELECT CNF_LookUp.ItemId,                                       
						   ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description               
						FROM CNF_Lookup with (nolock)                                   
						LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)     
											   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)       
											   and (CNF_MultiLanguage.FormName = 'LOOKUP')      
											   and (CNF_MultiLanguage.LanguageId = 0)         
						WHERE (CNF_LookUp.LookUpTableId = 818)                                
					) AS Lookup_0											ON Lookup_0.ItemId=CNF_AccountRestriction.RestrictionType  
    
   
 )p   
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>F651DB1615094E2AB8880D24160693BD</SqlScriptAK></Script></ScriptList></View><View Status="ACTIVE"><Name>vwCNF_RightDetailed</Name><ScriptList><Script Type="VW"><Database>stMsSQL2005</Database><Version>3</Version><SQL>CREATE VIEW [dbo].[vwCNF_RightDetailed]
-- 28/01/2025 This View has been created in order to optimize the time of reading the CNF_Rights&amp;#62;Attribute Information
-- They are static and so we decided to use the easy code below instead of parse the XML that is more expensive 
AS 
SELECT 
    RightId, 
    RightAK,
    DataType,
    FamilyType,
    CASE
 	WHEN (CHARINDEX('&amp;#60;Visibility&amp;#62;', Attribute) &amp;#62; 0)
	THEN SUBSTRING(Attribute,CHARINDEX('&amp;#60;Visibility&amp;#62;', Attribute)+LEN('&amp;#60;Visibility&amp;#62;'),CHARINDEX('&amp;#60;/Visibility&amp;#62;',Attribute)-CHARINDEX('&amp;#60;Visibility&amp;#62;', Attribute)-LEN('&amp;#60;Visibility&amp;#62;'))
	ELSE NULL
    END As Attribute_Visibility,
    CASE
	WHEN (CHARINDEX('&amp;#60;Default&amp;#62;', Attribute) &amp;#62; 0)
	THEN SUBSTRING(Attribute,CHARINDEX('&amp;#60;Default&amp;#62;', Attribute)+LEN('&amp;#60;Default&amp;#62;'),CHARINDEX('&amp;#60;/Default&amp;#62;',Attribute)-CHARINDEX('&amp;#60;Default&amp;#62;', Attribute)-LEN('&amp;#60;Default&amp;#62;'))
        ELSE NULL
    END As Attribute_Default,
    CASE
        WHEN (CHARINDEX('&amp;#60;Table&amp;#62;', Attribute) &amp;#62; 0)
	THEN SUBSTRING(Attribute,CHARINDEX('&amp;#60;Table&amp;#62;', Attribute)+LEN('&amp;#60;Table&amp;#62;'),CHARINDEX('&amp;#60;/Table&amp;#62;',Attribute)-CHARINDEX('&amp;#60;Table&amp;#62;', Attribute)-LEN('&amp;#60;Table&amp;#62;'))
	ELSE NULL
    END As Attribute_Table,
    CASE
 	WHEN (CHARINDEX('&amp;#60;Description&amp;#62;', Attribute) &amp;#62; 0)
	THEN SUBSTRING(Attribute,CHARINDEX('&amp;#60;Description&amp;#62;', Attribute)+LEN('&amp;#60;Description&amp;#62;'),CHARINDEX('&amp;#60;/Description&amp;#62;',Attribute)-CHARINDEX('&amp;#60;Description&amp;#62;', Attribute)-LEN('&amp;#60;Description&amp;#62;'))
	ELSE NULL
    END As Attribute_Description
FROM 
    CNF_Right WITH(NOLOCK)
</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>650B5AEA55A54FEDBC7C531C267C9302</SqlScriptAK></Script></ScriptList></View><View Status="ACTIVE">
			<Name>vwDmgCategoryHiercachy</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>1</Version>
					<SQL>create view [dbo].[vwDmgCategoryHiercachy]
as
WITH DmgHiercachy AS
 (SELECT DmgCategoryId, DmgCategoryId DMGParentId, 0 as level, description as parentdescr, description
    FROM CNF_DmgCategory
   WHERE DmgType = 1
  UNION ALL
  SELECT DmgParent.DmgCategoryId,
         DmgHiercachy.DmgParentId,DmgHiercachy.level +1 as level,
         DmgHiercachy.parentdescr as parentdescr, DmgParent.description
    FROM CNF_DmgCategory DmgParent, DmgHiercachy
   WHERE DmgParent.DMGParentId = DmgHiercachy.DmgCategoryId)
SELECT DmgCategoryId, DmgParentId, level, parentdescr, Description
  FROM DmgHiercachy</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>8EC325A9E2734EA6933A75B0B2BBCE64</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>vwInntopia_ExportAccountInformation</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>2</Version>
					<SQL>CREATE view [dbo].[vwInntopia_ExportAccountInformation]
AS

select DATA_Reservation.Reservationak,
       data_account.Accountid as CustomerAccountID,
       data_account.ParentAccountID as FamilyID,
	   TitleData.MaskData as Title,
	   data_account.FirstName,
	   data_account.SurName as LastName,
	   BirthDate.maskdata as Birthdate,
	   GenderData.MaskData as Gender,
	   Data_Account.Address1 as Address1,
	   Address2.MaskData as Address2,
	   Address3.MaskData as Address3,
	   data_account.City,
	   data_account.State,
	   data_account.ZipCode as PostalCode,
	   data_account.Country as Country,
	   AddressOptOut.MaskData as AddressOptOut,
	   data_account.EmailAddress1 as EmailAddress,
	   EmailOptOut.MaskData as EmailOptOut,
	   COALESCE(data_account.MobilePhone, data_account.HomePhone, data_account.BusinessPhone) as PhoneNumber,
	   PhoneOptOut.MaskData as PhoneOptOut,
	   data_account.DmgCategoryId as AccountCategoryID,
	   CNF_DmgCategory.Description as AccountCategoryDesc,
	   data_account.UpdDateTime,
	   data_account.InsDateTime

from data_account
	INNER JOIN DATA_Reservation				ON Data_Reservation.Accountid = Data_Account.Accountid
	INNER JOIN CNF_DmgCategory				on CNF_DmgCategory.dmgcategoryID = data_account.DmgCategoryId
	LEFT  JOIN DATA_DmgData TitleData		on TitleData.fkey = data_account.accountid 
	                                           and TitleData.dmgtype = 1 and TitleData.ObjType = 5
	LEFT  JOIN DATA_DmgData BirthDate		on BirthDate.fkey = data_account.accountid
	                                           and BirthDate.dmgtype = 1 and BirthDate.ObjType = 24
	LEFT  JOIN DATA_DmgData GenderData		on GenderData.fkey = data_account.accountid
	                                           and GenderData.dmgtype = 1 and GenderData.ObjType = 24
	LEFT  JOIN DATA_DmgData Address2		on Address2.fkey = data_account.accountid
	                                           and Address2.dmgtype = 1 and Address2.ObjType = 7
	LEFT  JOIN DATA_DmgData Address3		on Address3.fkey = data_account.accountid
	                                           and Address3.dmgtype = 1 and Address3.ObjType =27
	LEFT  JOIN DATA_DmgData AddressOptOut	on AddressOptOut.fkey = data_account.accountid
	                                           and AddressOptOut.dmgtype = 1 and AddressOptOut.ObjType =5002
	LEFT  JOIN DATA_DmgData EmailOptOut		on EmailOptOut.fkey = data_account.accountid
	                                           and EmailOptOut.dmgtype = 1 and EmailOptOut.ObjType =5001
	LEFT  JOIN DATA_DmgData PhoneOptOut		on PhoneOptOut.fkey = data_account.accountid
	                                           and PhoneOptOut.dmgtype = 1 and PhoneOptOut.ObjType =5004
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>454EBD53290944D199EB3E36F662265E</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>vwInntopia_ExportPassInformation</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>2</Version>
					<SQL>CREATE view [dbo].[vwInntopia_ExportPassInformation]
AS

select data_Account.Accountid as CustomerAccountID,
       data_sale.saleid as SalesID,
	   data_saleitem.saleitemid as SaleitemID,
	   Data_Ticket.Ticketid as Ticketid,
	   VoidType.Description as VoidType,
	   data_saleitem.UnitPrice as Unitprice,
	   data_sale.fsaleDate as SalesDate,
	   Data_Ticket.ActiveFrom as Activefrom,
	   data_ticket.ActiveTo as ActiveTo,
	   cnf_matrixcell.matrixcellid as ProductID,
	   cnf_matrixcell.Description as ProductDescription,
	   cnf_dmgcategory.description as ProductCategoryDescription,
	   cnf_matrixsheet.Matrixsheetname as ProductGroup
	   
from data_Account
	INNER JOIN data_ticket				on data_ticket.accountid = data_account.accountid
	INNER JOIN DATA_SaleItem			on data_saleitem.saleitemid = data_ticket.saleitemid
	INNER JOIN DATA_Sale				on data_sale.saleid = data_saleitem.saleid
	INNER JOIN CNF_MatrixCell			on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid
	LEFT  JOIN CNF_DmgCategory			on CNF_DmgCategory.dmgcategoryid = cnf_matrixcell.dmgcategoryid
	INNER JOIN CNF_MatrixSheet			on CNF_MatrixSheet.matrixsheetid = cnf_matrixcell.MatrixSheetId
	INNER JOIN CNF_LookUp VoidType		on Voidtype.Itemid = data_ticket.voidtype and VoidType.lookuptableid = 5</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>98BE84BA8A7A4680ACA509696BA3AC53</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>vwInntopia_ExportSales</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>2</Version>
					<SQL>CREATE view [dbo].[vwInntopia_ExportSales]
AS


Select Data_Sale.Saleid,
	   DATA_SaleItem.SaleItemId as SaleslineID,
	   data_reservation.accountid as PurchaserCustomerID,
	   data_ticket.accountid as ParticipantCustomerID,
	   cnf_matrixcell.matrixcellid as ProductID,
	   cnf_matrixcell.description as ProductDescription,
	   CNF_DmgCategory.Description as ProductCategoryDescription,
	   cnf_matrixsheet.matrixsheetname as ProductGroup,
	   case when data_sale.Completed = 1 then 'Completed'
	        when data_sale.Validated = 1 then 'Validated'
			when data_sale.Encoded = 1 then 'Encoded'
			when data_sale.Paid = 1 then 'Paid'
		end as Status,
	   1 as SaleItemQuantity,
	   data_saleitem.unitrawprice as UnitPrice,
	   data_saleitem.unittaxes as UnitTaxes,
	   (select sum(discountamount) from data_saleitemrule where data_saleitemrule.saleitemid = DATA_SaleItem.saleitemid) as promotionamount,
	   CNF_Workstation.WorkstationAK as WorkstationAK,
	   CNF_OperatingArea.OpAreaName as OperatingAreaName,
	   SaleSite.SiteName as SaleSiteName,
	   CNF_Location.LocationID as EventLocationID,
	   CNF_Location.Name as EventLocationDescription,
	   PerfSite.SiteName as PerfSiteName,
	   data_sale.saledate as SalesDate,
	   CNF_Performance.PerfDateTime as PerformanceBeginDate,
	   CNF_Performance.PerformanceEnd as PerformanceEndDate,
	   CNF_Performance.PerformanceID,
	   CNF_Performance.PerformanceName as PerformanceDescription,
	   CNF_User.Userid as Agentid,
	   CNF_User.UserName as AgentName,
	   null as ExternalOrderID,
	   null as ExternalSource,
	   data_sale.Approved,
	   data_sale.Paid,
	   data_sale.Completed,
	   data_sale.Validated,
	   data_sale.Encoded

from data_sale
	INNER JOIN DATA_SaleItem				on data_saleitem.saleid = data_sale.saleid
	INNER JOIN DATA_Reservation				on DATA_Reservation.saleid = data_sale.saleid
	LEFT  JOIN DATA_Ticket					on data_ticket.Saleitemid = data_saleitem.saleitemid
	INNER JOIN CNF_MatrixCell				on cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid
	LEFT  JOIN CNF_DmgCategory				on CNF_DmgCategory.Dmgcategoryid = cnf_matrixcell.dmgcategoryid
	INNER JOIN CNF_MatrixSheet				on cnf_matrixsheet.matrixsheetid = cnf_matrixcell.MatrixSheetId
	INNER JOIN CNF_Workstation				on CNF_Workstation.workstationid = data_sale.WorkstationId
	INNER JOIN CNF_OperatingArea			on CNF_OperatingArea.OperatingAreaId = cnf_workstation.OperatingAreaId
	INNER JOIN CNF_Site	SaleSite			on SaleSite.SiteID = CNF_OperatingArea.SiteID
	INNER JOIN CNF_User						on CNF_User.Userid = data_sale.userid
	LEFT  JOIN data_saleitem2Performance	on data_saleitem2Performance.saleitemid = data_saleitem.saleitemid
	LEFT  JOIN CNF_Performance				on cnf_performance.performanceid = data_saleitem2Performance.PerformanceId
	LEFT  JOIN ADM_AccessConfiguration		on ADM_AccessConfiguration.AccessConfigurationId = CNF_Performance.AccessConfigurationId
	LEFT  JOIN CNF_Location					on cnf_location.locationid = ADM_AccessConfiguration.locationid
	LEFT  JOIN CNF_Site	PerfSite			on PerfSite.SiteID = CNF_OperatingArea.SiteID

Where Data_Sale.Paid = 1</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>4BDC3C721AE145C393DA462CD18A3281</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>vwInntopia_ExportScanInformationforAccounts</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>2</Version>
					<SQL>CREATE view [dbo].[vwInntopia_ExportScanInformationforAccounts]
AS

select Data_ticket.Accountid as TicketAccountID,
       DATA_MediaIdentifier.IdentifierCode as MediaIdentifierCode,
	   Data_Account.Membership as Membershipflag,
	   Data_TicketUsage.Usagedate,
	   Adm_Gate.Gateid as ScanLocationKey,
	   Adm_Gate.Description as ScanLocationDescription,
	   cnf_Site.Siteid as ScanLocationResort,
	   cnf_Site.Sitename as ScanLocationResortName,
	   (select count(*)
		from data_ticketusage DTU
			INNER JOIN DATA_Ticket DT		    on DT.ticketid = DTU.ticketid

		where DTU.UsageType = 1
			and DT.ticketid = data_ticket.ticketid
			and DTU.ValidateResult &amp;#60; 100) TotalNumofScansforThisTicket


from data_ticket
	INNER JOIN DATA_Account						on data_account.accountid = data_ticket.accountid
	INNER JOIN DATA_TicketUsage					on data_ticketusage.ticketid = data_ticket.ticketid
	INNER JOIN CNF_MatrixCell					on cnf_matrixcell.matrixcellid = data_ticket.matrixcellid
	INNER JOIN DATA_MediaIdentifier				on DATA_MediaIdentifier.MediaIdentifierId = data_ticketusage.MediaIdentifierId
	INNER JOIN ADM_Gate							on ADM_Gate.Gateid = data_ticketusage.Gateid
	INNER JOIN cnf_location						on cnf_location.Locationid = Adm_Gate.Locationid
	INNER JOIN CNF_Site							on cnf_Site.Siteid = cnf_location.siteid

where data_ticketusage.ValidateResult &amp;#60; 100
  and data_ticketUsage.usagetype = 1</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>3F08D4C249B040ACB34FA64618524289</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>vwStatisticalGroup</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>2</Version>
					<SQL>CREATE view [dbo].[vwStatisticalGroup]
as
select
Main.StatisticalGroupId MainId,
cschild.StatisticalGroupId ChildId,
Main.StatisticalGroupDescription,
cschild.StatisticalGroupDescription Child,
Main.Level MainLevel,
cschild.Level ChildLevel,
cschild.Level-Main.Level RelLevel,
Main.Position MainPosition,
cschild.Position ChildPosition,
cschild.Position-Main.Position RelPosition

from
(
select
csg.Level,
csg.Position,
csg.StatisticalGroupId,
csg.Position StartPos,
csg.StatisticalGroupDescription,
Min(csgns.Position) EndPos
from
cnf_statisticalgroup csg left join
cnf_statisticalgroup csgns on csgns.Level &amp;#60;= csg.Level and csgns.Position&amp;#62;csg.Position
group by
csg.Level,
csg.Position,
csg.StatisticalGroupDescription,
csg.StatisticalGroupId,
csg.Position
union
select
0,
0,
null,
0,
'All',
null
) Main left join
( select StatisticalGroupId, StatisticalGroupCode, StatisticalGroupDescription, ParentId, Position, Level from cnf_statisticalgroup
 union
 select
  0,'','All',null,0,0) as cschild on cschild.Position &amp;#62;= Main.StartPos and cschild.Position &amp;#60;= IsNull(EndPos-1, cschild.Position)
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>0F3F4E99B63C4DED8DD2043200C448C6</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>vwStock_Inventory</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>4</Version>
					<SQL>CREATE VIEW [dbo].[vwStock_Inventory]
AS
-- modify 12/09/2024 by nchinea ticket IDBOS-10837
SELECT 
	SCP.MinStock,
	SCP.MatrixCellId,
	SCP.SKU                             AS Product,
	dbo.STOCK_CNF_Warehouse.WarehouseId,
	dbo.STOCK_CNF_Um.Description        AS Um,
	dbo.STOCK_CNF_Warehouse.Description AS WareHouse,
	Sum(Inventory.QtyLeft)              AS QtyLeft,
        Sum(Inventory.QtyLeft1)             AS QtyLeft1,
	Sum(Inventory.QtyOut)               AS QtyOut,
	Sum(Inventory.QtyToMove)            AS QtyToMove,
	Sum(Inventory.QtyToMove1)           AS QtyToMove1,
	dbo.CNF_MatrixCell.Price,
	dbo.CNF_MatrixCell.Name
FROM   
(
SELECT 
	MatrixCellId,
	WarehouseId,
	Sum(CASE WHEN MovementType IN ( 5, 6 ) THEN 0 ELSE QtyLeft END) AS QtyLeft1,
	sum(QtyLeft) as QtyLeft,
	0            AS QtyOut,
	0            AS QtyToMove,
	0            AS QtyToMove1
	FROM   dbo.STOCK_Movement WITH (nolock)
	WHERE  
           ( InOut = 1 )           
	   AND ( Completed = 1 )
	   AND ( ApprovalStatus = 1 )
	GROUP BY MatrixCellId,
		 	 WarehouseId

	UNION

SELECT 
	MatrixCellId,
	WarehouseId,
	0                   AS QtyLeft1,
	0                   AS QtyLeft,
	Sum(qty)            AS QtyOut,
	Sum(qty - qtymoved) AS QtyToMove,
	0         AS QtyToMove1
	FROM   dbo.STOCK_Movement AS STOCK_Movement_2 WITH (nolock)
	WHERE  ( InOut = -1 ) 
	   AND ( MovementDate = Dateadd(day, Datediff(day, 0, Getdate()), 0) )
	   AND ( ApprovalStatus = 1 )
	GROUP BY MatrixCellId,
		 	 WarehouseId

	UNION

SELECT 
	MatrixCellId,
	WarehouseId,
	0         AS QtyLeft1,
	0         AS QtyLeft,
	Sum(-qty) AS QtyOut,
	0         AS QtyToMove,
	Sum(-qty) AS QtyToMove1 -- In order to manage correctly the QtyToMove in case of Refund or Void Sales
	FROM   dbo.STOCK_Movement AS STOCK_Movement_1 WITH (nolock)
	WHERE  ( InOut = 1 )
	   AND ( MovementType IN ( 5, 6 ) )
	   AND ( MovementDate = Dateadd(day, Datediff(day, 0, Getdate()), 0) )
	   AND ( ApprovalStatus = 1 )
	GROUP BY MatrixCellId,
		 WarehouseId
) AS Inventory

    INNER JOIN dbo.STOCK_CNF_Product AS SCP WITH (nolock) ON Inventory.MatrixCellId = SCP.MatrixCellId
    INNER JOIN dbo.STOCK_CNF_Warehouse WITH (nolock) ON Inventory.WarehouseId = dbo.STOCK_CNF_Warehouse.WarehouseId
    INNER JOIN dbo.STOCK_CNF_Um WITH (nolock) ON dbo.STOCK_CNF_Um.UmId = SCP.UmId
    INNER JOIN dbo.CNF_MatrixCell WITH (nolock) ON SCP.MatrixCellId = dbo.CNF_MatrixCell.MatrixCellId

GROUP BY 
	SCP.MinStock,
	SCP.MatrixCellId,
	SCP.SKU,
	dbo.STOCK_CNF_Warehouse.WarehouseId,
	dbo.STOCK_CNF_Um.Description,
	dbo.STOCK_CNF_Warehouse.Description,
	dbo.CNF_MatrixCell.price,
	dbo.CNF_MatrixCell.Name 
</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>059641B6948C4C8E8BD22F289198F369</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE"><Name>VW_AccountLimit</Name><ScriptList><Script Type="VW"><Database>stMsSQL2005</Database><Version>5</Version><SQL>CREATE view [dbo].[VW_AccountLimit]
as

select  accountid,
		dmgcategoryID,
		AccountRestrictionId,
		PerformanceID,
		ISNULL(PerformanceName, EventName) as PerformanceName,
		EventName,
		Eventid,
		PerfDateTime,
		Saledate,                   
		cast(Description as varchar(100))  as ResDescription, 
		AccountType + ' ' + RestrictionDescription as AccountType, 
		ISNULL(Saleid, ' ') as SaleID ,             
		ISNULL(TicketName, ' ') as TicketName,               
		ISNULL(ReservationAccountQuantity,  ' ') as ReservationAccountQuantity,               
		ISNULL(WorkstationAK,  ' ') as WorkstationAK,         
		ISNULL(UserName,  ' ') as UserName,         
		ISNULL(reservationAK,  ' ') as reservationAK         
 from (             
			  select  DATA_AccountLimit.accountid, 
			      Null dmgcategoryID,
				  CNF_AccountRestriction.AccountRestrictionId as AccountRestrictionId,     
				  CNF_AccountRestriction.StartDateTime as StartDateTime,                   
				  CNF_AccountRestriction.EndDateTime as EndDateTime,                       
				  CNF_AccountRestriction.Enabled as Enabled,                                 
				  CNF_AccountRestriction.Description as Description,                         
				  CNF_AccountRestriction.RestrictionType as RestrictionType,                   
				  CNF_AccountRestriction.ReservationAccountLimit as ReservationAccountLimit,  
				  CNF_AccountRestriction.TicketAccountLimit as TicketAccountLimit,             
				  Lookup_0.Description as RestrictionDescription, 
				  AccountType.Description as AccountType,				  
				  DATA_AccountLimit.SaleDate,                                                  
				  DATA_AccountLimit.SaleID,                                                    
				  DATA_AccountLimit.SaleItemid,                                                
				  '[' + cnf_Matrixcell.code + ']' + cnf_Matrixcell.Name as TicketName,            
				  DATA_AccountLimit.ReservationAccountQuantity,                                                                        
				  cnf_User.username,                                                
				  cnf_workstation.workstationAK,                                                           
				  data_reservation.reservationAK as reservationAK,
				  cnf_performance.PerformanceID,
				  cnf_performance.Eventid,
				  cnf_performance.PerfDateTime,
				  cnf_performance.PerformanceName,
				  cnf_Event.EventName

			  from CNF_AccountRestriction with (nolock)                                            
				INNER JOIN DATA_AccountLimit WITH(NOLOCK)						ON data_accountlimit.accountrestrictionid = cnf_accountrestriction.accountrestrictionid  				
				LEFT  JOIN cnf_performance WITH(NOLOCK)							ON cnf_performance.Performanceid = data_accountlimit.Performanceid
				LEFT  JOIN cnf_event WITH(NOLOCK)								ON cnf_event.eventid = cnf_performance.eventid
				INNER JOIN DATA_SaleItem WITH(NOLOCK)							ON data_saleitem.saleitemid = data_accountLimit.SaleitemID
				INNER JOIN data_sale WITH(NOLOCK)								ON data_sale.saleid = data_saleitem.saleid
				INNER JOIN cnf_user WITH(NOLOCK)								ON cnf_user.Userid = data_sale.Userid
				INNER JOIN cnf_Workstation WITH(NOLOCK)							ON cnf_Workstation.workstationid = data_sale.workstationid
				INNER JOIN cnf_Matrixcell WITH(NOLOCK)							ON cnf_matrixcell.matrixcellid = data_saleitem.matrixcellid     
				LEFT  JOIN data_reservation WITH(NOLOCK)						ON data_reservation.saleid = data_accountlimit.saleid         
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId =  (select lookuptableid from cnf_lookuptable where lookupname = 'Restriction Type' )    )                                                
					) AS Lookup_0											ON Lookup_0.ItemId=CNF_AccountRestriction.RestrictionType  
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId = (select lookuptableid from cnf_lookuptable where lookupname = 'Restriction Account Type')  )                                                     
					) AS AccountType											ON AccountType.ItemId=CNF_AccountRestriction.AccountType  
					
			UNION ALL

			select CNF_AccountRestriction2Account.Accountid,
			      CNF_AccountRestriction2dmgCategory.dmgcategoryid,
				  CNF_AccountRestriction.AccountRestrictionId as AccountRestrictionId,      
				  CNF_AccountRestriction.StartDateTime as StartDateTime,              
				  CNF_AccountRestriction.EndDateTime as EndDateTime,                
				  CNF_AccountRestriction.Enabled as Enabled,                        
				  data_note.Note as Description,          
				  null as RestrictionType,                                     
				  null as ReservationAccountLimit,                              
				  CNF_AccountRestriction.TicketAccountLimit as TicketAccountLimit,       
				  Lookup_0.Description as RestrictionDescription,   
				  AccountType.Description as AccountType,
				  data_note.notedate,                                         
				  null,                                                        
				  null,                                                         
				  null,                                                         
				  null,                                                                                                               
				  cnf_User.username,                                                
				  cnf_workstation.workstationAK,                                    
				  null,
				  null,
				  null,
				  null,
				  null,
				  null

			  from                                                                
				CNF_AccountRestriction with (nolock)                              
				  left  join CNF_AccountRestriction2Account with (nolock)			ON CNF_AccountRestriction2Account.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId       
				  left  join CNF_AccountRestriction2dmgCategory with (nolock)		ON CNF_AccountRestriction2dmgCategory.AccountRestrictionId = CNF_AccountRestriction.AccountRestrictionId    
				INNER JOIN data_note WITH(NOLOCK)								on data_note.notekey = CNF_AccountRestriction.AccountRestrictionId       
												and data_note.notetype = 518               
												and data_note.note = 'Reset completed'        
				INNER JOIN cnf_User WITH(NOLOCK)                 ON cnf_User.userid = data_Note.Userid        
				INNER JOIN cnf_Workstation WITH(NOLOCK)          ON cnf_workstation.workstationid = data_note.workstationid     
				inner join (	  SELECT CNF_LookUp.ItemId,                                       
						   ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description               
						FROM CNF_Lookup with (nolock)                                   
						LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)     
											   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)       
											   and (CNF_MultiLanguage.FormName = 'LOOKUP')      
											   and (CNF_MultiLanguage.LanguageId = 0)         
						WHERE (CNF_LookUp.LookUpTableId = (select lookuptableid from cnf_lookuptable where lookupname = 'Restriction Type' ) )                                
					) AS Lookup_0											ON Lookup_0.ItemId=CNF_AccountRestriction.RestrictionType 
				inner join (SELECT CNF_LookUp.ItemId,              
						           ISNULL(dbo.CNF_MultiLanguage.Translation, dbo.CNF_LookUp.Description) AS Description                  
						      FROM CNF_Lookup with (nolock)                                                            
									LEFT JOIN CNF_MultiLanguage with (nolock) ON (CNF_Lookup.LookupTableId=CNF_MultiLanguage.ComponentName)    
																				   and (CNF_Lookup.ItemId=CNF_MultiLanguage.PropertyName)                   
																				   and (CNF_MultiLanguage.FormName = 'LOOKUP')                       
																				   and (CNF_MultiLanguage.LanguageId = 0)                             
						WHERE (CNF_LookUp.LookUpTableId = (select lookuptableid from cnf_lookuptable where lookupname = 'Restriction Account Type'))                                                     
					) AS AccountType											ON AccountType.ItemId=CNF_AccountRestriction.AccountType  					
    
   
 )p</SQL><CheckSuccess>0</CheckSuccess><ExecuteOnCreate>0</ExecuteOnCreate><SqlScriptAK>38607DBA9EDB4B82AA91E2CDD33BAEE1</SqlScriptAK></Script></ScriptList></View><View Status="ACTIVE">
			<Name>VW_Admissions</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>2</Version>
					<SQL>CREATE VIEW [dbo].[VW_Admissions]
AS
SELECT  CNF_Site.SiteId,
        CNF_Site.SiteName,
        CNF_Location.LocationId,
        CNF_Location.LocationCode,
	CNF_Location.Name CNF_Name,
	CNF_MatrixSheet.MatrixSheetId ,
	CNF_Event.EventId,
	CNF_Event.EventCode,
	CNF_Event.EventName,
	CNF_MatrixCell.MatrixCellId,
        ADM_Gate.GateId ADM_GateId,
	ADM_Gate.Name Gate_Name,
	ADM_Gate.Description,
        DATA_TicketUsage.FUsageDate,
        DATA_TicketUsage.Gateid,
	DATA_TicketUsage.UsageDate,
        DATEPART(HOUR, DATA_TicketUsage.UsageDate) RotHour,
	DATA_TicketUsage.UsageType,
	DATA_TicketUsage.ValidateResult,
	DATA_Ticket.PeopleCount,
	DATA_Ticket.VoidType,
	DATA_Ticket.Price,
	DATA_Ticket.PrintedPrice
 
 
FROM  DATA_TicketUsage WITH(NOLOCK)
      LEFT  JOIN DATA_Ticket WITH(NOLOCK)                              ON (DATA_Ticket.TicketId = DATA_TicketUsage.TicketId)
      LEFT  JOIN ADM_Gate WITH(NOLOCK)                                 ON (ADM_Gate.GateId = DATA_TicketUsage.GateId)
      LEFT  JOIN CNF_Location WITH(NOLOCK)                             ON  (CNF_Location.LocationId = ADM_Gate.LocationId)
      LEFT  JOIN CNF_Site WITH(NOLOCK)                                 ON (CNF_Site.SiteId = CNF_Location.SiteId)
      LEFT  JOIN CNF_MatrixCell CNF_MatrixCell WITH(NOLOCK)            ON (CNF_MatrixCell.MatrixCellId = DATA_Ticket.MatrixCellId)
      INNER JOIN CNF_MatrixSheet CNF_MatrixSheet WITH(NOLOCK)          ON (CNF_MatrixSheet.MatrixSheetId = CNF_MatrixCell.MatrixSheetId)
      INNER JOIN CNF_Event CNF_Event WITH(NOLOCK)                      ON (CNF_Event.EventId = CNF_MatrixSheet.EventId)
      INNER JOIN CNF_AttributeSet CNF_AttributeSet WITH(NOLOCK)        ON (CNF_AttributeSet.AttributeSetId = CNF_MatrixCell.AttributeSetId)</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>F169A44D48FD425DB79E17ECAC13A355</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
		<View Status="ACTIVE">
			<Name>VW_Sales</Name>
			<ScriptList>
				<Script Type="VW">
					<Database>stMsSQL2005</Database>
					<Version>3</Version>
					<SQL>CREATE view [dbo].[VW_Sales]
AS

select CNF_Site.SiteId,
       CNF_Site.SiteCode,
       CNF_Site.SiteName,
       CNF_User.UserId,
       CNF_User.UserCode,
       CNF_User.UserName,
       CNF_Event.EventId,
       CNF_Event.EventCode,
       CNF_Event.EventName,
       CNF_PriceTable.PriceTableId,
       CNF_PriceTable.Description,
       CNF_PriceList.PriceListId,
       CNF_PriceList.PriceListCode,
       CNF_PriceList.PriceListName,
       DATA_SaleItem.ProductType,
       CNF_MatrixSheet.MatrixSheetId,
       CNF_MatrixSheet.MatrixSheetName,
       CNF_MatrixCell.MatrixCellId,
       CNF_AttributeSet.AttributeCodes,
       DATA_Transaction.TransactionType,
       DATA_SaleItem.Quantity,
       DATA_SaleItem.TotalAmount,
       DATA_SaleItem.PeopleCount,
       data_transaction.TransactionId,
       FTransactionDate,
       DATA_Transaction.Paid,
       DATA_Transaction.Revenue,
       DATA_Transaction.TaxRevenue,
       CNF_OperatingArea.OperatingAreaId,
       CNF_OperatingArea.AreaCode,
       CNF_OperatingArea.OpAreaName,
       CNF_Workstation.WorkstationDescription,
       CNF_Workstation.WorkstationAK,
       CNF_Workstation.WorkstationId,
       AttributeNames,
       DATA_SaleItem.UnitPrice,
       DATA_Transaction.TransactionDate,
       DATA_Transaction.Completed,
       DATA_Transaction.Encoded,
       DATA_Transaction.Validated,
       DATA_Transaction.Approved,
       DATA_Transaction.TransactionStatus,
       DATA_Transaction.Tip,
       DATA_Transaction.Change,
       DATA_Transaction.Serial,
	   (select paid from data_sale where data_sale.saleid = data_transaction.saleid) as DSPaid

FROM DATA_Transaction WITH(NOLOCK) 
     INNER JOIN data_transactionITEM WITH(NOLOCK)	ON (data_transactionitem.transactionid = data_transaction.transactionid)
     INNER JOIN DATA_SaleItem WITH(NOLOCK)			ON (DATA_SaleItem.Saleitemid = data_transactionitem.Saleitemid)
     INNER JOIN CNF_MatrixCell WITH(NOLOCK)			ON (CNF_MatrixCell.MatrixCellId = DATA_SaleItem.MatrixCellId)
     INNER JOIN CNF_MatrixSheet WITH(NOLOCK)		ON (CNF_MatrixSheet.MatrixSheetId = CNF_MatrixCell.MatrixSheetId)
     INNER JOIN CNF_PriceTable WITH(NOLOCK)			ON (CNF_MatrixCell.PriceTableId = CNF_PriceTable.PriceTableId)
     INNER JOIN CNF_Site WITH(NOLOCK)				ON (CNF_Site.SiteId = DATA_Transaction.SiteId)
     INNER JOIN CNF_AttributeSet WITH(NOLOCK)		ON (CNF_AttributeSet.AttributeSetId = CNF_MatrixCell.AttributeSetId)
     INNER JOIN CNF_Event WITH(NOLOCK)				ON (CNF_Event.EventId = CNF_MatrixSheet.EventId)
     INNER JOIN CNF_PriceList WITH(NOLOCK)			ON (CNF_PriceList.PriceListId = CNF_MatrixCell.PriceListId)
     INNER JOIN CNF_User WITH(NOLOCK)				ON (CNF_User.UserId = DATA_Transaction.UserId)
     INNER JOIN CNF_OperatingArea WITH(NOLOCK)		ON (CNF_OperatingArea.OperatingAreaId = DATA_Transaction.OperatingAreaId)
     INNER JOIN CNF_Workstation WITH(NOLOCK)		ON (CNF_Workstation.WorkstationId = DATA_Transaction.WorkstationId)</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>F693410618524BE9BBB5053F2DB014D5</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</View>
	</ViewList>
	<FunctionList>
		<Function Status="ACTIVE">
			<Name>otn_fn_IsPromotionCalendarValid</Name>
			<ScriptList>
				<Script Type="FN">
					<Database>stMsSQL2005</Database>
					<Version>3</Version>
					<SQL>CREATE FUNCTION [dbo].[otn_fn_IsPromotionCalendarValid](@PromotionId int, @DateTime DateTime)
  /* Input param:  PromotionID, 
                   current datetime
     Output param: 1 = promotion valid
           0 = promotion not valid
   */
  RETURNS int
  AS
BEGIN
  DECLARE @ret int
  IF NOT EXISTS (SELECT PromotionId FROM CNF_PromotionValidity WITH(NOLOCK) WHERE (PromotionId = @PromotionId) AND (CNF_PromotionValidity.ValidityDateType = 0)) 
  BEGIN
    set @ret = 1     /* If not specified the validity the promotion is valid */
  END
  ELSE
  BEGIN
    set @ret = 0
    DECLARE @PromId as int;
    SET @PromId = 0;
    DECLARE my_cursor CURSOR FOR
            SELECT PromotionId FROM CNF_PromotionValidity WITH(NOLOCK)
                   WHERE PromotionId = @PromotionId AND (CNF_PromotionValidity.ValidityDateType = 0) AND
                         CAST( @DateTime AS DATE) BETWEEN CAST(ISNULL(FromDate, @DateTime) AS DATE) AND
                         CAST(ISNULL(ToDate, @DateTime) AS DATE) AND
                         CAST( @DateTime AS TIME) BETWEEN CAST(ISNULL(FromTime, @DateTime) AS TIME) AND
                         CAST(ISNULL(ToTime, @DateTime) AS TIME)
    OPEN my_cursor;

    FETCH NEXT FROM my_cursor INTO @PromId;

    WHILE @@FETCH_STATUS = 0
    BEGIN
      IF @PromId IS NOT NULL
      BEGIN
        set @ret = 1			/* if return the promotionId it means that the validity is ok*/
        GOTO EndLoop
      END
      FETCH NEXT FROM my_cursor INTO @PromId;
    END

    EndLoop:
    CLOSE my_cursor;
    DEALLOCATE my_cursor;
  END

  RETURN @ret;
END

</SQL>
					<CheckSuccess>0</CheckSuccess>
					<SqlScriptAK>4CA984D093B940E4BD4E98E37DA38AFD</SqlScriptAK>
					<ExecuteOnCreate>0</ExecuteOnCreate></Script>
			</ScriptList>
		</Function>
	</FunctionList>
</root>
