
-- This is the store procedure need to be run when new store is to be added to cash managemnt pilot

DECLARE @GoLiveDate		DATETIME	= '2020-10-31'
DECLARE @storeNumber	VARCHAR(6)	= '01023'
DECLARE	@StartingFloat	MONEY		= 2500

--mxls 766
DECLARE @EntityID		BIGINT
SELECT	@EntityID = EntityID from tbEntity where StoreNumber = @storeNumber 

--mxls 01639

BEGIN TRAN
-- COMMIT TRAN 
-- ROLLBACK TRAN

-- Set trading day rules for cash management stores
--if not exists (select * from tbMXDayRules where Type = 2 and Continuous = 1 and CalendarDayRule = 5 and PopulateMissingMarkers = 1 and PriorDaysToFix = 5 and (EntityID = @EntityID or EntityID = 0))
--begin
--	update tbMXDayShiftMarker set MarkerType = 3  
--	 where EntityID = @EntityID
--	   and description = 'dayopen'
--	PRINT '-- Updated MarkerType for POS Day Open Markers. --'
	   
--	delete tbMXDayRules where EntityID = @EntityID  
--	PRINT '-- Deleted previous Business Day Rules. --'

--	insert into tbMXDayRules (EntityID, Type, StartTime, EndTime, Continuous, DaysInAdvance, MaxShiftsPerDay, CalendarDayRule, ShiftNames, CalendarDayOffset, PopulateMissingMarkers, PriorDaysToFix, HoursDelayToPopulate)   
--    values   	
--      (@EntityID
--      ,2
--      ,'2007-01-01 00:00:00.000'
--      ,'2007-01-01 00:00:00.000'
--      ,1
--      ,2
--      ,10
--      ,5
--      ,''
--      ,1
--      ,1
--      ,5
--      ,12) 
      
--      PRINT '-- Added POS-Driven Business Day Rules --'
--end

-- Update entity item inventory cost from vendor entity item purchase price
--update tbEntityItem 
--   set InventoryUnitCost = vei.PurchasePrice/dbo.fn_GetUnitConversionRate(vei.PurchaseUnit,i.InventoryUnit)  
--  from tbVendorEntityItem vei with(nolock)
--  left join tbEntityItem ei with(nolock) on vei.EntityID = ei.EntityID and vei.ItemID = ei.ItemID 
--  join tbItem i with(nolock) on ei.ItemID = i.ItemID 
-- where ei.EntityID = @EntityID 
--   and ei.InventoryUnitCost = 0
--   and vei.PurchasePrice <> 0 
--   and dbo.fn_GetUnitConversionRate(vei.PurchaseUnit,i.InventoryUnit) <> 0   
   
--PRINT '-- Updated Store Item Costs based on Purchase Costs --'

-- Add store to cash management export zone
--declare @ZoneID int

--if not exists (select * from tbZone where Zone = 'Cash Management Export' and ZoneTypeId = 6)
--begin
--	insert tbZone (Zone, ZoneTypeId) values ('Cash Management Export', 6)
--	PRINT '-- Created Cash Management Export Zone (this zone should already exist). --'  
--end

--select @ZoneID = ZoneID from tbZone where Zone = 'Cash Management Export' and ZoneTypeId = 6

--if not exists (select * from tbEntityZone where EntityID = @EntityID and ZoneID = @ZoneID)
--begin
--	insert tbEntityZone (EntityID, ZoneID) values (@EntityID, @ZoneID)
	
--	PRINT '-- Added Store to Cash Management Export Zone --' 
--end
--ELSE
--BEGIN
--	PRINT '-- Store Already Existed in the Cash Management Export Zone --' 
--END

------ Add store to shift validation zone  
--if not exists (select * from tbZone where Zone = 'ShiftValidation' and ZoneTypeId = 14)
--begin
--	insert tbZone (Zone, ZoneTypeId) values ('ShiftValidation', 14)  
--	PRINT '-- Created Shift Validation Zone (This zone should already exist). --'
--end

--select @ZoneID = ZoneID from tbZone where Zone = 'ShiftValidation' and ZoneTypeId = 14

--if not exists (select * from tbEntityZone where EntityID = @EntityID and ZoneID = @ZoneID)
--begin
--	insert tbEntityZone (EntityID, ZoneID) values (@EntityID, @ZoneID)  
--	PRINT '-- Added Store to Shift Validation Zone. --'
--end

---- Add PollPOS for the new store
---- copy poll pos setting from store 00440 to the new store
--if not exists (select * from tbPollPOSEntity where EntityID = @EntityID) and exists (select * from tbPollPOSEntity where EntityID = 269)
--begin
--INSERT INTO tbPollPOSEntity
--           ([PollPOSID]
--           ,[EntityID]
--           ,[Title]
--           ,[ExtractionDSN]
--           ,[ExtractionSQL]
--           ,[TableName]
--           ,[FilePathName]
--           ,[UseSecurityLogin]
--           ,[UserName]
--           ,[Password]
--           ,[ExtractedField]
--           ,[ConditionField]
--           ,[Equals]
--           ,[DateDay]
--           ,[DateMonth]
--           ,[DateYear]
--           ,[TargetReport]
--           ,[TargetField]
--           ,[Notes]
--           ,[ExtractAll]
--           ,[GetDateAbove]
--           ,[ConditionForRep1]
--           ,[ConditionForRep2]
--           ,[ConditionForRep3]
--           ,[ConditionForRep4]
--           ,[ConditionForRep5]
--           ,[ExtractMode]
--           ,[GetFromSubDir]
--           ,[ExtractCode]
--           ,[ExStartPos]
--           ,[ExEndPos]
--           ,[CheckAll]
--           ,[ModExtention]
--           ,[OrigionalExtention]
--           ,[NewExtention]
--           ,[GetRegNoFromExt]
--           ,[AmountsInCents]
--           ,[TranslateUsing1]
--           ,[TranslateUsing2]
--           ,[TranslateUsing3]
--           ,[TranslateUsing4]
--           ,[TranslateUsing5]
--           ,[Frequency]
--           ,[RegisterType]
--           ,[DivCountBy1000]
--           ,[Cashup]
--           ,[ProcessLoyalty]
--           ,[ProcessTransactionSummary]
--           ,[PollAmountIncludesDiscount]
--           ,[PollAmountIncludesCompliment]
--           ,[PollAmountIncludesFree]
--           ,[PollAmountIncludesWaste]
--           ,[PollAmountIncludesRounding]
--           ,[StoreDiscount]
--           ,[StoreCompliment]
--           ,[StoreFree]
--           ,[StoreWaste]
--           ,[ClerkIDNameSetup]
--           ,[ItemApplyTaxSetup]
--           ,[ItemTaxRateSetup]
--           ,[DayShiftProcessing]
--           ,[CustomerCountProcessing]
--           ,[TranslateUsingControlInfoItem]
--           ,[TranslateUsingControlInfoItemID]
--           ,[FinancialPollAmount]
--           ,[FinancialPollCount]
--           ,[FinancialCategory]
--           ,[PollAmountIncludesTax]
--           ,[LogLevel]
--           ,[CheckForDupes]
--           ,[DupeType]
--           ,[EatInOut]
--           ,[DiscountPositive]
--           ,[ItemVoidPositive]
--           ,[ServiceCategory]
--           ,[ServiceTime1]
--           ,[ServiceTime2]
--           ,[ServiceTime3]
--           ,[PollAmountIncludesCount]
--           ,[StoreRefund]
--           ,[PollAmountIncludesRefund]
--           ,[TranslateUsingItem]
--           ,[UsePriceLevel]
--           ,[UseTransactionID]
--           ,[TransferControlInfoOtherInfo1]
--           ,[TransferControlInfoOtherInfo2]
--           ,[TransferControlInfoOtherInfo3]
--           ,[ItemTaxExemptCode]
--           ,[TimeAttendanceUsePayRate]
--           ,[TimeAttendanceUseJobCode]
--           ,[ServiceMethod]
--           ,[TranslateUsingClerk]
--           ,[LoyaltyType]
--           ,[TranslateItemCovers]
--           ,[TaxPositive]
--           ,[SplitSalesQueue]
--           ,[AttendanceClerkSetup]
--           ,[MinVersion]
--           ,[UsePOSCombo]
--           ,[PreProcessPOSCombo]
--           ,[AttendanceUserEntityMask]
--           ,[StoreServiceTimes]
--           ,[UseHeaderPollAmountAsTotal]
--           ,[TranslateCustomers]
--           ,[AddNewCustomers]
--           ,[NoOfCovers]
--           ,[TranslateRevenueCentre]
--           ,[UseNotionalPrice]
--           ,[UseFinancialTypes]
--           ,[UseModifier]
--           ,[UpdateEntitySalesItemPrice]
--           ,[UpdateEntityInformation]
--           ,[AccountNumberSetup]
--           ,[SummaryOtherInfo2]
--           ,[SummaryOtherInfo3]
--           ,[TimeAttendanceUpdateJobPayRate]
--           ,[ItemPollAmountIncludesDiscount]
--           ,[POSComboCostCalc]
--           ,[POSComboPriceCalc]
--           ,[POSModifierCalc]
--           ,[BasketAnalysisSetup]
--           ,[ProcessSequenceNo]
--           ,[LoyaltyProcessFlagField]
--           ,[ProcessNonSales]
--           ,[LocationNumberField]
--           ,[DisableDayClose]
--           ,[ProcessTaxExempt]
--           ,[NotionalPriceRatio]
--           ,[NotionalPriceModifier]
--           ,[WastageReasonField]
--           ,[PollAmountIncludesPromo]
--           ,[StorePromo]
--           ,[ProcessPettyCash]
--           ,[ProcessValidation]
--           ,[ItemTaxCodeField])
--     SELECT [PollPOSID]
--		   ,@EntityID 
--		   ,[Title]
--		   ,[ExtractionDSN]
--		   ,[ExtractionSQL]
--		   ,[TableName]
--		   ,[FilePathName]
--		   ,[UseSecurityLogin]
--		   ,[UserName]
--		   ,[Password]
--		   ,[ExtractedField]
--		   ,[ConditionField]
--		   ,[Equals]
--		   ,[DateDay]
--		   ,[DateMonth]
--		   ,[DateYear]
--		   ,[TargetReport]
--		   ,[TargetField]
--		   ,[Notes]
--		   ,[ExtractAll]
--		   ,[GetDateAbove]
--		   ,[ConditionForRep1]
--		   ,[ConditionForRep2]
--		   ,[ConditionForRep3]
--		   ,[ConditionForRep4]
--		   ,[ConditionForRep5]
--		   ,[ExtractMode]
--		   ,[GetFromSubDir]
--		   ,[ExtractCode]
--		  ,[ExStartPos]
--		  ,[ExEndPos]
--		  ,[CheckAll]
--		  ,[ModExtention]
--		  ,[OrigionalExtention]
--		  ,[NewExtention]
--		  ,[GetRegNoFromExt]
--		  ,[AmountsInCents]
--		  ,[TranslateUsing1]
--		  ,[TranslateUsing2]
--		  ,[TranslateUsing3]
--		  ,[TranslateUsing4]
--		  ,[TranslateUsing5]
--		  ,[Frequency]
--		  ,[RegisterType]
--		  ,[DivCountBy1000]
--		  ,[Cashup]
--		  ,[ProcessLoyalty]
--		  ,[ProcessTransactionSummary]
--		  ,[PollAmountIncludesDiscount]
--		  ,[PollAmountIncludesCompliment]
--		  ,[PollAmountIncludesFree]
--		  ,[PollAmountIncludesWaste]
--		  ,[PollAmountIncludesRounding]
--		  ,[StoreDiscount]
--		  ,[StoreCompliment]
--		  ,[StoreFree]
--		  ,[StoreWaste]
--		  ,[ClerkIDNameSetup]
--		  ,[ItemApplyTaxSetup]
--		  ,[ItemTaxRateSetup]
--		  ,[DayShiftProcessing]
--		  ,[CustomerCountProcessing]
--		  ,[TranslateUsingControlInfoItem]
--		  ,[TranslateUsingControlInfoItemID]
--		  ,[FinancialPollAmount]
--		  ,[FinancialPollCount]
--		  ,[FinancialCategory]
--		  ,[PollAmountIncludesTax]
--		  ,[LogLevel]
--		  ,[CheckForDupes]
--		  ,[DupeType]
--		  ,[EatInOut]
--		  ,[DiscountPositive]
--		  ,[ItemVoidPositive]
--		  ,[ServiceCategory]
--		  ,[ServiceTime1]
--		  ,[ServiceTime2]
--		  ,[ServiceTime3]
--		  ,[PollAmountIncludesCount]
--		  ,[StoreRefund]
--		  ,[PollAmountIncludesRefund]
--		  ,[TranslateUsingItem]
--		  ,[UsePriceLevel]
--		  ,[UseTransactionID]
--		  ,[TransferControlInfoOtherInfo1]
--		  ,[TransferControlInfoOtherInfo2]
--		  ,[TransferControlInfoOtherInfo3]
--		  ,[ItemTaxExemptCode]
--		  ,[TimeAttendanceUsePayRate]
--		  ,[TimeAttendanceUseJobCode]
--		  ,[ServiceMethod]
--		  ,[TranslateUsingClerk]
--		  ,[LoyaltyType]
--		  ,[TranslateItemCovers]
--		  ,[TaxPositive]
--		  ,[SplitSalesQueue]
--		  ,[AttendanceClerkSetup]
--		  ,[MinVersion]
--		  ,[UsePOSCombo]
--		  ,[PreProcessPOSCombo]
--		  ,[AttendanceUserEntityMask]
--		  ,[StoreServiceTimes]
--		  ,[UseHeaderPollAmountAsTotal]
--		  ,[TranslateCustomers]
--		  ,[AddNewCustomers]
--		  ,[NoOfCovers]
--		  ,[TranslateRevenueCentre]
--		  ,[UseNotionalPrice]
--		  ,[UseFinancialTypes]
--		  ,[UseModifier]
--		  ,[UpdateEntitySalesItemPrice]
--		  ,[UpdateEntityInformation]
--		  ,[AccountNumberSetup]
--		  ,[SummaryOtherInfo2]
--		  ,[SummaryOtherInfo3]
--		  ,[TimeAttendanceUpdateJobPayRate]
--		  ,[ItemPollAmountIncludesDiscount]
--		  ,[POSComboCostCalc]
--		  ,[POSComboPriceCalc]
--		  ,[POSModifierCalc]
--		  ,[BasketAnalysisSetup]
--		  ,[ProcessSequenceNo]
--		  ,[LoyaltyProcessFlagField]
--		  ,[ProcessNonSales]
--		  ,[LocationNumberField]
--		  ,[DisableDayClose]
--		  ,[ProcessTaxExempt]
--		  ,[NotionalPriceRatio]
--		  ,[NotionalPriceModifier]
--		  ,[WastageReasonField]
--		  ,[PollAmountIncludesPromo]
--		  ,[StorePromo]
--		  ,[ProcessPettyCash]
--		  ,[ProcessValidation]
--		  ,[ItemTaxCodeField]
--      FROM tbPollPOSEntity where EntityID = 269	
      
--      PRINT '-- Added Poll POS Configuration for Store ' + @StoreNumber + '. --'
--end
--ELSE
--BEGIN
--	PRINT '-- Poll POS Configuration already exists for store ' + @StoreNumber + '. --'
--END

-- Set previous days' banking close status as finalized.
declare @CurrentDate as datetime = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()))
INSERT INTO tbBankingClose
           ([EntityID]
           ,[BankingDate]
           ,[TransactionDate]
           ,[PeriodNo]
           ,[FiscalYear]
           ,[RegisterSales]
           ,[Voids]
           ,[PromoFree]
           ,[Discounts]
           ,[NetSalesWithTax]
           ,[NetSales]
           ,[Tax]
           ,[Eftpos]
           ,[DepositAM]
           ,[DepositPM]
           ,[Withhold]
           ,[Rebank]
           ,[CashVariance]
           ,[TotalTransactions]
           ,[Authorised]
           ,[AuthorisedByUsername]
           ,[DepositPMActual]
           ,[CashDrops]
           ,[PettyCash]
           ,[SpecialDeposits]
           ,[Comments]
           ,[Vouchers]
           ,[Cheques]
           ,[Catering]
           ,[CashOut]
           ,[VoucherCheques]
           ,[RegisterFloatMovement]
           ,[SafeFloatMovement]
           ,[ChangeReceive]
           ,[OpeningRegisterFloatVariance]
           ,[ClosingRegisterFloatVariance]
           ,[SafeFloatVariance]
           ,[BankingVariance]
           ,[CashupDeposit]
           ,[CashupPreviousDeposit]
           ,[LoyaltyCard]
           ,[NonSales]
           ,[PaidIn]
           ,[GiftCertificateSold]
           ,[GiftCertificateRedeemed]
           ,[CharityDonation]
           ,[CouponOverShort])
(select @EntityID
      ,pd.DayDate
      ,[TransactionDate]
      ,pd.PeriodNo
      ,pd.sFiscalYear
      ,0 --[RegisterSales]
      ,[Voids]
      ,[PromoFree]
      ,[Discounts]
      ,0 --[NetSalesWithTax]
      ,0 --[NetSales]
      ,0 --[Tax]
      ,[Eftpos]
      ,[DepositAM]
      ,[DepositPM]
      ,[Withhold]
      ,[Rebank]
      ,[CashVariance]
      ,[TotalTransactions]
      ,1
      ,'CMOperator'
      ,[DepositPMActual]
      ,[CashDrops]
      ,[PettyCash]
      ,[SpecialDeposits]
      ,'Finalized' --[Comments]
      ,[Vouchers]
      ,[Cheques]
      ,[Catering]
      ,[CashOut]
      ,[VoucherCheques]
      ,[RegisterFloatMovement]
      ,[SafeFloatMovement]
      ,[ChangeReceive]
      ,[OpeningRegisterFloatVariance]
      ,[ClosingRegisterFloatVariance]
      ,[SafeFloatVariance]
      ,[BankingVariance]
      ,[CashupDeposit]
      ,[CashupPreviousDeposit]
      ,[LoyaltyCard]
      ,[NonSales]
      ,[PaidIn]
      ,[GiftCertificateSold]
      ,[GiftCertificateRedeemed]
      ,[CharityDonation]
      ,[CouponOverShort]
from tbPeriodDay pd
cross join tbBankingClose bc
where bc.EntityID = 269 and bc.BankingDate = '2011-10-11 00:00:00.000'
and pd.sFiscalYear IN (SELECT DISTINCT sFiscalYear FROM tbPeriodDay WITH (NOLOCK) WHERE DayDate <= CONVERT(VARCHAR(10), @GoLiveDate, 101))
and pd.DayDate < @GoLiveDate
and pd.DayDate >= '2011-01-01 00:00:00.00'
and pd.DayDate not in (select BankingDate from tbBankingClose where EntityID = @EntityId))

PRINT '-- Marked all days prior to ' + CONVERT(VARCHAR(10), @GoLiveDate, 101) + ' as finalized. --'

-- If Any Finalize Day records prior to @GoLiveDate exist and are not marked as Authorized, close them
IF (Exists(SELECT * FROM tbBankingClose WHERE EntityID = @EntityID and BankingDate <= @GoLiveDate AND Authorised <> 1))
BEGIN
	UPDATE tbBankingClose
	SET Authorised = 1,
		AuthorisedByUsername = 'CMOperator',
		Comments = '',
		TransactionDate = GETDATE()
	WHERE EntityID = @EntityID
	AND	Authorised = 0
	AND BankingDate < @GoLiveDate
	
	PRINT '-- Unauthorized Finalize Day Records prior to Go-Live Date ' + CONVERT(VARCHAR(10), @GoLiveDate, 101) + ' existed and have been closed'
END

-- Set Starting Change Fund (Float) and create previous business day's Closing Change Fund Count

DECLARE @PreviousDay DATETIME = (SELECT TOP 1 CalendarDay from tbMXDay with (nolock) where EntityID = @EntityID and CalendarDay < @GoLiveDate AND DayType = 1 ORDER BY CalendarDay Desc)
DECLARE @Timestamp DATETIME = DATEADD(hh,23, @PreviousDay)

INSERT INTO tbTransactionCashCount (EntityID, Total, AmountToCompare, Variance, Registers, Custom1, Custom2, Custom3, Custom4, Custom5, Custom6, Custom7, Custom8, ExcludeTotalCustom1, CompareAmountDetail1, CompareAmountDetail2, CompareAmountDetail3, TimeStamp, ClerkName,BusinessDay)
VALUES (@EntityID, @StartingFloat, @StartingFloat, 0, 0, @StartingFloat, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @TimeStamp, 'CMOperator', @PreviousDay)

DECLARE @CashCountID BIGINT = (Select top 1 TransactionCashCountID from tbTransactionCashCount with (nolock) where EntityID = @EntityID and TimeStamp = @TimeStamp)

INSERT INTO tbBankingFloatCount (EntityID, FloatDate, TimeStamp, Float, Total, Variance, FloatCountRefID, AuthorisedBy1, Authorised, BankingTypeID)
VALUES (@EntityID, @PreviousDay, @TimeStamp, @StartingFloat, @StartingFloat, 0, @CashCountID, 'CMOperator',1,3)

INSERT INTO tbFloatMovement (EntityID, FloatMovementTypeID, StoreTimestamp, Amount, ExpectedAmount, RunningTotal, ManagerID, Variance, ReferenceID, FloatMovementDate)
VALUES (@EntityID, 3, @Timestamp, @StartingFloat, @StartingFloat, @StartingFloat, 1, 0, @CashCountID, @PreviousDay)

Update tbEntityFloat set DefaultStoreFloat = @StartingFloat where EntityId = @EntityID

PRINT '-- Inserted Closing Change Fund for ' + CONVERT(VARCHAR(10), @PreviousDay, 101) + '. --'

-- Set Auto-Order Type and UPTAutoCalc in preparation for Supply Chain Go-Live

--UPDATE	tbEntityItem
--SET		AutoOrderTypeID	= (SELECT OrderTypeID FROM tbOrderType WITH (NOLOCK) WHERE Title = 'Usage Per Thousand'), -- Set Auto-Order Type to UPT
--		UPTAutoCalc		= (CASE WHEN UPTQty <= 0 THEN 1 ELSE 0 END)											-- SET UPT Auto Calc to True if the item does not already have a UPT Value
		
--FROM	tbEntityItem ei
--JOIN	tbItem i WITH (NOLOCK)
--ON		i.ItemID = ei.ItemID
--JOIN	tbEntity e WITH (NOLOCK)
--ON		e.EntityID = ei.EntityID
--LEFT JOIN	tbOrderType t WITH (NOLOCK)
--ON		t.OrderTypeID = ei.AutoOrderTypeID
--JOIN	tbEntityZone ez WITH (NOLOCK)
--ON		ez.EntityID = ei.EntityID
--JOIN	tbZone z WITH (NOLOCK)
--ON		z.ZoneID = ez.ZoneID
--JOIN	tbZoneType zt WITH (NOLOCK)
--ON		zt.ZoneTypeId = z.ZoneTypeId

--WHERE	zt.ZoneType = 'Ordering Type'
--AND		ei.ItemID IN (SELECT ItemID from tbVendorItem)
--AND		ei.InUse = 1
--AND		z.Zone = 'Usage Ordering'
--AND		ei.AutoOrderTypeID IS NULL
--AND		e.StoreNumber = @StoreNumber

--Print '-- Set Usage Per Thousand Auto-Order type and UPT Auto-Calc Flag. --'


-- Delete Any Prior Workflow Instances
delete p from tbWorkFlowTemplateInstance i
JOIN tbWorkflowpendingtasks p 
on i.InstanceID = p.InstanceID
where i.EntityID = @EntityId

delete p from tbWorkFlowTemplateInstance i
JOIN tbWorkFlowTasksStatus p 
on i.InstanceID = p.InstanceID
where i.EntityID = @EntityId

delete from tbWorkFlowTemplateInstance where EntityID = @EntityId

-- Add Store to the Workflow Template
--INSERT INTO tbWorkFlowTemplateEntity (EntityID, TemplateID)
--VALUES (@EntityID, 2)

-- Insert Prior Business Day's Workflow Instance as Completed
INSERT INTO tbWorkFlowTemplateInstance (TemplateID, EntityID, UserID, StartDate, EndDate, Description, StatusID, Override, PreviousInstanceStatusID, BusinessDay)
values (1, @EntityID, 4, DATEADD(HH, 12,@PreviousDay), @GoLiveDate,'Daily Work Flow ' + CONVERT(VARCHAR(10), @PreviousDay, 101), 4, 0, 4, @PreviousDay)

--select * from tbWorkFlowTemplate with (nolock)

--select * from tbmxday with (nolock)
--where entityid = 1810 
--order by CalendarDay desc

--select * from tbWorkFlowTemplateEntity with (nolock)
--where entityid = 270

-- Add Store to the Workflow Template
--begin tran
--INSERT INTO tbWorkFlowTemplateEntity (EntityID, TemplateID)
--VALUES (270, 1)
----rollback tran
----commit tran


--sp_help tbWorkFlowTemplateInstance