SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL Serializable
GO
BEGIN TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptPurchaseOrderDetailUpdateFromWorksheet]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderDetailUpdateFromWorksheet]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptPurchaseOrderDetailUpdateFromWorksheet]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptProjectRollupUpdateQ]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectRollupUpdateQ]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptProjectRollupUpdateQ]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptProjectItemRollupUpdateQ]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectItemRollupUpdateQ]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptProjectItemRollupUpdateQ]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptProjectGetAI]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectGetAI]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptProjectGetAI]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[spApiAItTimerInsert]'
GO
IF OBJECT_ID(N'[dbo].[spApiAItTimerInsert]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[spApiAItTimerInsert]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptWidgetOptionsUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptWidgetOptionsUpdate]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptWidgetOptionsUpdate]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptWidgetOptionsGet]'
GO
IF OBJECT_ID(N'[dbo].[sptWidgetOptionsGet]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptWidgetOptionsGet]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[tWidgetOptions]'
GO
IF OBJECT_ID(N'[dbo].[tWidgetOptions]', 'U') IS NOT NULL
DROP TABLE [dbo].[tWidgetOptions]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping [dbo].[sptPurchaseOrderWSSummary]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderWSSummary]', 'P') IS NOT NULL
DROP PROCEDURE [dbo].[sptPurchaseOrderWSSummary]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tUser]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tUser]', N'DateInputMode') IS NULL
ALTER TABLE [dbo].[tUser] ADD[DateInputMode] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserColor') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserColor] [varchar] (10) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserBackgroundColor') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserBackgroundColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserBarColor') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserBarColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserMenuColor') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserMenuColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserDarkMode') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserDarkMode] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserAccentColor') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserAccentColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tUser]', N'UserBodyColor') IS NULL
ALTER TABLE [dbo].[tUser] ADD[UserBodyColor] [varchar] (20) NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tProject]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tProject]', N'BillExpensesByItem') IS NULL
ALTER TABLE [dbo].[tProject] ADD[BillExpensesByItem] [tinyint] NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tPreference]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tPreference]', N'DateInputMode') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[DateInputMode] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tPreference]', N'AppBackgroundColor') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AppBackgroundColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tPreference]', N'AppBarColor') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AppBarColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tPreference]', N'AppMenuColor') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AppMenuColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tPreference]', N'AppDarkMode') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AppDarkMode] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tPreference]', N'AppAccentColor') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AppAccentColor] [varchar] (20) NULL
IF COL_LENGTH(N'[dbo].[tPreference]', N'AppBodyColor') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AppBodyColor] [varchar] (20) NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tCampaign]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tCampaign]', N'BillExpensesByItem') IS NULL
ALTER TABLE [dbo].[tCampaign] ADD[BillExpensesByItem] [tinyint] NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tRetainer]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tRetainer]', N'BillExpensesByItem') IS NULL
ALTER TABLE [dbo].[tRetainer] ADD[BillExpensesByItem] [tinyint] NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tBillingSchedule]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tBillingSchedule]', N'BilledComment') IS NULL
ALTER TABLE [dbo].[tBillingSchedule] ADD[BilledComment] [varchar] (50) NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptBillingScheduleGetExistingInvoicesCampaign]'
GO
IF OBJECT_ID(N'[dbo].[sptBillingScheduleGetExistingInvoicesCampaign]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptBillingScheduleGetExistingInvoicesCampaign]
	@CampaignKey int,
	@AdvanceBill tinyint = 0
AS --Encrypt

/*
|| When      Who Rel      What
|| 07/30/26  MFT 26.07.30 (729259) Created
*/

	SET NOCOUNT ON

	select
		ci.InvoiceKey
		,ci.InvoiceNumber
		,ci.InvoiceDate
		,ci.AdvanceBill
		,sum(ci.Amount) as TotalAmount
		,sum(case when ci.BillFrom = 1 then ci.Amount else 0 end) as TotalAmountFF
		,sum(case when ci.BillFrom = 2 then ci.Amount else 0 end) as TotalAmountTM
	from (
		-- billed on projects belonging to the campaign
		select i.InvoiceKey, i.InvoiceNumber, i.InvoiceDate, i.AdvanceBill, il.BillFrom, isum.Amount
		from   tInvoice i (nolock)
			inner join tInvoiceLine il (nolock) on i.InvoiceKey = il.InvoiceKey
			inner join tInvoiceSummary isum (nolock) on il.InvoiceLineKey = isum.InvoiceLineKey
			inner join tProject p (nolock) on p.ProjectKey = isum.ProjectKey
		where  p.CampaignKey = @CampaignKey
		and    il.LineType = 2
		and    isnull(i.AdvanceBill, 0) = isnull(@AdvanceBill, 0)
		and    isnull(i.VoidInvoiceKey, 0) = 0

		union all

		-- billed directly on the campaign
		select i.InvoiceKey, i.InvoiceNumber, i.InvoiceDate, i.AdvanceBill, il.BillFrom, isum.Amount
		from   tInvoice i (nolock)
			inner join tInvoiceLine il (nolock) on i.InvoiceKey = il.InvoiceKey
			inner join tInvoiceSummary isum (nolock) on il.InvoiceLineKey = isum.InvoiceLineKey
		where  i.CampaignKey = @CampaignKey
		and    il.LineType = 2
		and    isnull(isum.ProjectKey, 0) = 0
		and    isnull(i.AdvanceBill, 0) = isnull(@AdvanceBill, 0)
		and    isnull(i.VoidInvoiceKey, 0) = 0
	) ci
	-- exclude invoices already linked to a billing schedule row
	where not exists (select 1 from tBillingSchedule bs (nolock) where bs.InvoiceKey = ci.InvoiceKey)
	group by ci.InvoiceKey, ci.InvoiceNumber, ci.InvoiceDate, ci.AdvanceBill
	order by ci.InvoiceDate, ci.InvoiceNumber

return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceDelete]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptInvoiceDelete]
 @InvoiceKey int,
 @RemoveActionLogRecord int = 0
 
AS --Encrypt

  /*
  || When     Who Rel   What
  || 02/22/07 CRG 8.4   Added Project Rollup section.
  || 04/22/07 GWG 8.42  Added a restriction to deleting invoices with applied credits
  || 08/07/07 GHL 8.5   Added invoice summary deletion + modified project rollup
  || 09/24/07 GHL 8.437 Enh 13169. Modified update of tRetainer since one invoice can be linked to
  ||                    several retainers 
  || 10/12/07 CRG 8.5   Modified to mark voucher unbilled if linked to an Expense Receipt that is being removed from this invoice. 
  || 02/26/08 GHL 8.505 (21944) Added check of child invoices before deleting 
  || 03/09/09 GHL 10.020 (48695) Added check of TotalCost <> 0 for prebill accruals
  || 09/24/09 GHL 10.5    Added deletion of tInvoiceTax
  || 03/01/10 GHL 10.519  Added deletion of tRecurTran
  || 01/17/12 GHL 10.552 Corrected logic for children of recurring parents
  ||                     If we delete the parent, make the children parentless 
  || 09/24/13 GHL 10.572 (181928) Added logic for void invoices
  || 07/31/15 WDF 10.582 (215641) Remove delete of tActionLog Invoice records
  || 03/04/16 GHL 10.602 Added blanking of tBillingSchedule.InvoiceKey
  || 08/18/16 GHL 10.607 Added deletion of tAppHistory
  || 06/16/17 GHL 10.617 (349625) Prevent deletion if there are some underlying transactions linked to close projects
  ||                     That would leave unbilled trans on closed projects
  || 10/04/18 GHL 18.910 (424266) Added logic to handle situation where 2 invoices are linked to the same billing worksheet
  || 06/30/20 MCM 20.070 (520466) Moved the tTime logic where we set fields to null inside a transaction
  || 08/06/20 GHL 20.100 (525304) Delete billing payment records
  || 04/21/23 GAR 23.11.19 (DEV2605) Added deletion of tInvoiceTaxAvalara records
  || 07/08/26 AMP 26.07.19 (729259) Clear BilledComment when invoice is deleted
  */

 IF EXISTS (SELECT 1 FROM tCheckAppl (nolock) WHERE InvoiceKey = @InvoiceKey)
	RETURN -1
   
IF EXISTS(SELECT 1 FROM tTime (nolock) inner join tInvoiceLine (nolock) on tTime.InvoiceLineKey = tInvoiceLine.InvoiceLineKey WHERE InvoiceKey = @InvoiceKey and (WIPPostingOutKey > 0)) 
	RETURN -2
	
IF EXISTS(SELECT 1 FROM tExpenseReceipt (nolock) inner join tInvoiceLine (nolock) on tExpenseReceipt.InvoiceLineKey = tInvoiceLine.InvoiceLineKey WHERE InvoiceKey = @InvoiceKey and (WIPPostingOutKey > 0)) 
	RETURN -2
	
IF EXISTS(SELECT 1 FROM tMiscCost (nolock) inner join tInvoiceLine (nolock) on tMiscCost.InvoiceLineKey = tInvoiceLine.InvoiceLineKey WHERE InvoiceKey = @InvoiceKey and (WIPPostingOutKey > 0)) 
	RETURN -2
	
IF EXISTS(SELECT 1 FROM tVoucherDetail (nolock) inner join tInvoiceLine (nolock) on tVoucherDetail.InvoiceLineKey = tInvoiceLine.InvoiceLineKey WHERE InvoiceKey = @InvoiceKey and (WIPPostingOutKey > 0)) 
	RETURN -2
		
IF EXISTS(SELECT 1 FROM	tInvoice (nolock) Where InvoiceKey = @InvoiceKey and Posted = 1)
	RETURN -3
	

		
Declare @AdvBill tinyint

if exists(Select 1 from tInvoiceAdvanceBill (nolock) Where AdvBillInvoiceKey = @InvoiceKey)
	return -4
		
if exists(Select 1 from tInvoiceCredit (nolock) Where CreditInvoiceKey = @InvoiceKey)
	return -5
	
if exists(Select 1 from tInvoiceAdvanceBill (nolock) Where InvoiceKey = @InvoiceKey)
	return -7
		
if exists(Select 1 from tInvoiceCredit (nolock) Where InvoiceKey = @InvoiceKey)
	return -8
	
if exists(Select 1 from tInvoice (nolock) Where ParentInvoiceKey = @InvoiceKey)
	return -9
	
-- You can not delete an invoice if it has a prebilled order and that order has a voucher applied to it. This would cause the prebill accruals to go out of whack
IF EXISTS(SELECT 1 FROM tPurchaseOrderDetail pd (nolock) 
	inner join tVoucherDetail vd (nolock) on pd.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey 
	inner join tInvoiceLine il (nolock) on pd.InvoiceLineKey = il.InvoiceLineKey
	WHERE il.InvoiceKey = @InvoiceKey
	AND   ISNULL(pd.TotalCost, 0) <> 0 -- Must have something to accrue
	) 
	RETURN -6

declare @VoidInvoiceKey int, @BillingKey int 
select @VoidInvoiceKey = VoidInvoiceKey 
      ,@BillingKey = BillingKey
from tInvoice (nolock) 
where InvoiceKey = @InvoiceKey

if @VoidInvoiceKey = @InvoiceKey
	return -10

if exists (select 1 from tInvoiceSummary summ (nolock)
			inner join tInvoiceLine il (nolock) on summ.InvoiceLineKey = il.InvoiceLineKey
			inner join tProject p (nolock) on summ.ProjectKey = p.ProjectKey
			where summ.InvoiceKey = @InvoiceKey
			and  p.Closed = 1   -- project is closed, that would leave unbilled transactions against a closed project
			and  il.BillFrom = 2 -- Use Transaction or Time and Material
			)
			return -11

-- If the voided transaction is being deleted, update the original to mark as unvoided
if @VoidInvoiceKey <> @InvoiceKey and @VoidInvoiceKey > 0
	Update tInvoice Set VoidInvoiceKey = 0 Where InvoiceKey = @VoidInvoiceKey
	if @@ERROR <> 0 
	begin
		return -99
	end

 CREATE TABLE #ProjectRollup (ProjectKey INT NULL)
 
 INSERT #ProjectRollup (ProjectKey)
 SELECT DISTINCT ProjectKey
 FROM   tInvoiceSummary (NOLOCK)
 WHERE  InvoiceKey = @InvoiceKey
 AND    ProjectKey IS NOT NULL
	

 
 --If Expense Receipts linked to this invoice are also linked to a voucher, mark as Unbilled
 UPDATE	tVoucherDetail
 SET	DateBilled = null,
		InvoiceLineKey = null
 FROM	tExpenseReceipt er (nolock)
 INNER JOIN tInvoiceLine il (nolock) ON er.InvoiceLineKey = il.InvoiceLineKey
 WHERE	il.InvoiceKey = @InvoiceKey
 AND	er.VoucherDetailKey = tVoucherDetail.VoucherDetailKey
  
 UPDATE tExpenseReceipt
 SET  
	InvoiceLineKey =NULL,
	AmountBilled = null,
	DateBilled = NULL
 FROM tInvoiceLine il (NOLOCK)
 WHERE il.InvoiceKey = @InvoiceKey
 AND  il.InvoiceLineKey = tExpenseReceipt.InvoiceLineKey
 
 UPDATE tMiscCost
 SET  
	InvoiceLineKey =NULL,
	AmountBilled = null,
	DateBilled = NULL
 FROM tInvoiceLine il (NOLOCK)
 WHERE il.InvoiceKey = @InvoiceKey
 AND  il.InvoiceLineKey = tMiscCost.InvoiceLineKey
 
  UPDATE tVoucherDetail
 SET 
	InvoiceLineKey =NULL,
	AmountBilled = null	,
	DateBilled = NULL
 FROM tInvoiceLine il (NOLOCK)
 WHERE il.InvoiceKey = @InvoiceKey
 AND  il.InvoiceLineKey = tVoucherDetail.InvoiceLineKey 
 
  UPDATE tPurchaseOrderDetail
 SET 
	InvoiceLineKey = NULL,
	AccruedCost = NULL,
	AmountBilled = null	,
	DateBilled = NULL
 FROM tInvoiceLine il (NOLOCK)
 WHERE il.InvoiceKey = @InvoiceKey
 AND  il.InvoiceLineKey = tPurchaseOrderDetail.InvoiceLineKey 
 
 Declare @CompanyKey int
		,@RecurringParentKey int
		,@InvoiceDate datetime		
 Select @CompanyKey = CompanyKey
		,@RecurringParentKey = RecurringParentKey
		,@InvoiceDate = InvoiceDate 
 from   tInvoice (NOLOCK)
 Where  InvoiceKey = @InvoiceKey

Declare @UpdateRetainer int, @RetainerKey int, @RetainerLastBillingDate datetime

	Select @RetainerKey = -1
	While (1=1)
	Begin
		Select  @RetainerKey = MIN(il.RetainerKey) 
		from    tInvoice i (NOLOCK)
			inner join tInvoiceLine il (NOLOCK) ON i.InvoiceKey = il.InvoiceKey
		Where   i.InvoiceKey = @InvoiceKey
		And     il.RetainerKey IS NOT NULL
		And     il.BillFrom = 1
		AND     il.RetainerKey > @RetainerKey

		If @RetainerKey IS NULL
			Break
			
		Select @RetainerKey = isnull(@RetainerKey, 0)
			  ,@UpdateRetainer = 0
			  	
		if @RetainerKey <> 0
		begin
			Select @RetainerLastBillingDate = LastBillingDate
			From tRetainer (NOLOCK)
			Where RetainerKey = @RetainerKey
			
			If @InvoiceDate = @RetainerLastBillingDate
			begin
				Select @UpdateRetainer = 1
					,@RetainerLastBillingDate = NULL
				
				Select @RetainerLastBillingDate = MAX(i.InvoiceDate)
				From tInvoice i (NOLOCK)
					Inner Join tInvoiceLine il (NOLOCK) ON i.InvoiceKey = il.InvoiceKey
				Where  i.CompanyKey = @CompanyKey
				And    i.InvoiceKey <> @InvoiceKey
				And	   il.RetainerKey = @RetainerKey
				And	   il.BillFrom = 1 -- Indicates retainer amount
			end
		end 

		If @UpdateRetainer = 1
			Update tRetainer Set LastBillingDate = @RetainerLastBillingDate Where RetainerKey = @RetainerKey  
	End

	DELETE tRecurTran WHERE Entity = ''INVOICE'' and EntityKey = @InvoiceKey

	DELETE tInvoiceAdvanceBill
	WHERE InvoiceKey = @InvoiceKey

	DELETE tBillingPayment
	WHERE  Entity = ''INVOICE'' and EntityKey = @InvoiceKey

	DELETE tInvoiceCredit
	WHERE InvoiceKey = @InvoiceKey

	DELETE tInvoiceLineTax
		FROM tInvoiceLine (NOLOCK)
	WHERE tInvoiceLine.InvoiceLineKey = tInvoiceLineTax.InvoiceLineKey
	AND   tInvoiceLine.InvoiceKey = @InvoiceKey

--start trans
Begin Transaction

	UPDATE tTime
	SET  
		InvoiceLineKey = null,
		BilledService = null,
		BilledHours = null,
		BilledRate = null,
		DateBilled = NULL
	FROM tInvoiceLine il (NOLOCK)
	WHERE il.InvoiceKey = @InvoiceKey
	AND  il.InvoiceLineKey = tTime.InvoiceLineKey

	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -12
	end

	DELETE tInvoiceSummary
	WHERE InvoiceKey = @InvoiceKey
	
	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -13
	end

	DELETE tInvoiceLine
	WHERE InvoiceKey = @InvoiceKey

	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -14
	end

	DELETE tInvoiceTax
	WHERE InvoiceKey = @InvoiceKey
	
	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -15
	end
	-- (424266) this is a patch because several invoices were linked to the same EBWS, if we blindly null InvoiceKey, the EBWS is free to be billed again
	-- but there is another invoice already, so try to rehook here the billing WS to another invoice

	declare @InvoiceCount int
	declare @OtherInvoiceKey int
	select @InvoiceCount = count(*) from tInvoice (nolock) where CompanyKey = @CompanyKey and BillingKey = @BillingKey

	if @InvoiceCount <= 1
		UPDATE tBilling
		SET    Status = 4
			  ,InvoiceKey = null
		WHERE CompanyKey = @CompanyKey
		AND   InvoiceKey = @InvoiceKey
	else 
	begin
		select @OtherInvoiceKey = InvoiceKey 
		from   tInvoice (nolock)
		where  CompanyKey = @CompanyKey and BillingKey = @BillingKey
		and InvoiceKey <> @InvoiceKey 

		if @OtherInvoiceKey is not null
			UPDATE tBilling
			SET    InvoiceKey = @OtherInvoiceKey
			WHERE CompanyKey = @CompanyKey
			AND   InvoiceKey = @InvoiceKey
	end

	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -16
	end

	update tBillingSchedule
	set    InvoiceKey = null
	      ,BilledComment = null
	where  InvoiceKey = @InvoiceKey

	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -17
	end

	DELETE tInvoiceTaxAvalara
	WHERE InvoiceKey = @InvoiceKey
 
	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -19 --Error on delete tInvoiceTaxAvalara record
	end

	DELETE tInvoice
	WHERE InvoiceKey = @InvoiceKey
 
	if @@ERROR <> 0 
	begin
		rollback transaction 
		return -18 --Error on delete invoice
	end
Commit Transaction

    DELETE tAppHistory WHERE ActionID = ''billing.invoices.edit'' AND ActionKey = @InvoiceKey

	-- if there is a recurrence going on and this is the parent
	if @RecurringParentKey <> 0 and @RecurringParentKey = @InvoiceKey
		-- if exists any children	
		if exists(Select 1 from tInvoice (nolock) Where RecurringParentKey = @RecurringParentKey and InvoiceKey <> @RecurringParentKey)
			-- make the children parentless
			Update tInvoice
			Set RecurringParentKey = 0 
			Where RecurringParentKey = @RecurringParentKey

 DECLARE @ProjectKey INT
 SELECT @ProjectKey = -1
 WHILE (1=1)
 BEGIN
	SELECT @ProjectKey = MIN(ProjectKey)
	FROM   #ProjectRollup
	WHERE  ProjectKey > @ProjectKey
	
	IF @ProjectKey IS NULL
		BREAK
		
	-- Rollup project, TranType = Billing or 6	
	EXEC sptProjectRollupUpdate @ProjectKey, 6, 0, 0, 0, 0
 END

 IF @RemoveActionLogRecord = 1
 BEGIN
	DELETE 
	FROM tActionLog 
	WHERE CompanyKey = @CompanyKey
		AND Entity = ''Client Invoice'' 
		AND EntityKey = @InvoiceKey
		AND Action = ''Generated''
 END
	 
 RETURN 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptBillingScheduleLinkInvoice]'
GO
IF OBJECT_ID(N'[dbo].[sptBillingScheduleLinkInvoice]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptBillingScheduleLinkInvoice]
	@BillingScheduleKey int,
	@InvoiceKey int
AS --Encrypt

/*
|| When      Who Rel      What
|| 07/30/26  MFT 26.07.30 (729259) Created to link an existing invoice to a billing schedule row.
*/

	SET NOCOUNT ON

	-- Link the selected invoice to this schedule row. Only one invoice may be linked.
	-- BilledComment is intentionally NOT set here.
	-- BillingScheduleKey is the unique PK; tBillingSchedule has no CompanyKey column.
	update tBillingSchedule
	set    InvoiceKey = @InvoiceKey
	where  BillingScheduleKey = @BillingScheduleKey

return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptBillingScheduleRemoveInvoice]'
GO
IF OBJECT_ID(N'[dbo].[sptBillingScheduleRemoveInvoice]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptBillingScheduleRemoveInvoice]
	@BillingScheduleKey int
AS --Encrypt

/*
|| When      Who Rel      What
|| 07/30/26  MFT 26.07.30 (729259) Created to remove the invoice reference (InvoiceKey) and BilledComment from a billing schedule row.
*/

	SET NOCOUNT ON

	-- Clear the invoice reference, the billing worksheet link and the billed comment so the
	-- scheduled milestone is freed up and can be billed again - same as when the invoice is voided.
	-- BillingScheduleKey is the unique PK; tBillingSchedule has no CompanyKey column.
	update tBillingSchedule
	set    InvoiceKey = null
	      ,BillingKey = null
	      ,BilledComment = null
	where  BillingScheduleKey = @BillingScheduleKey

return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_TimeDetail]'
GO
IF OBJECT_ID(N'[dbo].[vReport_TimeDetail]', 'V') IS NOT NULL
EXEC sp_executesql N'





ALTER VIEW [dbo].[vReport_TimeDetail] 
AS 
 
/* 
  || When     Who Rel      What 
  || 10/13/06 WES 8.3567   Added Project Billing Status 
  || 12/28/06 GHL 8.4      Added Campaign ID 
  || 11/06/07 CRG 8.5      (10954) Added DateBilled, Billing Item ID, and Billing Item Name 
  || 11/06/07 CRG 8.5      (13158) Added Client Company Type 
  || 5/23/08  CRG 8.5.1.2  (25454) Added GLCompany 
  || 7/20/08  GWG 10.0.0.6 (30741) Added GL Class from the project 
  || 8/14/08  GHL 10.0.0.6 (32476) Added task description 
  || 10/20/08 GWG 10.0.1.1 Fixed the project full name to use a - 
  || 04/06/09 MAS 10.0.2.2 (50443) Added Write-off Hours, Write-off Total, Marked Billed Hours and Marked Billed Total fields 
  || 05/1/09  GWG 10.0.2.4 Added the billed comments 
  || 09/10/09 GHL 10.5     Added Transferred Out 
  || 01/5/10  GWG 10.5.1.6 Added client''s project number 
  || 01/06/10 RLB 10.5.1.6 Added Task Type 
  || 03/10/10 RLB 10.5.2.0 Formatting Date Worked Month  
  || 04/30/10 RLB 10.5.2.2 (63218)Added Parent Company Name 
  || 07/28/10 RLB 10.5.3.3 (83803)Added Non Billable Project to the Data set 
  || 08/30/10 RLB 10.5.3.4 (88843)Added Billed Service Code 
  || 01/16/11 GWG 10.5.4.0 Added the rounding in for actual billable amount 
  || 04/07/11 RLB 10.5.4.3 (108045) Removed Project Short Name 
  || 04/28/11 RLB 10.5.4.3 (109940) fixed join on Parent Company Name 
  || 06/29/11 RLB 10.5.4.5 (115335) changed tCompany to a left outer join because contacts could not have a company 
  || 07/27/11 RLB 10.5.4.6 (114500) Added Line Number which is the tasks order in the projet schedule screen 
  || 07/27/11 RLB 10.5.4.6 (111324) Added Campaign Segment 
  || 10/8/11  GWG 10.5.4.9 Added a link to the task through the detail task key 
  || 10/11/11 RLB 10.5.4.9 Added ApprovedCOHours to the Budget hours  
  || 12/09/11 RLB 10.5.5.1 (121131) Added Verified 
  || 02/29/12 MFT 10.5.5.3 Added Date Worked Week 
  || 03/16/12 GHL 10.5.5.4 (137417) Add Date Time fields 
  || 04/24/12 GHL 10.5.5.5 Added GLCompanyKey in order to map/restrict 
  ||                       p.GLCompanySource = 0 then p.GLCompanyKey 
  ||                       p.GLCompanySource = 1 then u.GLCompanyKey 
  ||                       p.GLCompanySource is null i.e. no project then u.GLCompanyKey 
  || 09/25/12 GWG 10.5.6.0 Added Address fields 
  || 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey 
  || 01/15/13 GWG 10.5.6.4 Added some additional fields for reporting 
  || 02/13/13 WDF 10.5.6.5 (160177) Added Timesheet From/To dates 
  || 03/01/13 WDF 10.5.6.5 (169504) Added employees Default GLCompany 
  || 05/01/13 GWG 10.5.6.7 Added users class 
  || 05/22/13 MFT 10.5.6.8 (174957) Added ta.Comments 
  || 08/08/13 GWG 10.5.7.0 Added Allocated Hours 
  || 11/15/13 RLB 10.5.7.4 (191407) Added Yes OR No for tax 1 and 2  on tasks set on the time entry 
  || 06/17/14 WDF 10.5.8.1 (217923) Added Vendor Invoice Number 
  || 10/16/14 WDF 10.5.8.5 (Abelson Taylor) Added Billling Title 
  || 12/16/14 RLB 10.5.8.7 (239571) Added Client Billing State and Company CustomFields from the client on the project 
  || 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID 
  || 03/10/15 GHL 10.5.9.0 (Abelson Taylor) Added Department at the Time  
  || 03/20/15 WDF 10.5.9.0 (Abelson Taylor) Added WriteOffDate 
  || 05/15/15 MCM 10.5.9.2 (249457) Added Primary Contact  
  || 06/02/15 MCM 10.5.9.3 (256400) Added Contractor 
  || 10/09/15 KMC 10.5.9.7 (273426) Removed the CAST from the ts.DateCreated, ts.DateSubmitted, and ts.DateApproved and are converting to UTC adjusted 
  ||                        dates (no time) in WMJ 
  || 01/25/16 WDF 10.6.0.0 (286743) Formatting Date Worked Week  
  || 03/18/16 WDF 10.6.0.2 (293875) Added [On Hold] 
  || 04/12/16 MFT 10.6.0.3 (296036) Added WriteOffComment 
  || 06/15/16 GWG 10.6.0.5 Added in Paid Status 
  || 07/12/16 WDF 10.6.0.6 (299976) Added Campaign Custom Fields 
  || 08/09/16 WDF 10.6.0.7 (309294) Added [Salesperson Name] 
  || 08/11/16 KMC 10.6.0.7 (307284) Added Active status for tUser as [Active User] 
  || 09/20/16 QMD 10.6.0.8 (309378) Added LastModified 
  || 10/05/16 WDF 10.6.0.9 (316052) Set [Active User] as YES/NO 
  || 11/21/16 KMC 10.6.1.0 (321574) Added user email address 
  || 02/17/17 MCM 10.6.1.3 (323908) Updating the User Full Name logic to match the vUserName 
  || 02/17/17 QMD 10.6.1.3 Added TimeKey to the select 
  || 03/20/17 MCM 10.6.1.4 (339685) Adding User Name, already had User Full Name 
  || 09/25/17 GHL 10.6.2.0 (295216) Added timesheet tardiness field 
  || 09/28/17 GWG 10.6.2.0 Added Project Close Date 
  || 10/10/17 GWG 10.6.2.0 Fix spelling error 
  || 12/4/17  GWG 10.6.2.2 Added Predecessors completed 
  || 01/30/17 GWG 18.2     Added budget hours and dollars by project and service.
  || 04/03/18 WDF 18.4     Added [User Title]
  || 04/25/18 RLS 18.5     (398138) Added CurrencyID
  || 05/15/18 GWG 18.5.0   added campaign active
  || 06/26/18 AMP 18.7.0   (407643)  - Modified Column Name for Service Description lookup
  || 07/19/18 RLS 18.8.0   (410986) Added [Date of Hire]
  || 07/24/18 GWG 18.8.0   Added billable/nonbillable label for graphing
  || 08/28/18 AMP 18.9.0   (413912) Added standard column ''Billed on Invoice Amount'' 
  || 09/24/18 GWG 18.9.1   Protect against nulls in amount billed
  || 11/07/18 GHL 18.9.3   (428591) Added [Invoice Voided] that indicates that the invoice was voided
  || 12/18/18 GWG 19.1	   Added month name to formatted month
  || 03/07/19 AMP 19.0.4.0 (433620) Added Summary Task Name 
  || 03/25/19 GWG 10.0.4.0 (451555) Added project total hours, labor net and outside expenses net
  || 03/25/19 QMD 19.0.4.0 (452162) Added TaskKey
  || 05/29/19 RLS 19.0.5.0 (459194) Added Project Percent Complete
  || 06/06/19 RLB 19.0.7.0 (446229) Adding Project Manager
  || 07/25/19 QMD 19.0.8.0 (470423) Adding UserKey as EmployeeKey
  || 09/09/19 AMP 19.1.0.0 (477617) Added field for Service Hourly Cost
  || 10/21/19  RLB 19.1.1.0 (457226) Added SupervisorName
  || 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
  || 03/18/20 RLS 20.0.4.0 (505211) Added [Billing Group Code] and [Billing Group Description]
  || 03/18/20 RLB 20.0.4.0 (507087) removed the Convert on start time and end time
  || 06/22/20 CRG 20.0.7.0 (519687) Changed Date Created and Date And Time Created to use the time entry DateAdded instead of timesheet
  || 07/23/20 RLS 20.0.8.0 (520337) Added [Deliverable Name] and join to tReviewDeliverable
  || 07/29/20 RLB 20.0.8.0 (523363) Fixed how Project primary contact field
  || 08/20/20 RLB 20.0.9.0 (526270) change outer join to tDeliverable can only use DeliverableKey on tTime
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 09/08/20 GAR 20.1.0.0 (527210) Added Vendor Name (from the vendor invoice number)
  || 02/24/20 RLB 21.03.14 (543274) Added [Campaign Budget Hours] and [Campaign Segment Budget Hours]
  || 03/30/21 GHL 21.04.18 (552776) Added custom field key 4 to test 4th direction on CF
  || 05/06/21 RLS 21.0.6.0 (555522) Added [Time paused]
  || 06/29/21 RLS 21.0.7.0 (563027) Wrapped u.Title in ISNULL()
  || 07/12/21 MCM 21.0.8.0 (563356) Added Task Billing Item and Task Billing Item Name
  || 12/15/21 AMP 22.02.20 (579957) Added Timeline Segment
  || 01/06/22 AMP 22.01.23 (583009) Added Vendor Cost
  || 02/22/22 RLB 22.03.20 (587756) changed planned project name, number and full name to include the planning project name not just linked through planningprojectkey
  || 03/11/22 GWG 22.03.20 (583542) Adding in the allocated hours for the week. Needed by fusion for a particular report
  || 04/28/22 RLS 22.05.15 (595589) Added PlanStart,PlanComplete,ActStart,ActComplete,BaseStart,BaseComplete
  || 04/28/22 RLS 22.05.15 (598368) Replaced ISNULL(tu.ActStart, ta.ActStart) and ISNULL(tu.ActComplete, ta.ActComplete) with ta.ActStart and ta.ActComplete and removed the outer join to tTaskUser
  || 07/21/22 GHL 22.08.00 (604153) Added Overtime field
  || 09/01/22 AMP 22.09.18 (610375) Modified retrieving the Vendor Name. If there is no vendor invoice tied to the time entry get the Vendor Name from the user record
  || 01/04/23 RLB 23.02.19 (625612) Added Budget Hours by Task. Any task labor hours on approved estimate
  || 03/13/23 RLB 23.04.16 (629165) Adding Office Color, department and service
  || 08/11/23 RLB 23.09.17 (648008) added project type color and Timeline Segment Color
  || 03/18/24 RLS 24.04.14 (665054) Added [Project GL Company ID] and [Project GL Company Name]
  || 07/23/24 RLS 24.08.18 (675330) Added [Company Owner]
  || 10/25/24 QMD 24.11.17 (685924) Added DateUnapproved
  || 03/20/25 RLS 25.04.20 (695482) Added [Billable Rate]
  || 04/16/25 RLS 25.05.18 (694661) Added [Opportunity ID],[Opportunity Name],[Opportunity Outcome],[Opportunity Next Steps],[Opportunity Stage] and [Opportunity Status] 
  || 02/19/26 RLB 26.03.15 (722386) Added [Time Sheet Required]
  || 07/10/26 GAR 26.08.16 (732133) Added Source for use with the MCP time entries
  */ 
 
SELECT  
	ts.CompanyKey, 
	case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey, 
	ts.CompanyKey as OwnerCompanyKey, 
	ts.TimeSheetKey, 
	p.CustomFieldKey, 
	cClient.CustomFieldKey AS CustomFieldKey2, 
	cp.CustomFieldKey as CustomFieldKey3,
	rd.CustomFieldKey as CustomFieldKey4, 
	t.TimeKey, 
	cClient.CompanyName AS [Client Name],  
	cClient.CustomerID AS [Client ID], 
	clad.State AS [Client Billing State], 
	p.ProjectName AS [Project Name],   
	p.ProjectNumber AS [Project Number],  
	p.ClientProjectNumber AS [Client Project Number], 
	p.CurrencyID as [Currency],
	Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project],
	LTRIM(RTRIM(ISNULL(pc.FirstName,'''') + '' '' + ISNULL(pc.LastName,''''))) AS [Project Primary Contact], 
	p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name], 
	pt.ProjectTypeName as [Project Type],
	pt.ProjectTypeColor as [Project Type Color],
	pt.Description as [Project Type Description], 
	cp.CampaignID as [Campaign ID], 
	cp.CampaignName as [Campaign Name], 
	cs.SegmentName as [Campaign Segment], 
	LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager],
	LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager], 
	u.SystemID AS [User System ID],  
	ISNULL(u.Title, '''') AS [User Title],  
	u.FirstName AS [User First Name],  
	u.LastName AS [User Last Name],  
	LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,''''))) AS [User Name], 
	case  
		when u.MiddleName is null then LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,'''')))  
		else LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + SUBSTRING(u.MiddleName, 1, 1) + '' '' + ISNULL(u.LastName,'''')))  
	end as [User Full Name], 
	glc.GLCompanyID AS [Default GLCompany ID], 
	glc.GLCompanyID + '' - '' + glc.GLCompanyName AS [Default GLCompany Full Name], 
	d.DepartmentName AS [User Department], 
	d.DepartmentColor as [User Department Color],
	case when t.DepartmentKey is not null then d_t.DepartmentName  
		else case when isnull(pref.DefaultDepartmentFromUser, 0) = 1 then d.DepartmentName else d_s.DepartmentName end  
	end as [Department at the Time],
	case when t.DepartmentKey is not null then d_t.DepartmentColor  
		else case when isnull(pref.DefaultDepartmentFromUser, 0) = 1 then d.DepartmentColor else d_s.DepartmentColor end  
	end as [Department Color at the Time],	
	o.OfficeName AS [User Office Name],
	o.OfficeColor as [User Office Color],
	oP.OfficeName AS [Project Office Name], 
	oP.OfficeColor as [Project Office Color],
	c.CompanyName AS [User Company Name], 
	pcn.CompanyName AS [Parent Company], 
	ta.TaskID AS [Task ID],  
	ta.TaskID + '' - '' + ta.TaskName AS [Task Full Name],  
	ta.TaskName as [Task Name], 
	td.TaskID as [Assignment ID], 
	td.TaskName as [Assignment Subject], 
	td.TaskID + '' - '' + td.TaskName AS [Assignment Full Name], 
	ta.Comments AS [Task Status Comments], 
	tat.TaskAssignmentType as [Task Type], 
	ta.Description AS [Task Description],  
	ta.ProjectOrder AS [Line Number], 
	Case ISNULL(ta.PredecessorsComplete, 0) When 1 then ''YES'' else ''NO'' end as [Predecessors Completed], 
	Case ISNULL(ta.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable], 
	Case ISNULL(ta.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable 2], 
	s.ServiceCode AS [Service Code],
	s.ServiceColor as [Service Color],
	t.RateLevel AS [Service Rate Level], 
	bs.ServiceCode AS [Billed Service Code], 
	bs.ServiceColor as [Billed Service Color],
	ISNULL(t.DateAdded, ts.DateCreated) as [Date Created],   --Adjusted for UTC in WMJ and shown just as date without time 
	ts.DateSubmitted as [Date Submitted For Approval],   --Adjusted for UTC in WMJ and shown just as date without time 
	ts.DateApproved as [Date Approved],   --Adjusted for UTC in WMJ and shown just as date without time 
	ta.DueBy as [Task Due By], 
	ta.PercComp as [Task Percent Complete], 
	p.PercComp as [Project Percent Complete], 
	ISNULL(t.DateAdded, ts.DateCreated) as [Date And Time Created], 
	ts.DateSubmitted as [Date And Time Submitted], 
	ts.DateApproved as [Date And Time Approved], 
	ts.StartDate as [Time Sheet From], 
	ts.EndDate as [Time Sheet To], 
 
	abk.UserName AS [Approved By], 
	app.UserName AS [Current Approver], 
	spr.UserName AS [Supervisor Name], 
	Case ts.Status 
		When 1 then ''Not Sent For Approval'' 
		When 2 then ''Sent For Approval'' 
		When 3 then ''Rejected'' 
		When 4 then ''Approved'' end as [Approval Status], 
	wor.ReasonName AS [Write Off Reason], 
	t.WriteOffComment AS [Write Off Comment], 
	Case t.RateLevel  
		When 1 then ISNULL(s.Description1, s.Description) 
		When 2 then ISNULL(s.Description2, s.Description) 
		When 3 then ISNULL(s.Description3, s.Description) 
		When 4 then ISNULL(s.Description4, s.Description) 
		When 5 then ISNULL(s.Description5, s.Description) 
		Else s.Description 
	END as [Service Description for Rate], 
	s.Description as [Service Description],  
	ti.TitleName as [Billing Title Name], 
	ti.TitleID as [Billing Title ID], 
	cd.DivisionName as [Client Division], 
	cd.DivisionID as [Client Division ID], 
	cpd.ProductName as [Client Product], 
	cpd.ProductID as [Client Product ID], 
	t.WorkDate AS [Date Worked],  
	DATEPART(Year, t.WorkDate) AS [Date Worked Year], 
	CAST(DATEPART(Year, t.WorkDate) AS VARCHAR(4)) AS [Date Worked Year Formatted], 
	DATENAME(Month, t.WorkDate) AS [Date Worked Month], 
	RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, t.WorkDate) AS [Date Worked Month Formatted], 
	RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) AS [Date Worked Month Number], 
	t.ActualHours AS [Actual Hours Worked],  
	CASE WHEN p.NonBillable = 0 AND t.ActualRate > 0 THEN t.ActualHours 
		ELSE 0 END AS [Actual Billable Hours], 
	CASE WHEN p.NonBillable = 1 OR t.ProjectKey IS NULL OR t.ActualRate = 0  
		THEN t.ActualHours ELSE 0 END AS [Actual Non Billable Hours], 
	CASE WHEN (p.NonBillable = 0 OR p.NonBillable IS NULL) AND t.ActualRate > 0 THEN ROUND(t.ActualHours * t.ActualRate, 2) ELSE 0 END AS [Actual Billable Amount],  
	CASE WHEN p.NonBillable = 1 OR t.ProjectKey IS NULL  
		THEN ROUND(t.ActualHours * t.ActualRate, 2) ELSE 0 END AS [Actual Non Billable Amount], 
	t.ActualRate AS [Actual Billing Rate],  
	t.CostRate AS [Actual Cost Rate], 
	ROUND(t.CostRate * t.ActualHours, 2) AS [Actual Total Cost], 
	ROUND((t.ActualRate - t.CostRate) * t.ActualHours, 2) AS [Actual Net Profit], 
	ISNULL(t.BilledHours, 0) AS [Billed Hours],  
	t.BilledRate AS [Billed Rate],  
	ROUND(t.BilledHours * t.BilledRate, 2) AS [Billed Total Amount], 
	ROUND((t.BilledRate - t.CostRate) * t.BilledHours, 2) AS [Billed Net Profit], 
	t.BilledComment as [Billed Comments],  
	t.Comments, 
	Case t.OnHold When 1 then ''YES'' else ''NO'' end as [On Hold], 
	ps.ProjectStatus as [Project Status], 
	CASE p.NonBillable WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Non Billable Project], 
	CASE p.Active WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Active Project], 
	CASE t.Downloaded WHEN 1 THEN ''YES'' ELSE ''NO'' END as Downloaded, 
	v.InvoiceNumber as [Vendor Invoice Number], 
	Case When t.VoucherKey = 0 then ''Marked As Paid'' When t.VoucherKey > 0 then ''Paid'' else ''Not Paid'' end as [Paid Status], 
	i.InvoiceNumber as [Invoice Number], 
	Case When t.InvoiceLineKey IS NULL then 
		Case t.WriteOff When 1 then ''Write Off'' else ''Unbilled'' end 
		else ''Billed'' end as [Billing Status],	 
	 
	Case When t.InvoiceLineKey = 0 then 
		t.ActualHours else 0 end as [Marked Billed Hours], 
 
	Case When t.InvoiceLineKey = 0 then 
		ROUND(t.ActualRate * t.ActualHours, 2) else 0 end as [Marked Billed Total], 
 
	Case When t.WriteOff = 1 then 
		t.ActualHours else 0 end as [Write off Hours], 
 
	Case When t.WriteOff = 1 then 
		ROUND(t.ActualRate * t.ActualHours, 2) else 0	end as [Write off Total], 
 
	Case t.WriteOff 
		When 1 then t.DateBilled 
		else NULL 
	end as [Write Off Date], 
 
	Case When t.WIPPostingInKey = 0 then ''NO'' else ''YES'' end as [Posted Into WIP], 
	Case When t.WIPPostingOutKey = 0 then ''NO'' else ''YES'' end as [Posted Out Of WIP], 
	Case When t.Verified = 0 then ''NO'' else ''YES'' end as [Verified], 
 
	t.StartTime as [Start Time], 
	t.EndTime as [End Time], 
	t.StartTime as [Start Date Time], 
	t.EndTime as [End Date Time], 
 
	Case When t.InvoiceLineKey is null then 0 else ROUND(t.ActualRate * t.ActualHours, 2) - ISNULL(ROUND(t.BilledHours * t.BilledRate, 2), 0) end AS [Billed Difference], 
	ta.EstHours + ta.ApprovedCOHours as [Budget Hours], 
	r.Title as [Retainer Name], 
	pbs.ProjectBillingStatus as [Project Billing Status], 
	t.DateBilled as [Date Billed], 
	wt.WorkTypeID as [Billing Item ID], 
	wt.WorkTypeName as [Billing Item Name], 
	wti.WorkTypeID as [Billing Title Item ID], 
	wti.WorkTypeName as [Billing Title Item Name], 
	ct.CompanyTypeName as [Client Company Type], 
	case when p.GLCompanySource = 0 then glcP.GLCompanyID else glc.GLCompanyID end as [Company ID], 
	case when p.GLCompanySource = 0 then glcP.GLCompanyName else glc.GLCompanyName end as [Company Name], 
	glcP.GLCompanyID as [Project GL Company ID],
	glcP.GLCompanyName as [Project GL Company Name],
	cl.ClassID as [Class ID], 
	cl.ClassName as [Class Name], 
	ucl.ClassID as [User Class ID], 
	ucl.ClassName as [User Class Name], 
    Case When t.TransferToKey IS NULL Then ''NO'' else ''YES'' end as [Transferred Out], 
	Cast(CONVERT(varchar(2), DATEPART(WEEK, t.WorkDate), 0) AS INT) AS [Date Worked Week], 
	RIGHT(''0'' + CAST(DATEPART(WEEK, t.WorkDate) AS VARCHAR(2)), 2) AS [Date Worked Week Formatted], 
	 
	addrh.Address1 as [Home Address 1], 
	addrh.Address2 as [Home Address 2], 
	addrh.Address3 as [Home Address 3], 
	addrh.City as [Home Address City], 
	addrh.State as [Home Address State], 
	addrh.PostalCode as [Home Address Postal Code], 
	addrh.Country as [Home Address Country], 
	 
	addro.Address1 as [Other Address 1], 
	addro.Address2 as [Other Address 2], 
	addro.Address3 as [Other Address 3], 
	addro.City as [Other Address City], 
	addro.State as [Other Address State], 
	addro.PostalCode as [Other Address Postal Code], 
	addro.Country as [Other Address Country], 
	 
	Case p.BillingMethod When 1 then ''Time and Materials'' When 2 then ''Fixed Fee'' When 3 then ''Retainer'' end as [Project Billing Method], 
	p.StartDate as [Project Start Date], 
	p.CompleteDate as [Project Due Date], 
		-- Budgeted data 
	p.EstHours + p.ApprovedCOHours as [Project Budget Hours], -- [Estimate Total Hours] 
	p.EstLabor + p.ApprovedCOLabor as [Project Budget Labor Gross], -- [Estimate Total Labor] 
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Project Total Budget wo Taxes], -- [Estimate Total] 
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Project Total Budget], --New field 
	pir.EstQty as [Budget Hours by Service],
	pir.EstGross as [Budget Gross by Service],
	p.ProjectCloseDate as [Project Close Date], 
	pr.BilledAmount as [Project Amount Billed], 
	pr.Hours as [Project Total Hours],
	pr.LaborNet as [Project Total Labor Net],
	pr.MiscCostNet + pr.VoucherNet + pr.ExpReceiptNet + pr.OpenOrderNet as [Project Total Expense Net],
	aa.Hours as [Allocated Hours], 
	p.ProjectKey,  
	pcu.UserName as [Primary Contact], 
	case u.Contractor when 1 then ''YES'' ELSE ''NO'' end as [Contractor], 
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Salesperson Name], 
	CASE u.Active WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Active User], 
	t.LastModified as [Last Modified], 
	sg.GroupName as [Security Group], 
	u.Email as [User Email Address], 
	u.DateHired as [Date of Hire], 
	case  
		when ts.OnTime is null then '''' -- when the timesheet is not submitted or was created before issue 295216 
		when ts.OnTime = 0 then ''NO'' 
		else ''YES'' 
	end as [Time Sheet Submitted On Time], 
	case  
		when t.OnTime is null then '''' -- when the time entry was created before issue 295216 
		when t.OnTime = 0 then ''NO'' 
		else ''YES'' 
	end as [Time Entered On Time] ,
	Case cp.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active],
	Case When p.NonBillable = 1 or t.ActualRate = 0 then ''Non Billable'' else ''Billable'' end as [Billable],
	Case When t.InvoiceLineKey > 0 then 
		ISNULL(t.BilledHours, 0) else 0 end as [Billed on Invoice Hours], 
	Case When t.InvoiceLineKey > 0 then 
    	ROUND(ISNULL(t.BilledRate, 0) * ISNULL(t.BilledHours, 0), 2) else 0 end as [Billed on Invoice Amount], --Issue: 413912
	1 as Counter, -- What is that ???
	Case When isnull(i.VoidInvoiceKey,0) = 0 then ''NO'' else ''YES'' end as [Invoice Voided],
	st.TaskName as [Summary Task Name],
	t.TaskKey,
	u.UserKey as EmployeeKey,
	s.HourlyCost as [Hourly Cost],
	bg.BillingGroupCode as [Billing Group Code] ,
	bg.Description as [Billing Group Description],
	rd.DeliverableName as [Deliverable Name],	
	ISNULL(ven.CompanyName, c2.CompanyName ) as [Vendor Name],
	ISNULL(cp.EstHours, 0) + ISNULL(cp.ApprovedCOHours, 0) as [Campaign Budget Hours],
	ISNULL(cs.EstHours, 0) + ISNULL(cs.ApprovedCOHours, 0) as [Campaign Segment Budget Hours],
	ISNULL(t.PauseHours, 0) as [Time Paused],
	twt.WorkTypeID as [Task Billing Item ID], 
	twt.WorkTypeName as [Task Billing Item Name],
	ISNULL(tls.SegmentName,tls2.SegmentName) as [Timeline Segment],
	ISNULL(tls.SegmentColor, tls2.SegmentColor) as [Timeline Segment Color],
	u.VendorCost as [Vendor Cost],
	ta.PlanStart as [Plan Start Date],
	ta.PlanComplete as [Plan Complete Date],
	ta.BaseStart as [Baseline Start Date],
	ta.BaseComplete as [Baseline Complete Date],
	ta.ActStart as [Actual Start Date],
	ta.ActComplete as [Actual Complete Date],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectNumber
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else pp.ProjectNumber
				end
	end  as [Planning Project Number],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectName
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else pp.ProjectName
				end
	end  as [Planning Project Name],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectNumber + '' - '' + p.ProjectName
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else Case When pp.ProjectNumber is null then pp.ProjectName else pp.ProjectNumber + '' - '' + pp.ProjectName end
				end
	end  as [Planning Project Full Name],
	(Select Sum(Hours) from vTaskUserHour b (nolock)
		Where t.ProjectKey = b.ProjectKey and t.UserKey = b.UserKey and t.ServiceKey = b.ServiceKey and  DatePart(week, WorkDate) = DatePart(week,b.BucketStart) and YEAR(WorkDate) = year(b.BucketStart)) as [Assigned Week Hours]
   ,CASE t.Overtime WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Overtime]
   ,bb.Hours as [Budget Hours by Task]
   ,con.UserName as [Company Owner]
   ,ts.DateUnapproved as [Date And Time Unapproved]
   ,u.HourlyRate as [Billable Rate]
   ,l.LeadID as [Opportunity ID]
   ,l.Subject as [Opportunity Name]
   ,loc.Outcome as [Opportunity Outcome]
   ,l.CurrentStatus as [Opportunity Next Steps]
   ,lstage.LeadStageName as [Opportunity Stage]
   ,lstatus.LeadStatusName as [Opportunity Status]
   ,Case ISNULL(upf.TimesheetRequired, 0) When 1 then ''YES'' else ''NO'' end as [Time Sheet Required]
   ,t.Source as [Source]
FROM 
	tTimeSheet ts (nolock) 
	INNER JOIN tPreference pref (nolock) on ts.CompanyKey = pref.CompanyKey 
	INNER JOIN tTime t (nolock) ON ts.TimeSheetKey = t.TimeSheetKey 
	INNER JOIN tUser u (nolock) ON t.UserKey = u.UserKey 
	LEFT OUTER JOIN tUserPreference upf (nolock) on u.UserKey = upf.UserKey
	LEFT OUTER JOIN tVoucher v (nolock) ON t.VoucherKey = v.VoucherKey 
	LEFT OUTER JOIN tCompany c (nolock) ON u.CompanyKey = c.CompanyKey 
	LEFT OUTER JOIN tProject p (nolock) ON t.ProjectKey = p.ProjectKey 
	LEFT OUTER JOIN tDepartment d (nolock) ON u.DepartmentKey = d.DepartmentKey 
	LEFT OUTER JOIN tDepartment d_t (nolock) ON t.DepartmentKey = d_t.DepartmentKey 
	LEFT OUTER JOIN tOffice o (nolock) ON u.OfficeKey = o.OfficeKey 
	LEFT OUTER JOIN tOffice oP (nolock) ON p.OfficeKey = oP.OfficeKey 
	LEFT OUTER JOIN tService s (nolock) ON t.ServiceKey = s.ServiceKey 
	LEFT OUTER JOIN tDepartment d_s (nolock) ON s.DepartmentKey = d_s.DepartmentKey 
	LEFT OUTER JOIN tTitle ti (nolock) ON t.TitleKey = ti.TitleKey 
	LEFT OUTER JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey 
	LEFT OUTER JOIN tClientProduct cpd (nolock) on p.ClientProductKey = cpd.ClientProductKey 
	LEFT OUTER JOIN tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey 
	LEFT OUTER JOIN tCompany cClient (nolock) ON p.ClientKey = cClient.CompanyKey 
	LEFT OUTER JOIN tUser sales (NOLOCK) ON cClient.SalesPersonKey = sales.UserKey 
	LEFT OUTER JOIN tTask ta (nolock) ON t.TaskKey = ta.TaskKey 
	LEFT OUTER JOIN tTask td (nolock) ON t.DetailTaskKey = td.TaskKey 
	LEFT OUTER JOIN tTaskAssignmentType tat (nolock) on ta.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey 
	LEFT OUTER JOIN tInvoiceLine il (nolock) on t.InvoiceLineKey = il.InvoiceLineKey 
	LEFT OUTER JOIN tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey 
	LEFT OUTER JOIN tWriteOffReason wor (nolock) on t.WriteOffReasonKey = wor.WriteOffReasonKey 
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey 
	left outer join tUser pc (nolock) on p.BillingContact = pc.UserKey 
	left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey 
	left outer join tUser am (nolock) on p.AccountManager = am.UserKey 
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey 
	left outer join tRetainer r (nolock) on p.RetainerKey = r.RetainerKey 
	left outer join vUserName abk (nolock) on ts.ApprovedByKey = abk.UserKey 
	left outer join vUserName app (nolock) on u.TimeApprover = app.UserKey 
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey 
	LEFT OUTER JOIN tWorkType wt (nolock) ON s.WorkTypeKey = wt.WorkTypeKey 
	LEFT OUTER JOIN tWorkType wti (nolock) ON ti.WorkTypeKey = wti.WorkTypeKey 
	LEFT OUTER JOIN tCompanyType ct (nolock) ON cClient.CompanyTypeKey = ct.CompanyTypeKey 
	LEFT OUTER JOIN tGLCompany glcP (nolock) ON p.GLCompanyKey = glcP.GLCompanyKey 
	LEFT OUTER JOIN tGLCompany glc (nolock) ON u.GLCompanyKey = glc.GLCompanyKey 
	LEFT OUTER JOIN tClass cl (nolock) ON p.ClassKey = cl.ClassKey 
	LEFT OUTER JOIN tClass ucl (nolock) ON u.ClassKey = ucl.ClassKey 
	LEFT OUTER JOIN tCompany pcn (nolock) ON cClient.ParentCompanyKey = pcn.CompanyKey 
	LEFT OUTER JOIN tService bs (nolock) on t.BilledService = bs.ServiceKey 
	LEFT OUTER JOIN tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	LEFT OUTER JOIN tAddress addrw (nolock) on u.AddressKey = addrw.AddressKey 
	LEFT OUTER JOIN tAddress addrh (nolock) on u.HomeAddressKey = addrh.AddressKey 
	LEFT OUTER JOIN tAddress addro (nolock) on u.OtherAddressKey = addro.AddressKey 
	LEFT OUTER JOIN tProjectRollup pr (nolock) ON p.ProjectKey = pr.ProjectKey 
	LEFT OUTER JOIN tAddress clad (nolock) ON cClient.BillingAddressKey = clad.AddressKey 
	left outer join tTask st (nolock) on ta.SummaryTaskKey = st.TaskKey
	LEFT OUTER JOIN (Select UserKey, TaskKey, Sum(Hours) as Hours from tTaskUser (nolock) Group By UserKey, TaskKey) as aa on t.UserKey = aa.UserKey and ISNULL(t.DetailTaskKey, t.TaskKey) = aa.TaskKey 
	LEFT OUTER JOIN (Select TaskKey, Sum(tEstimateTaskLabor.Hours) as Hours from tEstimateTaskLabor (nolock) inner join tEstimate (Nolock) on tEstimateTaskLabor.EstimateKey = tEstimate.EstimateKey where tEstimate.InternalStatus = 4 Group By TaskKey) as bb on ISNULL(t.DetailTaskKey, t.TaskKey) = bb.TaskKey 
	LEFT OUTER JOIN vUserName pcu (nolock) on cClient.PrimaryContact = pcu.UserKey 
	LEFT OUTER JOIN vUserName spr (nolock) on u.SupervisorKey = spr.UserKey
	LEFT OUTER JOIN tSecurityGroup sg (nolock) on u.SecurityGroupKey = sg.SecurityGroupKey 
	LEFT OUTER JOIN tProjectItemRollup pir (nolock) on t.ProjectKey = pir.ProjectKey and t.ServiceKey = pir.EntityKey and pir.Entity = ''tService''
	LEFT OUTER JOIN tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	LEFT OUTER JOIN tReviewDeliverable rd (nolock) on t.DeliverableKey = rd.ReviewDeliverableKey
	LEFT OUTER JOIN tCompany ven (nolock) ON v.VendorKey = ven.CompanyKey 
	LEFT OUTER JOIN tWorkType twt (nolock) on ta.WorkTypeKey = twt.WorkTypeKey
	LEFT OUTER JOIN tTimelineSegment tls (nolock) on td.TimelineSegmentKey = tls.TimelineSegmentKey
	LEFT OUTER JOIN tTimelineSegment tls2 (nolock) on ta.TimelineSegmentKey = tls2.TimelineSegmentKey
	LEFT OUTER JOIN tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey
	LEFT OUTER JOIN tCompany c2 (nolock) ON u.VendorKey = c2.CompanyKey 
	LEFT OUTER JOIN vUserName con (nolock) on cClient.ContactOwnerKey = con.UserKey 
	LEFT OUTER JOIN tLead l (nolock) on p.LeadKey = l.LeadKey
	LEFT OUTER JOIN tLeadOutcome loc (nolock) on l.LeadOutcomeKey = loc.LeadOutcomeKey
	LEFT OUTER JOIN tLeadStage lstage (nolock) on l.LeadStageKey = lstage.LeadStageKey
	LEFT OUTER JOIN tLeadStatus lstatus (nolock) on l.LeadStatusKey = lstatus.LeadStatusKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAICompanyUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAICompanyUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   PROCEDURE [dbo].[spApiAICompanyUpdate]
	@CompanyKey int,
	@CompanyName nvarchar(200),
	@OwnerCompanyKey int,
	@Phone varchar(20) = null,
	@Fax varchar(20) = null,
	@WebSite varchar(100) = null,
	@Active tinyint = NULL,
	@CMFolderKey int = 0,
	@Comments text,
	@UserKey int,
	@DateConverted smalldatetime,
	@TwitterID varchar(50) = NULL,
	@CurrencyID varchar(10) = NULL,
	@ProjectManagerKey int = -1,
	@AccountManagerName varchar(300) = NULL,
	@ContactOwnerName varchar(300) = NULL,
	@SalesPersonName varchar(300) = NULL,
	@PrimaryContactName varchar(300) = NULL,
	@SourceName varchar(200) = NULL,
	@CompanyTypeName varchar(50) = NULL,
	@ExistingCompanyName nvarchar(200) = NULL


AS --Encrypt

/*
|| When      Who Rel        What
|| 06/29/26  GAR 26.08.16   (731183) Created -- AI API version of sptCompanyUpdate with security and error handling
|| 07/08/26  GAR 26.08.16   Added optional name-based resolution for AccountManager, ContactOwner (Company Owner),
||                                   SalesPerson, PrimaryContact, Source, and CompanyType so MCP callers can pass names
||                                   instead of raw keys.
|| 07/08/26  GAR 26.08.16   Removed the raw *Key parameters (SourceKey, CompanyTypeKey, PrimaryContact, ContactOwnerKey,
||                                   AccountManagerKey, SalesPersonKey) now that callers only pass names. They are now
||                                   local variables seeded from the existing row on update (so an update that omits a
||                                   name leaves that assignment unchanged) or 0 on insert.
|| 07/08/26  GAR 26.08.16   Fixed AccountManager/ContactOwner/SalesPerson resolution to scope by tUser.CompanyKey
||                                   (their employer) instead of tUser.OwnerCompanyKey (which scopes external contacts).
||                                   Matches the UI''s lookup.User "staff" search mode -- staff members were not being
||                                   found under the old (wrong) scoping.
|| 07/08/26  GAR 26.08.16   Added @IsNewCompany, returned as isNew alongside companyKey, so callers can tell whether
||                                   the call actually inserted a new row vs. updated one resolved by name -- previously
||                                   callers inferred this from whether they supplied a companyKey, which was wrong
||                                   whenever the company was found by name instead.
|| 07/08/26  GAR 26.08.16   Added @ExistingCompanyName so a company can be renamed in one call: when supplied it is
||                                   used as the lookup key instead of CompanyName, and CompanyName is written as the
||                                   new value. If ExistingCompanyName is supplied but matches no company, a NOT_FOUND
||                                   error is raised (with the other name-resolution errors below) instead of silently
||                                   creating a new company under the new name.
|| 07/08/26  GAR 26.08.16   Fixed the update branch wiping Phone/Fax/WebSite/Comments/TwitterID/CurrencyID to blank
||                                   whenever a partial update call omitted them -- these are now ISNULL(@Param, Column)
||                                   so an update that only touches e.g. primaryContact no longer clobbers the other
||                                   optional fields. (Found via an MCP add_update_company call that only passed
||                                   primaryContact and wiped out a previously-set Phone/Fax/WebSite.)
|| 07/08/26  GAR 26.08.16   Same fix for @Active: it now defaults to NULL (was 1) so a partial update no longer
||                                   silently reactivates an inactive company. New companies still default to active
||                                   when @Active is omitted; on update, ISNULL(@Active, Active) preserves the current
||                                   flag, and the ActiveClient/ActiveVendor cascade only runs when @Active was
||                                   actually supplied and differs from the current value.
|| 07/10/26  GAR 26.08.16   Added spCheckAccess (tCompany) record-level gate on update, alongside the existing
||                                   manual GL company checks -- mirrors spApiAIVoucherDetailUpdate / spApiAICompanyCustomFieldSave.
*/

  -- Set up error table
  select * into #errors from tAPIErrorTemplate where 1 = 2

  -- Validate required fields
  if @CompanyName is null or LTRIM(RTRIM(@CompanyName)) = ''''
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Company Name is required.'', ''companyName'')
  end

  if @OwnerCompanyKey is null or @OwnerCompanyKey = 0
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Owner Company is required.'', ''ownerCompanyKey'')
  end

  declare @ErrorCount int
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  -- If no CompanyKey supplied, try to resolve one by name within the owner company.
  -- ExistingCompanyName (when supplied) is used as the lookup key instead of CompanyName so a
  -- rename can be done in one call: pass the company''s current name in ExistingCompanyName and
  -- its new name in CompanyName. If ExistingCompanyName is supplied but doesn''t match, raise
  -- NOT_FOUND (checked below with the other name-resolution errors) rather than silently
  -- creating a duplicate company under the new name.
  if @CompanyKey = 0
  begin
    if @ExistingCompanyName is not null and LTRIM(RTRIM(@ExistingCompanyName)) <> ''''
    begin
      select @CompanyKey = CompanyKey
      from tCompany (nolock)
      where OwnerCompanyKey = @OwnerCompanyKey
        and CompanyName = @ExistingCompanyName

      if @CompanyKey is null or @CompanyKey = 0
      begin
        select @CompanyKey = 0
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''No company found matching existingCompanyName: '' + @ExistingCompanyName, ''existingCompanyName'')
      end
    end
    else if LTRIM(RTRIM(@CompanyName)) <> ''''
    begin
      select @CompanyKey = CompanyKey
      from tCompany (nolock)
      where OwnerCompanyKey = @OwnerCompanyKey
        and CompanyName = @CompanyName
    end
  end

  -- Local key variables for the fields now driven by name-based resolution.
  -- On update, seed from the existing row so omitting a name leaves that assignment unchanged.
  -- On insert, there is no existing row, so these start at 0 (unassigned).
  declare
    @SourceKey int = 0,
    @CompanyTypeKey int = 0,
    @PrimaryContact int = 0,
    @ContactOwnerKey int = 0,
    @AccountManagerKey int = 0,
    @SalesPersonKey int = 0

  if @CompanyKey > 0
  begin
    select @SourceKey = isnull(SourceKey, 0),
           @CompanyTypeKey = isnull(CompanyTypeKey, 0),
           @PrimaryContact = isnull(PrimaryContact, 0),
           @ContactOwnerKey = isnull(ContactOwnerKey, 0),
           @AccountManagerKey = isnull(AccountManagerKey, 0),
           @SalesPersonKey = isnull(SalesPersonKey, 0)
    from tCompany (nolock)
    where CompanyKey = @CompanyKey
  end

  -- Resolve optional name-based lookups to keys (name/email/UserID for people, name for source/type).
  -- Internal staff (AccountManager/ContactOwner/SalesPerson) are scoped by tUser.CompanyKey (their employer),
  -- NOT tUser.OwnerCompanyKey (which scopes external contacts -- see PrimaryContact below). This mirrors the
  -- UI''s lookup.User "staff" search mode (WJFramework/commonFunctions/Lookup.vb) which filters on CompanyKey.
  if @AccountManagerName is not null and LTRIM(RTRIM(@AccountManagerName)) <> ''''
  begin
    select @AccountManagerKey = UserKey
    from tUser (nolock)
    where CompanyKey = @OwnerCompanyKey
      and Active = 1
      and (   UserID like ''%'' + @AccountManagerName + ''%''
           or Email like ''%'' + @AccountManagerName + ''%''
           or FirstName + '' '' + LastName like ''%'' + @AccountManagerName + ''%'' )

    if @AccountManagerKey is null or @AccountManagerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for accountManager: '' + @AccountManagerName, ''accountManager'')
  end

  if @ContactOwnerName is not null and LTRIM(RTRIM(@ContactOwnerName)) <> ''''
  begin
    select @ContactOwnerKey = UserKey
    from tUser (nolock)
    where CompanyKey = @OwnerCompanyKey
      and Active = 1
      and (   UserID like ''%'' + @ContactOwnerName + ''%''
           or Email like ''%'' + @ContactOwnerName + ''%''
           or FirstName + '' '' + LastName like ''%'' + @ContactOwnerName + ''%'' )

    if @ContactOwnerKey is null or @ContactOwnerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for companyOwner: '' + @ContactOwnerName, ''companyOwner'')
  end

  if @SalesPersonName is not null and LTRIM(RTRIM(@SalesPersonName)) <> ''''
  begin
    select @SalesPersonKey = UserKey
    from tUser (nolock)
    where CompanyKey = @OwnerCompanyKey
      and Active = 1
      and (   UserID like ''%'' + @SalesPersonName + ''%''
           or Email like ''%'' + @SalesPersonName + ''%''
           or FirstName + '' '' + LastName like ''%'' + @SalesPersonName + ''%'' )

    if @SalesPersonKey is null or @SalesPersonKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for salesPerson: '' + @SalesPersonName, ''salesPerson'')
  end

  if @PrimaryContactName is not null and LTRIM(RTRIM(@PrimaryContactName)) <> ''''
  begin
    select @PrimaryContact = UserKey
    from tUser (nolock)
    where OwnerCompanyKey = @OwnerCompanyKey
      and Active = 1
      and (@CompanyKey = 0 or CompanyKey = @CompanyKey)
      and (   UserID like ''%'' + @PrimaryContactName + ''%''
           or Email like ''%'' + @PrimaryContactName + ''%''
           or FirstName + '' '' + LastName like ''%'' + @PrimaryContactName + ''%'' )

    if @PrimaryContact is null or @PrimaryContact = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Contact not found for primaryContact: '' + @PrimaryContactName, ''primaryContact'')
  end

  if @SourceName is not null and LTRIM(RTRIM(@SourceName)) <> ''''
  begin
    select @SourceKey = SourceKey
    from tSource (nolock)
    where CompanyKey = @OwnerCompanyKey
      and Active = 1
      and SourceName like ''%'' + @SourceName + ''%''

    if @SourceKey is null or @SourceKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Source not found: '' + @SourceName, ''companySource'')
  end

  if @CompanyTypeName is not null and LTRIM(RTRIM(@CompanyTypeName)) <> ''''
  begin
    select @CompanyTypeKey = CompanyTypeKey
    from tCompanyType (nolock)
    where CompanyKey = @OwnerCompanyKey
      and Active = 1
      and CompanyTypeName like ''%'' + @CompanyTypeName + ''%''

    if @CompanyTypeKey is null or @CompanyTypeKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Company Type not found: '' + @CompanyTypeName, ''companyType'')
  end

  -- Re-check for NOT_FOUND errors raised during name resolution above
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Security setup
  declare
    @IsAdministrator tinyint,
    @SecurityGroupKey int,
    @RestrictToGLCompany int,
    @GLCompanyKey int,
    @CompanyGLCompanyKey int

  select @IsAdministrator = Administrator,
         @SecurityGroupKey = SecurityGroupKey,
         @GLCompanyKey = GLCompanyKey
  from tUser (nolock)
  where UserKey = @UserKey

  select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
  from tPreference (nolock)
  where CompanyKey = @OwnerCompanyKey

  -- For updates, verify the user has GL company access to this company
  if @CompanyKey > 0 and @IsAdministrator <> 1 and @RestrictToGLCompany = 1
  begin
    select @CompanyGLCompanyKey = GLCompanyKey
    from tCompany (nolock)
    where CompanyKey = @CompanyKey

    if not exists (
      select 1 from tUserGLCompanyAccess (nolock)
      where UserKey = @UserKey
        and GLCompanyKey = @CompanyGLCompanyKey
    )
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You do not have access to this company based on your GL company restrictions.'', ''companyKey'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -103
    end
  end

  -- For inserts, verify the user has GL company access to the owner company
  if @CompanyKey = 0 and @IsAdministrator <> 1 and @RestrictToGLCompany = 1
  begin
    if ISNULL(@GLCompanyKey, 0) > 0
    begin
      if not exists (
        select 1 from tGLCompanyAccess (nolock)
        where Entity = ''tCompany''
          and GLCompanyKey = @GLCompanyKey
          and CompanyKey = @OwnerCompanyKey
      )
      and not exists (
        select 1 from tUserGLCompanyAccess (nolock)
        where UserKey = @UserKey
          and GLCompanyKey = @GLCompanyKey
      )
      begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''You do not have access to create companies for this GL company.'', ''ownerCompanyKey'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -103
      end
    end
  end

  -- Record-level access gate via spCheckAccess (tCompany) -- catches folder security and any
  -- other record-level restrictions beyond the manual GL company checks above. Only applies to
  -- an existing company (update); a brand-new company has no record to gate against yet.
  if @CompanyKey > 0
  begin
    declare @AccessOK int
    exec @AccessOK = spCheckAccess @UserKey, @OwnerCompanyKey, ''tCompany'', @CompanyKey
    if @AccessOK <> 1
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You do not have access to modify this company.'', ''companyKey'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -103
    end
  end

  -- Main logic
  begin try

    if @CurrencyID = ''''
      select @CurrencyID = null

    declare
      @GetRateFrom int,
      @TimeRateSheetKey int,
      @HourlyRate money,
      @GetMarkupFrom int,
      @ItemRateSheetKey int,
      @ItemMarkup decimal(24,4),
      @IOCommission decimal(24,4),
      @BCCommission decimal(24,4),
      @CurrentProjectManager int,
      @CurrentCompanyActiveFlag int,
      @IsNewCompany bit = 0

    if @CompanyKey = 0
    begin
      select @IsNewCompany = 1

      -- New companies default to active when @Active isn''t supplied
      if @Active is null
        select @Active = 1

      select @GetRateFrom = isnull(GetRateFrom, 1)
            ,@TimeRateSheetKey = isnull(TimeRateSheetKey, 0)
            ,@HourlyRate = isnull(HourlyRate, 0)
            ,@GetMarkupFrom = isnull(GetMarkupFrom, 1)
            ,@ItemRateSheetKey = isnull(ItemRateSheetKey, 0)
            ,@ItemMarkup = isnull(ItemMarkup, 0)
            ,@IOCommission = isnull(IOCommission, 0)
            ,@BCCommission = isnull(BCCommission, 0)
      from tPreference (nolock) where CompanyKey = @OwnerCompanyKey

      INSERT tCompany
      (
        CompanyName,
        SourceKey,
        CompanyTypeKey,
        PrimaryContact,
        OwnerCompanyKey,
        Phone,
        Fax,
        WebSite,
        Active,
        CMFolderKey,
        ContactOwnerKey,
        AccountManagerKey,
        SalesPersonKey,
        Comments,
        DateAdded,
        DateUpdated,
        CreatedBy,
        ModifiedBy,
        DateConverted,
        GetRateFrom,
        TimeRateSheetKey,
        HourlyRate,
        GetMarkupFrom,
        ItemRateSheetKey,
        ItemMarkup,
        IOCommission,
        BCCommission,
        TwitterID,
        CurrencyID,
        ProjectManagerKey
      )
      VALUES
      (
        @CompanyName,
        @SourceKey,
        @CompanyTypeKey,
        @PrimaryContact,
        @OwnerCompanyKey,
        @Phone,
        @Fax,
        @WebSite,
        @Active,
        @CMFolderKey,
        @ContactOwnerKey,
        @AccountManagerKey,
        @SalesPersonKey,
        @Comments,
        GETUTCDATE(),
        GETUTCDATE(),
        @UserKey,
        @UserKey,
        @DateConverted,
        @GetRateFrom,
        @TimeRateSheetKey,
        @HourlyRate,
        @GetMarkupFrom,
        @ItemRateSheetKey,
        @ItemMarkup,
        @IOCommission,
        @BCCommission,
        @TwitterID,
        @CurrencyID,
        @ProjectManagerKey
      )

      select @CompanyKey = @@IDENTITY

      -- Set the WebDav safe folder names (suppress result set to keep our DataSet layout clean)
      EXEC sptCompanyWebDavSafeFolders @CompanyKey, @SelectValues = 0

      -- If GL company restriction is on, grant the inserting user''s GL company access to the new record
      if @RestrictToGLCompany = 1
      begin
        if isnull(@GLCompanyKey, 0) > 0
        begin
          insert tGLCompanyAccess (Entity, EntityKey, GLCompanyKey, CompanyKey)
          values (''tCompany'', @CompanyKey, @GLCompanyKey, @OwnerCompanyKey)
        end
      end
    end
    else
    begin
      select @CurrentProjectManager = ProjectManagerKey,
             @CurrentCompanyActiveFlag = Active
      from tCompany (nolock)
      where CompanyKey = @CompanyKey

      if @ProjectManagerKey = -1
        select @ProjectManagerKey = @CurrentProjectManager

      -- If the company is being made inactive, cascade to ActiveClient and ActiveVendor.
      -- @Active is null when the caller didn''t pass it -- leave the active flag (and this cascade) alone.
      if @Active is not null and @Active <> @CurrentCompanyActiveFlag
      begin
        if @Active = 0
        begin
          UPDATE tCompany
          SET ActiveClient = 0,
              ActiveVendor = 0
          WHERE CompanyKey = @CompanyKey
        end
      end

      UPDATE tCompany
      SET CompanyName = @CompanyName,
          SourceKey = @SourceKey,
          CompanyTypeKey = @CompanyTypeKey,
          PrimaryContact = @PrimaryContact,
          Phone = ISNULL(@Phone, Phone),
          Fax = ISNULL(@Fax, Fax),
          WebSite = ISNULL(@WebSite, WebSite),
          Active = ISNULL(@Active, Active),
          CMFolderKey = @CMFolderKey,
          ContactOwnerKey = @ContactOwnerKey,
          AccountManagerKey = @AccountManagerKey,
          SalesPersonKey = @SalesPersonKey,
          Comments = ISNULL(@Comments, Comments),
          DateUpdated = GETUTCDATE(),
          ModifiedBy = @UserKey,
          DateConverted = @DateConverted,
          TwitterID = ISNULL(@TwitterID, TwitterID),
          CurrencyID = ISNULL(@CurrencyID, CurrencyID),
          ProjectManagerKey = @ProjectManagerKey
      WHERE CompanyKey = @CompanyKey
    end

    Update tUser Set UserCompanyName = @CompanyName Where CompanyKey = @CompanyKey

    -- Return any warnings followed by the result
    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    select @CompanyKey as companyKey, @IsNewCompany as isNew

    drop table #errors

    RETURN @CompanyKey

  end try
  begin catch

    declare @ErrMsg nvarchar(4000) = ERROR_MESSAGE()
    declare @ErrSeverity int = ERROR_SEVERITY()

    if object_id(''tempdb..#errors'') is not null
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', @ErrMsg, ''general'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
    end

    RAISERROR(@ErrMsg, @ErrSeverity, 1)
    return -100

  end catch

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityIncrementSequence]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityIncrementSequence]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityIncrementSequence]
	@ActivityKey int
AS --Encrypt

/*
|| When      Who Rel      What
|| 6/18/09   CRG 10.5.0.0 Created to increment the sequence in tActivity for CalDAV.
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time 

*/

	DECLARE	@Sequence int
	
	SELECT	@Sequence = Sequence
	FROM	tActivity (NOLOCK)
	WHERE	ActivityKey = @ActivityKey
	
	SELECT	@Sequence = ISNULL(@Sequence, 0) + 1
	
	UPDATE	tActivity
	SET		Sequence = @Sequence
	WHERE	ActivityKey = @ActivityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_TimeDetail2]'
GO
IF OBJECT_ID(N'[dbo].[vReport_TimeDetail2]', 'V') IS NOT NULL
EXEC sp_executesql N'




ALTER VIEW [dbo].[vReport_TimeDetail2] 
AS 
 
/* 
  || When     Who Rel      What 
  || 10/13/06 WES 8.3567   Added Project Billing Status 
  || 12/28/06 GHL 8.4      Added Campaign ID 
  || 11/06/07 CRG 8.5      (10954) Added DateBilled, Billing Item ID, and Billing Item Name 
  || 11/06/07 CRG 8.5      (13158) Added Client Company Type 
  || 5/23/08  CRG 8.5.1.2  (25454) Added GLCompany 
  || 7/20/08  GWG 10.0.0.6 (30741) Added GL Class from the project 
  || 8/14/08  GHL 10.0.0.6 (32476) Added task description 
  || 10/20/08 GWG 10.0.1.1 Fixed the project full name to use a - 
  || 3/02/09  RLB 10.0.2.0 (47918) Added Budget information 
  || 04/06/09 MAS 10.0.2.2 (50443) Added Write-off Hours, Write-off Total, Marked Billed Hours and Marked Billed Total fields 
  || 07/22/09 RLB 10.5.0.4 Added Project custom fields to this data set 
  || 09/10/09 GHL 10.5     Added Transferred Out 
  || 01/5/10  GWG 10.5.1.6 Added client''s project number 
  || 01/06/10 RLB 10.5.1.6 Added Task Type 
  || 03/10/10 RLB 10.5.2.0 Formatting Date Worked Month  
  || 04/29/10 RLB 10.5.2.2 (79487) removed time from Approved Date and Submitted Date 
  || 04/30/10 RLB 10.5.2.2 (63218)Added Parent Company Name 
  || 07/28/10 RLB 10.5.3.3 (83803)Added Non Billable Project to the Data set 
  || 08/30/10 RLB 10.5.3.4 (88843)Added Billed Service Code 
  || 01/16/11 GWG 10.5.4.0 Added the rounding in for actual billable amount 
  || 04/07/11 RLB 10.5.4.3 (108045) Removed Project Short Name 
  || 06/29/11 RLB 10.5.4.5 (115335) changed tCompany to a left outer join because contacts could not have a company 
  || 07/27/11 RLB 10.5.4.6 (114500) Added Line Number which is the tasks order in the projet schedule screen 
  || 07/27/11 RLB 10.5.4.6 (111324) Added Campaign Segment 
  || 10/8/11  GWG 10.5.4.9 Added a link to the task through the detail task key 
  || 12/09/11 RLB 10.5.5.1 (121131) Added Verified 
  || 02/29/12 MFT 10.5.5.3 Added Date Worked Week 
  || 03/16/12 GHL 10.5.5.4 (137417) Add Date Time fields 
  || 04/24/12 GHL 10.5.5.5 Added GLCompanyKey in order to map/restrict 
  ||                       p.GLCompanySource = 0 then p.GLCompanyKey 
  ||                       p.GLCompanySource = 1 then u.GLCompanyKey 
  ||                       p.GLCompanySource is null i.e. no project then u.GLCompanyKey 
  || 07/06/12 GHL 10.5.5.7 (148085) Getting now the parent company from the client on the project 
  ||                       instead of from the company on the user 
  || 09/25/12 GWG 10.5.6.0 Added Address fields 
  || 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey 
  || 01/15/13 GWG 10.5.6.4 Added some additional fields for reporting 
  || 02/13/13 WDF 10.5.6.5 (160177) Added Timesheet From/To dates 
  || 03/01/13 WDF 10.5.6.5 (169504) Added employees Default GLCompany 
  || 05/01/13 GWG 10.5.6.7 Added users class 
  || 05/22/13 MFT 10.5.6.8 (174957) Added ta.Comments 
  || 08/08/13 GWG 10.5.7.0 Added Allocated Hours 
  || 11/15/13 RLB 10.5.7.4 (191407) Added Yes OR No for tax 1 and 2  on tasks set on the time entry 
  || 06/17/14 WDF 10.5.8.1 (217923) Added Vendor Invoice Number 
  || 10/16/14 WDF 10.5.8.5 (Abelson Taylor) Added Billing Title 
  || 12/16/14 RLB 10.5.8.7 (239571) Added Client Billing State and Company CustomFields from the client on the project 
  || 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID 
  || 03/10/15 GHL 10.5.9.0 (Abelson Taylor) Added Department at the Time  
  || 03/20/15 WDF 10.5.9.0 (Abelson Taylor) Added WriteOffDate 
  || 06/02/15 MCM 10.5.9.3 (256400) Added Contractor field 
  || 10/09/15 KMC 10.5.9.7 (273426) Removed the CAST from the ts.DateCreated, ts.DateSubmitted, and ts.DateApproved and are converting to UTC adjusted 
  ||                        dates (no time) in WMJ 
  || 01/25/16 WDF 10.6.0.0 (286743) Formatting Date Worked Week  
  || 03/18/16 WDF 10.6.0.2 (293875) Added [On Hold] 
  || 04/12/16 MFT 10.6.0.3 (296036) Added WriteOffComment 
  || 06/15/16 GWG 10.6.0.5 Added in Paid Status 
  || 08/09/16 WDF 10.6.0.7 (309294) Added [Salesperson Name] 
  || 08/11/16 KMC 10.6.0.7 (307284) Added Active status for tUser as [Active User] 
  || 09/20/16 QMD 10.6.0.8 (309378) Added LastModified 
  || 10/05/16 WDF 10.6.0.9 (316052) Set [Active User] as YES/NO 
  || 11/21/16 KMC 10.6.1.0 (321574) Added user email address 
  || 12/13/16 MCM 10.6.1.1 (323908) Updating the User Full Name logic to match the vUserName 
  || 02/17/17 QMD 10.6.1.3 Added TimeKey to the select 
  || 03/20/17 MCM 10.6.1.4 (337685) Adding User Name - already had User Full Name 
  || 09/25/17 GHL 10.6.2.0 (295216) Added timesheet tardiness field 
  || 09/28/17 GWG 10.6.2.0 Added Project Close Date 
  || 10/10/17 GWG 10.6.2.0 Fix spelling error 
  || 12/4/17  GWG 10.6.2.2 Added Predecessors completed 
  || 01/30/17 GWG 18.2     Added budget hours and dollars by project and service.
  || 04/03/18 WDF 18.4     Added [User Title]
  || 04/27/18 RLS 18.5.0   (398138) Added CurrencyID
  || 05/15/18 GWG 18.5.0   added campaign active
  || 06/28/18 AMP 18.7.0   (407643) Modified Column Name for Service Description lookup
  || 07/19/18 RLS 18.8.0   (410986) Added [Date of Hire]
  || 07/24/18 GWG 18.8.0   Added billable/nonbillable label for graphing
  || 08/28/18 AMP 18.9.0   (413912) Added standard column ''Billed on Invoice Amount'' 
  || 09/24/18 GWG 18.9.1   Protect against nulls in amount billed
  || 12/18/18 GWG 19.1	   Added month name to formatted month
  || 03/08/19 AMP 19.0.4.0 (433620) Added Summary Task Name 
  || 03/25/19 GWG 10.0.4.0 (451555) Added project total hours, labor net and outside expenses net
  || 03/25/19 QMD 19.0.4.0 (452162) Added TaskKey
  || 05/29/19 RLS 19.0.5.0 (459194) Added Project Percent Complete
  || 06/06/19 RLB 19.0.7.0 (446229) Adding Project Manager
  || 07/25/19 QMD 19.0.8.0 (470423) Adding UserKey as EmployeeKey
  || 09/09/19 AMP 19.1.0.0 (477617) Added field for Service Hourly Cost
  || 10/21/19 RLB 19.1.1.0 (457226) Added SupervisorName
  || 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
  || 03/18/20 RLB 20.0.4.0 (507087) removed the Convert on start time and end time
  || 03/18/20 RLS 20.0.4.0 (505211) Added [Billing Group Code] and [Billing Group Description]
  || 07/23/20 RLS 20.0.8.0 (520337) Added [Deliverable Name] and join to tReviewDeliverable
  || 07/29/20 RLB 20.0.8.0 (523363) Fixed how Project primary contact field
  || 08/20/20 RLB 20.0.9.0 (526270) change outer join to tDeliverable can only use DeliverableKey on tTime
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 09/08/20 GAR 20.1.0.0 (527210) Added Vendor Name (from the vendor invoice number)
  || 02/24/20 RLB 21.03.14 (543274) Added [Campaign Budget Hours] and [Campaign Segment Budget Hours]
  || 03/30/21 GHL 21.04.18 (552776) Added custom field key 4 to test 4th direction on CF
  || 05/06/21 RLS 21.0.6.0 (555522) Added [Time paused]
  || 06/29/21 RLS 21.0.7.0 (563027) Wrapped u.Title in ISNULL()
  || 12/15/21 AMP 22.02.20 (579957) Added Timeline Segment
  || 02/22/22 RLB 22.03.20 (587756) changed planned project name, number and full name to include the planning project name not just linked through planningprojectkey
  || 03/11/22 GWG 22.03.20 (583542) Adding in the allocated hours for the week. Needed by fusion for a particular report
  || 04/28/22 RLS 22.05.15 (595589) Added PlanStart,PlanComplete,ActStart,ActComplete,BaseStart,BaseComplete
  || 05/06/22 RLB 22.06.19 (593471) made date created and time created match time detail
  || 04/28/22 RLS 22.05.15 (598368) Replaced ISNULL(tu.ActStart, ta.ActStart) and ISNULL(tu.ActComplete, ta.ActComplete) with ta.ActStart and ta.ActComplete and removed the outer join to tTaskUser
  || 07/21/22 GHL 22.08.00 (604153) Added Overtime field
  || 09/01/22 AMP 22.09.18 (610375) Modified retrieving the Vendor Name. If there is no vendor invoice tied to the time entry get the Vendor Name from the user record
  || 01/04/23 RLB 23.02.19 (625612) Added Budget Hours by Task. Any task labor hours on approved estimate
  || 03/13/23 RLB 23.04.16 (629165) Adding Office Color, department and service
  || 08/11/23 RLB 23.09.17 (648008) added project type color and timeline segment color
  || 03/26/24 RLB 24.05.19 (667979) added HourlyCost2
  || 07/23/24 RLS 24.08.18 (675330) Added [Company Owner]
  || 10/25/24 QMD 24.11.17 (685924) Added DateUnapproved
  || 03/20/25 RLS 25.04.20 (695482) Added [Billable Rate]
  || 04/16/25 RLS 25.05.18 (694661) Added [Opportunity ID],[Opportunity Name],[Opportunity Outcome],[Opportunity Next Steps],[Opportunity Stage] and [Opportunity Status] 
  || 02/19/26 RLB 26.03.15 (722386) Added [Time Sheet Required]
  || 07/10/26 GAR 26.08.16 (732133) Added Source for use with the MCP time entries
*/ 
 
SELECT  
    ts.CompanyKey,  
	case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey, 
	ts.CompanyKey as OwnerCompanyKey, 
	ts.TimeSheetKey, 
	u.CustomFieldKey, 
    p.CustomFieldKey as CustomFieldKey2, 
    cClient.CustomFieldKey AS CustomFieldKey3, 
	rd.CustomFieldKey as CustomFieldKey4,
	t.TimeKey, 
	cClient.CompanyName AS [Client Name],  
	cClient.CustomerID AS [Client ID], 
	clad.State AS [Client Billing State], 
	pcn.CompanyName AS [Parent Company], 
	p.ProjectName AS [Project Name],  
	p.ProjectNumber AS [Project Number],  
	p.ClientProjectNumber AS [Client Project Number], 
	p.CurrencyID as [Currency],
	Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project],
	LTRIM(RTRIM(ISNULL(pc.FirstName,'''') + '' '' + ISNULL(pc.LastName,''''))) AS [Project Primary Contact],  
	p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name], 
	pt.ProjectTypeName as [Project Type], 
	pt.ProjectTypeColor as [Project Type Color],
	pt.Description as [Project Type Description], 
	cp.CampaignID as [Campaign ID], 
	cp.CampaignName as [Campaign Name], 
	cs.SegmentName as [Campaign Segment], 
	LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager],
	LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS  [Project Manager], 
	u.SystemID AS [User System ID],  
	ISNULL(u.Title,'''') AS [User Title],  
	u.FirstName AS [User First Name],  
	u.LastName AS [User Last Name],  
	LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,''''))) AS [User Name], 
	case  
		when u.MiddleName is null then LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,'''')))  
		else LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + SUBSTRING(u.MiddleName, 1, 1) + '' '' + ISNULL(u.LastName,'''')))  
	end as [User Full Name], 
	glc.GLCompanyID AS [Default GLCompany ID], 
	glc.GLCompanyID + '' - '' + glc.GLCompanyName AS [Default GLCompany Full Name], 
	d.DepartmentName AS [User Department], 
	d.DepartmentColor as [User Department Color],
	case when t.DepartmentKey is not null then d_t.DepartmentName  
		else case when isnull(pref.DefaultDepartmentFromUser, 0) = 1 then d.DepartmentName else d_s.DepartmentName end  
	end as [Department at the Time], 
	case when t.DepartmentKey is not null then d_t.DepartmentColor  
		else case when isnull(pref.DefaultDepartmentFromUser, 0) = 1 then d.DepartmentColor else d_s.DepartmentColor end  
	end as [Department Color at the Time],	
	o.OfficeName AS [User Office Name], 
	o.OfficeColor as [User Office Color],
	oP.OfficeName AS [Project Office Name], 
	oP.OfficeColor as [Project Office Color],
	c.CompanyName AS [User Company Name], 
	ta.TaskID AS [Task ID],  
	ta.TaskID + '' - '' + ta.TaskName AS [Task Full Name],  
	ta.TaskName as [Task Name], 
	ta.Comments AS [Task Status Comments], 
	td.TaskID as [Assignment ID], 
	td.TaskName as [Assignment Subject], 
	td.TaskID + '' - '' + td.TaskName AS [Assignment Full Name],  
	tat.TaskAssignmentType as [Task Type], 
	ta.Description AS [Task Description], 
	ta.ProjectOrder AS [Line Number], 
	Case ISNULL(ta.PredecessorsComplete, 0) When 1 then ''YES'' else ''NO'' end as [Predecessors Completed], 
	Case ISNULL(ta.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable], 
	Case ISNULL(ta.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable 2], 
	s.ServiceCode AS [Service Code],
	s.ServiceColor as [Service Color],
	bs.ServiceCode AS [Billed Service Code], 
	bs.ServiceColor as [Billed Service Color],
	t.RateLevel AS [Service Rate Level], 
	ta.DueBy as [Task Due By], 
	ta.PercComp as [Task Percent Complete], 
	p.PercComp as [Project Percent Complete], 
	ISNULL(t.DateAdded, ts.DateCreated) as [Date Created],   --Adjusted for UTC in WMJ and shown just as date without time 
	ts.DateSubmitted as [Date Submitted For Approval],   --Adjusted for UTC in WMJ and shown just as date without time 
	ts.DateApproved as [Date Approved],   --Adjusted for UTC in WMJ and shown just as date without time 
	ISNULL(t.DateAdded, ts.DateCreated) as [Date And Time Created],  
	ts.DateSubmitted as [Date And Time Submitted], 
	ts.DateApproved as [Date And Time Approved], 
	ts.StartDate as [Time Sheet From], 
	ts.EndDate as [Time Sheet To], 
	 
	abk.UserName AS [Approved By], 
	app.UserName AS [Current Approver], 
	spr.UserName AS [Supervisor Name], 
	Case ts.Status 
		When 1 then ''Not Sent For Approval'' 
		When 2 then ''Sent For Approval'' 
		When 3 then ''Rejected'' 
		When 4 then ''Approved'' end as [Approval Status], 
	wor.ReasonName AS [Write Off Reason], 
	t.WriteOffComment AS [Write Off Comment], 
	Case t.RateLevel  
		When 1 then ISNULL(s.Description1, s.Description) 
		When 2 then ISNULL(s.Description2, s.Description) 
		When 3 then ISNULL(s.Description3, s.Description) 
		When 4 then ISNULL(s.Description4, s.Description) 
		When 5 then ISNULL(s.Description5, s.Description) 
		Else s.Description 
	END as [Service Description for Rate], 
	s.Description as [Service Description],
	ti.TitleName as [Billing Title Name], 
	ti.TitleID as [Billing Title ID], 
	cd.DivisionName as [Client Division], 
	cd.DivisionID as [Client Division ID], 
	cpd.ProductName as [Client Product], 
	cpd.ProductID as [Client Product ID], 
	t.WorkDate AS [Date Worked],  
	DATEPART(Year, t.WorkDate) AS [Date Worked Year], 
	CAST(DATEPART(Year, t.WorkDate) AS VARCHAR(4)) AS [Date Worked Year Formatted], 
	DATENAME(Month, t.WorkDate) AS [Date Worked Month], 
	RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, t.WorkDate) AS [Date Worked Month Formatted], 
	RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) AS [Date Worked Month Number], 
	t.ActualHours AS [Actual Hours Worked],  
	CASE WHEN p.NonBillable = 0 AND t.ActualRate > 0 THEN t.ActualHours 
		ELSE 0 END AS [Actual Billable Hours], 
	CASE WHEN p.NonBillable = 1 OR t.ProjectKey IS NULL OR t.ActualRate = 0  
		THEN t.ActualHours ELSE 0 END AS [Actual Non Billable Hours], 
	CASE WHEN (p.NonBillable = 0 OR p.NonBillable IS NULL) AND t.ActualRate > 0 THEN ROUND(t.ActualHours * t.ActualRate, 2) ELSE 0 END AS [Actual Billable Amount],  
	CASE WHEN p.NonBillable = 1 OR t.ProjectKey IS NULL  
		THEN ROUND(t.ActualHours * t.ActualRate, 2) ELSE 0 END AS [Actual Non Billable Amount], 
	t.ActualRate AS [Actual Billing Rate],  
	t.CostRate AS [Actual Cost Rate], 
	ROUND(t.CostRate * t.ActualHours, 2) AS [Actual Total Cost], 
	ROUND((t.ActualRate - t.CostRate) * t.ActualHours, 2) AS [Actual Net Profit], 
	ISNULL(t.BilledHours, 0) AS [Billed Hours],  
	t.BilledRate AS [Billed Rate],  
	ROUND(t.BilledHours * t.BilledRate, 2) AS [Billed Total Amount], 
	ROUND((t.BilledRate - t.CostRate) * t.BilledHours, 2) AS [Billed Net Profit], 
	t.Comments, 
	Case t.OnHold When 1 then ''YES'' else ''NO'' end as [On Hold], 
	ps.ProjectStatus as [Project Status], 
	CASE p.NonBillable WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Non Billable Project], 
	CASE p.Active WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Active Project], 
	CASE t.Downloaded WHEN 1 THEN ''YES'' ELSE ''NO'' END as Downloaded, 
	v.InvoiceNumber as [Vendor Invoice Number], 
	Case When t.VoucherKey = 0 then ''Marked As Paid'' When t.VoucherKey > 0 then ''Paid'' else ''Not Paid'' end as [Paid Status], 
	i.InvoiceNumber as [Invoice Number], 
	Case When t.InvoiceLineKey IS NULL then 
		Case t.WriteOff When 1 then ''Write Off'' else ''Unbilled'' end 
		else ''Billed'' end as [Billing Status], 
 
	Case When t.InvoiceLineKey = 0 then 
		t.ActualHours else 0 end as [Marked Billed Hours], 
 
	Case When t.InvoiceLineKey = 0 then 
		ROUND(t.ActualRate * t.ActualHours, 2) else 0 end as [Marked Billed Total], 
 
	Case When t.WriteOff = 1 then 
		t.ActualHours else 0 end as [Write off Hours], 
 
	Case When t.WriteOff = 1 then 
		ROUND(t.ActualRate * t.ActualHours, 2) else 0	end as [Write off Total], 
 
	Case t.WriteOff 
		When 1 then t.DateBilled 
		else NULL 
	end as [Write Off Date], 
 
	Case When t.WIPPostingInKey = 0 then ''NO'' else ''YES'' end as [Posted Into WIP], 
	Case When t.WIPPostingOutKey = 0 then ''NO'' else ''YES'' end as [Posted Out Of WIP], 
	Case When t.Verified = 0 then ''NO'' else ''YES'' end as [Verified], 
 
	t.StartTime as [Start Time], 
	t.EndTime as [End Time], 
	t.StartTime as [Start Date Time], 
	t.EndTime as [End Date Time], 
	Case When t.InvoiceLineKey is null then 0 else ROUND(t.ActualRate * t.ActualHours, 2) - ISNULL(ROUND(t.BilledHours * t.BilledRate, 2), 0) end AS [Billed Difference], 
	 
     -- Budgeted data 
	ta.EstHours as [Original Budget Hours], -- [Estimate Hours] 
	ta.BudgetLabor as [Original Budget Labor Net], -- [Estimate Labor Net] 
	ta.EstLabor as [Original Budget Labor Gross], -- [Estimate Labor] 
	ta.BudgetExpenses as [Original Budget Expense Net], --  [Estimate Expense Net] 
    ta.EstExpenses as [Original Budget Expense Gross], -- [Estimate Expense Gross] 
	ta.ApprovedCOHours as [CO Budget Hours], -- [Approved CO Hours] 
	ta.ApprovedCOBudgetLabor as [CO Budget Labor Net], -- [Approved CO Labor Net] 
	ta.ApprovedCOLabor as [CO Budget Labor Gross], -- [Approved CO Labor] 
	ta.ApprovedCOBudgetExp as [CO Budget Expense Net], -- [Approved CO Expense Net] 
	ta.ApprovedCOExpense as [CO Budget Expense Gross], -- [Approved CO Expense Gross] 
	ta.EstHours + ta.ApprovedCOHours as [Current Budget Hours], -- [Estimate Total Hours] 
	ta.EstLabor + ta.ApprovedCOLabor as [Current Budget Labor Gross], --[Estimate Total Labor] 
	ta.EstExpenses + ta.ApprovedCOExpense as [Current Budget Expense Gross], --[Estimate Total Gross Expense] 
	ta.EstLabor + ta.ApprovedCOLabor + ta.EstExpenses + ta.ApprovedCOExpense as [Current Total Budget wo Taxes], -- [Estimate Total] 
    ta.EstLabor + ta.ApprovedCOLabor + ta.EstExpenses + ta.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Current Total Budget], --[Total with Tax] 
	ta.EstLabor + ta.ApprovedCOLabor + ta.EstExpenses + ta.ApprovedCOExpense - ta.BudgetExpenses - ta.BudgetLabor - ta.ApprovedCOBudgetLabor - ta.ApprovedCOBudgetExp  as [Estimate Profit], -- No change, not in report 
		 
	r.Title as [Retainer Name], 
	pbs.ProjectBillingStatus as [Project Billing Status], 
	t.DateBilled as [Date Billed], 
	wt.WorkTypeID as [Billing Item ID], 
	wt.WorkTypeName as [Billing Item Name], 
	wti.WorkTypeID as [Billing Title Item ID], 
	wti.WorkTypeName as [Billing Title Item Name], 
	ct.CompanyTypeName as [Client Company Type], 
	case when p.GLCompanySource = 0 then glcP.GLCompanyID else glc.GLCompanyID end as [Company ID], 
	case when p.GLCompanySource = 0 then glcP.GLCompanyName else glc.GLCompanyName end as [Company Name], 
	cl.ClassID as [Class ID], 
	cl.ClassName as [Class Name], 
	ucl.ClassID as [User Class ID], 
	ucl.ClassName as [User Class Name], 
	Case When t.TransferToKey IS NULL Then ''NO'' else ''YES'' end as [Transferred Out], 
	Cast(CONVERT(varchar(2), DATEPART(WEEK, t.WorkDate), 0) AS INT) AS [Date Worked Week],
	RIGHT(''0'' + CAST(DATEPART(WEEK, t.WorkDate) AS VARCHAR(2)), 2) AS [Date Worked Week Formatted], 
	addrw.Address1 as [Work Address 1], 
	addrw.Address2 as [Work Address 2], 
	addrw.Address3 as [Work Address 3], 
	addrw.City as [Work Address City], 
	addrw.State as [Work Address State], 
	addrw.PostalCode as [Work Address Postal Code], 
	addrw.Country as [Work Address Country], 
	 
	addrh.Address1 as [Home Address 1], 
	addrh.Address2 as [Home Address 2], 
	addrh.Address3 as [Home Address 3], 
	addrh.City as [Home Address City], 
	addrh.State as [Home Address State], 
	addrh.PostalCode as [Home Address Postal Code], 
	addrh.Country as [Home Address Country], 
	 
	addro.Address1 as [Other Address 1], 
	addro.Address2 as [Other Address 2], 
	addro.Address3 as [Other Address 3], 
	addro.City as [Other Address City], 
	addro.State as [Other Address State], 
	addro.PostalCode as [Other Address Postal Code], 
	addro.Country as [Other Address Country], 
	Case p.BillingMethod When 1 then ''Time and Materials'' When 2 then ''Fixed Fee'' When 3 then ''Retainer'' end as [Project Billing Method], 
	p.StartDate as [Project Start Date], 
	p.CompleteDate as [Project Due Date], 
		-- Budgeted data 
	p.EstHours + p.ApprovedCOHours as [Project Budget Hours], -- [Estimate Total Hours] 
	p.EstLabor + p.ApprovedCOLabor as [Project Budget Labor Gross], -- [Estimate Total Labor] 
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Project Total Budget wo Taxes], -- [Estimate Total] 
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Project Total Budget], --New field 
	pir.EstQty as [Budget Hours by Service],
	pir.EstGross as [Budget Gross by Service],
	p.ProjectCloseDate as [Project Close Date], 
	pr.BilledAmount as [Project Amount Billed], 
	pr.Hours as [Project Total Hours],
	pr.LaborNet as [Project Total Labor Net],
	pr.MiscCostNet + pr.VoucherNet + pr.ExpReceiptNet + pr.OpenOrderNet as [Project Total Expense Net],
	aa.Hours as [Allocated Hours], 
	p.ProjectKey, 
	case u.Contractor when 1 then ''YES'' ELSE ''NO'' end as [Contractor], 
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Salesperson Name], 
	CASE u.Active WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Active User], 
	t.LastModified as [Last Modified], 
	sg.GroupName as [Security Group], 
	u.Email as [User Email Address], 
	u.DateHired as [Date of Hire], 
	case  
		when ts.OnTime is null then '''' -- when the timesheet is not submitted or was created before issue 295216 
		when ts.OnTime = 0 then ''NO'' 
		else ''YES'' 
	end as [Time Sheet Submitted On Time], 
	case  
		when t.OnTime is null then '''' -- when the time entry was created before issue 295216 
		when t.OnTime = 0 then ''NO'' 
		else ''YES'' 
	end as [Time Entered On Time] ,
	Case cp.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active],
	Case When p.NonBillable = 1 or t.ActualRate = 0 then ''Non Billable'' else ''Billable'' end as [Billable],
	Case When t.InvoiceLineKey > 0 then 
		ISNULL(t.BilledHours, 0) else 0 end as [Billed on Invoice Hours], 
	Case When t.InvoiceLineKey > 0 then 
    	ROUND(ISNULL(t.BilledRate, 0) * ISNULL(t.BilledHours, 0), 2) else 0 end as [Billed on Invoice Amount], --Issue: 413912
	st.TaskName as [Summary Task Name],
	t.TaskKey,
	u.UserKey as EmployeeKey,
	s.HourlyCost as [Hourly Cost],
	bg.BillingGroupCode as [Billing Group Code] ,
	bg.Description as [Billing Group Description],
	rd.DeliverableName as [Deliverable Name],
	ISNULL(ven.CompanyName, c2.CompanyName ) as [Vendor Name],
	ISNULL(cp.EstHours, 0) + ISNULL(cp.ApprovedCOHours, 0) as [Campaign Budget Hours],
	ISNULL(cs.EstHours, 0) + ISNULL(cs.ApprovedCOHours, 0) as [Campaign Segment Budget Hours],
	ISNULL(t.PauseHours, 0) as [Time Paused],
   	ISNULL(tls.SegmentName,tls2.SegmentName) as [Timeline Segment],
	ISNULL(tls.SegmentColor, tls2.SegmentColor) as [Timeline Segment Color],
	ta.PlanStart as [Plan Start Date],
	ta.PlanComplete as [Plan Complete Date],
	ta.BaseStart as [Baseline Start Date],
	ta.BaseComplete as [Baseline Complete Date],
	ta.ActStart as [Actual Start Date],
	ta.ActComplete as [Actual Complete Date],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectNumber
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else pp.ProjectNumber
				end
	end  as [Planning Project Number],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectName
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else pp.ProjectName
				end
	end  as [Planning Project Name],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectNumber + '' - '' + p.ProjectName
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else Case When pp.ProjectNumber is null then pp.ProjectName else pp.ProjectNumber + '' - '' + pp.ProjectName end
				end
	end  as [Planning Project Full Name],
	(Select Sum(Hours) from vTaskUserHour b (nolock)
		Where t.ProjectKey = b.ProjectKey and t.UserKey = b.UserKey and t.ServiceKey = b.ServiceKey and  DatePart(week, WorkDate) = DatePart(week,b.BucketStart) and YEAR(WorkDate) = year(b.BucketStart)) as [Assigned Week Hours]
	,CASE t.Overtime WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Overtime]
	,bb.Hours as [Budget Hours by Task]
	,u.HourlyCost2 as [Hourly Cost 2]
	,con.UserName as [Company Owner]
	,ts.DateUnapproved as [Date And Time Unapproved]
	,u.HourlyRate as [Billable Rate]
	,l.LeadID as [Opportunity ID]
   ,l.Subject as [Opportunity Name]
   ,loc.Outcome as [Opportunity Outcome]
   ,l.CurrentStatus as [Opportunity Next Steps]
   ,lstage.LeadStageName as [Opportunity Stage]
   ,lstatus.LeadStatusName as [Opportunity Status]
   ,Case ISNULL(upf.TimesheetRequired, 0) When 1 then ''YES'' else ''NO'' end as [Time Sheet Required]
   ,t.Source as [Source]
FROM 
	tTimeSheet ts (nolock) 
	INNER JOIN tPreference pref (nolock) on ts.CompanyKey = pref.CompanyKey 
	INNER JOIN tTime t (nolock) ON ts.TimeSheetKey = t.TimeSheetKey 
	INNER JOIN tUser u (nolock) ON t.UserKey = u.UserKey 
	LEFT OUTER JOIN tUserPreference upf (nolock) on u.UserKey = upf.UserKey
	LEFT OUTER JOIN tVoucher v (nolock) ON t.VoucherKey = v.VoucherKey 
	LEFT OUTER JOIN tCompany c (nolock) ON u.CompanyKey = c.CompanyKey 
	LEFT OUTER JOIN tProject p (nolock) ON t.ProjectKey = p.ProjectKey 
	LEFT OUTER JOIN tDepartment d (nolock) ON u.DepartmentKey = d.DepartmentKey 
	LEFT OUTER JOIN tDepartment d_t (nolock) ON t.DepartmentKey = d_t.DepartmentKey 
	LEFT OUTER JOIN tOffice o (nolock) ON u.OfficeKey = o.OfficeKey 
	LEFT OUTER JOIN tOffice oP (nolock) ON p.OfficeKey = oP.OfficeKey 
	LEFT OUTER JOIN tService s (nolock) ON t.ServiceKey = s.ServiceKey 
	LEFT OUTER JOIN tDepartment d_s (nolock) ON s.DepartmentKey = d_s.DepartmentKey 
	LEFT OUTER JOIN tTitle ti (nolock) ON t.TitleKey = ti.TitleKey 
	LEFT OUTER JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey 
	LEFT OUTER JOIN tClientProduct cpd (nolock) on p.ClientProductKey = cpd.ClientProductKey 
	LEFT OUTER JOIN tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey 
	LEFT OUTER JOIN tCompany cClient (nolock) ON p.ClientKey = cClient.CompanyKey 
	LEFT OUTER JOIN tUser sales (NOLOCK) ON cClient.SalesPersonKey = sales.UserKey 
	LEFT OUTER JOIN tTask ta (nolock) ON t.TaskKey = ta.TaskKey 
	LEFT OUTER JOIN tTask td (nolock) ON t.DetailTaskKey = td.TaskKey 
	LEFT OUTER JOIN tTaskAssignmentType tat (nolock) on ta.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey 
	LEFT OUTER JOIN tInvoiceLine il (nolock) on t.InvoiceLineKey = il.InvoiceLineKey 
	LEFT OUTER JOIN tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey 
	LEFT OUTER JOIN tWriteOffReason wor (nolock) on t.WriteOffReasonKey = wor.WriteOffReasonKey 
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey 
	left outer join tUser pc (nolock) on p.BillingContact = pc.UserKey 
	left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey 
	left outer join tUser am (nolock) on p.AccountManager = am.UserKey 
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey 
	left outer join tRetainer r (nolock) on p.RetainerKey = r.RetainerKey 
	left outer join vUserName abk (nolock) on ts.ApprovedByKey = abk.UserKey 
	left outer join vUserName app (nolock) on u.TimeApprover = app.UserKey 
	LEFT OUTER JOIN vUserName spr (nolock) on u.SupervisorKey = spr.UserKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey 
	LEFT OUTER JOIN tWorkType wt (nolock) ON s.WorkTypeKey = wt.WorkTypeKey 
	LEFT OUTER JOIN tWorkType wti (nolock) ON ti.WorkTypeKey = wti.WorkTypeKey 
	LEFT OUTER JOIN tCompanyType ct (nolock) ON cClient.CompanyTypeKey = ct.CompanyTypeKey 
	LEFT OUTER JOIN tGLCompany glcP (nolock) ON p.GLCompanyKey = glcP.GLCompanyKey 
	LEFT OUTER JOIN tGLCompany glc (nolock) ON u.GLCompanyKey = glc.GLCompanyKey 
	LEFT OUTER JOIN tClass cl (nolock) ON p.ClassKey = cl.ClassKey 
	LEFT OUTER JOIN tClass ucl (nolock) ON u.ClassKey = ucl.ClassKey 
	lEFT OUTER JOIN tCompany pcn (nolock) ON cClient.ParentCompanyKey = pcn.CompanyKey 
	LEFT OUTER JOIN tService bs (nolock) on t.BilledService = bs.ServiceKey 
	LEFT OUTER JOIN tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	LEFT OUTER JOIN tAddress addrw (nolock) on u.AddressKey = addrw.AddressKey 
	LEFT OUTER JOIN tAddress addrh (nolock) on u.HomeAddressKey = addrh.AddressKey 
	LEFT OUTER JOIN tAddress addro (nolock) on u.OtherAddressKey = addro.AddressKey 
	LEFT OUTER JOIN tAddress clad (nolock) ON cClient.BillingAddressKey = clad.AddressKey 
	LEFT OUTER JOIN tProjectRollup pr (nolock) ON p.ProjectKey = pr.ProjectKey 
	LEFT OUTER JOIN (Select UserKey, TaskKey, Sum(Hours) as Hours from tTaskUser (nolock) Group By UserKey, TaskKey) as aa on t.UserKey = aa.UserKey and ISNULL(t.DetailTaskKey, t.TaskKey) = aa.TaskKey 
	LEFT OUTER JOIN (Select TaskKey, Sum(tEstimateTaskLabor.Hours) as Hours from tEstimateTaskLabor (nolock) inner join tEstimate (Nolock) on tEstimateTaskLabor.EstimateKey = tEstimate.EstimateKey where tEstimate.InternalStatus = 4 Group By TaskKey) as bb on ISNULL(t.DetailTaskKey, t.TaskKey) = bb.TaskKey 
	LEFT OUTER JOIN tSecurityGroup sg (nolock) on u.SecurityGroupKey = sg.SecurityGroupKey 
	LEFT OUTER JOIN tProjectItemRollup pir (nolock) on t.ProjectKey = pir.ProjectKey and t.ServiceKey = pir.EntityKey and pir.Entity = ''tService''
	LEFT OUTER JOIN tTask st (nolock) on ta.SummaryTaskKey = st.TaskKey
	LEFT OUTER JOIN tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	LEFT OUTER JOIN tReviewDeliverable rd (nolock) on t.DeliverableKey = rd.ReviewDeliverableKey
	LEFT OUTER JOIN tCompany ven (nolock) ON v.VendorKey = ven.CompanyKey 
	LEFT OUTER JOIN tTimelineSegment tls (nolock) on td.TimelineSegmentKey = tls.TimelineSegmentKey
	LEFT OUTER JOIN tTimelineSegment tls2 (nolock) on ta.TimelineSegmentKey = tls2.TimelineSegmentKey
	LEFT OUTER JOIN tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey
	LEFT OUTER JOIN tCompany c2 (nolock) ON u.VendorKey = c2.CompanyKey 
	LEFT OUTER JOIN vUserName con (nolock) on cClient.ContactOwnerKey = con.UserKey 
	LEFT OUTER JOIN tLead l (nolock) on p.LeadKey = l.LeadKey
	LEFT OUTER JOIN tLeadOutcome loc (nolock) on l.LeadOutcomeKey = loc.LeadOutcomeKey
	LEFT OUTER JOIN tLeadStage lstage (nolock) on l.LeadStageKey = lstage.LeadStageKey
	LEFT OUTER JOIN tLeadStatus lstatus (nolock) on l.LeadStatusKey = lstatus.LeadStatusKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAICompanyCustomFieldSave]'
GO
IF OBJECT_ID(N'[dbo].[spApiAICompanyCustomFieldSave]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAICompanyCustomFieldSave]
    @CompanyKey      int,
    @OwnerCompanyKey int,
    @FieldName       varchar(75),
    @FieldValue      nvarchar(max),
    @UserKey         int

AS --Encrypt

/*
|| When      Who Rel        What
|| 06/29/26  GAR 26.08.16   (731183) Created - writes one custom field value for a tCompany record.
||                           Bootstraps the tObjectFieldSet instance if the company has none yet.
||                           Returns: >0 = CustomFieldKey (success)
||                                    -1  = no field sets configured for Company in this tenant
||                                    -2  = @FieldName not found in the resolved field set
||                                    -3  = user lacks viewCompanyCustomFields right
|| 07/09/26  GAR 26.08.16   Bootstrap a ''General'' field set for this tenant when none exists yet, instead
||                                   of returning -1 -- mirrors how ToolAddUpdateProject (MCPProjects.cs) already
||                                   auto-creates a project''s tObjectFieldSet instance on first use. The new set
||                                   is seeded with every active FieldDef this tenant already has defined for
||                                   ''General'' (the AssociatedEntity these tenant-defined Company fields use), so
||                                   it behaves the same as one built through Setup > Custom Fields > Company
||                                   Fields. -1 is now only returned if the auto-create itself fails.
|| 07/09/26  GEG 26.08.16   (sec review) Added spCheckAccess(tCompany) record-level gate after the feature-right
||                                   check. The viewCompanyCustomFields right alone did not verify access to the
||                                   specific company (GL company / folder security).
|| 07/10/26  GAR 26.07.19   Added gating security - requires right viewCompanyCustomFields.
*/

  DECLARE
    @CustomFieldKey  int,
    @FieldSetKey     int,
    @FieldDefKey     int,
    @rc              int,
    @IsAdministrator tinyint,
    @SecurityGroupKey int

  -- Security: must be admin or have viewCompanyCustomFields right
  SELECT @IsAdministrator  = Administrator,
         @SecurityGroupKey = SecurityGroupKey
  FROM   tUser (nolock)
  WHERE  UserKey = @UserKey

  IF ISNULL(@IsAdministrator, 0) <> 1
  BEGIN
    IF NOT EXISTS (
      SELECT 1
      FROM   tRight r (nolock)
      INNER JOIN tRightAssigned ra (nolock) ON r.RightKey = ra.RightKey
      WHERE  ra.EntityType = ''Security Group''
        AND  ra.EntityKey  = @SecurityGroupKey
        AND  r.RightID     = ''viewCompanyCustomFields''
    )
      RETURN -3   -- access denied
  END

  -- Record-level access to this specific company (GL company intersection + folder security).
  -- @OwnerCompanyKey is the tenant; @CompanyKey is the company whose custom field is being written.
  DECLARE @access int
  EXEC @access = spCheckAccess @UserKey, @OwnerCompanyKey, ''tCompany'', @CompanyKey
  IF @access <> 1
    RETURN -3   -- access denied

  -- Get the company''s existing CF instance (may be 0 for new or never-used companies)
  SELECT @CustomFieldKey = ISNULL(CustomFieldKey, 0)
  FROM   tCompany (nolock)
  WHERE  CompanyKey = @CompanyKey

  IF @CustomFieldKey = 0
  BEGIN
    -- Find the default active field set for ''Company'' in this tenant
    EXEC @FieldSetKey = spCF_GetAEFieldSet
        @AssociatedEntity = ''General'',
        @OwnerEntityKey   = @OwnerCompanyKey,
        @RequireFields    = 1

    IF ISNULL(@FieldSetKey, 0) = 0
    BEGIN
      -- No field set exists yet for this tenant''s Company custom fields -- bootstrap one so
      -- the save can proceed without requiring a manual Setup > Custom Fields step first.
      EXEC spCF_tFieldSetInsert
          @OwnerEntityKey   = @OwnerCompanyKey,
          @AssociatedEntity = ''General'',
          @FieldSetName     = ''Company Fields'',
          @UserKey          = @UserKey,
          @oIdentity        = @FieldSetKey OUTPUT

      IF ISNULL(@FieldSetKey, 0) = 0
        RETURN -1   -- failed to bootstrap a field set

      -- Seed it with every active ''General'' field def this tenant has already defined, so it
      -- behaves the same as a set built through the admin UI (which lists all of them at once)
      -- rather than only ever containing whichever single field happened to trigger the bootstrap.
      INSERT INTO tFieldSetField (FieldSetKey, FieldDefKey, DisplayOrder)
      SELECT @FieldSetKey, fd.FieldDefKey, ROW_NUMBER() OVER (ORDER BY fd.FieldDefKey)
      FROM   tFieldDef fd (nolock)
      WHERE  fd.OwnerEntityKey    = @OwnerCompanyKey
        AND  fd.AssociatedEntity  = ''General''
        AND  fd.Active            = 1
    END

    -- Resolve the FieldDefKey from FieldName within that field set
    SELECT @FieldDefKey = MIN(fd.FieldDefKey)
    FROM   tFieldDef fd (nolock)
    INNER JOIN tFieldSetField fsf (nolock) ON fd.FieldDefKey = fsf.FieldDefKey
    WHERE  fsf.FieldSetKey  = @FieldSetKey
      AND  fd.FieldName     = @FieldName
      AND  fd.Active        = 1

    IF ISNULL(@FieldDefKey, 0) = 0
      RETURN -2   -- field name not found in this field set

    -- spCF_tFieldValueInsertUpdate creates the tObjectFieldSet instance,
    -- wires CustomFieldKey back to tCompany, and inserts the value row.
    EXEC @CustomFieldKey = spCF_tFieldValueInsertUpdate
        @Entity         = ''tCompany'',
        @EntityKey      = @CompanyKey,
        @FieldSetKey    = @FieldSetKey,
        @FieldDefKey    = @FieldDefKey,
        @FieldValue     = @FieldValue,
        @UserKey        = @UserKey,
        @CustomFieldKey = 0
  END
  ELSE
  BEGIN
    -- Instance already exists - update by field name (resolves FieldDefKey internally)
    EXEC @rc = spCF_UpdateFieldValue
        @CustomFieldKey = @CustomFieldKey,
        @FieldName      = @FieldName,
        @FieldValue     = @FieldValue

    IF @rc = -1
      RETURN -2   -- field name not found (spCF_UpdateFieldValue returns -1 for not-found)
  END

  -- Stamp the parent record''s DateUpdated / ModifiedBy
  EXEC spCF_UpdateDateModified @UserKey, ''tCompany'', @CompanyKey

  RETURN @CustomFieldKey


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptTaskUserGetDefaultsForTime]'
GO
IF OBJECT_ID(N'[dbo].[sptTaskUserGetDefaultsForTime]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptTaskUserGetDefaultsForTime]
	@UserKey int,
	@EndDate smalldatetime

AS --Encrypt

/*
|| When      Who Rel      What
|| 02/10/16  CRG 10.6.0.1 Created for Platinum Time Entry
|| 02/23/16  CRG 10.6.0.1 Added ProjectFullName, ClientName, CampaignFullName, ProjectStatus, and ProjectTypeName for grouping
|| 09/16/16  RLB 10.6.0.8 Added TaskUserKey for setting closed task user status
|| 03/24/17  GWG 10.6.1.4 Adding assignments that are not directly tracking budget
|| 08/25/17  GAR 10.6.1.9 (359650) Added service code for searching
|| 08/31/17  GAR 10.6.1.9 (360988) Added user key for populating the row
|| 10/10/17  RLB 10.6.2.1 Added rights check for Tasks with predecessors complete
|| 11/10/17  GWG 10.6.2.1 Changed the join to budget task key so that only budget tracking tasks are brought down
|| 04/09/18  CRG 19.0.5.0 (454523) Added PlanningProject
|| 09/05/19  RLB 19.0.9.0 (476641) Added Account Manager and Project Manager to TimeEntry
|| 12/02/19  CRG 20.0.1.0 (466594) Added ProjectOrder
|| 04/13/21  RLB 21.05.16 (555048) Adding Deliverable options
|| 10/13/22  RLB 22.11.20 (610106) added pull of LimitProjectServices
|| 03/29/23  CRG 23.04.16 (622919) Added check for NoTimeEntry
|| 08/11/23  CRG 23.09.17 (642807) Added ScheduleTask
|| 07/16/26  RLB 26.08.16 (732714) When a task rolls up to a separate summary/budget task, also require the summary task''s own PercComp be incomplete so a completed summary task is not defaulted just because the detail assignment tracks completion separately
|| 07/17/26  RLB 26.08.16 (732714) Task-level PercComp=100 now always excludes regardless of PercCompSeparate, since that is the only signal spTaskValidatePercComp honors at save time; the PercCompSeparate/tu.PercComp check is now an additional restriction, not a replacement
*/

	DECLARE	@RateLevel int,
			@DefaultServiceKey int,
			@Administrator int,
			@SecurityGroupKey int,
			@HasRightForPredecessorComplete tinyint

	SELECT @HasRightForPredecessorComplete = 0

	SELECT	@RateLevel = RateLevel,
			@DefaultServiceKey = DefaultServiceKey,
			@Administrator = Administrator,
			@SecurityGroupKey = SecurityGroupKey
	FROM	tUser (nolock)
	WHERE	UserKey = @UserKey

	IF ISNULL(@Administrator, 0) = 1
		select @HasRightForPredecessorComplete = 1
	ELSE
	BEGIN
		-- check right for completed tasks
		if exists(select 1 from tRightAssigned ra (nolock) where ra.EntityType = ''Security Group'' and ra.EntityKey = @SecurityGroupKey and ra.RightKey = 100950)
			select @HasRightForPredecessorComplete = 1
	END

	CREATE TABLE #Tasks (
			TaskKey int NULL ,
			BudgetTaskKey int NULL ,
			ProjectKey int NULL ,
			ServiceKey int NULL ,
			TaskUserKey int NULL ,
			UserKey int NULL ,
			)

	IF @HasRightForPredecessorComplete = 1
	BEGIN
		-- Get all the task where track budget is on the assigned task
		INSERT #Tasks
		(
			TaskKey,
			BudgetTaskKey,
			ProjectKey,
			ServiceKey,
			TaskUserKey,
			UserKey
		)
		SELECT DISTINCT
				t.TaskKey,
				t.BudgetTaskKey,
				t.ProjectKey,
				ISNULL(tu.ServiceKey, @DefaultServiceKey) AS ServiceKey,
				tu.TaskUserKey,
				tu.UserKey
		FROM	tTaskUser tu (nolock)
		INNER JOIN tTask t (nolock) ON tu.TaskKey = t.TaskKey
		INNER JOIN tTask bt (nolock) ON t.BudgetTaskKey = bt.TaskKey
		INNER JOIN tProject p (nolock) on t.ProjectKey = p.ProjectKey
		INNER JOIN tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
		WHERE	tu.UserKey = @UserKey
		AND		(ISNULL(t.PercComp, 0) < 100 And (ISNULL(t.PercCompSeparate, 0) = 0 Or ISNULL(tu.PercComp, 0) < 100))
		AND		(t.BudgetTaskKey = t.TaskKey OR ISNULL(bt.PercComp, 0) < 100)
		AND		t.PlanStart <= @EndDate
		AND		p.Active = 1
		AND		ps.TimeActive = 1
		AND		t.BudgetTaskKey is not null
		AND		ISNULL(t.NoTimeEntry, 0) = 0
	END
	ELSE
	BEGIN
			INSERT #Tasks
			(
				TaskKey,
				BudgetTaskKey,
				ProjectKey,
				ServiceKey,
				TaskUserKey,
				UserKey
			)
			SELECT DISTINCT
					t.TaskKey,
					t.BudgetTaskKey,
					t.ProjectKey,
					ISNULL(tu.ServiceKey, @DefaultServiceKey) AS ServiceKey,
					tu.TaskUserKey,
					tu.UserKey
			FROM	tTaskUser tu (nolock)
			INNER JOIN tTask t (nolock) ON tu.TaskKey = t.TaskKey
			INNER JOIN tTask bt (nolock) ON t.BudgetTaskKey = bt.TaskKey
			INNER JOIN tProject p (nolock) on t.ProjectKey = p.ProjectKey
			INNER JOIN tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
			WHERE	tu.UserKey = @UserKey
			AND		(ISNULL(t.PercComp, 0) < 100 And (ISNULL(t.PercCompSeparate, 0) = 0 Or ISNULL(tu.PercComp, 0) < 100))
			AND		(t.BudgetTaskKey = t.TaskKey OR ISNULL(bt.PercComp, 0) < 100)
			AND     ISNULL(t.PredecessorsComplete, 0) = 1
			AND		t.PlanStart <= @EndDate
			AND		p.Active = 1
			AND		ps.TimeActive = 1
			AND		t.BudgetTaskKey is not null
			AND		ISNULL(t.NoTimeEntry, 0) = 0
	END


	SELECT DISTINCT	p.ProjectNumber,
			p.ProjectName,
			tmp.ProjectKey,
			t.TaskID,
			t.TaskName,
			t.ProjectOrder,
			tmp.BudgetTaskKey as TaskKey,
			tmp.BudgetTaskKey,
			@RateLevel AS RateLevel,
			tmp.ServiceKey,
			s.ServiceCode,
			s.Description AS ServiceDescription,
			ISNULL(p.ProjectNumber, '''') + ''-'' + ISNULL(p.ProjectName, '''') AS ProjectFullName,
			c.CompanyName AS ClientName,
			ISNULL(camp.CampaignID, '''') + ''-'' + ISNULL(camp.CampaignName, '''') AS CampaignFullName,
			ps.ProjectStatus,
			pt.ProjectTypeName,
			tmp.TaskUserKey,
			tmp.UserKey,
			p.PlanningProject,
			p.LimitProjectServices,
			p.AccountManager,
			RTRIM(LTRIM(ISNULL(am.FirstName,'''') + '' '' + ISNULL(am.LastName, ''''))) as AccountManagerName,
			p.ProjectManager,
			RTRIM(LTRIM(ISNULL(pm.FirstName,'''') + '' '' + ISNULL(pm.LastName, ''''))) as ProjectManagerName,
			rd.ReviewDeliverableKey as DeliverableKey,
			rd.ReviewDeliverableKey,
			rd.DeliverableName,
			rd.DeliverableID,
			t.ScheduleTask
	FROM	#Tasks tmp
	INNER JOIN tTask t (nolock) ON tmp.BudgetTaskKey = t.TaskKey
	INNER JOIN tProject p (nolock) ON tmp.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tUser am (NOLOCK) on am.UserKey = p.AccountManager
	LEFT OUTER JOIN tUser pm (NOLOCK) on pm.UserKey = p.ProjectManager
	LEFT JOIN tService s (nolock) ON tmp.ServiceKey = s.ServiceKey
	LEFT JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
	LEFT JOIN tCampaign camp (nolock) ON p.CampaignKey = camp.CampaignKey
	LEFT JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey
	LEFT JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey
	LEFT JOIN tReviewDeliverable rd (nolock) ON t.TaskKey = rd.TaskKey
	ORDER BY p.ProjectNumber, t.ProjectOrder

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_TimeDetailNoCost]'
GO
IF OBJECT_ID(N'[dbo].[vReport_TimeDetailNoCost]', 'V') IS NOT NULL
EXEC sp_executesql N'

-- View

ALTER VIEW [dbo].[vReport_TimeDetailNoCost] 
AS 

/* 
  || When     Who Rel      What 
  || 12/28/06 GHL 8.4      Added Campaign ID 
  || 11/06/07 CRG 8.5      (10954) Added DateBilled, Billing Item ID, and Billing Item Name 
  || 11/06/07 CRG 8.5      (13158) Added Client Company Type 
  || 11/07/07 CRG 8.5      (9651) Added Account Manager 
  || 5/23/08  CRG 8.5.1.2  (25454) Added GLCompany 
  || 7/20/08  GWG 10.0.0.6 (30741) Added GL Class from the project 
  || 8/14/08  GHL 10.0.0.7 (32476) Added task description  
  || 04/06/09 MAS 10.0.2.2 (50443) Added Write-off Hours, Write-off Total, Marked Billed Hours and Marked Billed Total fields 
  || 09/10/09 GHL 10.5     Added Transferred Out 
  || 01/5/10  GWG 10.5.1.6 Added client''s project number 
  || 01/06/10 RLB 10.5.1.6 Added Task Type 
  || 03/10/10 RLB 10.5.2.0 Formatting Date Worked Month 
  || 04/29/10 RLB 10.5.2.2 (79487) removed time from Approved Date and Submitted Date  
  || 04/30/10 RLB 10.5.2.2 (63218)Added Parent Company Name 
  || 07/28/10 RLB 10.5.3.3 (83803)Added Non Billable Project to the Data set 
  || 08/30/10 RLB 10.5.3.4 (88843)Added Billed Service Code 
  || 01/16/11 GWG 10.5.4.0 Added the rounding in for actual billable amount 
  || 04/07/11 RLB 10.5.4.3 (108045) Removed Project Short Name 
  || 06/29/11 RLB 10.5.4.5 (115335) changed tCompany to a left outer join because contacts could not have a company 
  || 07/27/11 RLB 10.5.4.6 (114500) Added Line Number which is the tasks order in the projet schedule screen 
  || 07/27/11 RLB 10.5.4.6 (111324) Added Campaign Segment 
  || 10/8/11  GWG 10.5.4.9 Added a link to the task through the detail task key 
  || 12/09/11 RLB 10.5.5.1 (121131) Added Verified 
  || 01/09/12 MFT 10.5.5.2 (107579) Added Title 
  || 02/29/12 MFT 10.5.5.3 Added Date Worked Week 
  || 03/16/12 GHL 10.5.5.4 (137417) Add Date Time fields 
  || 04/24/12 GHL 10.5.5.5 Added GLCompanyKey in order to map/restrict 
  ||                       p.GLCompanySource = 0 then p.GLCompanyKey 
  ||                       p.GLCompanySource = 1 then u.GLCompanyKey 
  ||                       p.GLCompanySource is null i.e. no project then u.GLCompanyKey 
  || 07/06/12 GHL 10.5.5.7 (148085) Getting now the parent company from the client on the project 
  ||                       instead of from the company on the user 
  || 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey 
  || 01/15/13 GWG 10.5.6.4 Added some additional fields for reporting 
  || 02/13/13 WDF 10.5.6.5 (160177) Added Timesheet From/To dates 
  || 05/01/13 GWG 10.5.6.7 Added users class 
  || 05/22/13 MFT 10.5.6.8 (174957) Added ta.Comments 
  || 08/08/13 GWG 10.5.7.0 Added Allocated Hours 
  || 11/15/13 RLB 10.5.7.4 (191407) Added Yes OR No for tax 1 and 2  on tasks set on the time entry 
  || 06/17/14 WDF 10.5.8.1 (217923) Added Vendor Invoice Number 
  || 10/16/14 WDF 10.5.8.5 (Abelson Taylor) Added Billing Title 
  || 10/28/14 WDF 10.5.8.5 (226655) Added Users Default GLCompany ID/Name 
  || 12/16/14 RLB 10.5.8.7 (239571) Added Client Billing State and Company CustomFields from the client on the project 
  || 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID 
  || 03/10/15 GHL 10.5.9.0 (Abelson Taylor) Added Department at the Time  
  || 03/20/15 WDF 10.5.9.0 (Abelson Taylor) Added WriteOffDate 
  || 06/02/15 MCM 10.5.9.2 (256400) Added Contractor field 
  || 01/25/16 WDF 10.6.0.0 (286743) Formatting Date Worked Week  
  || 03/18/16 WDF 10.6.0.2 (293875) Added [On Hold] 
  || 04/12/16 MFT 10.6.0.3 (296036) Added WriteOffComment 
  || 06/15/16 GWG 10.6.0.5 Added in Paid Status 
  || 07/12/16 WDF 10.6.0.6 (299976) Added Campaign Custom Fields 
  || 08/09/16 WDF 10.6.0.7 (309294) Added [Salesperson Name] 
  || 08/11/16 KMC 10.6.0.7 (307284) Added Active status for tUser as [Active User] 
  || 08/30/16 KMC 10.6.0.7 (311989) Added ProjectCloseDate as [Project Close Date] 
  || 09/20/16 QMD 10.6.0.8 (309378) Added LastModified 
  || 10/05/16 WDF 10.6.0.9 (316052) Set [Active User] as YES/NO 
  || 11/21/16 KMC 10.6.1.0 (321574) Added user email address 
  || 02/17/17 MCM 10.6.1.3 (323908) Updating the User Full Name logic to match the vUserName 
  || 02/17/17 QMD 10.6.1.3 Added TimeKey to the select 
  || 03/20/17 MCM 10.6.1.4 (337685) Adding User Name, already had User Full Name 
  || 09/25/17 GHL 10.6.2.0 (295216) Added timesheet tardiness field 
  || 09/28/17 GWG 10.6.2.0 Added Project Close Date 
  || 10/10/17 GWG 10.6.2.0 Fix spelling error 
  || 12/4/17  GWG 10.6.2.2 Added Predecessors completed 
  || 01/30/17 GWG 18.2     Added budget hours and dollars by project and service.
  || 04/03/18 WDF 18.4     Added [User Title]
  || 04/27/18 RLS 18.5.0   (398138) Added CurrencyID
  || 05/15/18 GWG 18.5.0   added campaign active
  || 06/28/18 AMP 18.7.0   (407643)  - Modified Column Name for Service Description lookup
  || 07/19/18 RLS 18.8.0   (410986) Added [Date of Hire]
  || 07/24/18 GWG 18.8.0   Added billable/nonbillable label for graphing
  || 08/28/18 AMP 18.9.0   (413912) Added standard column ''Billed on Invoice Amount'' 
  || 09/24/18 GWG 18.9.1   Protect against nulls in amount billed
  || 12/14/18 RLS 19.1.0   (435324) Added [Project Billing Status]
  || 12/18/18 GWG 19.1	   Added month name to formatted month
  || 03/08/19 AMP 19.0.4.0 (433620) Added Summary Task Name 
  || 03/25/19 QMD 19.0.4.0 (452162) Added TaskKey
  || 05/29/19 RLS 19.0.5.0 (459194) Added Project Percent Complete
  || 06/06/19 RLB 19.0.7.0 (446229) Adding Project Manager
  || 07/25/19 QMD 19.0.8.0 (470423) Adding UserKey as EmployeeKey
  || 09/09/19 AMP 19.1.0.0 (477617) Added field for Service Hourly Cost
  || 10/21/19 RLB 19.1.1.0 (457226) Added SupervisorName
  || 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
  || 11/24/20 AMP 20.0.3.0 (495923) Added Retainer Name 
  || 02/26/20 AMP 20.0.4.0 (500371) Added Month and Year Worked
  || 03/09/20 RLS 20.0.4.0 (505758) Changed ''/'' to ''-'' in [Project Full Name]
  || 03/18/20 RLB 20.0.4.0 (507087) removed the Convert on start time and end time
  || 03/18/20 RLS 20.0.4.0 (505211) Added [Billing Group Code] and [Billing Group Description]
  || 07/23/20 RLS 20.0.8.0 (520337) Added [Deliverable Name] and join to tReviewDeliverable
  || 07/29/20 RLB 20.0.8.0 (523363) Fixed how Project primary contact field
  || 08/20/20 RLB 20.0.9.0 (526270) change outer join to tDeliverable can only use DeliverableKey on tTime
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 09/08/20 GAR 20.1.0.0 (527210) Added Vendor Name (from the vendor invoice number)
  || 02/24/20 RLB 21.03.14 (543274) Added [Campaign Budget Hours] and [Campaign Segment Budget Hours]
  || 03/30/21 GHL 21.04.18 (552776) Added custom field key 4 to test 4th direction on CF
  || 05/06/21 RLS 21.0.6.0 (555522) Added [Time paused]
  || 06/29/21 RLS 21.0.7.0 (563027) Wrapped u.Title in ISNULL()
  || 12/15/21 AMP 22.02.20 (579957) Added Timeline Segment
  || 02/22/22 RLB 22.03.20 (587756) changed planned project name, number and full name to include the planning project name not just linked through planningprojectkey
  || 03/11/22 GWG 22.03.20 (583542) Adding in the allocated hours for the week. Needed by fusion for a particular report
  || 04/28/22 RLS 22.05.15 (595589) Added PlanStart,PlanComplete,ActStart,ActComplete,BaseStart,BaseComplete
  || 05/06/22 RLB 22.06.19 (593471) made date created and time created match time detail
  || 04/28/22 RLS 22.05.15 (598368) Replaced ISNULL(tu.ActStart, ta.ActStart) and ISNULL(tu.ActComplete, ta.ActComplete) with ta.ActStart and ta.ActComplete and removed the outer join to tTaskUser
  || 07/21/22 GHL 22.08.00 (604153) Added Overtime field
  || 09/01/22 AMP 22.09.18 (610375) Modified retrieving the Vendor Name. If there is no vendor invoice tied to the time entry get the Vendor Name from the user record
  || 01/04/23 RLB 23.02.19 (625612) Added Budget Hours by Task. Any task labor hours on approved estimate
  || 03/13/23 RLB 23.04.16 (629165) Adding Office Color, department and service
  || 08/11/23 RLB 23.09.17 (648008) added project type color and timeline segment color
  || 07/23/24 RLS 24.08.18 (675330) Added [Company Owner]
  || 07/29/24 RLS 24.08.18 (679241) Replaced missing closing bracket in [Project Type Color]
  || 10/25/24 QMD 24.11.17 (685924) Added DateUnapproved  
  || 03/20/25 RLS 25.04.20 (695482) Added [Billable Rate]
  || 04/10/25 QMD 24.11.17 (686745) Performance Initiative - Slight tweak to which tables are selected first
  || 04/16/25 RLS 25.05.18 (694661) Added [Opportunity ID],[Opportunity Name],[Opportunity Outcome],[Opportunity Next Steps],[Opportunity Stage] and [Opportunity Status] 
  || 02/19/26 RLB 26.03.15 (722386) Added [Time Sheet Required]
  || 07/10/26 GAR 26.08.16 (732133) Added Source for use with the MCP time entries
*/ 

SELECT  
	ts.CompanyKey,  
	ts.CompanyKey as OwnerCompanyKey, 
	case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey, 
	ts.TimeSheetKey, 
	p.CustomFieldKey, 
	cClient.CustomFieldKey AS CustomFieldKey2, 
	cp.CustomFieldKey as CustomFieldKey3, 
	rd.CustomFieldKey as CustomFieldKey4,
	t.TimeKey, 
	cClient.CompanyName AS [Client Name],  
	cClient.CustomerID AS [Client ID], 
	clad.State AS [Client Billing State], 
	pcn.CompanyName AS [Parent Company], 
	p.ProjectName AS [Project Name],   
	p.ProjectNumber AS [Project Number],  
	p.ClientProjectNumber AS [Client Project Number], 
	Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project],
	p.CurrencyID as [Currency],
	LTRIM(RTRIM(ISNULL(pc.FirstName,'''') + '' '' + ISNULL(pc.LastName,''''))) AS [Project Primary Contact], 
	p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name], 
	pt.ProjectTypeName as [Project Type], 
	pt.ProjectTypeColor as [Project Type Color],
	pt.Description as [Project Type Description], 
    cp.CampaignID as [Campaign ID], 
	cp.CampaignName as [Campaign Name], 
	cs.SegmentName as [Campaign Segment],
	LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager], 
	LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager], 
	u.SystemID AS [User System ID],  
	ISNULL(u.Title, '''') AS [User Title],  
	u.FirstName AS [User First Name],  
	u.LastName AS [User Last Name],  
	LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,''''))) AS [User Name], 
	case  
		when u.MiddleName is null then LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,'''')))  
		else LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + SUBSTRING(u.MiddleName, 1, 1) + '' '' + ISNULL(u.LastName,'''')))  
	end as [User Full Name], 
	glc.GLCompanyID AS [Default GLCompany ID], 
	glc.GLCompanyID + '' - '' + glc.GLCompanyName AS [Default GLCompany Full Name], 
	d.DepartmentName AS [User Department],
	d.DepartmentColor as [User Department Color],
	case when t.DepartmentKey is not null then d_t.DepartmentName  
		else case when isnull(pref.DefaultDepartmentFromUser, 0) = 1 then d.DepartmentName else d_s.DepartmentName end  
	end as [Department at the Time],
	case when t.DepartmentKey is not null then d_t.DepartmentColor  
		else case when isnull(pref.DefaultDepartmentFromUser, 0) = 1 then d.DepartmentColor else d_s.DepartmentColor end  
	end as [Department Color at the Time],	
	o.OfficeName AS [User Office Name], 
	o.OfficeColor as [User Office Color],
	oP.OfficeName AS [Project Office Name], 
	oP.OfficeColor as [Project Office Color],
	c.CompanyName AS [User Company Name], 
	ta.TaskID AS [Task ID],  
	ta.TaskID + '' - '' + ta.TaskName AS [Task Full Name],  
	ta.TaskName as [Task Name], 
	td.TaskID as [Assignment ID], 
	td.TaskName as [Assignment Subject], 
	ta.DueBy as [Task Due By], 
	ta.PercComp as [Task Percent Complete],
	p.PercComp as [Project Percent Complete],
	td.TaskID + '' - '' + td.TaskName AS [Assignment Full Name],  
	tat.TaskAssignmentType as [Task Type], 
	ta.Description AS [Task Description], 
	ta.ProjectOrder AS [Line Number], 
	Case ISNULL(ta.PredecessorsComplete, 0) When 1 then ''YES'' else ''NO'' end as [Predecessors Completed], 
	Case ISNULL(ta.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable], 
	Case ISNULL(ta.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable 2], 
	ta.Comments AS [Task Status Comments], 
	s.ServiceCode AS [Service Code], 
	s.ServiceColor as [Service Color],
	bs.ServiceCode AS [Billed Service Code], 
	bs.ServiceColor as [Billed Service Color],
	t.RateLevel AS [Service Rate Level], 

	Cast(Cast(MONTH(ISNULL(t.DateAdded, ts.DateCreated)) as varchar) + ''/'' + Cast(DAY(ISNULL(t.DateAdded, ts.DateCreated)) as varchar) + ''/'' + Cast(YEAR(ISNULL(t.DateAdded, ts.DateCreated)) as varchar) as smalldatetime) as [Date Created], 
	Cast(Cast(MONTH(ts.DateSubmitted) as varchar) + ''/'' + Cast(DAY(ts.DateSubmitted) as varchar) + ''/'' + Cast(YEAR(ts.DateSubmitted) as varchar) as smalldatetime) as [Date Submitted For Approval], 
	Cast(Cast(MONTH(ts.DateApproved) as varchar) + ''/'' + Cast(DAY(ts.DateApproved) as varchar) + ''/'' + Cast(YEAR(ts.DateApproved) as varchar) as smalldatetime) as [Date Approved], 

	ISNULL(t.DateAdded, ts.DateCreated) as [Date And Time Created],  
	ts.DateSubmitted as [Date And Time Submitted], 
	ts.DateApproved as [Date And Time Approved], 
	ts.StartDate as [Time Sheet From], 
	ts.EndDate as [Time Sheet To], 

	abk.UserName AS [Approved By],
	spr.UserName AS [Supervisor Name],  
	Case ts.Status 
		When 1 then ''Not Sent For Approval'' 
		When 2 then ''Sent For Approval'' 
		When 3 then ''Rejected'' 
		When 4 then ''Approved'' end as [Approval Status], 
	wor.ReasonName AS [Write Off Reason], 
	t.WriteOffComment AS [Write Off Comment], 
	Case t.RateLevel  
		When 1 then ISNULL(s.Description1, s.Description) 
		When 2 then ISNULL(s.Description2, s.Description) 
		When 3 then ISNULL(s.Description3, s.Description) 
		When 4 then ISNULL(s.Description4, s.Description) 
			Else s.Description 
	END as [Service Description for Rate], 
	s.Description as [Service Description],
	ti.TitleName as [Billing Title Name], 
	ti.TitleID as [Billing Title ID], 
	cd.DivisionName as [Client Division], 
	cd.DivisionID as [Client Division ID], 
	cpd.ProductName as [Client Product], 
	cpd.ProductID as [Client Product ID], 
	t.WorkDate AS [Date Worked],  
	DATEPART(Year, t.WorkDate) AS [Date Worked Year], 
	CAST(DATEPART(Year, t.WorkDate) AS VARCHAR(4)) AS [Date Worked Year Formatted], 
	DATENAME(Month, t.WorkDate) AS [Date Worked Month], 
	RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, t.WorkDate) AS [Date Worked Month Formatted], 
	RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) AS [Date Worked Month Number],     
	CAST(DATEPART(Year, t.WorkDate) AS VARCHAR(4)) + '' ''+ RIGHT(''0'' + CAST(DATEPART(Month, t.WorkDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, t.WorkDate) AS  [Month and Year Worked],
	t.ActualHours AS [Actual Hours Worked],  
	CASE WHEN (p.NonBillable = 0 OR p.NonBillable IS NULL) AND t.ActualRate > 0 THEN t.ActualHours 
		ELSE 0 END AS [Actual Billable Hours], 
	CASE WHEN p.NonBillable = 1 OR t.ProjectKey IS NULL OR t.ActualRate = 0  
		THEN t.ActualHours ELSE 0 END AS [Actual Non Billable Hours], 
	CASE WHEN (p.NonBillable = 0 OR p.NonBillable IS NULL) AND t.ActualRate > 0 THEN ROUND(t.ActualHours * t.ActualRate, 2) ELSE 0 END AS [Actual Billable Amount],  
	CASE WHEN p.NonBillable = 1 OR t.ProjectKey IS NULL  
		THEN ROUND(t.ActualHours * t.ActualRate, 2) ELSE 0 END AS [Actual Non Billable Amount], 
	t.ActualRate AS [Actual Billing Rate],  
	ISNULL(t.BilledHours, 0) AS [Billed Hours],  
	t.BilledRate AS [Billed Rate],  
	ROUND(t.BilledHours * t.BilledRate, 2) AS [Billed Total Amount], 
	t.Comments, 
	Case t.OnHold When 1 then ''YES'' else ''NO'' end as [On Hold], 
	ps.ProjectStatus as [Project Status], 
	CASE p.NonBillable WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Non Billable Project], 
	CASE p.Active WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Active Project], 
	CASE t.Downloaded WHEN 1 THEN ''YES'' ELSE ''NO'' END as Downloaded, 
	v.InvoiceNumber as [Vendor Invoice Number], 
	Case When t.VoucherKey = 0 then ''Marked As Paid'' When t.VoucherKey > 0 then ''Paid'' else ''Not Paid'' end as [Paid Status], 
	i.InvoiceNumber as [Invoice Number], 
	Case When t.InvoiceLineKey IS NULL then 
		Case t.WriteOff When 1 then ''Write Off'' else ''Unbilled'' end 
		else ''Billed'' end as [Billing Status], 

	Case When t.InvoiceLineKey = 0 then 
		t.ActualHours else 0 end as [Marked Billed Hours], 

	Case When t.InvoiceLineKey = 0 then 
		ROUND(t.ActualRate * t.ActualHours, 2) else 0 end as [Marked Billed Total], 

	Case When t.WriteOff = 1 then 
		t.ActualHours else 0 end as [Write off Hours], 

	Case When t.WriteOff = 1 then 
		ROUND(t.ActualRate * t.ActualHours, 2) else 0	end as [Write off Total], 

	Case t.WriteOff 
		When 1 then t.DateBilled 
		else NULL 
	end as [Write Off Date], 

	Case When t.WIPPostingInKey = 0 then ''NO'' else ''YES'' end as [Posted Into WIP], 
	Case When t.WIPPostingOutKey = 0 then ''NO'' else ''YES'' end as [Posted Out Of WIP], 
	Case When t.Verified = 0 then ''NO'' else ''YES'' end as [Verified], 
	t.StartTime as [Start Time], 
	t.EndTime as [End Time], 
	t.StartTime as [Start Date Time], 
	t.EndTime as [End Date Time], 
	Case When t.InvoiceLineKey is null then 0 else ROUND(t.ActualRate * t.ActualHours, 2) - ISNULL(ROUND(t.BilledHours * t.BilledRate, 2), 0) end AS [Billed Difference], 
	ta.EstHours as [Budget Hours], 
	apr.UserName as [Current Approver], 
	t.DateBilled as [Date Billed], 
	wt.WorkTypeID as [Billing Item ID], 
	wt.WorkTypeName as [Billing Item Name], 
	wti.WorkTypeID as [Billing Title Item ID], 
	wti.WorkTypeName as [Billing Title Item Name], 
	ct.CompanyTypeName as [Client Company Type], 
	case when p.GLCompanySource = 0 then glcP.GLCompanyID else glc.GLCompanyID end as [Company ID], 
	case when p.GLCompanySource = 0 then glcP.GLCompanyName else glc.GLCompanyName end as [Company Name], 
	cl.ClassID as [Class ID], 
	cl.ClassName as [Class Name], 
	ucl.ClassID as [User Class ID], 
	ucl.ClassName as [User Class Name], 
	Case When t.TransferToKey IS NULL Then ''NO'' else ''YES'' end as [Transferred Out], 
	u.Title, 
	Cast(CONVERT(varchar(2), DATEPART(WEEK, t.WorkDate), 0) AS INT) AS [Date Worked Week],
	RIGHT(''0'' + CAST(DATEPART(WEEK, t.WorkDate) AS VARCHAR(2)), 2) AS [Date Worked Week Formatted], 
	Case p.BillingMethod When 1 then ''Time and Materials'' When 2 then ''Fixed Fee'' When 3 then ''Retainer'' end as [Project Billing Method], 
	p.StartDate as [Project Start Date], 
	p.CompleteDate as [Project Due Date], 
	p.ProjectCloseDate as [Project Close Date], 
		-- Budgeted data 
	p.EstHours + p.ApprovedCOHours as [Project Budget Hours], -- [Estimate Total Hours] 
	p.EstLabor + p.ApprovedCOLabor as [Project Budget Labor Gross], -- [Estimate Total Labor] 
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Project Total Budget wo Taxes], -- [Estimate Total] 
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Project Total Budget], --New field 
	pir.EstQty as [Budget Hours by Service],
	pir.EstGross as [Budget Gross by Service],
	pr.BilledAmount as [Project Amount Billed], 
	aa.Hours as [Allocated Hours], 
	p.ProjectKey, 
	case u.Contractor when 1 then ''YES'' ELSE ''NO'' end as [Contractor],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Salesperson Name], 
	CASE u.Active WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Active User], 
	t.LastModified as [Last Modified], 
	sg.GroupName as [Security Group], 
	u.Email as [User Email Address], 
	u.DateHired as [Date of Hire], 
	pbs.ProjectBillingStatus as [Project Billing Status],
	case  
		when ts.OnTime is null then '''' -- when the timesheet is not submitted or was created before issue 295216 
		when ts.OnTime = 0 then ''NO'' 
		else ''YES'' 
	end as [Time Sheet Submitted On Time], 
	case  
		when t.OnTime is null then '''' -- when the time entry was created before issue 295216 
		when t.OnTime = 0 then ''NO'' 
		else ''YES'' 
	end as [Time Entered On Time] ,
	Case cp.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active],
	Case When p.NonBillable = 1 or t.ActualRate = 0 then ''Non Billable'' else ''Billable'' end as [Billable],
	Case When t.InvoiceLineKey > 0 then 
		ISNULL(t.BilledHours, 0) else 0 end as [Billed on Invoice Hours], 
	Case When t.InvoiceLineKey > 0 then 
    	ROUND(ISNULL(t.BilledRate, 0) * ISNULL(t.BilledHours, 0), 2) else 0 end as [Billed on Invoice Amount], --Issue: 413912
	st.TaskName as [Summary Task Name],
	t.TaskKey,
	u.UserKey as EmployeeKey,
	s.HourlyCost as [Hourly Cost],
	r.Title as [Retainer Name],
	bg.BillingGroupCode as [Billing Group Code],
	bg.Description as [Billing Group Description],
	rd.DeliverableName as [Deliverable Name],
	ISNULL(ven.CompanyName, c2.CompanyName ) as [Vendor Name],
	ISNULL(cp.EstHours, 0) + ISNULL(cp.ApprovedCOHours, 0) as [Campaign Budget Hours],
	ISNULL(cs.EstHours, 0) + ISNULL(cs.ApprovedCOHours, 0) as [Campaign Segment Budget Hours],
	ISNULL(t.PauseHours, 0) as [Time Paused],
	ISNULL(tls.SegmentName,tls2.SegmentName) as [Timeline Segment],
	ISNULL(tls.SegmentColor, tls2.SegmentColor) as [Timeline Segment Color],
	ta.PlanStart as [Plan Start Date],
	ta.PlanComplete as [Plan Complete Date],
	ta.BaseStart as [Baseline Start Date],
	ta.BaseComplete as [Baseline Complete Date],
	ta.ActStart as [Actual Start Date],
	ta.ActComplete as [Actual Complete Date],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectNumber
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else pp.ProjectNumber
				end
	end  as [Planning Project Number],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectName
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else pp.ProjectName
				end
	end  as [Planning Project Name],
	Case ISNULL(p.PlanningProject, 0)
		When 1 Then p.ProjectNumber + '' - '' + p.ProjectName
		When 0 then
				case ISNULL(p.PlanningProjectKey, 0)
				When 0 then null else Case When pp.ProjectNumber is null then pp.ProjectName else pp.ProjectNumber + '' - '' + pp.ProjectName end
				end
	end  as [Planning Project Full Name],
	(Select Sum(Hours) from vTaskUserHour b (nolock)
		Where t.ProjectKey = b.ProjectKey and t.UserKey = b.UserKey and t.ServiceKey = b.ServiceKey and  DatePart(week, WorkDate) = DatePart(week,b.BucketStart) and YEAR(WorkDate) = year(b.BucketStart)) as [Assigned Week Hours]
	,CASE t.Overtime WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Overtime]
	,bb.Hours as [Budget Hours by Task]
	,con.UserName as [Company Owner]
	,ts.DateUnapproved as [Date And Time Unapproved]
	,u.HourlyRate as [Billable Rate]
	,l.LeadID as [Opportunity ID]
	,l.Subject as [Opportunity Name]
	,loc.Outcome as [Opportunity Outcome]
	,l.CurrentStatus as [Opportunity Next Steps]
	,lstage.LeadStageName as [Opportunity Stage]
	,lstatus.LeadStatusName as [Opportunity Status]
	,Case ISNULL(upf.TimesheetRequired, 0) When 1 then ''YES'' else ''NO'' end as [Time Sheet Required]
	,t.Source as [Source]

FROM  
	tPreference pref (NOLOCK)
	INNER JOIN tTimeSheet ts (NOLOCK) ON ts.CompanyKey = pref.CompanyKey   
	INNER JOIN tTime t (NOLOCK) ON ts.TimeSheetKey = t.TimeSheetKey     
	INNER JOIN tUser u (NOLOCK) ON t.UserKey = u.UserKey   
	LEFT OUTER JOIN tUserPreference upf (nolock) on u.UserKey = upf.UserKey
	LEFT OUTER JOIN tVoucher v (nolock) ON t.VoucherKey = v.VoucherKey 
	LEFT OUTER JOIN tCompany c (nolock) ON u.CompanyKey = c.CompanyKey  
	LEFT OUTER JOIN tProject p (nolock) ON t.ProjectKey = p.ProjectKey  
	LEFT OUTER JOIN tDepartment d (nolock) ON u.DepartmentKey = d.DepartmentKey 
	LEFT OUTER JOIN tDepartment d_t (nolock) ON t.DepartmentKey = d_t.DepartmentKey 
	LEFT OUTER JOIN tOffice o (nolock) ON u.OfficeKey = o.OfficeKey  
	LEFT OUTER JOIN tOffice oP (nolock) ON p.OfficeKey = oP.OfficeKey  
	LEFT OUTER JOIN tService s (nolock) ON t.ServiceKey = s.ServiceKey  
	LEFT OUTER JOIN tDepartment d_s (nolock) ON s.DepartmentKey = d_s.DepartmentKey  
	LEFT OUTER JOIN tTitle ti (nolock) ON t.TitleKey = ti.TitleKey 
	LEFT OUTER JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey 
	LEFT OUTER JOIN tClientProduct cpd (nolock) on p.ClientProductKey = cpd.ClientProductKey 
	LEFT OUTER JOIN tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey 
	LEFT OUTER JOIN tCompany cClient (nolock) ON p.ClientKey = cClient.CompanyKey  
	LEFT OUTER JOIN tUser sales (NOLOCK) ON cClient.SalesPersonKey = sales.UserKey 
	LEFT OUTER JOIN tTask ta (nolock) ON t.TaskKey = ta.TaskKey 
	LEFT OUTER JOIN tTask td (nolock) ON t.DetailTaskKey = td.TaskKey 
	LEFT OUTER JOIN tTaskAssignmentType tat (nolock) on ta.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey 
	LEFT OUTER JOIN tInvoiceLine il (nolock) on t.InvoiceLineKey = il.InvoiceLineKey 
	LEFT OUTER JOIN tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey 
	LEFT OUTER JOIN tWriteOffReason wor (nolock) on t.WriteOffReasonKey = wor.WriteOffReasonKey 
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey 
	left outer join tUser pc (nolock) on p.BillingContact = pc.UserKey 
	left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey 
	left outer join vUserName abk (nolock) on ts.ApprovedByKey = abk.UserKey 
	left outer join vUserName apr (nolock) on u.TimeApprover = apr.UserKey 
	LEFT OUTER JOIN vUserName spr (nolock) on u.SupervisorKey = spr.UserKey
	LEFT OUTER JOIN tWorkType wt (nolock) ON s.WorkTypeKey = wt.WorkTypeKey 
	LEFT OUTER JOIN tWorkType wti (nolock) ON ti.WorkTypeKey = wti.WorkTypeKey 
	LEFT OUTER JOIN tCompanyType ct (nolock) ON cClient.CompanyTypeKey = ct.CompanyTypeKey 
	LEFT OUTER JOIN tUser am (nolock) on p.AccountManager = am.UserKey 
	LEFT OUTER JOIN tUser pm (nolock) on p.ProjectManager = pm.UserKey
	LEFT OUTER JOIN tGLCompany glcP (nolock) ON p.GLCompanyKey = glcP.GLCompanyKey 
	LEFT OUTER JOIN tGLCompany glc (nolock) ON u.GLCompanyKey = glc.GLCompanyKey 
    LEFT OUTER JOIN tClass cl (nolock) ON p.ClassKey = cl.ClassKey 
	LEFT OUTER JOIN tClass ucl (nolock) ON u.ClassKey = ucl.ClassKey 
	LEFT OUTER JOIN tCompany pcn (nolock) ON cClient.ParentCompanyKey = pcn.CompanyKey 
	LEFT OUTER JOIN tService bs (nolock) ON t.BilledService = bs.ServiceKey 
	LEFT OUTER JOIN tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	LEFT OUTER JOIN tProjectRollup pr (nolock) ON p.ProjectKey = pr.ProjectKey 
	LEFT OUTER JOIN tAddress clad (nolock) ON cClient.BillingAddressKey = clad.AddressKey 
	LEFT OUTER JOIN (Select UserKey, TaskKey, Sum(Hours) as Hours from tTaskUser (nolock) Group By UserKey, TaskKey) as aa on t.UserKey = aa.UserKey and ISNULL(t.DetailTaskKey, t.TaskKey) = aa.TaskKey 
	LEFT OUTER JOIN (Select TaskKey, Sum(tEstimateTaskLabor.Hours) as Hours from tEstimateTaskLabor (nolock) inner join tEstimate (Nolock) on tEstimateTaskLabor.EstimateKey = tEstimate.EstimateKey where tEstimate.InternalStatus = 4 Group By TaskKey) as bb on ISNULL(t.DetailTaskKey, t.TaskKey) = bb.TaskKey 
	LEFT OUTER JOIN tSecurityGroup sg (nolock) on u.SecurityGroupKey = sg.SecurityGroupKey 
	LEFT OUTER JOIN tProjectItemRollup pir (nolock) on t.ProjectKey = pir.ProjectKey and t.ServiceKey = pir.EntityKey and pir.Entity = ''tService''
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	LEFT OUTER JOIN tTask st (nolock) on ta.SummaryTaskKey = st.TaskKey
	LEFT OUTER JOIN tRetainer r (nolock) on p.RetainerKey = r.RetainerKey 
	LEFT OUTER JOIN tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	LEFT OUTER JOIN tReviewDeliverable rd (nolock) on t.DeliverableKey = rd.ReviewDeliverableKey
	LEFT OUTER JOIN tCompany ven (nolock) ON v.VendorKey = ven.CompanyKey 
    LEFT OUTER JOIN tTimelineSegment tls (nolock) on td.TimelineSegmentKey = tls.TimelineSegmentKey
	LEFT OUTER JOIN tTimelineSegment tls2 (nolock) on ta.TimelineSegmentKey = tls2.TimelineSegmentKey
	LEFT OUTER JOIN tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey
	LEFT OUTER JOIN tCompany c2 (nolock) ON u.VendorKey = c2.CompanyKey 
	LEFT OUTER JOIN vUserName con (nolock) on cClient.ContactOwnerKey = con.UserKey 
	LEFT OUTER JOIN tLead l (nolock) on p.LeadKey = l.LeadKey
	LEFT OUTER JOIN tLeadOutcome loc (nolock) on l.LeadOutcomeKey = loc.LeadOutcomeKey
	LEFT OUTER JOIN tLeadStage lstage (nolock) on l.LeadStageKey = lstage.LeadStageKey
	LEFT OUTER JOIN tLeadStatus lstatus (nolock) on l.LeadStatusKey = lstatus.LeadStatusKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spConvertAppSeedSetting]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[spConvertAppSeedSetting]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spConvertAppSeedSetting]
(
	@LoadBeta int = 0
)
AS

/*
|| When      Who Rel      What
||  exec spConvertAppSeedSetting 1
|| Previous Comments moved to the end of this SP
|| 01/04/24  CRG 24.01.21 (644751)  Added submittedMeetingApprovals
|| 01/05/24  AMP 24.02.18 (661148)  Added Grid Options/Calendar Options headers to the Traffic Calendar
|| 02/07/24  RLB 24.03.17 (663123)  Added hint to myTasks Date range 
|| 02/09/24  CRG 24.03.17 (664035)  Added Meeting Approver to adminEmployees
|| 02/28/24  GAR 24.03.17 (665372)  Added Billing Method to the planningProjects grid
|| 03/04/24  GAR 24.04.14 (665346)  Added Billing Option to the planningProjects grid
|| 03/05/24  RLS 24.04.14 (662926)  Removed campBudgetProjectFullName field from the campBudget section
|| 04/10/24  CRG 24.05.19 (665914)  Added Constraint Name column to Staff Schedule Detail screens
|| 04/11/24  RLB 24.05.19 (668621)  Added Date Task Assigned to staffScheduleWeekDetail and staffScheduleDayDetail (669161) Task Description as well
|| 04/22/24  RLB 24.05.19 (670398)  Removed time section in trafficRM because it is not used on the page
|| 05/16/24  MFT 24.06.00 (672517)  Make Billing Today ProjectStatus and ProjectBillingStatus SelectList to match other screens and fix bug on TM dash
|| 06/03/24  CRG 24.07.14 (667422)  Added Scheduled Transactions to billingToday and purchasingToday
|| 06/06/24  RLS 24.07.14 (671824)  Added AllocatedRemaining to the productionDash section
|| 06/07/24  MCM 24.07.14 (650217)  Added Use Markup to the Broadcast and Print Orders
|| 06/19/24  RLB 24.07.14 (674309)  Added option to use month worked on gl fin drill down
|| 06/26/24  RLS 24.07.14 (675529)  Remove the Your Comments field from the Project Request Approval section
|| 06/27/24  RLB 24.07.14 (675370)  Added Filter for I am BM to productionDash
|| 06/28/24  AMP 24.08.18 (672267)  Added Client Project Number and Client Campaign Number to the Forecast Detail Grid
|| 07/11/24  GAR 24.08.18 (676173)  Added ProjectManager to all 4 system settings for billingToday_
|| 07/20/24  RLB 24.08.18 (679274)  Added Task Plan Complete Date to toDoBoard grouping optionsprjbudgetSettings
|| 08/01/24  RLB 24.09.15 (679468) add Pub/Station to billingTransactions
|| 08/14/24  RLB 24.09.15 (679831) added Project Allocated Hours Remaining to campaignBudget
|| 08/21/24  MCM 24.09.15 (681078) add GLC Exchange Rate to the jeDetail
|| 08/26/24  AMP 24.09.15 (663557) Added the Unapplied Amount to the Project Budget -> Advanced Billed Column drill-down
|| 08/29/24  AMP 24.10.20 (681440) Added Last Transaction Date to the Scheduled Transactions
|| 09/05/24  AMP 24.10.20 (681249) Added Sales Account to Client Billing - Labor Line Settings & Expense Line Settings
|| 09/19/24  RLB 24.10.20 (682495) Added Last Logged Out to adminEmployees
|| 09/19/24  RLS 24.10.20 (682428) Added OpenOrdersGross to the ProjectDash
|| 09/19/24  RLS 24.10.20 (682529) Added CreatedBy to the EmployeeDash
|| 09/27/24  RLB 24.10.20 (682076) Added assigned user col and grouping options on productionAssignment
|| 10/02/24  MCM 24.10.20 (680536) Added authorize.net column widths
|| 10/14/24  GAR 24.11.17 (684046) Added project color to the staff schedule grid
|| 10/15/24  GAR 24.11.17 (683966) Added ProjectColor to today.creatives
|| 10/16/24  GAR 24.11.17 (683246) Added billable and non-billable hours in timesheet approvals
|| 10/21/24  RLB 24.11.17 (685887) productionCampDash changed am an pm to select list to match page
|| 10/24/24  GAR 24.11.17 (683767) Removed Current Total Budget w/o Tax field from the Project Budget screen
|| 10/29/24  GAR 24.11.17 (665347) Added Revenue Forecasts to the notifications approvals window
|| 11/13/24  GAR 24.12.15 (683889) Adding system setting in My Settings to Allow Edit of Backup Approver
|| 11/14/24  RLB 24.12.15 (684868) added Shpw set baseline to projectSchedule
|| 11/14/24  RLB 24.12.15 (688036) fixed label on subject to changeRequestApprovals
|| 11/19/24  RLB 24.12.15 (688036) add column FutureLaborGrossRemaining to prjbudgetSettings
|| 11/20/24  RLB 24.12.15 (688466) added project name to the changeRequestApprovals
|| 11/27/24  RLB 24.12.15 (674309) removed month worked from financialGLDrillDown because the field is not pulled and does not exists on screen
|| 11/27/24  RLS 25.01.19 (685516) Added field prjScheduleBudgetLaborGross and prjScheduleAllocatedHoursGross
|| 12/06/24  RLB 25.01.19 (689358) billingWorksheetsApprovals added worksheet comment
|| 12/11/24  RLB 25.01.19 (687329) Added Default GL Company to grouping of adminEmployees
|| 12/26/24  RLS 25.01.19 (688836) Added new CONNECTIONS - Retainers section
|| 12/26/24  CRG 25.01.19 (685528) Added AssignedTemplatesOnly to projectAdd
|| 11/27/24  RLB 24.12.15 (691987) removed month worked from financialGLDrillDown because the field is not pulled and does not exists on screen. There was an if and month worked was not removed from that when the above fix was done
|| 01/13/25  AMP 25.03.16 (687792) Added ''Entered By'' to Unapproved Transactions and Unposted Transactions (Journal Entries)
|| 01/22/25  MCM 25.02.x  (686981) Added ''Unapplied Amount'' to the Unposted Transactions
|| 01/29/25  RLB 25.02.16 (688067) adding new fields CurrentBudgetExpenseQuantity and ActualQuantity to prjbudgetSettings
|| 02/04/25  CRG 25.02.16 (685937) Added Campaign Snapshot to the Dashboard
|| 02/12/25  RLB 25.03.16 (692356) added hide zero option to both staffScheduleDayDetail and staffScheduleWeekDetail
|| 02/13/25  RLB 25.03.16 (688067) adding new fields CurrentBudgetExpenseQuantity and ActualQuantity to prjbudgetSettings item and type grids
|| 03/03/25  AMP 25.04.20 (695658) Added review Due Date for Billing Worksheet Approvals
|| 04/01/25  AMP 25.04.20 (697413) Added Posting Date to Client Billing->Billing Transaction Settings
|| 04/07/25  AMP 25.05.18 (697727) Added Media Plan Full Name to Accrued Order Detail
|| 04/16/25  RLB 25.05.18 (699375) Added Office to group by to productionDash and productionDashPlanning
|| 04/17/25  CRG 25.05.18 (695993) Added campaignBudgetAnalysis settings
|| 04/17/25  MCM 25.06.x  (681626) Added ApprovalStatus to connectionsInvoices
|| 04/24/25  MCM 25.06.x  (696669) added campaignID to the forecastdetail
|| 04/25/25  CRG 25.05.18 (695993) Modified the title of the campaignBudgetAnalysis group
|| 05/14/25  CRG 25.06.15 (701167) Changed the default setting for AllowCompletionPercentages on myTasks
|| 06/11/25  AMP 25.07.20 (699885) Added settings for Apply Advance Bill 
|| 06/13/25  GAR 25.07.20 (703925) Added Office Name to My Projects Settings
|| 06/18/25  RLB 25.07.20 (704114) Added Display Time Entry Comments to all today pages
|| 07/17/25  AMP 25.05.18 (692056) Added a new column called ''Master'' to the Worksheets to Review, and the Worksheets to Approve pages
|| 08/07/25  RLB 25.09.14 (707450) Added Office Name to productionCampDash
|| 08/11/25  RLB 25.09.14 (708552) Added removed Order number option since it is not a column and is defaulted on for boTraffic and ioTraffic
|| 08/13/25  RLB 25.10.19 (708111) Added Campaign Budget Labor Remaining and Campaign Budget Expense Remaining to campaignBudgetAnalysis
|| 08/19/25  RLB 25.10.19 (707695) Added Percentage of Allocated to the prjbudgetSettings
|| 08/19/25  RLS 25.09.14 (708120) Added Conversation Count to the mytask section
|| 08/25/25  AMP 25.08.17 (709683) Added UpdateStatusNotes, UpdateClientNotes, UpdateDetailNotes to Production Dash
|| 09/03/25  GAR 25.09.21 (709974) Changed the default on edit column sets on campaign schedules to be true
|| 09/16/25  RLS 25.11.16 (711029) Added activecolumn to Admin Screens - Opportunity Outcomes
|| 10/02/25  GAR 25.11.16 (710278) Adding Transaction Grid Settings to the Campaign Billing screen like we have in projects billing
|| 10/31/25  RLB 25.12.14 (714339) Added copy Specs to project Add
|| 11/5/25   GAR 25.11.16 (714330) Change PO Item Name to Item Description
|| 12/11/25  RLB 26.01.18 (717026) added HoursBilled from the rollup to productionDash
|| 12/12/25  MCM 26.01.18 (698136) added IncrementDespositID to the receiptAdd
|| 12/18/25  RLS 26.01.18 (715665) Added Hours After Writeoff to productionDash
|| 12/29/25  GAR 26.02.15 (718310) Added Actual Hours and Time Comments to MyTasks grid settings
|| 01/13/26  RLS 26.02.15 (718167) Added AutoExpandTaskGrid to the trafficRM settings
|| 01/19/26  AMP 26.03.15 (719364) Added Station/Publication to CONNECTIONS - Vendor Invoices
|| 01/27/26  RLB 26.02.15 (718216) Added Media Plans to Global Search
|| 02/02/26  RLS 26.03.15 (718905) Added Originated By and Created By to the coltodoBoard section
|| 02/11/26  GAR 26.03.15 (721898) Added Actual Hours and Time Comments to MyTasks grid settings default load
|| 03/02/26  RLB 26.04.19 (722093) added Variance to clientInvoiceExpense
|| 03/03/26  GAR 26.04.19 (723387) Changed the default columns for the MyTasks grid settings default load
|| 03/17/26  RLS 26.04.19 (722453) Added taskFullName to the deliverable Approval section
|| 04/02/26  GAR 26.05.17 (722819) Added TotalGrossUnbilled to Campaign Billing Detail Settings
|| 04/10/26  GAR 26.05.17 (723471) Added settings in my tasks for ShowAccountManager and ShowProjectManager
|| 04/15/26  GAR 26.05.17 (726555) Added DeliverableCount to the project schedule grid
|| 04/27/26  GAR 26.05.17 (727081) Added BudgetRemainingHours to the project schedule grid
|| 05/07/26  MCM 26.06.x  (719447) Added AdjustmentPct and AdjustmentGLAccountKey parameters to support service adjustments 
|| 05/12/26  GAR 26.06.14 (728245) Added Description to the Pay Credit Card Charges screen
|| 05/15/26  AMP 26.06.14 (724706) Added Billable to the Insertion Orders and Broadcast Orders
|| 05/07/26  MCM 26.06.x  (719447) Added AdjustmentPct and AdjustmentGLAccountKey parameters to support item adjustments 
|| 05/26/26  RLS 26.06.14 (729061) Added Billed Variance to the clientInvoiceExpense section
|| 06/02/26  GAR 26.07.19 (728472) Added Posting Date to project billing grid settings - unbilled only
|| 06/15/26  RLB 26.07.19 (729936) Adding option Use Task Count instead of Hours to MyTasks
|| 07/22/26  MAS 26.08.16 (733330) Added projectConversations settings group (HideAISummarize) to hide the AI Summarize button; reached from Admin > System Setup > Conversation Settings
 */

-- 3 grids are different if the GL companies have foreign currencies
declare @GLCompaniesWithForeignCurrencies int
select @GLCompaniesWithForeignCurrencies = 1

Delete tAppSettingGroup
Delete tAppSetting


/*************************************************************************************************************************
My Settings
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''mySettings'', ''System Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mySettings'', ''H1'', 0, ''My Settings Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''mySettings'', ''EditContactInfo'', 1, ''Allow Editing of Contact Info'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mySettings'', ''EditLoginInfo'', 2, ''Allow Editing of Login Info'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mySettings'', ''EditDefaultSettings'', 3, ''Allow Editing of Default Settings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mySettings'', ''EditBackupApprover'', 4, ''Allow Editing of Backup Approver'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
My Tasks
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''myTasks'', ''System Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H1'', 0, ''My Task Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required)
Values (''myTasks'', ''DateOption'', 1, ''Date Range'', ''1'', ''Due on or before a week from Today'', ''lookup'', ''Due on or before Today:0|Due on or before a week from Today:1|Due on or before 2 weeks from Today:2|Start on or before Today:3|Start on or before a week from Today:4|Start on or before 2 weeks from Today:5|All:6'', NULL, ''When using "All" as the Date Range and when "Completed Predecessors Only" is not checked the tasks shown will be limited to 6 weeks out from today. Any tasks with a start date greater than 6 weeks from today will not show.'', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''OpenToDo'', 2, ''Open To Do Items Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''PredCompOnly'', 3, ''Completed Predecessors Only'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''OpenDeliverablesOnly'', 4, ''Open Deliverables Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''MoreTasks'', 5, ''Assign New Tasks'', ''1'', NULL, ''checkbox'', NULL, NULL, ''Allow users to assign tasks to themselves'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''myTasks'', ''AssignOtherPeoplesTasks'', 6, ''Assign myself to other people''''s tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Allow users to assign others peoples tasks to themselves'', ''MoreTasks'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ProjectType'', 7, ''Project Type'', ''-1'', ''All'', ''selectlist'', NULL, ''selectlist.ProjectType'', NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ShowAccountManager'', 8, ''Show Account Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ShowProjectManager'', 9, ''Show Project Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H2'', 10, ''Display Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''GroupBy'', 11, ''Group By'', ''PlanComplete'', ''Due Date'', ''lookup'', ''No Grouping:NoGrouping|Priority:PriorityName|Project:ProjectFullName|Campaign:CampaignFullName|Campaign Segment:SegmentName|Client:ClientFullName|Task Name:TaskName|Task Type:TaskTypeDesc|Project Status:ProjectStatus|Project Type:ProjectTypeName|Account Manager:AccountManagerName|Summary Task:SummaryTaskName|Due Date:PlanComplete|Start Date:PlanStart|Project Manager:ProjectManagerName|Assignment Status:TaskUserStatusName|Timeline Segment:TimelineSegmentName|Product Name:ProductName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''GroupByDir'', 12, ''Group Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''SortBy'', 13, ''Sort By'', ''Priority'', ''Priority'', ''lookup'', ''Project Number:ProjectNumber|Campaign ID:CampaignID|Campaign Segment:SegmentName|Client:ClientID|Status:TaskStatus|Priority:Priority|Task:TaskName|Task Type:TaskTypeDesc|Start Date:PlanStart|Due Date:PlanComplete|Due Time:DueBy|Percent Complete:PercComp|Account Manager:AccountManagerName|Summary Task:SummaryTaskName|Open ToDo Items:OpenToDos|Project Manager:ProjectManagerName| Timeline Segment:TimelineSegmentName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''SortByDir'', 14, ''Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ShowCardView'', 15, ''Show Card View'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ShowGridView'', 16, ''Show Grid View'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ShowTileView'', 17, ''Show Tile View'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Date range, grouping and sorting options do not apply to Tile View.'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''myTasks'', ''ShowAssignmentZeroAllocated'', 18, ''Show Assignments With Zero Allocated'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will show task assignments regardless of how many hours are assigned. Use this option if you do not allocate hours to people.'', ''ShowTileView'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''DisableDragging'', 19, ''Disable Dragging Tiles'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''AllowCompletionPercentages'', 20, ''Allow Completion Percentages'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''HandOffTasks'', 21, ''Hand Off Tasks'', ''1'', NULL, ''checkbox'', NULL, NULL, ''Allow users to hand off tasks'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''UseTaskCountNotHours'', 22, ''Use Task Count Instead of Hours'', ''0'', NULL, ''checkbox'', NULL, null, ''This will show user totals based on task count instead of hours on tile view'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''myTasks'', ''grdMyTasksCols'', 23, ''Grid View Columns'', ''mytaskProjectFullName,mytaskTaskIDName,mytaskTaskStatus,mytaskActualHours,mytaskTimeComments,mytaskPercComp,mytaskRemainingHours,mytaskPlanStart,mytaskPlanComplete,mytaskDueBy'', NULL, ''grid'', 

''[{id:"mytaskProjectFullName", label:"Project"},
	{id:"mytaskTaskIDName", label:"Task"},
	{id:"mytaskTaskStatus", label:"Status"},
	{id:"mytaskOpenToDos", label:"Open ToDos"},
	{id:"mytaskOpenDeliverables", label:"Open Deliverables"},
	{id:"mytaskPlanStart", label:"Start"},
	{id:"mytaskPlanComplete", label:"Due"},
	{id:"mytaskPercComp", label:"% Complete"},
	{id:"mytaskDueBy", label:"Due By"},
	{id:"mytaskComments", label:"Task Status Comments"},
	{id:"mytaskRemainingHours", label:"Remaining"},
	{id:"mytaskAssignedHours", label:"Assigned Hours"},
	{id:"mytaskProjectNumber", label:"Project Number"},
	{id:"mytaskCampaignFullName", label:"Campaign"},
	{id:"mytaskCampaignSegmentName", label:"Campaign Segment"},
	{id:"mytaskAccountManagerName", label:"Account Manager"},
	{id:"mytaskProjectManagerName", label:"Project Manager"},
	{id:"mytaskProjectTypeName", label:"Project Type"},
	{id:"mytaskProjectName", label:"Project Name"},
	{id:"mytaskProjectStatus", label:"Project Status"},
	{id:"mytaskOnHold", label:"On Hold"},
	{id:"mytaskClientID", label:"Client ID"},
	{id:"mytaskClientName", label:"Client Name"},
	{id:"mytaskTaskDescription", label:"Description"},
	{id:"mytaskTaskTypeDesc", label:"Task Type"},
	{id:"mytaskTaskID", label:"Task ID"},
	{id:"mytaskPrimaryContact", label:"Primary Contact"},
	{id:"mytaskPhone1", label:"Phone"},
	{id:"mytaskEmail", label:"Email"},
	{id:"mytaskPhone", label:"Company Phone"},
	{id:"mytaskActStart", label:"Actual Start"},
	{id:"mytaskPriorityName", label:"Priority"},
	{id:"mytaskSummaryTaskID", label:"Summary Task ID"},
	{id:"mytaskSummaryTaskName", label:"Summary Task name"},
	{id:"mytaskServiceCode", label:"Service Code"},
	{id:"mytaskServiceDescription", label:"Service Description"},
	{id:"mytaskServiceFullName", label:"Service Full Name"},
	{id:"mytaskPredecessorsComplete", label:"Predecessor Complete"},
	{id:"mytaskBaseStart", label:"Orig Start"},
	{id:"mytaskBaseComplete", label:"Orig Complete"},
	{id:"mytaskProjectStartDate", label:"Project Start Date"},
	{id:"mytaskTaskUserStatusName", label:"Assignment Status"},
	{id:"mytaskProjectCompleteDate", label:"Project Complete Date"},
	{id:"mytaskKeyPeople1", label:"Key Person 1"},
	{id:"mytaskKeyPeople2", label:"Key Person 2"},
	{id:"mytaskKeyPeople3", label:"Key Person 3"},
	{id:"mytaskKeyPeople4", label:"Key Person 4"},
	{id:"mytaskKeyPeople5", label:"Key Person 5"},
	{id:"mytaskKeyPeople6", label:"Key Person 6"},
	{id:"mytaskNextSteps", label:"Next Steps"},
	{id:"mytaskConversationCount", label:"Conversation Count"},
	{id:"mytaskProjectColor", label:"Project Color"},
	{id:"mytaskActualHours", label:"Actual Hours"},
	{id:"mytaskTimeComments", label:"Time Comments"}]''

	 , NULL, NULL, ''Project'', ''Project'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''AutoExpandTaskGrid'', 24, ''Auto Expand Tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H3'', 25, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''myTasks'', ''DailyFeed'', 26, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H6'', 27, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''myTasks'', ''SortConversations'', 28, ''Sort Conversations'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''FilterProjectTab'', 29, ''Only show Project Conversations sent to me'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H4'', 30, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''hideSchedule'', 31, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''HideEnterTime'', 32, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''DisplayTimeEntries'', 33, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''myTasks'', ''DisplayTimeEntriesComments'', 34, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''IncludePublicMeetings'', 35, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H5'', 36, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''ShowInOutBoard'', 37, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Time Entry
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''timeEntry'', ''Time Entry Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''DefaultProjects'', 1, ''Default Projects From Assignments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''DefaultSystemLog'', 2, ''Default Projects Touched Today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''ShowRateLevel'', 3, ''Show Rate Level'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''OpenExpanded'', 4, ''Expand Time Sheet When Opened'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''ShowZeroHourTimesheets'', 5, ''Show 0 Hour Time Sheets'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''CopyTimeSheets'', 6, ''Allow Copy Time Sheet'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''H2'', 7, ''Display Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''GroupBy'', 8, ''Group By'', ''NoGrouping'', ''No Grouping'', ''lookup'', ''No Grouping:NoGrouping|Project:ProjectFullName|Client:ClientName|Campaign:CampaignFullName|Task Name:TaskName|Project Status:ProjectStatus|Project Type:ProjectTypeName|Account Manager:AccountManagerName|Project Manager:ProjectManagerName'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''hideWeekend'', 9, ''Hide Weekend Days'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timeEntry'', ''showStartEnd'', 10, ''Show Start Time, End Time, and Paused Hours in Day View grid'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Marketing Groups
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''marketinggroups'', ''Marketing Group Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''marketinggroups'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''marketinggroups'', ''grdListCols'', 1, ''Columns'', ''UserFullName,UserPhone1,UserEmail,CompanyName,ContactAddress1,ContactCity,ContactState,ContactPostalCode'', NULL, ''grid'', 
''[	{id:"UserFullName", label:"Contact Full Name"},
	{id:"UserPhone1", label:"Contact Phone 1"},
	{id:"UserEmail", label:"Contact Email"},
	{id:"CompanyName", label:"Company Name"},
	{id:"ContactAddress1", label:"Contact Address1"},
	{id:"ContactAddress2", label:"Contact Address2"},
	{id:"ContactAddress3", label:"Contact Address3"},
	{id:"ContactCity", label:"Contact City"},
	{id:"ContactState", label:"Contact State"},
	{id:"ContactPostalCode", label:"Contact PostalCode"},
	{id:"ContactCountry", label:"Contact Country"},
	{id:"CompanyMailingAddress1", label:"Company Mailing Address 1"},
	{id:"CompanyMailingAddress2", label:"Company Mailing Address 2"},
	{id:"CompanyMailingAddress3", label:"Company Mailing Address 3"},
	{id:"CompanyMailingCity", label:"Company Mailing City"},
	{id:"CompanyMailingState", label:"Company Mailing State"},
	{id:"CompanyMailingPostalCode", label:"Company Mailing Postal Code"},
	{id:"CompanyMailingCountry", label:"Company Mailing Country"},
	{id:"CompanyType", label:"Company Type"},
	{id:"CompanyWebSite", label:"Company WebSite"},
	{id:"CompanyMainPhone", label:"Company Main Phone"},
	{id:"CompanyMainFax", label:"Company Main Fax"},
	{id:"CompanySource", label:"Company Source"},
	{id:"UserFirstName", label:"Contact First Name"},
	{id:"UserLastName", label:"Contact Last Name"},
	{id:"UserSalutation", label:"Contact Salutation"},
	{id:"UserPhone2", label:"Contact Phone 2"},
	{id:"UserCell", label:"Contact Cell"},
	{id:"UserFax", label:"Contact Fax"},
	{id:"UserTitle", label:"Contact Title"},
	{id:"UserRole", label:"Contact Role"},
	{id:"Active", label:"Active"},
	{id:"ContactOwner", label:"Contact Owner"},
	{id:"AccountManager", label:"Account Manager"},
	{id:"IsPrimaryContact", label:"Is Primary Contact"},
	{id:"LastSyncMessage", label:"Last Sync Message"}
 ]''
 , NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
Misc Cost
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''misccosts'', ''Misc Cost Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''misccosts'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''misccosts'', ''grdMiscCostCols'', 1, ''Columns'', ''expenseDate,task,item,shortDescription,gridMiscCostTotalCost,gridMiscCostTotalGross'', NULL, ''grid'', 
''[	{id:"expenseDate", label:"Date"},
	{id:"task", label:"Task"},
	{id:"item", label:"Item"},
	{id:"shortDescription", label:"Description"},
	{id:"miscCostClass", label:"Class"},
	{id:"miscCostDepartment", label:"Department"},
	{id:"miscCostExchangeRate", label:"Exchange Rate"},
	{id:"miscCostQuantity", label:"Quantity"},
	{id:"miscCostUnitCost", label:"Unit Cost"},
	{id:"gridMiscCostTotalCost", label:"Net"},
	{id:"miscCostBillable", label:"Billable"},
	{id:"miscCostMarkup", label:"Markup"},
	{id:"misCostUnitRate", label:"Unit Rate"},
	{id:"gridMiscCostTotalGross", label:"Gross"},
	{id:"miscCostComments", label:"Comments"},
	{id:"miscCostStatus", label:"Status"},
	{id:"miscCostAddedBy", label:"Added By"},
	{id:"miscCostUnitDesc", label:"Unit Description"},
	{id:"miscCostScheduled", label:"Scheduled"}
 ]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Expense Report
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''expenses'', ''Expense Receipt Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''expenses'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''expenses'', ''grdExpenseReceiptsCols'', 1, ''Columns'', ''expenseDate,project,task,item,description,actualUnitCost,actualCost,comments'', NULL, ''grid'', 

''[	{id:"expenseDate", label:"Date"},
	{id:"project", label:"Project"},
	{id:"task", label:"Task"},
	{id:"item", label:"Item"},
	{id:"description", label:"Description"},
	{id:"quantity", label:"Quantity"},
	{id:"actualUnitCost", label:"Unit Cost"},
	{id:"actualCost", label:"Net"},
	{id:"comments", label:"Comments"},
	{id:"billable", label:"Billable"},
	{id:"gross", label:"Total Gross"},
	{id:"markup", label:"Mark Up"},
	{id:"paperReceipt", label:"Paper Receipt"},
	{id:"taxable", label:"Tax 1"},
	{id:"taxable2", label:"Tax 2"},
	{id:"actualCostWithTaxes", label:"Total Net With taxes"},
	{id:"unitRate", label:"Unit Rate"},
	{id:"attachmentCount", label:"Attachment Count"},
	{id:"office", label:"Office"},
	{id:"class", label:"Class"},
	{id:"er_ExpenseGLAccountKey", label:"Expense GL Account"}
 ]''
	 , NULL, NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''expenses'', ''GroupByDate'', 1, ''Group By Date'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)




/*************************************************************************************************************************
Project Estimate List
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateList'', ''Estimate List Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateList'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''estimateList'', ''gridCols'', 1, ''Columns'', ''EstimateFullName,EstimateNumber,ChangeOrder,DateAdded,EnteredByName,ExternalApprovalStatus,ExternalApproverName,InternalApprovalStatus,EstimateTotal'', NULL, ''grid'', 
''[	{id:"ChangeOrder", label:"Change Order"},
	{id:"DateAdded", label:"Date Added"},
	{id:"EnteredByName", label:"Entered By"},
	{id:"EstimatedDeliveryDate", label:"Estimated Delivery Date"},
	{id:"EstTypeDesc", label:"Est Type"},
	{id:"EstimateFullName", label:"Estimate Name"},
	{id:"EstimateDescription", label:"Estimate Description"},
	{id:"EstimateNumber", label:"Estimate Number"},
	{id:"ExternalApprovalStatus", label:"External Approval Status"},
	{id:"ExternalApproverName", label:"External Approver Name"},
	{id:"ExternalComments", label:"External Comments"},
    {id:"IncludeInForecast", label:"Include In Forecast"},
	{id:"InternalApprovalStatus", label:"Internal Approval Status"},
	{id:"InternalApproverName", label:"Internal Approver Name"},
	{id:"InternalComments", label:"Internal Comments"},
	{id:"Revision", label:"Revision"},
	{id:"EstimateTotal", label:"Estimate Total"},
	{id:"ExpenseGross", label:"Expense Gross"},
	{id:"ExpenseNet", label:"Expense Net"},
	{id:"Hours", label:"Hours"},
	{id:"LaborGross", label:"Labor Gross"},
	{id:"LaborNet", label:"Labor Net"},
	{id:"SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"TaxableTotal", label:"Taxable Total"},
	{id:"Total", label:"Total"},
	{id:"LaborTaxableDesc", label:"Labor Taxable"},
	{id:"SelectedOption", label:"Selected Option"},
	{id:"OptionName", label:"Option Name"},
	{id:"InternalApprovalDate", label:"Internal Approval Date"},
	{id:"ApprovedTotal", label:"Approved Total"}
 ]''
	 , NULL, NULL, null, NULL)


INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateExpense'', ''Estimate Expense Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateExpense'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''estimateExpense'', ''grdExpenseEstimateCols'', 1, ''Columns'', ''task_e,item_e,vendor_e,quantity_e,unitCost_e,totalCost_e,markup_e,gross_e'', NULL, ''grid'', 

''[	{id:"task_e", label:"Task"},
	{id:"line", label:"Line"},
	{id:"segment_e", label:"Segment"},
	{id:"item_e", label:"Item"},
	{id:"vendor_e", label:"Vendor"},
	{id:"vendorcurrency_e", label:"Vendor Currency"},
	{id:"description_e", label:"Description"},
	{id:"quantity_e", label:"Quantity"},
	{id:"unitCost_e", label:"Unit Cost"},
	{id:"totalCost_e", label:"Net"},
	{id:"billable_e", label:"Billable"},
	{id:"gross_e", label:"Gross"},
	{id:"markup_e", label:"Markup"},
	{id:"uom_e", label:"UOM"},
	{id:"uom2_e", label:"UOM 2"},
	{id:"uom3_e", label:"UOM 3"},
	{id:"uom4_e", label:"UOM 4"},
	{id:"uom5_e", label:"UOM 5"},
	{id:"uom6_e", label:"UOM 6"},
	{id:"taxable_e", label:"Tax 1"},
	{id:"taxable2_e", label:"Tax 2"},
	{id:"unitRate_e", label:"Unit Rate"},
	{id:"longdescription_e", label:"Long Description"},
	{id:"quantity2_e", label:"Quantity 2"},
	{id:"quantity3_e", label:"Quantity 3"},
	{id:"quantity4_e", label:"Quantity 4"},
	{id:"quantity5_e", label:"Quantity 5"},
	{id:"quantity6_e", label:"Quantity 6"},
	{id:"unitCost2_e", label:"Unit Cost 2"},
	{id:"unitCost3_e", label:"Unit Cost 3"},
	{id:"unitCost4_e", label:"Unit Cost 4"},
	{id:"unitCost5_e", label:"Unit Cost 5"},
	{id:"unitCost6_e", label:"Unit Cost 6"},
	{id:"totalCost2_e", label:"Net 2"},
	{id:"totalCost3_e", label:"Net 3"},
	{id:"totalCost4_e", label:"Net 4"},
	{id:"totalCost5_e", label:"Net 5"},
	{id:"totalCost6_e", label:"Net 6"},
	{id:"gross_e2", label:"Gross 2"},
	{id:"gross_e3", label:"Gross 3"},
	{id:"gross_e4", label:"Gross 4"},
	{id:"gross_e5", label:"Gross 5"},
	{id:"gross_e6", label:"Gross 6"},
	{id:"markup2_e", label:"Markup 2"},
	{id:"markup3_e", label:"Markup 3"},
	{id:"markup4_e", label:"Markup 4"},
	{id:"markup5_e", label:"Markup 5"},
	{id:"markup6_e", label:"Markup 6"},
	{id:"unitRate2_e", label:"Unit Rate 2"},
	{id:"unitRate3_e", label:"Unit Rate 3"},
	{id:"unitRate4_e", label:"Unit Rate 4"},
	{id:"unitRate5_e", label:"Unit Rate 5"},
	{id:"unitRate6_e", label:"Unit Rate 6"},
	{id:"comments_e", label:"Comments"}
 ]''
	 , NULL, NULL, null, NULL)



/*************************************************************************************************************************
Forecast Detail Grid
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''forecastDetails'', ''Forecast Details Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''forecastDetails'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''forecastDetails'', ''grdForecastDetail'', 1, ''Columns'', ''fdetail_status,fdetail_date,fdetail_months,fdetail_currencyid,fdetail_billingmethod,fdetail_percent,fdetail_total,fdetail_prior,fdetail_bill,fdetail_monthcols,fdetail_next,fdetail_reviewcomp,fdetail_client,fdetail_manager,fdetail_office,fdetail_type,fdetail_est,fdetail_regen,fdetail_clientprojnum,fdetail_clientcampnum'', NULL, ''grid'', 

''[	{id:"fdetail_status", label:"Status"},
	{id:"fdetail_date", label:"Start Date"},
	{id:"fdetail_projectduedate", label:"Project Due Date"},
	{id:"fdetail_months", label:"Number of Months"},
	{id:"fdetail_currencyid", label:"Currency"},
	{id:"fdetail_billingmethod", label:"Billing Method"},
	{id:"fdetail_percent", label:"Probability"},
	{id:"fdetail_totalbefore", label:"Total Before %"},
	{id:"fdetail_total", label:"Total"},
	{id:"fdetail_prior", label:"Prior Months"},
	{id:"fdetail_bill", label:"Act Billing"},
	{id:"fdetail_monthcols", label:"Monthly Cols"},
	{id:"fdetail_next", label:"Next 12 months"},
	{id:"fdetail_reviewcomp", label:"Reviewed"},
	{id:"fdetail_client", label:"Client"},
	{id:"fdetail_manager", label:"Account Manager"},
	{id:"fdetail_office", label:"Office"},
	{id:"fdetail_type", label:"Detail Type"},
	{id:"fdetail_projtype", label:"Project Type"},
	{id:"fdetail_est", label:"From Estimate"},
	{id:"fdetail_regen", label:"Regenerate Needed?"},
	{id:"fdetail_project_manager", label:"Project Manager"},
	{id:"fdetail_total_budget", label:"Total Budget"},
	{id:"fdetail_projstatus", label:"Project Status"},
	{id:"fdetail_clientprojnum", label:"Client Project Number"},
	{id:"fdetail_clientcampnum", label:"Client Campaign Number"},
	{id:"fdetail_campaignid", label:"Campaign ID"}
 ]''
	 , NULL, NULL, null, NULL)

	 
/*************************************************************************************************************************
Purchase Orders
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''poEdit'', ''Purchase Order Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''poEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''poEdit'', ''SpecSheets'', 1, ''Show Spec Sheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''poEdit'', ''Attachments'', 2, ''Show Attachments'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''poEdit'', ''grdPurchaseOrderDetail'', 1, ''Columns'', ''pod_ProjectKey,pod_ItemKey,pod_Quantity,pod_UnitCost,pod_TotalCost,pod_Markup,pod_GrossAmount'', NULL, ''grid'', 

''[	{id:"pod_LineNumber", label:"Line Number"},
	{id:"pod_LinkID", label:"Link ID"},
	{id:"pod_ProjectKey", label:"Project"},
	{id:"pod_TaskKey", label:"Task"},
	{id:"pod_ClassKey", label:"Class"},
	{id:"pod_ItemKey", label:"Item ID"},
	{id:"pod_OfficeKey", label:"Office"},
	{id:"pod_DepartmentKey", label:"Department"},
	{id:"pod_ShortDescription", label:"Item Description"},
	{id:"pod_LongDescription", label:"Standard Description"},
	{id:"pod_Quantity", label:"Quantity"},
	{id:"pod_UnitCost", label:"Unit Cost"},
	{id:"pod_TotalCost", label:"Net"},
	{id:"pod_UnitDescription", label:"Unit Description"},
	{id:"pod_Markup", label:"Markup"},
	{id:"pod_Billable", label:"Billable"},
	{id:"pod_GrossAmount", label:"Gross"},
	{id:"pod_AppliedCost", label:"Applied Cost"},
	{id:"pod_AmountBilled", label:"Amount Billed"},
	{id:"pod_AccruedCost", label:"Accrued Cost"},
	{id:"pod_DateBilled", label:"Date Billed"},
	{id:"pod_Closed", label:"Closed"},
	{id:"pod_Taxable", label:"Taxable"},
	{id:"pod_Taxable2", label:"Taxable2"},
	{id:"pod_BilledComment", label:"Billed Comment"},
	{id:"pod_TransferComment", label:"Transfer Comment"},
	{id:"pod_UnitRate", label:"Unit Rate"},
	{id:"pod_SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"pod_SalesTax1Amount", label:"Sales Tax1 Amount"},
	{id:"pod_SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"pod_OtherSalesTaxAmount", label:"Other Sales Tax Amount"}
 ]''
	 , NULL, NULL, null, NULL)

 
/*************************************************************************************************************************
Insertion Orders
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''ioEdit'', ''Insertion Order Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''ioEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''ioEdit'', ''SpecSheets'', 1, ''Show Spec Sheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''ioEdit'', ''Attachments'', 2, ''Show Attachments'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''ioEdit'', ''grdPurchaseOrderDetail'', 1, ''Columns'', ''pod_Actions,pod_DetailOrderDate,pod_ItemKey,pod_ShortDescription,pod_GrossAmount,pod_Markup,pod_TotalCost,pod_LineNumber,pod_AdjustmentNumber'', NULL, ''grid'', 

''[	{id:"pod_LineNumber", label:"Line #"},
    {id:"pod_AdjustmentNumber", label:"Adj #"},
	{id:"pod_LinkID", label:"Link ID"},
	{id:"pod_ReasonID", label:"Revision Reason"},
	{id:"pod_Actions", label:"Actions"},
	{id:"pod_ProjectKey", label:"Project"},
	{id:"pod_TaskKey", label:"Task"},
	{id:"pod_ClassKey", label:"Class"},
	{id:"pod_ItemKey", label:"Item ID"},
	{id:"pod_OfficeKey", label:"Office"},
	{id:"pod_DepartmentKey", label:"Department"},
	{id:"pod_ShortDescription", label:"Item Name (Ad Number/Caption)"},
	{id:"pod_LongDescription", label:"Standard Description"},
	{id:"pod_Quantity", label:"Quantity"},
	{id:"pod_TotalCost", label:"Net"},
	{id:"pod_MaterialsSent", label:"Materials Sent"},
	{id:"pod_MaterialsSentDate", label:"Materials Sent Date"},
	{id:"pod_Billable", label:"Billable"},
	{id:"pod_UnitDescription", label:"Unit Description"},
	{id:"pod_Markup", label:"Commission"},
	{id:"pod_GrossAmount", label:"Gross"},
	{id:"pod_AppliedCost", label:"Applied Cost"},
	{id:"pod_AmountBilled", label:"Amount Billed"},
	{id:"pod_AccruedCost", label:"Accrued Cost"},
	{id:"pod_DateBilled", label:"Date Billed"},
	{id:"pod_Closed", label:"Closed"},
	{id:"pod_Taxable", label:"Taxable"},
	{id:"pod_Taxable2", label:"Taxable2"},
	{id:"pod_BilledComment", label:"Billed Comment"},
	{id:"pod_TransferComment", label:"Transfer Comment"},
	{id:"pod_SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"pod_SalesTax1Amount", label:"Sales Tax1 Amount"},
	{id:"pod_SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"pod_OtherSalesTaxAmount", label:"Other Sales Tax Amount"},
	{id:"pod_DetailOrderDate", label:"Insertion Date"},
	{id:"pod_UserDate1", label:"Space Close"},
	{id:"pod_UserDate2", label:"Materials Due"},
	{id:"pod_InvoiceNumber", label:"Client Invoice #"},
	{id:"pod_VendorInvoiceNumber", label:"Vendor Invoice #"},
	{id:"pod_UnaccruedCost", label:"Unaccrued Cost"}
 ]''
	 , NULL, NULL, null, NULL)

 
/*************************************************************************************************************************
Broadcast Orders
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''bcEdit'', ''Broadcast Order Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''bcEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''bcEdit'', ''SpecSheets'', 1, ''Show Spec Sheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''bcEdit'', ''Attachments'', 2, ''Show Attachments'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''bcEdit'', ''grdPurchaseOrderDetail'', 1, ''Columns'', ''pod_Actions,pod_DetailOrderDate,pod_DetailOrderEndDate,pod_ItemKey,pod_ShortDescription,pod_Quantity,pod_GrossAmount,pod_Markup,pod_TotalCost,pod_LineNumber,pod_AdjustmentNumber'', NULL, ''grid'', 

''[	{id:"pod_LineNumber", label:"Line #"},
    {id:"pod_AdjustmentNumber", label:"Adj #"},
	{id:"pod_LinkID", label:"Link ID"},
	{id:"pod_ReasonID", label:"Revision Reason"},
	{id:"pod_Actions", label:"Actions"},
	{id:"pod_ProjectKey", label:"Project"},
	{id:"pod_TaskKey", label:"Task"},
	{id:"pod_ClassKey", label:"Class"},
	{id:"pod_ItemKey", label:"Item ID"},
	{id:"pod_OfficeKey", label:"Office"},
	{id:"pod_DepartmentKey", label:"Department"},
	{id:"pod_ShortDescription", label:"Item Name (Program)"},
	{id:"pod_LongDescription", label:"Standard Description"},
	{id:"pod_Quantity", label:"Spots"},
	{id:"pod_AppliedSpots", label:"Applied Spots"},
	{id:"pod_TotalCost", label:"Net"},
	{id:"pod_MaterialsSent", label:"Materials Sent"},
	{id:"pod_Billable", label:"Billable"},
	{id:"pod_MaterialsSentDate", label:"Materials Sent Date"},
	{id:"pod_UnitDescription", label:"Unit Description"},
	{id:"pod_Markup", label:"Commission"},
	{id:"pod_GrossAmount", label:"Gross"},
	{id:"pod_AppliedCost", label:"Applied Cost"},
	{id:"pod_AmountBilled", label:"Amount Billed"},
	{id:"pod_AppliedAmountBilled", label:"Amount Billed on VI"},
	{id:"pod_AccruedCost", label:"Accrued Cost"},
	{id:"pod_DateBilled", label:"Date Billed"},
	{id:"pod_Closed", label:"Closed"},
	{id:"pod_Taxable", label:"Taxable"},
	{id:"pod_Taxable2", label:"Taxable2"},
	{id:"pod_BilledComment", label:"Billed Comment"},
	{id:"pod_TransferComment", label:"Transfer Comment"},
	{id:"pod_SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"pod_SalesTax1Amount", label:"Sales Tax1 Amount"},
	{id:"pod_SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"pod_OtherSalesTaxAmount", label:"Other Sales Tax Amount"},
	{id:"pod_DetailOrderDate", label:"Start Date"},
	{id:"pod_DetailOrderEndDate", label:"End Date"},
	{id:"pod_UserDate1", label:"Space Close"},
	{id:"pod_UserDate2", label:"Materials Due"},
	{id:"pod_InvoiceNumber", label:"Client Invoice #"},
	{id:"pod_VendorInvoiceNumber", label:"Vendor Invoice #"},
	{id:"pod_UnitRate", label:"Unit Rate"},

	{id:"pod_UnaccruedCost", label:"Unaccrued Cost"},
	{id:"pod_OrderDays", label:"Days"},
	{id:"pod_OrderTime", label:"Time"},
	{id:"pod_OrderLength", label:"Length"}
 ]''
	 , NULL, NULL, null, NULL)

	  
/*************************************************************************************************************************
Media Plan Details
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''mediaPlanDetails'', ''Media Vendor Details Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaPlanDetails'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''mediaPlanDetails'', ''grdDetails'', 1, ''Columns'', ''mediaDescription,mediaID,mediaStartDate,mediaEndDate,mediaDate1,mediaDate2,mediaHistory,mediaQuantity,mediaUnitCost,mediaGross,mediaMU,mediaNet,mediaAmountToBill,mediaAppliedCost,mediaPO,mediaLine,mediaBilled,mediaDeleted'', NULL, ''grid'', 

''[	{id:"mediaDescription", label:"Description"},
	{id:"mediaID", label:"Link ID"},
	{id:"mediaOrderID", label:"Order Link ID"},
	{id:"mediaStartDate", label:"Start Date"},
	{id:"mediaEndDate", label:"End Date"},
	{id:"mediaDate1", label:"Space Close"},
	{id:"mediaDate2", label:"Materials Due"},
	{id:"mediaHistory", label:"Changes"},
	{id:"mediaQuantity", label:"Qty/Spots"},
	{id:"mediaUnitCost", label:"Unit Rate"},
	{id:"mediaNet", label:"Net"},
	{id:"mediaMU", label:"Commission"},
	{id:"mediaGross", label:"Gross"},
	{id:"mediaAmountToBill", label:"Amount To Bill"},
	{id:"mediaDeleted", label:"Deleted"},
	{id:"mediaAppliedCost", label:"Applied Costs"},
	{id:"mediaPO", label:"Order"},
	{id:"mediaLine", label:"Line"},
	{id:"mediaBilled", label:"Billed"},
	{id:"mediaOrderDays", label:"Days"},
	{id:"mediaOrderTime", label:"Time"},
	{id:"mediaOrderLength", label:"Length"},
	{id:"mediaErrMsgOrder", label:"Err Message"}
 ]''
	 , NULL, NULL, null, NULL)

/*************************************************************************************************************************
Vendor Invoices
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''voucherEdit'', ''Vendor Invoice Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''voucherEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''voucherEdit'', ''grdVoucherDetail'', 1, ''Columns'', ''vd_ProjectKey,vd_ItemKey,vd_Quantity,vd_UnitCost,vd_TotalCost,vd_Markup,vd_Commission,vd_GrossAmount'', NULL, ''grid'', 

''[	{id:"vd_LinkID", label:"Link ID"},
	{id:"vd_ProjectKey", label:"Project"},
	{id:"vd_TaskKey", label:"Task"},
	{id:"vd_ClassKey", label:"Class"},
	{id:"vd_ItemKey", label:"Item"},
	{id:"vd_OfficeKey", label:"Office"},
	{id:"vd_DepartmentKey", label:"Department"},
	{id:"vd_ExpenseGLAccountKey", label:"Expense GL Account"},
	{id:"vd_ShortDescription", label:"Description"},
	{id:"vd_Quantity", label:"Quantity"},
	{id:"vd_UnitCost", label:"Unit Cost"},
	{id:"vd_TotalCost", label:"Net Cost"},
	{id:"vd_Markup", label:"Markup"},
	{id:"vd_Commission", label:"Media Comm %"},
	{id:"vd_Billable", label:"Billable"},
	{id:"vd_GrossAmount", label:"Gross"},
	{id:"vd_BillableCost", label:"Amount to Bill"},
	{id:"vd_POLineAdjustment", label:"Order Info"},
	{id:"vd_PrebilledInvoice", label:"Prebilled Invoice"},
	{id:"vd_AmountBilled", label:"Amount Billed"},
	{id:"vd_DateBilled", label:"Date Billed"},
	{id:"vd_Taxable", label:"Taxable"},
	{id:"vd_Taxable2", label:"Taxable2"},
	{id:"vd_BilledComment", label:"Billed Comment"},
	{id:"vd_TransferComment", label:"Transfer Comment"},
	{id:"vd_UnitRate", label:"Unit Rate"},
	{id:"vd_SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"vd_SalesTax1Amount", label:"Sales Tax1 Amount"},
	{id:"vd_SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"vd_OtherSalesTaxAmount", label:"Other Sales Tax Amount"},
	{id:"vd_TotalWithTax", label:"Total With Tax"},
	{id:"vd_Dates", label:"Dates"},
	{id:"vd_TargetGLCompanyKey", label: "Target Company"},
	{id:"vd_ClientName", label: "Client Name"},
	{id:"vd_AccruedAmount", label: "Accrued Amount"},	
	{id:"vd_StationName", label: "Station / Pub"}
 ]''
	 , NULL, NULL, null, NULL)



/*************************************************************************************************************************
Journal Entries
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''jeEdit'', ''Journal Entry Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''jeEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''jeEdit'', ''grdJEDetail'', 1, ''Columns'', ''jed_account,jed_debit,jed_credit,jed_project,jed_targetglcompany,jed_client,jed_office,jed_department,jed_class,jed_memo,jed_currency'', NULL, ''grid'', 

''[	{id:"jed_account", label:"Account"},
	{id:"jed_debit", label:"Debit"},
	{id:"jed_credit", label:"Credit"},
	{id:"jed_project", label:"Project"},
	{id:"jed_targetglcompany", label:"Target GL Company"},
	{id:"jed_client", label:"Client"},
	{id:"jed_office", label:"Office"},
	{id:"jed_department", label:"Department"},
	{id:"jed_class", label:"Class"},
	{id:"jed_memo", label:"Memo"},
	{id:"jed_currency", label:"Currency"},
	{id:"jed_glcexchangerate", label:"GLC ExchangeRate"}
 ]''
	 , NULL, NULL, null, NULL)



/*************************************************************************************************************************
Unposted Transactions
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''postTransactions'', ''Unposted Transactions Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''postTransactions'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''postTransactions'', ''grdTransaction'', 1, ''Columns'', ''upt_amount,upt_amounthc,upt_PostingDate,upt_company,upt_office,upt_class,upt_glcompany,upt_project,upt_description'', NULL, ''grid'', 

''[	{id:"upt_amount", label:"Amount"},
	{id:"upt_amounthc", label:"Amount HC"},
	{id:"upt_PostingDate", label:"Posting Date"},
	{id:"upt_TransactionDate", label:"Date"},
	{id:"upt_project", label:"Project"},
	{id:"upt_glcompany", label:"GL Company"},
	{id:"upt_company", label:"Company ID"},
	{id:"upt_office", label:"Office"},
	{id:"upt_class", label:"Class"},
	{id:"upt_currency", label:"Currency"},
	{id:"upt_exchangerate", label:"Exch Rate"},
	{id:"upt_voucherid", label:"Voucher ID"},
	{id:"upt_description", label:"Description"},
	{id:"upt_createdby", label:"Entered By"},
	{id:"upt_unappliedamt", label:"Unapplied Amount"}
 ]''
	 , NULL, NULL, null, NULL)

	 

/*************************************************************************************************************************
Unapproved Transactions (Missing Transactions in Flex)
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''missingTransactions'', ''Unapproved Transactions Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''missingTransactions'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''missingTransactions'', ''grdTransaction'', 1, ''Columns'', ''miss_company,miss_project,miss_postingDate,miss_amount,miss_amounthc,miss_status,miss_currency,miss_exchangerate,miss_enteredBy'', NULL, ''grid'', 

''[	{id:"miss_amount", label:"Amount"},
	{id:"miss_amounthc", label:"Amount HC"},
	{id:"miss_postingDate", label:"Posting Date"},
	{id:"miss_company", label:"Company"},
	{id:"miss_currency", label:"Currency"},
	{id:"miss_exchangerate", label:"Exch Rate"},
	{id:"miss_status", label:"Status"},
	{id:"miss_voucherid", label:"Voucher ID"},
	{id:"miss_project", label:"Project"},
	{id:"miss_description", label:"Description"},
	{id:"miss_enteredBy", label:"Entered By"}
 ]''
	 , NULL, NULL, null, NULL)

/*************************************************************************************************************************
Post WIP
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''postWIP'', ''Post WIP Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''postWIP'', ''H1'', 0, ''WIP Detail Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''postWIP'', ''grdWIPDetail'', 1, ''Columns'', ''d_AccountFullName,d_Debit,d_Credit,d_ClientCompanyName,d_ClassFullName,d_ProjectFullName,d_OfficeName,d_DepartmentName'', NULL, ''grid'', 

''[	{id:"d_AccountFullName", label:"Account"},
	{id:"d_Debit", label:"Debit"},
	{id:"d_Credit", label:"Credit"},
	{id:"d_ClientCompanyName", label:"Client"},
	{id:"d_ClassFullName", label:"Class"},
	{id:"d_ProjectFullName", label:"Project"},
	{id:"d_OfficeName", label:"Office"},
	{id:"d_DepartmentName", label:"Department"}
 ]''
	 , NULL, NULL, null, NULL)


/*************************************************************************************************************************
Recurring Transactions
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''scheduledTransactions'', ''Scheduled Transactions Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''scheduledTransactions'', ''H1'', 0, ''Scheduled Transactions Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''scheduledTransactions'', ''grdTransactions'', 1, ''Columns'', ''schedTranRef,schedTranFreq,schedTranNext,schedTranAmount,schedTranNumber,schedTranDaysAdv,schedTranRemind,schedTranDesc,schedTranVendor,schedTranClient,schedCurApprover,schedTranActive,schedTranDaysRemaining,schedLastTranDate'', NULL, ''grid'', 

''[	{id:"schedTranRef", label:"Reference"},
	{id:"schedTranFreq", label:"Timing"},
	{id:"schedTranNext", label:"Next"},
	{id:"schedTranAmount", label:"Amount"},
	{id:"schedTranNumber", label:"# Generated"},
	{id:"schedTranDaysAdv", label:"Days In Advance"},
	{id:"schedTranRemind", label:"Reminder Option"},
	{id:"schedTranDesc", label:"Description"},
	{id:"schedTranVendor", label:"Vendor"},
	{id:"schedTranClient", label:"Client"},
	{id:"schedCurApprover", label:"Current Approver"},
	{id:"schedTranActive", label:"Active"},
	{id:"schedTranDaysRemaining", label:"# Remaining"},
	{id:"schedLastTranDate", label:"Last Transaction Date"}
 ]''
	 , NULL, NULL, null, NULL)


/*************************************************************************************************************************
Credit Card Charges
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''CCCEdit'', ''Credit Card Charge Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''CCCEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''CCCEdit'', ''grdVoucherDetail'', 1, ''Columns'', ''vd_ProjectKey,vd_ItemKey,vd_Quantity,vd_UnitCost,vd_TotalCost,vd_Markup,vd_GrossAmount,vd_Exclude1099'', NULL, ''grid'', 

''[	{id:"vd_LinkID", label:"Link ID"},
	{id:"vd_ProjectKey", label:"Project"},
	{id:"vd_TaskKey", label:"Task"},
	{id:"vd_ClassKey", label:"Class"},
	{id:"vd_ItemKey", label:"Item"},
	{id:"vd_OfficeKey", label:"Office"},
	{id:"vd_DepartmentKey", label:"Department"},
	{id:"vd_ExpenseGLAccountKey", label:"Expense GL Account"},
	{id:"vd_ShortDescription", label:"Description"},
	{id:"vd_Quantity", label:"Quantity"},
	{id:"vd_UnitCost", label:"Unit Cost"},
	{id:"vd_TotalCost", label:"Net Cost"},
	{id:"vd_Markup", label:"Markup"},
	{id:"vd_Commission", label:"Media Comm %"},
	{id:"vd_Billable", label:"Billable"},
	{id:"vd_GrossAmount", label:"Gross"},
	{id:"vd_BillableCost", label:"Amount to Bill"},
	{id:"vd_POLineAdjustment", label:"Order Info"},
	{id:"vd_PrebilledInvoice", label:"PrebilledInvoice"},
	{id:"vd_AmountBilled", label:"Amount Billed"},
	{id:"vd_DateBilled", label:"Date Billed"},
	{id:"vd_Taxable", label:"Taxable"},
	{id:"vd_Taxable2", label:"Taxable2"},
	{id:"vd_BilledComment", label:"Billed Comment"},
	{id:"vd_TransferComment", label:"Transfer Comment"},
	{id:"vd_UnitRate", label:"Unit Rate"},
	{id:"vd_SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"vd_SalesTax1Amount", label:"Sales Tax1 Amount"},
	{id:"vd_SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"vd_OtherSalesTaxAmount", label:"Other Sales Tax Amount"},
	{id:"vd_Exclude1099", label:"Exclude From 1099"},
 ]''
	 , NULL, NULL, null, NULL)


/*************************************************************************************************************************
Production Dash
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''productionDash'', ''My Projects Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''H1'', 0, ''My Projects Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''OpenAssignments'', 1, ''Projects With Open Assignments Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''productionDash'', ''OnlyYourOpenAssignments'', 2, ''My Open Assignments Only'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''OnlyProjectsOnTeam'', 3, ''Only Projects I am On The Team'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''productionDash'', ''IncludePlanningProjects'', 4, ''Include Planning Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''IAmAM'', 5, ''Only Projects where I am the AM'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''IAmPM'', 6, ''Only Projects where I am the PM'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''IAmBM'', 7, ''Only Projects where I am the BM'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''ProjectStatus'', 8, ''Project Status'', ''-3'', ''All Active'', ''selectlist'', NULL, ''selectlist.ProjectStatus'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''ProjectBillingStatus'', 9, ''Billing Status'', ''-1'', ''All'', ''selectlist'', NULL, ''selectlist.ProjectBillingStatus'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''GLCompanyID'', 10, ''GL Company'', ''-1'', ''All'', ''lookup'', NULL, ''lookup.GLCompany'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''BudgetWarning'', 11, ''Budget Warning'', ''80'', NULL, ''number'', NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''H2'', 12, ''Display Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''GroupBy'', 13, ''Group By'', ''CustomerFullName'', ''Client'', ''lookup'', ''No Grouping:NoGrouping|Campaign:CampaignName|Campaign Segment:SegmentName|Client:CustomerFullName|Project Status:ProjectStatus|Project Type:ProjectTypeName|Account Manager:AccountManagerName|Project Manager:ProjectManagerName|Parent Client:ParentClientName|Product Name:Product Name|Office:OfficeName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''GroupByDir'', 14, ''Group Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDash'', ''SortBy'', 15, ''Sort By'', ''ProjectNumber'', ''Project Number'', ''lookup'', ''No Sorting:NoSorting|Project Number:ProjectNumber|Project Status:ProjectStatus|My Open Assignments:OpenAssignments|Project Manager:ProjectManagerName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''productionDash'', ''SortByDir'', 16, ''Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)

/*************************************************************************************************************************
Project Conversations  (reached from Admin > System Setup > System Options > Conversation Settings)
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectConversations'', ''Conversation Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''projectConversations'', ''H1'', 0, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''projectConversations'', ''HideAISummarize'', 1, ''Hide the AI Summarize button'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''productionDash'', ''grdProductionDashCols'', 16, ''Columns'', ''productionDashProjectFullName,productionDashFinancialStatusImage,productionDashProjectTaskStatus,productionDashProjectStatus,productionDashProjectPercComp,productionDashOpenAssignments,productionDashStatusNotesUpdated,productionDashClientNotesUpdated,productionDashDetailNotesUpdated'', NULL, ''grid'', 
''[{id:"productionDashProjectFullName", label:"Project Full Name"},
	{id:"productionDashProjectQuickEdit", label:"Quick Edit"},
	{id:"productionDashFolderImage", label:"Project Info"},
	{id:"productionDashFinancialStatusImage", label:"Financial Status"},
	{id:"productionDashProjectTaskStatus", label:"Project Task Status"},	
	{id:"productionDashProjectTaskStatusColor", label:"Project Task Status Color"},	
	{id:"productionDashProjectStatus", label:"Project Status"},
	{id:"productionDashProjectPercComp", label:"% Complete"}, 
	{id:"productionDashAmtAdvBill", label:"Amount Advance Billed"},
	{id:"productionDashAmtAdvBillOpen", label:"Amount Advance Billed Open"},
	{id:"productionDashOpenAssignments", label:"Open Assignments"},
	{id:"productionDashOpenToDo", label:"Open To Dos"},
	{id:"productionDashDeliverables", label:"Deliverables"},
	{id:"productionDashProjectName", label:"Project Name"},
	{id:"productionDashAccountManagerName", label:"Account Manager"},
	{id:"productionDashProjectManagerName", label:"Project Manager"},
	{id:"productionDashBillingManagerName", label:"Billing Manager"},
	{id:"productionDashCustomerFullName", label:"Client Name"},
	{id:"productionDashProjectTypeName", label:"Project Type Name"},
	{id:"productionDashProjectTypeColor", label:"Project Type Color"},
	{id:"productionDashCampaignName", label:"Campaign Name"},
	{id:"productionDashCampaignSegName", label:"Campaign Segment Name"},
	{id:"productionDashPrimaryContact", label:"Primary Contact"},
	{id:"productionDashPhone1", label:"Contact Phone"},
	{id:"productionDashEmail", label:"Contact Email"},
	{id:"productionDashCompanyName", label:"Company Name"},
	{id:"productionDashDivisionName", label:"Division Name"},
	{id:"productionDashPhone", label:"Company Phone"},
	{id:"productionDashTotalGross", label:"Total Gross"},
	{id:"productionDashOriginalBudgetHours", label:"Original Budget Hours"},
	{id:"productionDashOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
	{id:"productionDashOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
	{id:"productionDashOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
	{id:"productionDashCOBudgetHours", label:"CO Budget Hours"},
	{id:"productionDashCOBudgetLaborGross", label:"CO Budget Labor Gross"},
	{id:"productionDashCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
	{id:"productionDashCurrentBudgetHours", label:"Current Budget Hours"},
	{id:"productionDashCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
	{id:"productionDashCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
	{id:"productionDashTotalBudget", label:"Total Budget w/o Tax"},
	{id:"productionDashTotalBudgetwTaxes", label:"Total Budget with Tax"},
	{id:"productionDashBilledAmountNoTax", label:"Total Billed w/o Tax"},
	{id:"productionDashBilledAmount", label:"Total Billed with Tax"},
	{id:"productionDashProjectDescription", label:"Project Description"},
	{id:"productionDashProjectStartDate", label:"Project Start Date"},
	{id:"productionDashProjectDueDate", label:"Project Due Date"},
	{id:"productionDashCreatedDate", label:"Created Date"},
	{id:"productionDashGetLaborRateFrom", label:"Get Labor Rate From"},
	{id:"productionDashGetMarkupFrom", label:"Get Markup From"},
	{id:"productionDashNonBillableProject", label:"Non Billable Project"},
	{id:"productionDashClosedProject", label:"Closed Project"},
	{id:"productionDashProjectNumber", label:"Project Number"},
	{id:"productionDashProjectBillingStatus", label:"Project Billing Status"},
	{id:"productionDashActualHours", label:"Actual Hours"},
	{id:"productionDashBilledHours", label:"Hours Billed"},
	{id:"productionDashProductName", label:"Product Name"},
	{id:"productionDashClientProjectNumber", label:"Client Project Number"},
	{id:"productionHasEstimate", label:"Has Estimate(s)"},
	{id:"productionFlightStartDate", label:"Flight Start Date"},
	{id:"productionFlightEndDate", label:"Flight End Date"},
	{id:"productionProjectColor", label:"Project Color"},
	{id:"productionStatusNotes", label:"Status Notes"},
	{id:"productionClientNotes", label:"Client Notes"},
	{id:"productionDashStatusNotesUpdated", label:"Status Notes Updated On"},
	{id:"productionDashClientNotesUpdated", label:"Client Notes Updated On"},
	{id:"productionDashDetailNotesUpdated", label:"Next Steps Updated On"},
	{id:"productionDashTotalLaborGross", label:"Total Labor Gross"},
	{id:"productionDashTotalCostsGross", label:"Total Costs Gross"},
	{id:"productionDashProjectToBillRemaining", label:"Project To Bill Remaining"},
	{id:"productionDashProjectRemainingHours", label:"Project Remaining Hours"},
	{id:"productionDashProjectRemainingBudget", label:"Project Remaining Budget"},
	{id:"productionDashRemainingLaborBudget", label:"Remaining Labor Budget"},
	{id:"productionDashRemainingExpenseBudget", label:"Remaining Expense Budget"},
	{id:"productionDashProjectCurrency", label:"Currency"},
	{id:"productionDashLastTaskDueDate", label:"Last Task Due Date"},
	{id:"productionNextSteps", label:"Next Steps"},
	{id:"productionDashGLCompanySource", label:"Revenue Source"},
	{id:"productionDashLastTimeEntry", label:"Date of Last Time Entry"},
	{id:"productionDashEstimateProfit", label:"Estimate Profit"},
	{id:"productionDashAllocatedHours", label:"Allocated Hours"},
	{id:"productionDashKeyPeople1", label:"Key Person 1"},
	{id:"productionDashKeyPeople2", label:"Key Person 2"},
	{id:"productionDashKeyPeople3", label:"Key Person 3"},
	{id:"productionDashKeyPeople4", label:"Key Person 4"},
	{id:"productionDashKeyPeople5", label:"Key Person 5"},
	{id:"productionDashKeyPeople6", label:"Key Person 6"},

	{id:"productionDashProjectScheduleAdherance", label:"Schedule Adherance"},
	{id:"productionDashProjectEffortVariance", label:"Effort Variance"},
	{id:"productionDashProjectProjectPerformance", label:"Project Performance"},
	{id:"productionDashTotalUnbilled", label:"Total Gross Unbilled"},
    {id:"productionDashBillingMethod", label:"Billing Method"},	
	{id:"productionDashGLCompany", label:"GL Company Name"},
	{id:"productionDashPlanningProjectName", label:"Planning Project Name"},
	{id:"productionDashAllocatedRemaining", label:"Allocated Remaining"},
	{id:"productionDashOpenOrdersGross", label:"Open Orders Gross"},
	{id:"productionDashRetainerName", label:"Retainer Name"},
	{id:"productionDashHoursAfterWriteoff", label:"Hours After Writeoff"},
	{id:"productionDashOfficeName", label:"Office Name"}]''
	 , NULL, NULL, ''Project'', ''Project'')

/*************************************************************************************************************************
Production Dash (Planning Project)
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''productionDashPlanning'', ''My Planning Projects Settings'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''H1'', 0, ''My Planning Projects Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''OpenAssignments'', 1, ''Projects With Open Assignments Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''productionDashPlanning'', ''OnlyYourOpenAssignments'', 2, ''My Open Assignments Only'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''OnlyProjectsOnTeam'', 3, ''Only Projects I am On The Team'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''IAmAM'', 5, ''Only Projects where I am the AM'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''IAmPM'', 6, ''Only Projects where I am the PM'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''ProjectStatus'', 7, ''Project Status'', ''-1'', ''All Active'', ''lookup'', NULL, ''lookup.ProjectStatus'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''ProjectBillingStatus'', 8, ''Billing Status'', ''-1'', ''All'', ''lookup'', NULL, ''lookup.ProjectBillingStatus'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''GLCompanyID'', 9, ''GL Company'', ''-1'', ''All'', ''lookup'', NULL, ''lookup.GLCompany'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''BudgetWarning'', 10, ''Budget Warning'', ''80'', NULL, ''number'', NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''H2'', 11, ''Display Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''GroupBy'', 12, ''Group By'', ''CustomerFullName'', ''Client'', ''lookup'', ''No Grouping:NoGrouping|Campaign:CampaignName|Campaign Segment:SegmentName|Client:CustomerFullName|Project Status:ProjectStatus|Project Type:ProjectTypeName|Account Manager:AccountManagerName|Project Manager:ProjectManagerName|Parent Client:ParentClientName|Product Name:Product Name|Office:OfficeName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''GroupByDir'', 13, ''Group Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''SortBy'', 14, ''Sort By'', ''ProjectNumber'', ''Project Number'', ''lookup'', ''No Sorting:NoSorting|Project Number:ProjectNumber|Project Status:ProjectStatus|My Open Assignments:OpenAssignments|Project Manager:ProjectManagerName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionDashPlanning'', ''SortByDir'', 15, ''Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''productionDashPlanning'', ''grdProductionDashCols'', 16, ''Columns''
, ''productionDashProjectFullName,productionDashFinancialStatusImage,productionDashProjectStatus,productionDashProjectDueDate,productionDashOpenAssignments'', NULL, ''grid'', 
''[{id:"productionDashProjectFullName", label:"Project Full Name"},
	{id:"productionDashProjectQuickEdit", label:"Quick Edit"},
	{id:"productionDashFolderImage", label:"Project Info"},
	{id:"productionDashFinancialStatusImage", label:"Financial Status"},
	{id:"productionDashProjectTaskStatus", label:"Project Task Status"},	
	{id:"productionDashProjectTaskStatusColor", label:"Project Task Status Color"},	
	{id:"productionDashProjectStatus", label:"Project Status"},
	{id:"productionDashAmtAdvBill", label:"Amount Advance Billed"},
	{id:"productionDashAmtAdvBillOpen", label:"Amount Advance Billed Open"},
	{id:"productionDashOpenAssignments", label:"Open Assignments"},
	{id:"productionDashOpenToDo", label:"Open To Dos"},
	{id:"productionDashDeliverables", label:"Deliverables"},
	{id:"productionDashProjectName", label:"Project Name"},
	{id:"productionDashAccountManagerName", label:"Account Manager"},
	{id:"productionDashProjectManagerName", label:"Project Manager"},
	{id:"productionDashBillingManagerName", label:"Billing Manager"},
	{id:"productionDashCustomerFullName", label:"Client Name"},
	{id:"productionDashProjectTypeName", label:"Project Type Name"},
	{id:"productionDashProjectTypeColor", label:"Project Type Color"},
	{id:"productionDashPrimaryContact", label:"Primary Contact"},
	{id:"productionDashPhone1", label:"Contact Phone"},
	{id:"productionDashEmail", label:"Contact Email"},
	{id:"productionDashCompanyName", label:"Company Name"},
	{id:"productionDashDivisionName", label:"Division Name"},
	{id:"productionDashPhone", label:"Company Phone"},
	{id:"productionDashTotalGross", label:"Total Gross"},
	{id:"productionDashOriginalBudgetHours", label:"Original Budget Hours"},
	{id:"productionDashOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
	{id:"productionDashOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
	{id:"productionDashOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
	{id:"productionDashCOBudgetHours", label:"CO Budget Hours"},
	{id:"productionDashCOBudgetLaborGross", label:"CO Budget Labor Gross"},
	{id:"productionDashCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
	{id:"productionDashCurrentBudgetHours", label:"Current Budget Hours"},
	{id:"productionDashCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
	{id:"productionDashCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
	{id:"productionDashTotalBudget", label:"Total Budget w/o Tax"},
	{id:"productionDashTotalBudgetwTaxes", label:"Total Budget with Tax"},
	{id:"productionDashBilledAmountNoTax", label:"Total Billed w/o Tax"},
	{id:"productionDashBilledAmount", label:"Total Billed with Tax"},
	{id:"productionDashProjectDescription", label:"Project Description"},
	{id:"productionDashProjectStartDate", label:"Project Start Date"},
	{id:"productionDashProjectDueDate", label:"Project Due Date"},
	{id:"productionDashCreatedDate", label:"Created Date"},
	{id:"productionDashGetLaborRateFrom", label:"Get Labor Rate From"},
	{id:"productionDashGetMarkupFrom", label:"Get Markup From"},
	{id:"productionDashNonBillableProject", label:"Non Billable Project"},
	{id:"productionDashClosedProject", label:"Closed Project"},
	{id:"productionDashProjectNumber", label:"Project Number"},
	{id:"productionDashProjectBillingStatus", label:"Project Billing Status"},
	{id:"productionDashActualHours", label:"Actual Hours"},
	{id:"productionDashProductName", label:"Product Name"},
	{id:"productionDashClientProjectNumber", label:"Client Project Number"},
	{id:"productionHasEstimate", label:"Has Estimate(s)"},
	{id:"productionProjectColor", label:"Project Color"},
	{id:"productionStatusNotes", label:"Status Notes"},
	{id:"productionClientNotes", label:"Client Notes"},
	{id:"productionDashTotalLaborGross", label:"Total Labor Gross"},
	{id:"productionDashTotalCostsGross", label:"Total Costs Gross"},
	{id:"productionDashProjectToBillRemaining", label:"Project To Bill Remaining"},
	{id:"productionDashProjectRemainingHours", label:"Project Remaining Hours"},
	{id:"productionDashProjectRemainingBudget", label:"Project Remaining Budget"},
	{id:"productionDashProjectCurrency", label:"Currency"},
	{id:"productionDashLastTaskDueDate", label:"Last Task Due Date"},
	{id:"productionNextSteps", label:"Next Steps"},
	{id:"productionDashGLCompanySource", label:"Revenue Source"},
	{id:"productionDashLastTimeEntry", label:"Date of Last Time Entry"},
	{id:"productionDashEstimateProfit", label:"Estimate Profit"},
	{id:"productionDashAllocatedHours", label:"Allocated Hours"},
	{id:"productionDashPlanningProjectFull", label:"Planning Project Full Name"},
	{id:"productionDashPlanningProjectName", label:"Planning Project Name"},
	{id:"productionDashplanningPrpojectNumber", label:"Plannning Project Number"},
	{id:"productionDashKeyPeople1", label:"Key Person 1"},
	{id:"productionDashKeyPeople2", label:"Key Person 2"},
	{id:"productionDashKeyPeople3", label:"Key Person 3"},
	{id:"productionDashKeyPeople4", label:"Key Person 4"},
	{id:"productionDashKeyPeople5", label:"Key Person 5"},
	{id:"productionDashKeyPeople6", label:"Key Person 6"},	
	{id:"productionDashTotalUnbilled", label:"Total Gross Unbilled"},
	{id:"productionDashBillingMethod", label:"Billing Method"},
	{id:"productionDashPlanningBillingOption", label:"Planning Project Billing Option"}]''
	 , NULL, NULL, ''Project'', ''Project'')

/*************************************************************************************************************************
Production Assignment
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''productionAssignment'', ''Assignment To Do Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''showNotes'', 1, ''Show notes under the subject'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''EditInGrid'', 2, ''Edit To Dos directly in grid'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''productionAssignment'', ''groupBy'', 3, ''Group To Dos By'', ''StatusName'', ''Status Name'', ''lookup'', ''Status Name:StatusName|Assigned:UserFullName|Type:TypeName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''productionAssignment'', ''grdToDosCols'', 4, ''Columns'', ''toDoSubject,toDoCompleted,todoType,todoStatus,todoDueDate'', NULL, ''grid'', 

''[	{id:"toDoSubject", label:"Subject"},
	{id:"toDoCompleted", label:"Completed"},
	{id:"todoType", label:"Type"},
	{id:"todoStatus", label:"Status"},
	{id:"todoUserFullName", label:"Assigned To"},
	{id:"todoDueDate", label:"Due Date"}
 ]''
	 , NULL, NULL, ''Activity'', ''Activity'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''DashboardSettings'', 5, ''Assignment Sections'', NULL, NULL, ''sectionheader'', NULL, NULL, ''Enabling the checkbox will show the item in the project details jump menu. These settings only apply to the assignment page.'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentProjectOverview'', 6, ''Project Overview'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentProjectSetup'', 7, ''Project Setup'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentSchedule'', 8, ''Schedule'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentTeam'', 9, ''Team'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentDailyFeed'', 10, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentSpecsheets'', 11, ''Specs'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentMiscCost'', 12, ''Misc Cost'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentDeliverables'', 13, ''Deliverables'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionAssignment'', ''AssignmentFiles'', 14, ''Files'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)



/*************************************************************************************************************************
Account Manager Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''salesToday'', ''System Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''hideSchedule'', 1, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''HideEnterTime'', 2, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''DisplayTimeEntriesComments'', 3, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''IncludePublicMeetings'', 4, ''Include Public Meetings'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''H3'', 5, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''salesToday'', ''SortConversations'', 6, ''Sort Conversations'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''H2'', 7, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesToday'', ''ShowInOutBoard'', 8, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Manager Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminToday'', ''System Settings'', '''', 1)

--INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
--Values (''adminToday'', ''H1'', 0, ''Open Items'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''H3'', 17, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''adminToday'', ''DailyFeed'', 18, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''adminToday'', ''FeedProjectOptions'', 19, ''Project Options'', ''0'', ''All Projects'', ''lookup'', ''All Projects:0|All Project I Am Assigned To:1|Projects Where I Am The Account Manager:2|Only Projects In My Office:3'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''adminToday'', ''ShowTimeEntries'', 20, ''Show Time Entries'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''H4'', 21, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''adminToday'', ''SortConversations'', 22, ''Sort Conversations'', ''DESC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''FilterProjectTab'', 23, ''Only show Project Conversations sent to me'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''H5'', 24, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''ShowInOutBoard'', 25, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''H6'', 26, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''hideSchedule'', 27, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''HideEnterTime'', 28, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''DisplayTimeEntries'', 29, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''adminToday'', ''DisplayTimeEntriesComments'', 30, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminToday'', ''IncludePublicMeetings'', 31, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Project Manager Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''pmToday'', ''System Settings'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''H1'', 0, ''Open Items'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''IncludeOthers'', 1, ''Include/Show Others'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Open items list will include other account managers and be grouped by account manager'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''UnapprovedPurchaseOrders'', 1, ''Unapproved Purchase Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''OpenOrders'', 2, ''Open Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''EstimatesWaitingOnInternalApproval'', 3, ''Estimates waiting on internal approval'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''EstimatesWaitingOnClientApproval'', 4, ''Estimates waiting on client approval'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''OpenRequestsForQuote'', 5, ''Open Requests for Quote'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''UnapprovedVendorInvoices'', 6, ''Unapproved Vendor Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''UnapprovedRequests'', 7, ''Unapproved Project Requests'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''UnapprovedRequestsOthers'', 8, ''Unapproved Project Requests for Others'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''RequestsNoProject'', 9, ''Approved Project Requests with no Project'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
if @LoadBeta = 1
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''UnapprovedChangeRequests'', 10, ''Unapproved Change Requests'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''H2'', 11, ''Items Needing Attention'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''ProjectsGoingOverBudget'', 12, ''Projects with budget warnings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''TasksDueButNotDone'', 13, ''Assignments due but not done'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''ProjectsWithScheduleWarnings'', 14, ''Project with schedule warnings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''ActiveTasks'', 15, ''My Tasks'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''OpenActivities'', 16, ''Open Activities'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''DailyDeliverableStatus'', 17, ''Daily Deliverable Status'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''OverdueBillingWorksheets'', 18, ''Overdue Billing Worksheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''OverworkedAssignments'', 19, ''Overworked Assignments'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''H3'', 20, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''DailyFeed'', 21, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''FeedProjectOptions'', 22, ''Project Options'', ''0'', ''All Projects'', ''lookup'', ''All Projects:0|All Project I Am Assigned To:1|Projects Where I Am The Account Manager Or Project Manager:2|Only Projects In My Office:3'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''pmToday'', ''ShowTimeEntries'', 23, ''Show Time Entries'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''H6'', 24, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''pmToday'', ''SortConversations'', 25, ''Sort Conversations'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''FilterProjectTab'', 26, ''Only show Project Conversations sent to me'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''H4'', 27, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''ShowInOutBoard'', 28, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''H5'', 29, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''hideSchedule'', 30, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''HideEnterTime'', 31, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''DisplayTimeEntries'', 32, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''pmToday'', ''DisplayTimeEntriesComments'', 33, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''pmToday'', ''IncludePublicMeetings'', 34, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)


INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''pmToday_18'', ''Project Manager Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''pmToday_18'', ''grdOpenItemsList_18'', 1, ''Columns'', ''colRequestID,colCompanyName,colSubject,colRequestedBy,colDateAdded,colDueDate,colDateSentForApproval,colProjectDescription'', NULL, ''grid'', 
''[	{id:"colRequestID", label:"Request ID"},
		{id:"colCompanyName", label:"Client"},
		{id:"colSubject", label:"Subject"},
		{id:"colRequestedBy", label:"Requested By"},
		{id:"colDateAdded", label:"Date Added"},
		{id:"colDueDate", label:"Project Due Date"},
		{id:"colDateSentForApproval", label:"Date Sent For Approval"},
		{id:"colProjectDescription", label:"Project Description"}
 ]''
 , NULL, NULL, NULL, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''pmToday_20'', ''Project Manager Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''pmToday_20'', ''grdOpenItemsList_20'', 1, ''Columns'', ''colRequestID,colCompanyName,colSubject,colRequestedBy,colDateAdded,colDueDate,colDateSentForApproval,colProjectDescription'', NULL, ''grid'', 
''[	{id:"colRequestID", label:"Request ID"},
		{id:"colCompanyName", label:"Client"},
		{id:"colSubject", label:"Subject"},
		{id:"colRequestedBy", label:"Requested By"},
		{id:"colDateAdded", label:"Date Added"},
		{id:"colDueDate", label:"Project Due Date"},
		{id:"colDateSentForApproval", label:"Date Sent For Approval"},
		{id:"colProjectDescription", label:"Project Description"}
 ]''
 , NULL, NULL, NULL, NULL)

 if @LoadBeta = 1
 BEGIN
	INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''pmToday_21'', ''Project Manager Settings'', '''', 0)
	INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
	Values (''pmToday_21'', ''grdOpenItemsList_21'', 1, ''Columns'', ''colVersionNumber,colCompanyName,colSubject,colRequestedBy,colDateAdded,colProjectDescription'', NULL, ''grid'', 
	''[	{id:"colVersionNumber", label:"Version"},
			{id:"colCompanyName", label:"Client"},
			{id:"colSubject", label:"Subject"},
			{id:"colRequestedBy", label:"Requested By"},
			{id:"colDateAdded", label:"Date Added"},
			{id:"colProjectDescription", label:"Description"}
	 ]''
	 , NULL, NULL, NULL, NULL)

 END
 
 
/*************************************************************************************************************************
Accounting Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''glToday'', ''System Settings'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''H1'', 1, ''Items Needing Attention'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''UnpostedTransactions'', 2, ''Unposted Transactions'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''UnapprovedTransactions'', 3, ''Unapproved Transactions'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''AROutOfBalance'', 4, ''AR Out of Balance'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''APOutOfBalance'', 5, ''AP Out of Balance'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''ScheduledTransactions'', 6, ''Scheduled Transactions'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''PostWorkInProgress'', 7, ''Post Work In Progress'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''OpenBankRecs'', 8, ''Open Bank Recs'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''H2'', 9, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''DailyFeed'', 10, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''FeedProjectOptions'', 11, ''Project Options'', ''0'', ''All Projects'', ''lookup'', ''All Projects:0|All Project I Am Assigned To:1|Projects Where I Am The Account Manager:2|Only Projects In My Office:3'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''glToday'', ''ShowTimeEntries'', 12, ''Show Time Entries'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''H3'', 13, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''glToday'', ''SortConversations'', 14, ''Sort Conversations'', ''DESC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''FilterProjectTab'', 15, ''Only show Project Conversations sent to me'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''H4'', 16, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''ShowInOutBoard'', 17, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''H5'', 18, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''hideSchedule'', 19, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''HideEnterTime'', 20, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''DisplayTimeEntries'', 21, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''glToday'', ''DisplayTimeEntriesComments'', 22, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''IncludePublicMeetings'', 23, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''H6'', 24, ''Account Balances'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''Bank'', 25, ''Bank Accounts'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''AR'', 26, ''AR Accounts'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''CurrentAsset'', 27, ''Current Asset Accounts'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''FixedAsset'', 28, ''Fixed Asset Accounts'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''OtherAsset'', 29, ''Other Asset Accounts'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''AP'', 30, ''AP Accounts'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''CurrentLiability'', 31, ''Current Liability'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''LongTermLiability'', 32, ''Long Term Liability'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''CreditCard'', 33, ''Credit Cards'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''EquityNoClose'', 34, ''Equity - Does not Close'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glToday'', ''EquityClose'', 35, ''Equity - Closes'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Media Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''mediaToday'', ''System Settings'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
VALUES (''mediaToday'', ''H1'', 0, ''Open Items'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''UnapprovedBroadcastOrders'', 1, ''Unapproved Broadcast Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''OpenBroadcastOrders'', 2, ''Open Broadcast Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''BOUnapprovedVouchers'', 3, ''Unapproved Broadcast Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''UnapprovedInsertionOrders'', 4, ''Unapproved Insertion Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''OpenInsertionOrders'', 5, ''Open Insertion Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''IOUnapprovedVouchers'', 6, ''Unapproved Insertion Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
VALUES (''mediaToday'', ''H2'', 7, ''Orders Needing Attention'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''ActiveTasks'', 8, ''My Tasks'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''BOSpaceClose'', 8, ''Broadcast Orders Space Close'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''BOMaterialsDue'', 9, ''Broadcast Orders Materials Due'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''IOSpaceClose'', 10, ''Insertion Orders Space Close'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''IOMaterialsDue'', 11, ''Insertion Orders Materials Due'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''DaysFromToday'', 12, ''Days Out from Today'', ''14'', NULL, ''number:n0'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''H3'', 17, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''DailyFeed'', 18, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''FeedProjectOptions'', 19, ''Project Options'', ''0'', ''All Projects'', ''lookup'', ''All Projects:0|All Project I Am Assigned To:1|Projects Where I Am The Account Manager:2|Only Projects In My Office:3'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''mediaToday'', ''ShowTimeEntries'', 20, ''Show Time Entries'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''H4'', 21, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''mediaToday'', ''SortConversations'', 22, ''Sort Conversations'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''H5'', 23, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''ShowInOutBoard'', 24, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''H6'', 25, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''HideEnterTime'', 26, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''DisplayTimeEntries'', 27, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''mediaToday'', ''DisplayTimeEntriesComments'', 28, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaToday'', ''IncludePublicMeetings'', 29, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)


INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) VALUES(''boTraffic'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
VALUES (''boTraffic'', ''grdMediaTrafficCols'', 1, ''Columns'', ''colVendorID,colVendorName,colStationName,colStatus,colDetailOrderDate,colDetailOrderEndDate,colDescription,colSpecialInstructions,colDeliveryInstructions,colLineNo,colSpaceClose,colMaterialsDue,colShortDescription,colLongDescription'', NULL, ''grid'', 
''[
	{id:"colVendorID", label:"Vendor ID"},
	{id:"colVendorName", label:"Vendor Name"},
	{id:"colStationName", label:"Station"},
	{id:"colStatus", label:"Status"},
	{id:"colDetailOrderDate", label:"Start Date"},
	{id:"colDetailOrderEndDate", label:"End Date"},
	{id:"colDescription", label:"Description"},
	{id:"colSpecialInstructions", label:"Special Instructions"},
	{id:"colDeliveryInstructions", label:"Traffic Instructions"},
	{id:"colLineNo", label:"Line #"},
	{id:"colSpaceClose", label:"Space Close"},
	{id:"colMaterialsDue", label:"Materials Due"},
	{id:"colShortDescription", label:"Program"},
	{id:"colLongDescription", label:"Comments"},
	{id:"colCustomerID", label:"Client ID"},
	{id:"colCompanyName", label:"Client Name"},
	{id:"colCampaignID", label:"Campaign ID"},
	{id:"colCampaignName", label:"Campaign Name"},
	{id:"colMaterialsSent", label:"Materials Sent"},
	{id:"colMaterialsSentDate", label:"Materials Sent Date"}
 ]''
 , NULL, NULL, ''PO_Detail'', ''PO_Detail'')

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) VALUES(''ioTraffic'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
VALUES (''ioTraffic'', ''grdMediaTrafficCols'', 1, ''Columns'', ''colVendorID,colVendorName,colStationName,colStatus,colDetailOrderDate,colDescription,colSpecialInstructions,colDeliveryInstructions,colLineNo,colSpaceClose,colMaterialsDue,colShortDescription,colLongDescription'', NULL, ''grid'', 
''[
	{id:"colVendorID", label:"Vendor ID"},
	{id:"colVendorName", label:"Vendor Name"},
	{id:"colStationName", label:"Publication"},
	{id:"colStatus", label:"Status"},
	{id:"colDetailOrderDate", label:"Insertion Date"},
	{id:"colDescription", label:"Description"},
	{id:"colSpecialInstructions", label:"Special Instructions"},
	{id:"colDeliveryInstructions", label:"Traffic Instructions"},
	{id:"colLineNo", label:"Line #"},
	{id:"colSpaceClose", label:"Space Close"},
	{id:"colMaterialsDue", label:"Materials Due"},
	{id:"colShortDescription", label:"Ad Number/Caption"},
	{id:"colLongDescription", label:"Comments"},
	{id:"colCustomerID", label:"Client ID"},
	{id:"colCompanyName", label:"Client Name"},
	{id:"colCampaignID", label:"Campaign ID"},
	{id:"colCampaignName", label:"Campaign Name"},
	{id:"colMaterialsSent", label:"Materials Sent"},
	{id:"colMaterialsSentDate", label:"Materials Sent Date"}
 ]''
 , NULL, NULL, ''PO_Detail'', ''PO_Detail'')

/*************************************************************************************************************************
Billing Dashboard 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingDashboard'', ''Dashboard Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingDashboard'', ''H2'', 1, ''Aging Periods'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required)
VALUES (''billingDashboard'', ''Period1'', 2, ''Period 1'', ''30'', NULL, ''number:n0'', NULL, NULL, NULL, 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required)
VALUES (''billingDashboard'', ''Period2'', 3, ''Period 2'', ''60'', NULL, ''number:n0'', NULL, NULL, NULL, 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required)
VALUES (''billingDashboard'', ''Period3'', 4, ''Period 3'', ''90'', NULL, ''number:n0'', NULL, NULL, NULL, 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingDashboard'', ''LimitToAM'', 5, ''Limit results to the account manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingDashboard'', ''SummarizeResults'', 6, ''Summarize excessive chart widget results'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)


--exec spConvertAppSeed  


/*************************************************************************************************************************
Billing Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingToday'', ''System Settings'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''H1'', 0, ''Billing Worksheets'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''BillingWorksheetsInReview'', 1, ''Billing Worksheets in Review'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''BillingWorksheetsToApprove'', 2, ''Billing Worksheets to Approve'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''ReadyToCreateInvoices'', 3, ''Ready to Create Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''H2'', 4, ''To Bill As Of'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''TimeAndMaterial'', 5, ''Time And Material'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''billingToday'', ''TMProjectStatus'', 6, ''Project Status'', ''-3'', ''All'', ''selectlist'', NULL, ''selectlist.ProjectStatus'', ''This is for Time and Material billing only'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''TMProjectBillingStatus'', 7, ''Billing Status'', ''-1'', ''All'', ''selectlist'', NULL, ''selectlist.ProjectBillingStatus'', ''This is for Time and Material billing only'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''FixedFee'', 8, ''Fixed Fee'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''Retainer'', 9, ''Retainer'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''Media'', 10, ''Media'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''FixedFeeCampaign'', 11, ''Fixed Fee Campaigns'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''H3'', 12, ''Invoices'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''WaitingToSend'', 13, ''Waiting to be Submitted'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''WaitingForApproval'', 14, ''Waiting for Approval'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField)
VALUES (''billingToday'', ''IncludeAllApprovers'', 15, ''Include all Approvers'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Include invoices waiting for approval for all approvers'', ''WaitingForApproval'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''InvoicesToPrintOrEmail'', 16, ''Invoices to Print or Email'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''ScheduledInvoices'', 17, ''Scheduled Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''ScheduledTransactions'', 18, ''Scheduled Transactions'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''PayByCC'', 19, ''Pay by Credit Card'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''billingToday'', ''H5'', 20, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''DailyFeed'', 21, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingToday'', ''FeedProjectOptions'', 22, ''Project Options'', ''0'', ''All Projects'', ''lookup'', ''All Projects:0|All Project I Am Assigned To:1|Projects Where I Am The Account Manager:2|Only Projects In My Office:3'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''H8'', 23, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''billingToday'', ''SortConversations'', 24, ''Sort Conversations'', ''DESC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''FilterProjectTab'', 25, ''Only show Project Conversations sent to me'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''H6'', 26, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''ShowInOutBoard'', 26, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''H7'', 28, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''hideSchedule'', 29, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''HideEnterTime'', 30, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingToday'', ''DisplayTimeEntries'', 31, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''billingToday'', ''DisplayTimeEntriesComments'', 32, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''billingToday'', ''IncludePublicMeetings'', 33, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingToday_18'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''billingToday_18'', ''grdOpenItemsList_18'', 1, ''Columns'', ''colBillingMethodName,colMasterWS,colProjectName,colProjectNumber,colDueDate,colFFTotal,colLaborTotal,colExpenseTotal,colOriginalToBill,colToBill,colWOTotal,colTransferTotal,colHoldTotal,colDoNotBillTotal,colPriorBilled,colCampaignName,colBudgetAmount'', NULL, ''grid'', 
''[	{id:"colBillingMethodName", label:"Billing Method"},
		{id:"colProjectName", label:"Project Name"},
		{id:"colBillingID", label:"ID"},
		{id:"colMasterWS", label:"Master"},
		{id:"colProjectNumber", label:"Project Number"},
		{id:"colDueDate", label:"Due Date"},
		{id:"colFFTotal", label:"Fixed Fee Total"},
		{id:"colLaborTotal", label:"Labor Total"},
		{id:"colExpenseTotal", label:"Expense Total"},
		{id:"colOriginalToBill", label:"Original To Bill"},
		{id:"colToBill", label:"To Bill"},
		{id:"colWOTotal", label:"To Write Off"},
		{id:"colTransferTotal", label:"Transfer"},
		{id:"colHoldTotal", label:"Hold"},
		{id:"colDoNotBillTotal", label:"Do Not Bill"},
		{id:"colPriorBilled", label:"Prior Billed"},
		{id:"colCurrencyID", label:"Currency"},
		{id:"colRetainerAmount", label:"Retainer Amount"},
		{id:"colWorkSheetComment", label:"Worksheet Comments"},
		{id:"colApprovalComments", label:"Approval Comments"},
		{id:"colCampaignName", label:"Campaign Name"},
		{id:"colBudgetAmount", label:"Budget"},
		{id:"colAddable", label:"Addable Transactions"},
	    {id:"colMarkedAsBilledExpenses", label:"Marked as Billed Expenses"},
	    {id:"colMarkedAsBilledLabor", label:"Marked as Billed Labor"},
		{id:"colProjectManager", label:"Project Manager"}
 ]''
 , NULL, NULL, NULL, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingToday_7'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''billingToday_7'', ''grdOpenItemsList_7'', 1, ''Columns'', ''colMasterWS,colBillingMethodName,colProjectName,colProjectNumber,colDueDate,colFFTotal,colLaborTotal,colExpenseTotal,colOriginalToBill,colToBill,colWOTotal,colTransferTotal,colHoldTotal,colDoNotBillTotal,colPriorBilled'', NULL, ''grid'', 
''[	{id:"colBillingMethodName", label:"Billing Method"},
		{id:"colProjectName", label:"Project Name"},
		{id:"colProjectNumber", label:"Project Number"},
		{id:"colBillingID", label:"ID"},
		{id:"colMasterWS", label:"Master"},
		{id:"colDueDate", label:"Due Date"},
		{id:"colFFTotal", label:"Fixed Fee Total"},
		{id:"colLaborTotal", label:"Labor Total"},
		{id:"colExpenseTotal", label:"Expense Total"},
		{id:"colOriginalToBill", label:"Original To Bill"},
		{id:"colToBill", label:"To Bill"},
		{id:"colWOTotal", label:"To Write Off"},
		{id:"colTransferTotal", label:"Transfer"},
		{id:"colHoldTotal", label:"Hold"},
		{id:"colDoNotBillTotal", label:"Do Not Bill"},
		{id:"colPriorBilled", label:"Prior Billed"},
		{id:"colCurrencyID", label:"Currency"},
		{id:"colRetainerAmount", label:"Retainer Amount"},
		{id:"colWorkSheetComment", label:"Worksheet Comments"},
		{id:"colApprovalComments", label:"Approval Comments"},
		{id:"colCampaignName", label:"Campaign Name"},
		{id:"colBudgetAmount", label:"Budget"},
		{id:"colProjectManager", label:"Project Manager"}
 ]''
 , NULL, NULL, NULL, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingToday_19'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''billingToday_19'', ''grdOpenItemsList_19'', 1, ''Columns'', ''colBillingMethodName,colProjectName,colProjectNumber,colDueDate,colFFTotal,colLaborTotal,colExpenseTotal,colOriginalToBill,colToBill,colWOTotal,colTransferTotal,colHoldTotal,colDoNotBillTotal,colPriorBilled,colErrorMsg,colRetainerAmount'', NULL, ''grid'', 
''[	{id:"colBillingMethodName", label:"Billing Method"},
		{id:"colProjectName", label:"Project Name"},
		{id:"colProjectNumber", label:"Project Number"},
		{id:"colBillingID", label:"ID"},		
		{id:"colDueDate", label:"Due Date"},
		{id:"colFFTotal", label:"Fixed Fee Total"},
		{id:"colLaborTotal", label:"Labor Total"},
		{id:"colExpenseTotal", label:"Expense Total"},
		{id:"colOriginalToBill", label:"Original To Bill"},
		{id:"colToBill", label:"To Bill"},
		{id:"colWOTotal", label:"To Write Off"},
		{id:"colTransferTotal", label:"Transfer"},
		{id:"colHoldTotal", label:"Hold"},
		{id:"colDoNotBillTotal", label:"Do Not Bill"},
		{id:"colPriorBilled", label:"Prior Billed"},
		{id:"colCurrencyID", label:"Currency"},
		{id:"colErrorMsg", label:"Error Message"},
		{id:"colRetainerAmount", label:"Retainer Amount"},
		{id:"colWorkSheetComment", label:"Worksheet Comments"},
		{id:"colApprovalComments", label:"Approval Comments"},
		{id:"colCampaignName", label:"Campaign Name"},
		{id:"colProjectManager", label:"Project Manager"}
 ]''
 , NULL, NULL, NULL, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingToday_23'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''billingToday_23'', ''grdOpenItemsList_23'', 1, ''Columns'', ''colBillingMethodName,colProjectName,colProjectNumber,colDueDate,colFFTotal,colLaborTotal,colExpenseTotal,colOriginalToBill,colToBill,colWOTotal,colTransferTotal,colHoldTotal,colDoNotBillTotal,colPriorBilled'', NULL, ''grid'', 
''[	{id:"colBillingMethodName", label:"Billing Method"},
		{id:"colProjectName", label:"Project Name"},
		{id:"colProjectNumber", label:"Project Number"},
		{id:"colDueDate", label:"Due Date"},
		{id:"colFFTotal", label:"Fixed Fee Total"},
		{id:"colLaborTotal", label:"Labor Total"},
		{id:"colExpenseTotal", label:"Expense Total"},
		{id:"colOriginalToBill", label:"Original To Bill"},
		{id:"colToBill", label:"To Bill"},
		{id:"colWOTotal", label:"To Write Off"},
		{id:"colTransferTotal", label:"Transfer"},
		{id:"colHoldTotal", label:"Hold"},
		{id:"colDoNotBillTotal", label:"Do Not Bill"},
		{id:"colPriorBilled", label:"Prior Billed"},
		{id:"colCurrencyID", label:"Currency"},
		{id:"colRetainerAmount", label:"Retainer Amount"},
		{id:"colWorkSheetComment", label:"Worksheet Comments"},
		{id:"colApprovalComments", label:"Approval Comments"},
		{id:"colCampaignName", label:"Campaign Name"},
		{id:"colProjectManager", label:"Project Manager"}		
 ]''
 , NULL, NULL, NULL, NULL)

 
 
/*************************************************************************************************************************
Purchasing Today 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''purchasingToday'', ''System Settings'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H1'', 0, ''Open Items'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''OpenRequestsForQuotes'', 1, ''Requests for Quotes'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''OpenItemsOrders'', 2, ''Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''UnapprovedOrders'', 3, ''Unapproved Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''UnsubmittedOrders'', 4, ''Unsubmitted Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''MyOpenItemsOnly'', 5, ''My Open Items Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H2'', 6, ''Incoming Charges'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''IncomingCharges'', 7, ''Incoming Charges'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H3'', 8, ''To Pay As Of'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''ToPayExpenseReports'', 9, ''Expense Reports'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''ToPayVendorInvoices'', 10, ''Vendor Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''ToPayCreditCards'', 11, ''Credit Cards'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H4'', 12, ''Invoices'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''WaitingToCreateInvoices'', 13, ''Expense Reports Waiting to Create Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''WaitingToSend'', 14, ''Waiting to be Submitted'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''WaitingForApproval'', 15, ''Waiting for Approval'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''RejectedInvoices'', 16, ''Rejected Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''ScheduledInvoices'', 17, ''Scheduled Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''ScheduledTransactions'', 18, ''Scheduled Transactions'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H5'', 19, ''Payments'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''PrintChecks'', 20, ''Checks to Print'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''CCNotSent'', 21, ''Charges not Sent'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''CCNotViewed'', 22, ''Charges Sent but not Viewed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H6'', 23, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''DailyFeed'', 24, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''purchasingToday'', ''FeedProjectOptions'', 25, ''Project Options'', ''0'', ''All Projects'', ''lookup'', ''All Projects:0|All Project I Am Assigned To:1|Projects Where I Am The Account Manager:2|Only Projects In My Office:3'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H7'', 26, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''purchasingToday'', ''SortConversations'', 27, ''Sort Conversations'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''FilterProjectTab'', 28, ''Only show Project Conversations sent to me'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H8'', 29, ''In/Out Board Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''ShowInOutBoard'', 30, ''Show In/Out Board'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''H9'', 31, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''hideSchedule'', 32, ''Hide the schedule on the side'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''HideEnterTime'', 33, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''DisplayTimeEntries'', 34, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''purchasingToday'', ''DisplayTimeEntriesComments'', 35, ''Display Time Entry Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''DisplayTimeEntries'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchasingToday'', ''IncludePublicMeetings'', 36, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Project Manager Scoreboard
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectSummaryScoreboard'', ''Scoreboard Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''ShowZeroes'', 1, ''Show Zeroes'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''ShowLaborNet'', 2, ''Show Labor Net'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''ShowLaborGross'', 3, ''Show Labor Gross'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''UseClientDivision'', 4, ''Display Client Division'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''LimitToAM'', 5, ''Limit results to the account manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''SummarizeResults'', 6, ''Summarize excessive chart widget results'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''H2'', 7, ''Choose Sections to View'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeRequests'', 8, ''Project Requests'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeProjectSummary'', 9, ''Project Summary'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeCompletedProjects'', 10, ''Completed Projects by Project Type'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeHoursByProjectType'', 11, ''Hours by Project Type'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeHoursByClient'', 12, ''Hours by Client'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeHoursByDivision'', 13, ''Hours by Division'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeBillingByClient'', 14, ''Billings by Client'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''WithAdvBills'', 15, ''Billings with Advanced Bills'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''IncludeProjectDetails'', 16, ''Completed Project Details'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
/*
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField)
VALUES (''projectSummaryScoreboard'', ''ProjectDetailsGroupBy'', 14, ''Group Project Details by'', ''1'', ''Project Type'', ''lookup'', ''Project Type:1|Client:2|Division:3'', NULL, NULL, ''IncludeProjectDetails'')
*/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSummaryScoreboard'', ''ProjectDetailsGroupBy'', 17, ''Group Project Details by'', ''1'', ''Project Type'', ''lookup'', ''Project Type:1|Client:2|Division:3'', NULL, NULL)

/*************************************************************************************************************************
Project Setup 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectSetup'', ''Project Setup Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSetup'', ''H2'', 1, ''Printing Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSetup'', ''ShowSummaryTasksOnly'', 2, ''Print Summary Tasks Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSetup'', ''LargePrint'', 3, ''Print With Larger Font'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Project Files 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectFiles'', ''Project Files Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFiles'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectFiles'', ''SortBy'', 1, ''Sort By'', ''2'', ''Last Modified'', ''lookup'', ''Name:0|Size:1|Last Modified:2|Modified By:3|Uploaded:4|Uploaded By:5'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectFiles'', ''Direction'', 2, ''Direction'', ''1'', ''Descending'', ''lookup'', ''Ascending:0|Descending:1'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectFiles'', ''ShowThumbnails'', 3, ''Show Thumbnails'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)




/*************************************************************************************************************************
Project Add 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectAdd'', ''Add Project Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''AddPrimaryContact'', 1, ''Add Primary Contact and Project Requester to the project team'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''DefaultOfficeFromUser'', 2, ''Default Office From User'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''ShowProjectNumber'', 3, ''Show Project Number'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''ShowClientProjectNumber'', 4, ''Show Client Project Number'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''ShowAccountManager'', 5, ''Show Account Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''AccountManagerRequired'', 6, ''Require Account Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''ClientRequired'', 7, ''Require Client'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''AccountTeamRequired'', 8, ''Require Account Team'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''TemplateProjectRequired'', 9, ''Require Template/Project to Copy'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''StartDateDueDateRequired'', 10, ''Require Start Date / Due Date'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref) 
Values (''projectAdd'', ''ShowProjectManager'', 11, ''Show Project Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''ShowProjectManager'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref) 
Values (''projectAdd'', ''ProjectManagerRequired'', 12, ''Require Project Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''ShowProjectManager'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''CopyEstimates'', 13, ''Copy Estimates'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''CopyFiles'', 14, ''Copy Files'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''CopySpecSheets'', 15, ''Copy Specs'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''ShowPlanningProject'', 16, ''Show Planning Project'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectAdd'', ''AssignedTemplatesOnly'', 17, ''Copy from Assigned Templates Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Project Edit 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectEdit'', ''Edit Project Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectEdit'', ''DisableEditingProjectNumber'', 1, ''Disable the editing of the Project Number'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Project Dashboard 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectDashBoard'', ''Project Dashboard Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardSettings'', 1, ''Dashboard Sections'', NULL, NULL, ''sectionheader'', NULL, NULL, ''Enabling a checkbox below will show the option in the Project Details section on the project dashboard.  The show on right option will remove the section from the Project Details and only show it on the right side within the body.'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardProjecNextStepsSR'', 2, ''Show Next Steps on right'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardProjecStatusNotesSR'', 3, ''Show Status Notes on right'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardProjectDescriptionSR'', 3, ''Show Project Description on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardDailyFeed'', 5, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''projectDashBoard'', ''DashboardDailyFeedSR'', 6, ''Show Daily Feed on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL, ''DashboardDailyFeed'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardBurnChart'', 7, ''Burn Chart'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardDiary'', 8, ''Recent Conversations'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''projectDashBoard'', ''DashboardIncludeActivities'', 9, ''Include sales conversations'', ''0'', NULL, ''checkbox'', NULL, NULL, ''This will include conversations entered in the sales area linked to this project.'', ''DashboardDiary'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''projectDashBoard'', ''DashboardDiarySR'', 10, ''Show Conversations on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL, ''DashboardDiary'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardCustomFieldsSR'', 11, ''Show Custom Fields on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardSnapshotSR'', 12, ''Show Project Snapshot'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardProfitabilitySR'', 13, ''Show Project Profitability'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardTeamSR'', 14, ''Show Team on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardSpecsheets'', 15, ''SpecSheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''projectDashBoard'', ''DashboardSpecsheetsSR'', 16, ''Show Specsheets on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL, ''DashboardSpecsheets'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardDeliverables'', 17, ''Deliverables'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''projectDashBoard'', ''DashboardDeliverablesSR'', 18, ''Show Deliverables on right'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL, ''DashboardDeliverables'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardCustomFiledsForTempate'', 19, ''Show Custom Fields for Template'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardChangeRequest'', 20, ''Show Project Change Requests'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''DashboardShowClosedBilling'', 21, ''Show Billing for Closed Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectDashBoard'', ''showProjectTrackingForms'', 22, ''Show Tracking Forms'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectDashBoard'', ''H3'', 23, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectDashBoard'', ''ShowTimeEntries'', 24, ''Show Time Entries'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Project Schedule
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectSchedule'', ''Project Schedule Grid'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
delete tAppSetting Where GroupID = ''projectSchedule'' and SessionID = ''AutoSave''
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''projectSchedule'', ''AutoSave'', 1, ''Auto Save Schedule'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''projectSchedule'', ''ScheduleLockedColumns'', 2, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectSchedule'', ''grdProjectScheduleCols'', 3, ''Columns'', ''prjScheduleTaskStatus,prjScheduleAssigned,prjScheduleAssignedFullName,prjSchedulePlanDuration,prjSchedulePlanStart,prjSchedulePlanComp,prjScheduleActualHours,prjScheduleActualStart,prjScheduleActualComplete,prjSchedulePercComp,prjSchedulePredecessors,prjScheduleLine'', NULL, ''grid'', 

''[	{id:"prjSchedulePlanDuration", label:"Days"},
	{id:"prjSchedulePlanStart", label:"Plan Start"},
	{id:"prjSchedulePlanComp", label:"Plan Complete"},
	{id:"prjScheduleTrackSeparately", label:"Track Separately"},
	{id:"prjSchedulePercComp", label:"%"},
	{id:"prjScheduleAssigned", label:"Assigned"},
	{id:"prjScheduleAssignedFullName", label:"Assigned Full Name"},
	{id:"prjScheduleActualHours", label:"Actual Hours"},
	{id:"prjSchedulePredecessors", label:"Predecessors"},
	{id:"prjScheduleActualStart", label:"Actual Start"},
	{id:"prjScheduleActualComplete", label:"Actual Complete"},
	{id:"prjScheduleAllTimesheets", label:"All Time Sheets"},
	{id:"prjScheduleBillingItem", label:"Billing Item"},
	{id:"prjScheduleBOCommision", label:"BO Commission"},
	{id:"prjScheduleConstraint", label:"Constraint"},
	{id:"prjScheduleConstraintDate", label:"Constraint Date"},
	{id:"prjScheduleConstraintDayOfWeek", label:"Constraint Day Of The Week"},
	{id:"prjScheduleDescription", label:"Description"},
	{id:"prjScheduleDueComment", label:"Due Comment"},
	{id:"prjScheduleAllocHours", label:"Allocated Hours"},
	{id:"prjScheduleRemainingHours", label:"Remaining Hours"},
	{id:"prjScheduleEstHours", label:"Est Hours"},
	{id:"prjScheduleHideFromClient", label:"Hide From Client"},
	{id:"prjScheduleMustFinishOnPredComplete", label:"Must Finish On when Pred Complete"},
	{id:"prjScheduleHourlyRate", label:"Hourly Rate"},
	{id:"prjScheduleIOCommision", label:"IO Commission"},

	{id:"prjScheduleLine", label:"Line"},
	{id:"prjScheduleMarkup", label:"Markup"},
	{id:"prjScheduleOrigStart", label:"Baseline Start"},
	{id:"prjScheduleOrigComp", label:"Baseline Complete"},
	{id:"prjSchedulePriority", label:"Priority"},
	{id:"prjScheduleReviewed", label:"Reviewed"},
	{id:"prjScheduleTaskScheduled", label:"Show On Schedule"},
	{id:"prjScheduleShowOnEstimate", label:"Show On Estimate"},
	{id:"prjScheduleTaskStatus", label:"Status"},
	{id:"prjScheduleStatusDescription", label:"Status Comment"},
	{id:"prjScheduleTaskID", label:"Task ID"},
	{id:"prjScheduleTax1", label:"Tax 1"},
	{id:"prjScheduleTax2", label:"Tax 2"},
	{id:"prjScheduleDateAssigned", label:"Date Assigned"},
	{id:"prjScheduleTimeAssigned", label:"Time Assigned"},
	{id:"prjScheduleTrackBudgets", label:"Track Budgets"},
	{id:"prjScheduleExcludeFromStatus", label:"Exclude From Status"},
	{id:"prjScheduleWorkAnyDay", label:"Work Any Day"},
	{id:"prjScheduleTimelineSection", label:"Timeline Section"},
	{id:"prjScheduleTimelineSegmentDisplayName", label:"Override Display Name"},
	{id:"prjScheduleTCProjectStatus", label:"Task Complete Project Status"},
	{id:"prjScheduleOpenToDos", label:"Open ToDos"},
	{id:"prjSchedulePredLegacy", label:"Predecessor Lookup"},
	{id:"prjScheduleConversationCount", label:"Conversation Count"},
	{id:"prjScheduleAllocatedHoursGross", label:"Allocated Hours Gross"},
	{id:"prjScheduleBudgetLaborGross", label:"Curr Budget Labor Gross"},
	{id:"prjScheduleNoTimeEntry", label:"Time Entry Excluded", customization:"deborahWoodTaskNoTime"},
	{id:"prjScheduleDeliverableCount", label:"Deliverable Count"},
	{id:"prjScheduleBudgetRemainingHours", label:"Budget Remaining Hours"}
 ]''
	 , NULL, NULL, null, null)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''OpenExpanded'', 4, ''Expand Schedule When Opened'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''editColumnSets'', 5, ''Edit Column Sets'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''IncludeProjects'', 6, ''Include Projects in Template List'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''IncludeAssignedEmailTo'', 7, ''Include Assigned Users on Task Conversation Email List '', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''PrevTaskPred'', 8, ''Set Previous Task as Predecessor of New Task'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''DefaultTrackBudget'', 9, ''Default Track Budget on New Task'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''PrjSchedBurnChart'', 10, ''Burn Chart'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSchedule'', ''ShowSetBaseline'', 10, ''Show Set Baseline'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Project Template
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectTemplate'', ''Project Template Grid'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectTemplate'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''projectTemplate'', ''TemplateLockedColumns'', 1, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectTemplate'', ''grdProjectTemplateCols'', 2, ''Columns'', ''prjSchedulePlanDuration,prjScheduleAssigned,prjSchedulePredecessors,prjScheduleLine,prjScheduleTrackBudgets,prjScheduleTCProjectStatus'', NULL, ''grid'', 

''[	{id:"prjSchedulePlanDuration", label:"Days"},
	{id:"prjSchedulePlanStart", label:"Plan Start"},
	{id:"prjSchedulePlanComp", label:"Plan Complete"},
	{id:"prjScheduleAssigned", label:"Assigned"},
	{id:"prjSchedulePredecessors", label:"Pred"},
	{id:"prjScheduleAllTimesheets", label:"All Time Sheets"},
	{id:"prjScheduleBillingItem", label:"Billing Item"},
	{id:"prjScheduleConstraint", label:"Constraint"},
	{id:"prjScheduleConstraintDate", label:"Constraint Date"},
	{id:"prjScheduleConstraintDayOfWeek", label:"Constraint Day Of The Week"},
	{id:"prjScheduleDescription", label:"Description"},
	{id:"prjScheduleEstHours", label:"Est Hours"},
	{id:"prjScheduleHideFromClient", label:"Hide From Client"},
	{id:"prjScheduleHourlyRate", label:"Hourly Rate"},
	{id:"prjScheduleLine", label:"Line"},
	{id:"prjScheduleMarkup", label:"Markup"},
	{id:"prjSchedulePriority", label:"Priority"},
	{id:"prjScheduleTaskScheduled", label:"Show On Schedule"},
	{id:"prjScheduleShowOnEstimate", label:"Show On Estimate"},
	{id:"prjScheduleTaskID", label:"Task ID"},
	{id:"prjScheduleTax1", label:"Tax 1"},
	{id:"prjScheduleTax2", label:"Tax 2"},
	{id:"prjScheduleTrackBudgets", label:"Track Budgets"},
	{id:"prjScheduleWorkAnyDay", label:"Work Any Day"},
	{id:"prjScheduleTimelineSection", label:"Timeline Section"},
	{id:"prjScheduleStatusDescription", label:"Status Comment"},
	{id:"prjScheduleTCProjectStatus", label:"Task Complete Project Status"},
	{id:"prjScheduleAllocHours", label:"Allocated Hours"}
 ]''
	 , NULL, NULL, null, null)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectTemplate'', ''editColumnSets'', 3, ''Edit Column Sets'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Project Spec Sheet
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectSpecSheets'', ''Spec Sheet Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSpecSheets'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSpecSheets'', ''useGridMode'', 1, ''Use Spec Sheet Grid Mode'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectSpecSheets'', ''SortByDateCreated'', 2, ''Sort Non-Grid Mode By Date Created'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectSpecSheets'', ''grdSpecSheetsCols'', 3, ''Columns'', ''specFullSpecID,specVersion,specSubject,specDescription,specCreatedBy,specDateCreated,specUpdatedBy,specDateUpdated'', NULL, ''grid'', 

''[	{id:"specSubject", label:"Subject"},
	{id:"specDescription", label:"Description"},
	{id:"specSpecID", label:"Spec ID"},
	{id:"specFullSpecID", label:"Full Spec ID"},
	{id:"specCreatedBy", label:"Created By"},
	{id:"specDateCreated", label:"Date Created"},
	{id:"specUpdatedBy", label:"Updated By"},
	{id:"specDateUpdated", label:"Date Updated"},
	{id:"specVersion", label:"Approved Version"}
 ]''
	 , NULL, NULL, ''Spec'', ''Spec'')


/*************************************************************************************************************************
Campaign Spec Sheet
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignSpecSheets'', ''Spec Sheet Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignSpecSheets'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campaignSpecSheets'', ''grdSpecSheetsCols'', 3, ''Columns'', ''specSubject,specDescription,specCreatedBy,specDateCreated,specUpdatedBy,specDateUpdated'', NULL, ''grid'', 

''[	{id:"specSubject", label:"Subject"},
	{id:"specDescription", label:"Description"},
	{id:"specSpecID", label:"Spec ID"},
	{id:"specFullSpecID", label:"Full Spec ID"},
	{id:"specCreatedBy", label:"Created By"},
	{id:"specDateCreated", label:"Date Created"},
	{id:"specUpdatedBy", label:"Updated By"},
	{id:"specDateUpdated", label:"Date Updated"}
 ]''
	 , NULL, NULL, ''Spec'', ''Spec'')


/*************************************************************************************************************************
Project Requests
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectRequestEdit'', ''Project Request Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestEdit'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestEdit'', ''useGridMode'', 1, ''Use Spec Sheet Grid Mode'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestEdit'', ''editSpecByClient'', 2, ''Client can edit Subject/Description'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestEdit'', ''resendCancelApprovedRequest'', 3, ''Cancel/Resend Approved Project Requests'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestEdit'', ''useConversations'', 4, ''Use Conversations'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectRequestEdit'', ''grdSpecSheetsCols'', 5, ''Columns'', ''specSubject,specDescription,specCreatedBy,specDateCreated,specUpdatedBy,specDateUpdated'', NULL, ''grid'', 

''[	{id:"specSubject", label:"Subject"},
	{id:"specDescription", label:"Description"},
	{id:"specSpecID", label:"Spec ID"},
	{id:"specCreatedBy", label:"Created By"},
	{id:"specDateCreated", label:"Date Created"},
	{id:"specUpdatedBy", label:"Updated By"},
	{id:"specDateUpdated", label:"Date Updated"}
 ]''
	 , NULL, NULL, ''Spec'', ''Spec'')


/*************************************************************************************************************************
Task Edit ToDos
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''taskEditToDo'', ''Task Edit To Do Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''taskEditToDo'', ''EditInGrid'', 1, ''Edit To Dos directly in grid'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''taskEditToDo'', ''grdToDosCols'', 3, ''Columns'', ''toDoSubject,toDoCompleted'', NULL, ''grid'', 

''[	{id:"toDoSubject", label:"Subject"},
	{id:"toDoCompleted", label:"Completed"},
	{id:"todoUserFullName", label:"Assigned To"}
 ]''
	 , NULL, NULL, ''Activity'',''Activity'')

/*************************************************************************************************************************
Select Invoices to Pay
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''payvouchers'', ''Select Invoices To Pay Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''payvouchers'', ''H_GRID'', 0, ''Grid Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''payvouchers'', ''grdVoucherCols'', 1, ''Columns'', ''payvouchVendor,payvouchVendorID,payvouchInvoiceNumber,payvouchOriginalOpenAmount,payvouchDiscAmount,payvouchOpenAmount,payvouchCurrency'', NULL, ''grid'', 

''[
{id:"payvouchVendor", label:"Vendor"},
{id:"payvouchVendorID", label:"Vendor ID"},
{id:"payvouchInvoiceNumber", label:"Invoice Number"},
{id:"payvouchDiscAmount", label:"Discount"},
{id:"payvouch1099", label:"Exclude From 1099"},
{id:"payvouchOpenAmount", label:"Amount to Pay"},
{id:"payvouchCurrency", label:"Currency"},
{id:"payvouchGLCompany", label:"Company"},
{id:"payvouchClass", label:"Class"},
{id:"payvouchInvoiceDate", label:"Invoice Date"},
{id:"payvouchDiscountDate", label:"Discount Date"},
{id:"payvouchDueDate", label:"Due Date"},
{id:"payvouchOriginalOpenAmount", label:"Open Amount"},
{id:"payvouchCompanyType", label:"Company Type"},
{id:"payvouchPaidByClient", label:"Paid By Client"},
{id:"payvouchBilledToClient", label:"Billed to Client"},
{id:"payvouchClient", label:"Client"},
{id:"payvouchClientID", label:"Client ID"},
{id:"payvouchDaysOld", label:"Days Old"},
{id:"payvouchDescription", label:"Description"},
{id:"payvouchDateCreated", label:"Date Created"},
{id:"payvouchDateReceived", label:"Date Received"},
{id:"payvouchACHEnabled", label:"ACH Enabled"}
]''
	 , NULL, NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''payvouchers'', ''Grouping1'', 2, ''Order By 1'', ''1'', ''Vendor Name'', ''lookup'', ''Vendor Name:1|Vendor ID:2|Client Name:3|Client ID:4|Invoice Number:5|Invoice Date:6|Due Date:7|Open Amount:8|Company Type:9'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''payvouchers'', ''Grouping2'', 3, ''Order By 2'', ''0'', ''No Sort'', ''lookup'', ''No Sort:0|Vendor Name:1|Vendor ID:2|Client Name:3|Client ID:4|Invoice Number:5|Invoice Date:6|Due Date:7|Open Amount:8|Company Type:9'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''payvouchers'', ''Grouping3'', 4, ''Order By 3'', ''0'', ''No Sort'', ''lookup'', ''No Sort:0|Vendor Name:1|Vendor ID:2|Client Name:3|Client ID:4|Invoice Number:5|Invoice Date:6|Due Date:7|Open Amount:8|Company Type:9'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''payvouchers'', ''InvoicesBilledToClient'', 5, ''Invoices Billed to Client'', ''0'', ''Invoices Billed to Client'', ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''payvouchers'', ''InvoicesPaidByClient'', 6, ''Invoices Paid by Client'', ''0'', ''Invoices Paid by Client'', ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''payvouchers'', ''HideBankAccountBalances'', 7, ''Hide Bank Account Balances'', ''0'', ''Hide Bank Account Balances'', ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Select Invoices to Pay
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''paycreditcards'', ''Pay Credit Card Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''paycreditcards'', ''H_GRID'', 0, ''Grid Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paycreditcards'', ''grdVoucherCols'', 1, ''Columns'', ''payccBoughtByName,payccBoughtFrom,payccVoucherID,payccInvoiceDate,payccCurrency,payccOpenAmount,payccVoucherTotal,payccDiscount,payccReference,payccPostingDate,payccPosted,payccGLCompany,payccClass'', NULL, ''grid'', 

''[
{id:"payccBoughtByName", label:"Charged By"},
{id:"payccBoughtFrom", label:"Purchased From"},
{id:"payccVoucherID", label:"Ref #"},
{id:"payccInvoiceDate", label:"Invoice Date"},
{id:"payccCurrency", label:"Currency"},
{id:"payccOpenAmount", label:"Amount To Pay"},
{id:"payccVoucherTotal", label:"Charge Amount"},
{id:"payccDiscount", label:"Discount"},
{id:"payccReference", label:"Reference"},
{id:"payccPostingDate", label:"Posting Date"},
{id:"payccPosted", label:"Posted"},
{id:"payccGLCompany", label:"Company"},
{id:"payccClass", label:"Class"},
{id:"payccDescription", label:"Description"}
]''
	 , NULL, NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''paycreditcards'', ''HideBankAccountBalances'', 7, ''Hide Bank Account Balances'', ''0'', ''Hide Bank Account Balances'', ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Project Budget
**************************************************************************************************************************/	 

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetSettings'', ''Project Budget Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''H_BY_ITEM'', 0, ''BY ITEM'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''prjbudgetSettings'', ''ScheduleLockedColumns1'', 1, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''HITEM1'', 2, ''Labor Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetServiceCols'', 3, ''Columns'', ''prjbudCurrentBudgetHours,prjbudCurrentTotalBudget,prjbudHours,prjbudLaborGross,prjbudTotalGross,prjbudRemainingAllocatedHours'', NULL, ''grid'', 

''[
{id:"prjbudCurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudCurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudCurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudCurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudCurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudCurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudCOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudCOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudCOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudCOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudCOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudCOTotalBudget", label:"CO Total Budget"},
{id:"prjbudCOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudHours", label:"Act Hours"},
{id:"prjbudHoursBilled", label:"Hours Billed"},
{id:"prjbudHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudHoursWriteOff", label:"Hours WriteOff"},
{id:"prjbudHoursAfterWriteOff", label:"Hours After WriteOff"},
{id:"prjbudHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudLaborNet", label:"Labor Net"},
{id:"prjbudLaborGross", label:"Labor Gross"},
{id:"prjbudLaborBilled", label:"Labor Billed"},
{id:"prjbudLaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudLaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudLaborWriteOff", label:"Labor WriteOff"},
{id:"prjbudLaborAfterWriteOff", label:"Labor After WriteOff"},
{id:"prjbudOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudExpenseWriteOff", label:"Expense WriteOff"},
{id:"prjbudExpenseBilled", label:"Expense Billed"},
{id:"prjbudExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudAdvanceBilled", label:"Advance Billed"},
{id:"prjbudAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudAmountBilled", label:"Amount Billed"},
{id:"prjbudAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudTotalCostsNet", label:"Total Costs Net"},
{id:"prjbudTotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudTotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudTotalNet", label:"Total Net"},
{id:"prjbudTotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudTotalGross", label:"Total Gross"},
{id:"prjbudTotalGrossAfterWriteOff", label:"Total Gross After WriteOff"},
{id:"prjbudRemainingAllocatedHours", label:"Remaining Allocated Hours"},
{id:"prjbudAllocatedHours", label:"Allocated Hours"},
{id:"prjbudPAllocated", label:"Percentage of Allocated"},
{id:"prjbudFutureAllocatedHours", label:"Future Allocated Hours"},
{id:"prjbudAllocatedGross", label:"Allocated Gross"},
{id:"prjbudFutureAllocatedGross", label:"Future Allocated Gross"},
{id:"prjbudFutureLaborGrossRemaining", label:"Future Labor Gross Remaining"},
{id:"prjbudHoursBilledRemaining", label:"Hours Billed Remaining"},
{id:"prjbudHoursBilledRemainingP", label:"Hours Billed Remaining %"},
{id:"prjbudHoursRemaining", label:"Hours Remaining"},
{id:"prjbudHoursRemainingP", label:"Hours Remaining %"},
{id:"prjbudHoursAfterWriteOffRemaining", label:"Hours After WriteOff Remaining"},
{id:"prjbudHoursAfterWriteOffRemainingP", label:"Hours After WriteOff Remaining %"},
{id:"prjbudLaborNetRemaining", label:"Labor Net Remaining"},
{id:"prjbudLaborNetRemainingP", label:"Labor Net Remaining %"},
{id:"prjbudLaborGrossRemaining", label:"Labor Gross Remaining"},
{id:"prjbudLaborGrossRemainingP", label:"Labor Gross Remaining %"},
{id:"prjbudLaborGrossAfterWriteOffRemaining", label:"Labor Gross After WriteOff Remaining"},
{id:"prjbudLaborGrossAfterWriteOffRemainingP", label:"Labor Gross After WriteOff Remaining %"},
{id:"prjbudCostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudCostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudCostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudCostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudGrossRemaining", label:"Gross Remaining"},
{id:"prjbudGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudBilledDifference", label:"Billed Difference"},
{id:"prjbudTransferInLabor", label:"Transfer In Labor"},
{id:"prjbudTransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudTransferInExpense", label:"Transfer In Expense"},
{id:"prjbudTransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudVarianceHours", label:"Variance Hours"},
{id:"prjbudSalesTax", label:"Sales Tax"},
{id:"prjbudTotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL)




INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''HITEM2'', 6, ''Expense Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetItemCols'', 7, ''Columns'', ''prjbudICurrentTotalBudget,prjbudITotalGross'', NULL, ''grid'', 

''[{id:"prjbudICurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudICurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudICurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudICurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudICurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudICurrentBudgetExpenseQuantity", label:"Current Budget Expense Quantity"},
{id:"prjbudICOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudICOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudICOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudICOTotalBudget", label:"CO Total Budget"},
{id:"prjbudICOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudIOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudIOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudIOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudIOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudIOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudIOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudIOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudIInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudIOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudIOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudIInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudIOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudIInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudIOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudIExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudIExpenseBilled", label:"Expense Billed"},
{id:"prjbudIExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudIActualQuantity", label:"Actual Quantity"},
{id:"prjbudIAdvanceBilled", label:"Advance Billed"},
{id:"prjbudIAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudIAmountBilled", label:"Amount Billed"},
{id:"prjbudIAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudITotalCostsNet", label:"Total Costs Net"},
{id:"prjbudITotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudITotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudITotalNet", label:"Total Net"},
{id:"prjbudITotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudITotalGross", label:"Total Gross"},
{id:"prjbudITotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudICostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudICostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudICostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudICostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudIToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudIToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudIGrossRemaining", label:"Gross Remaining"},
{id:"prjbudIGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudIBilledDifference", label:"Billed Difference"},
{id:"prjbudITransferInExpense", label:"Transfer In Expense"},
{id:"prjbudITransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudISalesTax", label:"Sales Tax"},
{id:"prjbudITotalCostsGrossAfterWriteOff", label:"Total Costs Gross After WriteOff w Open Orders"},
{id:"prjbudITotalCostsGrossAfterWriteOffNoOrder", label:"Total Costs Gross After WriteOff w/o Open Orders"},
{id:"prjbudICostsGrossAfterWriteOffRemaining", label:"Costs Gross After WriteOff Remaining"},
{id:"prjbudICostsGrossAfterWriteOffRemainingP", label:"Costs Gross After WriteOff Remaining %"},
{id:"prjbudICostsGrossAfterWriteOffNoOrderRemaining", label:"Costs Gross After WriteOff wo Order Remaining"},
{id:"prjbudICostsGrossAfterWriteOffNoOrderRemainingP", label:"Costs Gross After WriteOff wo Order Remaining %"},
{id:"prjbudITotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''H_BY_TYPE'', 8, ''BY TYPE'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''prjbudgetSettings'', ''ScheduleLockedColumns2'', 9, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetTypeCols'', 10, ''Columns'', ''prjbudYCurrentTotalBudget,prjbudYTotalGross,prjbudYRemainingAllocatedHours'', NULL, ''grid'', 

''[{id:"prjbudYCurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudYCurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudYCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudYCurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudYCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudYCurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudYCurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudYCurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudYCurrentBudgetExpenseQuantity", label:"Current Budget Expense Quantity"},
{id:"prjbudYCOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudYCOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudYCOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudYCOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudYCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudYCOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudYCOTotalBudget", label:"CO Total Budget"},
{id:"prjbudYCOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudYOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudYOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudYOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudYOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudYOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudYOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudYOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudYOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudYHours", label:"Act Hours"},
{id:"prjbudYHoursBilled", label:"Hours Billed"},
{id:"prjbudYHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudYHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudYLaborNet", label:"Labor Net"},
{id:"prjbudYLaborGross", label:"Labor Gross"},
{id:"prjbudYLaborBilled", label:"Labor Billed"},
{id:"prjbudYLaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudYLaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudYLaborWriteOff", label:"Labor Write Off"},
{id:"prjbudYOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudYOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudYInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudYOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudYOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudYInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudYOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudYInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudYOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudYExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudYExpenseBilled", label:"Expense Billed"},
{id:"prjbudYExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudYActualQuantity", label:"Actual Quantity"},
{id:"prjbudYAdvanceBilled", label:"Advance Billed"},
{id:"prjbudYAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudYAmountBilled", label:"Amount Billed"},
{id:"prjbudYAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudYTotalCostsNet", label:"Total Costs Net"},
{id:"prjbudYTotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudYTotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudYTotalNet", label:"Total Net"},
{id:"prjbudYTotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudYTotalGross", label:"Total Gross"},
{id:"prjbudYTotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudYRemainingAllocatedHours", label:"Remaining Allocated Hours"},
{id:"prjbudYAllocatedHours", label:"Allocated Hours"},
{id:"prjbudYPAllocated", label:"Percentage of Allocated"},
{id:"prjbudYFutureAllocatedHours", label:"Future Allocated Hours"},
{id:"prjbudYAllocatedGross", label:"Allocated Gross"},
{id:"prjbudYFutureAllocatedGross", label:"Future Allocated Gross"},
{id:"prjbudYFutureLaborGrossRemaining", label:"Future Labor Gross Remaining"},
{id:"prjbudYHoursBilledRemaining", label:"Hours Billed Remaining"},
{id:"prjbudYHoursBilledRemainingP", label:"Hours Billed Remaining %"},
{id:"prjbudYHoursRemaining", label:"Hours Remaining"},
{id:"prjbudYHoursRemainingP", label:"Hours Remaining %"},
{id:"prjbudYLaborNetRemaining", label:"Labor Net Remaining"},
{id:"prjbudYLaborNetRemainingP", label:"Labor Net Remaining %"},
{id:"prjbudYLaborGrossRemaining", label:"Labor Gross Remaining"},
{id:"prjbudYLaborGrossRemainingP", label:"Labor Gross Remaining %"},
{id:"prjbudYCostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudYCostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudYCostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudYCostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudYToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudYToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudYGrossRemaining", label:"Gross Remaining"},
{id:"prjbudYGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudYBilledDifference", label:"Billed Difference"},
{id:"prjbudYTransferInLabor", label:"Transfer In Labor"},
{id:"prjbudYTransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudYTransferInExpense", label:"Transfer In Expense"},
{id:"prjbudYTransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudYVarianceHours", label:"Variance Hours"},
{id:"prjbudYSalesTax", label:"Sales Tax"},
{id:"prjbudYHoursWriteOff", label:"Hours WriteOff"},
{id:"prjbudYHoursAfterWriteOff", label:"Hours After WriteOff"},
{id:"prjbudYLaborAfterWriteOff", label:"Labor After WriteOff"},
{id:"prjbudYHoursAfterWriteOffRemaining", label:"Hours After WriteOff Remaining"},
{id:"prjbudYHoursAfterWriteOffRemainingP", label:"Hours After WriteOff Remaining %"},
{id:"prjbudYLaborGrossAfterWriteOffRemaining", label:"Labor Gross After WriteOff Remaining"},
{id:"prjbudYLaborGrossAfterWriteOffRemainingP", label:"Labor Gross After WriteOff Remaining %"},
{id:"prjbudYTotalCostsGrossAfterWriteOff", label:"Total Costs Gross After WriteOff w Open Orders"},
{id:"prjbudYTotalCostsGrossAfterWriteOffNoOrder", label:"Total Costs Gross After WriteOff w/o Open Orders"},
{id:"prjbudYCostsGrossAfterWriteOffRemaining", label:"Costs Gross After WriteOff Remaining"},
{id:"prjbudYCostsGrossAfterWriteOffRemainingP", label:"Costs Gross After WriteOff Remaining %"},
{id:"prjbudYCostsGrossAfterWriteOffNoOrderRemaining", label:"Costs Gross After WriteOff wo Order Remaining"},
{id:"prjbudYCostsGrossAfterWriteOffNoOrderRemainingP", label:"Costs Gross After WriteOff wo Order Remaining %"},
{id:"prjbudYTotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"},
{id:"prjbudYCurrentBudgetQty", label:"Current Budget Quantity"},
{id:"prjbudYPurchasedQty", label:"Purchased Quantity"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''H_BY_TASK'', 11, ''BY TASK'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''prjbudgetSettings'', ''ScheduleLockedColumns3'', 12, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''HSUMMARY'', 13, ''Task Summary Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetTaskCols'', 14, ''Columns'', ''prjbudTCurrentTotalBudget,prjbudTTotalGross,prjbudTRemainingAllocatedHours'', NULL, ''grid'', 

''[
{id:"prjbudTPercComp", label:"% Complete"},
{id:"prjbudTCurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudTCurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudTCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudTCurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudTCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudTCurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudTCurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudTCurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudTCurrentBudgetExpenseQuantity", label:"Current Budget Expense Quantity"},
{id:"prjbudTCOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudTCOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudTCOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudTCOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudTCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudTCOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudTCOTotalBudget", label:"CO Total Budget"},
{id:"prjbudTCOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudTOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudTOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudTOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudTOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudTOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudTOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudTOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudTOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudTHours", label:"Act Hours"},
{id:"prjbudTHoursBilled", label:"Hours Billed"},
{id:"prjbudTHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudTHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudTLaborNet", label:"Labor Net"},
{id:"prjbudTLaborGross", label:"Labor Gross"},
{id:"prjbudTLaborBilled", label:"Labor Billed"},
{id:"prjbudTLaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudTLaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudTLaborWriteOff", label:"Labor Write Off"},
{id:"prjbudTOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudTOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudTInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudTOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudTOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudTInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudTOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudTInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudTOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudTExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudTExpenseBilled", label:"Expense Billed"},
{id:"prjbudTExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudTActualQuantity", label:"Actual Quantity"},
{id:"prjbudTAdvanceBilled", label:"Advance Billed"},
{id:"prjbudTAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudTAmountBilled", label:"Amount Billed"},
{id:"prjbudTAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudTTotalCostsNet", label:"Total Costs Net"},
{id:"prjbudTTotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudTTotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudTTotalNet", label:"Total Net"},
{id:"prjbudTTotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudTTotalGross", label:"Total Gross"},
{id:"prjbudTTotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudTRemainingAllocatedHours", label:"Remaining Allocated Hours"},
{id:"prjbudTAllocatedHours", label:"Allocated Hours"},
{id:"prjbudTPAllocated", label:"Percentage of Allocated"},
{id:"prjbudTFutureAllocatedHours", label:"Future Allocated Hours"},
{id:"prjbudTFutureLaborGrossRemaining", label:"Future Labor Gross Remaining"},
{id:"prjbudTAllocatedGross", label:"Allocated Gross"},
{id:"prjbudTFutureAllocatedGross", label:"Future Allocated Gross"},
{id:"prjbudTHoursBilledRemaining", label:"Hours Billed Remaining"},
{id:"prjbudTHoursBilledRemainingP", label:"Hours Billed Remaining %"},
{id:"prjbudTHoursRemaining", label:"Hours Remaining"},
{id:"prjbudTHoursRemainingP", label:"Hours Remaining %"},
{id:"prjbudTLaborNetRemaining", label:"Labor Net Remaining"},
{id:"prjbudTLaborNetRemainingP", label:"Labor Net Remaining %"},
{id:"prjbudTLaborGrossRemaining", label:"Labor Gross Remaining"},
{id:"prjbudTLaborGrossRemainingP", label:"Labor Gross Remaining %"},
{id:"prjbudTCostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudTCostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudTCostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudTCostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudTToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudTToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudTGrossRemaining", label:"Gross Remaining"},
{id:"prjbudTGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudTBilledDifference", label:"Billed Difference"},
{id:"prjbudTTransferInLabor", label:"Transfer In Labor"},
{id:"prjbudTTransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudTTransferInExpense", label:"Transfer In Expense"},
{id:"prjbudTTransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudTVarianceHours", label:"Variance Hours"},
{id:"prjbudTSalesTax", label:"Sales Tax"},
{id:"prjbudTHoursWriteOff", label:"Hours WriteOff"},
{id:"prjbudTHoursAfterWriteOff", label:"Hours After WriteOff"},
{id:"prjbudTLaborAfterWriteOff", label:"Labor After WriteOff"},
{id:"prjbudTHoursAfterWriteOffRemaining", label:"Hours After WriteOff Remaining"},
{id:"prjbudTHoursAfterWriteOffRemainingP", label:"Hours After WriteOff Remaining %"},
{id:"prjbudTLaborGrossAfterWriteOffRemaining", label:"Labor Gross After WriteOff Remaining"},
{id:"prjbudTLaborGrossAfterWriteOffRemainingP", label:"Labor Gross After WriteOff Remaining %"},
{id:"prjbudTTotalCostsGrossAfterWriteOff", label:"Total Costs Gross After WriteOff w Open Orders"},
{id:"prjbudTTotalCostsGrossAfterWriteOffNoOrder", label:"Total Costs Gross After WriteOff w/o Open Orders"},
{id:"prjbudTCostsGrossAfterWriteOffRemaining", label:"Costs Gross After WriteOff Remaining"},
{id:"prjbudTCostsGrossAfterWriteOffRemainingP", label:"Costs Gross After WriteOff Remaining %"},
{id:"prjbudTCostsGrossAfterWriteOffNoOrderRemaining", label:"Costs Gross After WriteOff wo Order Remaining"},
{id:"prjbudTCostsGrossAfterWriteOffNoOrderRemainingP", label:"Costs Gross After WriteOff wo Order Remaining %"},
{id:"prjbudTTotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL)


-- Task Details

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''HDETAILS'', 15, ''Task Detail Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetTaskDetailCols'', 16, ''Columns'', ''prjbudTDServiceItem,prjbudTDCurrentTotalBudget,prjbudTDTotalGross,prjbudTDRemainingAllocatedHours'', NULL, ''grid'', 

''[
{id:"prjbudTDServiceItem", label:"Item/Service"},
{id:"prjbudTDCurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudTDCurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudTDCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudTDCurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudTDCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudTDCurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudTDCurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudTDCurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudTDCOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudTDCOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudTDCOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudTDCOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudTDCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudTDCOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudTDCOTotalBudget", label:"CO Total Budget"},
{id:"prjbudTDCOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudTDOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudTDOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudTDOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudTDOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudTDOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudTDOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudTDOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudTDOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudTDHours", label:"Act Hours"},
{id:"prjbudTDHoursBilled", label:"Hours Billed"},
{id:"prjbudTDHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudTDHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudTDLaborNet", label:"Labor Net"},
{id:"prjbudTDLaborGross", label:"Labor Gross"},
{id:"prjbudTDLaborBilled", label:"Labor Billed"},
{id:"prjbudTDLaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudTDLaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudTDLaborWriteOff", label:"Labor Write Off"},
{id:"prjbudTDOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudTDOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudTDInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudTDOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudTDOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudTDInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudTDOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudTDInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudTDOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudTDExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudTDExpenseBilled", label:"Expense Billed"},
{id:"prjbudTDExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudTDAdvanceBilled", label:"Advance Billed"},
{id:"prjbudTDAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudTDAmountBilled", label:"Amount Billed"},
{id:"prjbudTDAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudTDTotalCostsNet", label:"Total Costs Net"},
{id:"prjbudTDTotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudTDTotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudTDTotalNet", label:"Total Net"},
{id:"prjbudTDTotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudTDTotalGross", label:"Total Gross"},
{id:"prjbudTDTotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudTDRemainingAllocatedHours", label:"Remaining Allocated Hours"},
{id:"prjbudTDAllocatedHours", label:"Allocated Hours"},
{id:"prjbudTDPAllocated", label:"Percentage of Allocated"},
{id:"prjbudTDFutureAllocatedHours", label:"Future Allocated Hours"},
{id:"prjbudTDFutureLaborGrossRemaining", label:"Future Labor Gross Remaining"},
{id:"prjbudTDAllocatedGross", label:"Allocated Gross"},
{id:"prjbudTDFutureAllocatedGross", label:"Future Allocated Gross"},
{id:"prjbudTDHoursBilledRemaining", label:"Hours Billed Remaining"},
{id:"prjbudTDHoursBilledRemainingP", label:"Hours Billed Remaining %"},
{id:"prjbudTDHoursRemaining", label:"Hours Remaining"},
{id:"prjbudTDHoursRemainingP", label:"Hours Remaining %"},
{id:"prjbudTDLaborNetRemaining", label:"Labor Net Remaining"},
{id:"prjbudTDLaborNetRemainingP", label:"Labor Net Remaining %"},
{id:"prjbudTDLaborGrossRemaining", label:"Labor Gross Remaining"},
{id:"prjbudTDLaborGrossRemainingP", label:"Labor Gross Remaining %"},
{id:"prjbudTDCostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudTDCostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudTDCostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudTDCostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudTDToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudTDToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudTDGrossRemaining", label:"Gross Remaining"},
{id:"prjbudTDGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudTDBilledDifference", label:"Billed Difference"},
{id:"prjbudTDTransferInLabor", label:"Transfer In Labor"},
{id:"prjbudTDTransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudTDTransferInExpense", label:"Transfer In Expense"},
{id:"prjbudTDTransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudTDVarianceHours", label:"Variance Hours"},
{id:"prjbudTDSalesTax", label:"Sales Tax"},
{id:"prjbudTDHoursWriteOff", label:"Hours WriteOff"},
{id:"prjbudTDHoursAfterWriteOff", label:"Hours After WriteOff"},
{id:"prjbudTDLaborAfterWriteOff", label:"Labor After WriteOff"},
{id:"prjbudTDHoursAfterWriteOffRemaining", label:"Hours After WriteOff Remaining"},
{id:"prjbudTDHoursAfterWriteOffRemainingP", label:"Hours After WriteOff Remaining %"},
{id:"prjbudTDLaborGrossAfterWriteOffRemaining", label:"Labor Gross After WriteOff Remaining"},
{id:"prjbudTDLaborGrossAfterWriteOffRemainingP", label:"Labor Gross After WriteOff Remaining %"},
{id:"prjbudTDTotalCostsGrossAfterWriteOff", label:"Total Costs Gross After WriteOff w Open Orders"},
{id:"prjbudTDTotalCostsGrossAfterWriteOffNoOrder", label:"Total Costs Gross After WriteOff w/o Open Orders"},
{id:"prjbudTDCostsGrossAfterWriteOffRemaining", label:"Costs Gross After WriteOff Remaining"},
{id:"prjbudTDCostsGrossAfterWriteOffRemainingP", label:"Costs Gross After WriteOff Remaining %"},
{id:"prjbudTDCostsGrossAfterWriteOffNoOrderRemaining", label:"Costs Gross After WriteOff wo Order Remaining"},
{id:"prjbudTDCostsGrossAfterWriteOffNoOrderRemainingP", label:"Costs Gross After WriteOff wo Order Remaining %"},
{id:"prjbudTDTotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref) 
Values (''prjbudgetSettings'', ''H_BY_TITLE'', 17, ''BY TITLE'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL, ''UseBillingTitles'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref)
Values (''prjbudgetSettings'', ''ScheduleLockedColumns4'', 18, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL, ''UseBillingTitles'')



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref) 
Values (''prjbudgetSettings'', ''HTITLE1'', 19, ''Labor Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL, ''UseBillingTitles'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1, TransPref) 
Values (''prjbudgetSettings'', ''grdProjectBudgetTitleCols'', 20, ''Columns'', ''prjbudBTCurrentBudgetHours,prjbudBTCurrentTotalBudget,prjbudBTHours,prjbudBTLaborGross,prjbudBTTotalGross,prjbudBTRemainingAllocatedHours'', NULL, ''grid'', 

''[
{id:"prjbudBTCurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudBTCurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudBTCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudBTCurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudBTCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudBTCurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudBTCurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudBTCurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudBTCOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudBTCOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudBTCOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudBTCOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudBTCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudBTCOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudBTCOTotalBudget", label:"CO Total Budget"},
{id:"prjbudBTCOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudBTOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudBTOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudBTOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudBTOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudBTOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudBTOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudBTOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudBTOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudBTHours", label:"Act Hours"},
{id:"prjbudBTHoursBilled", label:"Hours Billed"},
{id:"prjbudBTHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudBTHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudBTLaborNet", label:"Labor Net"},
{id:"prjbudBTLaborGross", label:"Labor Gross"},
{id:"prjbudBTLaborBilled", label:"Labor Billed"},
{id:"prjbudBTLaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudBTLaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudBTLaborWriteOff", label:"Labor Write Off"},
{id:"prjbudBTOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudBTOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudBTInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudBTOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudBTOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudBTInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudBTOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudBTInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudBTOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudBTExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudBTExpenseBilled", label:"Expense Billed"},
{id:"prjbudBTExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudBTAdvanceBilled", label:"Advance Billed"},
{id:"prjbudBTAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudBTAmountBilled", label:"Amount Billed"},
{id:"prjbudBTAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudBTTotalCostsNet", label:"Total Costs Net"},
{id:"prjbudBTTotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudBTTotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudBTTotalNet", label:"Total Net"},
{id:"prjbudBTTotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudBTTotalGross", label:"Total Gross"},
{id:"prjbudBTTotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudBTRemainingAllocatedHours", label:"Remaining Allocated Hours"},
{id:"prjbudBTAllocatedHours", label:"Allocated Hours"},
{id:"prjbudBTFutureAllocatedHours", label:"Future Allocated Hours"},
{id:"prjbudBTFutureLaborGrossRemaining", label:"Future Labor Gross Remaining"},
{id:"prjbudBTAllocatedGross", label:"Allocated Gross"},
{id:"prjbudBTPAllocated", label:"Percentage of Allocated"},
{id:"prjbudBTFutureAllocatedGross", label:"Future Allocated Gross"},
{id:"prjbudBTHoursBilledRemaining", label:"Hours Billed Remaining"},
{id:"prjbudBTHoursBilledRemainingP", label:"Hours Billed Remaining %"},
{id:"prjbudBTHoursRemaining", label:"Hours Remaining"},
{id:"prjbudBTHoursRemainingP", label:"Hours Remaining %"},
{id:"prjbudBTLaborNetRemaining", label:"Labor Net Remaining"},
{id:"prjbudBTLaborNetRemainingP", label:"Labor Net Remaining %"},
{id:"prjbudBTLaborGrossRemaining", label:"Labor Gross Remaining"},
{id:"prjbudBTLaborGrossRemainingP", label:"Labor Gross Remaining %"},
{id:"prjbudBTCostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudBTCostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudBTCostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudBTCostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudBTToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudBTToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudBTGrossRemaining", label:"Gross Remaining"},
{id:"prjbudBTGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudBTBilledDifference", label:"Billed Difference"},
{id:"prjbudBTTransferInLabor", label:"Transfer In Labor"},
{id:"prjbudBTTransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudBTTransferInExpense", label:"Transfer In Expense"},
{id:"prjbudBTTransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudBTVarianceHours", label:"Variance Hours"},
{id:"prjbudBTSalesTax", label:"Sales Tax"},
{id:"prjbudBTHoursWriteOff", label:"Hours WriteOff"},
{id:"prjbudBTHoursAfterWriteOff", label:"Hours After WriteOff"},
{id:"prjbudBTLaborAfterWriteOff", label:"Labor After WriteOff"},
{id:"prjbudBTHoursAfterWriteOffRemaining", label:"Hours After WriteOff Remaining"},
{id:"prjbudBTHoursAfterWriteOffRemainingP", label:"Hours After WriteOff Remaining %"},
{id:"prjbudBTLaborGrossAfterWriteOffRemaining", label:"Labor Gross After WriteOff Remaining"},
{id:"prjbudBTLaborGrossAfterWriteOffRemainingP", label:"Labor Gross After WriteOff Remaining %"},
{id:"prjbudBTTotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL, ''UseBillingTitles'')



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref) 
Values (''prjbudgetSettings'', ''HTITLE2'', 21, ''Expense Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL, ''UseBillingTitles'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1, TransPref) 
Values (''prjbudgetSettings'', ''grdProjectBudgetItem2Cols'', 22, ''Columns'', ''prjbudBTICurrentTotalBudget,prjbudBTITotalGross'', NULL, ''grid'', 

''[
{id:"prjbudBTICurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudBTICurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudBTICurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudBTICurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudBTICurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudBTICOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudBTICOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudBTICOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudBTICOTotalBudget", label:"CO Total Budget"},
{id:"prjbudBTICOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudBTIOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudBTIOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudBTIOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudBTIOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudBTIOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudBTIOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudBTIOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudBTIInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudBTIOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudBTIOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudBTIInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudBTIOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudBTIInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudBTIOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudBTIExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudBTIExpenseBilled", label:"Expense Billed"},
{id:"prjbudBTIExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudBTIAdvanceBilled", label:"Advance Billed"},
{id:"prjbudBTIAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudBTIAmountBilled", label:"Amount Billed"},
{id:"prjbudBTIAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudBTITotalCostsNet", label:"Total Costs Net"},
{id:"prjbudBTITotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudBTITotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudBTITotalNet", label:"Total Net"},
{id:"prjbudBTITotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudBTITotalGross", label:"Total Gross"},
{id:"prjbudBTITotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudBTICostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudBTICostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudBTICostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudBTICostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudBTIToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudBTIToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudBTIGrossRemaining", label:"Gross Remaining"},
{id:"prjbudBTIGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudBTIBilledDifference", label:"Billed Difference"},
{id:"prjbudBTITransferInExpense", label:"Transfer In Expense"},
{id:"prjbudBTITransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudBTISalesTax", label:"Sales Tax"},
{id:"prjbudBTITotalCostsGrossAfterWriteOff", label:"Total Costs Gross After WriteOff w Open Orders"},
{id:"prjbudBTITotalCostsGrossAfterWriteOffNoOrder", label:"Total Costs Gross After WriteOff w/o Open Orders"},
{id:"prjbudBTICostsGrossAfterWriteOffRemaining", label:"Costs Gross After WriteOff Remaining"},
{id:"prjbudBTICostsGrossAfterWriteOffRemainingP", label:"Costs Gross After WriteOff Remaining %"},
{id:"prjbudBTICostsGrossAfterWriteOffNoOrderRemaining", label:"Costs Gross After WriteOff wo Order Remaining"},
{id:"prjbudBTICostsGrossAfterWriteOffNoOrderRemainingP", label:"Costs Gross After WriteOff wo Order Remaining %"},
{id:"prjbudBTITotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL, ''UseBillingTitles'')



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''H_BY_PERSON'', 23, ''BY PERSON'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''prjbudgetSettings'', ''ScheduleLockedColumns5'', 24, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''HPERSON1'', 25, ''Labor Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetPersonCols'',26, ''Columns'', ''prjbudPCurrentBudgetHours,prjbudPCurrentTotalBudget,prjbudPHours,prjbudPLaborGross,prjbudPTotalGross,prjbudPRemainingAllocatedHours'', NULL, ''grid'', 

''[
{id:"prjbudPCurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudPCurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudPCurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudPCurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudPCurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudPCurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudPCurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudPCurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudPCOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudPCOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudPCOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudPCOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudPCOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudPCOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudPCOTotalBudget", label:"CO Total Budget"},
{id:"prjbudPCOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudPOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudPOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudPOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudPOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudPOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudPOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudPOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudPOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudPHours", label:"Act Hours"},
{id:"prjbudPHoursBilled", label:"Hours Billed"},
{id:"prjbudPHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudPHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudPLaborNet", label:"Labor Net"},
{id:"prjbudPLaborGross", label:"Labor Gross"},
{id:"prjbudPLaborBilled", label:"Labor Billed"},
{id:"prjbudPLaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudPLaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudPLaborWriteOff", label:"Labor Write Off"},
{id:"prjbudPOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudPOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudPInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudPOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudPOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudPInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudPOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudPInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudPOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudPExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudPExpenseBilled", label:"Expense Billed"},
{id:"prjbudPExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudPAdvanceBilled", label:"Advance Billed"},
{id:"prjbudPAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudPAmountBilled", label:"Amount Billed"},
{id:"prjbudPAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudPTotalCostsNet", label:"Total Costs Net"},
{id:"prjbudPTotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudPTotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudPTotalNet", label:"Total Net"},
{id:"prjbudPTotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudPTotalGross", label:"Total Gross"},
{id:"prjbudPTotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudPRemainingAllocatedHours", label:"Remaining Allocated Hours"},
{id:"prjbudPAllocatedHours", label:"Allocated Hours"},
{id:"prjbudPPAllocated", label:"Percentage of Allocated"},
{id:"prjbudPFutureAllocatedHours", label:"Future Allocated Hours"},
{id:"prjbudPAllocatedGross", label:"Allocated Gross"},
{id:"prjbudPFutureAllocatedGross", label:"Future Allocated Gross"},
{id:"prjbudPFutureLaborGrossRemaining", label:"Future Labor Gross Remaining"},
{id:"prjbudPHoursBilledRemaining", label:"Hours Billed Remaining"},
{id:"prjbudPHoursBilledRemainingP", label:"Hours Billed Remaining %"},
{id:"prjbudPHoursRemaining", label:"Hours Remaining"},
{id:"prjbudPHoursRemainingP", label:"Hours Remaining %"},
{id:"prjbudPLaborNetRemaining", label:"Labor Net Remaining"},
{id:"prjbudPLaborNetRemainingP", label:"Labor Net Remaining %"},
{id:"prjbudPLaborGrossRemaining", label:"Labor Gross Remaining"},
{id:"prjbudPLaborGrossRemainingP", label:"Labor Gross Remaining %"},
{id:"prjbudPCostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudPCostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudPCostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudPCostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudPToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudPToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudPGrossRemaining", label:"Gross Remaining"},
{id:"prjbudPGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudPBilledDifference", label:"Billed Difference"},
{id:"prjbudPTransferInLabor", label:"Transfer In Labor"},
{id:"prjbudPTransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudPTransferInExpense", label:"Transfer In Expense"},
{id:"prjbudPTransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudPVarianceHours", label:"Variance Hours"},
{id:"prjbudPSalesTax", label:"Sales Tax"},
{id:"prjbudPHoursWriteOff", label:"Hours WriteOff"},
{id:"prjbudPHoursAfterWriteOff", label:"Hours After WriteOff"},
{id:"prjbudPLaborAfterWriteOff", label:"Labor After WriteOff"},
{id:"prjbudPHoursAfterWriteOffRemaining", label:"Hours After WriteOff Remaining"},
{id:"prjbudPHoursAfterWriteOffRemainingP", label:"Hours After WriteOff Remaining %"},
{id:"prjbudPLaborGrossAfterWriteOffRemaining", label:"Labor Gross After WriteOff Remaining"},
{id:"prjbudPLaborGrossAfterWriteOffRemainingP", label:"Labor Gross After WriteOff Remaining %"},
{id:"prjbudPTotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetSettings'', ''HPERSON2'', 27, ''Expense Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetSettings'', ''grdProjectBudgetItem3Cols'', 28, ''Columns'', ''prjbudPICurrentTotalBudget,prjbudPITotalGross,prjbudPIRemainingAllocatedHours'', NULL, ''grid'', 

''[
{id:"prjbudPICurrentBudgetHours", label:"Current Budget Hours"},
{id:"prjbudPICurrentBudgetLaborNet", label:"Current Budget Labor Net"},
{id:"prjbudPICurrentBudgetLaborGross", label:"Current Budget Labor Gross"},
{id:"prjbudPICurrentBudgetExpenseNet", label:"Current Budget Expense Net"},
{id:"prjbudPICurrentBudgetExpenseGross", label:"Current Budget Expense Gross"},
{id:"prjbudPICurrentBudgetContingency", label:"Current Budget Contingency"},
{id:"prjbudPICurrentTotalBudget", label:"Current Total Budget"},
{id:"prjbudPICurrentTotalBudgetCont", label:"Current Total Budget Cont"},
{id:"prjbudPICOBudgetHours", label:"CO Budget Hours"},
{id:"prjbudPICOBudgetLaborNet", label:"CO Budget Labor Net"},
{id:"prjbudPICOBudgetLaborGross", label:"CO Budget Labor Gross"},
{id:"prjbudPICOBudgetExpenseNet", label:"CO Budget Expense Net"},
{id:"prjbudPICOBudgetExpenseGross", label:"CO Budget Expense Gross"},
{id:"prjbudPICOBudgetContingency", label:"CO Budget Contingency"},
{id:"prjbudPICOTotalBudget", label:"CO Total Budget"},
{id:"prjbudPICOTotalBudgetCont", label:"CO Total Budget Cont"},
{id:"prjbudPIOriginalBudgetHours", label:"Original Budget Hours"},
{id:"prjbudPIOriginalBudgetLaborNet", label:"Original Budget Labor Net"},
{id:"prjbudPIOriginalBudgetLaborGross", label:"Original Budget Labor Gross"},
{id:"prjbudPIOriginalBudgetExpenseNet", label:"Original Budget Expense Net"},
{id:"prjbudPIOriginalBudgetExpenseGross", label:"Original Budget Expense Gross"},
{id:"prjbudPIOriginalBudgetContingency", label:"Original Budget Contingency"},
{id:"prjbudPIOriginalTotalBudget", label:"Original Total Budget"},
{id:"prjbudPIOriginalTotalBudgetCont", label:"Original Total Budget Cont"},
{id:"prjbudPIHours", label:"Act Hours"},
{id:"prjbudPIHoursBilled", label:"Hours Billed"},
{id:"prjbudPIHoursInvoiced", label:"Hours Invoiced"},
{id:"prjbudPIHoursUnbilled", label:"Hours Unbilled"},
{id:"prjbudPILaborNet", label:"Labor Net"},
{id:"prjbudPILaborGross", label:"Labor Gross"},
{id:"prjbudPILaborBilled", label:"Labor Billed"},
{id:"prjbudPILaborInvoiced", label:"Labor Invoiced"},
{id:"prjbudPILaborUnbilled", label:"Labor Unbilled"},
{id:"prjbudPILaborWriteOff", label:"Labor Write Off"},
{id:"prjbudPIOpenOrdersNet", label:"Open Orders Net"},
{id:"prjbudPIOutsideCostsNet", label:"Outside Costs Net"},
{id:"prjbudPIInsideCostsNet", label:"Inside Costs Net"},
{id:"prjbudPIOpenOrdersGrossUnbilled", label:"Open Orders Gross Unbilled"},
{id:"prjbudPIOutsideCostsGrossUnbilled", label:"Outside Costs Gross Unbilled"},
{id:"prjbudPIInsideCostsGrossUnbilled", label:"Inside Costs Gross Unbilled"},
{id:"prjbudPIOutsideCostsGross", label:"Outside Costs Gross"},
{id:"prjbudPIInsideCostsGross", label:"Inside Costs Gross"},
{id:"prjbudPIOrderPrebilled", label:"Order Prebilled"},
{id:"prjbudPIExpenseWriteOff", label:"Expense Write Off"},
{id:"prjbudPIExpenseBilled", label:"Expense Billed"},
{id:"prjbudPIExpenseInvoiced", label:"Expense Invoiced"},
{id:"prjbudPIAdvanceBilled", label:"Advance Billed"},
{id:"prjbudPIAdvanceBilledOpen", label:"Advance Billed Open"},
{id:"prjbudPIAmountBilled", label:"Amount Billed"},
{id:"prjbudPIAmountBilledNoTax", label:"Amount Billed No Tax"},
{id:"prjbudPITotalCostsNet", label:"Total Costs Net"},
{id:"prjbudPITotalCostsGrossUnbilled", label:"Total Costs Gross Unbilled"},
{id:"prjbudPITotalCostsGross", label:"Total Costs Gross"},
{id:"prjbudPITotalNet", label:"Total Net"},
{id:"prjbudPITotalGrossUnbilled", label:"Total Gross Unbilled"},
{id:"prjbudPITotalGross", label:"Total Gross"},
{id:"prjbudPITotalGrossAfterWriteOff", label:"Total Gross After Write Off"},
{id:"prjbudPICostsNetRemaining", label:"Costs Net Remaining"},
{id:"prjbudPICostsNetRemainingP", label:"Costs Net Remaining %"},
{id:"prjbudPICostsGrossRemaining", label:"Costs Gross Remaining"},
{id:"prjbudPICostsGrossRemainingP", label:"Costs Gross Remaining %"},
{id:"prjbudPIToBillRemaining", label:"To Bill Remaining"},
{id:"prjbudPIToBillRemainingP", label:"To Bill Remaining %"},
{id:"prjbudPIGrossRemaining", label:"Gross Remaining"},
{id:"prjbudPIGrossRemainingP", label:"Gross Remaining %"},
{id:"prjbudPIBilledDifference", label:"Billed Difference"},
{id:"prjbudPITransferInLabor", label:"Transfer In Labor"},
{id:"prjbudPITransferOutLabor", label:"Transfer Out Labor"},
{id:"prjbudPITransferInExpense", label:"Transfer In Expense"},
{id:"prjbudPITransferOutExpense", label:"Transfer Out Expense"},
{id:"prjbudPIVarianceHours", label:"Variance Hours"},
{id:"prjbudPISalesTax", label:"Sales Tax"},
{id:"prjbudPITotalCostsGrossAfterWriteOff", label:"Total Costs Gross After WriteOff w Open Orders"},
{id:"prjbudPITotalCostsGrossAfterWriteOffNoOrder", label:"Total Costs Gross After WriteOff w/o Open Orders"},
{id:"prjbudPICostsGrossAfterWriteOffRemaining", label:"Costs Gross After WriteOff Remaining"},
{id:"prjbudPICostsGrossAfterWriteOffRemainingP", label:"Costs Gross After WriteOff Remaining %"},
{id:"prjbudPICostsGrossAfterWriteOffNoOrderRemaining", label:"Costs Gross After WriteOff wo Order Remaining"},
{id:"prjbudPICostsGrossAfterWriteOffNoOrderRemainingP", label:"Costs Gross After WriteOff wo Order Remaining %"},
{id:"prjbudPITotalGrossUnbilledFixedFee", label:"Total Gross Unbilled Fixed Fee"}
]''
	 , NULL, NULL, null, NULL)


/*Drill Down for Invoices Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetInvoices'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetInvoices'', ''DDInvoices'', 1, ''Invoice Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetInvoices'', ''grdBudgetDDInvoices'', 2, ''Columns'', ''prjbudDDBInvoiceNumber,prjbudDDBCustomerID,prjbudDDBInvoiceDate,prjbudDDBLineSubject,prjbudDDBAmount,prjbudDDBSalesTaxAmount,prjbudDDBTotalAmount,prjbudDDBTaskName,prjbudDDBItemName,prjbudDDBAppliedAmount'', NULL, ''grid'', 
''[
{id:"prjbudDDBInvoiceNumber",label:"Invoice Number"},
{id:"prjbudDDBCustomerID",label:"Customer ID"},
{id:"prjbudDDBInvoiceDate",label:"Invoice Date"},
{id:"prjbudDDBLineSubject",label:"Line Subject"},
{id:"prjbudDDBAmount",label:"Amount"},
{id:"prjbudDDBSalesTaxAmount",label:"Sales Tax Amount"},
{id:"prjbudDDBTotalAmount",label:"Total Amount"},
{id:"prjbudDDBTaskName",label:"Task Name"},
{id:"prjbudDDBItemName",label:"Item Name"},
{id:"prjbudDDBAppliedAmount", label:"Unapplied Amount"}
]''
, NULL, NULL, NULL, NULL)
 
/*Drill Down for Estimates Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetEstimates'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetEstimates'', ''DDEstimates'',1, ''Estimate Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetEstimates'', ''grdBudgetDDEstimates'',2, ''Columns'', ''prjbudDDEEstimateName,prjbudDDEEstimateDate,prjbudDDETaskName,prjbudDDEItemName,prjbudDDEHours,prjbudDDELaborNet,prjbudDDELaborGross,prjbudDDEQuantity,prjbudDDEExpenseNet,prjbudDDEExpenseGross,prjbudDDETotalBudget,prjbudDDEContingency,prjbudDDETotalBudgetCont,prjbudDDESalesTaxAmount,prjbudDDEVendorName'', NULL, ''grid'', 
''[
{id:"prjbudDDEEstimateName", label:"Estimate Name"},
{id:"prjbudDDEEstimateDate", label:"Estimate Date"},
{id:"prjbudDDETaskName", label:"Task Name"},
{id:"prjbudDDEItemName", label:"Item Name"},
{id:"prjbudDDEHours", label:"Hours"},
{id:"prjbudDDELaborNet", label:"Labor Net"},
{id:"prjbudDDELaborGross", label:"Labor Gross"},
{id:"prjbudDDEQuantity", label:"Quantity"},
{id:"prjbudDDEExpenseNet", label:"Expense Net"},
{id:"prjbudDDEExpenseGross", label:"Expense Gross"},
{id:"prjbudDDETotalBudget", label:"Total Budget"},
{id:"prjbudDDEContingency", label:"Contingency"},
{id:"prjbudDDETotalBudgetCont", label:"Total Budget Cont"},
{id:"prjbudDDESalesTaxAmount", label:"Sales Tax Amount"},
{id:"prjbudDDEVendorID", label:"Vendor ID"},
{id:"prjbudDDEVendorFullName", label:"Vendor Full Name"},
{id:"prjbudDDEVendorName", label:"Vendor Name"}
]''
 , NULL, NULL, NULL, NULL)

/*Drill Down for Gerneral Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetGeneral'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetGeneral'', ''DDGeneral'', 1, ''General Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetGeneral'', ''grdBudgetDDGeneral'', 2, ''Columns'', ''prjbudDDGTransactionType,prjbudDDGTransactionDate,prjbudDDGVendorID,prjbudDDGNumber,prjbudDDGDescription,prjbudDDGQuantity,prjbudDDGNetExp,prjbudDDGNetLabor,prjbudDDGGross,prjbudDDGGross2,prjbudDDGGross3,prjbudDDGTaskName,prjbudDDGItemName,prjbudDDGTitleName,prjbudDDGVendorName'', NULL, ''grid'', 
''[
{id:"prjbudDDGTransactionType", label:"Transaction Type"},
{id:"prjbudDDGTransactionDate", label:"Transaction Date"},
{id:"prjbudDDGVendorID", label:"Vendor ID"},
{id:"prjbudDDGNumber", label:"Number"},
{id:"prjbudDDGDescription", label:"Description"},
{id:"prjbudDDGQuantity", label:"Quantity"},
{id:"prjbudDDGNetExp", label:"Net Exp"},
{id:"prjbudDDGNetLabor", label:"Net Labor"},
{id:"prjbudDDGGross", label:"Total Gross"},
{id:"prjbudDDGGross2", label:"Gross"},
{id:"prjbudDDGGross3", label:"Billed"},
{id:"prjbudDDGTaskName", label:"Task Name"},
{id:"prjbudDDGItemName", label:"Item Name"},
{id:"prjbudDDGTitleName", label:"Title Name"},
{id:"prjbudDDGVendorFullName", label:"Vendor Full Name"},
{id:"prjbudDDGVendorName", label:"Vendor Name"},
]''
	 , NULL, NULL, NULL, NULL)
	 
/*Drill Down for Labor Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetLabor'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetLabor'', ''DDLabor'',1, ''Labor Settings'', NULL,NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetLabor'', ''grdBudgetDDLabor'', 2, ''Columns'', ''prjbudDDUserName,prjbudDDWorkDate,prjbudDDActualHours,prjbudDDHoursBilled,prjbudDDCostRate,prjbudDDActualRate,prjbudDDLaborNet,prjbudDDLaborGross,prjbudDDLaborBilled,prjbudDDDateBilled,prjbudDDInvoiceNumber,prjbudDDWriteOff,prjbudDDTaskName,prjbudDDServiceDescription,prjbudDDTitleDescription,prjbudDDDescription'', NULL, ''grid'', 
''[
{id:"prjbudDDUserName",label:"User Name"},
{id:"prjbudDDWorkDate",label:"Work Date"},
{id:"prjbudDDActualHours",label:"Actual Hours"},
{id:"prjbudDDHoursBilled",label:"Hours Billed"},
{id:"prjbudDDCostRate",label:"Cost Rate"},
{id:"prjbudDDActualRate",label:"Actual Rate"},
{id:"prjbudDDLaborNet",label:"Labor Net"},
{id:"prjbudDDLaborGross",label:"Labor Gross"},
{id:"prjbudDDLaborBilled",label:"Labor Billed"},
{id:"prjbudDDDateBilled",label:"Date Billed"},
{id:"prjbudDDInvoiceNumber",label:"Invoice Number"},
{id:"prjbudDDWriteOff",label:"Write Off"},
{id:"prjbudDDTaskName",label:"Task Name"},
{id:"prjbudDDServiceDescription",label:"Service Description"},
{id:"prjbudDDTitleDescription",label:"Title Description"},
{id:"prjbudDDDescription",label:"Description"}
]''
	 , NULL, NULL, NULL, NULL)

/*Drill Down for Expense Writeoff Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetExpense'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetExpense'', ''DDExpenseWriteOff'', 1, ''Expense Settings'', NULL,NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetExpense'', ''grdBudgetDDExpenseWriteOff'', 2, ''Columns'', ''prjbudDDWOTransactionType,prjbudDDWOUserName,prjbudDDWOExpenseDate,prjbudDDWOQuantity,prjbudDDWOUnitCost,prjbudDDWOTotalCost,prjbudDDWOBillableCost,prjbudDDWOAmountBilled,prjbudDDWODateBilled,prjbudDDWOWriteOff,prjbudDDWOTaskName,prjbudDDWOItemName,prjbudDDWODescription,prjbudDDWOHeaderNumber,prjbudDDWOVendorID,prjbudDDWOPurchaseOrderNumber,prjbudDDWOVendorInvoiceNumber,prjbudDDWOVendorName,prjbudDDWOVendorFullName'', NULL, ''grid'', 
''[
{id:"prjbudDDWOTransactionType", label:"Transaction Type"},
{id:"prjbudDDWOUserName", label:"User Name"},
{id:"prjbudDDWOExpenseDate", label:"Expense Date"},
{id:"prjbudDDWOQuantity", label:"Quantity"},
{id:"prjbudDDWOUnitCost", label:"Unit Cost"},
{id:"prjbudDDWOTotalCost", label:"Total Cost"},
{id:"prjbudDDWOBillableCost", label:"Billable Cost"},
{id:"prjbudDDWOAmountBilled", label:"Amount Billed"},
{id:"prjbudDDWODateBilled", label:"Date Billed"},
{id:"prjbudDDWOWriteOff", label:"Write Off"},
{id:"prjbudDDWOTaskName", label:"Task Name"},
{id:"prjbudDDWOItemName", label:"Item Name"},
{id:"prjbudDDWODescription", label:"Description"},
{id:"prjbudDDWOHeaderNumber", label:"Header Number"},
{id:"prjbudDDWOVendorID", label:"Vendor ID"},
{id:"prjbudDDWOPurchaseOrderNumber", label:"Purchase Order Number"},
{id:"prjbudDDWOVendorInvoiceNumber", label:"Vendor Invoice Number"},
{id:"prjbudDDWOVendorName", label:"Vendor Name"},
{id:"prjbudDDWOVendorFullName", label:"Vendor Full Name"},
]''
	 , NULL, NULL, NULL, NULL)
               
/*Drill Down for Advance Bill Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetAdvanceBilledOpen'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetAdvanceBilledOpen'', ''DDAdvanceBill'', 1, ''Advance Bill Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetAdvanceBilledOpen'', ''grdBudgetDDAdvanceBill'', 2, ''Columns'', ''prjbudDDABInvoiceNumber,prjbudDDABCustomerID,prjbudDDABInvoiceDate,prjbudDDABInvoiceTotalAmount,prjbudDDABAppliedAmount'', NULL, ''grid'', 
''[
{id:"prjbudDDABInvoiceNumber", label:"Invoice Number"},
{id:"prjbudDDABCustomerID", label:"Customer ID"},
{id:"prjbudDDABInvoiceDate", label:"Invoice Date"},
{id:"prjbudDDABInvoiceTotalAmount", label:"Invoice Total Amount"},
{id:"prjbudDDABAppliedAmount", label:"Unapplied Amount"}
]''
 , NULL, NULL, NULL, NULL)

/*Drill Down for Inside Costs Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetInsideCosts'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetInsideCosts'', ''DDInsideCosts'', 1, ''Inside Costs Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetInsideCosts'', ''grdBudgetDDInsideCosts'', 2, ''Columns'', ''prjbudDDICTransactionType,prjbudDDICUserName,prjbudDDICExpenseDate,prjbudDDICQuantity,prjbudDDICUnitCost,prjbudDDICTotalCost,prjbudDDICBillableCost,prjbudDDICAmountBilled,prjbudDDICDateBilled,prjbudDDICInvoiceNumber,prjbudDDICWriteOff,prjbudDDICTaskName,prjbudDDICItemName,prjbudDDICDescription,prjbudDDICVendorID,prjbudDDICPurchaseOrderNumber,prjbudDDICVendorInvoiceNumber,prjbudDDICVendorName,prjbudDDICVendorFullName'', NULL, ''grid'', 
''[
{id:"prjbudDDICTransactionType", label:"Transaction Type"},
{id:"prjbudDDICUserName", label:"User Name"},
{id:"prjbudDDICExpenseDate", label:"Expense Date"},
{id:"prjbudDDICQuantity", label:"Quantity"},
{id:"prjbudDDICUnitCost", label:"Unit Cost"},
{id:"prjbudDDICTotalCost", label:"Total Cost"},
{id:"prjbudDDICBillableCost", label:"Billable Cost"},
{id:"prjbudDDICAmountBilled", label:"Amount Billed"},
{id:"prjbudDDICDateBilled", label:"Date Billed"},
{id:"prjbudDDICInvoiceNumber", label:"Invoice Number"},
{id:"prjbudDDICWriteOff", label:"Write Off"},
{id:"prjbudDDICTaskName", label:"Task Name"},
{id:"prjbudDDICItemName", label:"Item Name"},
{id:"prjbudDDICDescription", label:"Description"},
{id:"prjbudDDICVendorID", label:"Vendor ID"},
{id:"prjbudDDICPurchaseOrderNumber", label:"Purchase Order Number"},
{id:"prjbudDDICVendorInvoiceNumber", label:"Vendor Invoice Number"},
{id:"prjbudDDICVendorName", label:"Vendor Name"},
{id:"prjbudDDICVendorFullName", label:"Vendor Full Name"}
]''
 , NULL, NULL, NULL, NULL)

/*Drill Down for Outside Costs Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetOutsideCosts'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetOutsideCosts'', ''DDOutsideCosts'', 1, ''Outside Costs Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetOutsideCosts'', ''grdBudgetDDOutsideCosts'', 2, ''Columns'', ''prjbudDDOCTransactionType,prjbudDDOCVendorID,prjbudDDOCNumber,prjbudDDOCTransactionDate,prjbudDDOCQuantity,prjbudDDOCUnitCost,prjbudDDOCTotalCost,prjbudDDOCBillableCost,prjbudDDOCDateClosed,prjbudDDOCAmountBilled,prjbudDDOCDateBilled,prjbudDDOCInvoiceNumber,prjbudDDOCWriteOff,prjbudDDOCTaskName,prjbudDDOCItemName,prjbudDDOCDescription,prjbudDDOCVendorFullName'', NULL, ''grid'', 
''[
{id:"prjbudDDOCTransactionType", label:"Transaction Type"},
{id:"prjbudDDOCVendorID", label:"Vendor ID"},
{id:"prjbudDDOCVendorName", label:"Vendor Name"},
{id:"prjbudDDOCNumber", label:"Number"},
{id:"prjbudDDOCTransactionDate", label:"Transaction Date"},
{id:"prjbudDDOCQuantity", label:"Quantity"},
{id:"prjbudDDOCUnitCost", label:"Unit Cost"},
{id:"prjbudDDOCTotalCost", label:"Total Cost"},
{id:"prjbudDDOCBillableCost", label:"Billable Cost"},
{id:"prjbudDDOCDateClosed", label:"Date Closed"},
{id:"prjbudDDOCAmountBilled", label:"Amount Billed"},
{id:"prjbudDDOCDateBilled", label:"Date Billed"},
{id:"prjbudDDOCInvoiceNumber", label:"Invoice Number"},
{id:"prjbudDDOCWriteOff", label:"Write Off"},
{id:"prjbudDDOCTaskName", label:"Task Name"},
{id:"prjbudDDOCItemName", label:"Item Name"},
{id:"prjbudDDOCDescription", label:"Description"},
{id:"prjbudDDOCVendorFullName", label:"Vendor Full Name"}
]''
 , NULL, NULL, NULL, NULL)
 
/*Drill Down for Outside Costs2 Grid Columns*/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbudgetOutsideCosts2'', ''Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbudgetOutsideCosts2'', ''DDOutsideCosts2'', 1, ''Outside Costs Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbudgetOutsideCosts2'', ''grdBudgetDDOutsideCosts2'', 2, ''Columns'', ''prjbudDDOC2TransactionType,prjbudDDOC2VendorID,prjbudDDOC2Number,prjbudDDOC2TransactionDate,prjbudDDOC2Quantity,prjbudDDOC2UnitCost,prjbudDDOC2TotalCost,prjbudDDOC2DateClosed,prjbudDDOC2AmountBilled,prjbudDDOC2DateBilled,prjbudDDOC2InvoiceNumber,prjbudDDOC2WriteOff,prjbudDDOC2TaskName,prjbudDDOC2ItemName,prjbudDDOC2Description,prjbudDDOC2PurchaseOrderNumber,prjbudDDOC2VendorInvoiceNumber,prjbudDDOC2VendorName,prjbudDDOC2VendorFullName'', NULL, ''grid'', 
''[
{id:"prjbudDDOC2TransactionType", label:"Transaction Type"},
{id:"prjbudDDOC2VendorID", label:"Vendor ID"},
{id:"prjbudDDOC2VendorName", label:"Vendor Name"},
{id:"prjbudDDOC2Number", label:"Number"},
{id:"prjbudDDOC2TransactionDate", label:"Transaction Date"},
{id:"prjbudDDOC2Quantity", label:"Quantity"},
{id:"prjbudDDOC2UnitCost", label:"Unit Cost"},
{id:"prjbudDDOC2TotalCost", label:"Total Cost"},
{id:"prjbudDDOC2DateClosed", label:"Date Closed"},
{id:"prjbudDDOC2AmountBilled", label:"Gross/Billed"},
{id:"prjbudDDOC2DateBilled", label:"Date Billed"},
{id:"prjbudDDOC2InvoiceNumber", label:"Invoice Number"},
{id:"prjbudDDOC2WriteOff", label:"Write Off"},
{id:"prjbudDDOC2TaskName", label:"Task Name"},
{id:"prjbudDDOC2ItemName", label:"Item Name"},
{id:"prjbudDDOC2Description", label:"Description"},
{id:"prjbudDDOC2PurchaseOrderNumber", label:"Purchase Order Number"},
{id:"prjbudDDOC2VendorInvoiceNumber", label:"Vendor Invoice Number"},
{id:"prjbudDDOC2VendorFullName", label:"Vendor Full Name"}
]''
 , NULL, NULL, NULL, NULL)
 



/*************************************************************************************************************************
Project FF Billing
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectFFBilling'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''H1'', 0, ''Invoice Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''AddProjectLine'', 1, ''Add top project line'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Only valid if Invoice By = Percentage of Service / Item or Billing Item. If this is checked, a summary line with the project name will be inserted at the top.'') 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''AddTaskDetails'', 2, ''Include service and item details under each task.'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Only valid if Invoice By = Percentage of Task. If this is checked, the system will create under each task, invoice lines corresponding to services or items on estimates.'') 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''AllowZeroLines'', 3, ''Include all selected lines even if 0 dollars'', ''0'', NULL, ''checkbox'', NULL, NULL, ''If this option is checked, checked zero lines will be created. If this option is not checked, checked zero lines will not be created.'') 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''GroupByBillingItem'', 4, ''Group by billing item'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Only valid if Invoice By = Percentage of Service / Item. Similar to the the TM option: One Line Per Billing Item and Item. When creating the invoice lines, expense items are grouped by billing item.'') 

 
/*By Tasks Grid Columns*/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''ByTaskGroup'', 5, ''Invoice By Task Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectFFBilling'', ''grdTasksCols'', 6, ''Columns'', ''colTaskEstHrs,colTaskEstLabor,colTaskEstExpenses,colTaskEstTotal,colTaskActHrs,colTaskActLabor,colTaskActExpenses,colTaskActTotal,colTaskBilled,colTaskAllBilled,colTaskRemaining'', NULL, ''grid'', 
''[
{id:"colTaskEstHrs", label:"Est Hrs"},
{id:"colTaskEstLabor", label:"Est Labor"},
{id:"colTaskEstExpenses", label:"Est Exp"},
{id:"colTaskEstTotal", label:"Est Total"},
{id:"colTaskActHrs", label:"Act Hrs"},
{id:"colTaskActLabor", label:"Act Labor"},
{id:"colTaskActExpenses", label:"Act Exp"},
{id:"colTaskActTotal", label:"Act Total"},
{id:"colTaskBilled", label:"Billed"},
{id:"colTaskAllBilled", label:"Total Billed"},
{id:"colTaskRemaining", label:"Remaining"},
{id:"colTaskActLaborNet", label:"Act Labor Net"},
{id:"colTaskActExpensesNet", label:"Act Exp Net"},
{id:"colTaskActGI", label:"Act GI"}
]''
 , NULL, NULL, NULL, NULL)

 
/*By Service Grid Columns*/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''ByServiceGroup'', 7, ''Invoice By Service Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectFFBilling'', ''grdServicesCols'', 8, ''Columns'', ''colServiceEstHrs,colServiceEstLabor,colServiceActHrs,colServiceActLabor,colServiceBilled,colServiceAllBilled,colServiceRemaining'', NULL, ''grid'', 
''[
{id:"colServiceEstHrs", label:"Est Hrs"},
{id:"colServiceEstLabor", label:"Est Labor"},
{id:"colServiceActHrs", label:"Act Hours"},
{id:"colServiceActLabor", label:"Act Labor"},
{id:"colServiceBilled", label:"Billed"},
{id:"colServiceAllBilled", label:"Total Billed"},
{id:"colServiceRemaining", label:"Remaining"},
{id:"colServiceActLaborNet", label:"Act Labor Net"},
{id:"colServiceActGI", label:"Act GI"}
]''
 , NULL, NULL, NULL, NULL)


  
/*By Items Grid Columns*/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''ByItemGroup'', 9, ''Invoice By Items Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectFFBilling'', ''grdItemCols'', 10, ''Columns'', ''colItemEstExpenses,colItemActExpenses,colItemBilled,colItemAllBilled,colItemRemaining'', NULL, ''grid'', 
''[
{id:"colItemEstExpenses", label:"Bill Amt"},
{id:"colItemActExpenses", label:"Act Exp"},
{id:"colItemBilled", label:"Billed"},
{id:"colItemAllBilled", label:"Total Billed"},
{id:"colItemRemaining", label:"Remaining"},
{id:"colItemActExpensesNet", label:"Act Exp Net"},
{id:"colItemActGI", label:"Act GI"}
]''
 , NULL, NULL, NULL, NULL)


 
/*By Billing Items Grid Columns*/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectFFBilling'', ''ByBillingGroup'', 11, ''Invoice By Billing Items Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectFFBilling'', ''grdBillingItemsCols'', 12, ''Columns'', ''colBIEstHrs,colBIEstLabor,colBIEstExpenses,colBIEstTotal,colBIActHrs,colBIActLabor,colBIActExpenses,colBIActTotal,colBIBilled,colBIAllBilled,colBIRemaining'', NULL, ''grid'', 
''[
{id:"colBIEstHrs", label:"Est Hrs"},
{id:"colBIEstLabor", label:"Est Labor"},
{id:"colBIEstExpenses", label:"Est Exp"},
{id:"colBIEstTotal", label:"Est Total"},
{id:"colBIActHrs", label:"Act Hours"},
{id:"colBIActLabor", label:"Act Labor"},
{id:"colBIActExpenses", label:"Act Exp"},
{id:"colBIActTotal", label:"Act Total"},
{id:"colBIBilled", label:"Billed"},
{id:"colBIAllBilled", label:"Total Billed"},
{id:"colBIRemaining", label:"Remaining"},
{id:"colBIActLaborNet", label:"Act Labor Net"},
{id:"colBIActExpensesNet", label:"Act Exp Net"},
{id:"colBIActGI", label:"GI"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Project TM Billing transactions grids
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''prjbillTransactions'', ''Project Billing Detail Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H1'', 0, ''Unbilled Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsUnbilledCols'', 1, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxPosted,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullNameprjbillxItemFullName,prjbillxWIPInBatch'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"},
{id:"prjbillxAttachmentCount", label:"Attachments"},
{id:"prjbillxPosted", label:"Posted"},
{id:"prjbillxPostingDate", label:"Posting Date"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H2'', 2, ''Unapproved Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsUnapprovedCols'', 3, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"},
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H3'', 4, ''Billed Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsBilledCols'', 5, ''Columns'', ''prjbillxBillingInvoiceNumber,prjbillxDateBilled,prjbillxAmountBilled,prjbillxTransactionDate,prjbillxDescription,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName,prjbillxWIPInBatch,prjbillxWIPOutBatch'', NULL, ''grid'', 

''[
{id:"prjbillxBillingInvoiceNumber", label:"Invoice Number"},
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxDateBilled", label:"Date Billed"},
{id:"prjbillxAmountBilled", label:"Amount Billed"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxWIPOutBatch", label:"WIP Out Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H4'', 6, ''Mark as Billed Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsMABCols'', 7, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName,prjbillxWIPInBatch,prjbillxWIPOutBatch,prjbillxDateBilled,prjbillxAmountBilled'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxWIPOutBatch", label:"WIP Out Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"},
{id:"prjbillxDateBilled", label:"Date Billed"},
{id:"prjbillxAmountBilled", label:"Amount Billed"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H5'', 8, ''Write Off Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsWOCols'', 9, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName,prjbillxWIPInBatch,prjbillxWIPOutBatch,prjbillxDateBilled,prjbillxWriteOffReason,prjbillxWriteOffComment'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxWIPOutBatch", label:"WIP Out Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"},
{id:"prjbillxDateBilled", label:"Write Off Date"},
{id:"prjbillxWriteOffComment", label:"Write Off Comment"},
{id:"prjbillxWriteOffReason", label:"Write Off Reason"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H6'', 10, ''On Hold Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsOnHoldCols'', 11, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName,prjbillxWIPInBatch'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxWIPOutBatch", label:"WIP Out Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H7'', 12, ''Transferred Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsTransferredCols'', 13, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxTransferInDate,prjbillxTransferOutDate,prjbillxTransferComment,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxWIPOutBatch", label:"WIP Out Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"},
{id:"prjbillxTransferOutDate", label:"Transfer Out Date"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''prjbillTransactions'', ''H8'', 14, ''Adjusted Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''prjbillTransactions'', ''grdbillTransactionsAdjustedCols'', 15, ''Columns'', ''prjbillxTransactionDate,prjbillxDescription,prjbillxTransferInDate,prjbillxTransferOutDate,prjbillxTransferComment,prjbillxQuantity,prjbillxHours,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName'', NULL, ''grid'', 

''[
{id:"prjbillxTransactionDate", label:"Transaction Date"},
{id:"prjbillxDescription", label:"Vendor/Person"},
{id:"prjbillxTransactionComments", label:"Transaction Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxHours", label:"Hours"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"},
{id:"prjbillxClassFullName", label:"Class"},
{id:"prjbillxSalesAccountFullName", label:"Sales GL Account"},
{id:"prjbillxWIPInBatch", label:"WIP In Batch"},
{id:"prjbillxWIPOutBatch", label:"WIP Out Batch"},
{id:"prjbillxTransferComment", label:"Transfer Comment"},
{id:"prjbillxTransferInDate", label:"Transfer In Date"},
{id:"prjbillxTransferOutDate", label:"Transfer Out Date"}
]''
	 , NULL, NULL, null, NULL)

/*************************************************************************************************************************
Sales Dashboard
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''salesDashboard'', ''Dashboard Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''DashboardSettings'', 0, ''Dashboard Sections'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''OppByStage'', 1, ''Opportunity By Stage'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''OppByWWP'', 2, ''Opportunity By WWP'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''Weighted'', 3, ''Weighted Opportunity Amounts'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''OppTwitter'', 4, ''Twitter Feeds'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''NeglectedOpps'', 5, ''Neglected Opportunities'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''SalesTarget'', 6, ''Sales Target'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboard'', ''ShowOtherSalesPeople'', 7, ''Show Other Sales People'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)



INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''salesDashboardDrilldown'', ''Drilldown Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboardDrilldown'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''salesDashboardDrilldown'', ''Weighted'', 1, ''Weighted Opportunity Amounts'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''salesDashboardDrilldown'', ''byStage'', 2, ''Columns'', ''Subject,ContactName,SaleAmount,AGI,ActivitySubject,Probability,CurrentStatus'', NULL, ''grid'', 
''[	{id:"Subject", label:"Subject"},
	{id:"ContactName", label:"Contact Name"},
    {id:"FolderName", label:"Folder Name"},
    {id:"DateAdded", label:"Date Added"},
    {id:"DateUpdated", label:"Date Updated"},

    {id:"SaleAmount", label:"Sale Amount"},
    {id:"Labor", label:"Labor"},
    {id:"OutsideCostsGross", label:"Production Amount"},
    {id:"OutsideCostsPerc", label:"Production Margin"},
    {id:"MediaGross", label:"Media Amount"},
    {id:"MediaPerc", label:"Media Margin"},
    {id:"AGI", label:"AGI"},

    {id:"Months", label:"Months"},

    {id:"ActivitySubject", label:"Next Conversation"},
    {id:"LeadStageName", label:"Stage"},
    {id:"Probability", label:"Probability"},

    {id:"CurrentStatus", label:"Next Steps"},
    {id:"EstCloseDate", label:"Forecasted Close Date"},

    {id:"WWPCurrentLevel", label:"WWP Level"},
    {id:"WWPNeedSupplyComment", label:"Need : Supply"},
    {id:"WWPTimelineComment", label:"Has a Timeline"},
    {id:"WWPBudgetComment", label:"Has a Budget"},
    {id:"WWPDecisionMakersComment", label:"Decision Makers"}
 ]''
 , NULL, NULL, NULL, NULL)


 /*************************************************************************************************************************
Opportunity Add/Edit
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''opportunitySettings'', ''Opportunity Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequiredFields'', 0, ''Required Fields'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequireForecastedCloseDate'', 1, ''Require Forecasted Close Date'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequireGLCompany'', 2, ''Require GL Company'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequireProjectType'', 3, ''Require Project Type'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequireOpportunityOwner'', 4, ''Require Opportunity Owner'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequirePrimaryContact'', 5, ''Require Primary Contact'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''RequireOutcome'', 6, ''Require Outcome When Status Is Inactive'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''Exclusions'', 7, ''Exclusions'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''opportunitySettings'', ''ExcludeVendors'', 8, ''Exclude Vendors'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Vendors that are not also clients will be excluded from the Company Dropdown.'')


/*************************************************************************************************************************
Campaign Budget
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignBudget'', ''Campaign Budget Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignBudget'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''campaignBudget'', ''LockedColumns'', 1, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campaignBudget'', ''grdCampaignBudgetsCols'', 1, ''Columns'', ''campBudgetDisplayName,campBudgetC_AmountBilled,campBudgetCS_AmountBilled,campBudgetC_ToBillRemaining,campBudgetCurrentBudgetHours,campBudgetCurrentTotalBudgetWithTax,campBudgetC_CurrentBudgetHours,campBudgetC_CurrentTotalBudget,campBudgetC_CurrentTotalBudgetWithTax,campBudgetHours,campBudgetExpenseBilled,campBudgetExpenseInvoiced,campBudgetAmountBilled,campBudgetAllocatedHours,campBudgetTotalGross,campBudgetToBillRemaining'', NULL, ''grid'', 
''[  {id:"campBudgetDisplayName", label:"Display Name"},
	{id:"campBudgetC_AmountBilled", label:"Campaign Amount Billed"},
	{id:"campBudgetCS_AmountBilled", label:"Campaign Segment Amount Billed"},
	{id:"campBudgetC_ToBillRemaining", label:"Campaign To Bill Remaining"},
	{id:"campBudgetC_AdvanceBilled", label:"Campaign Advance Billed"},
	{id:"campBudgetC_AdvanceBilledOpen", label:"Campaign Advance Billed Open"},
	{id:"campBudgetC_AdvanceBilledUnapplied", label:"Campaign Advance Billed Unapplied"},
	{id:"campBudgetCS_AdvanceBilled", label:"Campaign Segment Advance Billed"},
	{id:"campBudgetCurrentBudgetHours", label:"Project Current Budget Hours"},
	{id:"campBudgetCurrentBudgetLaborNet", label:"Project Current Budget Labor Net"},
	{id:"campBudgetCurrentBudgetLaborGross", label:"Project Current Budget Labor Gross"},
	{id:"campBudgetCurrentBudgetExpenseNet", label:"Project Current Budget Expense Net"},
	{id:"campBudgetCurrentBudgetExpenseGross", label:"Project Current Budget Expense Gross"},
	{id:"campBudgetCurrentBudgetContingency", label:"Project Current Budget Contingency"},
	{id:"campBudgetCurrentTotalBudget", label:"Project Current Total Budget"},
	{id:"campBudgetCurrentTotalBudgetWithTax", label:"Project Current Total Budget With Tax"},
	{id:"campBudgetCurrentTotalBudgetCont", label:"Project Current Total Budget Cont"},
	{id:"campBudgetCurrentTotalBudgetContWithTax", label:"Project Current Total Budget Cont With Tax"},
	{id:"campBudgetProjectToBillRemainingNoTax", label:"Project To Bill Remaining No Tax"},
	{id:"campBudgetProjectToBillRemainingWithTax", label:"Project To Bill Remaining with Tax"},
	{id:"campBudgetCOBudgetHours", label:"Project CO Budget Hours"},
	{id:"campBudgetCOBudgetLaborNet", label:"Project CO Budget Labor Net"},
	{id:"campBudgetCOBudgetLaborGross", label:"Project CO Budget Labor Gross"},
	{id:"campBudgetCOBudgetExpenseNet", label:"Project CO Budget Expense Net"},
	{id:"campBudgetCOBudgetExpenseGross", label:"Project CO Budget Expense Gross"},
	{id:"campBudgetCOBudgetContingency", label:"Project CO Budget Contingency"},
	{id:"campBudgetCOTotalBudget", label:"Project CO Total Budget"},
	{id:"campBudgetCOTotalBudgetWithTax", label:"Project CO Total Budget With Tax"},
	{id:"campBudgetCOTotalBudgetCont", label:"Project CO Total Budget Cont"},
	{id:"campBudgetCOTotalBudgetContWithTax", label:"Project CO Total Budget Cont With Tax"},
	{id:"campBudgetOriginalBudgetHours", label:"Project Original Budget Hours"},
	{id:"campBudgetOriginalBudgetLaborNet", label:"Project Original Budget Labor Net"},
	{id:"campBudgetOriginalBudgetLaborGross", label:"Project Original Budget Labor Gross"},
	{id:"campBudgetOriginalBudgetExpenseNet", label:"Project Original Budget Expense Net"},
	{id:"campBudgetOriginalBudgetExpenseGross", label:"Project Original Budget Expense Gross"},
	{id:"campBudgetOriginalBudgetContingency", label:"Project Original Budget Contingency"},
	{id:"campBudgetOriginalTotalBudget", label:"Project Original Total Budget"},
	{id:"campBudgetOriginalTotalBudgetWithTax", label:"Project Original Total Budget With Tax"},
	{id:"campBudgetOriginalTotalBudgetCont", label:"Project Original Total Budget Cont"},
	{id:"campBudgetOriginalTotalBudgetContWithTax", label:"Project Original Total Budget Cont With Tax"},
	{id:"campBudgetC_CurrentBudgetHours", label:"Campaign Current Budget Hours"},
	{id:"campBudgetC_CurrentBudgetLaborNet", label:"Campaign Current Budget Labor Net"},
	{id:"campBudgetC_CurrentBudgetLaborGross", label:"Campaign Current Budget Labor Gross"},
	{id:"campBudgetC_CurrentBudgetExpenseNet", label:"Campaign Current Budget Expense Net"},
	{id:"campBudgetC_CurrentBudgetExpenseGross", label:"Campaign Current Budget Expense Gross"},
	{id:"campBudgetC_CurrentBudgetContingency", label:"Campaign Current Budget Contingency"},
	{id:"campBudgetC_CurrentTotalBudget", label:"Campaign Current Total Budget"},
	{id:"campBudgetC_CurrentTotalBudgetWithTax", label:"Campaign Current Total Budget With Tax"},
	{id:"campBudgetC_CurrentTotalBudgetCont", label:"Campaign Current Total Budget Cont"},
	{id:"campBudgetC_CurrentTotalBudgetContWithTax", label:"Campaign Current Total Budget Cont With Tax"},
	{id:"campBudgetC_COBudgetHours", label:"Campaign CO Budget Hours"},
	{id:"campBudgetC_COBudgetLaborNet", label:"Campaign CO Budget Labor Net"},
	{id:"campBudgetC_COBudgetLaborGross", label:"Campaign CO Budget Labor Gross"},
	{id:"campBudgetC_COBudgetExpenseNet", label:"Campaign CO Budget Expense Net"},
	{id:"campBudgetC_COBudgetExpenseGross", label:"Campaign CO Budget Expense Gross"},
	{id:"campBudgetC_COBudgetContingency", label:"Campaign CO Budget Contingency"},
	{id:"campBudgetC_COTotalBudget", label:"Campaign CO Total Budget"},
	{id:"campBudgetC_COTotalBudgetWithTax", label:"Campaign CO Total Budget With Tax"},
	{id:"campBudgetC_COTotalBudgetCont", label:"Campaign CO Total Budget Cont"},
	{id:"campBudgetC_COTotalBudgetContWithTax", label:"Campaign CO Total Budget Cont With Tax"},
	{id:"campBudgetC_OriginalBudgetHours", label:"Campaign Original Budget Hours"},
	{id:"campBudgetC_OriginalBudgetLaborNet", label:"Campaign Original Budget Labor Net"},
	{id:"campBudgetC_OriginalBudgetLaborGross", label:"Campaign Original Budget Labor Gross"},
	{id:"campBudgetC_OriginalBudgetExpenseNet", label:"Campaign Original Budget Expense Net"},
	{id:"campBudgetC_OriginalBudgetExpenseGross", label:"Campaign Original Budget Expense Gross"},
	{id:"campBudgetC_OriginalBudgetContingency", label:"Campaign Original Budget Contingency"},
	{id:"campBudgetC_OriginalTotalBudget", label:"Campaign Original Total Budget"},
	{id:"campBudgetC_OriginalTotalBudgetWithTax", label:"Campaign Original Total Budget With Tax"},
	{id:"campBudgetC_OriginalTotalBudgetCont", label:"Campaign Original Total Budget Cont"},
	{id:"campBudgetC_OriginalTotalBudgetContWithTax", label:"Campaign Original Total Budget Cont With Tax"},
	{id:"campBudgetHours", label:"Project Actual Hours"},
	{id:"campBudgetHoursBilled", label:"Project Hours Billed"},
	{id:"campBudgetHoursInvoiced", label:"Project Hours Invoiced"},
	{id:"campBudgetHoursUnbilled", label:"Project Hours Unbilled"},
	{id:"campBudgetLaborNet", label:"Project Labor Net"},
	{id:"campBudgetLaborGross", label:"Project Labor Gross"},
	{id:"campBudgetLaborBilled", label:"Project Labor Billed"},
	{id:"campBudgetLaborInvoiced", label:"Project Labor Invoiced"},
	{id:"campBudgetLaborUnbilled", label:"Project Labor Unbilled"},
	{id:"campBudgetLaborWriteOff", label:"Project Labor Write Off"},
	{id:"campBudgetLaborHoursWriteOff", label:"Project Labor Hours Write Off"},
	{id:"campBudgetOpenOrdersNet", label:"Project Open Orders Net"},
	{id:"campBudgetOutsideCostsNet", label:"Project Outside Costs Net"},
	{id:"campBudgetInsideCostsNet", label:"Project Inside Costs Net"},
	{id:"campBudgetOpenOrdersGrossUnbilled", label:"Project Open Orders Gross Unbilled"},
	{id:"campBudgetOutsideCostsGrossUnbilled", label:"Project Outside Costs Gross Unbilled"},
	{id:"campBudgetInsideCostsGrossUnbilled", label:"Project Inside Costs Gross Unbilled"},
	{id:"campBudgetOutsideCostsGross", label:"Project Outside Costs Gross"},
	{id:"campBudgetInsideCostsGross", label:"Project Inside Costs Gross"},
	{id:"campBudgetOrderPrebilled", label:"Project Order Prebilled"},
	{id:"campBudgetExpenseWriteOff", label:"Project Expense Write Off"},
	{id:"campBudgetExpenseBilled", label:"Project Expense Billed"},
	{id:"campBudgetExpenseInvoiced", label:"Project Expense Invoiced"},
	{id:"campBudgetAdvanceBilled", label:"Project Advance Billed"},
	{id:"campBudgetAdvanceBilledOpen", label:"Project Advance Billed Open"},
	{id:"campBudgetAmountBilled", label:"Project Amount Billed"},
	{id:"campBudgetAmountBilledNoTax", label:"Project Amount Billed No Tax"},
	{id:"campBudgetAllocatedHours", label:"Project Allocated Hours"},
	{id:"campBudgetTotalCostsNet", label:"Project Total Costs Net"},
	{id:"campBudgetTotalCostsGrossUnbilled", label:"Project Total Costs Gross Unbilled"},
	{id:"campBudgetTotalCostsGross", label:"Project Total Costs Gross"},
	{id:"campBudgetTotalNet", label:"Project Total Net"},
	{id:"campBudgetTotalGrossUnbilled", label:"Project Total Gross Unbilled"},
	{id:"campBudgetTotalGross", label:"Project Total Gross"},
	{id:"campBudgetTotalGrossAfterWriteOff", label:"Project Total Gross After Write Off"},
	{id:"campBudgetHoursBilledRemaining", label:"Project Hours Billed Remaining"},
	{id:"campBudgetHoursRemaining", label:"Project Hours Remaining"},
	{id:"campBudgetHoursRemainingP", label:"Project Hours Remaining %"},
	{id:"campBudgetLaborNetRemaining", label:"Project Labor Net Remaining"},
	{id:"campBudgetLaborGrossRemaining", label:"Project Labor Gross Remaining"},
	{id:"campBudgetLaborGrossRemainingP", label:"Project Labor Gross Remaining %"},
	{id:"campBudgetCostsNetRemaining", label:"Project Costs Net Remaining"},
	{id:"campBudgetCostsGrossRemaining", label:"Project Costs Gross Remaining"},
	{id:"campBudgetCostsGrossRemainingP", label:"Project Costs Gross Remaining %"},
	{id:"campBudgetToBillRemaining", label:"Project To Bill Remaining"},
	{id:"campBudgetGrossRemaining", label:"Project Gross Remaining"},
    {id:"campBudgetGrossRemainingP", label:"Project Gross Remaining %"},
	{id:"campBudgetBilledDifference", label:"Project Billed Difference"},
	{id:"campBudgetRemainingAllocatedHours", label:"Project Allocated Hours Remaining"},
	{id:"campBudgetCampaignBudgetRemaining", label:"Campaign Budget Remaining"},
	{id:"campBudgetGrossRemainingCP", label:"Campaign Gross Remaining %"},
	{id:"campBudgetCampaignBudgetActualRemaining", label:"Campaign Budget Actual Remaining"},
	{id:"campBudgetCampaignBudgetActualHoursRemaining", label:"Campaign Budget Actual Hours Remaining"},
	{id:"campBudgetCampaignBudgetHoursRemaining", label:"Campaign Budget Hours Remaining"},
	{id:"campBudgetHoursRemainingCP", label:"Campaign Hours Remaining %"},	
	{id:"campBudgetLaborAfterWriteOff", label:"Project Labor Gross After WriteOff"},
	{id:"campBudgetLaborGrossAfterWriteOffRemaining", label:"Project Labor Gross After WriteOff Remaining"},
	{id:"campBudgetCostsGrossAfterWriteOffRemaining", label:"Project Costs Gross After WriteOff Remaining"},
	{id:"campBudgetGetLaborRateFrom", label:"Get Labor Rate From"},
	{id:"campBudgetProjectHoursAfterWriteoff ", label:"Project Hours After Writeoff"},
	{id:"campBudgetProjectHoursWriteoff ", label:"Project Hours Writeoff"},
	{id:"campBudgetProjectStatus ", label:"Project Status"},
	{id:"campBudgetCampaignBudgetUnbilledProjectRemaining", label:"Remaining Camp Budget Unbilled (Project)"}
 ]''
 , NULL, NULL, NULL, NULL)



 /*************************************************************************************************************************
Campaign Budget Detail
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignBudgetDetail'', ''Budget Detail Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignBudgetDetail'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''campaignBudgetDetail'', ''ScheduleLockedColumns'', 1, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campaignBudgetDetail'', ''grdCampaignBudgetDetailCols'', 1, ''Columns'', ''campBudDtlItemName,campBudDtlCurrentTotalBudget,campBudDtlCampaignCurrentTotalBudget,campBudDtlCampaignCurrentTotalBudgetWithTax,campBudDtlCampaignOriginalTotalBudgetWithTax,campBudDtlCurrentBudgetHours,campBudDtlCampaignCurrentBudgetHours,campBudDtlHours,campBudDtlAllocatedHours,campBudDtlExpenseBilled,campBudDtlExpenseInvoiced,campBudDtlTotalGross,campBudDtlAmountBilled,campBudDtlLaborUnbilled,campBudDtlToBillRemaining'', NULL, ''grid'', 
''[  {id:"campBudDtlItemID", label:"Item ID"},
	{id:"campBudDtlItemName", label:"Item Name"},
	{id:"campBudDtlDepartmentName", label:"Department Name"},
	{id:"campBudDtlWorkTypeID", label:"Work Type ID"},
	{id:"campBudDtlWorkTypeName", label:"Work Type Name"},
	{id:"campBudDtlWorkTypeDisplayOrder", label:"Work Type Display Order"},
	{id:"campBudDtlHours", label:"Project Act Hours"},
	{id:"campBudDtlHoursApproved", label:"Project Hours Approved"},
	{id:"campBudDtlHoursBilled", label:"Project Hours Billed"},
	{id:"campBudDtlHoursInvoiced", label:"Project Hours Invoiced"},
	{id:"campBudDtlHoursUnbilled", label:"Project Hours Unbilled"},
	{id:"campBudDtlLaborNet", label:"Project Labor Net"},
	{id:"campBudDtlLaborNetApproved", label:"Project Labor Net Approved"},
	{id:"campBudDtlLaborGross", label:"Project Labor Gross"},
	{id:"campBudDtlLaborGrossApproved", label:"Project Labor Gross Approved"},
	{id:"campBudDtlLaborUnbilled", label:"Project Labor Unbilled"},
	{id:"campBudDtlLaborBilled", label:"Project Labor Billed"},
	{id:"campBudDtlLaborInvoiced", label:"Project Labor Invoiced"},
	{id:"campBudDtlLaborWriteOff", label:"Project Labor Write Off"},
	{id:"campBudDtlLaborHoursWriteOff", label:"Project Labor Hours Write Off"},
	{id:"campBudDtlAmountBilled", label:"Project Amount Billed"},
	{id:"campBudDtlAmountBilledNoTax", label:"Project Amount Billed No Tax"},
	{id:"campBudDtlAdvanceBilled", label:"Project Advance Billed"},
	{id:"campBudDtlAdvanceBilledOpen", label:"Project Advance Billed Open"},
	{id:"campBudDtlAllocatedHours", label:"Project Allocated Hours"},
	{id:"campBudDtlOutsideCostsNet", label:"Project Outside Costs Net"},
	{id:"campBudDtlInsideCostsNet", label:"Project Inside Costs Net"},
	{id:"campBudDtlOpenOrdersGrossUnbilled", label:"Project Open Orders Gross Unbilled"},
	{id:"campBudDtlOutsideCostsGrossUnbilled", label:"Project Outside Costs Gross Unbilled"},
	{id:"campBudDtlInsideCostsGrossUnbilled", label:"Project Inside Costs Gross Unbilled"},
	{id:"campBudDtlOutsideCostsGross", label:"Project Outside Costs Gross"},
	{id:"campBudDtlInsideCostsGross", label:"Project Inside Costs Gross"},
	{id:"campBudDtlExpenseWriteOff", label:"Project Expense Write Off"},
	{id:"campBudDtlExpenseBilled", label:"Project Expense Billed"},
	{id:"campBudDtlExpenseInvoiced", label:"Project Expense Invoiced"},
	{id:"campBudDtlCurrentBudgetHours", label:"Project Current Budget Hours"},
	{id:"campBudDtlCurrentBudgetLaborNet", label:"Project Current Budget Labor Net"},
	{id:"campBudDtlCurrentBudgetLaborGross", label:"Project Current Budget Labor Gross"},
	{id:"campBudDtlCurrentBudgetExpenseNet", label:"Project Current Budget Expense Net"},
	{id:"campBudDtlCurrentBudgetExpenseGross", label:"Project Current Budget Expense Gross"},
	{id:"campBudDtlCurrentBudgetContingency", label:"Project Current Budget Contingency"},
	{id:"campBudDtlCurrentTotalBudget", label:"Project Current Total Budget"},
	{id:"campBudDtlCurrentTotalBudgetCont", label:"Project Current Total Budget Cont"},
	{id:"campBudDtlCurrentTotalBudgetWithTax", label:"Project Current Total Budget With Tax"},
	{id:"campBudDtlCurrentTotalBudgetContWithTax", label:"Project Current Total Budget Cont With Tax"},
	{id:"campBudDtlCOBudgetHours", label:"Project CO Budget Hours"},
	{id:"campBudDtlCOBudgetLaborNet", label:"Project CO Budget Labor Net"},
	{id:"campBudDtlCOBudgetLaborGross", label:"Project CO Budget Labor Gross"},
	{id:"campBudDtlCOBudgetExpenseNet", label:"Project CO Budget Expense Net"},
	{id:"campBudDtCOBudgetExpenseGross", label:"Project CO Budget Expense Gross"},
	{id:"campBudDtlCOBudgetContingency", label:"Project CO Budget Contingency"},
	{id:"campBudDtlCOTotalBudget", label:"Project CO Total Budget"},
	{id:"campBudDtlCOTotalBudgetCont", label:"Project CO Total Budget Cont"},
	{id:"campBudDtlCOTotalBudgetWithTax", label:"Project CO Total Budget With Tax"},
	{id:"campBudDtlCOTotalBudgetContWithTax", label:"Project CO Total Budget Cont With Tax"},
	{id:"campBudDtlOriginalBudgetHours", label:"Project Original Budget Hours"},
	{id:"campBudDtlOriginalBudgetLaborNet", label:"Project Original Budget Labor Net"},
	{id:"campBudDtlOriginalBudgetLaborGross", label:"Project Original Budget Labor Gross"},
	{id:"campBudDtlOriginalBudgetExpenseNet", label:"Project Original Budget Expense Net"},
	{id:"campBudDtlOriginalBudgetExpenseGross", label:"Project Original Budget Expense Gross"},
	{id:"campBudDtlOriginalBudgetContingency", label:"Project Original Budget Contingency"},
	{id:"campBudDtlOriginalTotalBudget", label:"Project Original Total Budget"},
	{id:"campBudDtlOriginalTotalBudgetCont", label:"Project Original Total Budget Cont"},
	{id:"campBudDtlOriginalTotalBudgetWithTax", label:"Project Original Total Budget With Tax"},
	{id:"campBudDtlOriginalTotalBudgetContWithTax", label:"Project Original Total Budget Cont With Tax"},
	{id:"campBudDtlCampaignCurrentBudgetHours", label:"Campaign Current Budget Hours"},
	{id:"campBudDtlCampaignCurrentBudgetLaborNet", label:"Campaign Current Budget Labor Net"},
	{id:"campBudDtlCampaignCurrentBudgetLaborGross", label:"Campaign Current Budget Labor Gross"},
	{id:"campBudDtlCampaignCurrentBudgetExpenseNet", label:"Campaign Current Budget Expense Net"},
	{id:"campBudDtlCampaignCurrentBudgetExpenseGross", label:"Campaign Current Budget Expense Gross"},
	{id:"campBudDtlCampaignCurrentBudgetContingency", label:"Campaign Current Budget Contingency"},
	{id:"campBudDtlCampaignCurrentTotalBudget", label:"Campaign Current Total Budget"},
	{id:"campBudDtlCampaignCurrentTotalBudgetWithTax", label:"Campaign Current Total Budget With Tax"},
	{id:"campBudDtlCampaignCurrentTotalBudgetCont", label:"Campaign Current Total Budget Cont"},
	{id:"campBudDtlCampaignCurrentTotalBudgetContWithTax", label:"Campaign Current Total Budget Cont With Tax"},
	{id:"campBudDtlCampaignCOBudgetHours", label:"Campaign CO Budget Hours"},
	{id:"campBudDtlCampaignCOBudgetLaborNet", label:"Campaign CO Budget Labor Net"},
	{id:"campBudDtlCampaignCOBudgetLaborGross", label:"Campaign CO Budget Labor Gross"},
	{id:"campBudDtlCampaignCOBudgetExpenseNet", label:"Campaign CO Budget Expense Net"},
	{id:"campBudDtlCampaignCOBudgetExpenseGross", label:"Campaign CO Budget Expense Gross"},
	{id:"campBudDtlCampaignCOBudgetContingency", label:"Campaign CO Budget Contingency"},
	{id:"campBudDtlCampaignCOTotalBudget", label:"Campaign CO Total Budget"},
	{id:"campBudDtlCampaignCOTotalBudgetWithTax", label:"Campaign CO Total Budget With Tax"},
	{id:"campBudDtlCampaignCOTotalBudgetCont", label:"Campaign CO Total Budget Cont"},
	{id:"campBudDtlCampaignCOTotalBudgetContWithTax", label:"Campaign CO Total Budget Cont With Tax"},
	{id:"campBudDtlCampaignOriginalBudgetHours", label:"Campaign Original Budget Hours"},
	{id:"campBudDtlCampaignOriginalBudgetLaborNet", label:"Campaign Original Budget Labor Net"},
	{id:"campBudDtlCampaignOriginalBudgetLaborGross", label:"Campaign Original Budget Labor Gross"},
	{id:"campBudDtlCampaignOriginalBudgetExpenseNet", label:"Campaign Original Budget Expense Net"},
	{id:"campBudDtlCampaignOriginalBudgetExpenseGross", label:"Campaign Original Budget Expense Gross"},
	{id:"campBudDtlCampaignOriginalBudgetContingency", label:"Campaign Original Budget Contingency"},
	{id:"campBudDtlCampaignOriginalTotalBudget", label:"Campaign Original Total Budget"},
	{id:"campBudDtlCampaignOriginalTotalBudgetWithTax", label:"Campaign Original Total Budget With Tax"},
	{id:"campBudDtlCampaignOriginalTotalBudgetCont", label:"Campaign Original Total Budget Cont"},
	{id:"campBudDtlCampaignOriginalTotalBudgetContWithTax", label:"Campaign Original Total Budget Cont With Tax"},
	{id:"campBudDtlTotalCostsNet", label:"Project Total Costs Net"},
	{id:"campBudDtlTotalCostsGrossUnbilled", label:"Project Total Costs Gross Unbilled"},
	{id:"campBudDtlTotalCostsGross", label:"Project Total Costs Gross"},
	{id:"campBudDtlTotalNet", label:"Project Total Net"},
	{id:"campBudDtlTotalGrossUnbilled", label:"Project Total Gross Unbilled"},
	{id:"campBudDtlTotalGross", label:"Project Total Gross"},
	{id:"campBudDtlTotalGrossAfterWriteOff", label:"Project Total Gross After Write Off"},
	{id:"campBudDtlHoursBilledRemaining", label:"Project Hours Billed Remaining"},
	{id:"campBudDtlHoursRemaining", label:"Project Hours Remaining"},
	{id:"campBudDtlHoursRemainingP", label:"Project Hours Remaining %"},
	{id:"campBudDtlLaborNetRemaining", label:"Project Labor Net Remaining"},
	{id:"campBudDtlLaborGrossRemaining", label:"Project Labor Gross Remaining"},
	{id:"campBudDtlLaborGrossRemainingP", label:"Project Labor Gross Remaining %"},
	{id:"campBudDtlCostsNetRemaining", label:"Project Costs Net Remaining"},
	{id:"campBudDtlCostsGrossRemaining", label:"Project Costs Gross Remaining"},
	{id:"campBudDtlCostsGrossRemainingP", label:"Project Costs Gross Remaining %"},
	{id:"campBudDtlToBillRemaining", label:"Project To Bill Remaining"},
	{id:"campBudDtlGrossRemaining", label:"Project Gross Remaining"},
	{id:"campBudDtlGrossRemainingP", label:"Project Gross Remaining %"},
	{id:"campBudDtlBilledDifference", label:"Project Billed Difference"}
 ]''
 , NULL, NULL, NULL, NULL)


 /*************************************************************************************************************************
Campaign Billing transactions grids
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campBillTransactions'', ''Campaign Billing Detail Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campBillTransactions'', ''H1'', 0, ''% of Service/Item Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campBillTransactions'', ''grdServicesItemsCols'', 1, ''Columns'', ''colServiceDescription,colServicePercent,colServiceBillAmt,colServiceEstHrs,colServiceEstLabor,colServiceEstExpenses,colServiceEstTotal,colServiceActHrs,colServiceActLabor,colServiceActExpenses,colServiceActTotal,colServiceBilled,colServiceRemaining'', NULL, ''grid'', 

''[
{id:"colServiceDescription", label:"Item/Service"},
{id:"colServicePercent", label:"%"},
{id:"colServiceBillAmt", label:"Bill Amt"},
{id:"colServiceEstHrs", label:"Est Hrs"},
{id:"colServiceEstLabor", label:"Est Labor"},
{id:"colServiceEstExpenses", label:"Est Exp"},
{id:"colServiceEstTotal", label:"Est Total"},
{id:"colServiceActHrs", label:"Act Hrs"},
{id:"colServiceActLabor", label:"Act Labor"},
{id:"colServiceActExpenses", label:"Act Exp"},
{id:"colServiceActTotal", label:"Act Total"},
{id:"colServiceBilled", label:"Billed"},
{id:"colServiceRemaining", label:"Remaining"},
{id:"colProjTotalGrossUnbilled", label:"Total Gross Unbilled"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campBillTransactions'', ''H2'', 2, ''% of Project Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campBillTransactions'', ''grdProjectsCols'', 3, ''Columns'', ''colProjName,colProjPercent,colProjBillAmt,colProjEstHrs,colProjEstLabor,colProjEstExpenses,colProjEstTotal,colProjActHrs,colProjActLabor,colProjActExpenses,colProjActTotal,colProjBilled,colProjRemaining'', NULL, ''grid'', 

''[
{id:"colProjName", label:"Project"},
{id:"colProjPercent", label:"%"},
{id:"colProjBillAmt", label:"Bill Amt"},
{id:"colProjEstHrs", label:"Est Hrs"},
{id:"colProjEstLabor", label:"Est Labor"},
{id:"colProjEstExpenses", label:"Est Exp"},
{id:"colProjEstTotal", label:"Est Total"},
{id:"colProjActHrs", label:"Act Hrs"},
{id:"colProjActLabor", label:"Act Labor"},
{id:"colProjActExpenses", label:"Act Exp"},
{id:"colProjActTotal", label:"Act Total"},
{id:"colProjBilled", label:"Billed"},
{id:"colProjRemaining", label:"Remaining"},
{id:"colProjTotalGrossUnbilled", label:"Total Gross Unbilled"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campBillTransactions'', ''H3'', 4, ''% of Segment Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campBillTransactions'', ''grdSegmentsCols'', 5, ''Columns'', ''colSegName,colSegPercent,colSegBillAmt,colSegEstHrs,colSegEstLabor,colSegEstExpenses,colSegEstTotal,colSegActHrs,colSegActLabor,colSegActExpenses,colSegActTotal,colSegBilled,colSegRemaining'', NULL, ''grid'', 

''[
{id:"colSegName", label:"Segment"},
{id:"colSegPercent", label:"%"},
{id:"colSegBillAmt", label:"Bill Amt"},
{id:"colSegEstHrs", label:"Est Hrs"},
{id:"colSegEstLabor", label:"Est Labor"},
{id:"colSegEstExpenses", label:"Est Exp"},
{id:"colSegEstTotal", label:"Est Total"},
{id:"colSegActHrs", label:"Act Hrs"},
{id:"colSegActLabor", label:"Act Labor"},
{id:"colSegActExpenses", label:"Act Exp"},
{id:"colSegActTotal", label:"Act Total"},
{id:"colSegBilled", label:"Billed"},
{id:"colSegRemaining", label:"Remaining"},
{id:"colProjTotalGrossUnbilled", label:"Total Gross Unbilled"}
]''
	 , NULL, NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campBillTransactions'', ''H4'', 6, ''Extras Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campBillTransactions'', ''grdTransactionDetailCols'', 7, ''Columns'', ''prjbillxProjectFullName,prjbillxTransactionDate,prjbillxDescription,prjbillxTransactionComments,prjbillxQuantity,prjbillxUnitRate,prjbillxTotalCost,prjbillxBillableCost,prjbillxTaskFullName,prjbillxItemFullName,prjbillxDepartmentName'', NULL, ''grid'', 

''[
{id:"prjbillxProjectFullName", label:"Project"},
{id:"prjbillxTransactionDate", label:"Date"},
{id:"prjbillxDescription", label:"Description"},
{id:"prjbillxTransactionComments", label:"Comments"},
{id:"prjbillxQuantity", label:"Quantity"},
{id:"prjbillxUnitRate", label:"Unit Rate"},
{id:"prjbillxTotalCost", label:"Net"},
{id:"prjbillxBillableCost", label:"Gross"},
{id:"prjbillxTaskFullName", label:"Task"},
{id:"prjbillxItemFullName", label:"Item/Service"},
{id:"prjbillxDepartmentName", label:"Department"}
]''
	 , NULL, NULL, null, NULL)


/*************************************************************************************************************************
Campaign Production Dash
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''productionCampDash'', ''Campaigns Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''H1'', 0, ''My Campaigns Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''Active'', 1, ''Active Campaigns Only'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''OpenExpanded'', 2, ''Expand Campaigns When Opened'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''AEKeys'', 3, ''Account Manager'', ''-1'', ''All'', ''selectlist'', NULL, ''selectlist.User'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''ProjectManagerKeys'', 4, ''Project Manager'', ''-1'', ''All'', ''selectlist'', NULL, ''selectlist.User'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''GLCompanyID'', 5, ''GL Company'', ''-1'', ''All'', ''lookup'', NULL, ''lookup.GLCompany'', NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''BudgetWarning'', 6, ''Budget Warning'', ''80'', NULL, ''number'', NULL, null, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''GroupBy'', 7, ''Group By'', ''CustomerFullName'', ''Client'', ''lookup'', ''No Grouping:NoGrouping|Client:CustomerFullName|Account Manager:AEFullName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampDash'', ''GroupByDir'', 8, ''Group Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''productionCampDash'', ''grdCampProductionDashCols'', 6, ''Columns'', ''prodCampDashCampaignFullName,prodCampDashClientName,prodCampDashDescription,prodCampDashStartDate,prodCampDashEndDate,prodCampDashProjectTaskStatus,prodCampDashFinancialStatusImage'', NULL, ''grid'', 

''[{id:"prodCampDashCampaignFullName", label:"Campaign Full Name"},
	{id:"prodCampDashClientName", label:"Client Name"},
	{id:"prodCampDashDescription", label:"Description"},	
	{id:"prodCampDashStartDate", label:"Start Date"},
	{id:"prodCampDashEndDate", label:"End Date"},
	{id:"prodCampDashProjectTaskStatus", label:"Campaign Status"},
	{id:"prodCampDashFinancialStatusImage", label:"Financial Status"},
	{id:"prodCampDashPrimaryContact", label:"Primary Contact"},
	{id:"prodCampDashAEName", label:"Account Manager"},
	{id:"prodCampDashObjective", label:"Objective"},
	{id:"prodCampDashCampaignID", label:"Campaign ID"},
	{id:"prodCampDashCampaignName", label:"Campaign Name"},
	{id:"prodCampDashCustomerID", label:"Client ID"},
	{id:"prodCampDashGLCompanyName", label:"GL Company Name"},
	{id:"prodCampDashGLCompanyID", label:"GL Company ID"},
	{id:"prodCampaignDashOfficeName", label:"Office Name"},	
	{id:"prodCampDashBillBy", label:"Bill By"},
	{id:"prodCampDashMultipleSegments", label:"Use Multiple Segments"},
	{id:"prodCampDashActive", label:"Active"},
	{id:"prodCampDashCurrencyID", label:"Currency ID"},
	{id:"prodCampDashProductName", label:"Product Name"},
	{id:"prodCampDashDivisionName", label:"Division Name"},
	{id:"prodCampDashCampaignBudgetNet", label:"Campaign Budget Net"},
	{id:"prodCampDashCampaignBudgetGross", label:"Campaign Budget Gross"},
	{id:"prodCampDashCampaignBudgetLaborGross", label:"Campaign Budget Labor Gross"},
	{id:"prodCampDashCampaignBudgetLaborNet", label:"Campaign Budget Labor Net"},
	{id:"prodCampDashCampaignBudgetHours", label:"Campaign Budget Hours"},
	{id:"prodCampDashCampaignBudgetExpenseGross", label:"Campaign Budget Expense Gross"},
	{id:"prodCampDashCampaignBudgetExpenseNet", label:"Campaign Budget Expense Net"},	
	{id:"prodCampDashCampaignBudgetQty", label:"Campaign Budget Qty"},	
	{id:"prodCampDashCampaignAmountBilled", label:"Campaign Amount Billed"},
	{id:"prodCampDashDeliverables", label:"Deliverables"},
	{id:"prodCampDashPMName", label:"Project Manager"},
	{id:"prodCampDashOpportunityFullName", label:"Opportunity Full Name"},
	{id:"prodCampDashLaborHours", label:"Labor Hours"},
	{id:"prodCampDashBudgetLaborHours", label:"Budget Labor Hours"},
	{id:"prodCampDashProjectAllocatedHours", label:"Project Allocated Hours"},
	{id:"prodCampDashLeadStageName", label:"Opportunity Stage"},
	{id:"prodCampDashLeadStatusName", label:"Opportunity Status"},
	{id:"prodCampDashLaborGross", label:"Labor Gross"}
]''
	 , NULL, NULL,''Campaign'',''Campaign'')




/*************************************************************************************************************************
Campaign Production PROJECTS
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''productionCampProjects'', ''Campaigns Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''productionCampProjects'', ''H1'', 0, ''Project Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''productionCampProjects'', ''grdCampaignProjectsCols'', 6, ''Columns'', ''campaignDisplayName,campaignProjectStatus,campaignAccountManager,campaignPrimaryContact,campaignProjectDueDate'', NULL, ''grid'', 

''[{id:"campaignDisplayName", label:"Projects"},
	{id:"campaignProjectStatus", label:"Project Status"},
	{id:"campaignAccountManager", label:"Account Manager"},		
	{id:"campaignPrimaryContact", label:"Primary Contact"},
	{id:"campaignProjectManager", label:"Project Manager"},
	{id:"campaignProjectDivision", label:"Division"},
	{id:"campaignProjectProduct", label:"Product"},
	{id:"campaignProjectDueDate", label:"Project Due Date"},
	{id:"campaignProjectType", label:"Project Type"}
]''
	 , NULL, NULL,NULL,NULL)



/*************************************************************************************************************************
Campaign Dashboard 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignDashBoard'', ''Campaign Dashboard Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardSettings'', 0, ''Dashboard Sections'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardDescription'', 1, ''Campaign Description'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardDailyFeed'', 2, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardBurnChart'', 3, ''Burn Chart'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardDiary'', 4, ''Recent Diary Posts'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardCustomFields'', 5, ''Custom Fields'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardDeliverables'', 6, ''Deliverables'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignDashBoard'', ''CampDashboardSnapshot'', 7, ''Campaign Snapshot'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Campaign Edit 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignEdit'', ''Edit Campaign Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignEdit'', ''DisableEditingCampaignID'', 1, ''Disable the editing of the Campaign ID'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)



/*************************************************************************************************************************
Campaign Estimate List
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateCampaignList'', ''Estimate List Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateCampaignList'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''estimateCampaignList'', ''gridCols'', 1, ''Columns'', ''EstimateFullName,EstimateNumber,ChangeOrder,DateAdded,EnteredByName,ExternalApprovalStatus,ExternalApproverName,InternalApprovalStatus,EstimateTotal'', NULL, ''grid'', 
''[	{id:"ChangeOrder", label:"Change Order"},
	{id:"DateAdded", label:"Date Added"},
	{id:"EnteredByName", label:"Entered By"},
	{id:"EstTypeDesc", label:"Est Type"},
	{id:"EstimateFullName", label:"Estimate Name"},
	{id:"EstimateNumber", label:"Estimate Number"},
	{id:"EstimateDescription", label:"Estimate Description"},
	{id:"ExternalApprovalStatus", label:"External Approval Status"},
	{id:"ExternalApproverName", label:"External Approver Name"},
	{id:"ExternalComments", label:"External Comments"},
	{id:"InternalApprovalStatus", label:"Internal Approval Status"},
	{id:"InternalApproverName", label:"Internal Approver Name"},
	{id:"InternalComments", label:"Internal Comments"},
	{id:"Revision", label:"Revision"},
	{id:"EstimateTotal", label:"Estimate Total"},
	{id:"ExpenseGross", label:"Expense Gross"},
	{id:"ExpenseNet", label:"Expense Net"},
	{id:"Hours", label:"Hours"},
	{id:"LaborGross", label:"Labor Gross"},
	{id:"LaborNet", label:"Labor Net"},
	{id:"SalesTax2Amount", label:"Sales Tax2 Amount"},
	{id:"SalesTaxAmount", label:"Sales Tax Amount"},
	{id:"TaxableTotal", label:"Taxable Total"},
	{id:"Total", label:"Total"}
 ]''
	 , NULL, NULL, null, NULL)

/*************************************************************************************************************************
Campaign Add
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignAdd'', ''Add Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignAdd'', ''ManualID'', 0, ''Manually Add Campaign ID'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignAdd'', ''ShowAccountManager'', 1, ''Show Account Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref) 
Values (''campaignAdd'', ''ShowProjectManager'', 2, ''Show Project Manager'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''ShowProjectManager'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignAdd'', ''StartDateEndDateRequired'', 3, ''Require Start Date / End Date'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Campaign Budget Analysis
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignBudgetAnalysis'', ''Campaign Budget Analysis Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignBudgetAnalysis'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''campaignBudgetAnalysis'', ''LockedColumns'', 1, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campaignBudgetAnalysis'', ''grdCampaignBudgetAnalysisCols'', 1, ''Columns'', ''campBudgetDisplayName,campBudgetC_AmountBilled,campBudgetCS_AmountBilled,campBudgetC_ToBillRemaining,campBudgetCurrentBudgetHours,campBudgetCurrentTotalBudgetWithTax,campBudgetC_CurrentBudgetHours,campBudgetC_CurrentTotalBudget,campBudgetC_CurrentTotalBudgetWithTax,campBudgetHours,campBudgetExpenseBilled,campBudgetExpenseInvoiced,campBudgetAmountBilled,campBudgetAllocatedHours,campBudgetTotalGross,campBudgetToBillRemaining'', NULL, ''grid'', 
''[  {id:"campBudgetDisplayName", label:"Display Name"},
	{id:"campBudgetC_AmountBilled", label:"Campaign Amount Billed"},
	{id:"campBudgetCS_AmountBilled", label:"Campaign Segment Amount Billed"},
	{id:"campBudgetC_ToBillRemaining", label:"Campaign To Bill Remaining"},
	{id:"campBudgetC_AdvanceBilled", label:"Campaign Advance Billed"},
	{id:"campBudgetC_AdvanceBilledOpen", label:"Campaign Advance Billed Open"},
	{id:"campBudgetC_AdvanceBilledUnapplied", label:"Campaign Advance Billed Unapplied"},
	{id:"campBudgetCS_AdvanceBilled", label:"Campaign Segment Advance Billed"},
	{id:"campBudgetCurrentBudgetHours", label:"Project Current Budget Hours"},
	{id:"campBudgetCurrentBudgetLaborNet", label:"Project Current Budget Labor Net"},
	{id:"campBudgetCurrentBudgetLaborGross", label:"Project Current Budget Labor Gross"},
	{id:"campBudgetCurrentBudgetExpenseNet", label:"Project Current Budget Expense Net"},
	{id:"campBudgetCurrentBudgetExpenseGross", label:"Project Current Budget Expense Gross"},
	{id:"campBudgetCurrentBudgetContingency", label:"Project Current Budget Contingency"},
	{id:"campBudgetCurrentTotalBudget", label:"Project Current Total Budget"},
	{id:"campBudgetCurrentTotalBudgetWithTax", label:"Project Current Total Budget With Tax"},
	{id:"campBudgetCurrentTotalBudgetCont", label:"Project Current Total Budget Cont"},
	{id:"campBudgetCurrentTotalBudgetContWithTax", label:"Project Current Total Budget Cont With Tax"},
	{id:"campBudgetProjectToBillRemainingNoTax", label:"Project To Bill Remaining No Tax"},
	{id:"campBudgetProjectToBillRemainingWithTax", label:"Project To Bill Remaining with Tax"},
	{id:"campBudgetCOBudgetHours", label:"Project CO Budget Hours"},
	{id:"campBudgetCOBudgetLaborNet", label:"Project CO Budget Labor Net"},
	{id:"campBudgetCOBudgetLaborGross", label:"Project CO Budget Labor Gross"},
	{id:"campBudgetCOBudgetExpenseNet", label:"Project CO Budget Expense Net"},
	{id:"campBudgetCOBudgetExpenseGross", label:"Project CO Budget Expense Gross"},
	{id:"campBudgetCOBudgetContingency", label:"Project CO Budget Contingency"},
	{id:"campBudgetCOTotalBudget", label:"Project CO Total Budget"},
	{id:"campBudgetCOTotalBudgetWithTax", label:"Project CO Total Budget With Tax"},
	{id:"campBudgetCOTotalBudgetCont", label:"Project CO Total Budget Cont"},
	{id:"campBudgetCOTotalBudgetContWithTax", label:"Project CO Total Budget Cont With Tax"},
	{id:"campBudgetOriginalBudgetHours", label:"Project Original Budget Hours"},
	{id:"campBudgetOriginalBudgetLaborNet", label:"Project Original Budget Labor Net"},
	{id:"campBudgetOriginalBudgetLaborGross", label:"Project Original Budget Labor Gross"},
	{id:"campBudgetOriginalBudgetExpenseNet", label:"Project Original Budget Expense Net"},
	{id:"campBudgetOriginalBudgetExpenseGross", label:"Project Original Budget Expense Gross"},
	{id:"campBudgetOriginalBudgetContingency", label:"Project Original Budget Contingency"},
	{id:"campBudgetOriginalTotalBudget", label:"Project Original Total Budget"},
	{id:"campBudgetOriginalTotalBudgetWithTax", label:"Project Original Total Budget With Tax"},
	{id:"campBudgetOriginalTotalBudgetCont", label:"Project Original Total Budget Cont"},
	{id:"campBudgetOriginalTotalBudgetContWithTax", label:"Project Original Total Budget Cont With Tax"},
	{id:"campBudgetC_CurrentBudgetHours", label:"Campaign Current Budget Hours"},
	{id:"campBudgetC_CurrentBudgetLaborNet", label:"Campaign Current Budget Labor Net"},
	{id:"campBudgetC_CurrentBudgetLaborGross", label:"Campaign Current Budget Labor Gross"},
	{id:"campBudgetC_CurrentBudgetExpenseNet", label:"Campaign Current Budget Expense Net"},
	{id:"campBudgetC_CurrentBudgetExpenseGross", label:"Campaign Current Budget Expense Gross"},
	{id:"campBudgetC_CurrentBudgetContingency", label:"Campaign Current Budget Contingency"},
	{id:"campBudgetC_CurrentTotalBudget", label:"Campaign Current Total Budget"},
	{id:"campBudgetC_CurrentTotalBudgetWithTax", label:"Campaign Current Total Budget With Tax"},
	{id:"campBudgetC_CurrentTotalBudgetCont", label:"Campaign Current Total Budget Cont"},
	{id:"campBudgetC_CurrentTotalBudgetContWithTax", label:"Campaign Current Total Budget Cont With Tax"},
	{id:"campBudgetC_COBudgetHours", label:"Campaign CO Budget Hours"},
	{id:"campBudgetC_COBudgetLaborNet", label:"Campaign CO Budget Labor Net"},
	{id:"campBudgetC_COBudgetLaborGross", label:"Campaign CO Budget Labor Gross"},
	{id:"campBudgetC_COBudgetExpenseNet", label:"Campaign CO Budget Expense Net"},
	{id:"campBudgetC_COBudgetExpenseGross", label:"Campaign CO Budget Expense Gross"},
	{id:"campBudgetC_COBudgetContingency", label:"Campaign CO Budget Contingency"},
	{id:"campBudgetC_COTotalBudget", label:"Campaign CO Total Budget"},
	{id:"campBudgetC_COTotalBudgetWithTax", label:"Campaign CO Total Budget With Tax"},
	{id:"campBudgetC_COTotalBudgetCont", label:"Campaign CO Total Budget Cont"},
	{id:"campBudgetC_COTotalBudgetContWithTax", label:"Campaign CO Total Budget Cont With Tax"},
	{id:"campBudgetC_OriginalBudgetHours", label:"Campaign Original Budget Hours"},
	{id:"campBudgetC_OriginalBudgetLaborNet", label:"Campaign Original Budget Labor Net"},
	{id:"campBudgetC_OriginalBudgetLaborGross", label:"Campaign Original Budget Labor Gross"},
	{id:"campBudgetC_OriginalBudgetExpenseNet", label:"Campaign Original Budget Expense Net"},
	{id:"campBudgetC_OriginalBudgetExpenseGross", label:"Campaign Original Budget Expense Gross"},
	{id:"campBudgetC_OriginalBudgetContingency", label:"Campaign Original Budget Contingency"},
	{id:"campBudgetC_OriginalTotalBudget", label:"Campaign Original Total Budget"},
	{id:"campBudgetC_OriginalTotalBudgetWithTax", label:"Campaign Original Total Budget With Tax"},
	{id:"campBudgetC_OriginalTotalBudgetCont", label:"Campaign Original Total Budget Cont"},
	{id:"campBudgetC_OriginalTotalBudgetContWithTax", label:"Campaign Original Total Budget Cont With Tax"},
	{id:"campBudgetHours", label:"Project Actual Hours"},
	{id:"campBudgetHoursBilled", label:"Project Hours Billed"},
	{id:"campBudgetHoursInvoiced", label:"Project Hours Invoiced"},
	{id:"campBudgetHoursUnbilled", label:"Project Hours Unbilled"},
	{id:"campBudgetLaborNet", label:"Project Labor Net"},
	{id:"campBudgetLaborGross", label:"Project Labor Gross"},
	{id:"campBudgetLaborBilled", label:"Project Labor Billed"},
	{id:"campBudgetLaborInvoiced", label:"Project Labor Invoiced"},
	{id:"campBudgetLaborUnbilled", label:"Project Labor Unbilled"},
	{id:"campBudgetLaborWriteOff", label:"Project Labor Write Off"},
	{id:"campBudgetLaborHoursWriteOff", label:"Project Labor Hours Write Off"},
	{id:"campBudgetOpenOrdersNet", label:"Project Open Orders Net"},
	{id:"campBudgetOutsideCostsNet", label:"Project Outside Costs Net"},
	{id:"campBudgetInsideCostsNet", label:"Project Inside Costs Net"},
	{id:"campBudgetOpenOrdersGrossUnbilled", label:"Project Open Orders Gross Unbilled"},
	{id:"campBudgetOutsideCostsGrossUnbilled", label:"Project Outside Costs Gross Unbilled"},
	{id:"campBudgetInsideCostsGrossUnbilled", label:"Project Inside Costs Gross Unbilled"},
	{id:"campBudgetOutsideCostsGross", label:"Project Outside Costs Gross"},
	{id:"campBudgetInsideCostsGross", label:"Project Inside Costs Gross"},
	{id:"campBudgetOrderPrebilled", label:"Project Order Prebilled"},
	{id:"campBudgetExpenseWriteOff", label:"Project Expense Write Off"},
	{id:"campBudgetExpenseBilled", label:"Project Expense Billed"},
	{id:"campBudgetExpenseInvoiced", label:"Project Expense Invoiced"},
	{id:"campBudgetAdvanceBilled", label:"Project Advance Billed"},
	{id:"campBudgetAdvanceBilledOpen", label:"Project Advance Billed Open"},
	{id:"campBudgetAmountBilled", label:"Project Amount Billed"},
	{id:"campBudgetAmountBilledNoTax", label:"Project Amount Billed No Tax"},
	{id:"campBudgetAllocatedHours", label:"Project Allocated Hours"},
	{id:"campBudgetTotalCostsNet", label:"Project Total Costs Net"},
	{id:"campBudgetTotalCostsGrossUnbilled", label:"Project Total Costs Gross Unbilled"},
	{id:"campBudgetTotalCostsGross", label:"Project Total Costs Gross"},
	{id:"campBudgetTotalNet", label:"Project Total Net"},
	{id:"campBudgetTotalGrossUnbilled", label:"Project Total Gross Unbilled"},
	{id:"campBudgetTotalGross", label:"Project Total Gross"},
	{id:"campBudgetTotalGrossAfterWriteOff", label:"Project Total Gross After Write Off"},
	{id:"campBudgetHoursBilledRemaining", label:"Project Hours Billed Remaining"},
	{id:"campBudgetHoursRemaining", label:"Project Hours Remaining"},
	{id:"campBudgetHoursRemainingP", label:"Project Hours Remaining %"},
	{id:"campBudgetLaborNetRemaining", label:"Project Labor Net Remaining"},
	{id:"campBudgetLaborGrossRemaining", label:"Project Labor Gross Remaining"},
	{id:"campBudgetLaborGrossRemainingP", label:"Project Labor Gross Remaining %"},
	{id:"campBudgetCostsNetRemaining", label:"Project Costs Net Remaining"},
	{id:"campBudgetCostsGrossRemaining", label:"Project Costs Gross Remaining"},
	{id:"campBudgetCostsGrossRemainingP", label:"Project Costs Gross Remaining %"},
	{id:"campBudgetToBillRemaining", label:"Project To Bill Remaining"},
	{id:"campBudgetGrossRemaining", label:"Project Gross Remaining"},
    {id:"campBudgetGrossRemainingP", label:"Project Gross Remaining %"},
	{id:"campBudgetBilledDifference", label:"Project Billed Difference"},
	{id:"campBudgetRemainingAllocatedHours", label:"Project Allocated Hours Remaining"},
	{id:"campBudgetCampaignBudgetRemaining", label:"Campaign Budget Remaining"},
	{id:"campBudgetGrossRemainingCP", label:"Campaign Gross Remaining %"},
	{id:"campBudgetCampaignBudgetActualRemaining", label:"Campaign Budget Actual Remaining"},
	{id:"campBudgetLaborRemaining", label:"Campaign Budget Labor Remaining"},
	{id:"campBudgetExpenseRemaining", label:"Campaign Budget Expense Remaining"},
	{id:"campBudgetCampaignBudgetActualHoursRemaining", label:"Campaign Budget Actual Hours Remaining"},
	{id:"campBudgetCampaignBudgetHoursRemaining", label:"Campaign Budget Hours Remaining"},
	{id:"campBudgetHoursRemainingCP", label:"Campaign Hours Remaining %"},	
	{id:"campBudgetLaborAfterWriteOff", label:"Project Labor Gross After WriteOff"},
	{id:"campBudgetLaborGrossAfterWriteOffRemaining", label:"Project Labor Gross After WriteOff Remaining"},
	{id:"campBudgetCostsGrossAfterWriteOffRemaining", label:"Project Costs Gross After WriteOff Remaining"},
	{id:"campBudgetGetLaborRateFrom", label:"Get Labor Rate From"},
	{id:"campBudgetProjectHoursAfterWriteoff ", label:"Project Hours After Writeoff"},
	{id:"campBudgetProjectHoursWriteoff ", label:"Project Hours Writeoff"},
	{id:"campBudgetProjectStatus ", label:"Project Status"},
	{id:"campBudgetCampaignBudgetUnbilledProjectRemaining", label:"Remaining Camp Budget Unbilled (Project)"}
 ]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Traffic Resource Manager
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''trafficRM'', ''Resource Manager Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''MaxHours'', 1, ''Max Daily Hours'', ''8'', NULL, ''number'', NULL, null, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''WarningThreshold'', 2, ''Warning Threshold'', ''5'', NULL, ''number:n0'', NULL, null, ''This is the number of hours left that will trigger a yellow status bar'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''CriticalThreshold'', 3, ''Critical Threshold'', ''0'', NULL, ''number:n0'', NULL, null, ''This is the number of hours left that will trigger a red status bar'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''ShorthandUserTiles'', 4, ''Shorthand User Tiles'', ''0'', NULL, ''checkbox'', NULL, null, ''This is a condensed view which only shows the initials so more people fit on a screen'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''UseTaskCountNotHours'', 5, ''Use Task Count Instead of Hours'', ''0'', NULL, ''checkbox'', NULL, null, ''This will show user totals based on task count instead of hours'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''PredCompOnly'', 6, ''Completed Predecessors Only'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''openToDoOnly'', 6, ''Open To Do Items Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''openDeliverablesOnly'', 6, ''Open Deliverables Only'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''ShowUnassignedTasks'', 7, ''Show Unassigned Tasks'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will show tasks that are not assigned to anyone or any service.'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''ShowAssignmentZeroAllocated'', 8, ''Show Assignments With Zero Allocated'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will show task assignments regardless of how many hours are assigned. Use this option if you do not allocate hours to people.'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''GroupBy'', 9, ''Group Unassigned Tasks By'', ''ProjectFullName'', ''Project'', ''lookup'', ''Project:ProjectFullName|Campaign:CampaignName|Client:ClientName|Task Name:TaskName|Summary Task:SummaryTaskName|Service:ServiceName'', NULL, NULL)
--INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
--Values (''trafficRM'', ''HideEnterTime'', 10, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''DisableDragDrop'', 10, ''Disable Drag and Drop'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficRM'', ''AutoExpandTaskGrid'', 11, ''Auto Expand Tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
/*************************************************************************************************************************
Traffic Calendar
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''trafficCalendar'', ''Traffic Calendar Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''H1'', 0, ''Grid Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''trafficCalendar'', ''grdTrafficCalendarCols'', 1, ''Columns'', ''colPlanStart,colPlanComplete,colPercentComplete,colTaskID,colConstraint,colBudgetHours'', NULL, ''grid'', 
''[	{id:"colPlanStart", label:"Plan Start"},
	{id:"colPlanComplete", label:"Plan Complete"},
	{id:"colTaskStatus", label:"Status"},
	{id:"colPercentComplete", label:"%"},
	{id:"colTaskID", label:"ID"},
	{id:"colConstraint", label:"Constraint"},
	{id:"colBudgetHours", label:"Budget Hours"},
	{id:"colActualHours", label:"Actual Hours"},
	{id:"colAllocatedHours", label:"Allocated Hours"},
	{id:"colAssignedNames", label:"Assigned"},
	{id:"colAllToDos", label:"All To Dos"},
	{id:"colOpenToDos", label:"Open To Dos"},
	{id:"colPlanDuration", label:"Days"},
	{id:"colActualStart", label:"Actual Start"},
	{id:"colActualComplete", label:"Actual Complete"},
	{id:"colBaseStart", label:"Orig Start"},
	{id:"colBaseComplete", label:"Orig Complete"},
	{id:"colHideFromClient", label:"Hide From Client"},
	{id:"colPriority", label:"Priority"},
	{id:"colDescription", label:"Description"},
	{id:"colProject", label:"Project"},
	{id:"colCampaign", label:"Campaign"},
	{id:"colSegmentName", label:"Campaign Segment"},
	{id:"colConstraintDate", label:"Constraint Date"},
	{id:"colDueComment", label:"Due Comment"},
	{id:"colTimelineSegment", label:"Timeline Segment"},
	{id:"colEventStart", label:"Start Time"},
	{id:"colEventEnd", label:"End Time"},
	{id:"colPercCompSeparate", label:"Track Seperately"},
	{id:"colComments", label:"Status Comment"},
	{id:"colDueBy", label:"Due By Comment"},
	{id:"colSumTaskName", label:"Summary Task Name"}
 ]''
 , NULL, NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''ExpandCollapse'', 2, ''Collapsed / Expanded Mode'', ''1'', ''Partial'', ''lookup'', ''Collapsed:0|Partial:1|Expanded:2'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''H2'', 3, ''Calendar Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''UseTimelineColors'', 4, ''Use Timeline Section Colors on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''IncludeProjects'', 5, ''Include Projects on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''IncludeSummaryTasks'', 6, ''Include Summary Tasks on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''IncludeDetailTasks'', 7, ''Include Detail Tasks on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''UseEndDates'', 8, ''Show End Dates Only on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''ShowProjectNames'', 9, ''Show Project Names on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''trafficCalendar'', ''ShowProjectNumbers'', 10, ''Show Project Numbers on Calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

 /*************************************************************************************************************************
Staff Schedule Details
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''staffScheduleDetail'', ''Staff Schedule Details'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''staffScheduleDetail'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''staffScheduleDetail'', ''grdStaffScheduleDetailBucketCols'', 3, ''Columns'', ''stfSchdDtlSTPlanStart,stfSchdDtlSTPlanComplete,stfSchdDtlSTPlanDuration,stfSchdDtlSTHours,stfSchdDtlSTActualHours,stfSchdDtlSTRemaining,stfSchdDtlSTBucketHours,stfSchdDtlSTPercomp'', NULL, ''grid'', 
''[	{id:"stfSchdDtlSTPlanStart", label:"Plan Start"},
	{id:"stfSchdDtlSTPlanComplete", label:"Plan Complete"},
	{id:"stfSchdDtlSTPlanDuration", label:"Days"},
	{id:"stfSchdDtlSTHours", label:"Hours"},
	{id:"stfSchdDtlSTActualHours", label:"Actual"},
	{id:"stfSchdDtlSTRemaining", label:"Remaining"},
	{id:"stfSchdDtlSTBucketHours", label:"Hours Per Period"},
	{id:"stfSchdDtlSTPercomp", label:"%"},
	{id:"stfSchdDtlSTSummaryTask", label:"Summary Task"},
	{id:"stfSchdDtlSTProjectFN", label:"Project"},
	{id:"stfSchdDtlSTUserService", label:"Service"},
	{id:"stfSchdDtlSTProjectStatus", label:"Project Status"},
	{id:"stfSchdDtlSTComments", label:"Comments"}
 ]''
 , NULL, NULL, NULL, NULL)


 
 /*************************************************************************************************************************
Staff Schedule Day Details
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''staffScheduleDayDetail'', ''Staff Schedule Day Details'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''staffScheduleDayDetail'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''staffScheduleDayDetail'', ''grdStaffScheduleDayDetailBucketCols'', 3, ''Columns'', ''stfSchdDtlSTPlanStart,stfSchdDtlSTPlanComplete,stfSchdDtlSTPlanDuration,stfSchdDtlSTHours,stfSchdDtlSTActualHours,stfSchdDtlSTBucketHours,stfSchdDtlSTRemaining,stfSchdDtlSTPercomp'', NULL, ''grid'', 
''[	{id:"stfSchdDtlSTSummaryTask", label:"Summary Task"},
	{id:"stfSchdDtlSTUserService", label:"Service"},
	{id:"stfSchdDtlSTProjectStatus", label:"Project Status"},
	{id:"stfSchdDtlSTPlanStart", label:"Plan Start"},
	{id:"stfSchdDtlSTPlanComplete", label:"Plan Complete"},
	{id:"stfSchdDtlSTPlanDuration", label:"Days"},
	{id:"stfSchdDtlSTHours", label:"Hours"},
	{id:"stfSchdDtlSTActualHours", label:"Actual"},
	{id:"stfSchdDtlSTRemaining", label:"Remaining"},
	{id:"stfSchdDtlSTBucketHours", label:"Hours Per Day"},
	{id:"stfSchdDtlSTPercomp", label:"%"},	
	{id:"stfSchdDtlSTComments", label:"Comments"},
	{id:"stfSchdDtlSTTrafficComments", label:"Traffic Comments"},
	{id:"stfSchdDtlSTDateTaskAssigned", label:"Date Task Assigned"},
	{id:"stfSchdDtlSTTaskDescription", label:"Task Description"},
	{id:"stfSchdDtlSTDueBy", label:"Due By Comment"},
	{id:"stfSchdDtlSTPredComplete", label:"Predecessors Complete"},
	{id:"stfSchdDtlSTConstraintName", label:"Constraint"},
	{id:"stfSchdDtlSTConstraintDate", label:"Constraint Date"},
	{id:"stfSchdDtlSTProjectColor", label:"Project Color"}
 ]''
 , NULL, NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''staffScheduleDayDetail'', ''HideZeroHourTask'', 4, ''Hide Zero Hour Tasks'', '''', NULL, ''checkbox'', NULL, NULL, ''hide zero tasks within date range'')


 
 
 /*************************************************************************************************************************
Staff Schedule Week Details
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''staffScheduleWeekDetail'', ''Staff Schedule Week Details'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''staffScheduleWeekDetail'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''staffScheduleWeekDetail'', ''grdStaffScheduleDetailBucketCols'', 3, ''Columns'', ''stfSchdDtlSTProjectFullName,userServiceName,planStart,planComplete,hours,perccomp'', NULL, ''grid'', 
''[	{id:"stfSchdDtlSTProjectFullName", label:"Project"},
	{id:"stfSchdWeelDTLSummaryTask", label:"Summary Task"},
	{id:"userServiceName", label:"Service"},
	{id:"stfSchdWeekDTLProjectStatus", label:"Project Status"},
	{id:"planStart", label:"Plan Start"},
	{id:"planComplete", label:"Plan Complete"},
	{id:"stfSchdWeekDTLPlanDuration", label:"Days"},
	{id:"hours", label:"Hours"},
	{id:"stfSchdWeekDtlActualHours", label:"Actual"},
	{id:"stfSchdWeekDTLRemaining", label:"Remaining"},
	{id:"perccomp", label:"%"},	
	{id:"stfSchdWeekDTLComments", label:"Comments"},	
	{id:"stfSchdWeekDTLDateTaskAssigned", label:"Date Task Assigned"},
	{id:"stfSchdWeekDTLTaskDescription", label:"Task Description"},
	{id:"stfSchdWeekDTLTrafficComments", label:" Traffic Comments"},
	{id:"stfSchdWeekDTLDueBy", label:"Due By Comment"},
	{id:"detailPredComplete", label:"Predecessors Complete"},
	{id:"stfSchdWeekDTLConstraintName", label:"Constraint"},
	{id:"stfSchdWeekDTLConstraintDate", label:"Constraint Date"},
	{id:"stfSchdWeekDTLProjectColor", label:"Project Color"}
 ]''
 , NULL, NULL, NULL, NULL)
  INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''staffScheduleWeekDetail'', ''HideZeroHourTask'', 4, ''Hide Zero Hour Tasks'', '''', NULL, ''checkbox'', NULL, NULL, ''hide zero tasks within date range'')


 
 
/*************************************************************************************************************************
GL Transactions Detail grids
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''glTransactionsDetail'', ''Posting Detail Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glTransactionsDetail'', ''H1'', 0, ''Accrual Detail Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

if @GLCompaniesWithForeignCurrencies = 0

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''glTransactionsDetail'', ''grdPostingDetailAccrualCols'', 1, ''Columns'', ''accrualAccountName,accrualDebit,accrualCredit,accrualProject,accrualReconciliation'', NULL, ''grid'', 

''[
{id:"accrualAccountName", label:"Account"},
{id:"accrualDebit", label:"Debit"},
{id:"accrualCredit", label:"Credit"},
{id:"accrualCurrency", label:"Currency"},
{id:"accrualExchangeRate", label:"Exch Rate"},
{id:"accrualHDebit", label:"Debit HC"},
{id:"accrualHCredit", label:"Credit HC"},
{id:"accrualGLCompany", label:"GL Company"},
{id:"accrualClass", label:"Class"},
{id:"accrualProject", label:"Project"},
{id:"accrualOffice", label:"Office"},
{id:"accrualDepartment", label:"Department"},
{id:"accrualReconciliation", label:"Reconciliation"}
]''
	 , NULL, NULL, null, NULL)

else -- add the fields specific to GL companies 

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''glTransactionsDetail'', ''grdPostingDetailAccrualCols'', 1, ''Columns'', ''accrualAccountName,accrualDebit,accrualCredit,accrualProject,accrualReconciliation'', NULL, ''grid'', 

''[
{id:"accrualAccountName", label:"Account"},
{id:"accrualDebit", label:"Debit"},
{id:"accrualCredit", label:"Credit"},
{id:"accrualCurrency", label:"Currency"},
{id:"accrualExchangeRate", label:"Exch Rate"},
{id:"accrualHDebit", label:"Debit HC"},
{id:"accrualHCredit", label:"Credit HC"},
{id:"accrualGLCompany", label:"GL Company"},
{id:"accrualGLCCurrency", label:"Company Currency"},
{id:"accrualGLCExchangeRate", label:"Company Rate"},
{id:"accrualGLCDebit", label:"Company Debit"},
{id:"accrualGLCCredit", label:"Company Credit"},
{id:"accrualClass", label:"Class"},
{id:"accrualProject", label:"Project"},
{id:"accrualOffice", label:"Office"},
{id:"accrualDepartment", label:"Department"},
{id:"accrualReconciliation", label:"Reconciliation"}
]''
	 , NULL, NULL, null, NULL)



INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glTransactionsDetail'', ''H2'', 2, ''Cash Detail Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

if @GLCompaniesWithForeignCurrencies = 0

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''glTransactionsDetail'', ''grdPostingDetailCashCols'', 3, ''Columns'', ''cashAccountName,cashDebit,cashCredit,cashProject,cashAppliedRef'', NULL, ''grid'', 

''[
{id:"cashAccountName", label:"Account"},
{id:"cashDebit", label:"Debit"},
{id:"cashCredit", label:"Credit"},
{id:"cashCurrency", label:"Currency"},
{id:"cashExchangeRate", label:"Exch Rate"},
{id:"cashHDebit", label:"Debit HC"},
{id:"cashHCredit", label:"Credit HC"},
{id:"cashGLCompany", label:"GL Company"},
{id:"cashClass", label:"Class"},
{id:"cashProject", label:"Project"},
{id:"cashOffice", label:"Office"},
{id:"cashDepartment", label:"Department"},
{id:"cashAppliedRef", label:"Applied Ref"}
]''
	 , NULL, NULL, null, NULL)

else -- add the fields specific to GL companies

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''glTransactionsDetail'', ''grdPostingDetailCashCols'', 3, ''Columns'', ''cashAccountName,cashDebit,cashCredit,cashProject,cashAppliedRef'', NULL, ''grid'', 

''[
{id:"cashAccountName", label:"Account"},
{id:"cashDebit", label:"Debit"},
{id:"cashCredit", label:"Credit"},
{id:"cashCurrency", label:"Currency"},
{id:"cashExchangeRate", label:"Exch Rate"},
{id:"cashHDebit", label:"Debit HC"},
{id:"cashHCredit", label:"Credit HC"},
{id:"cashGLCompany", label:"GL Company"},
{id:"cashGLCCurrency", label:"Company Currency"},
{id:"cashGLCExchangeRate", label:"Company Rate"},
{id:"cashGLCDebit", label:"Company Debit"},
{id:"cashGLCCredit", label:"Company Credit"},
{id:"cashClass", label:"Class"},
{id:"cashProject", label:"Project"},
{id:"cashOffice", label:"Office"},
{id:"cashDepartment", label:"Department"},
{id:"cashAppliedRef", label:"Applied Ref"}
]''
	 , NULL, NULL, null, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''globalSearch'', ''Search Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''H1'', 0, ''Application Sections'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ActiveProjects'', 1, ''Active Projects'', ''1'', NULL, ''checkbox'', NULL, NULL, ''Search contains Project Number, Project Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''InactiveProjects'', 2, ''Inactive Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Project Number, Project Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ActivePlanningProjects'', 3, ''Active Planning Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Project Number, Project Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''InactivePlanningProjects'', 4, ''Inactive Planning Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Project Number, Project Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ActiveCampaigns'', 5, ''Active Campaigns'', ''1'', NULL, ''checkbox'', NULL, NULL, ''Search contains Campaign ID, Campaign Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''InactiveCampaigns'', 6, ''Inactive Campaigns'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Campaign ID, Campaign Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Meetings'', 7, ''Meetings'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Subject'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Activities'', 8, ''Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains the conversation subject only'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ActivityNotes'', 9, ''Conversation Notes'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains the conversation notes also. This can dramatically slow down searching'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Leads'', 10, ''Leads'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains First Name, Last Name, Company Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Contacts'', 11, ''Contacts'', ''1'', NULL, ''checkbox'', NULL, NULL, ''Search contains First Name, Last Name, Company Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Companies'', 12, ''Companies'', ''1'', NULL, ''checkbox'', NULL, NULL, ''Search contains Company Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Opportunities'', 13, ''Opportunities'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Subject, First name, Last Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Invoices'', 14, ''Client Invoices'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Invoice Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Receipts'', 15, ''Receipts'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Reference Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''PurchaseOrders'', 16, ''Purchase Orders'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Purchase Order Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''VendorInvoices'', 17, ''Vendor Invoices'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Invoice Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''VendorPayments'', 18, ''Vendor Payments'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Check Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''CreditCardCharges'', 19, ''Credit Card Charges'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Invoice Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Employees'', 20, ''Employees'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains First Name, Last Name, Company Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ProjectRequests'', 21, ''Project Requests'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Request ID, Subject'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''InsertionOrders'', 22, ''Insertion Orders'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Purchase Order Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''BroadcastOrders'', 23, ''Broadcast Orders'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Purchase Order Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''MediaEstimates'', 24, ''Media Estimates'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Estimate ID, Estimate Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''RequestQuotes'', 25, ''Request For Quotes'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Subject, Description, Project Number, Project name, Company Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''JournalEntries'', 26, ''Journal Entries'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Journal Number, Company Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ExpenseReports'', 27, ''Expense Reports'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Expense Report Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Stations'', 28, ''Stations'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Station ID, Station Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''Publications'', 29, ''Publications'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Publication ID, Publication Name'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''ActiveEstimates'', 30, ''Active Estimates'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Estimate Name, Estimate Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''InactiveEstimates'', 31, ''Inactive Estimates'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Estimate Name, Estimate Number'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''globalSearch'', ''MediaPlans'', 32, ''Media Plans'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Search contains Plan ID, Plan Name'')

/*************************************************************************************************************************
Credit Card Connector
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''creditCardConnector'', ''Credit Card Connector'', '''', 0)

/*
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''creditCardConnector'', ''H1'', 0, ''Display Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''creditCardConnector'', ''HideClearedTransactions'', 1, ''Hide Cleared Transactions'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''creditCardConnector'', ''HideCreditTransactions'', 2, ''Hide Payments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required) 
Values (''creditCardConnector'', ''DateOption'', 3, ''Date Range'', ''6'', ''All'', ''lookup'', ''Due on or before Today:0|Due on or before a week from Today:1|Due on or before 2 weeks from Today:2|Start on or before Today:3|Start on or before a week from Today:4|Start on or before 2 weeks from Today:5|All:6'', NULL, NULL, 0)
*/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''creditCardConnector'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''creditCardConnector'', ''grdEntriesCols'', 1, ''Columns'', ''transactionPostedDate,amount,payeeName,fitid,postingDate,transactionType,glCompanyID,expenseAccountNumber,billable,receipt,officeID,departmentName,project,splitProjects,task,item,class,vendor,voucher,splitVouchers,userName,memo,comment,processedStatus,salesTax,salesTaxAmount,salesTax2,salesTax2Amount'', NULL, ''grid'', 

''[	{id:"transactionPostedDate", label:"Date"},
	{id:"amount", label:"Amount"},
	{id:"payeeName", label:"Payee Name"},
	{id:"fitid", label:"FITID"},
	{id:"postingDate", label:"Posting Date"},
	{id:"transactionType", label:"Transaction Type"},
	{id:"glCompanyID", label:"GL Company"},
	{id:"expenseAccountNumber", label:"Expense Account Number"},
	{id:"billable", label:"Billable"},
	{id:"receipt", label:"Receipt"},
	{id:"overhead", label:"Overhead"},
	{id:"officeID", label:"Office"},
	{id:"departmentName", label:"Department Name"},
	{id:"project", label:"Project"},
	{id:"splitProjects", label:"Split Projects"},
	{id:"task", label:"Task"},
	{id:"item", label:"Item"},
	{id:"class", label:"Class"},
	{id:"vendor", label:"Vendor"},
	{id:"voucher", label:"Invoice Number"},
	{id:"splitVouchers", label:"Split Invoices"},
	{id:"splitOrders", label:"Orders"},
	{id:"userName", label:"Charged By"},
	{id:"memo", label:"Memo"},
	{id:"comment", label:"Comment"},
	{id:"processedStatus", label:"Status"},
	{id:"salesTax", label:"Sales Tax"},
	{id:"salesTaxAmount", label:"Sales Tax Amount"},
	{id:"salesTax2", label:"Sales Tax2"},
	{id:"attachmentCount", label:"Attachment Count"},
	{id:"salesTax2Amount", label:"Sales Tax2 Amount"},
    {id:"markUp", label:"Markup"},
	{id:"chargeRef", label:"Charge Reference"}
 ]''
	 , NULL, NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''creditCardConnector'', ''NumberOfDigits'', 2, ''Number of characters to check for duplicate entries'', 20, NULL, ''number:n0'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''creditCardConnector'', ''ShowExpenseReportItems'', 3, ''Show Expense Report Items'', 1, NULL, ''checkbox'', NULL, NULL, NULL)
/*************************************************************************************************************************
Credit Card Connector - UnMatched Charges
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''unMatchedCharges'', ''Unmatched Charges'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''unMatchedCharges'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''unMatchedCharges'', ''grdUnMatchedChargesCols'', 1, ''Columns'', ''invoiceDateMatchedCharges,invoiceNumberMatchedCharges,voucherTotalMatchedCharges,projectFullNameMatchedCharges,vendorFullNameMatchedCharges,purchasedFromMatchedCharges,description'', NULL, ''grid'', 
''[  {id:"invoiceDateMatchedCharges", label:"Date"},
    {id:"invoiceNumberMatchedCharges", label:"Invoice Number"},
	{id:"voucherTotalMatchedCharges", label:"Total"},
	{id:"projectFullNameMatchedCharges", label:"Project"},
	{id:"vendorFullNameMatchedCharges", label:"Vendor"},
	{id:"purchasedFromMatchedCharges", label:"Purchased From"},
	{id:"description", label:"Description"}
 ]''
	 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Credit Card Connector - Split Projects Panel
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''editProjects'', ''Split Projects'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''editProjects'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''editProjects'', ''grdSplitProjectsCols'', 1, ''Columns'', ''projectSplitProjects,taskSplitProjects,glCompanyIDSplitProjects,classSplitProjects,itemSplitProjects,descriptionSplitProjects,markupSplitProjects,expenseAccountSplitProjects,amountSplitProjects'', NULL, ''grid'', 
''[  {id:"projectSplitProjects", label:"Project"},
    {id:"taskSplitProjects", label:"Task"},
	{id:"glCompanyIDSplitProjects", label:"GL Company"},
	{id:"classSplitProjects", label:"Class"},	
	{id:"itemSplitProjects", label:" Item Name"},
	{id:"descriptionSplitProjects", label:"Description"},
	{id:"markupSplitProjects", label:"Markup"},
	{id:"expenseAccountSplitProjects", label:"Expense Account"},
	{id:"amountSplitProjects", label:"Amount"}
	
 ]''
	 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Notifications 
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''myNotifications'', ''Notifications Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''myNotificationsSettings'', 0, ''Notification Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiTimeSheets'', 1, ''Time Sheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiTimeUnsubmitted'', 2, ''Unsubmitted Time Sheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiExpenseReports'', 3, ''Expense Reports'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiPurchaseOrders'', 4, ''Purchase Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiInsertionOrders'', 5, ''Insertion Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiBroadcastOrders'', 6, ''Broadcast Orders'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiVendorInvoices'', 7, ''Vendor Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiCreditCC'', 8, ''Credit Card Charges'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiCreditCCC'', 9, ''Credit Card Connector'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiClientInvoices'', 10, ''Client Invoices'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiEstimates'', 11, ''Estimates'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiProjectRequests'', 12, ''Project Requests'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiBillingToReview'', 13, ''Billing Worksheets To Review'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiBillingToApprove'', 14, ''Billing Worksheets To Approve'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiMyMeetings'', 15, ''My Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiOthersMeetings'', 16, ''Others Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiDeliverables'', 17, ''Deliverables'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiShowRejected'', 18, ''Show Rejected Items'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiBackupApprovals'', 19, ''Backup Approvals'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiChanges'', 20, ''Change Request'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiTrackingForms'', 21, ''Tracking Forms'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiSystemMessages'', 22, ''Show Unread System Messages'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myNotifications'', ''NotiForecasts'', 23, ''Revenue Forecasts'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************
Approvals
**************************************************************************************************************************/
-- Timesheet Approvals
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''timesheetApprovals'', ''Time Sheet Approvals'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timesheetApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''timesheetApprovals'', ''grdTimesheetApprovalsCols'', 1, ''Columns'', ''reference,startDate,endDate,totalHours,totalPauseHours,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"Name"},
	{id:"startDate", label:"Start Date"},
	{id:"endDate", label:"End Date"},
	{id:"totalHours", label:"Hours"},
	{id:"totalPauseHours", label:"Hours Paused"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"totalBillableHours", label:"Billable Hours"},
	{id:"totalNonBillableHours", label:"Non Billable Hours"}
 ]''
 , NULL, NULL, NULL, NULL)

-- Expense Report Approvals
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''expensesApprovals'', ''Expense Report Approvals'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''expensesApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''expensesApprovals'', ''grdExpenseApprovalsCols'', 1, ''Columns'', ''userName,notifyEmail,reference,startDate,endDate,totalCost,approvalComments'', NULL, ''grid'', 
''[	{id:"userName", label:"Name"},
    {id:"notifyEmail", label:"Email"},
    {id:"reference", label:"Number"},
	{id:"startDate", label:"Start Date"},
	{id:"endDate", label:"End Date"},
	{id:"totalCost", label:"Total Cost"},
	{id:"approvalComments", label:"Your Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

-- Billing Worksheet Approvals 
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingWorksheetsApprovals'', ''Billing Worksheet Approvals'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingWorksheetsApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''billingWorksheetsApprovals'', ''grdBillingWorksheetsCols'', 1, ''Columns'', ''reference,project,methodName,toBill,budget,amountBilled,approvalComments,dueDate'', NULL, ''grid'', 
''[	{id:"reference", label:"ID"},
    {id:"project", label:"Project"},
    {id:"methodName", label:"Type"},
	{id:"toBill", label:"to Bill"},
	{id:"budget", label:"Budget"},
	{id:"amountBilled", label:"Amount Billed"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"clientID", label:"Client ID"},
	{id:"clientName", label:"Client Name"},
	{id:"campaignFullNameName", label:"Campaign Full Name"},
	{id:"productName", label:"Project Product Name"},
	{id:"divisionName", label:"Project Division Name"},
	{id:"projectBillingStatus", label:"Project Billing Status"},
	{id:"projectStatus", label:"Project Status"},
	{id:"worksheetComments", label:"Worksheet Comment"},
	{id:"dueDate", label:"Due Date"}
 ]''
 , NULL, NULL, NULL, NULL)
 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingWorksheetsApprovals'', ''groupByClient'', 2, ''Group By Client'', 0 , NULL, ''checkbox'', NULL, NULL, NULL)



-- Voucher Approvals
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''voucherApprovals'', ''Vendor Invoice Approvals'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''voucherApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''voucherApprovals'', ''grdVoucherApprovalsCols'', 1, ''Columns'', ''reference,invoiceDate,vendorName,voucherTotal,description,approvalComments,projectFullName'', NULL, ''grid'', 
''[	{id:"reference", label:"Invoice Number"},
	{id:"invoiceDate", label:"Invoice Date"},
	{id:"vendorName", label:"Purchased From"},
	{id:"voucherTotal", label:"Voucher Total"},
	{id:"salesTaxAmount", label:"Sales Tax Total"},
	{id:"description", label:"Description"},
	{id:"createdBy", label:"Created By"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectFullName", label:"Project Full Name"},
	{id:"approverName", label:"Approver Name"}
 ]''
 , NULL, NULL, NULL, NULL)

  -- Voucher CC Approvals - aka Credit Card
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''voucherCCApprovals'', ''Credit Card Approvals'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''voucherCCApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''voucherCCApprovals'', ''grdChargesCols'', 1, ''Columns'', ''reference,chargeDate,vendor,purchasedBy,purchasedFrom,voucherTotal,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"Reference"},
	{id:"chargeDate", label:"Charge Date"},
	{id:"vendor", label:"Vendor"},
	{id:"purchasedBy", label:"Purchased By"},
	{id:"purchasedFrom", label:"Purchased From"},
	{id:"voucherTotal", label:"Net Amount"},
	{id:"voucherID", label:"VoucherID"},
	{id:"createdBy", label:"Created By"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"voucherDescription", label:"Description"},
	{id:"creditCardNumber", label:"Credit Card Number"},
	{id:"postingDate", label:"Posting Date"}	
 ]''
 , NULL, NULL, NULL, NULL)

 -- Journal Entry Approvals
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''jeApprovals'', ''Journal Entry Approvals'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''jeApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''jeApprovals'', ''grdJEApprovalsCols'', 1, ''Columns'', ''reference,postingDate,approvalComments,rejectionComments,approverName'', NULL, ''grid'', 
''[	{id:"reference", label:"Journal Entry Number"},
	{id:"postingDate", label:"Posting Date"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"rejectionComments", label:"Reject Number"},
	{id:"approverName", label:"Approver"}
 ]''
 , NULL, NULL, NULL, NULL)

-- Calendar
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''calendar'', ''Calendar Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''SendNotification'', 1, ''Send Notifications'', ''0'', ''Always'', ''lookup'', ''Always:0|Ask:1|Never:2'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''GroupOther'', 2, ''Group other calendars'', '''', ''No Grouping'', ''lookup'', ''No Grouping:|Department:DepartmentName|Office:OfficeName'', NULL, NULL) 

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''ShowLegend'', 3, ''Show legend with calendar'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''WorkWeek'', 4, ''Display work week in week view'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''Show12Hour'', 5, ''Show 12 hour day'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''PartialDaySolidColor'', 6, ''Show non-All Day meetings as solid color'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calendar'', ''ReminderTime'', 7, ''Default reminder time'', ''30'', NULL, ''lookup'', 
		''No Reminder:0'' +
        ''|5 Minutes Before:5'' +
        ''|10 Minutes Before:10'' +
        ''|15 Minutes Before:15'' +
        ''|30 Minutes Before:30'' +
        ''|1 Hour Before:60'' +
        ''|2 Hours Before:120'' +
        ''|3 Hours Before:180'' +
        ''|4 Hours Before:240'' +
        ''|5 Hours Before:300'' +
        ''|6 Hours Before:360'' +
        ''|7 Hours Before:420'' +
        ''|8 Hours Before:480'' +
        ''|9 Hours Before:540'' +
        ''|10 Hours Before:600'' +
        ''|11 Hours Before:660'' +
        ''|0.5 Days Before:720'' +
        ''|18 Hours Before:1080'' +
        ''|1 Day Before:1440'' +
        ''|2 Days Before:2880'' +
        ''|3 Days Before:4320'' +
        ''|4 Days Before:5760'' +
        ''|5 Days Before:7200'' +
        ''|6 Days Before:8640'' +
        ''|1 Week Before:10080'' +
        ''|2 Weeks Before:20160|'', NULL, NULL) 

 -- deliverable Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''deliverableApprovals'', ''Deliverable Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''deliverableApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''deliverableApprovals'', ''grdDeliverablesCols'', 1, ''Columns'', ''project,deliverableName,roundName,dueDate'', NULL, ''grid'', 
''[	{id:"project", label:"Project"},
	{id:"deliverableName", label:"Name"},
	{id:"roundName", label:"Round"},
	{id:"dueDate", label:"Due Date"},
	{id:"instructions", label:"Instructions"},
	{id:"dateSent", label:"Date/Time Sent"},
	{id:"currentStep", label:"Current Step"},
	{id: "taskFullName", label:"Task"} 
 ]''
 , NULL, NULL, NULL, NULL)

  -- Broadcast Order Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''broadcastOrderApprovals'', ''Broadcast Order Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''broadcastOrderApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''broadcastOrderApprovals'', ''grdBCOrdersCols'', 1, ''Columns'', ''reference,poDate,vendorName,netCost,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"BO Number"},
	{id:"poDate", label:"BO Date"},
	{id:"vendorName", label:"Vendor"},
	{id:"netCost", label:"Net Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"clientName", label:"Client Name"},
	{id:"createdBy", label:"Created By"},
	{id:"approvalComments", label:"Your Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

 -- estimate Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateApprovals'', ''Estimate Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''estimateApprovals'', ''grdEstimatesCols'', 1, ''Columns'', ''reference,project,methodName,estimateTotal,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"ID"},
	{id:"project", label:"Project"},
	{id:"methodName", label:"Type"},
	{id:"estimateTotal", label:"Total"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"clientName", label:"Client Name"}
 ]''
 , NULL, NULL, NULL, NULL)

 -- Insertion Order Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''insertionOrderApprovals'', ''Insertion Order Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''insertionOrderApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''insertionOrderApprovals'', ''grdIOOrdersCols'', 1, ''Columns'', ''reference,poDate,vendorName,netCost,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"IO Number"},
	{id:"poDate", label:"IO Date"},
	{id:"vendorName", label:"Vendor"},
	{id:"netCost", label:"Net Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"clientName", label:"Client Name"},
	{id:"createdBy", label:"Created By"},
	{id:"approvalComments", label:"Your Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

 
 -- Invoice Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''invoiceApprovals'', ''Invoice Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''invoiceApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''invoiceApprovals'', ''grdInvoicesCols'', 1, ''Columns'', ''reference,invoiceDate,client,invoiceTotal,projectNumber,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"Invoice Number"},
	{id:"invoiceDate", label:"Invoice Date"},
	{id:"client", label:"Client"},
	{id:"invoiceTotal", label:"Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"createdBy", label:"Created By"},
	{id:"approvalComments", label:"Your Comments"}
 ]''

 , NULL, NULL, NULL, NULL)

--Project Request Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectRequestApprovals'', ''Project Request Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectRequestApprovals'', ''grdProjectRequestCols'', 1, ''Columns'', ''reference,companyName,subject,requestedBy,dateActivated,dueDate,projectDueDate,assignedUser'', NULL, ''grid'', 
''[	{id:"reference", label:"ID"},
	{id:"companyName", label:"Client"},
	{id:"subject", label:"Project Name"},
	{id:"requestedBy", label:"Requested By"},
	{id:"dateActivated", label:"Date Activated"},
	{id:"dueDate", label:"Due"},
	{id:"projectDueDate", label:"Project Due Date"},
	{id:"assignedUser", label:"Assigned User"},
	{id:"lastComment", label:"Last Comment"},
	{id:"projectDescription", label:"Project Description"},
	{id:"campaignID", label:"Campaign ID"},
	{id:"campaignName", label:"Campaign Name"}
 ]''
 , NULL, NULL, ''RequestDef'', NULL)

-- Purchase Order Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''purchaseOrderApprovals'', ''Purchase Order Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchaseOrderApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''purchaseOrderApprovals'', ''grdPOOrdersCols'', 1, ''Columns'', ''reference,poDate,vendorName,netCost,approvalComments'', NULL, ''grid'', 
''[	{id:"reference", label:"PO Number"},
	{id:"poDate", label:"PO Date"},
	{id:"vendorName", label:"Vendor"},
	{id:"netCost", label:"Net Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"projectFullName", label:"Project Full Name"},
	{id:"clientName", label:"Client Name"},
	{id:"createdBy", label:"Created By"},
	{id:"approvalComments", label:"Your Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

-- My Meeting Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''myMeetingApprovals'', ''My Meeting Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myMeetingApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1)
Values (''myMeetingApprovals'', ''grdMeetingCols'', 1, ''Columns'', ''reference,eventStart,eventEnd,attendee,location'', NULL, ''grid'', 
''[	{id:"reference", label:"Meeting"},
	{id:"eventTime", label:"Time"},
	{id:"attendee", label:"Attendee"},
	{id:"location", label:"Location"}
 ]''
 , NULL, NULL, NULL, NULL)

-- Other Meeting Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''otherMeetingApprovals'', ''Other Meeting Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''otherMeetingApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1)
Values (''otherMeetingApprovals'', ''grdMeetingCols'', 1, ''Columns'', ''reference,eventStart,eventEnd,attendee,location'', NULL, ''grid'', 
''[	{id:"reference", label:"Meeting"},
	{id:"eventTime", label:"Time"},
	{id:"attendee", label:"Attendee"},
	{id:"location", label:"Location"}
 ]''
 , NULL, NULL, NULL, NULL)

 -- Submitted Meeting Approvals
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''submittedMeetingApprovals'', ''My Meeting Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''submittedMeetingApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1)
Values (''submittedMeetingApprovals'', ''grdMeetingCols'', 1, ''Columns'', ''reference,eventStart,eventEnd,createdBy,location'', NULL, ''grid'', 
''[	{id:"reference", label:"Meeting"},
	{id:"eventTime", label:"Time"},
	{id:"createdBy", label:"Created By"},
	{id:"location", label:"Location"}
 ]''
 , NULL, NULL, NULL, NULL)

 --Change Request Approval
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''changeRequestApprovals'', ''Change Request Approval'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''changeRequestApprovals'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''changeRequestApprovals'', ''grdChangeRequestCols'', 1, ''Columns'', ''changeFullName,companyName,subject,requestedBy,dateActivated,dueDate,assignedUser,approvalComments,'', NULL, ''grid'', 
''[	{id:"changeFullName", label:"ID"},
	{id:"companyName", label:"Client"},
	{id:"projectName", label:"Project Name"},
	{id:"subject", label:"Subject"},
	{id:"requestedBy", label:"Requested By"},
	{id:"dateActivated", label:"Date Activated"},
	{id:"dueDate", label:"Due"},
	{id:"assignedUser", label:"Assigned User"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"lastComment", label:"Last Comment"},
	{id:"description", label:"Description"},
	{id:"changeType", label:"Type"},
	{id:"entityNumber", label:"Entity ID"},
	{id:"entityName", label:"Entity Name"},
	{id:"entityFullName", label:"Entity Full Name"}
	]''
	, NULL, NULL, ''ChangeDef'', NULL)

 /*************************************************************************************************************************
Rejections
**************************************************************************************************************************/
-- Timesheet Rejections
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''timesheetRejections'', ''Time Sheet Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timesheetRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''timesheetRejections'', ''grdTimesheetApprovalsCols'', 1, ''Columns'', ''reference,startDate,endDate,totalHours,totalPauseHours,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"Name"},
	{id:"startDate", label:"Start Date"},
	{id:"endDate", label:"End Date"},
	{id:"totalHours", label:"Hours"},
	{id:"totalPauseHours", label:"Hours Paused"},
	{id:"rejectionComments", label:"Reject Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

-- Expense Report Rejections
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''expensesRejections'', ''Expense Report Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''expensesRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''expensesRejections'', ''grdExpenseApprovalsCols'', 1, ''Columns'', ''userName,reference,startDate,endDate,totalCost,rejectionComments'', NULL, ''grid'', 
''[	{id:"userName", label:"Name"},
    {id:"reference", label:"Number"},
	{id:"startDate", label:"Start Date"},
	{id:"endDate", label:"End Date"},
	{id:"totalCost", label:"Total Cost"},
	{id:"rejectionComments", label:"Reject Comments"},
	{id:"creditCardNumber", label:"Credit Card Number"}
 ]''
 , NULL, NULL, NULL, NULL)


-- Voucher Rejections
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''voucherRejections'', ''Vendor Invoice Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''voucherRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''voucherRejections'', ''grdVoucherApprovalsCols'', 1, ''Columns'', ''reference,invoiceDate,vendorName,voucherTotal,description,rejectionComments,projectNumber'', NULL, ''grid'', 
''[	{id:"reference", label:"Invoice Number"},
	{id:"invoiceDate", label:"Invoice Date"},
	{id:"vendorName", label:"Purchased From"},
	{id:"voucherTotal", label:"Voucher Total"},
	{id:"salesTaxAmount", label:"Sales Tax Total"},
	{id:"description", label:"Description"},
	{id:"createdBy", label:"Created By"},
	{id:"rejectionComments", label:"Rejection Comments"},
	{id:"projectNumber", label:"Project Number"}
 ]''
 , NULL, NULL, NULL, NULL)

  -- Voucher CC Rejections - aka Credit Card
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''voucherCCRejections'', ''Credit Card Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''voucherCCRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''voucherCCRejections'', ''grdChargesCols'', 1, ''Columns'', ''reference,chargeDate,vendor,purchasedBy,purchasedFrom,voucherTotal,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"Reference"},
	{id:"chargeDate", label:"Charge Date"},
	{id:"vendor", label:"Vendor"},
	{id:"purchasedBy", label:"Purchased By"},
	{id:"purchasedFrom", label:"Purchased From"},
	{id:"voucherTotal", label:"Net Amount"},
	{id:"voucherID", label:"VoucherID"},
	{id:"createdBy", label:"Created By"},
	{id:"rejectionComments", label:"Rejection Comments"},
	{id:"voucherDescription", label:"Description"},
	{id:"creditCardNumber", label:"Credit Card Number"}
 ]''
 , NULL, NULL, NULL, NULL)

  -- Journal Entry Rejections
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''jeRejections'', ''Journal Entry Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''jeRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''jeRejections'', ''jeRejections'', 1, ''Columns'', ''reference,postingDate,approvalComments,rejectionComments,approverName'', NULL, ''grid'', 
''[	{id:"reference", label:"Journal Entry Number"},
	{id:"postingDate", label:"Posting Date"},
	{id:"approvalComments", label:"Your Comments"},
	{id:"rejectionComments", label:"Reject Number"},
	{id:"approverName", label:"Approver"}
 ]''
 , NULL, NULL, NULL, NULL)

  -- Broadcast Order Rejection
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''broadcastOrderRejections'', ''Broadcast Order Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''broadcastOrderRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''broadcastOrderRejections'', ''grdBCOrdersCols'', 1, ''Columns'', ''reference,poDate,vendorName,netCost,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"BO Number"},
	{id:"poDate", label:"BO Date"},
	{id:"vendorName", label:"Vendor"},
	{id:"netCost", label:"Net Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"clientName", label:"Client Name"},
	{id:"createdBy", label:"Created By"},
	{id:"rejectionComments", label:"Reject Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

 -- estimate Rejections
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateRejections'', ''Estimate Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''estimateRejections'', ''grdEstimatesCols'', 1, ''Columns'', ''reference,project,methodName,estimateTotal,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"ID"},
	{id:"project", label:"Project"},
	{id:"methodName", label:"Type"},
	{id:"estimateTotal", label:"Total"},
	{id:"rejectionComments", label:"Reject Comments"},
	{id:"clientName", label:"Client Name"}
 ]''
 , NULL, NULL, NULL, NULL)

 -- Insertion Order Rejection
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''insertionOrderRejections'', ''Insertion Order Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''insertionOrderRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''insertionOrderRejections'', ''grdIOOrdersCols'', 1, ''Columns'', ''reference,poDate,vendorName,netCost,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"IO Number"},
	{id:"poDate", label:"IO Date"},
	{id:"vendorName", label:"Vendor"},
	{id:"netCost", label:"Net Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"clientName", label:"Client Name"},
	{id:"createdBy", label:"Created By"},
	{id:"rejectionComments", label:"Reject Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

 
 -- Invoice Rejection
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''invoiceRejections'', ''Invoice Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''invoiceRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''invoiceRejections'', ''grdInvoicesCols'', 1, ''Columns'', ''reference,invoiceDate,client,invoiceTotal,projectNumber,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"Invoice Number"},
	{id:"invoiceDate", label:"Invoice Date"},
	{id:"client", label:"Client"},
	{id:"invoiceTotal", label:"Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"createdBy", label:"Created By"},
	{id:"rejectionComments", label:"Reject Comments"}
 ]''

 , NULL, NULL, NULL, NULL)
-- Purchase Order Rejection
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''purchaseOrderRejections'', ''Purchase Order Rejections'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchaseOrderRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''purchaseOrderRejections'', ''grdPOOrdersCols'', 1, ''Columns'', ''reference,poDate,vendorName,netCost,rejectionComments'', NULL, ''grid'', 
''[	{id:"reference", label:"PO Number"},
	{id:"poDate", label:"PO Date"},
	{id:"vendorName", label:"Vendor"},
	{id:"netCost", label:"Net Amount"},
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"clientName", label:"Client Name"},
	{id:"createdBy", label:"Created By"},
	{id:"rejectionComments", label:"Reject Comments"}
 ]''
 , NULL, NULL, NULL, NULL)

 --Project Request Rejections
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectRequestRejections'', ''Project Request Rejection'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectRequestRejections'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectRequestRejections'', ''grdProjectRequestCols'', 1, ''Columns'', ''reference,companyName,subject,projectDueDate'', NULL, ''grid'', 
''[	{id:"reference", label:"ID"},
	{id:"companyName", label:"Client"},
	{id:"subject", label:"Project Name"},
	{id:"projectDueDate", label:"Project Due Date"},
	{id:"projectDescription", label:"Project Description"},
	{id:"campaignID", label:"Campaign ID"},
	{id:"campaignName", label:"Campaign Name"}
 ]''
 , NULL, NULL, ''RequestDef'', NULL)
 /*************************************************************************************************************************
Unsubmitted
**************************************************************************************************************************/
-- Timesheets Unsubmitted
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''timesheetUnsubmitted'', ''Time Sheet Unsubmitted'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''timesheetUnsubmitted'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
--Values (''timesheetUnsubmitted'', ''grdTimesheetCols'', 1, ''Columns'', ''reference,startDate,endDate,totalHours'', NULL, ''grid'', 
Values (''timesheetUnsubmitted'', ''grdTimesheetCols'', 1, ''Columns'', ''startDate,endDate,totalHours,totalPauseHours'', NULL, ''grid'', 
''[
	{id:"startDate", label:"Start Date"},
	{id:"endDate", label:"End Date"},
	{id:"totalHours", label:"Hours"},
	{id:"totalPauseHours", label:"Hours Paused"}
 ]''
 , NULL, NULL, NULL, NULL)
/*************************************************************************************************************************
  Company Settings
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''companySettings'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''H1'', 0, ''Exclude From History'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''hideActivities'', 1, ''Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''hideOpenActivities'', 2, ''Open Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''hideClosedActivities'', 3, ''Completed Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''hideMeetings'', 4, ''Meetings'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''hideProjectItems'', 5, ''Project Items'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companySettings'', ''hideTaskItems'', 6, ''Task Items'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
  Contact Settings
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''contactSettings'', ''System Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''H1'', 0, ''Exclude From History'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''hideActivities'', 1, ''Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''hideOpenActivities'', 2, ''Open Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''hideClosedActivities'', 3, ''Completed Activities'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''hideMeetings'', 4, ''Meetings'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''hideProjectItems'', 5, ''Project Items'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''contactSettings'', ''hideTaskItems'', 6, ''Task Items'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''contactSettings'', ''hidePastCompanies'', 7, ''Past Companies'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL,''showPreviousCompany'')


/*************************************************************************************************************************
Estimate Edit Labor Drilldown
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateEdit'', ''Estimate Edit Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''H1'', 0, ''Estimate Summary'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowProfit'', 1, ''Show the Profit Breakout'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowLaborSum'', 2, ''Show the Labor Summary'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowContingency'', 3, ''Show Contingency'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''H2'', 4, ''Labor Entry Grid'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowCostRate'', 5, ''Show labor cost rate'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Only if the user has appropriate rights'') 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowServiceCode'', 6, ''Show labor service code'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowServicesZeroAmounts'', 7, ''Show services with zero amounts'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowServicesZeroRates'', 8, ''Show services with zero rates'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowExpenses'', 9, ''Show Expenses in Labor Breakout'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateEdit'', ''EstShowLine'', 10, ''Show Line number'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 


/*************************************************************************************************************************
Print Check  exec spConvertAppSeed
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''printCheck'', ''Print Check Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''printCheck'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''printCheck'', ''showACH'', 1, ''Use ACH'', ''0'', NULL, ''checkbox'', NULL, NULL, ''ACH - Automated Clearing House file for electronic fund transfers in the US'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''printCheck'', ''showBacs'', 2, ''Use BACS'', ''0'', NULL, ''checkbox'', NULL, NULL, ''BACS or Banker Automated Clearing Services, used in the United Kingdom'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''printCheck'', ''showPAIN'', 3, ''Use PAIN.001'', ''0'', NULL, ''checkbox'', NULL, NULL, ''PAIN.001 v3 - XML Payment Initiation file that describes credit transfers in the Eurozone'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''printCheck'', ''showABA'', 4, ''Use ABA'', ''0'', NULL, ''checkbox'', NULL, NULL, ''ABA - Australian Banking Authority file for electronic fund transfers in the Australia'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''printCheck'', ''showVisa'', 5, ''Use CSI vCard'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''printCheck'', ''csiTestSite'', 6, ''Use CSI Test Site'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''showVisa'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''printCheck'', ''showFastPay'', 7, ''Use FastPay'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Fast Pay'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''printCheck'', ''showCoupa'', 8, ''Use Coupa'', ''0'', NULL, ''checkbox'', NULL, NULL, ''Coupa'')


/*************************************************************************************************************************
Mass Billing
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''massBilling'', ''Mass Billing Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''massBilling'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''massBilling'', ''BillMediaSeparately'', 1, ''Bill Media Separately'', ''1'', NULL, ''checkbox'', NULL, NULL, ''If this is checked, the user is assumed to use media mass billing separately and the media orders will not be pulled by default in the T&M mass billing'') 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''massBilling'', ''ExcludeCampaignProjects'', 2, ''Exclude Campaign Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, ''If this is checked, we exclude projects linked to a campaign where the campaign is set to Bill by Campaign.'') 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''massBilling'', ''IncludeOHClients'', 3, ''Include Overhead Clients'', ''1'', NULL, ''checkbox'', NULL, NULL, ''If this is checked, we include Overhead Clients.'') 


/*************************************************************************************************************************
Client Billing
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''clientInvoiceLine'', ''Client Invoice Line Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientInvoiceLine'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''clientInvoiceLine'', ''grdInvoiceLineCols'', 1, ''Columns'', ''il_ProjectKey,il_TaskKey,il_SalesGLAccountKey,il_Quantity,il_UnitCost,il_TotalCost,il_Taxable,il_Taxable2'', NULL, ''grid'', 

''[	{id:"il_ProjectKey", label:"Project"},
	{id:"il_TaskKey", label:"Task"},
	{id:"il_SalesGLAccountKey", label:"Sales GL Account"},
	{id:"il_Quantity", label:"Quantity"},
	{id:"il_UnitCost", label:"Unit Amt"},
	{id:"il_TotalCost", label:"Total Amt"},
	{id:"il_Taxable", label:"Taxable"},
	{id:"il_Taxable2", label:"Taxable2"},
	{id:"il_SalesTax1Amount", label:"Tax 1 Amt"},
	{id:"il_SalesTax2Amount", label:"Tax 2 Amt"},
	{id:"il_SalesTaxAmount", label:"Other Tax Amt"},
	{id:"il_ClassKey", label:"Class"},
	{id:"il_OfficeKey", label:"Office"},
	{id:"il_ShortDescription", label:"Description"},
	{id:"il_ItemService", label:"Item/Service"},
	{id:"il_ItemKey", label:"Item"},
	{id:"il_ServiceKey", label:"Service"},
	{id:"il_WorkTypeKey", label:"Billing Item"},
	{id:"il_DisplayOption", label:"Display Option"},
	{id:"il_RetainerKey", label:"Retainer"},
	{id:"il_DepartmentKey", label:"Department"},
	{id:"il_AdjustmentAmount", label:"Adjustment Amount"},
	{id:"il_AdjustmentGLAccountKey", label:"Adjustment GL Account"},
 ]''
	 , NULL, NULL, null, NULL)


INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''clientInvoiceExpense'', ''Expense Line Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientInvoiceExpense'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''clientInvoiceExpense'', ''grdExpenseCols'', 1, ''Columns'', ''invExpenseSource,invExpenseProjectFullName,invExpenseItem,invExpenseAmount,invExpenseBillComments,invExpenseDescription,invExpenseSalesAccount'', NULL, ''grid'', 

''[	{id:"invExpenseSource", label:"Source"},
	{id:"invExpenseProjectFullName", label:"Project"},
	{id:"invExpenseItem", label:"Billed Item"},
	{id:"invExpenseAmount", label:"Billed Amount"},
	{id:"invExpenseBilledVariance", label:"Billed Variance"},
	{id:"invExpenseBillComments", label:"Billed Comments"},
	{id:"invExpenseDescription", label:"Description"},
	{id:"invExpenseDate", label:"Date"},
	{id:"invExpenseReason", label:"Reason"},
	{id:"invExpenseQuantity", label:"Qty"},
	{id:"invExpenseUnitCost", label:"Unit Cost"},
	{id:"invExpenseTotalCost", label:"Net"},
	{id:"invExpenseBillableCost", label:"Gross"},
	{id:"invExpenseVariance", label:"Variance"},
	{id:"invExpenseComments", label:"Comments"},
	{id:"invVendorName", label:"Vendor Name"},
	{id:"invPurchasedFrom", label:"Purchased From"},
	{id:"invExpenseSalesAccount", label:"Sales Account"}
 ]''
	 , NULL, NULL, null, NULL)


INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''clientInvoiceLabor'', ''Labor Line Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientInvoiceLabor'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''clientInvoiceLabor'', ''grdLaborCols'', 1, ''Columns'', ''laborPerson,laborProjectFullName,laborBilledService,laborBilledHours,laborBilledRate,laborBilledAmount,laborActualHours,laborActualRate,laborActualAmount,laborBilledComments,laborDate,laborTimesheetComments,laborSalesAccount'', NULL, ''grid'', 

''[	{id:"laborPerson", label:"Person"},
	{id:"laborProjectFullName", label:"Project"},
	{id:"laborBilledService", label:"Billed Service"},
	{id:"laborBilledHours", label:"Billed Hours"},
	{id:"laborBilledRate", label:"Billed Rate"},
	{id:"laborBilledAmount", label:"Billed Amount"},
	{id:"laborActualHours", label:"Actual Hours"},
	{id:"laborActualRate", label:"Actual Rate"},
	{id:"laborActualAmount", label:"Actual Amount"},
	{id:"laborBilledComments", label:"Billed Comments"},
	{id:"laborDate", label:"Date"},
	{id:"laborTimesheetComments", label:"Timesheet Comments"},
    {id:"laborSalesAccount", label:"Sales Account"}
 ]''
	 , NULL, NULL, null, NULL)

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) VALUES(''billingTransactions'', ''Billing Transaction Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
VALUES (''billingTransactions'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''billingTransactions'', ''grdTransactionDetailCols'', 1, ''Columns'', ''colTransactionDate,colDescription,colHours,colUnitCost,colNet,colGross,colItem,colPostedToWIP,colPostingDate,colTaskName,colEditedBy,colBillAction,colComments,colEditComments,colBillingComments'', NULL, ''grid'', 

''[
	{id:"colTransactionDate", label:"Date"},
	{id:"colDescription", label:"Vendor/Person"},
	{id:"colTransactionComments", label:"Transaction Comments"},
	{id:"colHours", label:"Qty"},
	{id:"colUnitCost", label:"Unit Cost"},
	{id:"colNet", label:"Net"},
	{id:"colGross", label:"Gross"},
	{id:"colItem", label:"Item"},
	{id:"colPostedToWIP", label:"Posted to WIP"},
	{id:"colPostingDate", label:"Posting Date"},
	{id:"colTaskName", label:"Task"},
	{id:"colEditedBy", label:"Edited"},
	{id:"colBillAction", label:"Action"},
	{id:"colComments", label:"Comments"},
	{id:"colEditComments", label:"Edit Comments"},
	{id:"colBillingComments", label:"Billing Comments"},
	{id:"invSalesTaxAmount", label:"Sales Tax Amount"},
	{id:"invProfit", label:"Profit"},
	{id:"invVendorName", label:"Vendor Name"},
	{id:"colBillMediaPub", label:"Pub/Station"},
	{id:"colWriteOffReasons", label:"Write Off Reasons"}
]''
	, NULL, NULL
)

/*************************************************************************************************************************
Advance Billings
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''advanceBilling'', ''Advance Billings Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''advanceBilling'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''advanceBilling'', ''grdAddAdvanceBill'', 1, ''Columns'', ''referenceNumber_u,project_u,clientName_u,checkDate_u'', NULL, ''grid'', 
''[	{id:"referenceNumber_u", label:"Invoice"},
    {id:"project_u", label:"Project"},
	{id:"clientName_u", label:"Client Name"},
	{id:"checkDate_u", label:"Invoice Date"},  
	{id:"checkAmount_u", label:"Amount"},
	{id:"unappliedAmount_u", label:"Open"},
	{id:"amount_u", label:"Applied"},
	{id:"openSalesTax_u", label:"Open Sales Tax"},
	{id:"posted_u", label:"Posted"},
	{id:"Campaign_u", label:"Campaign"}
 ]''
 , NULL, NULL, NULL, NULL)

 --#699885-AP - Apply advance bill screen
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''advanceBillDetail'', ''Advance Billings Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''advanceBillDetail'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''advanceBillDetail'', ''grdAdvanceBill'', 1, ''Columns'', ''referenceNumber,checkDate,checkAmount,unappliedAmount,amount,openSalesTax,appliedSalesTax,fromAB,effective,posted,project,campaign'', NULL, ''grid'', 
 ''[ {id:"referenceNumber", label:"Invoice #"},
	{id:"checkDate", label:"Invoice Date"},
	{id:"checkAmount", label:"Billed"},  
	{id:"unappliedAmount", label:"Remaining"},
	{id:"amount", label:"Applied"},
	{id:"openSalesTax", label:"Open Sales Tax"},
	{id:"appliedSalesTax", label:"Applied Sales Tax"},
	{id:"fromAB", label:"Applied From"},
	{id:"effective", label:"Effective"},
	{id:"posted", label:"Posted"},
	{id:"project", label:"Project"},
	{id:"campaign", label:"Campaign"}
  ]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Client Portal
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''clientPortal'', ''System Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''H1'', 1, ''Dashboard Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required)
Values (''clientPortal'', ''DateOptionClient'', 3, ''Date Range'', ''6'', ''All'', ''lookup'', ''Due on or before Today:0|Due on or before a week from Today:1|Due on or before 2 weeks from Today:2|Start on or before Today:3|Start on or before a week from Today:4|Start on or before 2 weeks from Today:5|All:6'', NULL, NULL, 1) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''sortByDueDate'', 4, ''Sort Assigned Tasks by Due Date (Default is by Project Number)'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''H2'', 8, ''Project Details'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''client_schedule'', 9, ''View the project schedule'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showSpecs'', 10, ''Show Spec Sheets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showDeliverables'', 11, ''Show Deliverables'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showFiles'', 12, ''Show Files'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showEstimates'', 13, ''Show Estimates'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showNextSteps'', 14, ''Show Next Steps'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showConv'', 15, ''Show Conversations'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''client_editNotes'', 16, ''Start new conversations'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''client_completeTasks'', 17, ''Allow clients to complete assigned tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showTeam'', 18, ''Show Project Team'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
if @LoadBeta = 1
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showToDo'', 19, ''Show Project To Dos'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField) 
Values (''clientPortal'', ''AddToDo'', 20, ''Add Project To Dos'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL, ''showToDo'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showProjectStatus'', 21, ''Show Project Status'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showProjectView'', 22, ''Show Project Views'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showDueComments'', 23, ''Show Due Comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showProjectList'', 24, ''Show Assigned Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showAssignments'', 25, ''Show Assigned Tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, Required)
Values (''clientPortal'', ''taskDatesToShow'', 26, ''Task Dates to Show'', ''1'', ''Due Dates'', ''lookup'', ''Start Dates:0|Due Dates:1|Both:2'', NULL, NULL, 1) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''sortByTaskDueDate'', 27, ''Sort Tasks by Due Date'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCompletePct'', 28, ''Show Schedule Complete Percent'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''H3'', 29, ''Budget'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showBudgetTotal'', 30, ''Show the Total Budget'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showActual'', 31, ''Show the Total Actual and Remaining'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showActualHours'', 32, ''Show Actual Hours to Date'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showBilled'', 33, ''Show Billed to Date'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''H4'', 34, ''Campaign Details'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCampaignProjAndSeg'', 35, ''Show Projects and Segments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCampaignSpecs'', 36, ''Show Spec Sheets'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCampaignDeliverables'', 37, ''Show Deliverables'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCampaignFiles'', 38, ''Show Files'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCampaignConv'', 39, ''Show Conversations'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL) 
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''client_editCampaignNotes'', 40, ''Start new conversations'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCampaignView'', 41, ''Show Campaign Views'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''H5'', 42, ''Project Request Details'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showRequestView'', 43, ''Show Project Request Views'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''H6'', 44, ''Invoice Details'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showCurrentInvoices'', 45, ''Show Current Invoices'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showClosedInvoices'', 46, ''Show Closed Invoices'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showInvoicesForAssignedProjects'', 47, ''Show Invoices for Assigned Projects'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showInvoicesForCompany'', 48, ''Show Invoices for Company'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showInvoicesForParentCompany'', 49, ''Show Invoices for Parent Company'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''clientPortal'', ''showInvoicesForChildCompany'', 50, ''Show Invoices for Child Company'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
/*************************************************************************************************************************
Client Portal Request List
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''clientRequestList'', ''Project Request List'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''clientRequestList'', ''grdListCols'', 1, ''Columns'', ''cr_RequestID,cr_Subject,cr_DueDate,cr_ReasonName'', NULL, ''grid'', 
''[	{id:"cr_RequestID", label:"Request ID"},
	{id:"cr_DateAdded", label:"Date Added"},
	{id:"cr_RequestedBy", label:"Requested By"},
	{id:"cr_NotifyEmail", label:"Email to Notify"},
	{id:"cr_Subject", label:"Subject"},
	{id:"cr_ClientProjectNumber", label:"Client Project Number"},
	{id:"cr_ProjectNumber", label:"Project Number"},
	{id:"cr_ProjectDescription", label:"Project Description"},
	{id:"cr_DueDate", label:"Due Date"},
	{id:"cr_DateCancelled", label:"Date Cancelled"},
	{id:"cr_UpdatedBy", label:"Last Updated By"},
	{id:"cr_ReasonName", label:"Rejection Reason"},
	{id:"cr_RejectionDescription", label:"Rejection Description"}
 ]''
 , NULL, NULL, ''RequestDef'', NULL)



/*************************************************************************************************************************
Generate Billing Worksheets
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''generateBillingWorksheets'', ''Generate Billing Worksheets'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''DaysToReview'', 1, ''Days to review a worksheet'', 1, NULL, ''number:n0'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''DateOption'', 2, ''Select by Invoice date or posting date'', 1, NULL, ''lookup'', ''Invoice Date:1|Posting Date:2'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''ExpenseReports'', 3, ''Expense Reports'', 0, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''PurchaseOrders'', 4, ''Purchase Orders'', 0, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''IncludeZeroAmounts'', 5, ''Include T&M Zero Amounts'', 1, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''MarkTMZeroBilled'', 6, ''Mark T&M Zero Amounts as Billed'', 0, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''IncludeZeroAmountsFF'', 7, ''Include Fixed Fee Zero Unbilled'', 1, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''OpenOrdersOnly'', 8, ''Open Orders Only'', 1, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''IncludeOverheadClients'', 9, ''Include Overhead Clients'', 1, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''InsertionOrders'', 10, ''Insertion Orders'', 0, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''BroadcastOrders'', 11, ''Broadcast Orders'', 0, NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''generateBillingWorksheets'', ''ApproverIsAM'', 12, ''Approver is'', 1, ''Account Manager'', ''lookup'', ''Account Manager:1|Project Manager:0|Billing Manager:2'', NULL, NULL)

/*************************************************************************************************************************
Receipts Add
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''receiptAddSession'', ''Receipt Add Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''receiptAddSession'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''receiptAddSession'', ''PostOnSave'', 1, ''Post All New Receipts'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''receiptAddSession'', ''IncrementDepositID'', 2, ''Auto Increment Deposit ID'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)




/*************************************************************************************************************************
Payment Add
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''paymentAddSession'', ''Payment Add Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''paymentAddSession'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''paymentAddSession'', ''PostOnSave'', 1, ''Post All New Payments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''paymentAddSession'', ''H_GRID'', 3, ''Grid Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentAddSession'', ''grdPaymentInvoicesCol'', 4, '' Invoice Columns'', ''addInvoiceInvoiceNumber,addInvoiceInvoiceDate,addInvoiceAmountOpen,addInvoiceDiscount,addInvoiceApplied,addInvoiceExclude'', NULL, ''grid'', 

''[
{id:"addInvoiceInvoiceNumber", label:"Invoice #"},
{id:"addInvoiceInvoiceDate", label:"Invoice Date"},
{id:"addInvoiceAmountOpen", label:"Open"},
{id:"addInvoiceDiscount", label:"Discount"},
{id:"addInvoiceApplied", label:"Applied"},
{id:"addInvoiceExclude", label:"Exclude From 1099"},
{id:"addInvoiceDescription", label:"Description"},
{id:"addInvoiceVoucherTotal", label:"Invoice Total"},
{id:"addInvoiceVoucherPaid", label:"Voucher Amount Paid"},
{id:"addInvoiceOpenDiscount", label:"Open Discount"}
]''
	 , NULL, NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentAddSession'', ''grdCCChargesCol'', 5, ''CC Charge Columns'', ''addCCCVoucherID,addCCCInvoiceDate,addCCCBoughtByName,addCCCBoughtFrom,addCCCAmountOpen,addCCCDiscount,addCCCApplied,cccVoucherTotal,addCCCInvoiceNumber'', NULL, ''grid'', 

''[
{id:"addCCCVoucherID", label:"Ref #"},
{id:"addCCCInvoiceDate", label:"Charge Date"},
{id:"addCCCBoughtByName", label:"Purchased By"},
{id:"addCCCBoughtFrom", label:"Purchased From"},
{id:"addCCCAmountOpen", label:"Open"},
{id:"addCCCDiscount", label:"Discount"},
{id:"addCCCApplied", label:"Amount"},
{id:"addCCCInvoiceNumber", label:"Charge Reference"},
{id:"addCCCDescription", label:"Description"},
{id:"addCCCVoucherTotal", label:"Charge Total"},
{id:"addCCCVoucherPaid", label:"Charge Amount Paid"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentAddSession'', ''grdExpensesCol'', 6, ''Expense Columns'', ''expenseGLAccount,expenseAmount,expenseSaleTax,expenseExclude'', NULL, ''grid'', 

''[
{id:"expenseGLAccount", label:"GL Account"},
{id:"expenseClass", label:"Class"},
{id:"expenseOffice", label:"Office"},
{id:"expenseDepartment", label:"Department"},
{id:"expenseGLCompany", label:"GL Company"},
{id:"expenseQuantity", label:"Quantity"},
{id:"expenseUnit", label:"Unit Amount"},
{id:"expenseSaleTax", label:"Sales Taxes"},
{id:"expenseAmount", label:"Amount"},
{id:"expenseExclude", label:"Exclude From 1099"},
{id:"expenseDescription", label:"Description"}
]''
	 , NULL, NULL, null, NULL)


/*************************************************************************************************************************
Payment Edit
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''paymentEditDetail'', ''Payment Edit Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''paymentEditDetail'', ''H_GRID'', 0, ''Grid Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

if @GLCompaniesWithForeignCurrencies = 0

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentEditDetail'', ''grdInvoicesCol'', 1, '' Invoice Columns'', ''invInvoiceNumber,invInvoiceDate,invOpen,invDiscount,invApplied,invExclude'', NULL, ''grid'', 

''[
{id:"invInvoiceNumber", label:"Invoice Number"},
{id:"invInvoiceDate", label:"Invoice Date"},
{id:"invOpen", label:"Open"},
{id:"invDiscount", label:"Discount"},
{id:"invApplied", label:"Applied"},
{id:"invExclude", label:"Exclude From 1099"},
{id:"invDescription", label:"Description"},
{id:"invVoucherTotal", label:"Invoice Total"},
{id:"invVoucherPaid", label:"Voucher Amount Paid"},
{id:"invOpenDiscount", label:"Open Discount"}
]''
	 , NULL, NULL, null, NULL)

else


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentEditDetail'', ''grdInvoicesCol'', 1, '' Invoice Columns'', ''invInvoiceNumber,invInvoiceDate,invOpen,invDiscount,invApplied,invExclude'', NULL, ''grid'', 

''[
{id:"invInvoiceNumber", label:"Invoice Number"},
{id:"invInvoiceDate", label:"Invoice Date"},
{id:"invOpen", label:"Open"},
{id:"invDiscount", label:"Discount"},
{id:"invApplied", label:"Applied"},
{id:"invExclude", label:"Exclude From 1099"},
{id:"invDescription", label:"Description"},
{id:"invVoucherTotal", label:"Invoice Total"},
{id:"invVoucherPaid", label:"Voucher Amount Paid"},
{id:"invOpenDiscount", label:"Open Discount"},
{id:"invGLCCurrencyID", label:"Company Currency"},
{id:"invGLCExchangeRate", label:"Company Exch Rate"} 
]''
	 , NULL, NULL, null, NULL)

if @GLCompaniesWithForeignCurrencies = 0

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentEditDetail'', ''grdCCCsColCol'', 2, ''CC Charge Columns'', ''cccVoucherID,cccInvoiceDate,cccPurchaseBy,cccPurchaseFrom,cccAmountOpen,cccDiscount,cccAmount,cccVoucherTotal,cccInvoiceNumber'', NULL, ''grid'', 

''[
{id:"cccVoucherID", label:"Ref #"},
{id:"cccInvoiceDate", label:"Charge Date"},
{id:"cccPurchaseBy", label:"Purchased By"},
{id:"cccPurchaseFrom", label:"Purchased From"},
{id:"cccAmountOpen", label:"Open"},
{id:"cccDiscount", label:"Discount"},
{id:"cccAmount", label:"Amount"},
{id:"cccVoucherTotal", label:"Charge Total"},
{id:"cccInvoiceNumber", label:"Charge Reference"},
{id:"cccDescription", label:"Description"},
{id:"cccVoucherPaid", label:"Charge Amount Paid"}
]''
	 , NULL, NULL, null, NULL)

else

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentEditDetail'', ''grdCCCsColCol'', 2, ''CC Charge Columns'', ''cccVoucherID,cccInvoiceDate,cccPurchaseBy,cccPurchaseFrom,cccAmountOpen,cccDiscount,cccAmount,cccVoucherTotal,cccInvoiceNumber'', NULL, ''grid'', 

''[
{id:"cccVoucherID", label:"Ref #"},
{id:"cccInvoiceDate", label:"Charge Date"},
{id:"cccPurchaseBy", label:"Purchased By"},
{id:"cccPurchaseFrom", label:"Purchased From"},
{id:"cccAmountOpen", label:"Open"},
{id:"cccDiscount", label:"Discount"},
{id:"cccAmount", label:"Amount"},
{id:"cccVoucherTotal", label:"Charge Total"},
{id:"cccInvoiceNumber", label:"Charge Reference"},
{id:"cccDescription", label:"Description"},
{id:"cccVoucherPaid", label:"Charge Amount Paid"},
{id:"cccGLCCurrencyID", label:"Company Currency"},
{id:"cccGLCExchangeRate", label:"Company Exch Rate"} 
]''
	 , NULL, NULL, null, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentEditDetail'', ''grdPrePaymentsCol'', 3, ''Prepay Columns'', ''preInvoiceNumber,preInvoiceDate,prePostingDate,preAmount,preExclude,preDiscount,preDescription'', NULL, ''grid'', 

''[
{id:"preInvoiceNumber", label:"Invoice #"},
{id:"preInvoiceDate", label:"Charge Date"},
{id:"prePostingDate", label:"Posting Date"},
{id:"preAmount", label:"Amount"},
{id:"preExclude", label:"Excluded from 1099"},
{id:"preDiscount", label:"Discount"},
{id:"preDescription", label:"Description"}
]''
	 , NULL, NULL, null, NULL)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''paymentEditDetail'', ''grdExpensesCol'', 4, ''Expense Columns'', ''expenseGLAccount,expenseAmount,expenseSaleTax,expenseExclude'', NULL, ''grid'', 

''[
{id:"expenseGLAccount", label:"GL Account"},
{id:"expenseClass", label:"Class"},
{id:"expenseOffice", label:"Office"},
{id:"expenseDepartment", label:"Department"},
{id:"expenseGLCompany", label:"GL Company"},
{id:"expenseQuantity", label:"Quantity"},
{id:"expenseUnit", label:"Unit Amount"},
{id:"expenseSaleTax", label:"Sales Taxes"},
{id:"expenseAmount", label:"Amount"},
{id:"expenseExclude", label:"Exclude From 1099"},
{id:"expenseDescription", label:"Description"}
]''
	 , NULL, NULL, null, NULL)

/*************************************************************************************************************************
Accrued Order Detail
**************************************************************************************************************************/


INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''accruedOrderDetail'', ''Accrued Order Detail'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''accruedOrderDetail'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''accruedOrderDetail'', ''grdOrders'', 1, ''Columns'', ''orderPurchaseOrderNumber,orderVendorName,orderClientName,orderPODate,orderPOClosed,orderTotalCost,orderAccruedCost,orderPrebillAmount,orderBalance,mediaPlanFullName'', NULL, ''grid'', 
''[	{id:"orderPurchaseOrderNumber", label:"Order #"},
	{id:"orderVendorName", label:"Vendor"},
	{id:"orderClientName", label:"Client"},
	{id:"orderPODate", label:"Order Date"},
	{id:"orderPOClosed", label:"Closed"},
	{id:"orderDetailDateRange", label:"Detail Date Range"},
	{id:"orderAccruedCost", label:"Amt Accrued"},
	{id:"orderPrebillAmount", label:"Amt Unaccrued"},
	{id:"orderBalance", label:"Balance"},
	{id:"orderTotalCost", label:"Net Cost"},
	{id:"orderOpenAmount", label:"Open Amount"},
	{id:"orderARPaidInFull", label:"AR Paid in Full"},
	{id:"orderProjectName", label:"Project Name"},
	{id:"orderEstimateName", label:"Media Estimate Name"},
	{id:"orderStationName", label:"Station / Pub"},
	{id:"orderCampaignName", label:"Campaign Name"},
	{id:"mediaPlanFullName", label:"Media Plan Full Name"}
 ]''
, NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
Financial GL drill down
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''financialGLDrillDown'', ''Financial GL Drill Down'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''financialGLDrillDown'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)

if @GLCompaniesWithForeignCurrencies = 0

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''financialGLDrillDown'', ''grdFinancialGLDDResultsCols'', 1, ''Columns'', ''postingStatus,entity,accountNumberName,reference,memo,currencyID,balance,cAmount,cDebit,cCredit'', NULL, ''grid'', 
''[  {id:"postingStatus", label:"Posting Status"},
	{id:"entity", label:"Type"},
    {id:"accountNumberName", label:"Account Number"},
	{id:"transactionDate", label:"Date"},
    {id:"reference", label:"Reference"},
	{id:"memo", label:"Memo"},
	{id:"currencyID", label:"CurrencyID"},
	{id:"balance", label:"Balance"},
	{id:"cAmount", label:"Amount"},
    {id:"cDebit", label:"Debit"},
	{id:"cCredit", label:"Credit"},
    {id:"amount", label:"Amount (HC)"},
    {id:"debit", label:"Debit (HC)"},
    {id:"credit", label:"Credit (HC)"},
	{id:"companyName", label:"Name"},
    {id:"clientID", label:"Client ID"},
	{id:"clientName", label:"Client Name"},
    {id:"vendorID", label:"Vendor ID"},
	{id:"vendorName", label:"Vendor Name"},
    {id:"classID", label:"Class ID"},
    {id:"className", label:"Class Name"},
    {id:"gLCompanyID", label:"Company ID"},
    {id:"gLCompanyName", label:"Company Name"},
    {id:"officeID", label:"Office ID"},
    {id:"officeName", label:"Office Name"},
    {id:"projectNumber", label:"Project Number"},
    {id:"projectName", label:"Project Name"},
    {id:"departmentName", label:"Department Name"},
    {id:"voucherID", label:"Unique Auto Number"},
	{id:"exchangeRate", label:"Exchange Rate"},
	{id:"debitRevalue", label:"Debit Revalued"},
	{id:"creditRevalue", label:"Credit Revalued"}, 
	{id:"amountRevalue", label:"Amount Revalued"},
	{id:"campaignID", label:"Campaign ID"}
 ]''
 , NULL, NULL, ''PO_Detail'', ''PO_Detail'')

 else -- use for GL companies with foreign currencies

 INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''financialGLDrillDown'', ''grdFinancialGLDDResultsCols'', 1, ''Columns'', ''postingStatus,entity,accountNumberName,reference,memo,currencyID,balance,cAmount,cDebit,cCredit'', NULL, ''grid'', 
''[  {id:"postingStatus", label:"Posting Status"},
	{id:"entity", label:"Type"},
    {id:"accountNumberName", label:"Account Number"},
	{id:"transactionDate", label:"Date"},
    {id:"reference", label:"Reference"},
	{id:"memo", label:"Memo"},
	{id:"currencyID", label:"CurrencyID"},
	{id:"balance", label:"Balance"},
	{id:"cAmount", label:"Amount"},
    {id:"cDebit", label:"Debit"},
	{id:"cCredit", label:"Credit"},
    {id:"amount", label:"Amount (HC)"},
    {id:"debit", label:"Debit (HC)"},
    {id:"credit", label:"Credit (HC)"},
	{id:"companyName", label:"Name"},
    {id:"clientID", label:"Client ID"},
	{id:"clientName", label:"Client Name"},
    {id:"vendorID", label:"Vendor ID"},
	{id:"vendorName", label:"Vendor Name"},
    {id:"classID", label:"Class ID"},
    {id:"className", label:"Class Name"},
    {id:"gLCompanyID", label:"Company ID"},
    {id:"gLCompanyName", label:"Company Name"},
    {id:"officeID", label:"Office ID"},
    {id:"officeName", label:"Office Name"},
    {id:"projectNumber", label:"Project Number"},
    {id:"projectName", label:"Project Name"},
    {id:"departmentName", label:"Department Name"},
    {id:"voucherID", label:"Unique Auto Number"},
	{id:"exchangeRate", label:"Exchange Rate"},
	{id:"debitRevalue", label:"Debit Revalued"},
	{id:"creditRevalue", label:"Credit Revalued"}, 
	{id:"amountRevalue", label:"Amount Revalued"},
	{id:"campaignID", label:"Campaign ID"},
	{id:"gLCCurrencyID", label:"Company Currency"},
	{id:"gLCExchangeRate", label:"Company Exchange Rate"},
	{id:"gLCAmount", label:"Amount (Company)"},
	{id:"gLCDebit", label:"Debit (Company)"},
	{id:"gLCCredit", label:"Credit (Company)"}
 ]''
 , NULL, NULL, ''PO_Detail'', ''PO_Detail'')



/*************************************************************************************************************************
CONNECTIONS - Contacts
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsContacts'', ''Connections - Contacts'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsContacts'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsContacts'', ''grdConnectionsContactsCols'', 1, ''Columns'', ''isPrimaryContact,contactFullName,phone1,email,personalWorkAddress1,personalWorkCity,personalWorkState,personalWorkPostalCode'', NULL, ''grid'', 
''[
	{id:"contactFullName", label:"Contact Full Name"},
	{id:"phone1", label:"Phone1"},
	{id:"phone2", label:"Phone2"},
	{id:"cell", label:"Cell"},
	{id:"email", label:"Email"},
	{id:"companyMainPhone", label:"Company Main Phone"},
	{id:"companyName", label:"Company Name"},
	{id:"userCompanyName", label:"User Company Name"},
	{id:"personalWorkAddress1", label:"Personal Work Address1"},
	{id:"personalWorkAddress2", label:"Personal Work Address2"},
	{id:"personalWorkAddress3", label:"Personal Work Address3"},
	{id:"personalWorkCity", label:"Personal Work City"},
	{id:"personalWorkState", label:"Personal Work State"},
	{id:"personalWorkPostalCode", label:"Personal Work Postal Code"},
	{id:"personalWorkCountry", label:"Personal Work Country"},
	{id:"homeAddress1", label:"Home Address1"},
	{id:"homeAddress2", label:"Home Address2"},
	{id:"homeAddress3", label:"Home Address3"},
	{id:"homeCity", label:"Home City"},
	{id:"homeState", label:"Home State"},
	{id:"homePostalCode", label:"Home Postal Code"},
	{id:"homeCountry", label:"Home Country"},
	{id:"companyAddress1", label:"Company Address1"},
	{id:"companyAddress2", label:"Company Address2"},
	{id:"companyAddress3", label:"Company Address3"},
	{id:"companyCity", label:"Company City"},
	{id:"companyState", label:"Company State"},
	{id:"companyPostalCode", label:"Company Postal Code"},
	{id:"companyCountry", label:"Company Country"},
	{id:"otherAddress1", label:"Other Address1"},
	{id:"otherAddress2", label:"Other Address2"},
	{id:"otherAddress3", label:"Other Address3"},
	{id:"otherCity", label:"Other City"},
	{id:"otherState", label:"Other State"},
	{id:"otherPostalCode", label:"Other Postal Code"},
	{id:"otherCountry", label:"Other Country"},
	{id:"isFavorite", label:"Is Favorite"},
	{id:"favoriteDisplayOrder", label:"Favorite Display Order"},
	{id:"isRecent", label:"Is Recent"},
	{id:"recentSort", label:"Recent Sort"},
	{id:"firstName", label:"First Name"},
	{id:"lastName", label:"Last Name"},
	{id:"title", label:"Title"},
	{id:"linkedInURL", label:"Linked In U R L"},
	{id:"twitterID", label:"Twitter I D"},
	{id:"contractor", label:"Contractor"},
	{id:"doNotCall", label:"Do Not Call"},
	{id:"doNotFax", label:"Do Not Fax"},
	{id:"doNotEmail", label:"Do Not Email"},
	{id:"doNotMail", label:"Do Not Mail"},
	{id:"lastModified", label:"Last Modified"},
	{id:"dateAdded", label:"Date Added"},
	{id:"dateUpdated", label:"Date Updated"},
	{id:"active", label:"Active"},
	{id:"isPrimaryContact", label:"Is Primary Contact"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Opportunities
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsOpps'', ''Connections - Opps'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsOpps'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsOpps'', ''grdConnectionsOppsCols'', 1, ''Columns'', ''subject,accountManagerName,stageName'', NULL, ''grid'', 
''[
	{id:"subject", label:"Subject"},
	{id:"accountManagerName", label:"Account Manager Name"},
	{id:"stageName", label:"Stage Name"},
	{id:"projectNumber", label:"Project Number"},
	{id:"leadStatusName", label:"Lead Status Name"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Projects
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsProjects'', ''Connections - Projects'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsProjects'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsProjects'', ''grdConnectionsProjectsCols'', 1, ''Columns'', ''projectNumber,projectName,projectStatus'', NULL, ''grid'', 
''[
	{id:"projectNumber", label:"Project Number"},
	{id:"projectName", label:"Project Name"},
	{id:"projectStatus", label:"Project Status"},
	{id:"projectBillingStatus", label:"Project Billing Status"},
	{id:"projectTypeName", label:"Project Type Name"},
	{id:"createdDate", label:"Created Date"},
	{id:"ExpensesNet", label:"Net Expenses"},
	{id:"GrossExpenses", label:"Gross Expenses"},
	{id:"TotalGross", label:"Total Gross"},
	{id:"EstimateGross", label:"Estimate Gross"},
	{id:"ActualHours", label:"Actual Hours"},
	{id:"LaborGross", label:"Gross Labor"},
	{id:"LaborNet", label:"Net Labor"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Project Requests
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsProjectRequests'', ''Connections - Project Requests'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsProjectRequests'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsProjectRequests'', ''grdConnectionsProjectRequestsCols'', 1, ''Columns'', ''requestID,requestName,statusText'', NULL, ''grid'', 
''[
	{id:"requestID", label:"Request ID"},
	{id:"dateAdded", label:"Date Added"},
	{id:"dateCompleted", label:"Date Completed"},
	{id:"requestedBy", label:"Requested By"},
	{id:"notifyEmail", label:"Notify Email"},
	{id:"subject", label:"Subject"},
	{id:"clientProjectNumber", label:"Client Project Number"},
	{id:"projectDescription", label:"Project Description"},
	{id:"dueDate", label:"Due Date"},
	{id:"campaignID", label:"Campaign ID"},
	{id:"cancelled", label:"Cancelled"},
	{id:"dateSentForApproval", label:"Date Sent For Approval"},
	{id:"dateCancelled", label:"Date Cancelled"},
	{id:"dateUpdated", label:"Date Updated"},
	{id:"customerID", label:"Customer ID"},
	{id:"companyName", label:"Company Name"},
	{id:"requestName", label:"Request Name"},
	{id:"statusText", label:"Status Text"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Estimates
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsEstimates'', ''Connections - Estimates'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsEstimates'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsEstimates'', ''grdConnectionsEstimateCols'', 1, ''Columns'', ''estimateName,estimateNumber,estimateType,totalWithTax,estimateTotal'', NULL, ''grid'', 
''[
	{id:"project_Full_Name", label:"Project Full Name"},
	{id:"estimateName", label:"Estimate Name"},
	{id:"estimateNumber", label:"Estimate Number"},
	{id:"estimate_Full_Name", label:"Estimate Full Name"},
	{id:"estimateType", label:"Estimate Type"},
	{id:"totalWithTax", label:"Total With Tax"},
	{id:"estimateTotal", label:"Estimate Total"},
	{id:"internalStatusName", label:"Internal Status Name"}
]''
 , NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
CONNECTIONS - Campaigns
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsCampaigns'', ''Connections - Campaigns'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsCampaigns'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsCampaigns'', ''grdConnectionsCampaignCols'', 1, ''Columns'', ''campaignID,campaignName'', NULL, ''grid'', 
''[
	{id:"campaignID", label:"Campaign ID"},
	{id:"campaignName", label:"Campaign Name"},
	{id:"campaignProjectManager", label:"Project Manager"},
	{id:"campaignAccountManager", label:"Account Manager"},
	{id:"campaignStartDate", label:"Start Date"},
	{id:"campaignEndDate", label:"End Date"}
]''
 , NULL, NULL, ''Campaign'', ''Campaign'')

/*************************************************************************************************************************
CONNECTIONS - Invoices
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsInvoices'', ''Connections - Invoices'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsInvoices'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsInvoices'', ''grdConnectionsInvoiceCols'', 1, ''Columns'', ''invoiceNumber,invoiceDate,postingDate,projectFullName,amountTotal,amountOpen'', NULL, ''grid'', 
''[
	{id:"invoiceNumber", label:"Invoice Number"},
	{id:"invoiceDate", label:"Invoice Date"},
	{id:"postingDate", label:"Posting Date"},
	{id:"projectFullName", label:"Project Full Name"},
	{id:"amountTotal", label:"Amount Total"},
	{id:"amountOpen", label:"Amount Open"},
	{id:"advanceBill", label:"Advance Bill"},
	{id:"headerComment", label:"Comments"},
	{id:"primaryContact", label:"Contact"},
	{id:"approvalStatus", label:"Approval Status"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Receipts
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsReceipts'', ''Connections - Receipts'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsReceipts'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsReceipts'', ''grdConnectionsReceiptCols'', 1, ''Columns'', ''referenceNumber,checkAmount,postingDate,dateReceived'', NULL, ''grid'', 
''[
	{id:"referenceNumber", label:"Reference Number"},
	{id:"paymentMethod", label:"Payment Method"},
	{id:"checkAmount", label:"Check Amount"},
	{id:"postingDate", label:"Posting Date"},
	{id:"dateReceived", label:"Date Received"},
	{id:"paymentDescription", label:"Payment Description"},
	{id:"unappliedAmount", label:"Unapplied Amount"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Purchase Orders
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsPurchaseOrders'', ''Connections - Purchase Orders'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsPurchaseOrders'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsPurchaseOrders'', ''grdConnectionsPurchaseOrdersCols'', 1, ''Columns'', ''poNumber,poDate,invoicedAmount'', NULL, ''grid'', 
''[
	{id:"poNumber", label:"PO Number"},
	{id:"poDate", label:"PO DateInsertion"},
	{id:"netAmount", label:"Net"},
	{id:"grossAmount", label:"Gross"},
	{id:"openAmount", label:"Open"},
	{id:"invoicedAmount", label:"Invoiced"},
	{id:"appliedAmount", label:"Applied"},
	{id:"status", label:"Status"}
]''
 , NULL, NULL, NULL, NULL)

 
/*************************************************************************************************************************
CONNECTIONS - Insertion Orders
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsInsertionOrders'', ''Connections - Insertion Orders'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsInsertionOrders'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsInsertionOrders'', ''grdConnectionsInsertionOrdersCols'', 1, ''Columns'', ''poNumber,poDate,invoicedAmount'', NULL, ''grid'', 
''[
	{id:"poNumber", label:"IO Number"},
	{id:"poDate", label:"IO Date"},
	{id:"netAmount", label:"Net"},
	{id:"grossAmount", label:"Gross"},
	{id:"openAmount", label:"Open"},
	{id:"invoicedAmount", label:"Invoiced"},
	{id:"appliedAmount", label:"Applied"},
	{id:"status", label:"Status"}
]''
 , NULL, NULL, NULL, NULL)

 
/*************************************************************************************************************************
CONNECTIONS - Broadcast Orders
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsBroadcastOrders'', ''Connections - Broadcast Orders'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsBroadcastOrders'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsBroadcastOrders'', ''grdConnectionsBroadcastOrdersCols'', 1, ''Columns'', ''poNumber,poDate,invoicedAmount'', NULL, ''grid'', 
''[
	{id:"poNumber", label:"BO Number"},
	{id:"poDate", label:"BO Date"},
	{id:"netAmount", label:"Net"},
	{id:"grossAmount", label:"Gross"},
	{id:"openAmount", label:"Open"},
	{id:"invoicedAmount", label:"Invoiced"},
	{id:"appliedAmount", label:"Applied"},
	{id:"status", label:"Status"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Credit Card Charges
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsCCCharges'', ''Connections - Credit Card Charges'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsCCCharges'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsCCCharges'', ''grdConnectionsCCChargesCols'', 1, ''Columns'', ''boughtFrom,chargeDate,chargeAmount,amountOpen'', NULL, ''grid'', 
''[
	{id:"boughtFrom", label:"Purchased From"},
	{id:"chargeDate", label:"Charge Date"},
	{id:"chargeAmount", label:"Charge Amount"},
	{id:"amountOpen", label:"Open"},
	{id:"posted", label:"Posted"},
	{id:"referenceNumber", label:"Reference Number"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Credit Card Payments
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsCCPayments'', ''Connections - Credit Card Payments'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsCCPayments'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsCCPayments'', ''grdConnectionsCCPaymentCols'', 1, ''Columns'', ''payToName,checkNumber,cashAccount,amount_cc'', NULL, ''grid'', 
''[
    {id:"payToName",label:"Pay To Name"},
	{id:"checkNumber",label:"Check Number"},
	{id:"cashAccount",label:"Cash Account"},
	{id:"checkDate_cc",label:"Payment Date"},
	{id:"amount_cc",label:"Amount Paid"},
	{id:"posted", label:"Posted"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Payments
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsVendorPayments'', ''Connections - Payments'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsVendorPayments'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsVendorPayments'', ''grdConnectionsPaymentsCols'', 1, ''Columns'', ''check_Number,check_Date,check_Amount'', NULL, ''grid'', 
''[
	{id:"check_Number", label:"Check Number"},
	{id:"check_Date", label:"Check Date"},
	{id:"check_Amount", label:"Check Amount"},
	{id:"cash_Account_Number", label:"Cash Account Number"},
	{id:"cash_Account_Name", label:"Cash Account Name"},
	{id:"cash_Account_Full_Name", label:"Cash Account Full Name"},
	{id:"posted", label:"Posted"},
	{id:"check_Memo", label:"Check Memo"},
	{id:"cleared", label:"Cleared"}

]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Vendor Invoices
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsVendorInvoices'', ''Connections - Vendor Invoices'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsVendorInvoices'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsVendorInvoices'', ''grdConnectionsVendorInvoicesCols'', 1, ''Columns'', ''invoice_Number,invoice_Date,invoice_Amount'', NULL, ''grid'', 
''[
	{id:"invoice_Number", label:"Invoice Number"},
	{id:"invoice_Amount", label:"Invoice Amount"},
	{id:"invoice_Amount_Open", label:"Invoice Amount Open"},
	{id:"invoice_AmountHC", label:"Invoice Amount HC"},
	{id:"invoice_Amount_OpenHC", label:"Amount Open HC"},
	{id:"invoice_Date", label:"Invoice Date"},
	{id:"due_Date", label:"Due Date"},
	{id:"posting_Date", label:"Posting Date"},
	{id:"invoice_Status", label:"Invoice Status"},
	{id:"invoice_Curr", label:"Currency"},
	{id:"project_Full_Name", label:"Project Full Name"},
	{id:"GL_Company", label:"GL Company"},
	{id:"station_Pub_Name", label:"Station/Publication"}	
]''
 , NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
CONNECTIONS - Expense Reports
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsExpenseReports'', ''Connections - Expense Reports'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsExpenseReports'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsExpenseReports'', ''grdConnectionsExpenseReportsCols'', 1, ''Columns'', ''envelopeNumber,invoiceNumber,dateSubmitted,expenseTotal,amountPaid,status'', NULL, ''grid'', 
''[
	{id:"envelopeNumber", label:"Envelope Number"},
	{id:"invoiceNumber", label:"Invoice Number"},
	{id:"dateSubmitted", label:"Date Submitted"},
	{id:"expenseTotal", label:"Expense Total"},
	{id:"amountPaid", label:"Amount Paid"},
	{id:"status", label:"Status"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
 CONNECTIONS - Timesheets
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsTimesheets'', ''Connections - Time Sheets'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsTimesheets'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsTimesheets'', ''grdConnectionsTimesheetsCols'', 1, ''Columns'', ''startDate,endDate,totalHours,status'', NULL, ''grid'', 
''[
	{id:"startDate", label:"Start Date"},
	{id:"endDate", label:"End Date"},
	{id:"totalHours", label:"Total Hours"},
	{id:"status", label:"Status"}
]''
 , NULL, NULL, NULL, NULL)

 
/*************************************************************************************************************************
CONNECTIONS - Publications
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsPublications'', ''Connections - Publications'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsPublications'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsPublications'', ''grdConnectionsPublicationsCols'', 1, ''Columns'', ''pubStationID,pubName,pubFrequency,pubMarket,pubItem,pubLink,pubActive,pubContact'', NULL, ''grid'', 
''[
	{id:"pubStationID", label:"Publication ID"},
	{id:"pubName", label:"Publication Name"},
	{id:"pubFrequency", label:"Frequency"},
	{id:"pubMarket", label:"Market"},
	{id:"pubItem", label:"Item"},
	{id:"pubLink", label:"Link ID"},
	{id:"pubActive", label:"Active"},
	{id:"pubContact", label:"Publication Contact"}

]''
 , NULL, NULL, NULL, NULL)

 
 
/*************************************************************************************************************************
CONNECTIONS - Stations
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsStations'', ''Connections - Stations'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsStations'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsStations'', ''grdConnectionsStationsCols'', 1, ''Columns'', ''staStationID,staName,staMarket,staItem,staLink,staActive,staContact'', NULL, ''grid'', 
''[
	{id:"staStationID", label:"Station ID"},
	{id:"staName", label:"Station Name"},
	{id:"staMarket", label:"Market"},
	{id:"staItem", label:"Item"},
	{id:"staLink", label:"Link ID"},
	{id:"staActive", label:"Active"},
	{id:"staContact", label:"Station Contact"}
]''
 , NULL, NULL, NULL, NULL)

 /*************************************************************************************************************************
CONNECTIONS - banking -> Authorize.net 
**************************************************************************************************************************/
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminCompanyConnections'', ''grdAuthorizeDotNetCols'', 1, ''Columns'', ''ccProcessorID,APILoginID,APITransactionKey,CurrencyID,CCCashAccountKey'', NULL, ''grid'', 
''[
	{id:"ccProcessorID", label:"Processor ID"},
	{id:"APILoginID", label:"API Login ID"},
	{id:"APITransactionKey", label:"API Key"},
	{id:"CurrencyID", label:"Currency ID"},
	{id:"CCCashAccountKey", label:"Receipt Account"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
CONNECTIONS - Retainers
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''connectionsRetainers'', ''Connections - Retainers'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''connectionsRetainers'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''connectionsRetainers'', ''grdConnectionsRetainersCols'', 1, ''Columns'', ''retainerClientID,retainerClientName,retainerAmountPerPeriod,retainerExtraAmountBilled,retainerTotalBilled,retainerTitle'', NULL, ''grid'', 
''[
{id:  "retainerClientID", label:"Client  ID"},
{id:  "retainerClientName", label:"Client Name"},
{id:  "retainerParentCompany Name", label:"Parent Company Name"},
{id:  "retainerAccountExecutive", label:"Account Executive"},
{id:  "retainerBillingManager", label:"Billing Manager"},
{id:  "retainerTitle", label:"Title"},
{id:  "retainerNumberOfPeriods", label:"Number of Periods"},
{id:  "retainerAmountPerPeriod", label:"Amount Per Period"},
{id:  "retainerStartDate", label:"Start Date"},
{id:  "retainerFrequency", label:"Frequency"},
{id:  "retainerNextBillingDate", label:"Next Billing Date"},
{id:  "retainerLastInvoiced", label:"Last Invoiced"},
{id:  "retainerTotalBilled", label:"Total Billed"},
{id:  "retainerRetainerAmountBilled", label:"Retainer Amount Billed"},
{id:  "retainerExtraAmountBilled", label:"Extra Amount Billed"},
{id:  "retainerSalesGLAccountNumber", label:"Sales GL Account Number"},
{id:  "retainerSalesGLAccountName", label:"Sales GL Account Name"},
{id:  "retainerTotalLabor", label:"Total Labor"},
{id:  "retainerTotalExpense", label:"Total Expense"},
{id:  "retainerVariance", label:"Variance"},
{id:  "retainerActive", label:"Active"},
{id:  "retainerDescription", label:"Description"},
{id:  "retainerCompanyID", label:"Company ID"},
{id:  "retainerCompanyName", label:"Company Name"},
{id:  "retainerOfficeID", label:"Office ID"},
{id:  "retainerOfficeName", label:"Office Name"},
{id:  "retainerCurrency", label:"Currency"},
{id:  "retainerRetainerID", label:"Retainer ID"},
{id:  "retainerPeriodsRemaining", label:"Periods Remaining"},
{id:  "retainerInvoiceTemplate", label:"Invoice Template"},
{id:  "retainerLayout", label:"Layout"},
{id:  "retainerIncludeLabor", label:"Include Labor"},
{id:  "retainerIncludeExpenses", label:"Include Expenses"},
{id:  "retainerDepartmentName", label:"Department Name"},
{id:  "retainerContactName", label:"Contact Name"}
]''
 , NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
Admin Screens
**************************************************************************************************************************/

/*************************************************************************************************************************
Admin Screens - Activity Type
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''activityTypeSetup'', ''Activity Type Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''activityTypeSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''activityTypeSetup'', ''grdlistCols'', 1, ''Columns'', ''typeName,active,autoRollDate,typeColor'', NULL, ''grid'', 
''[
	{id:"typeName", label:"Type Name"},
	{id:"active", label:"Active"},
	{id:"autoRollDate", label:"Auto Roll Date"},
	{id:"typeColor", label:"Display Color"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Billing Item
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''billingItemSetup'', ''Billing Item Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''billingItemSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''billingItemSetup'', ''grdlistCols'', 1, ''Columns'', ''workTypeID,workTypeName,standardPrice,description,accountName,classId,taxable,taxable2,departmentName,avalaraTaxCode,active'', NULL, ''grid'', 
''[
	{id:"workTypeID", label:"ID"},
	{id:"workTypeName", label:"Name"},
	{id:"standardPrice", label:"StarndardPrice"},
	{id:"description", label:"Description"},
	{id:"accountName", label:"Sales Account"},
	{id:"classId", label:"Class"},
	{id:"taxable", label:"Taxable"},
	{id:"taxable2", label:"Taxable2"},
	{id:"departmentName", label:"Department Name"},
	{id:"avalaraTaxCode", label:"Avalara Tax Code"},
	{id:"active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
Admin Screens - Calendar Resources Type
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''calResourceSetup'', ''Calendar Resources Type Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''calResourceSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''calResourceSetup'', ''grdlistCols'', 1, ''Columns'', ''resourceName'', NULL, ''grid'', 
''[
	{id:"resourceName", label:"Resource Name"}

]''
 , NULL, NULL, NULL, NULL)

 /*************************************************************************************************************************
Admin Screens - Project Type Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''projectTypeSetup'', ''Project Type Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''projectTypeSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''projectTypeSetup'', ''grdlistCols'', 1, ''Columns'', ''projectTypeName,description,active,projectNumPrefix,nextProjNum,projectTypeColor,avalaraTaxCode'', NULL, ''grid'', 
''[
      {id:"projectTypeName", label:"Project Type"},  
      {id:"description", label:"Description"},
	  {id:"active", label:"Active"}, 
      {id:"projectNumPrefix", label:"Project Number Prefix/Suffix"}, 
	  {id:"nextProjNum", label:"Next Project Number"}, 
	  {id:"projectTypeColor",label:"Project Type Color"},
	  {id:"avalaraTaxCode", label:"Avalara Tax Code"}
]''
 , NULL, NULL, NULL, NULL)
/*************************************************************************************************************************
Admin Screens - Company Type
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''companyTypeSetup'', ''Company Type Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''companyTypeSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''companyTypeSetup'', ''grdlistCols'', 1, ''Columns'', ''companyTypeName,active'', NULL, ''grid'', 
''[
	{id:"companyTypeName", label:"Company Type Name"},
	{id:"active", label:"Active"}

]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Item Rate Sheet
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminItemRateSheet'', ''Item Rate Sheet Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminItemRateSheet'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminItemRateSheet'', ''grdlistCols'', 1, ''Columns'', ''itemRS_RateSheetName,itemRS_Active'', NULL, ''grid'', 
''[
	{id:"itemRS_RateSheetName", label:"Rate Sheet Name"},
	{id:"itemRS_Active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Item Rate Sheet Details
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminItemRateSheetDetails'', ''Item Rate Sheet Detail Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminItemRateSheetDetails'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminItemRateSheetDetails'', ''grdlistCols'', 1, ''Columns'', ''itemRSD_ItemID,itemRSD_ItemName,itemRSD_UseUnitRate,itemRSD_Markup,itemRSD_UnitRate'', NULL, ''grid'', 
''[
	{id:"itemRSD_ItemID" label:"Item ID"},
	{id:"itemRSD_ItemName", label:"Item Name"},
	{id:"itemRSD_UseUnitRate", label:"Use Unit Rate"},
	{id:"itemRSD_Markup", label:"Markup/Commission"},
	{id:"itemRSD_UnitRate", label:"Unit Rate"}
]''
 , NULL, NULL, NULL, NULL)

 /*************************************************************************************************************************
Admin Screens - Medai Marekets
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''mediaMarkets'', ''Media Markets'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''mediaMarkets'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''mediaMarkets'', ''grdlistCols'', 1, ''Columns'', ''marketID,marektName,active'', NULL, ''grid'', 
''[
	{id:"marketID", label:"ID},
	{id:"marektName", label:"Description"},
	{id:"active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Meeting Type
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''meetingTypeSetup'', ''Meeting Type Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''meetingTypeSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''meetingTypeSetup'', ''grdlistCols'', 1, ''Columns'', ''typeName,typeColor'', NULL, ''grid'', 
''[
	{id:"typeName", label:"Meeting Type Name"},
	{id:"typeColor", label:"Type Color"}

]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Opportunity Outcomes
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''oppOutcomeSetup'', ''Opportunity Outcome Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''oppOutcomeSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''oppOutcomeSetup'', ''grdlistCols'', 1, ''Columns'', ''leadStageName,postiveOutcome,active'', NULL, ''grid'', 
''[
	{id:"leadStageName", label:"Outcome"},
	{id:"postiveOutcome", label:"Positive Outcome"},
	{id:"active", label:"Active"}

]''
 , NULL, NULL, NULL, NULL)



 /*************************************************************************************************************************
Admin Screens - Opportunity Status
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''oppStatusSetup'', ''Opportunity Status Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''oppStatusSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''oppStatusSetup'', ''grdlistCols'', 1, ''Columns'', ''opStage_Stage,opStage_DisplayOrder,opStage_DefaultProbability,opStage_DisplayOnDashboard,opStage_UseDefaultProbability'', NULL, ''grid'', 
''[
	{id:"opStatus_LeadStatusName", label:"Lead Status Name"},
	{id:"opStatus_DisplayOrder", label:"Display Order"},
	{id:"opStatus_Active", label:"Active"}
	
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Revision Reasons
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''revisionReasons'', ''Revision Reasons'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''revisionReasons'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''revisionReasons'', ''grdlistCols'', 1, ''Columns'', ''reasonID,description,active'', NULL, ''grid'', 
''[
	{id:"reasonID", label:"ID},
	{id:"description", label:"Description"},
	{id:"active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Source
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminSource'', ''Source Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminSource'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminSource'', ''grdlistCols'', 1, ''Columns'', ''sourceName,active'', NULL, ''grid'', 
''[
	{id:"sourceName", label:"Source Name"},
	{id:"active", label:"Active"}
	
	
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Service Rate Sheet
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminServiceRateSheet'', ''Servies Rate Sheet Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminServiceRateSheet'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminServiceRateSheet'', ''grdlistCols'', 1, ''Columns'', ''SheetName,active'', NULL, ''grid'', 
''[
	{id:"SheetName", label:"Rate Sheet Name"},
	{id:"active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Service Rate Sheet Details
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminServiceRateSheetDetails'', ''Servies Rate Sheet Detail Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminServiceRateSheetDetails'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminServiceRateSheetDetails'', ''grdlistCols'', 1, ''Columns'', ''ServiceCode,Description,HourlyRate1,HourlyRate2,HourlyRate3,HourlyRate4,HourlyRate5'', NULL, ''grid'', 
''[
	{id:"ServiceCode" label:"Service Code"},
	{id:"Description", label:"Description"},
	{id:"HourlyRate1", label:"Rate 1"},
	{id:"HourlyRate2", label:"Rate 2"},
	{id:"HourlyRate3", label:"Rate 3"},
	{id:"HourlyRate4", label:"Rate 4"},
	{id:"HourlyRate5", label:"Rate 5"}
]'' , NULL, NULL, NULL, NULL)

 /*************************************************************************************************************************
Admin Screens - Title Rate Sheet
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminTitleRateSheet'', ''Title Rate Sheet Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminTitleRateSheet'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminTitleRateSheet'', ''grdlistCols'', 1, ''Columns'', ''SheetName,active'', NULL, ''grid'', 
''[
	{id:"SheetNamev", label:"Rate Sheet Name"},
	{id:"active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Title Rate Sheet Details
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminTitleRateSheetDetails'', ''Title Rate Sheet Detail Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminTitleRateSheetDetails'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminTitleRateSheetDetails'', ''grdlistCols'', 1, ''Columns'', ''titleID,titleName,hourlyRate'', NULL, ''grid'', 
''[
	{id:"titleID" label:"Title ID"},
	{id:"titleName", label:"Title Name"},
	{id:"hourlyRate", label:"Hourly Rate"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Service Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''serviceSetup'', ''Service Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''serviceSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''serviceSetup'', ''grdlistCols'', 1, ''Columns'', ''services_ServiceCode,services_Description,services_Active,services_Color'', NULL, ''grid'', 
''[
	{id:"services_ServiceCode", label:"Service Code"},
	{id:"services_Description", label:"Description"},
	{id:"services_Color", label:"Color"},
	{id:"services_HourlyRate1", label:"Hourly Rate1"},
	{id:"services_HourlyRate2", label:"Hourly Rate2"},
	{id:"services_HourlyRate3", label:"Hourly Rate3"},
	{id:"services_HourlyRate4", label:"Hourly Rate4"},
	{id:"services_HourlyRate5", label:"Hourly Rate5"},
	{id:"services_Active", label:"Active"},
	{id:"services_Description1", label:"Description1"},
	{id:"services_Description2", label:"Description2"},
	{id:"services_Description3", label:"Description3"},
	{id:"services_Description4", label:"Description4"},
	{id:"services_Description5", label:"Description5"},
	{id:"services_HourlyCost", label:"Hourly Cost"},
	{id:"services_Taxable", label:"Taxable"},
	{id:"services_Taxable2", label:"Taxable2"},
	{id:"services_WorkTypeID", label:"Billing Item"},
	{id:"services_ClassID", label:"Class"},
	{id:"services_DepartmentName", label:"Department"},
	{id:"services_AccessRestrictions", label:"Access Restrictions"},
	{id:"services_SalesAccountName", label:"Sales Account Name"},
	{id:"services_AvalaraTaxCode", label:"Avalara Tax Code"},
	{id:"services_AdjustmentPct", label:"Adjustment Pct"},
	{id:"services_AdjustmentGLAccountName", label:"Adjustment GL Account Name"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Expense Report Items Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''expenseItemsSetup'', ''Expense Items Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''expenseItemsSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''expenseItemsSetup'', ''grdItemList'', 1, ''Columns'', ''itemID,itemName,unitCost,unitRate,standardDescription,workTypeID,active'', NULL, ''grid'', 
''[
	{id:"itemID", label:"Item ID"},
	{id:"itemName", label:"Item Name"},
	{id:"unitCost", label:"Unit Cost"},
	{id:"unitRate", label:"Unit Rate"},
	{id:"markup", label:"Markup"},
	{id:"useUnitRate", label:"Use Unit Rate"},
	{id:"standardDescription", label:"Standard Description"},
	{id:"workTypeID", label:"Billing Item"},
	{id:"department", label:"Department"},
	{id:"expenseAccount", label:"Expense Account"},
	{id:"salesAccount", label:"Sales Account"},
	{id:"class", label:"Class"},
	{id:"taxable", label:"Taxable"},
	{id:"taxable2", label:"Taxable2"},
	{id:"active", label:"Active"},
	{id:"avalaraTaxCode", label:"Avalara Tax Code"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Purchase Items Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''purchaseItemsSetup'', ''Purchase Items Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchaseItemsSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''purchaseItemsSetup'', ''grdItemList'', 1, ''Columns'', ''itemID,itemName,expenseAccount,salesAccount,unitCost,unitRate,unitDescription,standardDescription,workTypeID,active'', NULL, ''grid'', 
''[
	{id:"itemID", label:"Item ID"},
	{id:"itemName", label:"Item Name"},
	{id:"unitCost", label:"Unit Cost"},
	{id:"unitRate", label:"Unit Rate"},
	{id:"unitDescription", label:"Unit Description"},
	{id:"markup", label:"Markup"},
	{id:"useUnitRate", label:"Use Unit Rate"},
	{id:"standardDescription", label:"Standard Description"},
	{id:"workTypeID", label:"Billing Item"},
	{id:"department", label:"Department"},
	{id:"expenseAccount", label:"Expense Account"},
	{id:"salesAccount", label:"Sales Account"},
	{id:"class", label:"Class"},
	{id:"quantityOnHand", label:"Quantity On Hand"},
	{id:"taxable", label:"Taxable"},
	{id:"taxable2", label:"Taxable2"},
	{id:"active", label:"Active"},
	{id:"avalaraTaxCode", label:"Avalara Tax Code"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Broadcast Items Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''broadcastItemsSetup'', ''Broadcast Items Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''broadcastItemsSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''broadcastItemsSetup'', ''grdItemList'', 1, ''Columns'', ''itemID,itemName,markup,standardDescription,workTypeID,active'', NULL, ''grid'', 
''[
	{id:"itemID", label:"Item ID"},
	{id:"itemName", label:"Item Name"},
	{id:"markup", label:"Commission"},
	{id:"standardDescription", label:"Standard Description"},
	{id:"workTypeID", label:"Billing Item"},
	{id:"department", label:"Department"},
	{id:"expenseAccount", label:"Expense Account"},
	{id:"salesAccount", label:"Sales Account"},
	{id:"class", label:"Class"},
	{id:"taxable", label:"Taxable"},
	{id:"taxable2", label:"Taxable2"},
	{id:"active", label:"Active"},
	{id:"avalaraTaxCode", label:"Avalara Tax Code"},
	{id:"useMarkup", label:"Use Markup"},
	{id:"boItem_AdjustmentPct", label:"Adjustment Pct"},
	{id:"boItem_AdjustmentGLAccountName", label:"Adjustment GL Account Name"}
]''
 , NULL, NULL, NULL, NULL)

/*************************************************************************************************************************
Admin Screens - Print Items Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''printItemsSetup'', ''Print and Digital Items'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''printItemsSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''printItemsSetup'', ''grdItemList'', 1, ''Columns'', ''itemID,itemName,markup,standardDescription,workTypeID,expenseAccount,salesAccount,active'', NULL, ''grid'', 
''[
	{id:"itemID", label:"Item ID"},
	{id:"itemName", label:"Item Name"},
	{id:"unitRate", label:"Standard Gross"},
	{id:"markup", label:"Commission"},
	{id:"standardDescription", label:"Standard Description"},
	{id:"workTypeID", label:"Billing Item"},
	{id:"department", label:"Department"},
	{id:"expenseAccount", label:"Expense Account"},
	{id:"salesAccount", label:"Sales Account"},
	{id:"class", label:"Class"},
	{id:"taxable", label:"Taxable"},
	{id:"taxable2", label:"Taxable2"},
	{id:"active", label:"Active"},
	{id:"avalaraTaxCode", label:"Avalara Tax Code"},
	{id:"useMarkup", label:"Use Markup"},
	{id:"printItem_AdjustmentPct", label:"Adjustment Pct"},
	{id:"printItem_AdjustmentGLAccountName", label:"Adjustment GL Account Name"}
]''
 , NULL, NULL, NULL, NULL)

 /*************************************************************************************************************************
Admin Screens - GL Accounts setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''glaccountSetup'', ''GL Account Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''glaccountSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''glaccountSetup'', ''grdlistCols'', 1, ''Columns'', ''glaccount_AccountNumber,glaccount_Active,glaccount_AccountTypeAccrual,glaccount_AccountTypeCash,glaccount_PayrollExpense,glaccount_FacilityExpense,glaccount_LaborIncome'', NULL, ''grid'', 
''[
	{id:"glaccount_AccountNumber", label:"Account Number"},
	{id:"glaccount_Active", label:"Active"},
	{id:"glaccount_AccountTypeAccrual", label:"Account Type (Accrual)"},
	{id:"glaccount_AccountTypeCash", label:"Account Type (Cash)"},
	{id:"glaccount_PayrollExpense", label:"Payroll Expense"},
	{id:"glaccount_FacilityExpense", label:"Facility Expense"},
	{id:"glaccount_LaborIncome", label:"Labor Income"},
	{id:"glaccount_BankAccountNumber", label:"Bank Account Number"},
	{id:"glaccount_CurrencyID", label:"Currency"},
	{id:"glaccount_NextCheckNumber", label:"Next Check Number"},
	{id:"glaccount_DefaultCheckFormat", label:"Default Check Format"},
	{id:"glaccount_RevalueCurr", label:"Revalue Balance Sheet"},
	{id:"glaccount_Description", label:"Description"},
	{id:"glaccount_SubAccount", label:"SubAccount Of"},
	{id:"glaccount_Ebitda", label:"EBITDA Account"},
]''
 , NULL, NULL, NULL, NULL)


/*************************************************************************************************************************
Admin Screens - Purchase Order Types Setup
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''purchaseOrderTypesSetup'', ''Purchase Order Types Setup'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''purchaseOrderTypesSetup'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''purchaseOrderTypesSetup'', ''grdItemList'', 1, ''Columns'', ''purchaseOrderTypeName,description,headerFieldSet,detailFieldSet,standardHeaderText,standardFooterText,active'', NULL, ''grid'', 
''[
	{id:"purchaseOrderTypeName", label:"PO Type Name"},
	{id:"description", label:"Description"},
	{id:"headerFieldSet", label:"Default PO Header Fields"},
	{id:"detailFieldSet", label:"Default PO Line Fields"},
	{id:"standardHeaderText", label:"Standard Header Text"},
	{id:"standardFooterText", label:"Standard Footer Text"},
	{id:"active", label:"Active"}
]''
 , NULL, NULL, NULL, NULL)
 
 /*************************************************************************************************************************/

/*************************************************************************************************************************
Employees
**************************************************************************************************************************/

INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''adminEmployees'', ''Employee Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminEmployees'', ''H2'', 1, ''Display Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminEmployees'', ''GroupBy'', 2, ''Group By'', ''Department'', ''Department'', ''lookup'', ''No Grouping:NoGrouping|Department:Department|Security Group:SecurityGroup|Default GL Company:DefaultGLCompanyName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminEmployees'', ''GroupByDir'', 3, ''Group Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminEmployees'', ''SortBy'', 4, ''Sort By'', ''LastName'', ''Last Name'', ''lookup'', ''No Sorting:NoSorting|Department:Department|First Name:FirstName|Last Name:LastName|Security Group:SecurityGroup'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''adminEmployees'', ''SortByDir'', 5, ''Sort Order'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''adminEmployees'', ''grdEmployeeCols'', 6, ''Columns'', ''firstName,lastName,phone,email,active,securityGroup'', NULL, ''grid'', 
''[
	{id:"userKey", label:"User Key"},
	{id:"companyKey", label:"Company Key"},
	{id:"gLCompanyKey", label:"G L Company Key"},
	{id:"firstName", label:"First Name"},
	{id:"middleName", label:"Middle Name"},
	{id:"lastName", label:"Last Name"},
	{id:"salutation", label:"Salutation"},
	{id:"department", label:"Department"},
	{id:"phone", label:"Phone"},
	{id:"secondPhone", label:"Second Phone"},
	{id:"cellPhone", label:"Cell Phone"},
	{id:"fax", label:"Fax"},
	{id:"pager", label:"Pager"},
	{id:"title", label:"Title"},
	{id:"email", label:"Email"},
	{id:"rateLevel", label:"Rate Level"},
	{id:"securityGroup", label:"Security Group"},
	{id:"administrator", label:"Administrator"},
	{id:"userID", label:"User ID"},
	{id:"systemID", label:"System ID"},
	{id:"active", label:"Active"},
	{id:"autoAssign", label:"Auto Assign"},
	{id:"canNotBeUnassigned", label:"Can Not Be Unassigned"},
	{id:"hourlyRate", label:"Hourly Rate"},
	{id:"hourlyCost", label:"Hourly Cost"},
	{id:"monthlyCost", label:"Monthly Cost"},
	{id:"timeApprover", label:"Time Approver"},
	{id:"expenseApprover", label:"Expense Approver"},
	{id:"creditCardApprover", label:"Credit Card Approver"},
	{id:"calendarApprover", label:"Meeting Approver"},
	{id:"backupApprover", label:"Backup Approver"},
	{id:"supervisor", label:"Supervisor"},
	{id:"mySupervisor", label:"My Supervisor"},
	{id:"pOLimit", label:"PO Limit"},
	{id:"broadcastOrderLimit", label:"Broadcast Order Limit"},
	{id:"insertionOrderLimit", label:"Insertion Order Limit"},
	{id:"vendorID", label:"Vendor ID"},
	{id:"vendorFullName", label:"Vendor Full Name"},
	{id:"classID", label:"Class ID"},
	{id:"classFullName", label:"Class Full Name"},
	{id:"office", label:"Office"},
	{id:"locked", label:"Locked"},
	{id:"address1", label:"Address1"},
	{id:"address2", label:"Address2"},
	{id:"address3", label:"Address3"},
	{id:"city", label:"City"},
	{id:"state", label:"State"},
	{id:"postalCode", label:"Postal Code"},
	{id:"country", label:"Country"},
	{id:"homeAddress1", label:"Home Address1"},
	{id:"homeAddress2", label:"Home Address2"},
	{id:"homeAddress3", label:"Home Address3"},
	{id:"homeCity", label:"Home City"},
	{id:"homeState", label:"Home State"},
	{id:"homePostalCode", label:"Home Postal Code"},
	{id:"homeCountry", label:"Home Country"},
	{id:"otherAddress1", label:"Other Address1"},
	{id:"otherAddress2", label:"Other Address2"},
	{id:"otherAddress3", label:"Other Address3"},
	{id:"otherCity", label:"Other City"},
	{id:"otherState", label:"Other State"},
	{id:"otherPostalCode", label:"Other Postal Code"},
	{id:"otherCountry", label:"Other Country"},
	{id:"defaultService", label:"Default Service"},
	{id:"defaultServiceDescription", label:"Default Service Description"},
	{id:"birthday", label:"Birthday"},
	{id:"dateHired", label:"Date Hired"},
	{id:"role", label:"Role"},
	{id:"assistant", label:"Assistant"},
	{id:"assistantPhone", label:"Assistant Phone"},
	{id:"assistantEmail", label:"Assistant Email"},
	{id:"spousePartner", label:"Spouse/Partner"},
	{id:"children", label:"Children"},
	{id:"anniversary", label:"Anniversary"},
	{id:"hobbies", label:"Hobbies"},
	{id:"usageLevel", label:"Usage Level"},
	{id:"contractor", label:"Contractor"},
	{id:"defaultGLCompanyID", label:"Default GL Company ID"},
	{id:"defaultGLCompanyName", label:"Default GL Company Name"},
	{id:"billingTitleID", label:"Billing Title ID"},
	{id:"billingTitleName", label:"Billing  Title Name"},
	{id:"billingTitleFullName", label:"Billing Title Full Name"},
	{id:"lastLoggedIn", label:"Last Logged In"},
	{id:"lastLoggedOut", label:"Last Logged Out"},
	{id:"userToken", label:"User Token"},
	{id:"dateCreated", label:"Date Created"},
	{id:"defaultCulture", label:"Default Culture"},
	{id:"timeZoneDisplay", label:"Employee Time Zone"},
	{id:"createdBy", label:"Created By"}
]''
 , NULL, NULL, NULL, NULL)



/*************************************************************************************************************************
Deliverable Reviews
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''review'', ''Review Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''DisplayActualSize'', 1, ''Always load review items at actual size'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''UseAdvancedTools'', 2, ''Use Advanced Tools'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''RequireMarkupForComment'', 3, ''Require annotations for comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''ShowApprovedWithChanges'', 4, ''Show Approved with Changes as a decision'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''ShowAssignFollupUpTaskLink'', 5, ''Show Assign a Followup Task Link'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''correspondingAnnotations'', 6, ''Use corresponding annotations and comments'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''review'', ''useReplaceTextOnPDF'', 7, ''Use replace text with PDFs'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)

/*************************************************************************************************************************/



/*************************************************************************************************************************
Account Rec
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''acctRec'', ''Acct Rec Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''acctRec'', ''grdDecreaseCols'', 1, ''Decrease Columns'', ''colDTranDate,colDRef,colDMemo,colDAmount'', NULL, ''grid'', 
''[
	{id:"colDTranDate", label:"Transaction Date"},
	{id:"colDRef", label:"Reference"},
	{id:"colDMemo", label:"Memo"},
	{id:"colDPayee", label:"Payee Name"},
	{id:"colDAmount", label:"Amount"}

]''
 , NULL, NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''acctRec'', ''grdIncreaseCols'', 2, ''Increase Columns'', ''colITranDate,colIRef,colIMemo,colIAmount'', NULL, ''grid'', 
''[
	{id:"colITranDate", label:"Transaction Date"},
	{id:"colIRef", label:"Reference"},
	{id:"colIMemo", label:"Memo"},
	{id:"colIAmount", label:"Amount"}

]''
 , NULL, NULL, NULL, NULL)

 
/*************************************************************************************************************************
Add People
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''myAddPeople'', ''Add People Settings'', '''', 0)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''myAddPeople'', ''keepOpen'', 1, ''Keep panel open'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will keep the add people screen open after you select and add people so that you can select other people'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''myAddPeople'', ''autoRunStaff'', 2, ''Search for staff when the screen is opened'', ''1'', NULL, ''checkbox'', NULL, NULL, ''If you have a lot of employees, you may uncheck this option so you can first enter some search criteria rather than opening the entire list'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''myAddPeople'', ''autoRunContacts'', 3, ''Search for contacts when the screen is opened'', ''1'', NULL, ''checkbox'', NULL, NULL, ''If you have a lot of contacts, you may uncheck this option so you can first enter some search criteria rather than opening the entire list'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''myAddPeople'', ''projectTeamOnly'', 4, ''Project Team Only'', ''0'', NULL, ''checkbox'', NULL, NULL, ''This will limit the search options to just client contacts and project team and will override the search for staff when screen is open option above'')




/*************************************************************************************************************************  exec spConvertAppSeedSetting 1
deliverables Board
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''deliverablesBoard'', ''Board Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''groupBy'', 1, ''Group Grid By'', ''StatusName'', ''Deliverable Status'', ''lookup'', ''No Grouping:NoGrouping|Deliverable Status:StatusName|Type:TypeName|Deliverable Name:DeliverableName|Due Date:DueDate|Approved:IsApproved|Owner Name:OwnerName|Completed:IsCompleted'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''sortBy'', 2, ''Sort Grid By'', ''DueDate'', ''Due Date'', ''lookup'', ''Status:StatusName|Due Date:DueDate'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''sortByDir'', 3, ''Sort Direction'', ''DESC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''boardViewAllowed'', 4, ''Group Cards By'', ''Both'', NULL, ''lookup'', ''Task|Status|Both'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''filterClient'', 5, ''Show Client Filter'', ''0'', NULL, ''checkbox'', NULL, NULL, ''If you filter by client alone, you will not be able to set specific display orders'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''filterCampaign'', 6, ''Show Campaign Filter'', ''0'', NULL, ''checkbox'', NULL, NULL, ''If you filter by campaign alone, you will not be able to set specific display orders'')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''hideCompletedTasks'', 7, ''Hide Deliverables For Completed Tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, '''')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''hideApprovedCompleted'', 8, ''Hide Completed Deliverables'', ''0'', NULL, ''checkbox'', NULL, NULL, '''')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesBoard'', ''hideDuplicate'', 9, ''Hide Duplicate Button'', ''0'', NULL, ''checkbox'', NULL, NULL, '''')

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''deliverablesBoard'', ''grdDeliverablesCols'', 10, ''Grid Columns'', ''colDBoardDeliverableName,colDBoardComments,colDBoardDueDate,colDBoardStatusName,colDBoardDeliverableType,colDBoardRoundName,colDBoardApprovalStatus,colDBoardOpenIssueCount'', NULL, ''grid'', 
''[   
	{id:  "colDBoardStatusName", label:"Status Name"},   
	{id:  "colDBoardDeliverableName", label:"Deliverable Name"},   
	{id:  "colDBoardProjectNumber", label:"Project Number"},  
	{id:  "colDBoardProjectName", label:"Project Name"},  
	{id:  "colDBoardTask", label:"Task Name"},  
	{id:  "colDBoardComments", label:"Conversation Count"},  
	{id:  "colDBoardDeliverableType", label:"Type"},  
	{id:  "colDBoardDescription", label:"Description"},   
	{id:  "colDBoardDueDate", label:"Due Date"},    
	{id:  "colDBoardApproved", label:"Approved"},   
	{id:  "colDBoardApprovedDate", label:"Approved Date"},
	{id:  "colDBoardCompleted", label:"Completed"},   
	{id:  "colDBoardOwnerName", label:"Owner Name"},   
	{id:  "colDBoardRoundCount", label:"Round Count"},   
	{id:  "colDBoardOpenIssueCount", label:"Open To Do Count"},   
	{id:  "colDBoardClosedIssueCount", label:"Closed To Do Count"} ,   
	{id:  "colDBoardRoundName", label:"Current Round"},   
	{id:  "colDBoardApprovalStatus", label:"Approval Status"},
	{id:  "colDBoardDeliverableID", label:"Deliverable ID"},
	{id:  "colDBoardSubject", label:"Current Step Name"}
]''
 , NULL, NULL, ''Deliverable'', ''Deliverables'')

 /*************************************************************************************************************************
Deliverables Dash
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''deliverablesDash'', ''Deliverable Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesDash'', ''showSampleImage'', 1, ''Show Sample Image'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesDash'', ''showDailyFeed'', 2, ''Show the Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesDash'', ''showConversations'', 3, ''Show Conversations'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesDash'', ''showToDos'', 4, ''Show To Dos'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''deliverablesDash'', ''showReviewRounds'', 5, ''Show Review Rounds'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, VisibleField)
Values (''deliverablesDash'', ''showReverseOrder'', 6, ''Show Reverse Order'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL, ''showReviewRounds'')




/*************************************************************************************************************************
ToDo Board - Need to finish updating
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''toDoBoard'', ''Board Settings'', '''', 1)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''groupBy'', 1, ''Group Grid By'', ''StatusName'', ''Status Name'', ''lookup'', ''No Grouping:NoGrouping|Status Name:StatusName|Project:ProjectFullName|Client:FullClientName|Assigned:AssignedUserName|Due Date:ActivityDate|Type:TypeName|Task Plan Complete Date:PlanComplete'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''sortBy'', 2, ''Sort Grid By'', ''StatusName'', ''Status Name'', ''lookup'', ''Status Name:StatusName|Project:ProjectFullName|Client:FullClientName|Assigned:AssignedUserName|Due Date:ActivityDate|Type:TypeName'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''sortByDir'', 3, ''Sort Direction'', ''DESC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''filterClient'', 4, ''Show Client Filter'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will display the client filter'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''filterProject'', 5, ''Show Project Filter'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will display the project filter'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''filterTask'', 6, ''Show Task Filter'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will display the task filter.'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''toDoBoard'', ''filterUser'', 7, ''Show User Filter'', ''1'', NULL, ''checkbox'', NULL, NULL, ''This will display the user filter'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, TransPref)
Values (''toDoBoard'', ''filterType'', 8, ''Show Type Filter'', ''0'', NULL, ''checkbox'', NULL, NULL, ''This will display the type filter'', ''UseTypeOnToDo'')
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''toDoBoard'', ''grdToDoCols'', 9, ''Grid Columns'', ''coltodoBoardSubject,coltodoBoardProject,coltodoBoardClient,coltodoBoardAssigned,coltodoBoardNotes,coltodoBoardStatusName,coltodoBoardType'', NULL, ''grid'', 
''[   
	{id:  "coltodoBoardSubject", label:"Subject"},   
	{id:  "coltodoBoardProject", label:"Project"},   
	{id:  "coltodoBoardClient", label:"Client"},   
	{id:  "coltodoBoardAssigned", label:"Assigned"},   
	{id:  "coltodoBoardDueDate", label:"Due Date"},
	{id:  "coltodoBoardNotes", label:"Description"},
	{id:  "coltodoBoardStatusName", label:"Status Name"},
	{id:  "coltodoBoardType", label:"Type"},
	{id:  "coltodoBoardTaskFullName", label:"Task"},
	{id:  "coltodoBoardTodoID", label:"To Do ID"},
	{id:  "coltodoBoardCompleted", label:"Completed"},
	{id:  "coltodoBoardPlanComplete", label:"Task Plan Complete Date"},
	{id:   "coltodoBoardOriginatedBy", label:"Originated By"},
	{id:   "coltodoBoardCreatedBy", label:"Created By"}

]''
 , NULL, NULL, ''Activity'', ''Activity'')

 /*************************************************************************************************************************
Estimate Add
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''estimateAdd'', ''Add Estimate Settings'', '''', 0)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''estimateAdd'', ''DeliveryDateRequired'', 1, ''Require Delivery Date'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Common Timeline Options
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''commonTimeLine'', ''Timeline Settings'', '''', 0)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''commonTimeLine'', ''HideEnterTime'', 29, ''Hide enter your time for today'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''commonTimeLine'', ''DisplayTimeEntries'', 30, ''Display Time Entries'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''commonTimeLine'', ''IncludePublicMeetings'', 31, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)


/*************************************************************************************************************************
Campaign Schedule
**************************************************************************************************************************/
INSERT tAppSettingGroup(GroupID, Title, Rights, ResetSettings) Values(''campaignSchedule'', ''Campaign Schedule Grid'', '''', 1)

INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignSchedule'', ''H1'', 0, ''Settings'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''campaignSchedule'', ''ScheduleLockedColumns'', 1, ''Locked Columns'', ''1'', ''1'', ''lookup'', ''1:1|2:2|3:3|4:4|5:5'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint, CFEntity1, CFPrefix1) 
Values (''campaignSchedule'', ''grdCampaignScheduleCols'', 2, ''Columns'', ''campaignAssigned,campaignProjectStart,campaignProjectEnd,campaignPercComp'', NULL, ''grid'', 

''[	{id:"campaignAssigned", label:"Assigned"},
	{id:"campaignProjectStart", label:"Plan Start"},
	{id:"campaignProjectEnd", label:"Plan Complete"},
	{id:"campaignPercComp", label:"%"},
	{id:"campaignScheduleTaskStatus", label:"Status"},
	{id:"campaignScheduleAssignedFullName", label:"Assigned Full Name"},
	{id:"campaignSchedulePlanDuration", label:"Days"},
	{id:"campaignScheduleActualHours", label:"Actual Hours"},
	{id:"campaignSchedulePredecessors", label:"Predecessors"},
	{id:"campaignScheduleActualStart", label:"Actual Start"},
	{id:"campaignScheduleActualComplete", label:"Actual Complete"},
	{id:"campaignScheduleAllTimesheets", label:"All Time Sheets"},
	{id:"campaignScheduleBillingItem", label:"Billing Item"},
	{id:"campaignProject", label:"Project"},
	{id:"campaignSummaryTask", label:"Summary Task"},
	{id:"campaignSegment", label:"Segment"},
	{id:"campaignScheduleBOCommision", label:"BO Commission"},
	{id:"campaignScheduleConstraint", label:"Constraint"},
	{id:"campaignScheduleConstraintDate", label:"Constraint Date"},
	{id:"campaignScheduleConstraintDayOfWeek", label:"Constraint Day Of The Week"},
	{id:"campaignScheduleDescription", label:"Description"},
	{id:"campaignScheduleDueComment", label:"Due Comment"},
	{id:"campaignScheduleAllocHours", label:"Allocated Hours"},
	{id:"campaignScheduleRemainingHours", label:"Remaining Hours"},
	{id:"campaignScheduleEstHours", label:"Est Hours"},
	{id:"campaignScheduleHideFromClient", label:"Hide From Client"},
	{id:"campaignScheduleHourlyRate", label:"Hourly Rate"},
	{id:"campaignScheduleIOCommision", label:"IO Commission"},

	{id:"campaignScheduleLine", label:"Line"},
	{id:"campaignScheduleMarkup", label:"Markup"},
	{id:"campaignScheduleOrigStart", label:"Baseline Start"},
	{id:"campaignScheduleOrigComp", label:"Baseline Complete"},
	{id:"campaignSchedulePriority", label:"Priority"},
	{id:"campaignScheduleReviewed", label:"Reviewed"},
	{id:"campaignScheduleTaskScheduled", label:"Show On Schedule"},
	{id:"campaignScheduleShowOnEstimate", label:"Show On Estimate"},
	{id:"campaignScheduleStatusDescription", label:"Status Comment"},
	{id:"campaignScheduleTaskID", label:"Task ID"},
	{id:"campaignScheduleTax1", label:"Tax 1"},
	{id:"campaignScheduleTax2", label:"Tax 2"},
	{id:"campaignScheduleDateAssigned", label:"Date Assigned"},
	{id:"campaignScheduleTimeAssigned", label:"Time Assigned"},
	{id:"campaignScheduleTrackBudgets", label:"Track Budgets"},
	{id:"campaignScheduleExcludeFromStatus", label:"Exclude From Status"},
	{id:"campaignScheduleWorkAnyDay", label:"Work Any Day"},
	{id:"campaignScheduleTimelineSection", label:"Timeline Section"},
	{id:"campaignScheduleTimelineSegmentDisplayName", label:"Override Display Name"},
	{id:"campaignScheduleTCProjectStatus", label:"Task Complete Project Status"},
	{id:"campaignScheduleOpenToDos", label:"Open ToDos"}

 ]''
	 , NULL, NULL, null, null)


INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''campaignSchedule'', ''editColumnSets'', 3, ''Edit Column Sets'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)

/* Old Comments:
|| 02/18/19  CRG 19.0.3.0 (421239) Removed PlanningMultipleTasks from the project schedule settings (it is now a setting on the project itself)
|| 02/19/19  CRG 19.0.3.0 (446583) Added Remaining Hours to projectSchedule columns
|| 02/26/19  AMP 19.0.3.0 (440082) Added Client Name and Vendor Name to the GL Drilldown
|| 02/26/19  RLS 19.0.3.0 (444491) Added Campaign Description to the campaignDashBoard
|| 02/26/19  GHL 19.0.3.0 (442017) Added currency to estimate listing (under project)
|| 02/27/19  AMP 19.0.3.0 (447860) Added Journal Entries to the Global Search option  
|| 03/04/19  GWG 19.0.3.0  Fixing group options on deliverables board
|| 03/07/19  AMP 19.0.4.0 (447900) Added Date/Time Sent to the Deliverable Approvals
|| 03/11/19  AMP 19.0.4.0 (448928) Added TaskID to Today-Creatives grid view
|| 03/13/09  AMP 19.0.4.0 (422224) Added the Approval Comments and Worksheet Comments to the BillingWorksheetsToApprove, BillingWorksheetsInReview,ReadyToCreateInvoices and BillingWorksheetsAll listings
|| 03/14/19  GHL 19.0.4.0 Added Applied spots and amount to bill on BO grid after discussion with Greg
|| 03/13/19  GWG 19.0.4.0 Adding labs to this side since they mostly affect the menus
|| 03/18/19  CRG 19.0.4.0 (449162) Added prjScheduleExcludeFromStatus to projectSchedule columns
|| 03/18/19  AMP 19.0.4.0 (449681) Added the Currency field as an available field to the projects screen.  
|| 03/20/19  MCM 19.0.4.0 (443519) Adding ToDo Board column information
|| 03/21/19  GWG 19.0.4.0 Removing platMedia, officeBlockoutCalendars, plaid, DeliverableBoard, crossProjectPreds  from labs
|| 03/25/19  RLS 19.0.4.0 (443168) Added projectFiles > ShowThumbnails
|| 03/25/19  RLB 19.0.4.0 (441482) Added change request options for project and campaign dash boards on client login
|| 03/25/19  GWG 19.0.4.0 Adding in option to show todos on the client dash and a lab for planning projects
|| 03/26/19  MFT 19.0.4.0 (446667) Added Created By columns to approval screens
|| 03/29/19  RLB 19.0.4.0 (441482) Added change request to myNotifications
|| 04/03/19  AMP 19.0.5.0 (437595) Added Vendor Name to Expenses
|| 04/03/19  AMP 19.0.5.0 (448992) Added Locked Columns to Campaign Budget
|| 04/11/19  AMP 19.0.5.0 (454685) Added Tax Amount and Profit to Expenses
|| 04/17/19  AMP 19.0.5.0 (455566) Corrected Spelling 
|| 04/17/19  AMP 19.0.5.0 (454685) Removed Tax Amount and Profit from Expenses and added Vendor Name, Tax Amount and Profit to Billing Worksheet -> To Bill-> Transaction Settings 
|| 04/18/19  RLB 19.0.5.0 (456086) fixed spelling error
|| 04/22/19  RLB 19.0.5.0 (441482) Added back in change request approvals
|| 04/22/19  RLB 19.0.5.0 (441482) Added today pm unapproved change request
|| 04/23/19  RLS 19.0.5.0 (456491) Added projectRequestRejections and NotiShowRejected in myNotifications
|| 04/23/19  RLB 19.0.5.0 (441482) Added project dashboard change request section
|| 04/30/19  RLB 19.0.5.0 (454160) Added edit column sets to project templates 
|| 04/30/19  GAR 19.0.5.0 (455939) Added system setting for hiding sample image in deliverables dash
|| 05/01/19  MCM 19.0.5.0 (443518) Added Due Date to the todo board section
|| 05/02/19  AMP 19.0.6.0 (456405) Added ''My Tasks'' to the Today-> Media page
|| 05/02/19  GAR 19.0.5.0 (457457) Added AssignedFullName to System Settings for the schedule
|| 05/02/19  GAR 19.0.5.0 (458014) Added setting for Show/Hide Handoff Tasks button
|| 05/06/19  AMP 19.0.5.0 (458012) Added Voucher Description to the Select Invoices to Pay Screen
|| 05/06/19  AMP 19.0.5.0 (452434) Added Client Name column to the Estimates section of the Approval window
|| 05/05/19  GWG 19.0.5.0 Added Version number for specs in grid mode
|| 05/13/19  GHL 19.0.6.0 (434271) Added attachment count on the transaction project billing grid
|| 05/15/19  GWG 19.0.6.0 Removing the setting to view change requests. controlled by a right
|| 05/17/19  AMP 19.0.6.0 (460415) Added Show Client Project Number to Project Add
|| 05/21/19  RLS 19.0.6.0 (460733) Added NotiTimeUnsubmitted to myNotifications
|| 05/22/19  AMP 19.0.6.0 (460354) Added Date Created and Date Received to the Select Invoices to Pay Screen
|| 05/23/19  CRG 19.0.6.0 (460946) Added IncludePlanningProjects to Project Production Dash
|| 05/30/19  GHL 19.0.6.0 Added mediaPlanDetails grid for new media plans, corrected markup and unit cost 
|| 06/04/19  RLS 19.0.7.0 Added productionDashLastTaskDueDate
|| 06/06/19  AMP 19.0.7.0 (458184) Removed Variance from Projects - Connections
|| 06/10/19  AMP 19.0.7.0 (456900) Added Expense Reports, Purchase Orders, Insertion Orders and Broadcast Orders options to the Generate Billing Worksheets System Settings screen.
|| 06/10/19  AMP 19.0.7.0 (464149) Added the following columns to the Campaign Budget screen: Project Gross Remaining %,Project Hours Remaining %,Project Labor Gross Remaining %,Project Costs Gross Remaining %
|| 06/11/19  RLB 19.0.7.0 (446229) Readd of project manager columns etc....
|| 06/12/19  MCM 19.0.7.0 (464959) Added purchased from to the client Invoice expense
|| 06/13/19  RLB 19.0.7.0 (446229) Added project manager as option to today pm project feed
|| 06/13/19  GWG 19.0.7.0 Fix group by default on deliverables board.
|| 06/14/19  GAR 19.0.7.0 (466091) Added system setting for turning on/off daily feed in today.creative
|| 06/17/19  RLB 19.0.7.0 (446229) reverted this change. Just change account manager option to a or project manager
|| 06/20/19  AMP 19.0.7.0 (461523) Changed label for the attachment count on the transaction project billing grid 
|| 06/25/19  WDF 19.0.7.0 (467442) Fixed ''Hint'' for ''projectDashBoard''...''DashboardIncludeActivities''; Changed ''myTask'' SessionID for ''In/Out Board Options'' from ''H4'' to ''H5'' due to duplicate Key error
|| 07/02/19  GWG 19.0.7.0 Added different display options for deliverables
|| 07/03/19  RLB 19.0.8.0 removed client campaign change request option. it will be ruled by client rights
|| 07/11/19  AMP 19.0.8.0 (451506) Added Comments to Estimate Expense Settings
|| 07/17/19  AMP 19.0.8.0 (456195) Added System Settings for the Project Budget DrillDowns
|| 07/18/19  AMP 19.0.8.0 (470168) Changed ''Comments'' to ''Long Description'' on Broadcast Orders
|| 07/18/19  RLS 19.0.8.0 (468559) Added HideEnterTime on all the today pages
|| 07/22/19  RLS 19.0.8.0 (468559) Change order for timeline settings to make them consistant across the Today pages (related to above)
|| 07/29/19  AMP 19.0.8.0 (470117) Added the Cash Account Number, Cash Account Name, and Cash Account Full Name to CONNECTIONS - Payments (Vendor Payments)
|| 07/30/19  RLB 19.0.8.0 (471378) Added project manager options to today creative
|| 07/30/19  AMP 19.0.8.0 (471039) Added Custom Fields for Campaigns
|| 08/02/19  AMP 19.0.9.0 (457107) Added Line to the Estimate Edit Labor Drilldown and Estimate Expense Settings
|| 08/06/19  RLB 19.0.9.0 (460882) Added customized grid option to project Billing FF
|| 08/07/19  GHL 19.0.0.0 Added error message to media plan detail grid
|| 08/12/19  GAR 19.0.9.0 (473674) Added project manager to group by and sort by in projects dash
|| 08/19/19  CRG 19.0.9.0 (475151) Modified labels in productionDash
|| 08/23/19  GAR 19.0.9.0 (475355) In client portal project requests - change project number to client project number and add project number
|| 08/29/19  GAR 19.0.9.0 (476924) Added DeliverableID column to the Deliverables board
|| 09/05/19  RLB 19.0.9.0 (476641) Added Account Manager and Project Manager to TimeEntry
|| 09/05/19  MCM 19.0.9.0 (476550) Update description verbage for ExcludeVendors on the opportunitySettings
|| 09/13/19  GHL 19.1.0.0 (479305) Added UOM columns to grdExpenseEstimateCols
|| 09/17/19  GAR 19.1.0.0 (479571) Added Show On Schedule and Show On Estimate to the template grid
|| 09/20/19  GHL 19.1.0.0 Added Deleted column to media plam details
|| 09/20/19  AMP 19.1.0.0 (477552) Added Materials Sent, and Materials Sent Date on the IO and BO''s\\

|| 09/23/19  GAR 19.1.0.0 (480171) Added Project Type Color to My Projects Settings 
|| 09/23/19  GWG 19.1.0.0 (480783) Add tran pref to hide billing titles
|| 09/26/19  RLS 19.1.0.0 (458816) Added showDueComments to clientPortal
|| 10/03/19  RLB 19.1.0.0 (469418) Added LaborGrossAfterWriteOff, LaborGrossAfterWriteOffRemaining, CostsGrossAfterWriteOffRemaining wanted TotalGrossAfterWriteOff but it seems to be there already for campaignBudget
|| 10/07/19  RLS 19.1.1.0 (480740) Change CampaignName to CampaignFullName in myTasks
|| 10/07/19  GAR 19.1.1.0 (481547) Added Project Manager to Campaigns Settings
|| 10/08/19  AMP 19.1.0.0 (464052) Added ''Backup Approvals'' to the Notification Settings
|| 10/16/19  RLS 19.0.8.0 (469411) Added NotiShowTimers to myNotifications section
|| 10/17/19  RLB 19.1.1.0 (457226) Added My Superviser
|| 10/23/19  GAR 19.1.1.0 (484469) Added Estimate Profit column to My Projects Settings
|| 10/23/19  AMP 19.1.1.0 (465917) Add Expense GL Account to Expense Reports
|| 10/30/19  RLS 19.1.1.0 (485619) Add autoRunClients in myAddPeople
|| 10/30/19  AMP 19.1.1.0 (486067) Add Client ID and Client name columns to Billing Worksheet Approvals
|| 10/30/19  GWG 19.1.1.0 Added deliverable count (productionDashDeliverables)
|| 11/14/19  AMP 19.1.2.0 (487355) Addded Campaign Name on the Billing Worksheets
|| 11/15/19  AMP 19.1.2.0 (466117) Added Unit Description Field on the Misc Costs screen
|| 11/15/19  GAR 19.1.2.0 (488065) Client Portal System Settings - the campaign show spec sheets had the wrong DisplayOrder - changed from 3 to 30
|| 11/18/19  GAR 19.1.2.0 (487501) Adding Current Step to the deliverable approvals screen
|| 11/18/19  AMP 19.1.2.0 (479932) Label changes to standardize the labels for Orders between System Setup, and Add and Edit pages. 
|| 11/20/19  GHL 19.1.2.0 Added media plan detail history count
|| 11/22/19  RLB 19.1.2.0 (469047) added pred complete column to staff schedule day detail 
|| 11/22/19  RLB 19.1.2.0 (476758) Added option to copy time sheets to user time entry page
|| 12/02/19  RLS 19.1.2.0 (487506) Removed NotiShowTimers to myNotifications section
|| 12/4/19   GWG 19.1.2.0 Adding a conversation column for deliverables
|| 12/12/19  GAR 20.0.1.0 (469720) Moved the Hand Off Tasks setting from production assignment settings to creatives today settings
|| 12/17/19  RLB 20.0.1.0 (487336) removed client portal option to see all projects since a right will not control that
|| 12/30/19  RLB 20.0.1.0 (486087) Added hint to tile view on today creative
|| 01/02/20  MCM 20.0.1.0 (464614) Added show labor summary to the estimate edit
|| 01/02/20  AMP 20.0.1.0 (493508) Added Description to the GL Account Setup screen
|| 01/02/20  GHL 20.0.1.0 (493640) Changed the order/number of mediaPlanDetails columns after review by Dave Arnold
|| 01/02/20  MFT 20.0.2.0 (478136) Added ABA option for Autrailan electronic bank transfer payments
|| 01/17/20  AMP 20.0.2.0 (495297) Added settings for the Credit Card Connector - on the Unmatched Charges Panel
|| 01/20/20  RLS 20.0.2.0 (479118) Added CopyEstimates and CopyFiles in the projectAdd section
|| 01/30/20  AMP 20.0.3.0 (498114) Added setting in the Schedule screen of the Project to Show Burn Chart (enabled by default) 
|| 02/04/20  GAR 20.0.3.0 (498506) Added Status Name as a column option in the To Do board settings
|| 02/07/20  GAR 20.0.3.0 (499184) Added Open Deliverables Only flag to Creatives Today - My Task Options
|| 02/12/20  MCM 20.0.3.0 (467817) Added ShowExpenseReportItems to credit card connector in order to hide expense report items
|| 02/25/20  GAR 20.0.3.0 (503504) Added Task Complete Project Status to project template grid settings
|| 02/25/20  GAR 20.0.4.0 (500265) Added Show Assign a Followup Task Link right in deliverable reviews
|| 02/27/20  MCM 20.0.4.0 (469227) Added ability to group by client for the billingWorksheetsApprovals
|| 02/28/20  GWG 20.0.4.0  Changed deliverablesBoard to prompt to blow user settings
|| 03/06/20  GAR 20.0.4.0 (505536) Added Current Budget Quantity and Purchased Quantity fields to the Project Budget - By Type
|| 03/11/20  GAR 20.0.4.0 (472155) Added Client can Resend / Cancel an Approved Request to project request settings
|| 03/12/20  AMP 20.0.4.0 (504078) Added Write Off Reasons to Billing Transaction Settings
|| 03/13/20  GAR 20.0.4.0 (505771) Added sortByDueDate to the client portal settings
|| 03/18/20  GAR 20.0.4.0 (506143) Added project start date and project complete date to creatives today grid
|| 03/30/20  GAR 20.0.4.0 (502095) In the Schedule grid, rename the columns Original Start and Original Complete to Baseline Start and Baseline Complete
|| 03/31/20  RLS 20.0.4.0 (440975) Added Require Start Date / Due Date in the projectAdd section
|| 03/31/20  RLS 20.0.4.0 (440975) Added new section estimateAdd adn in it, Require Delivery Date
|| 04/08/20  GAR 20.0.4.0 (506720) Change system settings for new deliverable page to have to dos, time, and conversations hidden by default
|| 04/09/20  RLB 20.0.5.0 (508861) Added show project request views to client portal
|| 04/14/20  GAR 20.0.5.0 (510589) Added planning projects to system settings for global search
|| 04/14/20  MCM 20.0.5.0 (471784) Added Mass Billing "Include Overhead Clients" so can filter it out
|| 05/01/20  RLS 20.0.6.0 (505989) Added Hints to all the items in groupID globalSearch
|| 05/01/20  AMP 20.0.7.0 (477845) Added ''Show Spec Sheets'' and ''Show Attachments'' to IO''s and BO''s
|| 05/05/20  AMP 20.0.6.0 (513817) Added Description to Unposted Transactions
|| 05/06/20  RLB 20.0.6.0 (494017) added overworked assignments option to today pm
|| 05/11/20  RLS 20.0.6.0 (505989) Changed the verbiage of the hints for groupID globalSearch
|| 05/12/20  RLS 20.0.6.0 (513828) Added Show Next Steps on right and Show Status Notes on right to projectDashBoard
|| 05/13/20  RLB 20.0.6.0 (514574) Added system setting to campaign projects page
|| 05/14/20  MCM 20.0.6.0 (491375) Added client portal invoice options
|| 05/22/20  RLS 20.0.6.0 (516299) Added StartDateEndDateRequired to campaignAdd
|| 05/28/20  AMP 20.0.6.0 (514609) Added Budget column to the Billing Worksheets (Worksheets in Review)
|| 06/02/20  RLS 20.0.6.0 (517053) Added SortConversations to all of the Today pages
|| 06/04/20  AMP 20.0.7.0 (515624) Added Date Created 
|| 06/08/20  RLS 20.0.7.0 (515357) OptionName and SelectedOption to estimateList
|| 06/09/20  RLS 20.0.7.0 (517205) Added colDBoardSubject to the deliverablesBoard
|| 06/29/20  RLS 20.0.7.0 (518686) Added productionDashGLCompanySource to grdProductionDash
|| 06/30/20  AMP 20.0.8.0 (517117) Add Pay To Name field from check
|| 07/06/20  GHL 20.0.8.0 Added Order ID to mediaPlanDetails
|| 08/04/20  RLB 20.0.9.0 (479157) Added Show Estimates on Client Portal
|| 08/04/20  GAR 20.0.6.0 (517761) Added ShowProjectManager to campaignAdd
|| 08/19/20  GAR 20.0.9.0 (526380) Added Project Due Date to campaign settings
|| 08/28/20  RLS 20.0.9.0 (525634) Added prodCampDashDeliverables
|| 08/31/20  RLS 20.0.9.0 (525753) Added productionDashLastTimeEntry
|| 08/31/20  GAR 20.1.0.0 (526908) Added Key People to My Projects Settings 
|| 09/09/20  GAR 20.1.0.0 (528577) Added Use Conversations setting to project request settings
|| 09/14/20  RLS 20.1.0.0 (528009) Added prodCampDashOpportunityFullName
|| 10/01/20  WDF 20.1.1.0 (531698)  Added ''NoGrouping'' as a key to ''timeEntry''.
|| 10/05/20  RLB 20.1.1.0 (531647) removing options to remove first column on all project budget grids since it is needed
|| 10/08/20  GAR 20.1.1.0 (530355) Added project number as an available column in the Vendor Invoice Approvals and Rejections settings grids
|| 10/13/20  MCM 20.1.1.0 (524234) Added show all invoices waiting for approval - not just ones where I''m the approver
|| 10/13/20  GHL 20.1.1.0 (529464) Added FF campaign mass billing to Billing Today
|| 10/13/20  AMP 20.1.1.0 (498290) Added SubAccount Of to the GL Account Setup Screen
|| 10/21/20  GAR 20.1.1.0 (534408) Removed PProject Change Requests lab
|| 10/22/20  RLS 20.1.1.1 (530509) Added campaignFullNameName, productName, divisionName, projectBillingStatus, projectStatus to ''grdBillingWorksheetsCols''
|| 10/23/20  RLS 20.1.1.1 (532874) Added "To Do ID" to the coltodoBoard columns
|| 10/27/20  RLB 20.1.1.0 (534454) Added open deliverables
|| 10/29/20  GAR 20.1.2.0 (533018) Added Labor Hours, Budget Labor Hours, and Project Allocated Hours to the Campaigns Settings grid
|| 11/17/20  AMP 21.0.1.0 (534968) Added Department to the Client Invoice Line 
|| 11/23/20  RLS 21.1.2.0 (537478) Added Allocated Hours to the project template schedule (''projectTemplate'' section)
|| 12/07/20  RLB 21.0.1.0 (531678) Added current approver to scheduledTransactions
|| 12/08/20  GHL 21.0.1.0 (536860) Added forecast detail grid columns (+ proj type)
|| 12/11/20  RLS 20.0.1.0 (538620) Added prodCampDashLeadStageName and prodCampDashLeadStageName columns
|| 12/11/20  AMP 21.0.1.0 (538425) Added Vendor Name to the Project Budget Analysis Report - Outside Costs drilldown
|| 12/17/20  GAR 21.0.1.0 (538022) Added Checkbox to group / not group by date in expense reports
|| 01/04/21  GAR 21.0.2.0 (535624) Added custom fields to the client portal project request status listings
|| 01/15/21  RLS 21.0.2.0 (542067) Added services_AccessRestrictions to the Admin Screens - Service Setup section
|| 01/20/21  GAR 21.0.2.0 (543934) Added Labor Gross to campaigns settings
|| 01/21/21  AMP 21.03.14.0000 (544090) Added the Accrued Amount field to the Vendor Invoices screen for the lines
|| 01/28/21  GHL 21.03.14.0000 (526158) Added split orders on cc connector 
|| 02/08/21  MCM 21.03.14.0000 (546918) Fixed spelling with colDetailOrderDate in ioTraffic
|| 02/24/21  RLB 21.03.14 (545442) removed grouping option on Accrued Order Detail 
|| 03/02/21  AMP 21.05.16.0000(546279) Added # Remaining field for the Scheduled Transactions view
|| 03/03/21  RLB 21.04.18 (544932) Added Total Gross Unbilled to projects production dash
|| 03/05/21  RLB 21.04.18 (550876) Added display options for deliverable board for completed tasks and approved or completed delivrables
|| 03/18/21  RLB 21.04.18 (552161) Added Completed to deliverable board dash
|| 03/18/21  WDF 21.04.18 (551861) Added Item/Service to Task Detail Settings
|| 03/18/21  GHL 21.04.18 (547004) Added Vendor Currency to the estimate expenses
|| 03/19/21  GHL 21.04.18 (546926) Added Total Before % (id = fdetail_totalbefore) to forecast grid
|| 03/24/21  RLB 21.04.18 (549892) Added Hide Duplicate button to Deliverable Dash and removed timesheet option on del dash 2 moved to trans pref
|| 04/06/21  GHL 21.04.18 (554332) Changed Split Orders to Orders on cc connector
|| 04/16/21  RLB 21.05.16 (549134) Added shwo unread system messages to notifications
|| 04/27/21  GHL 21.05.16 (555670) Added setting to hide bank account balances in AP (HideBankAccountBalances)
|| 04/30/21  WDF 21.05.16 (557033) Replace the incorrect title for tAppSettingGroup of ''printItemsSetup''
|| 05/07/21  WDF 21.06.20 (555495) Added columns todoType and todoStatus to group productionAssignment
|| 05/12/21  GAR 21.06.20 (558461) Changed client legacy rights over to system settings (client_projectlist = showProjectList, client_assignments = showAssignments)
|| 06/02/21  GAR 21.07.18 (559051) Add a setting on the review round tab of the deliverable to show latest round first - deliverablesDash, showReverseOrder
|| 06/07/21  CRG 21.07.18 (544844) Added Default Culture to adminEmployees columns
|| 06/08/21  GAR 21.07.18 (559917) Added To Do due date to assignment to do grid - Assignment To Do Settings
|| 06/09/21  AMP 21.07.18.0000 (554517) Change label on Billing Transactions from Description to Vendor/Person, and Added column Transaction Comments
|| 06/15/21  WDF 21.07.18 (560349) Added coltodoBoardType to GroupID ''toDoBoard''
|| 06/17/21  RLB 21.07.18 (548863) Added Summary Task Name to traffic calendar
|| 06/23/21  AMP 21.07.18.0000 (549387) Added Expense Reports to the Global Search option
|| 06/24/21  AMP 21.07.18.0000 (562316) Added Publication/Station to System Settings to be displayed on the Vendor Invoice Lines for IO/BO''s  
|| 06/25/21  RLB 21.07.18 (560670) Added new common Timeline options
|| 07/01/21  RLB 21.08.15 (562793) Added new campaign schedule options
|| 07/19/21  RLS 21.08.15 (559791) Added to the ''myTasks'' section: group by TaskUserStatusName and column mytaskTaskUserStatusName
|| 07/19/22  GHL 21.08.15 (560579) Added Posted column to project billing grid
|| 08/04/21  MCM 21.09.19 (566562) Added CurrentTotalBudgetNoTax to prjbudgetSettings
|| 08/10/21  GHL 21.09.19 (567346) Added DashboardShowClosedBilling to project dashboard
|| 08/20/21  MCM 21.09.19 (564526) Added UnsubmittedOrders to purchasingToday
|| 08/26/21  MCM 21.09.19 (562437) Removed ''Print Selected Spec Sheets'' from ''projectDashBoard''
|| 08/27/21  MCM 21.09.19 (566456) Added HoursUnbilled to project budget columns
|| 08/31/21  RLS 21.09.19 (566254) Added productionDashAllocatedHours
|| 09/01/21  RLS 21.09.19 (565860) Added coltodoBoardTaskFullName
|| 09/02/21  GAR 21.10.17 (569710) Changed description for DashboardProfitabilitySR and DashboardSnapshotSR to remove ''on the right'' from the description
|| 09/07/21  GHL 21.10.17 (451878) Added commented out grids for 451878, uncomment out when we deploy 451878
||                        doing this because this sp changes constantly
|| 09/29/21  MCM 21.10.17 (571693) added ebitda to the glaccounts
|| 10/06/21  AMP 21.11.14 (573200) Added GLCompany to CONNECTIONS - Vendor Invoices
|| 10/14/21  RLB 21.11.14 (568263) Adding project manager and campaign CF''s to campaign dash board connections
|| 10/19/21  GHL 21.11.14 (572385) Added ApproverIsAM for billing worksheets
|| 10/20/21  AMP 21.12.19 (574400) Added ''active'' column to the Admin Screens - Company Type
|| 10/20/21  RLS 21.12.19 (568009) Added VendorID and VendorFullName to the grid cols in the prjbudgetEstimates section and VendorFullName to the prjbudgetGeneral section
|| 10/14/21  RLB 21.11.21 (568263A) Adding account manager dash board connections
|| 11/22/21  MCM 21.12.x  (578053) Added campBudgetLaborHoursWriteOff
|| 12/14/21  GHL 22.12.00 (574154) Added payvouch1099 for col Exclude From 1099 when paying vouchers
|| 12/17/21  RLB 22.01.16 (578277) Added new grouping field ParentClientName from project client on productionDash
|| 12/21/21  GHL 22.01.16 (564964) Added ProjectFullName for VI approvals
|| 12/21/21  AMP 22.01.16 (577578) Added System Settings for Advance Billings 
|| 01/03/22  AMP 22.02.20 (582124) Added ''Contact'' to the Connections-> Invoices
|| 01/19/22  GHL 22.02.00 (583350) Added Addable transactions to billing worksheets to review
|| 02/02/22  RLS 22.02.20 (582600) Added timeZoneDisplay to grdEmployeeCols
|| 02/03/22  AMP xx.xx.xx (DEV2506-486) Changed ''ToDos'' to ''Issues'' on the Deliverables Dash
|| 02/08/22  AMP 22.03.20 (583455) Added Station Contact to the Station Connections listing
|| 02/10/22  AMP xx.xx.xx (DEV2506-486) Reverted Previous Change on the Deliverables Dash from ''Issues'' back to ''ToDos''
|| 02/15/22  RLS 22.03.20 (585537) Added IAmAM and IAmPM to the productionDash section
|| 02/15/22  WDF 22.03.20 (586670) Added ''productionDashPlanning''
|| 02/16/22  MCM 22.03.20 (582548) added CampaignID to grdFinancialGLDDResults
|| 02/17/22  AMP 22.03.20 (586206) Added ''Cleared'' to the CONNECTIONS - Payments
|| 02/17/22  AMP 22.03.20 (583455) Added Publication Contact to the Publication Connections listing
|| 02/18/22  WDF 22.03.20 (589015) Added fields to ''productionDashPlanning''
|| 02/21/22  WDF 22.03.20 (588477) Added ''ScheduleLockedColumns'' to ''campaignBudgetDetail''
|| 02/21/22  RLB 22.03.20 (587756) Aadded planned project name, number and full name to productionDashPlanning
|| 02/24/22  GHL 22.03.20 (589427) Removed Open To Dos from planning projects because todos are not used with PPs 
|| 02/24/22  AMP 22.03.20 (588429) Added Project Manger to the Forecast Detail Grid
|| 03/04/22  GHL 22.04.20 (589782) Added Created By to Post Transactions page
|| 04/14/22  AMP 22.04.17 (589401) Added Stations and Publications to the Global Search
|| 04/15/22  AMP 22.04.17 (587510) Added VendorID, VendorName, VendorFullName for the drill down cost fields on the Project Budget Analysis Report
|| 03/21/22  CRG 22.04.17 (588480) Added DisableDragDrop to trafficRM
|| 03/28/22  GHL 22.04.17 (451878) Added variable @GLCompaniesWithForeignCurrencies to use for GL companies using foreign currencies
||                         Change value to 1 when 451878 goes live 
|| 04/12/22  GAR 22.05.15 (592290) Added sort by project task due date setting in client portal / project details
|| 04/12/22  RLB 22.05.15 (587411) change labor for option to filter completed on deliverablesBoard
|| 04/18/22  WDF 22.05.15 (591615) change ProjectStatus and ProjectBillingStatus to SelectList on productionDash
|| 04/18/22  CRG 22.05.15 (565772) Added DefaultTrackBudget to projectSchedule
|| 04/18/22  WDF 22.05.15 (595682) Added hideCompletePct to clientPortal
|| 05/09/22  WDF 22.05.15 (595682B) Change hideCompletePct to showCompletePct in clientPortal
|| 05/13/22  RLB 22.06.19 (590887) Added to do board setting for hiding Client, project etc.. and added type to grouping and sorting options
|| 05/24/22  RLS 22.06.19 (596984) Added productionDashRemainingLaborBudget and productionDashRemainingExpenseBudget. Also fixed a typo in Current Budget Expense Gross in productionDash and in productionDashPlanning
|| 05/23/22  RLB 22.06.19 (599630) added fields for new multirow update
|| 06/15/22  RLB 22.07.17 (595567) Added tracking forms options to myNotifications
|| 06/21/22  RLB 22.07.17 (599080) Added staff schedule week detail 
|| 06/27/22  WDF 22.07.17 (603776) Added KeyPeople to ''myTasks'' group
|| 07/05/22  GAR 22.07.17 (598563) Added CustomerID, CompanyName, CampaignID, and CampaignName to ioTraffic and boTraffic grids
|| 07/07/22  AMP 22.07.24 (604434) Added Retainer Name to Production Dash
|| 07/11/22  GAR 22.08.14 (600901) Added forecast detail grid column project end date
|| 07/12/22  RLS 22.08.14 (604984) Added showProjectTrackingForms to the projectDashBoard section
|| 07/27/22  GHL 22.08.14 (451878) Setting now @GLCompaniesWithForeignCurrencies = 1 to display info on GL companies diff currency
|| 08/04/22  AMP 22.09.18 (606737) Added Billing Method to the Production Dash
|| 08/18/22  GAR 22.09.18 (609310) Added approver name as an available column in the Vendor Invoice Approvals grid
|| 09/02/22  RLB 22.09.18 (608687,608688) Added to option on deliverable review page
|| 09/19/22  RLS 22.10.16 (610385) Added totalPauseHours to TimesheetApprovals, TimesheetRejections and TimesheetUnsubmitted
|| 09/19/22  RLS 22.10.16 (612766) Added timesheetUnsubmitted
|| 09/20/22  GAR 22.10.16 (DEV2605) Added services_AvalaraTaxCode to the Admin Screens - Service Setup section
|| 09/21/22  RLB 22.10.16 (608687) changed label
|| 09/21/22  GAR 22.10.16 (DEV2605) Added avalaraTaxCode to the Admin Screens - Billing Item Setup section
|| 09/21/22  GAR 22.10.16 (DEV2605) Added avalaraTaxCode to the Admin Screens - Project Type Setup section
|| 10/24/22  AMP 22.12.18 (610063)  Added Materials Sent and Materials Sent Date to the Broadcast(boTraffic) and Print(ioTraffic)
|| 10/25/22  GAR 22.12.18 (616959)  Added Budget Amount to Worksheets to Approve (billingToday_7)
|| 11/09/22  GAR 22.12.18 (618114)  Added Conversations Count to Project Schedule
|| 11/14/22  RLB 22.12.18 (618115)  maybe project type into a select list on myTasks
|| 11/30/22  RLS 22.12.18 (618630)  Added InternalApprovalDate field to the estimateList section
|| 12/05/22  AMP 23.01.15 (618868)  Added Total with Tax to Vendor Invoices
|| 12/08/22  GAR 23.01.15 (622519)  Added Campaign Edit seetting - to prevent Campaign ID from being edited
|| 12/19/22  RLB 23.01.15 (623076) added ProjectToBillRemainingNoTax and ProjectToBillRemainingWithTax to campaignBudget
|| 01/10/23  GAR 23.02.19 (DEV2605) Added avalaraTaxCode to the Admin Screens - Broadcast Items Setup, Print and Digital Items, Purchase Items Setup, Expense Report Items sections
|| 01/11/23  RLS 23.02.19 (622336)  Added ActiveEstimates and InactiveEstimates to globalsearch
|| 01/11/23  GAR 22.02.19 (624263)  Added ApprovedTotal to Estimate List Settings
|| 01/19/23  MCM 22.02.19 (612387)  Added InvoiceOpenAmount to Accrued Order Settings
|| 01/25/23  RLS 23.02.19 (626814)  Added ACH Enabled to payvouchers
|| 03/10/23  RLB 23.04.16 (629165)  added service color to serviceSetup
|| 03/15/23  RLS 23.04.16 (628601)  Added StartDate and EndDate to the connectionsCampaigns section
|| 11/14/22  RLB 23.04.16 (632084)  added timeline segment to mytask
|| 03/23/23  MCM 23.04.16 (630378)  Added journal entry approval items
|| 03/29/23  RLS 23.04.16 (631456)  Added campBudgetGetLaborRateFrom
|| 04/03/23  RLB 23.05.14 (633964)  Added Produce Name to productionDash, productionDashPlanning and myTasks
|| 04/05/22  MAS 23.05.14 (629790)  Added Credit Card Connector Comment
|| 04/05/23  AMP 23.05.14 (631585)  Corrected the order under Today Purchasing -> My Open Items Only will be displayed under Open Items
|| 04/03/23  RLB 23.05.14 (632548)  adding traffic comment to staffScheduleWeekDetail and staffScheduleDayDetail
|| 04/12/23  GAR 23.05.14 (631174)  Added Show Contingency to the Estimate Edit Settings.
|| 04/17/23  RLB 23.05.14 (632486)  Added add project to dos to clientPortal
|| 04/19/23  RLB 23.05.14 (633165)  Added added options for  Open To Do Items Only and Open Deliverables Only to Traffic RM
|| 04/19/23  RLS 23.05.14 (631259)  Added campBudgetProjectHoursAfterWriteoff
|| 05/12/23  AMP 23.06.18 (632148)  Added ''Days Out From Today'' to Today Media -> Orders Needing Attention
|| 05/26/23  CRG 23.06.18 (622919)  Added ''No Time Entry'' column to the projectSchedule grid
|| 06/02/23  RLS 23.07.16 (634668)  Added ProjectStatus to the campign budget section
|| 06/07/23  AMP 23.08.20 (633543)  Added Scheduled to Misc Costs section
|| 06/27/23  RLB 23.07.16 (631684)  Added Show other sales person option on salesDashboard
|| 06/29/23  AMP 23.09.17 (637168)  Added Detail Date Range to the Accrued Order Detail section
|| 06/30/23  AMP 23.07.23 (644091)  Added GL Company to Production Dash 
|| 07/10/23  AMP 23.08.20 (636196)  Added Marked as Billed Expenses and Marked as Billed Labor to Billing Today
|| 07/10/23  AMP 24.01.14 (644720)  Added Posting Date to the Approvals -> Credit Card Approval
|| 07/12/23  RLS 23.08.20 (644618)  Added PlanningProjectName to productionDash
|| 07/14/23  AMP 23.09.17 (637239)  Added Total Budget to the Forecast Details Settings
|| 08/01/23  AMP 23.09.17 (635756)  Added Markup to the Credit Card Connector
|| 08/22/23  CRG 23.09.17 (641607)  Added ShowPlanningProject to Add Project Settings
|| 08/25/23  RLB 23.09.17 (649026)  Added CampaignBudgetHoursRemainingP and CampaignBudgetRemainingP on campaignBudget removed and changed
|| 09/05/23  RLB 23.10.15 (649724)  Added project Type to productionCampProjects
|| 09/06/23  AMP 23.10.15 (650736)  Added Descripiton to the Unapproved Transactions
|| 09/15/23  AMP 23.10.15 (635756)  Added the More menu for the display options to the Split Projects Panel on the Credit Card Connector
|| 09/21/23  MCM 23.10.15 (651682)  removing CampaignBudgetHoursRemainingP and CampaignBudgetRemainingP on campaignBudget since they''re not sure about 649026
|| 09/27/23  RLS 23.10.15 (650572)  Added mytaskNextSteps to the My Tasks section
|| 09/27/23  RLB 23.10.15 (651884)  Added project column to trafficCalendar and project, Summary task and Segment to campaignSchedule
|| 09/29/23  AMP 23.10.15 (631719)  Added the ability to modify the custom fields on the IO and BO traffic screens in the grid
|| 10/02/23  MCM 23.10.15 (628804)  Added FastPay and Coupa to the Print Checks Payment Types
|| 10/04/23  CRG 23.11.19 (647340)  Added Must Finish On when Pred Complete to Project Schedule grid
|| 10/18/23  RLB 23.09.17 (649026)  Added campBudgetGrossRemainingCP and campBudgetHoursRemainingCP on campaignBudget
|| 10/20/23  RLS 23.11.19 (650272)  Added campBudgetCampaignBudgetUnbilledProjectRemaining to campaignBudget
|| 10/27/23  AMP 23.12.17 (651259)  Added Charge Reference to the Credit Card Connector
|| 11/08/23  AMP 23.12.17 (648523)  Added Billing Manager to the Generate Billing Worksheets
|| 12/06/23  CRG 24.01.14 (658230)  Changed label for prjScheduleNoTimeEntry
|| 12/18/23  RLB 24.01.14 (656836)  added conversation filter to today pages Only show Project Conversations sent to me that have the project tab
|| 12/21/23  AMP 24.01.21 (657972)  Added Project Status to the Forecast Detail Grid
*/

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tRecentFavorite]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[tRecentFavorite]', 'U') IS NULL
CREATE TABLE [dbo].[tRecentFavorite]
(
[CompanyKey] [int] NOT NULL,
[UserKey] [int] NOT NULL,
[Entity] [varchar] (50) NOT NULL,
[EntityKey] [int] NOT NULL,
[Favorite] [tinyint] NULL,
[Recent] [tinyint] NULL,
[DateRecent] [smalldatetime] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tRecentFavorite] on [dbo].[tRecentFavorite]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tRecentFavorite]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tRecentFavorite]', 'U'))
ALTER TABLE [dbo].[tRecentFavorite] ADD CONSTRAINT [PK_tRecentFavorite] PRIMARY KEY CLUSTERED ([CompanyKey], [UserKey], [Entity], [EntityKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptRecentFavoriteRecordRecent]'
GO
IF OBJECT_ID(N'[dbo].[sptRecentFavoriteRecordRecent]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptRecentFavoriteRecordRecent]
(
	@CompanyKey int,
	@UserKey int,
	@Entity varchar(50),
	@EntityKey int
)

as --Encrypt

/*
|| When      Who Rel        What
|| 07/06/26  GG  26.07.01   Created - generic recent tracker for any entity (replaces sptWidgetDashRecentUpsert).
||                          Marks Recent=1 with a timestamp, caps at the 10 newest per user/entity.
*/

Declare @Now datetime
Select @Now = getutcdate()

if exists (Select 1 from tRecentFavorite (nolock)
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey)
begin
	Update tRecentFavorite Set Recent = 1, DateRecent = @Now
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey
end
else
begin
	Insert into tRecentFavorite (CompanyKey, UserKey, Entity, EntityKey, Favorite, Recent, DateRecent)
	Values (@CompanyKey, @UserKey, @Entity, @EntityKey, 0, 1, @Now)
end

-- Keep only the 10 most-recent for this user/entity.
Declare @Keep Table ( EntityKey int )
Insert into @Keep ( EntityKey )
Select TOP 10 EntityKey
from tRecentFavorite (nolock)
Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and ISNULL(Recent, 0) = 1
Order by DateRecent desc

-- Recents that fell out and are also favorites: keep the row, just clear the recent flag.
Update tRecentFavorite Set Recent = 0, DateRecent = null
Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity
  and ISNULL(Recent, 0) = 1 and ISNULL(Favorite, 0) = 1
  and EntityKey not in (Select EntityKey from @Keep)

-- Recents that fell out and are not favorites: remove the row entirely.
Delete from tRecentFavorite
Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity
  and ISNULL(Recent, 0) = 1 and ISNULL(Favorite, 0) = 0
  and EntityKey not in (Select EntityKey from @Keep)
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spProcessWIPWorksheetRetainer]'
GO
IF OBJECT_ID(N'[dbo].[spProcessWIPWorksheetRetainer]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spProcessWIPWorksheetRetainer]
	(
	@NewInvoiceKey INT
	,@DefaultSalesAccountKey INT
	,@DefaultClassKey INT
	,@WorkTypeKey INT
	,@PostSalesUsingDetail INT
	)

AS --Encrypt

  /*
  || When   Who         Rel    What
  || GHL    06/29/07    8.5    Added new fields OfficeKey, DepartmentKey
  || GHL    07/31/07    8.5    Removed refs to expense types
  || GHL    08/30/07    8434   Bug 12318. Changed conditions for setting InvoiceLineKey on expenses
  || GHL    09/20/07    8437   Bug 13169. Added retainer description, this is a new field  
  || GHL    09/21/07    8437   Complete rewrite for Enh 13169
  ||                           must be able to invoice retainers by client (see pseudocode below) 
  || GHL    11/02/07    8440  (15376) Use TranCount > 0 rather than Amount Billed <> 0 to
  ||                           determine if an invoice line must be created (because +750 - 750 = 0
  ||                           causing invoice line to be missing)  
  || GHL    09/03/09    10.509 (60144) Include OfficeKey from the retainer   
  || 01/22/10 GHL 10.517 (69011) Changed retainer amount logic since we can have amounts <0  
  || 10/04/13 GHL 10.573 Using now PTotalCost for multi currency
  || 01/25/17 GHL 10.612 Using now sptInvoiceLineInsertMassBilling vs sptInvoiceLineInsert for perfo  
  || 02/09/21 MCM 22.03x (585358) Changed the verbiage from "extra expenses" to "extra charges"
  || 08/15/22 AMP 22.090 (604178) Added Department as an option on the Retainer Setup if GL Tracking Options has Show/Require Depts enabled
  || 10/22/24 MFT 24.100 (622384) Added check for existing InvoiceLineKey in #tProcWIPKeys before updating lines as billed
  || 07/28/26 MFT 26.08.01 (729267) Added BillExpensesByItem: bill extra charges one invoice line per Item/Service
  || 07/28/26 MFT 26.08.01 (729267) BillExpensesByItem: added a parent "Expenses" summary line containing the per-Item/Service lines
  || 07/28/26 MFT 26.08.01 (729267) BillExpensesByItem: per-Item/Service lines now carry the Item/Service Taxable flags so tax is applied
 */

/*
for each #tProcWIPKeys
	if EntityType = ''Retainer'' and AmountBilled > 0
		insert invoice line
end for

create 1 invoice line for all #tProcWIPKeys where LineFormat = 1

for each ProjectKey in #tProcWIPKeys where LineFormat = 2
	create 1 invoice line
end for

*/

	SET NOCOUNT ON
	
Declare @RetainerKey INT
Declare @NewInvoiceLineKey int
Declare @RetVal int
Declare @ProjectName varchar(100)
Declare @ProjectKey int
Declare @InvoiceDate datetime
Declare @Title VARCHAR(100)
Declare @Description VARCHAR(1500)
Declare @ExtraTitle VARCHAR(100) -- this is the title for the extra charges where LineFormat = 1
Declare @SalesAccountKey int
Declare @AmountBilled money
Declare @TranCount money
Declare @ProjectClassKey int
Declare @ClassKey int
Declare @OfficeKey int
Declare @ProjectCount int
Declare @DepartmentKey int

-- used when BillExpensesByItem = 1 (extra charges billed one line per Item/Service)
Declare @CurIsService tinyint
Declare @CurItemKey int
Declare @CurItemName varchar(250)
Declare @CurAmount money
Declare @CurLineOrder int
Declare @CurEntityKey int
Declare @CurEntity varchar(50)
Declare @CurTaxable tinyint
Declare @CurTaxable2 tinyint
Declare @ExpensesLineKey int   -- parent "Expenses" summary line that groups the per-Item/Service lines


	SELECT @InvoiceDate = InvoiceDate
	FROM   tInvoice (NOLOCK)
	WHERE  InvoiceKey = @NewInvoiceKey
	
	-- Can only set the line subject to the retainer''s title if we have a single retainer
	IF (SELECT COUNT(DISTINCT RetainerKey) FROM #tProcWIPKeys WHERE EntityType = ''Retainer'') = 1
		SELECT @ExtraTitle = r.Title + '' - Extra charges''
		FROM   tRetainer r (NOLOCK)
			INNER JOIN #tProcWIPKeys k ON r.RetainerKey = k.RetainerKey 
		WHERE k.EntityType = ''Retainer''
	ELSE
		SELECT @ExtraTitle = '' Extra charges''

	
	-- First process all the true retainer amounts
	SELECT @RetainerKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @RetainerKey = MIN(RetainerKey)
		FROM   #tProcWIPKeys
		WHERE  EntityType = ''Retainer''
		--AND    AmountBilled > 0 -- because now the retainer amounts can be <0, =0, >0
		AND    RetainerKey > @RetainerKey
		
		IF @RetainerKey IS NULL
			BREAK
			
		SELECT 	@AmountBilled = AmountBilled -- that would be the retainer amount		
		FROM    #tProcWIPKeys
		WHERE   EntityType = ''Retainer''
		AND     RetainerKey = @RetainerKey  -- EntityKey would work too 
		
		SELECT @Title			= Title 
			  ,@Description		= Description
			  ,@SalesAccountKey = SalesAccountKey
		      ,@OfficeKey       = OfficeKey
		      ,@ClassKey        = ClassKey
			  ,@DepartmentKey   = DepartmentKey
		FROM   tRetainer (NOLOCK)
		WHERE  RetainerKey = @RetainerKey 
			
		IF ISNULL(@SalesAccountKey, 0) = 0
			SELECT @SalesAccountKey = @DefaultSalesAccountKey

		IF ISNULL(@ClassKey, 0) = 0
			SELECT @ClassKey = @DefaultClassKey
			
		SELECT @ProjectCount = COUNT(*) FROM tProject (NOLOCK) WHERE RetainerKey = @RetainerKey
		
		IF @ProjectCount = 1
			SELECT @ProjectKey = ProjectKey FROM tProject (NOLOCK) WHERE RetainerKey = @RetainerKey
		ELSE
			SELECT @ProjectKey = NULL
				
		-- One line for the retainer amount
		exec @RetVal = sptInvoiceLineInsertMassBilling
				@NewInvoiceKey				-- Invoice Key
				,@ProjectKey						-- ProjectKey
				,NULL						-- TaskKey
				,@Title						-- Line Subject
				,@Description    			-- Line description
				,1               			-- Bill From: Important to distinguish Retainer Amount from extra 
				,0							-- Quantity
				,0							-- Unit Amount
				,@AmountBilled				-- Line Amount
				,2							-- line type
				,0							-- parent line key
				,@SalesAccountKey			-- Default Sales AccountKey
				,@ClassKey           -- Class Key
				,0							-- Taxable
				,0							-- Taxable2
				,@WorkTypeKey				-- Work TypeKey
   				,0							-- always 0 as the amount is on the line
				,NULL						-- Entity
				,NULL						-- EntityKey	
				,@OfficeKey					-- OfficeKey
				,@DepartmentKey		    	-- DepartmentKey	  						  
				,@NewInvoiceLineKey output

		if @RetVal <> 1 
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17					   	
			end
		if @@ERROR <> 0 
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17					   	
			end			           		   		
		
		Update tInvoiceLine Set RetainerKey = @RetainerKey Where InvoiceLineKey = @NewInvoiceLineKey
		if @RetVal <> 1 
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17					   	
			end
	
	END
	
	-- Now the transactions where the line format = 1 (one invoice line only)
	-- Rows flagged BillExpensesByItem = 1 are handled separately below (one line per Item/Service)
	SELECT @AmountBilled = ISNULL(SUM(AmountBilled), 0)
			,@TranCount = COUNT(*)
	FROM   #tProcWIPKeys
	WHERE  Action = 1 AND LineFormat = 1 AND ISNULL(BillExpensesByItem, 0) = 0

	--IF @AmountBilled <> 0
	IF @TranCount > 0
	BEGIN

		-- if we only have ONE project put on the line
		IF (SELECT COUNT(DISTINCT ProjectKey) FROM #tProcWIPKeys
			WHERE Action = 1 AND LineFormat = 1 AND ISNULL(BillExpensesByItem, 0) = 0) = 1
				SELECT @ProjectKey = ProjectKey FROM #tProcWIPKeys
				WHERE Action = 1 AND LineFormat = 1 AND ISNULL(BillExpensesByItem, 0) = 0
		ELSE
				SELECT @ProjectKey = NULL
					
		exec @RetVal = sptInvoiceLineInsertMassBilling
					  @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,NULL							-- TaskKey
					  ,@ExtraTitle					-- Line Subject
					  ,null    						-- Line description
					  ,2               				-- Bill From: Important to distinguish between extra and retainer 
					  ,0							-- Quantity
					  ,0							-- Unit Amount
					  ,@AmountBilled				-- Line Amount
					  ,2							-- line type
					  ,0							-- parent line key
					  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
					  ,@DefaultClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,@WorkTypeKey					-- Work TypeKey
   					  ,@PostSalesUsingDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey						  						  
    				  ,NULL							-- OfficeKey
					  ,@DepartmentKey				-- DepartmentKey	  						  
					  ,@NewInvoiceLineKey output

		if @RetVal <> 1 
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17					   	
			end
		if @@ERROR <> 0 
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17					   	
			end			           		   		

		UPDATE tInvoiceLine SET RetainerKey = @RetainerKey WHERE InvoiceLineKey = @NewInvoiceLineKey
		UPDATE #tProcWIPKeys
		SET    InvoiceLineKey = @NewInvoiceLineKey
		WHERE  Action = 1
		AND    LineFormat = 1
		AND    ISNULL(BillExpensesByItem, 0) = 0
	END
	  
	
	-- Now process the transactions where the line format = 2 (one invoice line per project)
	SELECT @ProjectKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @ProjectKey = MIN(ProjectKey)
		FROM   #tProcWIPKeys
		WHERE  Action = 1
		AND    LineFormat = 2
		AND    ISNULL(BillExpensesByItem, 0) = 0
		AND    ProjectKey > @ProjectKey

		IF @ProjectKey IS NULL
			BREAK

		SELECT @AmountBilled = ISNULL(SUM(AmountBilled), 0)
			  ,@TranCount = COUNT(*)
		FROM #tProcWIPKeys WHERE Action = 1
		AND LineFormat = 2
		AND ISNULL(BillExpensesByItem, 0) = 0
		AND ProjectKey = @ProjectKey
		
		--IF @AmountBilled <> 0
		IF @TranCount > 0
		BEGIN
		
			SELECT @ProjectName = ProjectName + '' - Extra charges''
				   ,@ProjectClassKey = ClassKey
				   ,@OfficeKey = OfficeKey				 
			FROM   tProject (NOLOCK)
			WHERE  ProjectKey = @ProjectKey
			
			IF ISNULL(@ProjectClassKey, 0) > 0
				SELECT @ClassKey = @ProjectClassKey
			ELSE
				SELECT @ClassKey = @DefaultClassKey
			 
			exec @RetVal = sptInvoiceLineInsertMassBilling
						@NewInvoiceKey				-- Invoice Key
						,@ProjectKey				-- ProjectKey
						,NULL						-- TaskKey
						,@ProjectName				-- Line Subject
						,null    					-- Line description
						,2               			-- Bill From: Important to distinguish between extra and retainer 
						,0							-- Quantity
						,0							-- Unit Amount
						,@AmountBilled				-- Line Amount
						,2							-- line type
						,0							-- parent line key
						,@DefaultSalesAccountKey	-- Default Sales AccountKey
						,@ClassKey					-- Class Key
						,0							-- Taxable
						,0							-- Taxable2
						,@WorkTypeKey				-- Work TypeKey
   						,@PostSalesUsingDetail
						,NULL						-- Entity
						,NULL						-- EntityKey						  						  
    					,@OfficeKey					-- OfficeKey
						,@DepartmentKey				-- DepartmentKey	  						  
						,@NewInvoiceLineKey output

			if @RetVal <> 1 
				begin
				exec sptInvoiceDelete @NewInvoiceKey
				return -17					   	
				end
			if @@ERROR <> 0 
				begin
				exec sptInvoiceDelete @NewInvoiceKey
				return -17					   	
				end			           		   		

			UPDATE #tProcWIPKeys
			SET    InvoiceLineKey = @NewInvoiceLineKey
			WHERE  Action = 1
			AND    LineFormat = 2
			AND    ISNULL(BillExpensesByItem, 0) = 0
			AND    ProjectKey = @ProjectKey

		END

	END

	-- Now the extra charges where BillExpensesByItem = 1 (one invoice line per Item/Service).
	-- Each distinct Item (expenses) or Service (labor billed as an extra) gets its own line,
	-- regardless of the retainer''s one-line/one-per-project LineFormat setting.
	IF EXISTS (SELECT 1 FROM #tProcWIPKeys WHERE Action = 1 AND ISNULL(BillExpensesByItem, 0) = 1)
	BEGIN
		CREATE TABLE #extraByItem (
			 IsService tinyint NULL			-- 1 = Service (labor), 0 = Item (expense)
			,ItemKey int NULL
			,ItemName varchar(250) NULL
			,Amount money NULL
			,RetainerKey int NULL
			,ProjectKey int NULL
			,LineOrder int NULL
			,Taxable tinyint NULL
			,Taxable2 tinyint NULL
		)

		INSERT #extraByItem (IsService, ItemKey, Amount, RetainerKey, ProjectKey)
		SELECT CASE WHEN EntityType = ''Time'' THEN 1 ELSE 0 END
			  ,ISNULL(ItemKey, 0)
			  ,SUM(ISNULL(AmountBilled, 0))
			  ,MIN(RetainerKey)
			  ,CASE WHEN COUNT(DISTINCT ProjectKey) = 1 THEN MIN(ProjectKey) ELSE NULL END
		FROM   #tProcWIPKeys
		WHERE  Action = 1
		AND    ISNULL(BillExpensesByItem, 0) = 1
		GROUP BY CASE WHEN EntityType = ''Time'' THEN 1 ELSE 0 END, ISNULL(ItemKey, 0)

		-- Resolve the display name and taxable flags: Service for labor, Item for expenses
		UPDATE #extraByItem
		SET    ItemName = s.Description
			  ,Taxable  = s.Taxable
			  ,Taxable2 = s.Taxable2
		FROM   tService s (NOLOCK)
		WHERE  #extraByItem.IsService = 1
		AND    #extraByItem.ItemKey = s.ServiceKey

		UPDATE #extraByItem
		SET    ItemName = i.ItemName
			  ,Taxable  = i.Taxable
			  ,Taxable2 = i.Taxable2
		FROM   tItem i (NOLOCK)
		WHERE  #extraByItem.IsService = 0
		AND    #extraByItem.ItemKey = i.ItemKey

		UPDATE #extraByItem
		SET    ItemName = CASE WHEN IsService = 1 THEN ''[No Service]'' ELSE ''[No Item]'' END
		WHERE  ItemKey = 0 OR ItemName IS NULL

		UPDATE #extraByItem
		SET    Taxable  = ISNULL(Taxable, 0)
			  ,Taxable2 = ISNULL(Taxable2, 0)

		-- Establish a stable, alphabetical line order
		SELECT @CurLineOrder = 1
		SELECT @CurItemName = ''''
		WHILE (1 = 1)
		BEGIN
			SELECT @CurItemName = MIN(ItemName) FROM #extraByItem WHERE ItemName > @CurItemName
			IF @CurItemName IS NULL
				BREAK
			UPDATE #extraByItem SET LineOrder = @CurLineOrder WHERE ItemName = @CurItemName
			SELECT @CurLineOrder = @CurLineOrder + 1
		END

		-- Add a parent "Expenses" summary line (amount 0) that will contain all per-Item/Service lines.
		-- Amount stays 0 so the invoice total is not double-counted (sptInvoiceRecalcAmounts sums every line).
		exec @RetVal = sptInvoiceLineInsertMassBilling
				  @NewInvoiceKey				-- Invoice Key
				  ,NULL							-- ProjectKey
				  ,NULL							-- TaskKey
				  ,''Expenses''					-- Line Subject
				  ,null							-- Line description
				  ,2							-- Bill From: Important to distinguish between extra and retainer
				  ,0							-- Quantity
				  ,0							-- Unit Amount
				  ,0							-- Line Amount (header only - children carry the amounts)
				  ,1							-- line type (1 = header/summary)
				  ,0							-- parent line key
				  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
				  ,@DefaultClassKey				-- Class Key
				  ,0							-- Taxable
				  ,0							-- Taxable2
				  ,@WorkTypeKey					-- Work TypeKey
				  ,@PostSalesUsingDetail
				  ,NULL							-- Entity
				  ,NULL							-- EntityKey
				  ,NULL							-- OfficeKey
				  ,@DepartmentKey				-- DepartmentKey
				  ,@ExpensesLineKey output

		if @RetVal <> 1
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17
			end
		if @@ERROR <> 0
			begin
			exec sptInvoiceDelete @NewInvoiceKey
			return -17
			end

		SELECT @CurLineOrder = MIN(LineOrder) FROM #extraByItem
		WHILE @CurLineOrder IS NOT NULL
		BEGIN
			SELECT @CurIsService = IsService
				  ,@CurItemKey   = ItemKey
				  ,@CurItemName  = ItemName
				  ,@CurAmount    = ISNULL(Amount, 0)
				  ,@RetainerKey  = RetainerKey
				  ,@ProjectKey   = ProjectKey
				  ,@CurTaxable   = ISNULL(Taxable, 0)
				  ,@CurTaxable2  = ISNULL(Taxable2, 0)
			FROM   #extraByItem
			WHERE  LineOrder = @CurLineOrder

			SELECT @CurEntity = CASE WHEN @CurIsService = 1 THEN ''tService'' ELSE ''tItem'' END
			SELECT @CurEntityKey = NULL
			IF @CurItemKey > 0
				SELECT @CurEntityKey = @CurItemKey

			exec @RetVal = sptInvoiceLineInsertMassBilling
					  @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,NULL							-- TaskKey
					  ,@CurItemName					-- Line Subject
					  ,null							-- Line description
					  ,2							-- Bill From: Important to distinguish between extra and retainer
					  ,0							-- Quantity
					  ,0							-- Unit Amount
					  ,@CurAmount					-- Line Amount
					  ,2							-- line type
					  ,@ExpensesLineKey				-- parent line key (nested under the "Expenses" summary line)
					  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
					  ,@DefaultClassKey				-- Class Key
					  ,@CurTaxable					-- Taxable (from the Item/Service master)
					  ,@CurTaxable2					-- Taxable2 (from the Item/Service master)
					  ,@WorkTypeKey					-- Work TypeKey
					  ,@PostSalesUsingDetail
					  ,@CurEntity					-- Entity
					  ,@CurEntityKey				-- EntityKey
					  ,NULL							-- OfficeKey
					  ,@DepartmentKey				-- DepartmentKey
					  ,@NewInvoiceLineKey output

			if @RetVal <> 1
				begin
				exec sptInvoiceDelete @NewInvoiceKey
				return -17
				end
			if @@ERROR <> 0
				begin
				exec sptInvoiceDelete @NewInvoiceKey
				return -17
				end

			UPDATE tInvoiceLine SET RetainerKey = @RetainerKey WHERE InvoiceLineKey = @NewInvoiceLineKey

			-- Link the source transactions for this Item/Service to the new line so they are marked billed below
			UPDATE #tProcWIPKeys
			SET    InvoiceLineKey = @NewInvoiceLineKey
			WHERE  Action = 1
			AND    ISNULL(BillExpensesByItem, 0) = 1
			AND    CASE WHEN EntityType = ''Time'' THEN 1 ELSE 0 END = @CurIsService
			AND    ISNULL(ItemKey, 0) = @CurItemKey

			SELECT @CurLineOrder = MIN(LineOrder) FROM #extraByItem WHERE LineOrder > @CurLineOrder
		END
	END
	
	/*
	|| All transactions must be marked as billed with proper InvoiceLineKey
	*/
			
	update tTime
		set InvoiceLineKey = w.InvoiceLineKey
			,BilledService = tTime.ServiceKey
			,BilledHours = tTime.ActualHours
			,BilledRate = tTime.ActualRate
			,DateBilled = @InvoiceDate
		from #tProcWIPKeys w 
		where w.EntityType = ''Time''
		and tTime.TimeKey = cast(w.EntityKey as uniqueidentifier)					  
	if @@ERROR <> 0 
		begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -8					   	
		end

	update tExpenseReceipt
		set InvoiceLineKey = w.InvoiceLineKey
			,AmountBilled = BillableCost
			,DateBilled = @InvoiceDate
		from #tProcWIPKeys w
		where w.EntityType = ''Expense''
		and tExpenseReceipt.ExpenseReceiptKey = cast(w.EntityKey as integer)
	if @@ERROR <> 0 
		begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -8					   	
		end
	
	--misc expenses
	update tMiscCost
		set InvoiceLineKey = w.InvoiceLineKey
			,AmountBilled = BillableCost
			,DateBilled = @InvoiceDate
		from #tProcWIPKeys w
		where w.EntityType = ''MiscExpense''
		and tMiscCost.MiscCostKey = cast(w.EntityKey as integer)
	if @@ERROR <> 0 
		begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -9					 	
		end
		
	--voucher	   
	update tVoucherDetail
		set InvoiceLineKey = w.InvoiceLineKey
			,AmountBilled = BillableCost
			,DateBilled = @InvoiceDate
		from #tProcWIPKeys w
		where w.EntityType = ''Voucher''
		and tVoucherDetail.VoucherDetailKey = cast(w.EntityKey as integer)
	if @@ERROR <> 0 
		begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -10				   	
		end
		
	--Order	   
	update tPurchaseOrderDetail
		set InvoiceLineKey = w.InvoiceLineKey
			,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
			When 0 then isnull(BillableCost,0)
			When 1 then isnull(PTotalCost,isnull(TotalCost,0))
			When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
			,DateBilled = @InvoiceDate
		from #tProcWIPKeys w, tPurchaseOrder po
		where w.EntityType = ''Order''
		and tPurchaseOrderDetail.PurchaseOrderDetailKey = cast(w.EntityKey as integer)
		and po.PurchaseOrderKey = tPurchaseOrderDetail.PurchaseOrderKey
	if @@ERROR <> 0 
		begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -10				   	
		end
	
	UPDATE tRetainer
	SET    tRetainer.LastBillingDate = @InvoiceDate
	FROM   #tProcWIPKeys
	WHERE  tRetainer.RetainerKey = #tProcWIPKeys.RetainerKey
	--AND    #tProcWIPKeys.AmountBilled > 0 (because can be <0,=0, >0)
	AND    #tProcWIPKeys.EntityType = ''Retainer''
	
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spProcessWIPWorksheet]'
GO
IF OBJECT_ID(N'[dbo].[spProcessWIPWorksheet]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spProcessWIPWorksheet]
	 @ProcessKey int	-- ProjectKey, RetainerKey or ClientKey depending on InvoiceBy
	,@InvoiceBy int		-- 0: Invoice By Project, 1: Invoice By Client, 2: Invoice By Client Parent,
						-- 3: Invoice By Estimate, 4: Invoice By Retainer Per Client,  5: Invoice By Retainer Per Retainer
	,@Rollup int		-- 0: 1 Line Item
						-- 1: 1 Line per Task (only applicable if invoiced by Project)
						-- 2: 1 Line per Service
						-- 3: 1 line per Billing Item
						-- 4: 1 Line per Project  (only applicable if invoiced by Client or Estimate)
						-- 5: 1 Line per Estimate (only applicable if invoiced by Client or Project)
						-- 6: 1 Line per Client   (only applicable if invoiced by Parent Company)
						-- 7: 1 line per ProjectType + Project (only applicable if invoiced per Client or Parent Client)
						-- 8: 1 line per Billing Item then Item
						-- 9: 1 line per Project then Billing Item then Item
						--10: 1 line per Publication/Station (for new media screens)
						--11: 1 line per title (for Abelson/Taylor)
						--12: 1 line per title/service (for Abelson/Taylor)
						--13: 1 line per service/title (for Abelson/Taylor)
						--14: 1 line per service/item  
						--15: 1 line per Project then Billing Item (only applicable if invoiced by Client or Parent Client)
	,@UserKey int
	,@WriteOffReasonKey int
	,@PercentOfActual decimal(15,8)
	,@InvoiceDate smalldatetime = Null
	,@PostingDate smalldatetime = Null
	,@DefaultUIClassKey int = Null			-- Can be changed on screen on UI
	,@InvoiceByClassKey int = NULL			-- class for the entity, project, client, estimate, retainer
	,@GLCompanyKey int = NULL
	,@OfficeKey int = NULL
	,@CreateAsApproved INT = 0
	,@UILayoutKey int = null                -- only for Invoice By = 1 (Client) and Rollup =9 (Project/BillingItem/Item)
	,@CurrencyID varchar(10) = null
	,@WriteOffComment varchar(500) = NULL
	,@CreatedByKey int = NULL
	,@DepartmentKey int = NULL
	,@BillExpensesByItem int = 0			-- when 1 (retainer extras billed one line per Item/Service), route Rollup=0 to spProcessWIPWorksheetRetainer
AS --Encrypt

  /*
  || When     Who Rel   What
  || 09/28/06 GHL 8.35  Added validations section
  || 10/11/06 CRG 8.35  Added Emailed column.
  || 02/01/07 GHL 8.4   Added ClassKey parm to allow users to enter class when require classes
  ||                    Bug 8154 Partners Napier
  || 06/06/07 GHL 8.4.3 Bug 9416. Added checking of billing worksheets to validation section
  || 06/29/07 GHL 8.5   Added new parms GLCompanyKey and OfficeKey
  || 08/07/07 GHL 8.5   Added call to Invoice Summary
  || 09/21/07 GHL 8437  Changes for Enh 13169
  ||                    must be able to invoice several retainers by client in one invoice now
  || 09/26/07 GHL 8.5   Removed invoice summary since it is done in invoice recalc amounts
  || 02/08/08 GHL 8.504 (20788) Added Group by Project Type then Project
  || 04/08/08 GHL 8.508 (23712) Added new logic for classes
  || 06/18/08 GHL 8.513 added opening balance
  || 03/18/09 GHL 10.021 (37453) Added invoice lines per billing item then item
  || 10/21/09 GHL 10.513 Do not recalculate invoice sales taxes in sptInvoiceLineUpdateTotals since we do it at the end
  || 03/24/10 GHL 10.521 Added LayoutKey
  || 07/23/10 RLB 10.532 Change subject line to Media Estimane Name when creating invoice by Estimate
  || 12/27/10 GHL 10.539 (97889) Added rounding of AmountBilled * @PercentOfActual (12.99 * 101 % = 13.1199 = 13.12)
  || 08/12/11 RLB 10.547 (118561) Added a check of the transaction was written off because of the changes on an old issue 56327
  || 08/24/11 GHL 10.547 (118149) When invoicing per estimate, get primary contact info from the client
  || 04/26/12 GHL 10.555 (141647) Added CreateAsApproved param
  || 09/10/12 RLB 10.560 (87856) Changes made for enhancement...contact on retainer
  || 10/05/12 GHL 10.560 Added Rollup 9 (Project / Billing Item/Item) and @UILayoutKey
  || 05/22/13 GHL 10.568 (179110) Take Billing Address instead of null (default from company for address)
  || 07/23/13 GHL 10.570 (181721) Added setting of the campaigns when we invoice by project/client
  || 10/01/13 GHL 10.573 Added currency parameter to support multi currency
  || 11/04/13 GHL 10.573 (194532) Fixed query when getting number of campaigns (should be count(distinct ProjectKey))
  || 01/03/14 WDF 10.576 (188500) Pass UserKey to sptInvoiceInsert
  || 10/03/14 GHL 10.584 (230462) Added rollup by Publication/Station
  || 11/11/14 GHL 10.586 Added support for titles for Abelson Taylor
  || 12/03/14 GHL 10.587 (237117) Added rollup by service/item
  || 12/15/14 GHL 10.587 Added RateLevel and BilledComments to #labor (needed because they are edited on the BWS)
  || 01/21/15 GHL 10.588 (243227) Temporary fix to correct Rollup ''by task'' from the Project Transactions screen
  ||                     Was incorrectly set to ''by project'' on the UI
  || 03/19/15 GHL 10.590 Added setting of Hours on invoice lines for abelson taylor
  || 04/01/15 GHL 10.590 (252013) Added patch against PTotalCost with 3 digits from Media
  || 08/05/15 KMC 10.595 (264823) Added parameter to sptInvoiceInsert for when call is coming from Retainer process
  || 09/10/15 MCM 10.596 (266501) Added #tProcWIPKeysTime temp table because a client continued to get invalid cast from
  ||					  #tProcWIPKeys.entityKey to uniqueidentifier even though where clause was only looking for Time
  || 09/23/15 GHL 10.596 (271356) Added select * into
  || 04/12/16 MFT 10.603 Added @WriteOffComment
  || 08/22/16 GHL 10.607 If Bill % is not 1, calc BilledRate at 4 digits instead of 2, also removed cast to Decimal
  || 01/26/17 GHL 10.612 (329491) Added checking of error after inserts in #tProcWIPKeysTime so that if it fails, we abort the process
  || 02/28/17 GHL 10.613 (334769) Do not send the invoice for approval
  || 06/22/17 GHL 10.613 (338647) Apply PercentOfActual as a batch versus line by line
  || 08/14/17 GHL 10.619 (341875) customization for Owens Harkey..get taxes from vendor
  || 10/02/17 GHL 10.621 (363756) Added AR account info
  || 04/05/18 RLB 18.500 if there is no primary contact on a project try to set the primary contact from the client
  || 06/26/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
  || 07/11/18 GHL 18.800 (DEV1784 todo 4216) validate that the AR account matches the currency
  || 11/30/18 GHL 18.930 (433642) Pull the layout and the invoice template from retainer and set them on the invoice
  || 01/11/19 GHL 19.200 (439994) Added support for layouts in project and mass billing (by project or client) when the
  ||                      line format is ''Billing Item and Item'' (similar to ''Project and Billing Item and Item'')
  || 02/18/19 GHL 19.300 In the case (Invoice By Client and By Project/Billing Item/Item), do not set the LayoutKey to null
  ||                      if the user does not select a layout on the UI
  || 04/23/19 MFT 19.050 (455923) Added call to sptInvoiceLineApplyTaskOptions for Project Mass Billing by Task to apply Layout settings
  || 05/07/19 MFT 19.050 (452966) Added @CreatedByKey
  || 09/09/19 GHL 19.100 (454143) Added Rollup 15 - by project and billing item
  || 03/18/22 GHL 22.040 (590582) Added support for tProject.SetTaxableOnInvoice
  || 08/15/22 AMP 22.090 (604178) Added Department as an option on the Retainer Setup if GL Tracking Options has Show/Require Depts enabled
  || 11/30/22 MFT 22.120 (618633) Respecting Layout settings for Service/Item rollup
  || 12/16/24 MFT 25.010 (686350) Use TimeRateSheet InvoiceLabel if exists
  || 12/19/24 MFT 25.010 (690879) Apply DisplayOption to Invoice Lines on by Service (2) Invoice with Layout
  || 02/06/25 MCM 25.03x (694434) Wrapped RTRIM(LTRIM( around @NextTranNo when setting InvoiceNumber
  || 11/04/25 MCM 25.11.x (656423) Added Liability Account Key when calling sptInvoiceInsert
  || 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
  || 08/10/26 MFT 26.08.01 (729267) Added @BillExpensesByItem: route Rollup=0 to spProcessWIPWorksheetRetainer so per-Project retainer expense invoices are itemized
 */

declare @CompanyKey int
declare @ClientKey int
declare @ProjectKey int
declare @MediaEstimateKey int
declare @RetainerKey int
declare @CampaignKey int
declare @PCurrencyID varchar(10)
declare @IsForRetainer tinyint

if @InvoiceBy = 4 or @InvoiceBy = 5
	select @IsForRetainer = 1
else
	select @IsForRetainer = 0

-- if we invoice by project and the rollup is by project, change rollup to by task
if @InvoiceBy = 0 and @Rollup = 4
	select @Rollup = 1

if @InvoiceBy = 0
begin
	select @ProjectKey = @ProcessKey
	select @CompanyKey = CompanyKey
		  ,@PCurrencyID = CurrencyID
	from tProject (nolock) where ProjectKey = @ProjectKey

	-- The CurrencyID field should be set properly when called from the stored procs
	-- But not for the transactions screen, so get it now
	if @CurrencyID is null
		select @CurrencyID = @PCurrencyID
end
if @InvoiceBy in (1, 2, 4)
begin
	select @ClientKey = @ProcessKey
	select @CompanyKey = OwnerCompanyKey from tCompany (nolock) where CompanyKey = @ClientKey
end
if @InvoiceBy = 3
begin
	select @MediaEstimateKey = @ProcessKey
	select @CompanyKey = CompanyKey from tMediaEstimate (nolock) where MediaEstimateKey = @MediaEstimateKey
end
if @InvoiceBy = 5
begin
	-- we now point to retainer not the client because (87856)
	select @ClientKey = ClientKey from tRetainer (nolock) where RetainerKey = @ProcessKey
	select @CompanyKey = OwnerCompanyKey from tCompany (nolock) where CompanyKey = @ClientKey
end


-- Assume done in calling sp or web page
-- create table #tProcWIPKeys (EntityType varchar(20), EntityKey varchar(50), Action int) OR
-- create table #tProcWIPKeys (ProjectKey int, EntityType varchar(20), EntityKey varchar(50), Action int)
declare @NewInvoiceKey int
declare @BillingContact varchar(100)
declare @PrimaryContactKey int
declare @RetVal int
declare @TodaysDate smalldatetime
declare @DueDate smalldatetime
declare @DueDays int
declare @LineSubject varchar(100)
declare @WorkTypeKey int
declare @DefaultARAccountKey int
declare @DefaultSalesAccountKey int
declare @ARAccountKey int
Declare @SalesGLAccountKey int
Declare @PostSalesUsingDetail tinyint
Declare @InvoiceTemplateKey int
Declare @SalesTaxKey int, @SalesTax2Key int, @PaymentTermsKey int
Declare @RequireClasses tinyint
Declare @DefaultClassKey int
Declare @LayoutKey int
Declare @BillingAddressKey int
Declare @UseBillingTitles int -- this will indicate the Abelson Taylor company
Declare @UseMediaTaxes int -- this will indicate to pull the taxes from the vendor
declare @Customizations varchar(2000)
declare @SetTaxableOnInvoice int
declare @LayoutFromGLCompany int
declare @AdvBillAccountKey int
declare @LiabilityAccountKey int

	--09/10/15 - Adding this because #tProcWIPKeys.EnityKey isn''t always a GUID.  The execution plan for the one user is trying to do the join before the where clause on the billing for Ervin & Smith
	/*
	create table #tProcWIPKeysTime (RetainerKey int null
							,ProjectKey int null
							,EntityType varchar(20) null
							,EntityKey varchar(50) null
							,AmountBilled money null
							,Action int null
							,InvoiceLineKey int null
							,LineFormat int null)

	INSERT INTO #tProcWIPKeysTime SELECT * from #tProcWIPKeys WHERE EntityType = ''Time''
	*/
	select * into #tProcWIPKeysTime from #tProcWIPKeys WHERE EntityType = ''Time''
	if @@ERROR <> 0
		RETURN -1

	/*
	|| Validations
	*/
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeysTime  a
					INNER JOIN tTime b (NOLOCK) ON b.TimeKey = cast(a.EntityKey as uniqueidentifier)
				WHERE a.EntityType = ''Time''
				AND   b.InvoiceLineKey > 0
				)
			RETURN -100
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tMiscCost b (NOLOCK) ON b.MiscCostKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''MiscExpense''
				AND   b.InvoiceLineKey > 0
				)
			RETURN -100
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tExpenseReceipt b (NOLOCK) ON b.ExpenseReceiptKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''Expense''
				AND   b.InvoiceLineKey > 0
				)
			RETURN -100
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tVoucherDetail b (NOLOCK) ON b.VoucherDetailKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''Voucher''
				AND   b.InvoiceLineKey > 0
				)
			RETURN -100
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tPurchaseOrderDetail b (NOLOCK) ON b.PurchaseOrderDetailKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''Order''
				AND   b.InvoiceLineKey > 0
				)
			RETURN -100

	-- Check if anything is on a billing worksheet
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeysTime  a
					INNER JOIN tBillingDetail bd (NOLOCK) ON bd.EntityGuid = cast(a.EntityKey as uniqueidentifier)
					INNER JOIN tBilling b (NOLOCK) ON b.BillingKey = bd.BillingKey
				WHERE a.EntityType = ''Time''
				AND   bd.Entity = ''tTime''
				AND   b.CompanyKey = @CompanyKey
				AND   b.Status < 5
				)
			RETURN -101
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tBillingDetail bd (NOLOCK) ON bd.EntityKey = cast(a.EntityKey as integer)
					INNER JOIN tBilling b (NOLOCK) ON b.BillingKey = bd.BillingKey
				WHERE a.EntityType = ''MiscExpense''
				AND   bd.Entity = ''tMiscCost''
				AND   b.CompanyKey = @CompanyKey
				AND   b.Status < 5
				)
			RETURN -101
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tBillingDetail bd (NOLOCK) ON bd.EntityKey = cast(a.EntityKey as integer)
					INNER JOIN tBilling b (NOLOCK) ON b.BillingKey = bd.BillingKey
				WHERE a.EntityType = ''Expense''
				AND   bd.Entity = ''tExpenseReceipt''
				AND   b.CompanyKey = @CompanyKey
				AND   b.Status < 5
				)
			RETURN -101
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tBillingDetail bd (NOLOCK) ON bd.EntityKey = cast(a.EntityKey as integer)
					INNER JOIN tBilling b (NOLOCK) ON b.BillingKey = bd.BillingKey
				WHERE a.EntityType = ''Voucher''
				AND   bd.Entity = ''tVoucherDetail''
				AND   b.CompanyKey = @CompanyKey
				AND   b.Status < 5
				)
			RETURN -101
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tBillingDetail bd (NOLOCK) ON bd.EntityKey = cast(a.EntityKey as integer)
					INNER JOIN tBilling b (NOLOCK) ON b.BillingKey = bd.BillingKey
				WHERE a.EntityType = ''Order''
				AND   bd.Entity = ''tPurchaseOrderDetail''
				AND   b.CompanyKey = @CompanyKey
				AND   b.Status < 5
				)
			RETURN -101

	-- Check if any transaction are written off
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeysTime  a
					INNER JOIN tTime b (NOLOCK) ON b.TimeKey = cast(a.EntityKey as uniqueidentifier)
				WHERE a.EntityType = ''Time''
				AND   b.WriteOff = 1
				)
			RETURN -102
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tMiscCost b (NOLOCK) ON b.MiscCostKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''MiscExpense''
				AND  b.WriteOff = 1
				)
			RETURN -102
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tExpenseReceipt b (NOLOCK) ON b.ExpenseReceiptKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''Expense''
				AND  b.WriteOff = 1
				)
			RETURN -102
	IF EXISTS (SELECT 1
				FROM  #tProcWIPKeys  a
					INNER JOIN tVoucherDetail b (NOLOCK) ON b.VoucherDetailKey = cast(a.EntityKey as integer)
				WHERE a.EntityType = ''Voucher''
				AND  b.WriteOff = 1
				)
			RETURN -102

DROP Table #tProcWIPKeysTime

-- patch for SmartPlus and Strata sending 3 digits after decimal point
update tPurchaseOrderDetail
set    tPurchaseOrderDetail.PTotalCost = round(tPurchaseOrderDetail.PTotalCost, 2)
from   #tProcWIPKeys a
where  a.EntityType = ''Order''
and    tPurchaseOrderDetail.PurchaseOrderDetailKey = cast(a.EntityKey as integer)

	/*
	|| Date Inits
	*/
	If @PostingDate IS NOT NULL
		select @TodaysDate = cast(cast(DATEPART(m,@PostingDate) as varchar(5))+''/''+cast(DATEPART(d,@PostingDate) as varchar(5))+''/''+cast(DATEPART(yy,@PostingDate)as varchar(5)) as smalldatetime)
	ELSE
	BEGIN
		select @TodaysDate = cast(cast(DATEPART(m,getdate()) as varchar(5))+''/''+cast(DATEPART(d,getdate()) as varchar(5))+''/''+cast(DATEPART(yy,getdate())as varchar(5)) as smalldatetime)
		Select @PostingDate = @TodaysDate
	END
	if @InvoiceDate is null
		Select @InvoiceDate = @TodaysDate

	/*
	|| Process actions which do not require invoices
	*/
	exec @RetVal = spProcessWIPWorksheetNoInvoice @TodaysDate, @WriteOffReasonKey, @WriteOffComment
	if @RetVal < 0
	  begin
		return @RetVal
	  end

	-- Determine if there are any billable charges (greg)
	if not exists(select 1 from #tProcWIPKeys)
	  begin
		return 1
	  end

	/*
	|| Get Invoice defaults
	*/

	declare @ProjectLayoutKey int

	-- If Invoice By Project
	if @InvoiceBy = 0
	begin
		--get client key
		select @ClientKey = ClientKey
		from tProject (nolock)
		where ProjectKey = @ProjectKey
		if ISNULL(@ClientKey, 0) = 0
		begin
			return -25
		end

		--get invoice defaults from project
		select @CompanyKey = p.CompanyKey
				,@BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
				,@PrimaryContactKey = u.UserKey
				,@LineSubject = p.ProjectName
				,@CampaignKey = p.CampaignKey
				,@ProjectLayoutKey = p.LayoutKey
		from tProject p (nolock)
				left outer join tUser u (nolock) on p.BillingContact = u.UserKey
		where p.ProjectKey = @ProjectKey

		-- if there is no primary contact on project try to get it from the client
		IF @PrimaryContactKey IS NULL
			select @PrimaryContactKey = u.UserKey
			from tCompany cl (nolock)
				left outer join tUser u (nolock) on cl.PrimaryContact = u.UserKey
			Where cl.CompanyKey = @ClientKey

	end

	-- If Invoice By Client or By Client Parent
	if @InvoiceBy in (1, 2, 4)
	begin

		-- get invoice defaults from client
		SELECT @CompanyKey = OwnerCompanyKey
			,@LineSubject = CompanyName
		FROM   tCompany (NOLOCK)
		WHERE  CompanyKey = @ClientKey

		-- Get the billing contact as the primary contact from the client
		select @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
				,@PrimaryContactKey = u.UserKey
		from tCompany cl (nolock)
			left outer join tUser u (nolock) on cl.PrimaryContact = u.UserKey
		Where cl.CompanyKey = @ClientKey

		-- For Davis, track a for a possible campaign, only if we have a single campaign
		if @InvoiceBy = 1
		begin
			if (select count(distinct p.CampaignKey)
				from tProject p (nolock)
				inner join #tProcWIPKeys b on p.ProjectKey = b.ProjectKey
				) = 1
			select @CampaignKey = p.CampaignKey
			from tProject p (nolock)
			inner join #tProcWIPKeys b on p.ProjectKey = b.ProjectKey
		end

	end

	-- by estimate
	if @InvoiceBy = 3
	begin
		--get client key
		select @ClientKey = ClientKey
			,@LineSubject = EstimateName
		from tMediaEstimate (nolock)
		where MediaEstimateKey = @MediaEstimateKey
		if ISNULL(@ClientKey, 0) = 0
		begin
			return -25
		end

		-- Get the billing contact as the primary contact from the client
		select @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
				,@PrimaryContactKey = u.UserKey
		from tCompany cl (nolock)
			left outer join tUser u (nolock) on cl.PrimaryContact = u.UserKey
		Where cl.CompanyKey = @ClientKey

		-- get invoice defaults from client
		SELECT @CompanyKey = OwnerCompanyKey
		FROM   tCompany (nolock)
		WHERE  CompanyKey = @ClientKey
	end

	declare @RetainerInvoiceTemplateKey int
	declare @RetainerLayoutKey int

	-- If Invoice Retainer Per Retainer
	if @InvoiceBy = 5
	begin
		-- get invoice defaults from client
		SELECT @CompanyKey = OwnerCompanyKey
			,@LineSubject = CompanyName
		FROM   tCompany (NOLOCK)
		WHERE  CompanyKey = @ClientKey

		-- Get the billing contact as the primary contact from the retainer + other info
		select @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
				,@PrimaryContactKey = u.UserKey
				,@RetainerInvoiceTemplateKey = r.InvoiceTemplateKey
				,@RetainerLayoutKey = r.LayoutKey
				,@DepartmentKey = r.DepartmentKey
		from tRetainer r (nolock)
			left outer join tUser u (nolock) on r.ContactKey = u.UserKey
		Where r.RetainerKey = @ProcessKey

		if ISNULL(@PrimaryContactKey, 0) = 0
			select @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
				,@PrimaryContactKey = u.UserKey
			from tCompany cl (nolock)
			left outer join tUser u (nolock) on cl.PrimaryContact = u.UserKey
			Where cl.CompanyKey = @ClientKey
	end

	-- get other client defaults
	Select @InvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
			, @SalesTaxKey = SalesTaxKey
			, @SalesTax2Key = SalesTax2Key
			, @DefaultSalesAccountKey = ISNULL(DefaultSalesAccountKey, 0)
			, @ARAccountKey = ISNULL(DefaultARAccountKey, 0)
			, @PaymentTermsKey = ISNULL(PaymentTermsKey, 0)
			, @LayoutKey = LayoutKey
			, @BillingAddressKey = BillingAddressKey
	from tCompany (nolock)
	Where CompanyKey = @ClientKey

	-- we need to check where the layout comes from
	select @LayoutFromGLCompany = isnull(LayoutFromGLCompany, 0)
			,@AdvBillAccountKey = AdvBillAccountKey
	from  tPreference (nolock)
	where CompanyKey = @CompanyKey

	if @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
		Select @InvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
			, @LayoutKey = LayoutKey
		from tGLCompany (nolock)
		Where GLCompanyKey = @GLCompanyKey

	-- now get the overrides on project and retainer

	if isnull(@RetainerInvoiceTemplateKey, 0) > 0
		select @InvoiceTemplateKey = @RetainerInvoiceTemplateKey

	if isnull(@RetainerLayoutKey, 0) > 0
		select @LayoutKey = @RetainerLayoutKey

	if isnull(@ProjectLayoutKey, 0) > 0
		select @LayoutKey = @ProjectLayoutKey

	-- be careful in this case (Invoice By Client and By Project/Billing Item/Item)
	-- the user can pick a layout
	if @InvoiceBy = 1 And @Rollup = 9
	begin
		if isnull(@UILayoutKey, 0) > 0
			select @LayoutKey = @UILayoutKey
	end

	-- get preferences
	if isnull(@DefaultSalesAccountKey,0) = 0
		Select @DefaultSalesAccountKey = DefaultSalesAccountKey
		From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	if @PaymentTermsKey = 0
		Select @PaymentTermsKey = PaymentTermsKey
		From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	Select @PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
			,@DefaultARAccountKey = DefaultARAccountKey
			,@WorkTypeKey         = AdvBillItemKey
			,@RequireClasses      = ISNULL(RequireClasses, 0)
			,@DefaultClassKey     = DefaultClassKey
			,@UseBillingTitles	   = ISNULL(UseBillingTitles, 0)
			,@Customizations = LOWER(ISNULL(Customizations, ''''))
			,@SetTaxableOnInvoice  = ISNULL(SetTaxableOnInvoice,0) -- this overrides the Taxable on tasks/items/services/BI and also used for 1-line invoice
	From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	if isnull(@ARAccountKey,0) > 0
		select @DefaultARAccountKey = @ARAccountKey

	-- check for mismatch between currency and AR account
	if @CurrencyID is not null
	begin
		if not exists (select 1 from tGLAccount (nolock) where GLAccountKey = @DefaultARAccountKey and CurrencyID = @CurrencyID)
			begin
				if exists (select 1 from tGLAccount (nolock) where CompanyKey = @CompanyKey and AccountType = 11 and CurrencyID = @CurrencyID)
					select @DefaultARAccountKey = GLAccountKey from tGLAccount (nolock) where CompanyKey = @CompanyKey and AccountType = 11 and CurrencyID = @CurrencyID
			end
	end
	else
	begin
		-- @CurrencyID is null
		if not exists (select 1 from tGLAccount (nolock) where GLAccountKey = @DefaultARAccountKey and CurrencyID is null)
			begin
				if exists (select 1 from tGLAccount (nolock) where CompanyKey = @CompanyKey and AccountType = 11 and CurrencyID is null)
					select @DefaultARAccountKey = GLAccountKey from tGLAccount (nolock) where CompanyKey = @CompanyKey and AccountType = 11 and CurrencyID is null
			end
	end

	-- customization for Owens Harkey, use taxes from the vendor, vouchers, orders
	if charindex(''mediataxes'', @Customizations) > 0
		select @UseMediaTaxes = 1
	else
		select @UseMediaTaxes = 0

	IF ISNULL(@PaymentTermsKey, 0) > 0
	BEGIN
		SELECT @DueDays = ISNULL(DueDays, 0)  -- Why are they NULL in the database ???
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @PaymentTermsKey

		SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate)
	END
	ELSE
		SELECT @DueDate = @TodaysDate

	-- Logic for classes
	Declare @HeaderClassKey int

	IF ISNULL(@DefaultUIClassKey, 0) = 0
	BEGIN
		IF @RequireClasses = 1
			SELECT @DefaultUIClassKey = @DefaultClassKey
		IF @DefaultUIClassKey = 0
			SELECT @DefaultUIClassKey = NULL

	END
	IF ISNULL(@InvoiceByClassKey, 0) > 0
		SELECT @HeaderClassKey = @InvoiceByClassKey
	ELSE
		SELECT @HeaderClassKey = @DefaultUIClassKey
			   ,@InvoiceByClassKey = NULL
	
	--Set the AdvBillAcountKey	
	Set @LiabilityAccountKey = NULL  --AdvanceBill is 0
		
	/*
	|| Create Invoice
	*/
	SELECT @CreatedByKey = ISNULL(@CreatedByKey, @UserKey)

	exec @RetVal = sptInvoiceInsert
			@CompanyKey = @CompanyKey,
			@ClientKey = @ClientKey,
			@ContactName = @BillingContact,
			@PrimaryContactKey = @PrimaryContactKey,
			@AddressKey = @BillingAddressKey,
			@AdvanceBill = 0,
			@InvoiceNumber = null,
			@InvoiceDate = @InvoiceDate,
			@DueDate = @DueDate,
			@PostingDate = @PostingDate,
			@TermsKey = @PaymentTermsKey,
			@ARAccountKey = @DefaultARAccountKey,
			@ClassKey = @HeaderClassKey,
			@ProjectKey = @ProjectKey,
			@HeaderComment = null,
			@SalesTaxKey = @SalesTaxKey,
			@SalesTax2Key = @SalesTax2Key,
			@InvoiceTemplateKey = @InvoiceTemplateKey,
			@ApprovedByKey = @UserKey,
			@UserDefined1 = NULL,
			@UserDefined2 = NULL,
			@UserDefined3 = NULL,
			@UserDefined4 = NULL,
			@UserDefined5 = NULL,
			@UserDefined6 = NULL,
			@UserDefined7 = NULL,
			@UserDefined8 = NULL,
			@UserDefined9 = NULL,
			@UserDefined10 = NULL,
			@Downloaded = 0,
			@Printed = 0,
			@ParentInvoice = 0,
			@Emailed = 0,
			@CreatedByKey = @CreatedByKey,
			@GLCompanyKey = @GLCompanyKey,
			@OfficeKey = @OfficeKey,
			@OpeningTransaction = 0,
			@LayoutKey = @LayoutKey,
			@CurrencyID = @CurrencyID,
			@ExchangeRate = 1,
			@RequestExchangeRate = 1, -- set exch rate
			@IsForRetainer = @IsForRetainer,
			@LiabilityAccountKey = @LiabilityAccountKey, -- **NEW PARAMETER ADDED**
			@oIdentity = @NewInvoiceKey OUTPUT -- Maps the output variable

	if @RetVal <> 1
	 begin
		return -5
	  end
	if @@ERROR <> 0
	  begin
		return -5
	  end

	--update campaign key if needed (Invoice by project/client and there is a campaign on the project)
	if @InvoiceBy in ( 0, 1) and isnull(@CampaignKey, 0) > 0
	begin
		update tInvoice
		set    CampaignKey = @CampaignKey
		where  InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0
		  begin
			return -5
		  end
	end

	declare @NextTranNo varchar(100)
	declare @InvoiceStatus int
	declare @ApprovedByKey int
	declare @AdvanceBill int

	If @CreateAsApproved = 1
	BEGIN

		--Check to see if the tInvoice Insert SP set the Invoice Number
		SELECT	@NextTranNo = InvoiceNumber,
		        @AdvanceBill = AdvanceBill
		FROM	tInvoice (nolock)
		WHERE	InvoiceKey = @NewInvoiceKey

		IF @NextTranNo IS NULL
		BEGIN
			--If the InvoiceNumber has not been set yet, get the next number
			DECLARE @TranType varchar(10) = CASE @AdvanceBill WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

			EXEC spGetNextTranNo
				@CompanyKey,
				@TranType,
				@RetVal		      OUTPUT,
				@NextTranNo 	  OUTPUT

			IF @RetVal <> 1
				RETURN -5
		END

		update tInvoice
		set	  ApprovedByKey = @UserKey
			 ,InvoiceStatus = 4 -- Approved
			 ,InvoiceNumber = RTRIM(LTRIM(@NextTranNo))
		where InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0
		begin
			return -5
		end
	END

	/* Removed for issue 334769
	ELSE
	BEGIN

		select @InvoiceStatus = InvoiceStatus
		      ,@ApprovedByKey = ApprovedByKey
		from   tInvoice (nolock)
		where  InvoiceKey = @NewInvoiceKey

		-- only if not already approved and the approver is valid, submit
		if @InvoiceStatus <> 4 And isnull(@ApprovedByKey, 0) > 0
		update tInvoice
		set    InvoiceStatus = 2
		where InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0
		begin
			return -5
		end
	END
	*/

	/*
	|| Handle single invoice line
	|| (when @BillExpensesByItem = 1 the extras are itemized instead - see the retainer block below)
	*/
	if @Rollup = 0 and isnull(@BillExpensesByItem, 0) = 0
	begin
		exec @RetVal = spProcessWIPWorksheetOneLine @NewInvoiceKey ,@ProjectKey ,@LineSubject
			,@DefaultSalesAccountKey, @HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
		if @RetVal < 0
		begin
			return @RetVal
		end
	 end

	/*
	|| Handle invoice lines by Task
	*/
	if @Rollup = 1
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerTask @NewInvoiceKey ,@ProjectKey
			,@DefaultSalesAccountKey , @HeaderClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end

		exec @RetVal = sptInvoiceLineApplyTaskOptions @NewInvoiceKey
	end

	/*
	|| Handle invoice lines by Service, expenses are on a single ''Expenses'' line
	*/
	if @Rollup = 2
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerService @NewInvoiceKey ,@ProjectKey
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
		
		UPDATE tInvoiceLine
		SET DisplayOption = lb.DisplayOption
		FROM
			tInvoiceLine il (nolock)
			INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
			INNER JOIN tLayoutBilling lb (nolock) ON il.Entity = lb.Entity AND il.EntityKey = lb.EntityKey AND lb.LayoutKey = i.LayoutKey
		WHERE il.InvoiceKey = @NewInvoiceKey
	end

	/*
	|| Handle invoice lines by Billing Item or WorkType
	*/
	if @Rollup = 3
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerBillingItem @CompanyKey, @NewInvoiceKey ,@ProjectKey
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	/*
	|| Handle invoice lines by Project (When Invoiced By Client)
	*/
	if @Rollup = 4
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerProject @NewInvoiceKey
			,@DefaultSalesAccountKey ,@HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	-- handle invoice lines by Estimate (when invoiced by Project, Client, Client Parent)
	if @Rollup = 5
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerEstimate @NewInvoiceKey
			,@DefaultSalesAccountKey ,@HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	-- handle invoice lines by Client (when invoiced by Client Parent)
	if @Rollup = 6
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerClient @NewInvoiceKey
			,@DefaultSalesAccountKey ,@HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	-- handle invoice lines by ProjectType + Project (when invoiced by Client)
	if @Rollup = 7
	begin
		exec @RetVal = spProcessWIPWorksheetProjectTypeProject @NewInvoiceKey
			,@DefaultSalesAccountKey ,@HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	/*
	|| Handle special case of retainers
	|| Rollup will be determined in sp below
	|| Also used when @BillExpensesByItem = 1 (retainer extras billed one line per Item/Service),
	|| e.g. the "Invoice Extras Separately -> one per Project" pass which invoices by Project (@InvoiceBy = 0)
	*/
	if @InvoiceBy in (4, 5) or isnull(@BillExpensesByItem, 0) = 1
	begin
		exec @RetVal = spProcessWIPWorksheetRetainer @NewInvoiceKey
			,@DefaultSalesAccountKey ,@HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	/*
	|| Handle invoice lines by Billing Item or WorkType THEN Item....without a layout
	*/
	if @Rollup = 8 and isnull(@LayoutKey,0) = 0
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerBillingItemItem @CompanyKey, @NewInvoiceKey ,@ProjectKey
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	/*
	|| Handle invoice lines by Project then Billing Item or WorkType THEN Item
	|| The design is different here because we are leveraging what we did for the billing worksheets
	*/


declare @LoopProjectKey int
declare @LoopProjectID int
declare @ParentInvoiceLineKey int

-- Layout display options
DECLARE @kDisplayOptionNoDetail INT			SELECT @kDisplayOptionNoDetail = 1
DECLARE @kDisplayOptionSubItemDetail INT	SELECT @kDisplayOptionSubItemDetail = 2
DECLARE @kDisplayOptionTransactions INT		SELECT @kDisplayOptionTransactions = 3

declare @LayoutProjectDisplayOption int

-- If by Billing Item/Item or By Service/Item, we use a core function, place transactions in this temp table

-- create all temp tables used by the billing worksheet subroutines


if @Rollup in (9, 14)  Or (@Rollup = 8 and isnull(@LayoutKey, 0) > 0)
begin
	-- In Billing WS we will convert from tBillingDetail to #tran
	-- Mass Billing will convert from #ProcWIPKeys to #tran

	-- #tran will contain all transactions
	CREATE TABLE #tran(
		Entity varchar(20) null,		-- like in tBillingDetail, tMiscCost, tTime, etc....
		EntityKey varchar(50) null,     -- transaction key
		EntityGuid uniqueidentifier null,

		BilledAmount money null,
		Quantity decimal(24,4) null,
		RateLevel int null,
		Rate money null,
		BilledComment varchar(2000),

		LayoutEntityKey int null,       -- ItemKey or ServiceKey depending on LayoutEntity

		-- All fields above should be set before this SP

		LayoutEntity varchar(50) null,   -- like in tLayoutBilling, tItem, tService
		LayoutOrder int null,
		WorkTypeLayoutOrder int null,

		WorkTypeKey int null,
		WorkTypeName varchar(200) null,
		ItemName varchar(200) null,     -- will come from item or service

		-- Use this for simpler grouping (Service/Item)
		GroupEntity varchar(25) null,
		GroupEntityKey int null,
		GroupName varchar(250) null,

		InvoiceLineKey int null,
		LineID int null,

		UpdateFlag int null
		)
	end

	if @Rollup = 9 Or (@Rollup = 8 and isnull(@LayoutKey, 0) > 0)
	begin
		--  #line will contain the lines ready to be inserted in tInvoiceLine

		CREATE TABLE #line(
		LineID int identity(1,1),
		ParentLineID int null,
		InvoiceLineKey int null,
		ParentLineKey int null,

		BilledAmount money null,
		Quantity decimal(24,4) null,
		UnitCost money null,

		Subject VARCHAR(200) null,
		Description text null,
		Taxable int null,
		Taxable2 int null,
		ClassKey int null,
		SalesAccountKey int null,

		WorkTypeKey int null,
		ItemKey int null,
		ServiceKey int null,

		LayoutOrder int null, -- just for initial pull

		DisplayOption int null,

		UpdateFlag int null
		)
	end

	/*
	|| Handle invoice lines by Project THEN Billing Item or WorkType THEN Item....with or without a layout
	*/

	if @Rollup = 9
	begin
		create table #allitems (Entity varchar(20) null, EntityKey int, WorkTypeKey int
	    , EntityName varchar(200) null, Description text null
	    , StdEntityName varchar(200) null, StdDescription text null
	    , DisplayOrder int null, SalesAccountKey int null,ClassKey int null, Taxable int null, Taxable2 int null
		)

		create table #project (ProjectID int identity(1,1), ProjectKey int null, ProjectName varchar(100) null)

		-- cleanup ProjectKey in #tProcWIPKeys, because we are going to loop on ProjectKey
		update #tProcWIPKeys
		set ProjectKey = isnull(ProjectKey, 0)

		if exists (select 1 from  #tProcWIPKeys where ProjectKey = 0)
			insert #project (ProjectKey, ProjectName)
			values (0, ''[No Project]'')

		insert #project (ProjectKey, ProjectName)
		select distinct isnull(a.ProjectKey, 0), p.ProjectName
		from   #tProcWIPKeys a
			inner join tProject p (nolock) on a.ProjectKey = p.ProjectKey
		order by p.ProjectName -- Will look better on the invoice if by aphabetical order

		select @LayoutKey = isnull(@LayoutKey, 0)

		SELECT @LayoutProjectDisplayOption = DisplayOption
		FROM   tLayoutBilling (nolock)
		WHERE  LayoutKey = @LayoutKey
		AND    Entity = ''tProject''
		AND    EntityKey = 0

		select @LayoutProjectDisplayOption = isnull(@LayoutProjectDisplayOption, @kDisplayOptionSubItemDetail)

		-- Get all the items/services/billing items
		-- this will populate #allitems
		exec spBillingLinesGetItems @CompanyKey, null, 0

		--select * from #tProcWIPKeys

		select @LoopProjectID = -1
		while (1=1)
		begin
			select @LoopProjectID = min(ProjectID)
			from  #project
			where ProjectID > @LoopProjectID

			if @LoopProjectID is null
				break

			select @LineSubject = ProjectName
			      ,@LoopProjectKey = ProjectKey
			from #project
			where ProjectID = @LoopProjectID

			--create single invoice line for the project
			exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
														-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
														-- (GHL 4/23/10 put it back for custom fields)
						  ,@LoopProjectKey					-- ProjectKey
						  ,NULL							-- TaskKey
						  ,@LineSubject					-- Line Subject
						  ,NULL                 		-- Line description
						  ,0		      				-- Bill From
						  ,0							-- Quantity
						  ,0							-- Unit Amount
						  ,0							-- Line Amount
						  ,1							-- line type = Summary
						  ,0							-- parent line key
						  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
						  ,null				             -- Class Key
						  ,0							-- Taxable
						  ,0							-- Taxable2
						  ,NULL							-- Work TypeKey
						  ,@PostSalesUsingDetail
						  ,NULL							-- Entity
						  ,NULL							-- EntityKey
						  ,NULL							-- OfficeKey
						  ,NULL							-- DepartmentKey
						  ,@ParentInvoiceLineKey output

			if @@ERROR <> 0
			  begin
				exec sptInvoiceDelete @NewInvoiceKey
				return -1 -- check error returns later
			  end
			if @RetVal <> 1
			  begin
				exec sptInvoiceDelete @NewInvoiceKey
				return -1
			  end

			  -- DisplayOption from tLayoutBilling must be set for the project
			update tInvoiceLine
			set    DisplayOption = @LayoutProjectDisplayOption
			where  InvoiceLineKey = @ParentInvoiceLineKey

			-- apply custom billing item descriptions
			exec spBillingLinesUpdateItems ''tProject'', @LoopProjectKey

			-- this will populate #tran
			truncate table #tran
			exec spProcessWIPWorksheetGetTrans @LoopProjectKey

			-- this will populate #line from #tran and #allitems and the layout
			exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tProject'', @LoopProjectKey
				,@DefaultSalesAccountKey,@DefaultUIClassKey,@InvoiceByClassKey, 0 --@GetItemInfo
			
			EXEC spBillingLinesUpdateFromRateSheet @ProjectKey = @ProjectKey

			--select * from #tran
			--select * from #line

			-- this will create tInvoiceLine recs from #line
			exec @RetVal = spBillingLinesInsert @CompanyKey,@NewInvoiceKey,@LoopProjectKey ,@DefaultSalesAccountKey ,@DefaultUIClassKey
				,@ParentInvoiceLineKey,@PostSalesUsingDetail, 0

			IF @RetVal < 0
			BEGIN
				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN -1
			END

		end -- project loop

		-- DisplayOption is null if LayoutKey = 0
		-- by default
		-- I apply the SubItemDetail disp option to summary tasks
		-- I apply the NoDetail disp option to detail tasks

		update tInvoiceLine
		set    DisplayOption = 2 --@kDisplayOptionSubItemDetail
		where  InvoiceKey = @NewInvoiceKey
		and    LineType = 1 -- @kLineTypeSummary
		and    isnull(DisplayOption, 0) = 0

		update tInvoiceLine
		set    DisplayOption = 1 -- @kDisplayOptionNoDetail
		where  InvoiceKey = @NewInvoiceKey
		and    LineType = 2 -- @kLineTypeDetail
		and    isnull(DisplayOption, 0) = 0

	end -- rollup =9

	/*
	|| Handle invoice lines by Billing Item or WorkType THEN Item....with a layout
	*/

	-- this will work for ''by project'' and ''by client''
	if @Rollup = 8 and isnull(@LayoutKey, 0) > 0
	begin
		-- populate #tran
		if @InvoiceBy = 0
			update #tProcWIPKeys set ProjectKey = @ProjectKey -- when we bill by project, this is missing in the temp table

		exec spProcessWIPWorksheetGetTrans @ProjectKey

		-- populate #lines
		if @InvoiceBy = 0
			exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tProject'', @ProjectKey
				,@DefaultSalesAccountKey,@DefaultUIClassKey,@InvoiceByClassKey, 1 --@GetItemInfo
		else
			exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, null, 0
				,@DefaultSalesAccountKey,@DefaultUIClassKey,@InvoiceByClassKey, 1 --@GetItemInfo
		
		--If there is a TimeRateSheet with custom InvoiceLabels, update the line Subject
		EXEC spBillingLinesUpdateFromRateSheet @ProjectKey = @ProjectKey

		-- this will create tInvoiceLine recs from #line at the parent root
		select @ParentInvoiceLineKey = 0
		exec @RetVal = spBillingLinesInsert @CompanyKey,@NewInvoiceKey,@ProjectKey ,@DefaultSalesAccountKey ,@DefaultUIClassKey
			,@ParentInvoiceLineKey,@PostSalesUsingDetail, 0

		--select * from #tProcWIPKeys
		--select * from #tran
		--select * from #line

		IF @RetVal < 0
		BEGIN
			EXEC sptInvoiceDelete @NewInvoiceKey
			RETURN -1
		END
	end


	/*
	|| Handle invoice lines by Publication/Station
	*/
	if @Rollup = 10
	begin
		-- This will also copy the taxes from orders/vouchers to invoices
		exec @RetVal = spProcessWIPWorksheetOneLinePerPublication @NewInvoiceKey ,@ProjectKey
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end
	end

	/*
	|| Handle invoice lines by title for Abelson/Taylor
	*/
	if @Rollup in (11, 12, 13)
	begin
		-- Use a stored proc created for both mass billing and billing worksheet

		 CREATE TABLE #labor (TimeKey uniqueidentifier null
		  , ActualRate decimal(24,4) null
		  , ActualHours decimal(24,4) null
		  , BillAmount money null
		  , ServiceKey int null
		  , TitleKey int null
		  , RateLevel int null
          , Comments varchar(2000) null

		  , GroupEntity varchar(50) null
		  , GroupEntityKey int null
		  , SubGroupEntity varchar(50) null
		  , SubGroupEntityKey int null

		  , InvoiceLineKey int null
		  )

		  CREATE TABLE #expense (Entity varchar(25) null
			, EntityKey int null
			, BillAmount money  null

			, GroupEntity varchar(50) null
			, GroupEntityKey int null
			, SubGroupEntity varchar(50) null
			, SubGroupEntityKey int null

			, InvoiceLineKey int null
		  )

		-- load labor
		insert #labor (TimeKey, ActualRate, ActualHours, ServiceKey, TitleKey)
		select cast(#tProcWIPKeys.EntityKey as uniqueidentifier), tTime.ActualRate, tTime.ActualHours, tTime.ServiceKey, tTime.TitleKey
		from #tProcWIPKeys, tTime (nolock)
			where #tProcWIPKeys.EntityType = ''Time''
			and tTime.TimeKey = cast(#tProcWIPKeys.EntityKey as uniqueidentifier)
			and #tProcWIPKeys.Action = 1

		update #labor set BillAmount = Round ( isnull(ActualRate, 0) * isnull(ActualHours, 0), 2 )

		-- load expenses
		insert #expense (Entity, EntityKey)
		select EntityType, cast(EntityKey as integer)
		from #tProcWIPKeys
		where #tProcWIPKeys.EntityType <> ''Time''
		and #tProcWIPKeys.Action = 1

		update #expense
		set    #expense.BillAmount = t.BillableCost
		from   tExpenseReceipt t (nolock)
		where  #expense.Entity = ''Expense''
		and    t.ExpenseReceiptKey = #expense.EntityKey

		update #expense
		set    #expense.BillAmount = t.BillableCost
		from   tMiscCost t (nolock)
		where  #expense.Entity = ''MiscExpense''
		and    t.MiscCostKey = #expense.EntityKey

		update #expense
		set    #expense.BillAmount = t.BillableCost
		from   tVoucherDetail t (nolock)
		where  #expense.Entity = ''Voucher''
		and    t.VoucherDetailKey = #expense.EntityKey

		update #expense
		set    #expense.BillAmount = case po.BillAt
			When 0 then isnull(BillableCost,0)
			When 1 then isnull(PTotalCost,isnull(TotalCost,0))
			When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0))
			Else isnull(BillableCost,0)
			end
		from   tPurchaseOrderDetail t (nolock)
		      ,tPurchaseOrder po (nolock)
		where  #expense.Entity = ''Order''
		and    t.PurchaseOrderDetailKey = #expense.EntityKey
		and    t.PurchaseOrderKey = po.PurchaseOrderKey

		declare @TitleRollup varchar(25)
		if @Rollup = 11
			select @TitleRollup = ''TitleOnly''
		else if @Rollup = 12
			select @TitleRollup = ''TitleService''
		else if @Rollup = 13
			select @TitleRollup = ''ServiceTitle''

		exec @RetVal = spBillingPerTitle @NewInvoiceKey , @TitleRollup, @ProjectKey
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end

		update tInvoiceLine
		set    DisplayOption = case when LineType =1 then 2 else 1 end
		where  InvoiceKey = @NewInvoiceKey
		and    DisplayOption is null

	end

	/*
	|| Handle invoice lines by Service/Item, expenses are grouped by item (ie. not a single line)
	*/
	if @Rollup = 14
	begin
		-- Copy keys from #procwipkeys to #tran, no need to specify project (pass a null)
		exec spProcessWIPWorksheetGetTrans null

		-- call core function to create lines per service or item
		exec @RetVal = spBillingPerServiceItem @NewInvoiceKey ,@ProjectKey
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end

		IF ISNULL(@LayoutKey,0) > 0
			BEGIN
				UPDATE tInvoiceLine

					SET DisplayOption = lb.DisplayOption
					FROM
						tInvoiceLine il (nolock)
						INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
						LEFT JOIN tLayoutBilling lb (nolock) ON il.Entity = lb.Entity AND il.EntityKey = lb.EntityKey AND lb.LayoutKey = i.LayoutKey
					WHERE il.InvoiceKey = @NewInvoiceKey
			END
		ELSE
			update tInvoiceLine
			set    DisplayOption = case when LineType =1 then 2 else 1 end
			where  InvoiceKey = @NewInvoiceKey
			and    DisplayOption is null
	end

	/*
	|| Handle invoice lines by PROJECT then Billing Item or WorkType
	*/
	if @Rollup = 15
	begin
		exec @RetVal = spProcessWIPWorksheetOneLinePerProjectBillingItem @CompanyKey, @NewInvoiceKey 
			,@DefaultSalesAccountKey ,@DefaultUIClassKey, @InvoiceByClassKey, @PostSalesUsingDetail
	  	if @RetVal < 0
		begin
			return @RetVal
		end

		update tInvoiceLine
		set    DisplayOption = case when LineType =1 then 2 else 1 end
		where  InvoiceKey = @NewInvoiceKey
		and    DisplayOption is null
	end

	--Update Lines for the percent of actual billing amount
	Declare @CurKey int
	if @PercentOfActual <> 1
	begin
		Update tTime Set BilledRate = ROUND(BilledRate * @PercentOfActual, 4)  --round rates with 4 digits
		from tInvoiceLine il (nolock)
		where il.InvoiceKey = @NewInvoiceKey
		and   il.InvoiceLineKey = tTime.InvoiceLineKey

		Update tExpenseReceipt Set AmountBilled = ROUND(AmountBilled * @PercentOfActual, 2)
		from tInvoiceLine il (nolock)
		where il.InvoiceKey = @NewInvoiceKey
		and   il.InvoiceLineKey = tExpenseReceipt.InvoiceLineKey

		Update tMiscCost Set AmountBilled = ROUND(AmountBilled * @PercentOfActual, 2)
		from tInvoiceLine il (nolock)
		where il.InvoiceKey = @NewInvoiceKey
		and   il.InvoiceLineKey = tMiscCost.InvoiceLineKey

		Update tVoucherDetail Set AmountBilled = ROUND(AmountBilled * @PercentOfActual, 2)
		from tInvoiceLine il (nolock)
		where il.InvoiceKey = @NewInvoiceKey
		and   il.InvoiceLineKey = tVoucherDetail.InvoiceLineKey

		Update tPurchaseOrderDetail Set AmountBilled = ROUND(AmountBilled * @PercentOfActual, 2)
		from tInvoiceLine il (nolock)
		where il.InvoiceKey = @NewInvoiceKey
		and   il.InvoiceLineKey = tPurchaseOrderDetail.InvoiceLineKey

		Select @CurKey = -1
		while 1=1
		begin
			Select @CurKey = min(InvoiceLineKey) from tInvoiceLine (nolock) Where InvoiceKey = @NewInvoiceKey and InvoiceLineKey > @CurKey
			if @CurKey is null
				break
			-- do not recalc sales taxes at the invoice level or the invoice line level since we do it at the end (pass 2 zeroes)
			exec sptInvoiceLineUpdateTotals @CurKey, 0, 0
		end
	end

	-- before we leave, better to recalc the amounts in the header
	if @Rollup = 10
		-- If by publication, rollup taxes
		exec sptInvoiceRollupAmounts @NewInvoiceKey
	else
	begin
		-- This will force the Taxable fields if the pref or the project requires them
		exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

		-- else we only set the Taxable fields, so recalc
		exec sptInvoiceRecalcAmounts @NewInvoiceKey
	end

	-- the media taxes will be placed in the other taxes, tax1 and tax2 must be calculated first
	if @UseMediaTaxes = 1
		-- customization: pull taxes from the vendor instead of the client
		exec @RetVal = sptInvoiceGetVendorTaxes @NewInvoiceKey


	-- Calculate the line order and position
	exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0

	-- this is for Abelson Taylor, rollup hours on invoicelines
	exec  sptInvoiceLineSetHours @NewInvoiceKey

	return @NewInvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesUpdateBillingSchedule]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesUpdateBillingSchedule]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER procedure [dbo].[spFixedFeesUpdateBillingSchedule]
	(
	@InvoiceKey int
	,@ProjectKey int
	,@BillingScheduleKey int = null
	)

	as --encrypt
begin

SET NOCOUNT ON

	/*
    || When     Who Rel     What
    || 10/06/17 GHL 10.621 (366896) update the billing schedule after creating a FF invoice for a project
	|| 11/14/17 GHL 10.622 Only update a single billing schedule
	|| 11/22/17 GHL 10.622 Only update a billing schedule if there is none for this invoice and project
	|| 06/26/18 GHL 18.700 (402606) Only update billing schedule if no invoice and no EBW yet
	|| 02/04/22 GHL 22.020 (587196) When having 3 blank schedules, the system would select the last one instead of the first
	||                     Changed max to min to fix it. see below
	||12/11/23  AMP 23.12.17 (628292) Modified to attach the Revenue Invoice or an Advance Bill invoice from Project Billing to the
	||                                correct billing schedule. Also modified to handle the same for a Time and Materials Project
	||07/08/26  AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
	*/

	declare @BilledBudgetAmount money
	declare @BilledLaborBudget money
	declare @BilledExpensesBudget money
	declare @BilledExpensesNotIncluded int

	select @BilledLaborBudget = isnull(EstLabor, 0) + isnull(ApprovedCOLabor, 0)
	      ,@BilledExpensesBudget = isnull(EstExpenses, 0) + isnull(ApprovedCOExpense, 0)
	      ,@BilledExpensesNotIncluded = isnull(ExpensesNotIncluded, 0)
	from   tProject (nolock)
	where  ProjectKey = @ProjectKey

	if isnull(@BilledExpensesNotIncluded, 0) = 0
		select @BilledBudgetAmount = isnull(@BilledLaborBudget, 0) + isnull(@BilledExpensesBudget, 0)
	else
		select @BilledBudgetAmount = isnull(@BilledLaborBudget, 0)

	-- If InvoiceKey is already linked to a row but BilledComment was not populated, fill it in now
	-- (occurs when a billing path sets InvoiceKey on tBillingSchedule before this proc is called)
	if exists (select 1 from tBillingSchedule (nolock)
	           where ProjectKey    = @ProjectKey
	           and   InvoiceKey    = @InvoiceKey
	           and   isnull(PercentBudget, 0) > 0
	           and   BilledComment is null)
	begin
		update tBillingSchedule
		set    BilledComment = ''Scheduled Amount: '' + FORMAT(ROUND(isnull(PercentBudget, 0) * @BilledBudgetAmount / 100.00, 2), ''N2'')
		where  ProjectKey    = @ProjectKey
		and    InvoiceKey    = @InvoiceKey
		and    isnull(PercentBudget, 0) > 0
		and    BilledComment is null
		return 1
	end

	if @BillingScheduleKey > 0
	begin
		if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @InvoiceKey and ProjectKey = @ProjectKey)
		update tBillingSchedule
		set   InvoiceKey = @InvoiceKey
		     ,BilledComment = case when isnull(PercentBudget, 0) > 0
		                           then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(PercentBudget, 0) * @BilledBudgetAmount / 100.00, 2), ''N2'')
		                           else null end
		where BillingScheduleKey = @BillingScheduleKey
		and   ProjectKey = @ProjectKey
		and    BillingKey is null
		and    InvoiceKey is null
		return 1
	end

declare @AdvanceBill int
declare @InvoiceDate smalldatetime
declare @NextBillDate smalldatetime
declare @BillingMethod int


	select  @BillingMethod = BillingMethod
	from tProject (nolock)
	where ProjectKey = @ProjectKey

	if exists (select 1 from tBillingSchedule (nolock) where ProjectKey = @ProjectKey)
	begin
		select @InvoiceDate = InvoiceDate
		      ,@AdvanceBill = AdvanceBill
		from tInvoice (nolock)
		where InvoiceKey = @InvoiceKey

		-- For T&M, find first unlinked row by date regardless of invoice date (no BillingKey link exists for T&M)
		-- For FF, restrict to rows on or before the invoice date to match the correct milestone
		select @NextBillDate = min(NextBillDate) -- changed from max to min for 587196
		from   tBillingSchedule (nolock)
		where  ProjectKey = @ProjectKey
		and    (@BillingMethod = 1 OR NextBillDate <= @InvoiceDate)
		and    BillingKey is null
		and    InvoiceKey is null
		and   (
		       (@BillingMethod = 2 and AdvanceBill = @AdvanceBill) OR
		        @BillingMethod = 1
			  )

		if @@rowcount = 0
			return 1

		if @NextBillDate is null
			return 1

		-- there are some users or testers using the same NextBillDate
		-- so pickup just one tBillingSchedule record
		select @BillingScheduleKey = min(BillingScheduleKey)
		from  tBillingSchedule (nolock)
		where  ProjectKey = @ProjectKey
		and    NextBillDate = @NextBillDate
		and    BillingKey is null
		and    InvoiceKey is null
		and   (
		       (@BillingMethod = 2 and AdvanceBill = @AdvanceBill) OR
		        @BillingMethod = 1
			  )

		if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @InvoiceKey and ProjectKey = @ProjectKey)
		update tBillingSchedule
		set    InvoiceKey = @InvoiceKey
		      ,BilledComment = case when isnull(PercentBudget, 0) > 0
		                            then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(PercentBudget, 0) * @BilledBudgetAmount / 100.00, 2), ''N2'')
		                            else null end
		where  BillingScheduleKey = @BillingScheduleKey


	end

end


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spMassBillingBillClient]'
GO
IF OBJECT_ID(N'[dbo].[spMassBillingBillClient]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[spMassBillingBillClient]
	 @CompanyKey int
	,@ClientKey int
	,@ProjectKeys varchar(8000)
	,@InvoiceBy int -- 1 By Client, 2 By Client Parent
	,@Rollup int
	,@UserKey int
	,@ThruDate datetime
	,@BillingStatusKey int
	,@PercentOfActual decimal(15,8)
	,@Time tinyint
	,@Expense tinyint
	,@PO tinyint
	,@POBeginDate datetime
	,@POEndDate datetime
	,@IO tinyint
	,@IOBeginDate datetime
	,@IOEndDate datetime
	,@BC tinyint
	,@BCBeginDate datetime
	,@BCEndDate datetime
	,@InvoiceDate smalldatetime
	,@PostingDate smalldatetime
	,@DefaultClassKey INT = NULL	-- This is already validated on the screen
	,@DefaultOfficeKey INT = NULL	-- This is already validated on the screen
	,@CreateAsApproved INT = 0
	,@UILayoutKey int = null        -- only for Invoice By = 1 (Client) and Rollup =9 (Project/BillingItem/Item)
	,@OpenOrdersOnly int = 1
	,@WJAPP int = 0
	,@LaborAtNet int = 0			-- 0 Bill labor at gross, 1 Bill labor at net
	,@PostedOnly int = 0        -- Posted vendor Invoices only
	,@InvoiceKeys varchar(8000) = NULL OUTPUT

AS --Encrypt

  /*
  || When     Who Rel   What
  || 02/23/07 GHL 8.4   Added Project Rollup section
  || 05/03/07 GHL 8.4.2.1 Added ClassKey for Partners Napier  
  || 07/02/07 GHL 8.5   Added logic for GLCompanyKey, OfficeKey, ClassKey 
  || 07/09/07 GHL 8.5   Restricting ER to VoucherDetailKey null   
  || 02/22/08 GHL 8.5   Added filtering of transactions by GLCompanyKey
  || 04/08/08 GHL 8.508 (23712) Added new logic for classes    
  || 04/26/12 GHL 10.555 (141647) Added CreateAsApproved param  
  || 10/04/12 GHL 10.560 Corrected second call to spProcessWIPWorksheet (missing class)
  || 10/05/12 GHL 10.560 Added Rollup 9 (Project / Billing Item/Item) and @UILayoutKey
  || 08/28/13 RLB 10.571 (185871) Adding Date filters options for IO, PO and BO
  || 10/04/13 GHL 10.573 Added support for multi currency
  || 09/04/14 GHL 10.584 (228260) Added param @OpenOrdersOnly to support new media screens
  || 11/11/14 GHL 10.585 Do not take Misc Cost recs which are on hold
  || 03/16/16 GHL 10.602 Added parameter @wjapp to handle the case when we bill media separately
  || 07/21/16 GHL 10.606 Added action logging for MN''s ToDo 
  || 02/20/19 GHL 19.300 (432772) Added LaborAtNet param to recalc the labor at net instead of gross for WONGDOODY
  || 07/23/21 GHL 21.080 (560579) Adedd Posted Vendor Invoices only 
  || 08/03/23 GAR 23.11.19 (DEV2605) Added InvoiceKeys as an output parameter to pass back for Avalara tax calcs
  || 07/08/26 AMP 26.07.19 (729259) Populate BilledComment on tBillingSchedule when invoiced from T&M mass billing by client
  */
	
	DECLARE @MyStatement As VARCHAR(8000)
	
	create table #tProject (ProjectKey int null, GLCompanyKey int null, CurrencyID varchar(10) null, CurrencyKey int null)
	
	-- list of PO Kinds we use when we query vendor invoices VIs (when @Expense = 1)
	create table #pokind (POKind int null)
	if @WJAPP = 0
	begin
		-- flex code, take all
		insert #pokind (POKind) values (0)
		insert #pokind (POKind) values (1)
		insert #pokind (POKind) values (2)
	end
	else
	begin
		-- wjapp code, there is a setting BillMediaSeparately in wjapp
		-- if BillMediaSeparately = 1, IO and BC = 0, do not take applied VIs
		-- if BillMediaSeparately = 0, IO and BC = 1, take applied VIs  
		insert #pokind (POKind) values (0) -- POs always
		if @IO = 1
			insert #pokind (POKind) values (1)
		if @BC = 1
			insert #pokind (POKind) values (2)
	end

	-- Capture projects and GLCompanyKey
	-- Use GLCompanyKey = 0 because we need a loop to create invoices per client AND GLCompanyKey
	
	-- for a particular client
	IF @InvoiceBy = 1		
	BEGIN	
		SELECT @MyStatement = ''	INSERT #tProject (ProjectKey, GLCompanyKey, CurrencyID, CurrencyKey) '' 
		SELECT @MyStatement = @MyStatement + '' SELECT ProjectKey, ISNULL(GLCompanyKey, 0), CurrencyID, 0 FROM tProject (NOLOCK) ''
		SELECT @MyStatement = @MyStatement + '' WHERE CompanyKey = '' + CAST(@CompanyKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' AND ClientKey = '' + CAST(@ClientKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' AND ProjectKey IN '' + @ProjectKeys
		SELECT @MyStatement = @MyStatement + '' AND NonBillable = 0 AND Closed = 0 ''
	END
	ELSE
	-- for a particular client parent
	BEGIN	
		SELECT @MyStatement = ''	INSERT #tProject (ProjectKey, GLCompanyKey, CurrencyID, CurrencyKey) '' 
		SELECT @MyStatement = @MyStatement + '' SELECT ProjectKey, ISNULL(GLCompanyKey, 0), CurrencyID, 0 FROM tProject (NOLOCK) ''
		SELECT @MyStatement = @MyStatement + '' WHERE CompanyKey = '' + CAST(@CompanyKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' AND ( ClientKey = '' + CAST(@ClientKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' OR ClientKey IN (SELECT CompanyKey FROM tCompany (NOLOCK) ''
		SELECT @MyStatement = @MyStatement + '' WHERE ParentCompanyKey = '' + CAST(@ClientKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' )) ''
		SELECT @MyStatement = @MyStatement + '' AND ProjectKey IN '' + @ProjectKeys
		SELECT @MyStatement = @MyStatement + '' AND NonBillable = 0 AND Closed = 0 ''
	END
	
	EXEC ( @MyStatement )	
	
	DECLARE @CurrencyID varchar(10), @CurrencyKey int

	-- We must manufacture CurrencyKey to use in the loops
	-- CurrencyKey initialized at 0 -- Home Currency
	select @CurrencyID = ''''
	Select @CurrencyKey = 1
	while (1=1)
	begin
		select @CurrencyID = min(CurrencyID)
		from   #tProject
		where  CurrencyID is not null
		and    CurrencyID > @CurrencyID

		if @CurrencyID is null
			break

		update #tProject
		set    CurrencyKey = @CurrencyKey 
		where  CurrencyID = @CurrencyID

		select @CurrencyKey = @CurrencyKey + 1
	end

	-- Note: Simulate code in WIP page before calling spProcessWIPWorksheet

	create table #tProcWIPKeysInit (ProjectKey int null					
								, EntityType varchar(20) null
								, EntityKey varchar(50) null
								, Action int null)
								
	create table #tProcWIPKeys (ProjectKey int null					-- Added to same table in spMassBillingBill
								, EntityType varchar(20) null
								, EntityKey varchar(50) null
								, Action int null)
	TRUNCATE TABLE #tProcWIPKeys

	-- Simulate code in the WIP ASP page
	------------------------------------
	
	DECLARE @UseGLCompany int, @RequireGLCompany int
	
	SELECT @UseGLCompany = ISNULL(UseGLCompany, 0), @RequireGLCompany = ISNULL(RequireGLCompany, 0)
	FROM tPreference (NOLOCK)
	WHERE CompanyKey = @CompanyKey			

	IF @POBeginDate is null
		select @POBeginDate = ''1/1/1960''
	IF @IOBeginDate is null
		select @IOBeginDate = ''1/1/1960''
	IF @BCBeginDate is null
		select @BCBeginDate = ''1/1/1960''
	IF @ThruDate IS NULL
		SELECT @ThruDate = ''01/01/2050''
	IF @IOEndDate is null
		select @IOEndDate = ''01/01/2050''
	IF @BCEndDate is null
		select @BCEndDate = ''01/01/2050''
	IF @POEndDate is null
		select @POEndDate = ''01/01/2050''
			
	if @Time = 1
		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Time'', cast(TimeKey as VARCHAR(50)), 1
		FROM    tTime (NOLOCK), tTimeSheet (nolock), #tProject b
		WHERE   tTime.ProjectKey = b.ProjectKey
		AND		tTime.TimeSheetKey = tTimeSheet.TimeSheetKey
		AND		tTimeSheet.Status = 4
		AND     InvoiceLineKey IS NULL
		AND     (WriteOff IS NULL OR WriteOff = 0)
		AND     ISNULL(OnHold, 0) = 0		
		AND     WorkDate <= @ThruDate
   		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND bill.Status < 5 -- Not Invoiced
				AND   bd.EntityGuid = tTime.TimeKey  
				AND   bd.Entity = ''tTime''
				)

   if @Expense = 1
   BEGIN
		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Expense'', cast(ExpenseReceiptKey as VARCHAR(50)), 1
		FROM    tExpenseReceipt (NOLOCK), tExpenseEnvelope (nolock), #tProject b
		WHERE   tExpenseReceipt.ProjectKey = b.ProjectKey
		AND		tExpenseReceipt.ExpenseEnvelopeKey = tExpenseEnvelope.ExpenseEnvelopeKey
		AND		tExpenseEnvelope.Status = 4
		AND     InvoiceLineKey IS NULL
		AND     (WriteOff IS NULL OR WriteOff = 0)
		AND     ISNULL(OnHold, 0) = 0		
		AND     ExpenseDate <= @ThruDate
   		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = tExpenseReceipt.ExpenseReceiptKey  
				AND   bd.Entity = ''tExpenseReceipt''
				)
		AND		tExpenseReceipt.VoucherDetailKey IS NULL

		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''MiscExpense'', cast(MiscCostKey as VARCHAR(50)), 1
		FROM    tMiscCost (NOLOCK), #tProject b
		WHERE   tMiscCost.ProjectKey = b.ProjectKey
		AND     InvoiceLineKey IS NULL
		AND     (WriteOff IS NULL OR WriteOff = 0)
		AND     ISNULL(OnHold, 0) = 0	
		AND     ExpenseDate <= @ThruDate
   		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = tMiscCost.MiscCostKey  
				AND   bd.Entity = ''tMiscCost''
				)

		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Voucher'', cast(vd.VoucherDetailKey as VARCHAR(50)), 1
		FROM    tVoucherDetail vd (NOLOCK)
				,tVoucher       v  (NOLOCK)
				, #tProject b
		WHERE   vd.ProjectKey = b.ProjectKey
		AND     vd.InvoiceLineKey IS NULL
		AND     ISNULL(vd.WriteOff, 0) = 0
		AND     ISNULL(vd.OnHold, 0) = 0
		AND      vd.VoucherKey = v.VoucherKey
		AND		v.Status = 4
		AND  v.InvoiceDate <= @ThruDate		-- Or DueDate ?
		AND    isnull(vd.PurchaseOrderDetailKey, 0) = 0 -- not applied
		AND    (@PostedOnly = 0 OR v.Posted = 1)
   		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = vd.VoucherDetailKey  
				AND   bd.Entity = ''tVoucherDetail''
				)

	INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Voucher'', cast(vd.VoucherDetailKey as VARCHAR(50)), 1
		FROM    tVoucherDetail vd (NOLOCK)
		INNER JOIN tVoucher v  (NOLOCK) on vd.VoucherKey = v.VoucherKey
		INNER JOIN tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
		INNER JOIN tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		INNER JOIN #tProject b on vd.ProjectKey = b.ProjectKey
		WHERE   vd.ProjectKey = b.ProjectKey
		AND     vd.InvoiceLineKey IS NULL
		AND     ISNULL(vd.WriteOff, 0) = 0
		AND     ISNULL(vd.OnHold, 0) = 0
		AND      vd.VoucherKey = v.VoucherKey
		AND		v.Status = 4
		AND     v.InvoiceDate <= @ThruDate		-- Or DueDate ?
		AND     po.POKind in (select POKind from #pokind) -- applied to PO, IO or BC
		AND    (@PostedOnly = 0 OR v.Posted = 1)
   		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = vd.VoucherDetailKey  
				AND   bd.Entity = ''tVoucherDetail''
				)

	END
	
	IF @PO = 1
		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Order'', cast(pod.PurchaseOrderDetailKey as VARCHAR(50)), 1
		FROM   tPurchaseOrderDetail pod (NOLOCK)
				,tPurchaseOrder po  (NOLOCK)
				, #tProject b
		WHERE   pod.ProjectKey = b.ProjectKey
		AND     pod.InvoiceLineKey IS NULL
		AND      pod.PurchaseOrderKey = po.PurchaseOrderKey
		AND		ISNULL(pod.AppliedCost, 0) = 0
		AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
		AND		ISNULL(pod.AmountBilled, 0) = 0
		AND		po.Status = 4
		AND		po.POKind = 0
		AND     ISNULL(pod.OnHold, 0) = 0		
		AND		po.PODate >= @POBeginDate
		AND		po.PODate <= @POEndDate
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = pod.PurchaseOrderDetailKey  
				AND   bd.Entity = ''tPurchaseOrderDetail''
				)

	IF @IO = 1
		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Order'', cast(pod.PurchaseOrderDetailKey as VARCHAR(50)), 1
		FROM    tPurchaseOrderDetail pod (NOLOCK)
				,tPurchaseOrder po  (NOLOCK)
				, #tProject b
		WHERE   pod.ProjectKey = b.ProjectKey
		AND     pod.InvoiceLineKey IS NULL
		AND      pod.PurchaseOrderKey = po.PurchaseOrderKey
		AND		ISNULL(pod.AppliedCost, 0) = 0
		AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
		AND		ISNULL(pod.AmountBilled, 0) = 0
		AND		po.Status = 4
		AND		po.POKind = 1
		AND     ISNULL(pod.OnHold, 0) = 0		
		AND		pod.DetailOrderDate >= @IOBeginDate
		AND		pod.DetailOrderDate <= @IOEndDate			
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = pod.PurchaseOrderDetailKey  
				AND   bd.Entity = ''tPurchaseOrderDetail''
				)
	
	IF @BC = 1
		INSERT #tProcWIPKeysInit (ProjectKey, EntityType, EntityKey, Action)
		SELECT  b.ProjectKey, ''Order'', cast(pod.PurchaseOrderDetailKey as VARCHAR(50)), 1
		FROM tPurchaseOrderDetail pod (NOLOCK)
				,tPurchaseOrder po  (NOLOCK)
				, #tProject b
		WHERE   pod.ProjectKey = b.ProjectKey
		AND     pod.InvoiceLineKey IS NULL
		AND      pod.PurchaseOrderKey = po.PurchaseOrderKey
		AND		ISNULL(pod.AppliedCost, 0) = 0
		AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
		AND		ISNULL(pod.AmountBilled, 0) = 0
		AND		po.Status = 4
		AND		po.POKind = 2
		AND     ISNULL(pod.OnHold, 0) = 0		
		AND		pod.DetailOrderDate >= @BCBeginDate
		AND		pod.DetailOrderDate <= @BCEndDate		
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
				WHERE bill.CompanyKey = @CompanyKey
				AND   bill.Status < 5 -- Not Invoiced				
				AND   bd.EntityKey = pod.PurchaseOrderDetailKey  
				AND   bd.Entity = ''tPurchaseOrderDetail''
				)
	
	-- End of Simulate code in the WIP ASP page
	-------------------------------------------	

	-- Variables used for logging 
	declare	@Entity varchar(50),
		@EntityKey int,
		@Action varchar(200),
		@ActionDate smalldatetime,
		@ActionBy varchar(500),
		@Comments varchar(4000),
		@Reference varchar(200),
		@SourceCompanyID varchar(100),
		@CampaignKey int,
		@ProjectKey int 

	DECLARE @Ret INT
			,@SingleInvoice INT
			,@GLCompanyCount INT
			,@CurrencyCount INT
			,@GLCompanyKey INT
			,@MissingGLCompany INT
			,@Error INT
			
	SELECT @MissingGLCompany = 0
		   ,@Error = 0
		   							
	SELECT @GLCompanyCount = COUNT(DISTINCT GLCompanyKey) FROM #tProject 
	SELECT @CurrencyCount = COUNT(DISTINCT CurrencyKey) FROM #tProject 

	if @GLCompanyCount = 1 and @CurrencyCount = 1
		select @SingleInvoice = 1
	else
		select @SingleInvoice = 0

	IF @SingleInvoice = 1
	BEGIN
		-- Just ONE Invoice ! We can report on errors
		SELECT @GLCompanyKey = GLCompanyKey FROM #tProject
		SELECT @CurrencyID = CurrencyID FROM #tProject

		-- we must separate the transactions by GLCompanyKey
		TRUNCATE TABLE #tProcWIPKeys
		INSERT #tProcWIPKeys (ProjectKey, EntityType, EntityKey, Action)
		SELECT k.ProjectKey, k.EntityType, k.EntityKey, k.Action
		FROM   #tProcWIPKeysInit k
			INNER JOIN #tProject p ON k.ProjectKey = p.ProjectKey
		WHERE p.GLCompanyKey = @GLCompanyKey

		IF @GLCompanyKey = 0
			SELECT @GLCompanyKey = NULL
		
		IF @GLCompanyKey IS NULL AND @UseGLCompany = 1 AND @RequireGLCompany = 1
			RETURN -1000
					
		-- Call spProcessWIPWorksheet passing the ClientKey instead of ProjectKey
		EXEC @Ret = spProcessWIPWorksheet @ClientKey , @InvoiceBy, @Rollup, @UserKey, NULL, @PercentOfActual
			, @InvoiceDate, @PostingDate, @DefaultClassKey, NULL, @GLCompanyKey, @DefaultOfficeKey, @CreateAsApproved, @UILayoutKey, @CurrencyID

		-- If positive, this is an invoice key, not an error	
		-- No need to return an InvoiceKey in mass billing
		
		IF @Ret > 0
		BEGIN
			IF @BillingStatusKey IS NOT NULL
				UPDATE tProject
				SET    tProject.ProjectBillingStatusKey = @BillingStatusKey
				FROM   #tProject b
				WHERE  tProject.ProjectKey = b.ProjectKey
				
			-- If positive, this is an invoice key, not an error	
			IF @Ret > 0
				EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret
		
			-- Now add a log record

			-- we do not set the project key when billing by client
			select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0, @ProjectKey = 0

			select @Reference = i.InvoiceNumber
				  ,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @Ret

			select @Reference = isnull(@Reference,'''')
				  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through mass billing by client''
			else
				select @Comments = ''Invoice was generated through mass billing by client''

			if @WJAPP = 1
				select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

			if @LaborAtNet = 1
			begin
				exec sptInvoiceLaborAtNet @Ret, @PercentOfActual
			end

			-- Update billing schedules for each project included in this invoice
			DECLARE @BsProjKey int = -1
			WHILE (1=1)
			BEGIN
				SELECT @BsProjKey = MIN(ProjectKey) FROM #tProject WHERE ProjectKey > @BsProjKey
				IF @BsProjKey IS NULL BREAK
				EXEC spFixedFeesUpdateBillingSchedule @Ret, @BsProjKey
			END

			SET @InvoiceKeys = @Ret

			RETURN 1
		END
		ELSE
			RETURN @Ret

	END
	ELSE
	BEGIN
		-- We need to create several invoices, ONE per GLCompanyKey
		-- We would not be able to report on errors
		SELECT @GLCompanyKey = -1
		WHILE (1=1)
		BEGIN
			SELECT @GLCompanyKey = MIN(GLCompanyKey) FROM #tProject
			WHERE GLCompanyKey > @GLCompanyKey
		
			IF @GLCompanyKey IS NULL
				BREAK

			SELECT @CurrencyKey = -1
			WHILE (1=1)
			BEGIN
				SELECT @CurrencyKey = MIN(CurrencyKey)
				FROM   #tProject 
				WHERE  GLCompanyKey   =  @GLCompanyKey	
				AND    CurrencyKey    >  @CurrencyKey
					
				IF @CurrencyKey IS NULL
					BREAK

				select @CurrencyID = CurrencyID from #tProject
				where  CurrencyKey =  @CurrencyKey -- All separate currency IDs should have same key

				-- we must separate the transactions by GLCompanyKey
				TRUNCATE TABLE #tProcWIPKeys
				INSERT #tProcWIPKeys (ProjectKey, EntityType, EntityKey, Action)
				SELECT k.ProjectKey, k.EntityType, k.EntityKey, k.Action
				FROM   #tProcWIPKeysInit k
					INNER JOIN #tProject p ON k.ProjectKey = p.ProjectKey
				WHERE p.GLCompanyKey = @GLCompanyKey
				AND   p.CurrencyKey =  @CurrencyKey

				IF @GLCompanyKey = 0
				BEGIN
					SELECT @GLCompanyKey = NULL
			
					IF @GLCompanyKey IS NULL AND @UseGLCompany = 1 AND @RequireGLCompany = 1
						SELECT @MissingGLCompany = 1
				END
			
				-- Call spProcessWIPWorksheet passing the ClientKey instead of ProjectKey
				EXEC @Ret = spProcessWIPWorksheet @ClientKey , @InvoiceBy, @Rollup, @UserKey, NULL, @PercentOfActual
				, @InvoiceDate, @PostingDate, @DefaultClassKey, NULL, @GLCompanyKey, @DefaultOfficeKey, @CreateAsApproved, @UILayoutKey, @CurrencyID
			
				-- to continue our loop
				SELECT @GLCompanyKey = ISNULL(@GLCompanyKey, 0)
		
				IF @Ret > 0
				BEGIN
					IF @BillingStatusKey IS NOT NULL
						UPDATE tProject
						SET    tProject.ProjectBillingStatusKey = @BillingStatusKey
						FROM   #tProject b
						WHERE  tProject.ProjectKey = b.ProjectKey
					
					-- If positive, this is an invoice key, not an error	
					IF @Ret > 0
						EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret

					SELECT @Error = @Ret	
					
						-- Now add a log record

					-- we do not set the project key when billing by client
					select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0, @ProjectKey = 0

					select @Reference = i.InvoiceNumber
						  ,@SourceCompanyID = c.CustomerID
					from   tInvoice i (nolock)
						left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
					where  i.InvoiceKey = @Ret

					select @Reference = isnull(@Reference,'''')
						  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
					-- the Invoice number may be missing if the user assign #s at approval time
					if len(@Reference) > 0
						select @Comments = ''Invoice '' + @Reference + '' was generated through mass billing by client''
					else
						select @Comments = ''Invoice was generated through mass billing by client''

					if @WJAPP = 1
						select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

					exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

					if @LaborAtNet = 1
					begin
						exec sptInvoiceLaborAtNet @Ret, @PercentOfActual
					end

					-- Update billing schedules for projects included in this GLCompany/Currency invoice
					DECLARE @BsProjKey2 int = -1
					WHILE (1=1)
					BEGIN
						SELECT @BsProjKey2 = MIN(ProjectKey) FROM #tProject
						WHERE  ProjectKey    > @BsProjKey2
						AND    GLCompanyKey  = @GLCompanyKey
						AND    CurrencyKey   = @CurrencyKey
						IF @BsProjKey2 IS NULL BREAK
						EXEC spFixedFeesUpdateBillingSchedule @Ret, @BsProjKey2
					END

					SET @InvoiceKeys = CONCAT(@InvoiceKeys, @Ret, '','')
		
				END	-- @Ret > 0	, Invoice was created						

				IF @MissingGLCompany = 1
					SELECT @Error = -1000
						
			END -- loop on Currency
										
		END -- loop on GLCompany

		SET @InvoiceKeys = SUBSTRING(@InvoiceKeys, 1, LEN(@InvoiceKeys) - 1)
			
		IF @Error < 0
			RETURN @Error
		ELSE
			RETURN 1
			
	END -- several invoices



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptRecentFavoriteToggle]'
GO
IF OBJECT_ID(N'[dbo].[sptRecentFavoriteToggle]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptRecentFavoriteToggle]
(
	@CompanyKey int,
	@UserKey int,
	@Entity varchar(50),
	@EntityKey int
)

as --Encrypt

/*
|| When      Who Rel        What
|| 07/06/26  GG  26.07.01   Created - generic favorite toggle for any entity (replaces sptWidgetDashFavoriteToggle).
||                          Rows are shared with Recent, so toggling off keeps the row when it is still a recent.
*/

Declare @IsFavorite tinyint

if exists (Select 1 from tRecentFavorite (nolock)
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey and ISNULL(Favorite, 0) = 1)
begin
	-- Already a favorite -> turn it off. Keep the row if it is still a recent, otherwise remove it.
	Update tRecentFavorite Set Favorite = 0
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey

	Delete from tRecentFavorite
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey
	  and ISNULL(Favorite, 0) = 0 and ISNULL(Recent, 0) = 0

	Select @IsFavorite = 0
end
else if exists (Select 1 from tRecentFavorite (nolock)
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey)
begin
	-- Row exists (as a recent) but is not a favorite -> flag it.
	Update tRecentFavorite Set Favorite = 1
	Where CompanyKey = @CompanyKey and UserKey = @UserKey and Entity = @Entity and EntityKey = @EntityKey

	Select @IsFavorite = 1
end
else
begin
	-- No row yet -> create it as a favorite.
	Insert into tRecentFavorite (CompanyKey, UserKey, Entity, EntityKey, Favorite, Recent)
	Values (@CompanyKey, @UserKey, @Entity, @EntityKey, 1, 0)

	Select @IsFavorite = 1
end

Select @IsFavorite as isFavorite
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spConvertAppSeedLab]'
GO
IF OBJECT_ID(N'[dbo].[spConvertAppSeedLab]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spConvertAppSeedLab]
(
	@LoadBeta int = 0
)
AS

/*
|| spConvertAppSeedLab 1
|| When      Who Rel      What
||
|| Previous Comments moved to the end of this SP
|| 02/18/19  CRG 19.0.3.0 (421239) Removed PlanningMultipleTasks from the project schedule settings (it is now a setting on the project itself)
|| 02/19/19  CRG 19.0.3.0 (446583) Added Remaining Hours to projectSchedule columns
|| 02/26/19  AMP 19.0.3.0 (440082) Added Client Name and Vendor Name to the GL Drilldown
|| 02/26/19  RLS 19.0.3.0 (444491) Added Campaign Description to the campaignDashBoard
|| 02/26/19  GHL 19.0.3.0 (442017) Added currency to estimate listing (under project)
|| 02/27/19  AMP 19.0.3.0 (447860) Added Journal Entries to the Global Search option
|| 03/04/19  GWG 19.0.3.0  Fixing group options on deliverables board
|| 03/07/19  AMP 19.0.4.0 (447900) Added Date/Time Sent to the Deliverable Approvals
|| 03/11/19  AMP 19.0.4.0 (448928) Added TaskID to Today-Creatives grid view
|| 03/13/09  AMP 19.0.4.0 (422224) Added the Approval Comments and Worksheet Comments to the BillingWorksheetsToApprove, BillingWorksheetsInReview,ReadyToCreateInvoices and BillingWorksheetsAll listings
|| 03/14/19  GHL 19.0.4.0 Added Applied spots and amount to bill on BO grid after discussion with Greg
|| 03/13/19  GWG 19.0.4.0 Adding labs to this side since they mostly affect the menus
|| 03/18/19  CRG 19.0.4.0 (449162) Added prjScheduleExcludeFromStatus to projectSchedule columns
|| 03/18/19  AMP 19.0.4.0 (449681) Added the Currency field as an available field to the projects screen.
|| 03/20/19  MCM 19.0.4.0 (443519) Adding ToDo Board column information
|| 03/21/19  GWG 19.0.4.0 Removing platMedia, officeBlockoutCalendars, plaid, DeliverableBoard, crossProjectPreds  from labs
|| 03/25/19  RLS 19.0.4.0 (443168) Added projectFiles > ShowThumbnails
|| 03/25/19  RLB 19.0.4.0 Added change request options for project and campaign dash boards on client login
|| 03/25/19  GWG 19.0.4.0 Adding in option to show todos on the client dash and a lab for planning projects
|| 03/26/19  MFT 19.0.4.0 (446667) Added Created By columns to approval screens
|| 06/24/19  GAR 19.0.7.0 (416773) Changed description of global file search to File Search / Delete
|| 08/09/19  CRG 19.0.8.0 (454914) Added usePivot lab
|| 08/26/19  GAR 19.0.9.0 (429222) Removed File Search / Delete from labs.
|| 09/25/19  GWG 19.1.00  Moved deliverables to labs
|| 11/15/19  GWG 19.1.2.0 Adding media plans
|| 01/31/20  MFT 20.0.2.0 (478136) Adding ABA
|| 02/05/20  MCM 20.0.2.0 (499413) Added Credit Card Receipts
|| 04/01/20  WDF 20.0.4.0 (499413) Added Merge Duplicates
|| 06/12/20  MCM 20.0.7.0 (518930) Removed Credit card receipts from beta
|| 07/01/20  MFT 20.0.7.0 (486491) Added newLayoutDesignPlatinum
|| 07/27/20  RLB 20.0.8.0 (523358) removed beta tag on change requests
|| 08/06/20  GWG 20.0.9.0  Move merge dupes to labs
|| 09/17/20  RLB 20.1.0.0 (519667) Removed Tracking Forms Beta Tag
|| 09/22/20  CRG 20.1.0.0 (530562) Removed Pivot Table lab
|| 10/21/20  GAR 20.1.1.0 (534408) Removed PProject Change Requests lab
|| 12/04/20  GWG 20.1.2.0  Moved planning projects into general labs
|| 12/14/20  MFT 21.01.17  (530937) Removed NewLayoutDesign (7) and newLayoutDesignPlatinum (106) labs
|| 01/26/21  GAR 21.02.14  (545516) Removed mergeDuplicates (104) lab
|| 03/31/21  GAR 21.04.18.0000 (552751) Remove Planning Projects from labs
|| 04/06/21  GWG 21.04.18  Added newemailto for testing email to control
|| 05/06/21  GHL 21.06.20  (557067) Added newaddvendorinvoice for new Add Vendor Invoice function
|| 05/11/21  MCM 21.06.20  (558000) Added Excel Power Query lab
|| 06/30/21  MCM 21.07.18  (562958) Removed excel power query lab
|| 08/05/21  CRG 21.09.19  (556855) Added real time notification lab
|| 08/06/21  QMD 21.09.19  (DEV2364) Added rich text editor lab
|| 09/14/21  CRG 21.09.19  (556855) Added a customization to the RTN lab
|| 09/27/21  GAR 21.10.17  (DEV2501) Added a lab for Slack integration
|| 10/12/21  MCM 21.11.X   (574012) Removed newemailto
|| 10/26/21  CRG 21.11.14  Per Greg, I''ve removed the customization on the RTN lab
|| 11/23/21  GAR 21.12.19  Added a customization code to the Slack lab
|| 01/05/22  RLB 22.01.23  (582824) removed deliverables board
|| 03/30/22  RLB 22.04.17  (592293) removed Tracking Forms
|| 04/13/22  GHL 22.04.17  (451878) added GL companies with foreign currency
|| 07/27/22  RLB 22.08.14  (606866) move to labs from beta
|| 07/28/22  GHL 22.08.14  (607098) added lab for overtime
|| 08/25/22  KMC 22.12.18  Adding lab for Avalara Sales Tax integration, but leaving commented out until release - needed to turn Beta on
|| 10/11/22  MCM 22.11.x   (605911) added lab for receiptProcessCC
|| 11/10/22  GAR 22.11.20  (618885) Remove Slack from Beta in labs
|| 11/30/22  GAR 22.12.18  (622203) Spelling corrections in text editor lab
|| 12/20/22  GAR 23.01.15  (623756) Remove RTN from Beta in labs
|| 02/22/23  MCM 23.03.x   (630378) Added lab for journal entry approval process
|| 05/02/23  CRG 23.06.18  (630097) Added lab for two factor authentication
|| 05/04/23  MCM 23.06.18  (638917) Removed journal entry approval process from lab
|| 07/30/23  RLB 23.08.20  (646957) moved two factor authentication to a lab
|| 08/29/23  CRG 23.09.17  (649970) Removed two factor authentication from labs
|| 06/20/24  AMP 24.07.14  (671674) Added lab for Existing Invoices link
|| 07/26/24  MFT 24.08.00  (664163) Added lab for CanadianACH
|| 07/30/24  CRG 24.08.18  (679347) Removed RTN lab
|| 08/28/24  MCM 24.09.15  (680536) Added lab for MultiCurrCCBill (Multi Currency Credit Card billing)
|| 01/23/25  AMP 25.02.16  (679537) Removed existing invoices from labs
|| 01/24/25  MCM 25.02.16  (693257) Removed allow GL Companies from Beta in Labs
|| 02/21/25  GAR 25.XX.XX  (688217) Added a new lab for using the new project dashboard
|| 04/12/25  GWG 25.04.XX  Adding a lab for the new themes
|| 05/06/25  GAR 25.06.15  (701013) Remove Avalara from Beta in labs
|| 08/11/25  AMP 25.09.14  (707231) Removed Beta from Media Plans
|| 10/14/25  QMD 25.11.14  (xxxxxx) Added AI lab
|| 01/05/26  MCM 26.01.18  (718694) Removed allow GL Companies from Beta in Labs...again
|| 01/09/26  CRG 26.02.15  (548907) Added Recurring Tasks lab
|| 01/12/26  CRG 26.02.15  (548907) Made Recurring Tasks lab Beta
|| 03/03/26  RLB 26.04.19  (718338) removed Media plan lab
|| 03/19/26  QMD 26.04.19  (724849) Added timesuggestlab
|| 04/08/26  MAS 26.05.17  (714824) Added AI Conversation lab
|| 04/16/26  CRG 26.05.17  (721964) Added Automation lab
|| 04/22/26  MFT 26.05.00  (726644) removed useABALab, canadianACH (now customizations) & vPayment
|| 05/18/26  CRG 26.05.17  Made Automation lab Beta
|| 05/19/26  GWG 26.05.17  Added emailtemplates lab
|| 06/02/26  GWG 26.06.21  Adding timerpill and sidemenu labs
|| 06/25/26  RLS 26.07.19  (731609) Moved recurringTasks, automation, and emailtemplates to ''moved out (general release)''
|| 07/21/26  GWG 26.15.15  Adding in the new card design
*/


DELETE tLab

-- moved out (general release)
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (113,  0, 1, ''slack'', ''Use the Slack integration'', ''This enables integration with Slack.  You will be able to set up a connection to a Slack account and create channels from projects and send diary conversations to a Slack channel.'', '''')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription) Values (65,  1, 1, ''vPayment'', ''(BETA) American Express vPayment process'', '''')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription) Values (102,  1, 1, ''useABALab'', ''(BETA) Use ABA Payments (Australia)'', ''Enables setup fields so ABA files may be generated to be submitted to Australian financial institutions.'')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription) Values (121,  1, 1, ''canadianACH'', ''(BETA) Generate ACH files using the Canadian banking specifications'', ''When enabled, ACH files will be generated using the Canadian banking specifications'')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (114,  0, 1, ''glcompanydiffcurrency'', ''Allow GL companies to have foreign currency'', ''This allows you to have GL companies with a currency different from your home currency'', '''')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (115,  0, 1, ''trackovertime'', ''Track Overtime'', ''This allows you to track overtime with a different cost rate'', '''')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (116,  0, 1, ''avalara'', ''Avalara Sales Tax'', ''This enables integration with Avalara for real time calculation of sales tax'', '''')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (117,  0, 1, ''receiptProcessCC'', ''Receipt Credit Card'', ''This enables users to process multiple receipts with credit card'', '''')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription) Values (122,  0, 1, ''multiCurrCCBill'', ''Multi Currency Credit Card Billing'', ''This allows clients to pay in multi currency.  Currently for authoriz.net with multiple gateways (1 for each currency)'')
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (126,  0, 0, ''recurringTasks'', ''Recurring Tasks'', ''This will allow you to set up recurring tasks on the project schedule.'', '''')  -- moved out (general release) 06/25/26
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (128,  1, 0, ''automation'', ''Automation (BETA)'', ''This will allow you to set up automation rules.'', '''')  -- moved out (general release) 06/25/26
--INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (130,  1, 0, ''emailtemplates'', ''(BETA) Email Templates'', ''This allows you to generate project conversations with templated information from the project.'', '''')  -- moved out (general release) 06/25/26


-- In review to remove
INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription) Values (112,  0, 1, ''richTextEditor'', ''Rich Text Editor'', ''The next text editor form will support the ability to cut and paste with the same style from different applications. Please see the help guide for further information and limitations.'')
INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription) Values (108,  0, 1, ''newaddvendorinvoice'', ''New Add Vendor Invoice'', '''')


-- Labs
INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (123,  0, 1, ''newProjectDashboard'', ''New Project Dashboard'', ''This enables the new project dashboard that is more interactive and configurable.'', '''')

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (124,  0, 1, ''systemThemes'', ''New System Display Themes'', ''This allows you to select one of the new display themes. We do not suggest setting the company wide theme as this will change the display for everyone in your company.'', '''')

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (125,  0, 1, ''ai'', ''AI Feature Testing'', ''This will allow you to test different AI features within the application.'', ''AI'')

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (131,  0, 0, ''timerpill'', ''Persistent timer widget'', ''This enables a timer widget in the bottom left corner of your screen that is visible at all times unless you dock it into the side menu.'', '''')

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (132,  0, 0, ''sidenav'', ''New Side Navigation'', ''This enables the new side menu and header bar'', '''')

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (133,  0, 0, ''appColors'', ''Custom System Colors'', ''This enables you to change key colors in the application like the app bar, side menu, background and light and dark mode'', '''')

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (134,  0, 0, ''newcard'', ''New Card Design'', ''We have updated the card design on the creative today page'', '''')

-- Beta Items

--  NOT MERGED IN YET INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (127,  1, 1, ''timesuggest'', ''Auto Suggest Time Entries'', ''The application will suggest time entries.'', '''')

--  NOT MERGED IN YET INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (129,  1, 0, ''aiConversation'', ''(BETA) AI Conversations'', ''This enables the new conversation AI feature within the application.'', '''')


-- active plat betas   **************   Next Key: 135  *****************  exec spConvertAppSeed 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAICompanyAddressSave]'
GO
IF OBJECT_ID(N'[dbo].[spApiAICompanyAddressSave]', 'P') IS NULL
EXEC sp_executesql N'CREATE    PROCEDURE [dbo].[spApiAICompanyAddressSave]
    @CompanyKey      int,
    @OwnerCompanyKey int,
    @UserKey         int,
    @AddressName     varchar(200),
    @Address1        varchar(100) = NULL,
    @Address2        varchar(100) = NULL,
    @Address3        varchar(100) = NULL,
    @City            varchar(100) = NULL,
    @State           varchar(50)  = NULL,
    @PostalCode      varchar(20)  = NULL,
    @Country         varchar(50)  = NULL,
    @MainAddress     bit          = NULL

AS --Encrypt

/*
|| When      Who Rel        What
|| 07/08/26  GAR 26.08.16   (731183) Created -- AI API helper to add/update a company''s default address
||                           (Address1-3, City, State, PostalCode, Country). Each field is optional
||                           and preserved when omitted -- only supplied fields overwrite the existing
||                           address. Bootstraps tAddress + tCompany.DefaultAddressKey if the company
||                           has no default address yet.
|| 07/09/26  GAR 26.08.16   Reworked to support multiple named addresses per company. @AddressName is
||                           now required and is the lookup key (scoped to the company) -- a match
||                           updates that address, no match inserts a new one. Replaced the old
||                           DefaultAddressKey-only lookup. Added @MainAddress: when 1, the saved
||                           address is promoted to tCompany.DefaultAddressKey. New addresses are no
||                           longer auto-promoted to default -- that only happens when @MainAddress = 1.
|| 07/09/26  GAR 26.08.16   Fixed: stopped setting Entity=''tCompany''/EntityKey=@CompanyKey on insert.
||                           tAddress rows for a plain company address book entry must have Entity/
||                           EntityKey NULL -- Company.vb''s getAddressList (the UI''s company address
||                           list) filters on "Entity IS NULL", so addresses saved with Entity set were
||                           persisted and correctly wired to DefaultAddressKey, but invisible in the UI.
||                           Matches the column list sptCompanyUpdateInfo already uses for its own insert.
|| 07/09/26  GAR 26.08.19   A brand new address is now auto-promoted to the company''s default address
||                           when the company doesn''t have one yet (DefaultAddressKey is NULL/0),
||                           regardless of @MainAddress. @MainAddress is still how a caller explicitly
||                           promotes/re-promotes an address once the company already has a default.
*/

  -- Set up error table
  select * into #errors from tAPIErrorTemplate where 1 = 2

  -- Validate required fields
  if @CompanyKey is null or @CompanyKey = 0
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Company Key is required.'', ''companyKey'')
  end

  if @OwnerCompanyKey is null or @OwnerCompanyKey = 0
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Owner Company is required.'', ''ownerCompanyKey'')
  end

  if @AddressName is null or LEN(@AddressName) = 0
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Address Name is required.'', ''addressName'')
  end

  declare @ErrorCount int
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  declare @CompanyName nvarchar(200)
  select @CompanyName = CompanyName
  from tCompany (nolock)
  where CompanyKey = @CompanyKey
    and OwnerCompanyKey = @OwnerCompanyKey

  if @CompanyName is null
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Company not found for companyKey: '' + CAST(@CompanyKey as varchar(20)), ''companyKey'')
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  begin try

    -- Capture this before any changes -- determines whether a newly-inserted address should
    -- be auto-promoted to default because the company doesn''t have one yet.
    declare @HadNoDefaultAddress bit = 0
    if not exists (select 1 from tCompany (nolock) where CompanyKey = @CompanyKey and isnull(DefaultAddressKey, 0) > 0)
      set @HadNoDefaultAddress = 1

    declare @IsNewAddress bit = 0

    -- Look up an existing address for this company by name -- this (not DefaultAddressKey)
    -- is now the identity of "which address" a call is targeting.
    declare @AddressKey int
    select @AddressKey = AddressKey
    from tAddress (nolock)
    where CompanyKey = @CompanyKey
      and OwnerCompanyKey = @OwnerCompanyKey
      and AddressName = @AddressName
      and Entity is null

    if isnull(@AddressKey, 0) > 0
    begin
      -- Partial update: only overwrite fields that were supplied, keep the rest as-is
      update tAddress
      set Address1   = isnull(@Address1, Address1),
          Address2   = isnull(@Address2, Address2),
          Address3   = isnull(@Address3, Address3),
          City       = isnull(@City, City),
          State      = isnull(@State, State),
          PostalCode = isnull(@PostalCode, PostalCode),
          Country    = isnull(@Country, Country)
      where AddressKey = @AddressKey
    end
    else
    begin
      set @IsNewAddress = 1

      -- Entity/EntityKey are intentionally left NULL -- that''s what marks this as a plain
      -- company address book entry (see Company.vb''s getAddressList, which filters on it).
      insert into tAddress
      (
        OwnerCompanyKey,
        CompanyKey,
        AddressName,
        Address1,
        Address2,
        Address3,
        City,
        State,
        PostalCode,
        Country,
        Active
      )
      values
      (
        @OwnerCompanyKey,
        @CompanyKey,
        @AddressName,
        @Address1,
        @Address2,
        @Address3,
        @City,
        @State,
        @PostalCode,
        @Country,
        1
      )

      select @AddressKey = @@IDENTITY
    end

    -- Promote to the company''s default address when explicitly requested (@MainAddress = 1),
    -- or automatically when this is a brand new address and the company had no default yet.
    if @MainAddress = 1 or (@IsNewAddress = 1 and @HadNoDefaultAddress = 1)
    begin
      update tCompany
      set DefaultAddressKey = @AddressKey
      where CompanyKey = @CompanyKey
    end

    update tCompany
    set LastModified = GETUTCDATE(),
        DateUpdated  = GETUTCDATE()
    where CompanyKey = @CompanyKey

    -- Return any warnings followed by the saved address
    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    select a.AddressKey   as addressKey,
           a.AddressName  as addressName,
           a.Address1     as address1,
           a.Address2     as address2,
           a.Address3     as address3,
           a.City         as city,
           a.State        as state,
           a.PostalCode   as postalCode,
           a.Country      as country,
           case when c.DefaultAddressKey = a.AddressKey then 1 else 0 end as isMainAddress
    from tAddress a (nolock)
    inner join tCompany c (nolock) on c.CompanyKey = a.CompanyKey
    where a.AddressKey = @AddressKey

    drop table #errors

    RETURN @AddressKey

  end try
  begin catch

    declare @ErrMsg nvarchar(4000) = ERROR_MESSAGE()
    declare @ErrSeverity int = ERROR_SEVERITY()

    if object_id(''tempdb..#errors'') is not null
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', @ErrMsg, ''general'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
    end

    RAISERROR(@ErrMsg, @ErrSeverity, 1)
    return -100

  end catch
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptRecentFavoriteLoad]'
GO
IF OBJECT_ID(N'[dbo].[sptRecentFavoriteLoad]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptRecentFavoriteLoad]
(
	@CompanyKey int,
	@UserKey int,
	@Entity varchar(50),
	@DashID varchar(50) = ''''
)

as --Encrypt

/*
|| When      Who Rel        What
|| 07/06/26  GG  26.07.01   Created - generic loader for <cm-source-picker>. Returns three result sets
||                          (All, Recent, Favorite) for the given entity, columns normalized to
||                          [Key] / [Name] so the picker consumes any entity with its default fields.
||                          Add a new IF block per entity, mirroring the tWidgetDash shape.
*/

if @Entity = ''tWidgetDash''
begin
	Declare @SGKey int, @Admin tinyint, @SuspendAdmin tinyint
	Select @SGKey = SecurityGroupKey, @Admin = ISNULL(Administrator, 0), @SuspendAdmin = ISNULL(SuspendAdmin, 0)
	from tUser (nolock) Where UserKey = @UserKey
	if @SuspendAdmin = 1 Select @Admin = 0

	-- WidgetDashKeys this user is allowed to see (mirrors sptWidgetDashLoad''s visibility rules).
	Create Table #visibleDash ( WidgetDashKey int )

	if @Admin = 0
		Insert Into #visibleDash ( WidgetDashKey )
		Select distinct wd.WidgetDashKey from tWidgetDash wd (nolock)
		left outer join tSecurityAccess sa (nolock) on wd.WidgetDashKey = sa.EntityKey and sa.Entity = ''tWidgetDash''
		Where wd.DashID = @DashID and wd.CompanyKey = @CompanyKey
		  and ((ISNULL(wd.UserKey, 0) = 0 and sa.SecurityGroupKey = @SGKey) or wd.UserKey = @UserKey)
	else
		Insert Into #visibleDash ( WidgetDashKey )
		Select distinct wd.WidgetDashKey from tWidgetDash wd (nolock)
		Where wd.DashID = @DashID and wd.CompanyKey = @CompanyKey
		  and (ISNULL(wd.UserKey, 0) = 0 or wd.UserKey = @UserKey)

	-- All
	Select wd.WidgetDashKey as [Key], wd.Label as [Name],
	       case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private
	from tWidgetDash wd (nolock)
	inner join #visibleDash vd (nolock) on wd.WidgetDashKey = vd.WidgetDashKey
	Order by wd.Label

	-- Recent
	Select top 10 wd.WidgetDashKey as [Key], wd.Label as [Name],
	       case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private, rf.DateRecent
	from tRecentFavorite rf (nolock)
	inner join tWidgetDash wd (nolock) on rf.EntityKey = wd.WidgetDashKey
	inner join #visibleDash vd (nolock) on wd.WidgetDashKey = vd.WidgetDashKey
	Where rf.CompanyKey = @CompanyKey and rf.UserKey = @UserKey and rf.Entity = ''tWidgetDash'' and ISNULL(rf.Recent, 0) = 1
	Order by rf.DateRecent desc

	-- Favorite
	Select wd.WidgetDashKey as [Key], wd.Label as [Name],
	       case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private
	from tRecentFavorite rf (nolock)
	inner join tWidgetDash wd (nolock) on rf.EntityKey = wd.WidgetDashKey
	inner join #visibleDash vd (nolock) on wd.WidgetDashKey = vd.WidgetDashKey
	Where rf.CompanyKey = @CompanyKey and rf.UserKey = @UserKey and rf.Entity = ''tWidgetDash'' and ISNULL(rf.Favorite, 0) = 1
	Order by wd.Label

	return
end

-- ── Add additional entity blocks above this line, mirroring tWidgetDash. ──
-- Fallback for an entity with no dedicated block: no label table to join, so All is
-- empty and Recent/Favorite echo the EntityKey as the name. Keeps the picker functional
-- (and errors-free) until a real block is added.
Select cast(null as int) as [Key], cast(null as varchar(1)) as [Name] Where 1 = 0

Select rf.EntityKey as [Key], cast(rf.EntityKey as varchar(50)) as [Name], rf.DateRecent
from tRecentFavorite rf (nolock)
Where rf.CompanyKey = @CompanyKey and rf.UserKey = @UserKey and rf.Entity = @Entity and ISNULL(rf.Recent, 0) = 1
Order by rf.DateRecent desc

Select rf.EntityKey as [Key], cast(rf.EntityKey as varchar(50)) as [Name]
from tRecentFavorite rf (nolock)
Where rf.CompanyKey = @CompanyKey and rf.UserKey = @UserKey and rf.Entity = @Entity and ISNULL(rf.Favorite, 0) = 1
Order by rf.EntityKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateSendNotification]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateSendNotification]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateSendNotification]
	@ActivityKey int,
	@SendNotification int = NULL
AS

/*
|| When      Who Rel      What
|| 8/23/19   GAR 18.9.0.0 (416097) Created to store user''s choice to send email notifications or not
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time, this is an internal flag update
*/

	UPDATE	tActivity
	SET		SendNotification = @SendNotification
	WHERE	ActivityKey = @ActivityKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetDSO]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetDSO]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIGetDSO]
(
    @CompanyKey        int,
    @UserKey           int,
    @AsOfDate          datetime = null,   -- defaults to today
    @RevenueWindowDays int      = 90,     -- trailing window for the sales denominator
    @GLCompanyID       varchar(50) = null,
    @RedDSO            int      = 75,      -- DSO at/above = red
    @YellowDSO         int      = 60,      -- DSO at/above = yellow
    @IncludeComparison tinyint  = 1        -- 1 = compute prior-window DSO
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GHL 26.xx      Created. Days Sales Outstanding for the AI CFO MCP tool.
||                          DSO = ending open AR / billed revenue over trailing N days * N.
||                          Open AR = InvoiceTotalAmount - AmountReceived - RetainerAmount
||                          on posted, non-advance invoices dated on/before as-of with a positive balance.
||                          Revenue = tInvoiceLine.TotalAmount on posted, non-advance invoices in window.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    if @AsOfDate is null set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())
    if ISNULL(@RevenueWindowDays, 0) <= 0 set @RevenueWindowDays = 90

    ------------------------------------------------------------
    -- Rights: AR aging / invoice summary (admins bypass)
    ------------------------------------------------------------
    declare @IsAdministrator tinyint, @SecurityGroupKey int
    select @IsAdministrator = ISNULL(Administrator, 0), @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock) where UserKey = @UserKey and CompanyKey = @CompanyKey

    if @SecurityGroupKey is null and @IsAdministrator = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    if @IsAdministrator = 0
    begin
        if not exists (
            select 1 from tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where ra.EntityType = ''Security Group''
              and ra.EntityKey  = @SecurityGroupKey
              and r.RightID in (''acct_ar_aging'', ''acct_ar_invoicesummary'', ''billingviewclientinvoice''))
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''You do not have rights to view AR / DSO.'', ''general'')
            select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
            drop table #errors
            return -103
        end
    end

    ------------------------------------------------------------
    -- Resolve GL company filter + restriction
    ------------------------------------------------------------
    declare @RestrictToGLCompany tinyint
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    from   tPreference (nolock) where CompanyKey = @CompanyKey

    declare @GLCompanyKey int = null
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
        select @GLCompanyKey = GLCompanyKey
        from   tGLCompany (nolock)
        where  CompanyKey = @CompanyKey and GLCompanyID = @GLCompanyID

    ------------------------------------------------------------
    -- Window bounds (current + prior)
    ------------------------------------------------------------
    declare @CurRevStart   datetime = DATEADD(d, -(@RevenueWindowDays - 1), @AsOfDate)
    declare @PriorAsOf     datetime = DATEADD(d, -@RevenueWindowDays, @AsOfDate)
    declare @PriorRevStart datetime = DATEADD(d, -(@RevenueWindowDays - 1), @PriorAsOf)

    ------------------------------------------------------------
    -- Helper measures
    ------------------------------------------------------------
    declare @EndingAR money, @Revenue money, @PriorEndingAR money, @PriorRevenue money

    -- Ending open AR as of @AsOfDate
    select @EndingAR = ISNULL(SUM(ISNULL(i.InvoiceTotalAmount,0) - ISNULL(i.AmountReceived,0) - ISNULL(i.RetainerAmount,0)), 0)
    from   tInvoice i (nolock)
    where  i.CompanyKey = @CompanyKey
      and  ISNULL(i.Posted,0) = 1
      and  ISNULL(i.AdvanceBill,0) = 0
      and  i.InvoiceDate <= @AsOfDate
      and  (ISNULL(i.InvoiceTotalAmount,0) - ISNULL(i.AmountReceived,0) - ISNULL(i.RetainerAmount,0)) > 0
      and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
      and  (@RestrictToGLCompany = 0
            or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))

    -- Billed revenue over the trailing window
    select @Revenue = ISNULL(SUM(il.TotalAmount), 0)
    from   tInvoiceLine il (nolock)
    inner join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
    where  i.CompanyKey = @CompanyKey
      and  ISNULL(i.Posted,0) = 1
      and  ISNULL(i.AdvanceBill,0) = 0
      and  i.InvoiceDate >= @CurRevStart and i.InvoiceDate <= @AsOfDate
      and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
      and  (@RestrictToGLCompany = 0
            or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))

    if @IncludeComparison = 1
    begin
        select @PriorEndingAR = ISNULL(SUM(ISNULL(i.InvoiceTotalAmount,0) - ISNULL(i.AmountReceived,0) - ISNULL(i.RetainerAmount,0)), 0)
        from   tInvoice i (nolock)
        where  i.CompanyKey = @CompanyKey
          and  ISNULL(i.Posted,0) = 1
          and  ISNULL(i.AdvanceBill,0) = 0
          and  i.InvoiceDate <= @PriorAsOf
          and  (ISNULL(i.InvoiceTotalAmount,0) - ISNULL(i.AmountReceived,0) - ISNULL(i.RetainerAmount,0)) > 0
          and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0
                or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))

        select @PriorRevenue = ISNULL(SUM(il.TotalAmount), 0)
        from   tInvoiceLine il (nolock)
        inner join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
        where  i.CompanyKey = @CompanyKey
          and  ISNULL(i.Posted,0) = 1
          and  ISNULL(i.AdvanceBill,0) = 0
          and  i.InvoiceDate >= @PriorRevStart and i.InvoiceDate <= @PriorAsOf
          and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0
                or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))
    end

    declare @DSO decimal(9,2) = case when @Revenue > 0
                                     then CONVERT(decimal(9,2), @EndingAR / @Revenue * @RevenueWindowDays) else 0 end
    declare @PriorDSO decimal(9,2) = case when ISNULL(@PriorRevenue,0) > 0
                                          then CONVERT(decimal(9,2), @PriorEndingAR / @PriorRevenue * @RevenueWindowDays) else 0 end

    ------------------------------------------------------------
    -- Warnings
    ------------------------------------------------------------
    if @Revenue <= 0
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''PARTIAL_DATA'', ''No billed revenue in the trailing window — DSO cannot be computed and is reported as 0.'', ''general'')

    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    ------------------------------------------------------------
    -- Result (single meta row)
    ------------------------------------------------------------
    select
         CONVERT(varchar(10), @AsOfDate, 120)                                as asOf
        ,@RevenueWindowDays                                                  as revenueWindowDays
        ,@EndingAR                                                           as endingAR
        ,@Revenue                                                            as trailingRevenue
        ,@DSO                                                                as dso
        ,case when @IncludeComparison = 1 then @PriorEndingAR else null end  as priorEndingAR
        ,case when @IncludeComparison = 1 then @PriorRevenue  else null end  as priorTrailingRevenue
        ,case when @IncludeComparison = 1 then @PriorDSO      else null end  as priorDso
        ,case when @IncludeComparison = 1 then CONVERT(decimal(9,2), @DSO - @PriorDSO) else null end as dsoDelta
        ,@RedDSO                                                             as redDSO
        ,@YellowDSO                                                          as yellowDSO
        ,case
            when @Revenue <= 0            then ''gray''
            when @DSO >= @RedDSO          then ''red''
            when @DSO >= @YellowDSO       then ''yellow''
            else ''green''
         end                                                                 as severity
        ,case
            when @Revenue <= 0            then ''no_revenue''
            when @DSO >= @RedDSO          then ''collections_priority''
            when @DSO >= @YellowDSO       then ''watch''
            else ''healthy''
         end                                                                 as flag
        ,CONVERT(varchar(10), @CurRevStart, 120)                             as windowStart
        ,CONVERT(varchar(10), @AsOfDate, 120)                                as windowEnd

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetFinancialTargets]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetFinancialTargets]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIGetFinancialTargets]
(
    @CompanyKey    int,
    @UserKey       int,
    @StartDate     datetime,              -- window start (required)
    @EndDate       datetime,              -- window end (required)
    @BudgetName    varchar(100) = null,   -- resolve budget by name; else the active budget
    @GLCompanyID   varchar(50)  = null,
    @IncludeActual tinyint      = 1       -- 1 = also return GL actuals + variance
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GHL 26.xx      Created. Financial targets (budgeted revenue / COGS / expense / net) for the
||                          AI CFO MCP tool. Sources tGLBudget/tGLBudgetDetail. The budget is a 12-month
||                          template (Month1..Month12); each calendar month in the window is mapped to a
||                          fiscal month index via tPreference.FirstMonth. Revenue = GL AccountType 40/41,
||                          COGS = 50, Expense = 51/52. Optional GL actuals from tTransaction for variance.
||                          Use categories[Revenue].budgetedAmount as the revenue target for pipeline coverage.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    ------------------------------------------------------------
    -- Validation
    ------------------------------------------------------------
    if @StartDate is null or @EndDate is null
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''startDate and endDate are required.'', ''startDate'')
    else if @EndDate < @StartDate
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''endDate must be on or after startDate.'', ''endDate'')

    ------------------------------------------------------------
    -- Rights: corporate P&L (admins bypass)
    ------------------------------------------------------------
    declare @IsAdministrator tinyint, @SecurityGroupKey int
    select @IsAdministrator = ISNULL(Administrator, 0), @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock) where UserKey = @UserKey and CompanyKey = @CompanyKey

    if @SecurityGroupKey is null and @IsAdministrator = 0
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

    if @IsAdministrator = 0 and @SecurityGroupKey is not null
       and not exists (
            select 1 from tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where ra.EntityType = ''Security Group''
              and ra.EntityKey  = @SecurityGroupKey
              and r.RightID = ''acct_gl_pl_ytd'')
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''You do not have rights to view financial targets (acct_gl_pl_ytd).'', ''general'')

    declare @ErrorCount int
    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -100
    end

    ------------------------------------------------------------
    -- GL company restriction + optional filter
    ------------------------------------------------------------
    declare @RestrictToGLCompany tinyint
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    from   tPreference (nolock) where CompanyKey = @CompanyKey

    declare @GLCompanyKey int = null
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
        select @GLCompanyKey = GLCompanyKey
        from   tGLCompany (nolock)
        where  CompanyKey = @CompanyKey and GLCompanyID = @GLCompanyID

    ------------------------------------------------------------
    -- Resolve budget (by name, else the active budget). Keys are never
    -- exposed to callers, so the LLM selects by name; when the choice is
    -- ambiguous or unresolved we surface the available names to pick from.
    ------------------------------------------------------------
    declare @GLBudgetKey int = null

    -- Comma list of budgets a caller could name (active first, then the rest)
    declare @AvailableBudgets varchar(4000)
    select @AvailableBudgets = STUFF((
        select '', '' + BudgetName
        from   tGLBudget (nolock)
        where  CompanyKey = @CompanyKey
        order by ISNULL(Active,0) desc, BudgetName
        for xml path(''''), type).value(''.'', ''varchar(4000)''), 1, 2, '''')

    if @BudgetName is not null and LTRIM(RTRIM(@BudgetName)) <> ''''
        select @GLBudgetKey = MIN(GLBudgetKey)
        from   tGLBudget (nolock)
        where  CompanyKey = @CompanyKey and BudgetName = @BudgetName

    declare @NameNotFound tinyint = 0
    if @BudgetName is not null and LTRIM(RTRIM(@BudgetName)) <> '''' and @GLBudgetKey is null
        set @NameNotFound = 1

    declare @ActiveCount int = 0
    if @GLBudgetKey is null
    begin
        select @ActiveCount = COUNT(*) from tGLBudget (nolock)
        where CompanyKey = @CompanyKey and ISNULL(Active,0) = 1

        select @GLBudgetKey = MIN(GLBudgetKey) from tGLBudget (nolock)
        where CompanyKey = @CompanyKey and ISNULL(Active,0) = 1
    end

    declare @ResolvedBudgetName varchar(100) = null
    if @GLBudgetKey is not null
        select @ResolvedBudgetName = BudgetName from tGLBudget (nolock) where GLBudgetKey = @GLBudgetKey

    if @NameNotFound = 1
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'',
                ''Budget "'' + @BudgetName + ''" not found; used the active budget instead. Available budgets: ''
                    + ISNULL(@AvailableBudgets, ''(none)'') + ''.'', ''budgetName'')

    if @GLBudgetKey is null
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'',
                ''No active GL budget found — targets returned as 0.''
                    + case when @AvailableBudgets is not null then '' Available budgets: '' + @AvailableBudgets + ''.'' else '''' end,
                ''general'')
    else if @NameNotFound = 0 and @BudgetName is null and @ActiveCount > 1
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''AMBIGUOUS'',
                ''Multiple active budgets exist; used "'' + ISNULL(@ResolvedBudgetName, '''') + ''". Pass budgetName to choose. Available: ''
                    + ISNULL(@AvailableBudgets, '''') + ''.'', ''budgetName'')

    ------------------------------------------------------------
    -- Map each calendar month in the window to a fiscal month index (1..12)
    ------------------------------------------------------------
    declare @FirstMonth int
    select @FirstMonth = ISNULL(FirstMonth, 1) from tPreference (nolock) where CompanyKey = @CompanyKey
    if ISNULL(@FirstMonth,0) not between 1 and 12 set @FirstMonth = 1

    create table #months (FiscalIdx int)

    declare @Cur datetime = DATEFROMPARTS(YEAR(@StartDate), MONTH(@StartDate), 1)
    declare @Stop datetime = DATEFROMPARTS(YEAR(@EndDate), MONTH(@EndDate), 1)
    declare @Guard int = 0
    while @Cur <= @Stop and @Guard < 60
    begin
        insert into #months (FiscalIdx) values ( ((MONTH(@Cur) - @FirstMonth + 12) % 12) + 1 )
        set @Cur = DATEADD(m, 1, @Cur)
        set @Guard = @Guard + 1
    end

    ------------------------------------------------------------
    -- Budgeted amounts by category (unpivot Month1..12, join #months on fiscal index)
    ------------------------------------------------------------
    declare @BudRevenue money = 0, @BudCOGS money = 0, @BudExpense money = 0

    if @GLBudgetKey is not null
    begin
        ;with bud as
        (
            select gl.AccountType, v.FiscalIdx, v.Amount
            from   tGLBudgetDetail d (nolock)
            inner join tGLAccount gl (nolock) on d.GLAccountKey = gl.GLAccountKey
            cross apply (values
                (1,d.Month1),(2,d.Month2),(3,d.Month3),(4,d.Month4),
                (5,d.Month5),(6,d.Month6),(7,d.Month7),(8,d.Month8),
                (9,d.Month9),(10,d.Month10),(11,d.Month11),(12,d.Month12)) v(FiscalIdx, Amount)
            where  d.GLBudgetKey = @GLBudgetKey
              and  gl.AccountType in (40,41,50,51,52)
              and  (@GLCompanyKey is null or d.GLCompanyKey = @GLCompanyKey)
              and  (@RestrictToGLCompany = 0
                    or d.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))
        )
        select
             @BudRevenue = ISNULL(SUM(case when b.AccountType in (40,41) then b.Amount else 0 end), 0)
            ,@BudCOGS    = ISNULL(SUM(case when b.AccountType = 50 then b.Amount else 0 end), 0)
            ,@BudExpense = ISNULL(SUM(case when b.AccountType in (51,52) then b.Amount else 0 end), 0)
        from bud b
        inner join #months m on b.FiscalIdx = m.FiscalIdx
    end

    ------------------------------------------------------------
    -- Actuals from GL (income = Credit-Debit; cost/expense = Debit-Credit)
    ------------------------------------------------------------
    declare @ActRevenue money = 0, @ActCOGS money = 0, @ActExpense money = 0

    if @IncludeActual = 1
    begin
        select
             @ActRevenue = ISNULL(SUM(case when gl.AccountType in (40,41) then (t.Credit - t.Debit) else 0 end), 0)
            ,@ActCOGS    = ISNULL(SUM(case when gl.AccountType = 50 then (t.Debit - t.Credit) else 0 end), 0)
            ,@ActExpense = ISNULL(SUM(case when gl.AccountType in (51,52) then (t.Debit - t.Credit) else 0 end), 0)
        from   tTransaction t (nolock)
        inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
        where  t.CompanyKey = @CompanyKey
          and  gl.AccountType in (40,41,50,51,52)
          and  t.TransactionDate >= @StartDate and t.TransactionDate <= @EndDate
          and  (@GLCompanyKey is null or t.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0
                or t.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))
    end

    ------------------------------------------------------------
    -- Warnings + meta
    ------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    select
         @GLBudgetKey                                            as glBudgetKey
        ,@ResolvedBudgetName                                    as budgetName
        ,@FirstMonth                                            as fiscalFirstMonth
        ,(select COUNT(*) from #months)                         as monthsInWindow
        ,CONVERT(varchar(10), @StartDate, 120)                  as windowStart
        ,CONVERT(varchar(10), @EndDate, 120)                    as windowEnd
        ,@IncludeActual                                         as includeActual

    ------------------------------------------------------------
    -- Categories (one row each; Net = Revenue - COGS - Expense)
    ------------------------------------------------------------
    ;with cat as
    (
        select ''Revenue''   as category, 1 as sortOrder, @BudRevenue as budgeted, @ActRevenue as actual
        union all select ''COGS'',       2, @BudCOGS,    @ActCOGS
        union all select ''Expense'',    3, @BudExpense, @ActExpense
        union all select ''NetIncome'',  4, @BudRevenue - @BudCOGS - @BudExpense,
                                           @ActRevenue - @ActCOGS - @ActExpense
    )
    select
         c.category                                             as category
        ,c.budgeted                                             as budgetedAmount
        ,case when @IncludeActual = 1 then c.actual else null end as actualAmount
        ,case when @IncludeActual = 1 then c.actual - c.budgeted else null end as variance
        ,case when @IncludeActual = 1 and c.budgeted <> 0
              then CONVERT(decimal(9,2), 100.0 * (c.actual - c.budgeted) / ABS(c.budgeted)) else null end as variancePct
        ,case
            when @IncludeActual = 0 or c.budgeted = 0 then ''gray''
            -- Revenue/Net: under target is bad. COGS/Expense: over target is bad.
            when c.category in (''Revenue'',''NetIncome'') then
                case when c.actual >= c.budgeted then ''green''
                     when c.actual >= c.budgeted * 0.9 then ''yellow'' else ''red'' end
            else
                case when c.actual <= c.budgeted then ''green''
                     when c.actual <= c.budgeted * 1.1 then ''yellow'' else ''red'' end
         end                                                    as severity
    from cat c
    order by c.sortOrder

    drop table #months
    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptContactActivityInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptContactActivityInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptContactActivityInsert]
	@CompanyKey int,
	@Type varchar(50),
	@Priority varchar(20),
	@Subject varchar(200),
	@ContactCompanyKey int,
	@ContactKey int,
	@AssignedUserKey int,
	@Status smallint,
	@Outcome smallint,
	@ActivityDate smalldatetime,
	@ActivityTime varchar(50),
	@LeadKey int,
	@ProjectKey int,
	@Notes text,
	@oIdentity INT OUTPUT
AS --Encrypt

  /*
  || When      Who Rel      What
  || 01/08/09  GHL 10.016   Updating now tActivity instead of tContactActivity
  || 7/10/09   CRG 10.5.0.3 Removed TimeZoneIndex
  || 12/21/10  GHL 10.5.3.9 Added ActivityEntity (''Activity'' always)
  || 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time - this proc no longer being used 
  */

Declare @DateCompleted smalldatetime
Declare @Completed int
Declare @ActivityEntity varchar(50)

select @ActivityEntity = ''Activity''

if @Status = 2
	Select @DateCompleted = GETDATE(), @Completed = 1
else
	Select @DateCompleted = NULL, @Completed = 0

-- clone of spConverttActivity
INSERT tActivity
		(
		CompanyKey,
		ParentActivityKey,
		RootActivityKey,
		Private,
		Type,
		Priority,
		Subject,
		ContactCompanyKey,
		ContactKey,
		UserLeadKey,
		LeadKey,
		ProjectKey,
		StandardActivityKey,
		AssignedUserKey,
		OriginatorUserKey,
		CustomFieldKey,
		VisibleToClient,
		Outcome,
		ActivityDate,
		StartTime,
		EndTime,
		ReminderMinutes,
		ActivityTime,
		Completed,
		DateCompleted,
		Notes,
		AddedByKey,
		UpdatedByKey,
		ActivityEntity
		)
	Select
		@CompanyKey,
		0, -- parent key
		0, -- root key
		0, -- private
		@Type,
		@Priority,
		@Subject,
		@ContactCompanyKey,
		@ContactKey,
		NULL, -- UserLeadKey
		@LeadKey,
		@ProjectKey,
		NULL, -- StandardActivityKey
		@AssignedUserKey,
		@AssignedUserKey, --originator
		NULL, -- custom field key
		0,  -- visible to client
		@Outcome,
		@ActivityDate,
		NULL, --start time
		NULL, -- end time
		0, -- reminder min
		@ActivityTime,
		@Completed,
		@DateCompleted,
		@Notes,
		@AssignedUserKey,
		@AssignedUserKey,
		@ActivityEntity

	SELECT @oIdentity = @@IDENTITY

	Update tActivity Set RootActivityKey = ActivityKey Where ActivityKey = @oIdentity
	
	RETURN 1
	



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectCopy]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectCopy]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[sptProjectCopy]
 (
 @UserKey int,
 @ProjectName nvarchar(100),
 @ProjectNumber varchar(100),
 @CompanyKey int,
 @ProjectStatusKey int,
 @ProjectTypeKey int,
 @ClientDivisionKey int,
 @ClientProductKey int,
 @OfficeKey int,
 @GLCompanyKey int,
 @ClassKey int,
 @ClientKey int,
 @RequestKey int,
 @CopyProjectKey int,
 @CopyEstimate tinyint,
 @CopyFrom int, -- 0 from project, 1 from project type, 2 from project template on UI
 @EstimateInternalApprover int,
 @AccountManager int,
 @TeamKey int,  
 @LeadKey int,
 @ProjectColor varchar(10),  
 @ModelYear varchar(10) = null, 
 @CampaignKey int = null,
 @DefaultRetainerKey int = null,
 @Template tinyint = 0,
 @Opportunity tinyint = 0,
 @RetainerKey int = null,
 @Retainer tinyint = 0,
 @IsLegacy bit = 0, --To be deprecated
 @ProjectManager int = null,
 @DoNotCopyAssignments int = null,
 @oIdentity INT OUTPUT  
 )
AS --Encrypt
----------------------------------------
-- SEX:  NOTE: If Add parameter, also add it to sptProjectCopy_OneTransaction
-----------------------------------------
  /*
  || When     Who Rel      What
  || 10/16/06 GHL 8.4      Removed SummaryTaskKey parm when calling sptTaskQuickInsert 
  ||                       Added CanTrackBudget parm when calling sptTaskQuickInsert
  || 12/13/06 GHL 8.4      Added validation of master tasks
  || 12/21/06 GHL 8.4      Added logic to prevent duplicates in tAssignment
  || 04/10/07 QMD 8.4.2	   Added ProjectColor field -- See Issue 8638 for more information
  || 06/15/07 GWG 8.5      Added GL Company Key
  || 11/07/07 CRG 8.5      (9503) Modified to only pull over Active users from the copied project
  || 8/6/08   CRG 10.1.0.0 (31724) Modified to default the Labor and Purchasing rate sheet info from the Client if they''re not copying from another project.
  ||                       (31632) Fixed logic problem where it was not executing the copy master tasks functionality if they were copying from the project type.
  || 8/29/08  CRG 10.1.0.0 (32709) Modified so that team memebers are added when not copying a project
  || 9/10/08  CRG 10.0.0.8 (the release formerly known as 10.1.0.0) Removed If statement that was doing nothing.
  || 11/4/08  CRG 10.0.1.2 (39543) Moved the insert into tProjectUserServices outside of the CopyProject If block so that it''ll default the services whether
  ||                       you are copying the projects or not.
  || 12/29/08 CRG 10.0.1.5 (39387) Now updating new tProject column: TeamKey
  || 12/1/10  RLB 10.5.3.9 (94833) just adding Default User Service instead of all users services
  || 07/19/11 RLB 10.5.4.6 (116508) set project Billing Method from copied project
  || 09/27/11 GWG 10.5.4.8 (122426) Reversed the last change for billing method
  || 10/27/11 GWG 10.5.4.9 Added the copy of the client budget columns from the template
  || 11/08/11 GWG 10.5.5.1 Moved the update of hourly rate to the bottom and removed a duplicate reference since it should always happen
  || 11/22/11 RLB 10.5.5.1 (124338) If client has a Default EstimateTemplate or layout set that on the Estimates
  || 03/28/12 GWG 10.5.5.4 Added in the defaulting of GLCompanySource and copying of deliverables
  || 10/5/12  CRG 10.5.6.0 Added call to sptProjectWebDavSafeFolders
  || 02/12/13 GHL 10.5.6.5 (167857) Added ModelYear for a customization for Spark44
  || 06/18/13 GHL 10.5.6.9 (181721) Added campaign key for new project numbers by campaign
  || 08/26/13 RLB 10.5.7.1 (170225) Set BillingManagerKey from Client Default
  || 09/12/13 GHL 10.5.7.2 Copying now currency ID from client to project
  || 11/25/13 RLB 10.5.7.4 (197740) Adding some validation for client and selected gl company
  || 08/27/14 GHL 10.5.8.3 (227654) Only validate client and GL company if client key > 0
  || 11/05/14 RLB 10.5.8.6 Copy AnyoneChargeTime over to new project from template
  || 12/19/14 WDF 10.5.8.7 (237583) Add @DefaultRetainerKey
  || 02/06/15 GHL 10.5.8.8 When copying defaults from the client, do not forget the title info
  || 03/27/15 GHL 10.5.9.1 Added constants for CopyFrom
  || 05/15/15 GHL 10.5.9.2 (254386) Change for Abelson Taylor. If the client says ''Lock Labor Rate'', we should pull the ''Get Rate From''
  ||                       from the client, else do as usual 
  || 06/30/15 MCM 10.5.9.3 (261476) Updated to pull the AutoIDTask from tPreferences.DefaultAutoIDTask
  || 09/25/15 GHL 10.5.9.6 Added Opportunity parameter for projects under an opportunity
  ||                       Added Template parameter for project templates which do not require project status
  || 09/30/15 WDF 10.5.9.6 (270980) Copy Description from Template 
  || 10/23/15 GHL 10.5.9.7  DoNotPostWIP = 1 for opportunity projects
  || 10/30/15 WDF 10.5.9.7 (257042) Added customization for ''AVERA''
  || 02/23/16 GHL 10.6.0.1  DEV1740 todo 2930 MN''s request in ToDo: Templates must have GetRateFrom = FromClient
  || 08/20/16 GWG 10.6.0.7 Added the insert from tRequestSplit
  || 09/29/16 RLB 10.6.0.8 (314235) Added copying any default deliverable users 
  || 01/04/17 GWG 10.6.1.1 Adding tracking for the source project that this project was copied from
  || 03/13/17 MFT 10.6.1.4 (335024) Added @IsLegacy and logic. May be removed when this sp is no longer called from classic
  || 04/04/17 MFT 10.6.1.4 (335024) caught exception for Template copy.
  || 06/05/17 MCM 10.6.1.7 (347853) Added SalesTax and SalesTax2 to be pulled from the company table
  || 06/07/17 MCM 10.6.1.7 (347853) Updated Sales Tax Info to recalc the estimate sales tax if applicable.
  || 01/17/18 GHL 18.2.0   (380667) For Partners Napier, get rates from template ou project instead of client
  || 05/31/18 GHL 18.6.0   Added Retainer and RetainerKey parameters for the new advanced features functionality in wjapp
  ||                       This is similar to what we did for the opportunity. Also set the BillingMethod to 3
  || 06/01/18 WDF 18.6.0   (402185) Added AccountManager for Kohls customization for Templates
  || 09/11/18 GHL 18.9.1   (420027) Templates should have get rate/markup from service/item instead of client/project
  || 10/10/18 RLB 18.9.2   (417883) Add Trans Pref to copy deliverables by default set to pull them
  || 06/06/19 RLB 19.0.7.0 (446229) Added project manager 
  || 10/02/19 MCM 19.1.0.0 (481718) If the project we''re copying is a template, then we pull the GLCompanySource from the tPrefernce
  || 01/28/20 CRG 20.0.2.0 (498769) We are now allowing Get Rate From "Task" in Platinum
  || 02/05/20 GHL 20.0.3.0 (495024) Get layout and templates from the GL company
  || 02/13/20 QMD 20.0.3.0 () Remove the update on the tRetainer where the projectkey is no longer valid.
  || 04/10/20 GAR 20.0.5.0 (493286) Added SubscribeFileUpload to pull from the employee record when creating new assignments
  || 09/02/20 GHL 20.0.9.0 (524833) When we create an opportunity project (not real), make the company Overhead to prevent
  ||                        to show on PL repts...only if that is the only project for the company/client
  || 10/12/20 CRG 20.1.0.0 (532716) Removed the Master Task check
  || 11/23/20 RLS 20.1.2.0 (535729) Changed @ProjectName to nvarchar
  || 01/28/21 GAR 21.01.14 (545162) Made changes to the default internal approver for estimates
  || 02/08/21 CRG 21.03.14 (521442) Now copying PlanningProjectAutoRollover for Planning Projects
  || 06/04/21 MCM 21.07.18 (560867) If the internal approver on the estimate is 0 then set to the account manager
  || 09/03/21 MCM 21.09.19 (570477) Added check for campaign Key and project key must be same. copying from sptProjectUpdate- Now returning an error if the campaign client is not the same as the project client and the campaign''s BillBy is not set to Project.
  || 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
  || 01/18/23 RLS 23.02.19 (625948) When copying form a project/template, use the services defined in the project/template
  || 03/02/23 RLS 23.03.19 (631460) Remove changes from 625948 (directly above)
  || 03/02/23 RLS 23.04.16 (589021) Added @DoNotCopyAssignments
  || 04/20/23 MCM 23.04.x  (638276) Added note to also update sptProjectCopy_OneTransaction if add parameter
  || 08/06/24 RLS 24.09.15  (673662) Added BillingManagerKey to the @EstimateInternalApprover logic
  || 12/18/24 RLB 25.01.19 (688771) added added check for new user options subscribe project or to do when AM/PM only
  || 01/21/26 CRG 26.02.15 (717807) Now defaulting BucketPerWeek from copied project
  || 01/30/26 GAR 26.02.15 (718857) Check if Avalara is enabled before copying estimate taxes
  || 07/14/26 RLB 26.08.16 (731407) Copy DoNotPostWIP over to new project from template
 */
  
  DECLARE @RequireMasterTask INT
  declare @Customizations varchar(1000)
  declare @SparkCustomization int
  declare @AveraCustomization int
  declare @PartnersnapierCustomization int
  declare @MultiCurrency int
  declare @RestrictToGLCompany int
  declare @LayoutFromGLCompany int
  declare @AutoIDTasks int  
  declare @AvalaraEnabled smallint
 
  -- copy from template is converted to copy from project in ProjectSetup.vb, so only use 2 constants 
  declare @kCopyFromProject int						select @kCopyFromProject = 0
  declare @kCopyFromProjectType int					select @kCopyFromProjectType = 1
 
  IF isnull(@ClientKey, 0) > 0 and isnull(@DefaultRetainerKey, 0) > 0
  BEGIN 
	IF EXISTS (SELECT 1
			     FROM tCompany (NOLOCK)
			    WHERE CompanyKey = @ClientKey
			      AND DefaultBillingMethod = 3)
			UPDATE tCompany 
			  set DefaultRetainerKey = @DefaultRetainerKey
			WHERE  CompanyKey = @ClientKey 
  END

  IF ISNULL(@CampaignKey, 0) > 0
  BEGIN
		DECLARE @CampaignClientKey int,
				@BillBy smallint
		
		SELECT	@CampaignClientKey = ClientKey,
				@BillBy = BillBy
		FROM	tCampaign (nolock)
		WHERE	CampaignKey = @CampaignKey
		
		IF @ClientKey <> @CampaignClientKey AND @BillBy <> 1
			RETURN -7 --The campaign must be for the same client, unless the campaign''s BillBy is set to "Project" (1)
  END	
 
  SELECT @RequireMasterTask = ISNULL(RequireMasterTask, 0)
        ,@Customizations = UPPER(ISNULL(Customizations, ''''))
		,@MultiCurrency = isnull(MultiCurrency, 0)
		,@RestrictToGLCompany = isnull(RestrictToGLCompany, 0)
		,@AutoIDTasks = isNull(DefaultAutoIDTask, 0)  
		,@LayoutFromGLCompany = isnull(LayoutFromGLCompany,0)
		,@AvalaraEnabled = ISNULL(AvalaraEnabled, 0)
  FROM   tPreference (NOLOCK)
  WHERE  CompanyKey = @CompanyKey 

  IF @RestrictToGLCompany = 1 And isnull(@ClientKey, 0) > 0
  BEGIN
	IF NOT EXISTS (SELECT 1
				   FROM  tGLCompanyAccess (NOLOCK)
				   WHERE CompanyKey = @CompanyKey
				    AND Entity = ''tCompany''
					AND EntityKey = @ClientKey
					AND GLCompanyKey = @GLCompanyKey)
					RETURN -15

  END

select @AveraCustomization = 0
if (charindex(''AVERA'',@Customizations) > 0) and (@CopyFrom = @kCopyFromProject)
begin
	if @CopyProjectKey > 0
	begin 
		if not exists(select ProjectNumber from tProject (nolock) where ProjectKey = @CopyProjectKey and Template = 1)
		begin
			select @AveraCustomization = 1
		end
	end
end
 
-- for Partners Napier, we will pull the rate and markup from the template or project, instead of the client
select @PartnersnapierCustomization = 0
if charindex(''PARTNERSNAPIER'',@Customizations) > 0
begin
	if @CopyProjectKey > 0
		select @PartnersnapierCustomization = 1
end

if charindex(''SPARK44'',@Customizations) > 0
begin
	select @SparkCustomization = 1

	if @ModelYear is null
	begin
		if @CopyProjectKey > 0
			select @ModelYear = ModelYear from tProject (nolock) where ProjectKey = @CopyProjectKey

		if @ModelYear is null
			select @ModelYear = DATEPART("YEAR",GETDATE()) - 2000

		if len(@ModelYear) = 1
			select @ModelYear = ''0'' + @ModelYear

	end

end
else
	select @SparkCustomization = 0


	DECLARE @RetVal INT
	       ,@ProjectKey INT
	       ,@SpecCustomFieldKey INT
	       ,@ValidateRetainer INT

	-- if we have a retainer key, do not validate the default retainer on the client
	if isnull(@RetainerKey, 0) > 0
		select @ValidateRetainer = 0
	else
		select @ValidateRetainer = 1

	-- First call sptProjectCreate
	EXEC @RetVal = sptProjectCreate
				@UserKey,
				@ProjectName,
				@ProjectNumber,
				@CompanyKey,
				@ProjectStatusKey,
				@ProjectTypeKey,
				@ClientDivisionKey,
				@ClientProductKey,
				@OfficeKey,
				@GLCompanyKey,
				@ClientKey,
				@CampaignKey,
				@ProjectColor,
				@SparkCustomization,
				@AveraCustomization,
				@CopyProjectKey,
				@ModelYear,
				@Template,
				@ValidateRetainer,
				@IsLegacy,
				@ProjectKey OUTPUT
	
	IF @RetVal <> 1 
	BEGIN
		SELECT @oIdentity = 0
		RETURN @RetVal
	END
	
	-- if this is not a real project but an opportunity
	-- do the links now before any error happens
	if @Opportunity = 1
	begin
		update tProject
		set    Opportunity = 1
		      ,LeadKey = @LeadKey
			  ,DoNotPostWIP = 1
		where ProjectKey = @ProjectKey

		update tLead
		set    ProjectKey = @ProjectKey
		where  LeadKey = @LeadKey

		-- mark the company Overhead to prevent the project to show on PL report with time entries
		update tCompany
		set    Overhead = 1
		where  CompanyKey = @ClientKey
		and    isnull(BillableClient,0) = 0 -- only if not a client yet
		-- and this is the only one for the client
		and    not exists (select 1 from tProject (nolock) 
			where ProjectKey <> @ProjectKey
			and   CompanyKey = @CompanyKey -- for index 
			and   ClientKey = @ClientKey)
	end
	 
	-- if this is not a real project but a retainer
	-- do the links now before any error happens
	if @Retainer = 1
	begin
		update tProject
		set    Retainer = 1
		      ,RetainerKey = @RetainerKey
			  ,DoNotPostWIP = 1
			  ,BillingMethod = 3 -- Retainer
		where ProjectKey = @ProjectKey

	end

	SELECT @oIdentity = @ProjectKey

	--Set the WebDav safe folder names
	EXEC sptProjectWebDavSafeFolders @ProjectKey, 0
	
	IF @RequestKey > 0
	begin
		
		Update	tProject
		Set		RequestKey = @RequestKey
		Where	ProjectKey = @ProjectKey

		Insert Into tProjectSplitBilling (ProjectKey, ClientKey, PercentageSplit)
		Select @ProjectKey, ClientKey, Split
		From tRequestSplit (nolock) Where RequestKey = @RequestKey
		
	end

	DECLARE @GetRateFrom SMALLINT, @GetMarkupFrom SMALLINT, @LockRateFrom SMALLINT, @LockMarkupFrom SMALLINT
		   ,@DefaultGLCompanySource SMALLINT,@CopyDeliverables SMALLINT

	Select @DefaultGLCompanySource = ISNULL(DefaultGLCompanySource, 0), @CopyDeliverables = ISNULL(CopyDeliverables, 1) from tPreference (nolock) Where CompanyKey = @CompanyKey
	Update tProject Set GLCompanySource = @DefaultGLCompanySource Where ProjectKey = @ProjectKey

	IF (ISNULL(@CopyProjectKey, 0) = 0) AND (@CopyFrom <> @kCopyFromProjectType )
	BEGIN
		IF ISNULL(@ClientKey, 0) > 0
		BEGIN
			UPDATE	tProject 
			SET		tProject.GetRateFrom = 
				CASE @IsLegacy
					WHEN 1 THEN ISNULL(cl.GetRateFrom, 2)
					ELSE
						CASE ISNULL(cl.GetRateFrom, 2)
							WHEN 1 THEN 2
							--WHEN 6 THEN 4
							ELSE ISNULL(cl.GetRateFrom, 2)
						END
				END
				,tProject.TimeRateSheetKey = ISNULL(cl.TimeRateSheetKey, 0)
				,tProject.TitleRateSheetKey = ISNULL(cl.TitleRateSheetKey, 0)
				,tProject.HourlyRate = ISNULL(cl.HourlyRate, 0)
				,tProject.GetMarkupFrom = ISNULL(cl.GetMarkupFrom, 2)
				,tProject.ItemRateSheetKey = ISNULL(cl.ItemRateSheetKey, 0)
				,tProject.ItemMarkup = ISNULL(cl.ItemMarkup, 0)
			FROM	tCompany cl (NOLOCK)
			WHERE	cl.CompanyKey = @ClientKey
			AND		tProject.ProjectKey = @ProjectKey
		END
		
		-- If a team was specified, add the people in it. Allowing team members even if @DoNotCopyAssignments
		IF ISNULL(@TeamKey, 0) > 0
			INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
			SELECT DISTINCT @ProjectKey  -- new ProjectKey
					,tTeamUser.UserKey, 0
			FROM	tTeamUser (NOLOCK)
			INNER JOIN tUser u (nolock) ON tTeamUser.UserKey = u.UserKey
			WHERE	tTeamUser.TeamKey = @TeamKey
			AND		u.Active = 1
			AND		tTeamUser.UserKey not in (Select UserKey from tAssignment (nolock) Where ProjectKey = @ProjectKey)

		-- correct markups/getrate for templates
		if isnull(@Template, 0) = 1
		begin
			UPDATE	tProject 
			SET
				AccountManager = @AccountManager
				,ProjectManager = @ProjectManager
			   -- ,GetRateFrom = CASE @IsLegacy WHEN 1 THEN 1 ELSE 2 END -- client or project
			    ,GetRateFrom = 4 -- service
				,TimeRateSheetKey = null
				,TitleRateSheetKey = null
				,HourlyRate = 0
				--,GetMarkupFrom = 1 -- client
				,GetMarkupFrom = 3 -- item
				,ItemRateSheetKey = null
				,ItemMarkup = 0  
				,IOCommission = 0
				,BCCommission = 0
			where	ProjectKey = @ProjectKey
		end
		 
	END	
	ELSE
	BEGIN
		-- CopyProjectKey > 0 OR CopyFrom = @kCopyFromProjectType

		-- Copy these settings from the other project
		IF @IsLegacy = 1
			UPDATE
				tProject
			SET
				tProject.GetRateFrom = p2.GetRateFrom,
				tProject.TimeRateSheetKey = p2.TimeRateSheetKey,
				tProject.TitleRateSheetKey = p2.TitleRateSheetKey,
				tProject.HourlyRate = p2.HourlyRate,
				tProject.GetMarkupFrom = p2.GetMarkupFrom,
				tProject.ItemRateSheetKey = p2.ItemRateSheetKey,
				tProject.ItemMarkup = p2.ItemMarkup,
				tProject.IOCommission = p2.IOCommission,
				tProject.BCCommission = p2.BCCommission,
				tProject.ScheduleDirection = p2.ScheduleDirection,
				tProject.ClassKey = ISNULL(p2.ClassKey, @ClassKey),
				tProject.SourceProjectKey = @CopyProjectKey
			FROM tProject
				,tProject p2 (NOLOCK)
			WHERE
				tProject.ProjectKey = @ProjectKey 
			AND  
				p2.ProjectKey = @CopyProjectKey
		ELSE
			UPDATE
				tProject
			SET
				tProject.ScheduleDirection = p2.ScheduleDirection,
				tProject.ClassKey = ISNULL(p2.ClassKey, @ClassKey),
				tProject.SourceProjectKey = @CopyProjectKey,
				tProject.PlanningProjectAutoRollover = p2.PlanningProjectAutoRollover,
				tProject.BucketPerWeek = p2.BucketPerWeek
			FROM tProject
				,tProject p2 (NOLOCK)
			WHERE
				tProject.ProjectKey = @ProjectKey 
			AND  
				p2.ProjectKey = @CopyProjectKey
		
		-- Check if we need to get defaults from the client
		If ISNULL(@ClientKey, 0) > 0
		BEGIN
			SELECT @GetRateFrom =
				CASE @IsLegacy
					WHEN 1 THEN ISNULL(GetRateFrom, 2)
					ELSE
						CASE ISNULL(GetRateFrom, 2)
							WHEN 1 THEN 2
							--WHEN 6 THEN 4
							ELSE ISNULL(GetRateFrom, 2)
						END
				END
				,@GetMarkupFrom = isnull(GetMarkupFrom, 0)
			FROM   tProject (NOLOCK)
			WHERE  ProjectKey = @ProjectKey
			
			select @LockRateFrom = isnull(LockLaborRate, 0)
				  ,@LockMarkupFrom = isnull(LockMarkupFrom, 0)
			from   tCompany (nolock)
			where  CompanyKey = @ClientKey

			-- If Get Rate from Client or the Client says it is locked
			IF @GetRateFrom = 1 Or @LockRateFrom = 1
			BEGIN
				UPDATE tProject 
				SET
					tProject.GetRateFrom =
						CASE @IsLegacy
							WHEN 1 THEN ISNULL(cl.GetRateFrom, 2)
							ELSE
								CASE ISNULL(cl.GetRateFrom, 2)
									WHEN 1 THEN 2
									--WHEN 6 THEN 4
									ELSE ISNULL(cl.GetRateFrom, 2)
								END
						END
					,tProject.TimeRateSheetKey = ISNULL(cl.TimeRateSheetKey, 0)
					,tProject.TitleRateSheetKey = ISNULL(cl.TitleRateSheetKey, 0)
					,tProject.HourlyRate = ISNULL(cl.HourlyRate, 0)
				FROM   tCompany cl (NOLOCK)
				WHERE  cl.CompanyKey = @ClientKey
				AND    cl.GetRateFrom IS NOT NULL
				AND    tProject.ProjectKey = @ProjectKey
			END	

			-- If Get Markup  from Client or the Client says it is locked
			IF @GetMarkupFrom = 1 Or @LockMarkupFrom = 1
			BEGIN
				UPDATE tProject 
				SET    tProject.GetMarkupFrom = ISNULL(cl.GetMarkupFrom, 2)
					  ,tProject.ItemRateSheetKey = ISNULL(cl.ItemRateSheetKey, 0)
					  ,tProject.ItemMarkup = ISNULL(cl.ItemMarkup, 0)
				FROM   tCompany cl (NOLOCK)
				WHERE  cl.CompanyKey = @ClientKey
				AND    cl.GetMarkupFrom IS NOT NULL
				AND  tProject.ProjectKey = @ProjectKey
			END	

		END -- ClientKey > 0
			
		-- Now copy detail from CopyProjectKey to ProjectKey
		UPDATE
			tProject
		SET
			tProject.BillingContact = CASE 
				WHEN tProject.ClientKey = p2.ClientKey THEN p2.BillingContact
				ELSE NULL
				END,
			tProject.OverrideRate = p2.OverrideRate,
			tProject.NonBillable = p2.NonBillable,
			tProject.ScheduleDirection = p2.ScheduleDirection,
			tProject.ClientBHours = p2.ClientBHours,
			tProject.ClientBLabor = p2.ClientBLabor,
			tProject.ClientBCO = p2.ClientBCO,
			tProject.ClientBExpenses = p2.ClientBExpenses,
			tProject.ClientAHours = p2.ClientAHours,
			tProject.ClientALabor = p2.ClientALabor,
			tProject.ClientAPO = p2.ClientAPO,
			tProject.ClientAExpenses = p2.ClientAExpenses,
			tProject.GLCompanySource = ISNULL(p2.GLCompanySource, @DefaultGLCompanySource),
			tProject.AnyoneChargeTime = p2.AnyoneChargeTime,
			tProject.DoNotPostWIP = p2.DoNotPostWIP,
			tProject.Description = p2.Description
		FROM tProject (NOLOCK) 
			 ,tProject p2 (NOLOCK)
		WHERE
			tProject.ProjectKey = @ProjectKey 
		AND  
			p2.ProjectKey = @CopyProjectKey

		-- correct markups/getrate for templates
		if isnull(@Template, 0) = 1
		begin
			UPDATE	tProject 
			SET
				AccountManager = @AccountManager
				,ProjectManager = @ProjectManager
			   --,GetRateFrom = CASE @IsLegacy WHEN 1 THEN 1 ELSE 2 END -- client or project
			    ,GetRateFrom = 4 -- service
				,TimeRateSheetKey = null
				,TitleRateSheetKey = null
				,HourlyRate = 0
				--,GetMarkupFrom = 1 -- client
				,GetMarkupFrom = 3 -- item
				,ItemRateSheetKey = null
				,ItemMarkup = 0  
				,IOCommission = 0
				,BCCommission = 0
			where	ProjectKey = @ProjectKey
		end

		-- for Partners Napier, we will pull the rate and markup from the template or project, instead of the client
		if @PartnersnapierCustomization = 1
		begin
			UPDATE tProject
			SET
				tProject.GetRateFrom = p2.GetRateFrom,
				tProject.TimeRateSheetKey = p2.TimeRateSheetKey,
				tProject.TitleRateSheetKey = p2.TitleRateSheetKey,
				tProject.HourlyRate = p2.HourlyRate,
				tProject.GetMarkupFrom = p2.GetMarkupFrom,
				tProject.ItemRateSheetKey = p2.ItemRateSheetKey,
				tProject.ItemMarkup = p2.ItemMarkup,
				tProject.IOCommission = p2.IOCommission,
				tProject.BCCommission = p2.BCCommission,
				tProject.SourceProjectKey = @CopyProjectKey
			FROM tProject
				,tProject p2 (NOLOCK)
			WHERE
				tProject.ProjectKey = @ProjectKey 
			AND  
				p2.ProjectKey = @CopyProjectKey
		end

		 -- sptProjectCreate assigns people with AutoAssign = 0 and the creator even if AutoAssign = 0
		 -- Copy now people from the old project
		IF ISNULL(@DoNotCopyAssignments, 0) = 0
			INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
			SELECT DISTINCT @ProjectKey  -- new ProjectKey
					,tAssignment.UserKey, 0
			FROM	tAssignment (NOLOCK)
			INNER JOIN tUser u (nolock) ON tAssignment.UserKey = u.UserKey
			WHERE	ProjectKey = @CopyProjectKey 
			AND		u.Active = 1
			AND		tAssignment.UserKey not in (Select UserKey from tAssignment (nolock) Where ProjectKey = @ProjectKey)

		-- If a team was specified, add the people in it. Allowing team members even if @DoNotCopyAssignments
		IF ISNULL(@TeamKey, 0) > 0
			INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
			SELECT DISTINCT @ProjectKey  -- new ProjectKey
					,tTeamUser.UserKey, 0
			FROM	tTeamUser (NOLOCK)
			INNER JOIN tUser u (nolock) ON tTeamUser.UserKey = u.UserKey
			WHERE	tTeamUser.TeamKey = @TeamKey
			AND		u.Active = 1
			AND		tTeamUser.UserKey not in (Select UserKey from tAssignment (nolock) Where ProjectKey = @ProjectKey)

		if @CopyFrom = @kCopyFromProject 
		BEGIN
			exec sptProjectCopyTasks @ProjectKey, @CopyProjectKey, @CopyEstimate, @UserKey, @DoNotCopyAssignments
		END
		ELSE
		BEGIN
			
			Declare @MaxOrder int, @NewTaskKey int, @CurOrder int, @CurMTID varchar(100)
			Select @MaxOrder = Max(DisplayOrder), @CurOrder = 0 from tProjectTypeMasterTask (NOLOCK) Where ProjectTypeKey = @ProjectTypeKey
			
			While @CurOrder < @MaxOrder
			BEGIN
				Select @CurOrder = @CurOrder + 1
				Select @CurMTID = TaskID from tProjectTypeMasterTask (NOLOCK) 
					inner join tMasterTask (NOLOCK) on tProjectTypeMasterTask.MasterTaskKey = tMasterTask.MasterTaskKey
				Where ProjectTypeKey = @ProjectTypeKey and DisplayOrder = @CurOrder
				if @CurMTID is not null
				BEGIN
					exec sptTaskQuickInsert @ProjectKey, @CurMTID, NULL, 0, 1, @NewTaskKey OUTPUT
				END
			END
			
			exec sptTaskOrder @ProjectKey, 0, 0, 0
		END
		
		-- Defaulting Layout, Estimate Template and Billing Manager from client onto Estimate
		DECLARE @DefaultLayoutKey int, @DefaultEstimateTemplateKey int, @DefaultBillingManagerKey int, @SalesTaxKey int, @SalesTax2Key int
		If ISNULL(@ClientKey, 0) > 0
			Select @DefaultLayoutKey = ISNULL(LayoutKey, 0), @DefaultEstimateTemplateKey = ISNULL(EstimateTemplateKey, 0), @DefaultBillingManagerKey = ISNULL(BillingManagerKey, 0 )
			,@SalesTaxKey = SalesTaxKey, @SalesTax2Key = SalesTax2Key
			from tCompany (NOLOCK) Where CompanyKey = @ClientKey

		if @LayoutFromGLCompany = 0 and ISNULL(@DefaultEstimateTemplateKey, 0) <> 0
			UPDATE tEstimate
			SET EstimateTemplateKey = @DefaultEstimateTemplateKey
			WHERE ProjectKey = @ProjectKey

		if @LayoutFromGLCompany = 0 and ISNULL(@DefaultLayoutKey, 0) <> 0
			UPDATE tEstimate
			SET LayoutKey = @DefaultLayoutKey
			WHERE ProjectKey = @ProjectKey

		if @LayoutFromGLCompany = 1 and isnull(@GLCompanyKey,0) > 0
		begin
			Select @DefaultLayoutKey = ISNULL(LayoutKey, 0), @DefaultEstimateTemplateKey = ISNULL(EstimateTemplateKey, 0)
			from tGLCompany (NOLOCK) Where GLCompanyKey = @GLCompanyKey

			if ISNULL(@DefaultEstimateTemplateKey, 0) <> 0
				UPDATE tEstimate
				SET EstimateTemplateKey = @DefaultEstimateTemplateKey
				WHERE ProjectKey = @ProjectKey

			if ISNULL(@DefaultLayoutKey, 0) <> 0
				UPDATE tEstimate
				SET LayoutKey = @DefaultLayoutKey
				WHERE ProjectKey = @ProjectKey
		end

		-- 545162 - GAR - If we pass in the EstimateInternalApprover, use that, if its -1 use the AM from the project, if its -3 use the PM from the project, if its -4 use the BM from the project
		If isnull(@EstimateInternalApprover, 0) > 0
			UPDATE tEstimate
			SET    InternalApprover = @EstimateInternalApprover
			WHERE  ProjectKey = @ProjectKey
		Else If isnull(@EstimateInternalApprover, 0) = -1
			UPDATE tEstimate
			SET    InternalApprover = (SELECT ISNULL(AccountManager, @UserKey) FROM tProject WHERE ProjectKey = @ProjectKey)
			WHERE  ProjectKey = @ProjectKey
		Else If isnull(@EstimateInternalApprover, 0) = -3
			UPDATE tEstimate
			SET    InternalApprover = (SELECT ISNULL(ProjectManager, @UserKey) FROM tProject WHERE ProjectKey = @ProjectKey)
			WHERE  ProjectKey = @ProjectKey
		Else If isnull(@EstimateInternalApprover, 0) = -4
			UPDATE tEstimate
			SET    InternalApprover = (SELECT ISNULL(BillingManagerKey, @UserKey) FROM tProject WHERE ProjectKey = @ProjectKey)
			WHERE  ProjectKey = @ProjectKey
		Else If isnull(@EstimateInternalApprover, 0) = 0
			UPDATE tEstimate
			SET    InternalApprover = (SELECT ISNULL(ProjectManager, @UserKey) FROM tProject WHERE ProjectKey = @ProjectKey)
			WHERE  ProjectKey = @ProjectKey

		if ISNULL(@DefaultBillingManagerKey, 0) <> 0
			UPDATE tProject
			SET BillingManagerKey = @DefaultBillingManagerKey
			WHERE ProjectKey = @ProjectKey
			
		if ISNULL(@SalesTaxKey, 0) <> 0
			UPDATE tEstimate
			SET SalesTaxKey = @SalesTaxKey
			WHERE ProjectKey = @ProjectKey

		if ISNULL(@SalesTax2Key, 0) <> 0
			UPDATE tEstimate
			SET SalesTax2Key = @SalesTax2Key
			WHERE ProjectKey = @ProjectKey

			
		if exists (SELECT 1 from tProject WHERE ProjectKey = @CopyProjectKey AND Template = 1)
			BEGIN
				UPDATE	tProject 
					SET
					GLCompanySource = @DefaultGLCompanySource
					where	ProjectKey = @ProjectKey
			END

		if ISNULL(@SalesTaxKey, 0) <> 0 OR ISNULL(@SalesTax2Key, 0) <> 0 
			BEGIN
			--Reclalc sales tax 
			declare @EstimateKey int, @ApprovedQty int, @SalesTax1Amount money, @SalesTax2Amount money

			select @EstimateKey = 0
			while (1=1)
				begin
					select @EstimateKey = min(EstimateKey)
					from   tEstimate (nolock)
					where  ProjectKey = @ProjectKey
					and    EstimateKey > @EstimateKey
					-- And not approved
					AND    NOT  ((isnull(ExternalApprover, 0) > 0 and  ExternalStatus = 4) 
								Or (isnull(ExternalApprover, 0) = 0 and  InternalStatus = 4))  

					if @EstimateKey is null
						break

					Select @ApprovedQty = ApprovedQty from tEstimate (nolock) where EstimateKey = @EstimateKey
					Exec sptEstimateRecalcSalesTax @EstimateKey, @ApprovedQty, @SalesTax1Amount OUTPUT, @SalesTax2Amount 

					if @AvalaraEnabled = 1	
						begin
						Update tEstimate set SalesTaxAmount = 0, SalesTax2Amount = 0 where EstimateKey = @EstimateKey
						end						
					else
						begin
						Update tEstimate set SalesTaxAmount = @SalesTax1Amount, SalesTax2Amount = @SalesTax2Amount where EstimateKey = @EstimateKey
						end

					Exec sptEstimateTaskRollupDetail @EstimateKey
				end
			END
	END

	-- Allowing this even if @DoNotCopyAssignments because team members are inserted in tAssignment, so they need to be updated here.
	-- insert trigger should be setting SubscribeDiary and SubscribeToDo on tAssignment removing setting them here (688771)
	UPDATE tAssignment 
	SET    tAssignment.HourlyRate = u.HourlyRate,
		   tAssignment.SubscribeFileUpload = ISNULL(u.SubscribeFileUpload, 0),
		   tAssignment.DeliverableReviewer = ISNULL(u.DeliverableReviewer, 0),
		   tAssignment.DeliverableNotify = ISNULL(u.DeliverableNotify, 0)

	FROM   tUser u (NOLOCK)
	WHERE  tAssignment.UserKey = u.UserKey
	AND    tAssignment.ProjectKey = @ProjectKey
	
	-- Allowing this even if @DoNotCopyAssignments for users who are AutoAssign = 1, we need their services
	Delete tProjectUserServices Where ProjectKey = @ProjectKey
	
	Insert tProjectUserServices (ProjectKey, UserKey, ServiceKey)
		Select DISTINCT @ProjectKey, u.UserKey, u.DefaultServiceKey
		from tUser u (nolock) 
		inner join tAssignment a (nolock) on u.UserKey = a.UserKey  
		Where ISNULL(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
		And   a.ProjectKey = @ProjectKey And u.DefaultServiceKey IS NOT NULL

	declare @CurrencyID varchar(10)  -- will be null by default
	if @MultiCurrency = 1 and isnull(@ClientKey, 0) > 0
		select @CurrencyID = CurrencyID from tCompany (nolock) where CompanyKey = @ClientKey


	UPDATE	tProject
	SET		TeamKey = @TeamKey
	       ,LeadKey = @LeadKey
		   ,ModelYear = @ModelYear
		   ,CurrencyID = @CurrencyID
		   ,AutoIDTask = @AutoIDTasks 
	WHERE	ProjectKey = @ProjectKey

	-- copy all the deliverables over
	-- new Pref should default to copy
	IF @CopyDeliverables = 1
		EXEC sptReviewDeliverableProjectCopy @CompanyKey, @ProjectKey, @CopyProjectKey, @UserKey

	-- Copies any deliverables from a request to the project. No option. Just does it
	if @RequestKey > 0
		Exec sptProjectCopyDeliverableFromRequest @CompanyKey, @ProjectKey, @RequestKey
 			
 /* set nocount on */
 return 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddUpdateProject]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddUpdateProject]', 'P') IS NOT NULL
EXEC sp_executesql N'-- Created by GitHub Copilot in SSMS - review carefully before executing

ALTER PROCEDURE [dbo].[spApiAIAddUpdateProject]
    (
        @CompanyKey int,
        @UserKey int,
        @ProjectName nvarchar(100),
        @ProjectNumber varchar(100) = null,
        @ProjectStatusID varchar(50) = null,
        @ProjectTypeName varchar(50) = null,
        @ClientDivisionID varchar(50) = null,
        @ClientProductID varchar(50) = null,
        @OfficeID varchar(50) = null,
        @GLCompanyID varchar(50) = null,
        @ClassID varchar(50) = null,
        @Client nvarchar(500),
        @CopyProjectNumber varchar(100) = null,
        @CopyEstimate tinyint = 1,
        @EstimateInternalApproverUserID varchar(100) = null,
        @AccountManager nvarchar(500) = null,
        @TeamName varchar(50) = null,
        @LeadID varchar(50) = null,
        @ProjectColor varchar(10) = null,
        @ModelYear varchar(10) = null,
        @CampaignID varchar(50) = null,
        @Template tinyint = 0,
        @Opportunity tinyint = 0,
        @ProjectManager nvarchar(500) = null,
        @DoNotCopyAssignments int = 0,
		@EstimateLikeProjectNumber varchar(100) = null,
		@StatusNotes nvarchar(max) = null

    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 01/21/26  XXX 26.02.15   Created - AI-friendly version of sptProjectCopy that accepts text IDs instead of keys
|| 01/21/26  XXX 26.02.15   Added update capability with security checks (GL Company, assignment, prjAccessAny)
|| 01/21/26  XXX 26.02.15   Added change tracking for updates (returns old/new values)
|| 04/27/26  XXX 26.02.15   Enhanced user lookup to support UserID, Email, or "FirstName LastName"
|| 04/27/26  XXX 26.02.15   Renamed parameters @AccountManagerUserID to @AccountManager, @ProjectManagerUserID to @ProjectManager
|| 05/01/26  CRG 26.05.17   Added UPPER around the lookup values
|| 05/12/26  GRY 26.06.15   Added @EstimateLikeProjectNumber to copy estimate+tasks from a like project on create
|| 05/05/26  CRG 26.05.17   Validated required Project Type field
|| 06/08/26  GAR 26.07.19   (730440) ProjectType can be inherited from copy/template project; validation deferred until after all lookups
|| 05/28/26  AI  26.05.28   spCheckAccess (tProject) on update path replaces inline GL company + assignment checks.
|| 06/18/26  GAR 26.07.19   (730520) Added custom field key so we can get custom fields on the front end.
|| 07/10/26  GAR 26.07.19   Added gating security - create requires adminCreateProject, update requires prjInfo.
|| 07/21/26  GAR 26.08.16   (731957) Return @CopyProjectKey so the MCP layer can drive spec-sheet copying (copySpecs param).
|| 07/23/26  GAR 26.08.16   (732943) Added @StatusNotes; StatusNotesUpdated is stamped automatically by tU_tProject''s trigger logic.
|| 07/28/26  GAR 26.08.16   (733662) Updated the sptActionLogInsert call to not include @ActionBy so it will get the user name on its own.
|| 07/28/26  GAR 26.08.16   (733817) Fixed: on update with no @ProjectStatusID passed, no longer defaults to the company''s default status; leaves @ProjectStatusKey NULL so the existing status is preserved. Default lookup now only applies to new projects.
*/

-- Create temp error table
select * into #errors from tAPIErrorTemplate where 1 = 2

-- Declare variables for looked-up keys
DECLARE @ProjectStatusKey int
DECLARE @ProjectTypeKey int
DECLARE @ClientDivisionKey int
DECLARE @ClientProductKey int
DECLARE @OfficeKey int
DECLARE @GLCompanyKey int
DECLARE @ClassKey int
DECLARE @ClientKey int
DECLARE @RequestKey int
DECLARE @CopyProjectKey int
DECLARE @EstimateInternalApprover int
DECLARE @AccountManagerKey int
DECLARE @TeamKey int
DECLARE @LeadKey int
DECLARE @CampaignKey int
DECLARE @DefaultRetainerKey int
DECLARE @RetainerKey int
DECLARE @ProjectManagerKey int
DECLARE @NewProjectKey int
DECLARE @ErrorCount int
DECLARE @EstimateLikeProjectKey int

-- Security variables
DECLARE @IsUpdate int
DECLARE @ExistingProjectKey int
DECLARE @SecurityGroupKey int
DECLARE @IsAdministrator bit
DECLARE @RestrictToGLCompany int
DECLARE @CheckAssignment int

-- Set defaults
select @RequestKey = null
select @DefaultRetainerKey = null
select @RetainerKey = null
select @IsUpdate = 0
select @ExistingProjectKey = null



-- Check for fatal errors
select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
if @ErrorCount > 0
begin
    select errorType, errorCode, errorMessage, fieldName
    from #errors
    order by errorType desc, fieldName

    drop table #errors
    return -100
end

-- ========================================
-- GET USER SECURITY INFO
-- ========================================

SELECT @SecurityGroupKey = SecurityGroupKey,
       @IsAdministrator = Administrator
FROM tUser (nolock)
WHERE UserKey = @UserKey
  AND CompanyKey = @CompanyKey

if @SecurityGroupKey is null
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''User not found or does not belong to this company.'', ''userKey'')

    select errorType, errorCode, errorMessage, fieldName
    from #errors
    order by errorType desc, fieldName

    drop table #errors
    return -103
end

-- Get security settings
select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
from tPreference (nolock)
where CompanyKey = @CompanyKey

-- ========================================
-- CHECK IF PROJECT EXISTS (FOR UPDATE)
-- ========================================

if @ProjectNumber is not null and LTRIM(RTRIM(@ProjectNumber)) <> ''''
begin
    select @ExistingProjectKey = ProjectKey
    from tProject (nolock)
    where CompanyKey = @CompanyKey
      and ProjectNumber = @ProjectNumber

    if @ExistingProjectKey is not null
    begin
        -- Project exists - this will be an UPDATE
        select @IsUpdate = 1
        select @NewProjectKey = @ExistingProjectKey

        -- ========================================
        -- APPLY SECURITY CHECKS FOR UPDATE - spCheckAccess (tProject)
        -- ========================================
        DECLARE @AccessOK int
        exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ExistingProjectKey
        if @AccessOK <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''You do not have access to update this project.'', ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from #errors
            order by errorType desc, fieldName

            drop table #errors
            return -103
        end
    end
end

-- ========================================
-- GATING SECURITY
--   create (@IsUpdate = 0) -> adminCreateProject
--   update (@IsUpdate = 1) -> prjInfo
-- ========================================
DECLARE @gsRightID varchar(50)
select @gsRightID = case when @IsUpdate = 1 then ''prjInfo'' else ''adminCreateProject'' end

if (@IsAdministrator = 0 or @IsAdministrator is null)
   and not exists (
       select 1
       from   tRight r (nolock)
       inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
       where  ra.EntityType = ''Security Group''
         and  ra.EntityKey  = @SecurityGroupKey
         and  r.RightID     = @gsRightID
   )
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''User does not have the required right ('' + @gsRightID + '').'', ''general'')

    select errorType, errorCode, errorMessage, fieldName
    from #errors
    order by errorType desc, fieldName

    drop table #errors
    return -103
end

if @IsUpdate = 0
begin
    -- ========================================
    -- REQUIRED FIELD VALIDATIONS
    -- ========================================

    if @ProjectName is null or LTRIM(RTRIM(@ProjectName)) = ''''
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''Project name is required.'', ''projectName'')
    end

    if @Client is null or LTRIM(RTRIM(@Client)) = ''''
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''Client ID is required.'', ''clientID'')
    end

end

-- Return errors if validation failed
select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
if @ErrorCount > 0
begin
	select errorType, errorCode, errorMessage, fieldName
	from #errors
	order by errorType desc, fieldName

	drop table #errors
	return -100
end

-- Create temp table for change tracking
CREATE TABLE #changes (
    ChangeID int IDENTITY(1,1) PRIMARY KEY,
    fieldName nvarchar(100),
    oldValue nvarchar(500),
    newValue nvarchar(500)
)

-- ========================================
-- LOOKUP CLIENT KEY
-- ========================================

if @Client is not null and LTRIM(RTRIM(@Client)) <> ''''
begin
    -- Try lookup by CustomerID first
    select @ClientKey = CompanyKey
    from tCompany (nolock)
    where OwnerCompanyKey = @CompanyKey
      and UPPER(CustomerID) = UPPER(@Client)
      and Active = 1
      and ActiveClient = 1

    -- If not found, try by CompanyName using LIKE
    if @ClientKey is null
    begin
        select @ClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and UPPER(CompanyName) LIKE UPPER(@Client)
          And Active = 1
          and ActiveClient = 1
    end

    if @ClientKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Client not found with ID: '' + @Client, ''clientID'')
    end
end

-- ========================================
-- LOOKUP PROJECT STATUS KEY
-- ========================================

if @ProjectStatusID is not null and LTRIM(RTRIM(@ProjectStatusID)) <> ''''
begin
    select @ProjectStatusKey = ProjectStatusKey
    from tProjectStatus (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(ProjectStatusID) = UPPER(@ProjectStatusID)

    if @ProjectStatusKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Project status not found with ID: '' + @ProjectStatusID, ''projectStatusID'')
    end
end
else if @IsUpdate = 0
begin
    -- New project with no status specified - get default project status
    select top 1 @ProjectStatusKey = ProjectStatusKey
    from tProjectStatus (nolock)
    where CompanyKey = @CompanyKey
      and Active = 1
      and ISNULL(IsDefault, 0) = 1
    order by DisplayOrder

    -- If no default, get first active status
    if @ProjectStatusKey is null
    begin
        select top 1 @ProjectStatusKey = ProjectStatusKey
        from tProjectStatus (nolock)
        where CompanyKey = @CompanyKey
          and Active = 1
        order by DisplayOrder
    end

    if @ProjectStatusKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''No active project status found. Please specify projectStatusID.'', ''projectStatusID'')
    end
end
-- else: update with no projectStatusID passed - leave @ProjectStatusKey NULL so
-- ProjectStatusKey = ISNULL(@ProjectStatusKey, ProjectStatusKey) below preserves the existing status

-- ========================================
-- LOOKUP PROJECT TYPE KEY
-- ========================================

if @ProjectTypeName is not null and LTRIM(RTRIM(@ProjectTypeName)) <> ''''
begin
    select @ProjectTypeKey = ProjectTypeKey
    from tProjectType (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(ProjectTypeName) = UPPER(@ProjectTypeName)

    if @ProjectTypeKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Project type not found with ID: '' + @ProjectTypeName, ''projectTypeName'')
    end
end

-- ========================================
-- LOOKUP GL COMPANY KEY
-- ========================================

if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
begin
    select @GLCompanyKey = GLCompanyKey
    from tGLCompany (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

    if @GLCompanyKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''GL Company not found with ID: '' + @GLCompanyID, ''glCompanyID'')
    end
end

-- ========================================
-- LOOKUP OFFICE KEY
-- ========================================

if @OfficeID is not null and LTRIM(RTRIM(@OfficeID)) <> ''''
begin
    select @OfficeKey = OfficeKey
    from tOffice (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(OfficeID) = UPPER(@OfficeID)

    if @OfficeKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Office not found with ID: '' + @OfficeID, ''officeID'')
    end
end

-- ========================================
-- LOOKUP CLIENT DIVISION KEY
-- ========================================

if @ClientDivisionID is not null and LTRIM(RTRIM(@ClientDivisionID)) <> ''''
begin
    select @ClientDivisionKey = ClientDivisionKey
    from tClientDivision (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(DivisionID) = UPPER(@ClientDivisionID)

    if @ClientDivisionKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Client division not found with ID: '' + @ClientDivisionID, ''clientDivisionID'')
    end
end

-- ========================================
-- LOOKUP CLIENT PRODUCT KEY
-- ========================================

if @ClientProductID is not null and LTRIM(RTRIM(@ClientProductID)) <> ''''
begin
    select @ClientProductKey = ClientProductKey
    from tClientProduct (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(ProductID) = UPPER(@ClientProductID)

    if @ClientProductKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Client product not found with ID: '' + @ClientProductID, ''clientProductID'')
    end
end

-- ========================================
-- LOOKUP CLASS KEY
-- ========================================

if @ClassID is not null and LTRIM(RTRIM(@ClassID)) <> ''''
begin
    select @ClassKey = ClassKey
    from tClass (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(ClassID) = UPPER(@ClassID)

    if @ClassKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Class not found with ID: '' + @ClassID, ''classID'')
    end
end

-- ========================================
-- LOOKUP COPY PROJECT KEY
-- ========================================

if @CopyProjectNumber is not null and LTRIM(RTRIM(@CopyProjectNumber)) <> ''''
begin
    select @CopyProjectKey = ProjectKey
    from tProject (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(ProjectNumber) = UPPER(@CopyProjectNumber)

    if @CopyProjectKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Copy project not found with number: '' + @CopyProjectNumber, ''copyProjectNumber'')
    end
end

-- ========================================
-- FALLBACK: INHERIT PROJECT TYPE FROM COPY PROJECT
-- ========================================

-- If no ProjectType was explicitly provided but a copy/template project was given,
-- inherit the ProjectType from that project.
if @IsUpdate = 0 and @ProjectTypeKey is null and @CopyProjectKey is not null
begin
    select @ProjectTypeKey = ProjectTypeKey
    from tProject (nolock)
    where ProjectKey = @CopyProjectKey
      and CompanyKey = @CompanyKey
end

-- ProjectType is required for new projects (after all fallback attempts)
if @IsUpdate = 0 and @ProjectTypeKey is null
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Project Type is required. Provide projectTypeName or a copyProjectNumber whose project has a Project Type.'', ''projectType'')
end

-- ========================================
-- LOOKUP ESTIMATE LIKE PROJECT KEY
-- ========================================

if @EstimateLikeProjectNumber is not null and LTRIM(RTRIM(@EstimateLikeProjectNumber)) <> ''''
begin
    select @EstimateLikeProjectKey = ProjectKey
    from tProject (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(ProjectNumber) = UPPER(@EstimateLikeProjectNumber)

    if @EstimateLikeProjectKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'', ''Estimate like project not found with number: '' + @EstimateLikeProjectNumber + ''. Estimate will not be copied.'', ''estimateLikeProjectNumber'')
    end
end


-- ========================================
-- LOOKUP TEAM KEY
-- ========================================

if @TeamName is not null and LTRIM(RTRIM(@TeamName)) <> ''''
begin
    select @TeamKey = TeamKey
    from tTeam (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(TeamName) = UPPER(@TeamName)

    if @TeamKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Team not found with ID: '' + @TeamName, ''team'')
    end
end

-- ========================================
-- LOOKUP LEAD KEY
-- ========================================

if @LeadID is not null and LTRIM(RTRIM(@LeadID)) <> ''''
begin
    select @LeadKey = LeadKey
    from tLead (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(LeadID) = UPPER(@LeadID)

    if @LeadKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Lead not found with ID: '' + @LeadID, ''leadID'')
    end
end

-- ========================================
-- LOOKUP CAMPAIGN KEY
-- ========================================

if @CampaignID is not null and LTRIM(RTRIM(@CampaignID)) <> ''''
begin
    select @CampaignKey = CampaignKey
    from tCampaign (nolock)
    where CompanyKey = @CompanyKey
      and UPPER(CampaignID) = UPPER(@CampaignID)

    if @CampaignKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Campaign not found with ID: '' + @CampaignID, ''campaignID'')
    end
end

-- ========================================
-- LOOKUP ESTIMATE INTERNAL APPROVER KEY
-- ========================================

if @EstimateInternalApproverUserID is not null and LTRIM(RTRIM(@EstimateInternalApproverUserID)) <> ''''
begin
    select @EstimateInternalApprover = UserKey
    from tUser (nolock)
    where CompanyKey = @CompanyKey
      and UserID = @EstimateInternalApproverUserID

    if @EstimateInternalApprover is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'', ''Estimate internal approver not found with user ID: '' + @EstimateInternalApproverUserID + ''. Will use default.'', ''estimateInternalApproverUserID'')
    end
end

-- ========================================
-- LOOKUP ACCOUNT MANAGER KEY
-- ========================================

if @AccountManager is not null and LTRIM(RTRIM(@AccountManager)) <> ''''
begin
    -- Try lookup by UserID first
    select @AccountManagerKey = UserKey
    from tUser (nolock)
    where CompanyKey = @CompanyKey
      and UserID = @AccountManager
      and Active = 1

    -- If not found, try by Email
    if @AccountManagerKey is null
    begin
        select @AccountManagerKey = UserKey
        from tUser (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(Email) = UPPER(@AccountManager)
          and Active = 1
    end

    -- If still not found, try by "FirstName LastName"
    if @AccountManagerKey is null
    begin
        select @AccountManagerKey = UserKey
        from tUser (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(LTRIM(RTRIM(FirstName))) + '' '' + UPPER(LTRIM(RTRIM(LastName))) = UPPER(@AccountManager)
          and Active = 1
    end

    -- If still not found after all attempts, log warning
    if @AccountManagerKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'', ''Account manager not found with identifier: '' + @AccountManager + ''. Tried UserID, Email, and Name.'', ''accountManager'')
    end
end

-- ========================================
-- LOOKUP PROJECT MANAGER KEY
-- ========================================

if @ProjectManager is not null and LTRIM(RTRIM(@ProjectManager)) <> ''''
begin
    -- Try lookup by UserID first
    select @ProjectManagerKey = UserKey
    from tUser (nolock)
    where CompanyKey = @CompanyKey
      and UserID = @ProjectManager
      and Active = 1

    -- If not found, try by Email
    if @ProjectManagerKey is null
    begin
        select @ProjectManagerKey = UserKey
        from tUser (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(Email) = UPPER(@ProjectManager)
          and Active = 1
    end

    -- If still not found, try by "FirstName LastName"
    if @ProjectManagerKey is null
    begin
        select @ProjectManagerKey = UserKey
        from tUser (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(LTRIM(RTRIM(FirstName))) + '' '' + UPPER(LTRIM(RTRIM(LastName))) = UPPER(@ProjectManager)
          and Active = 1
    end

    -- If still not found after all attempts, log warning
    if @ProjectManagerKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'', ''Project manager not found with identifier: '' + @ProjectManager + ''. Tried UserID, Email, and Name.'', ''projectManager'')
    end
end

-- ========================================
-- CHECK FOR ERRORS BEFORE PROCEEDING
-- ========================================

select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
if @ErrorCount > 0
begin
    select errorType, errorCode, errorMessage, fieldName
    from #errors
    order by errorType desc, fieldName

    drop table #errors
    return -101
end

-- ========================================
-- UPDATE EXISTING PROJECT OR CREATE NEW
-- ========================================

if @IsUpdate = 1
begin
    -- Capture OLD values before update (with string representations)
    DECLARE @OldProjectName nvarchar(100)
    DECLARE @OldProjectStatusID varchar(50)
    DECLARE @OldProjectStatusName nvarchar(200)
    DECLARE @OldProjectTypeName nvarchar(100)
    DECLARE @OldClientID varchar(75)
    DECLARE @OldClientName nvarchar(200)
    DECLARE @OldDivisionID varchar(50)
    DECLARE @OldDivisionName nvarchar(300)
    DECLARE @OldProductID varchar(50)
    DECLARE @OldProductName nvarchar(300)
    DECLARE @OldOfficeID nvarchar(50)
    DECLARE @OldOfficeName nvarchar(200)
    DECLARE @OldGLCompanyID varchar(50)
    DECLARE @OldGLCompanyName nvarchar(500)
    DECLARE @OldClassID varchar(50)
    DECLARE @OldClassName nvarchar(200)
    DECLARE @OldProjectColor varchar(10)
    DECLARE @OldModelYear varchar(10)
    DECLARE @OldCampaignID varchar(50)
    DECLARE @OldAccountManagerID varchar(100)
    DECLARE @OldAccountManagerName nvarchar(300)
    DECLARE @OldProjectManagerID varchar(100)
    DECLARE @OldProjectManagerName nvarchar(300)
    DECLARE @OldTeamName nvarchar(200)
    DECLARE @OldLeadID int
    DECLARE @OldLeadSubject nvarchar(200)
    DECLARE @OldTemplate tinyint
    DECLARE @OldOpportunity tinyint
    DECLARE @OldStatusNotes nvarchar(max)

    SELECT @OldProjectName = p.ProjectName,
           @OldProjectStatusID = ps.ProjectStatusID,
           @OldProjectStatusName = ps.ProjectStatus,
           @OldProjectTypeName = pt.ProjectTypeName,
           @OldClientID = c.CustomerID,
           @OldClientName = c.CompanyName,
           @OldDivisionID = cd.DivisionID,
           @OldDivisionName = cd.DivisionName,
           @OldProductID = cp.ProductID,
           @OldProductName = cp.ProductName,
           @OldOfficeID = o.OfficeID,
           @OldOfficeName = o.OfficeName,
           @OldGLCompanyID = gl.GLCompanyID,
           @OldGLCompanyName = gl.GLCompanyName,
           @OldClassID = cl.ClassID,
           @OldClassName = cl.ClassName,
           @OldProjectColor = p.ProjectColor,
           @OldModelYear = p.ModelYear,
           @OldCampaignID = ca.CampaignID,
           @OldAccountManagerID = am.UserID,
           @OldAccountManagerName = am.FirstName + '' '' + am.LastName,
           @OldProjectManagerID = pm.UserID,
           @OldProjectManagerName = pm.FirstName + '' '' + pm.LastName,
           @OldTeamName = t.TeamName,
           @OldLeadID = l.LeadID,
           @OldLeadSubject = l.Subject,
           @OldTemplate = p.Template,
           @OldOpportunity = p.Opportunity,
           @OldStatusNotes = p.StatusNotes
    FROM tProject p (nolock)
    LEFT JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey
    LEFT JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey
    LEFT JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
    LEFT JOIN tClientDivision cd (nolock) ON p.ClientDivisionKey = cd.ClientDivisionKey
    LEFT JOIN tClientProduct cp (nolock) ON p.ClientProductKey = cp.ClientProductKey
    LEFT JOIN tOffice o (nolock) ON p.OfficeKey = o.OfficeKey
    LEFT JOIN tGLCompany gl (nolock) ON p.GLCompanyKey = gl.GLCompanyKey
    LEFT JOIN tClass cl (nolock) ON p.ClassKey = cl.ClassKey
    LEFT JOIN tCampaign ca (nolock) ON p.CampaignKey = ca.CampaignKey
    LEFT JOIN tUser am (nolock) ON p.AccountManager = am.UserKey
    LEFT JOIN tUser pm (nolock) ON p.ProjectManager = pm.UserKey
    LEFT JOIN tTeam t (nolock) ON p.TeamKey = t.TeamKey
    LEFT JOIN tLead l (nolock) ON p.LeadKey = l.LeadKey
    WHERE p.ProjectKey = @NewProjectKey

    -- UPDATE existing project
    UPDATE tProject
    SET ProjectName = @ProjectName,
        ProjectStatusKey = ISNULL(@ProjectStatusKey, ProjectStatusKey),
        ProjectTypeKey = ISNULL(@ProjectTypeKey, ProjectTypeKey),
        ClientKey = ISNULL(@ClientKey, ClientKey),
        ClientDivisionKey = ISNULL(@ClientDivisionKey, ClientDivisionKey),
        ClientProductKey = ISNULL(@ClientProductKey, ClientProductKey),
        OfficeKey = ISNULL(@OfficeKey, OfficeKey),
        GLCompanyKey = ISNULL(@GLCompanyKey, GLCompanyKey),
        ClassKey = ISNULL(@ClassKey, ClassKey),
        ProjectColor = ISNULL(@ProjectColor, ProjectColor),
        ModelYear = ISNULL(@ModelYear, ModelYear),
        CampaignKey = ISNULL(@CampaignKey, CampaignKey),
        AccountManager = ISNULL(@AccountManagerKey, AccountManager),
        ProjectManager = ISNULL(@ProjectManagerKey, ProjectManager),
        TeamKey = ISNULL(@TeamKey, TeamKey),
        LeadKey = ISNULL(@LeadKey, LeadKey),
        Template = @Template,
        Opportunity = @Opportunity,
        StatusNotes = ISNULL(@StatusNotes, StatusNotes),
        DateUpdated = getutcdate()
    WHERE ProjectKey = @NewProjectKey
      AND CompanyKey = @CompanyKey

    if @@ROWCOUNT = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''GENERAL'', ''Failed to update project.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from #errors
        order by errorType desc, fieldName

        drop table #errors
        drop table #changes
        return -102
    end

    -- Track changes (compare old vs new values)
    -- Get NEW values with string representations
    DECLARE @NewProjectName nvarchar(100)
    DECLARE @NewProjectStatusID varchar(50)
    DECLARE @NewProjectStatusName nvarchar(200)
    DECLARE @NewProjectTypeName nvarchar(100)
    DECLARE @NewClientID varchar(75)
    DECLARE @NewClientName nvarchar(200)
    DECLARE @NewDivisionID varchar(50)
    DECLARE @NewDivisionName nvarchar(300)
    DECLARE @NewProductID varchar(50)
    DECLARE @NewProductName nvarchar(300)
    DECLARE @NewOfficeID nvarchar(50)
    DECLARE @NewOfficeName nvarchar(200)
    DECLARE @NewGLCompanyID varchar(50)
    DECLARE @NewGLCompanyName nvarchar(500)
    DECLARE @NewClassID varchar(50)
    DECLARE @NewClassName nvarchar(200)
    DECLARE @NewProjectColor varchar(10)
    DECLARE @NewModelYear varchar(10)
    DECLARE @NewCampaignID varchar(50)
    DECLARE @NewAccountManagerID varchar(100)
    DECLARE @NewAccountManagerName nvarchar(300)
    DECLARE @NewProjectManagerID varchar(100)
    DECLARE @NewProjectManagerName nvarchar(300)
    DECLARE @NewTeamName nvarchar(200)
    DECLARE @NewLeadID int
    DECLARE @NewLeadSubject nvarchar(200)
    DECLARE @NewTemplate tinyint
    DECLARE @NewOpportunity tinyint
    DECLARE @NewStatusNotes nvarchar(max)

    SELECT @NewProjectName = p.ProjectName,
           @NewProjectStatusID = ps.ProjectStatusID,
           @NewProjectStatusName = ps.ProjectStatus,
           @NewProjectTypeName = pt.ProjectTypeName,
           @NewClientID = c.CustomerID,
           @NewClientName = c.CompanyName,
           @NewDivisionID = cd.DivisionID,
           @NewDivisionName = cd.DivisionName,
           @NewProductID = cp.ProductID,
           @NewProductName = cp.ProductName,
           @NewOfficeID = o.OfficeID,
           @NewOfficeName = o.OfficeName,
           @NewGLCompanyID = gl.GLCompanyID,
           @NewGLCompanyName = gl.GLCompanyName,
           @NewClassID = cl.ClassID,
           @NewClassName = cl.ClassName,
           @NewProjectColor = p.ProjectColor,
           @NewModelYear = p.ModelYear,
           @NewCampaignID = ca.CampaignID,
           @NewAccountManagerID = am.UserID,
           @NewAccountManagerName = am.FirstName + '' '' + am.LastName,
           @NewProjectManagerID = pm.UserID,
           @NewProjectManagerName = pm.FirstName + '' '' + pm.LastName,
           @NewTeamName = t.TeamName,
           @NewLeadID = l.LeadID,
           @NewLeadSubject = l.Subject,
           @NewTemplate = p.Template,
           @NewOpportunity = p.Opportunity,
           @NewStatusNotes = p.StatusNotes
    FROM tProject p (nolock)
    LEFT JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey
    LEFT JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey
    LEFT JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
    LEFT JOIN tClientDivision cd (nolock) ON p.ClientDivisionKey = cd.ClientDivisionKey
    LEFT JOIN tClientProduct cp (nolock) ON p.ClientProductKey = cp.ClientProductKey
    LEFT JOIN tOffice o (nolock) ON p.OfficeKey = o.OfficeKey
    LEFT JOIN tGLCompany gl (nolock) ON p.GLCompanyKey = gl.GLCompanyKey
    LEFT JOIN tClass cl (nolock) ON p.ClassKey = cl.ClassKey
    LEFT JOIN tCampaign ca (nolock) ON p.CampaignKey = ca.CampaignKey
    LEFT JOIN tUser am (nolock) ON p.AccountManager = am.UserKey
    LEFT JOIN tUser pm (nolock) ON p.ProjectManager = pm.UserKey
    LEFT JOIN tTeam t (nolock) ON p.TeamKey = t.TeamKey
    LEFT JOIN tLead l (nolock) ON p.LeadKey = l.LeadKey
    WHERE p.ProjectKey = @NewProjectKey

    -- Compare and insert changes
    if ISNULL(@OldProjectName, '''') <> ISNULL(@NewProjectName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''projectName'', @OldProjectName, @NewProjectName)

    if ISNULL(@OldProjectStatusName, '''') <> ISNULL(@NewProjectStatusName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''projectStatus'', @OldProjectStatusName, @NewProjectStatusName)

    if ISNULL(@OldProjectTypeName, '''') <> ISNULL(@NewProjectTypeName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''projectType'', @OldProjectTypeName, @NewProjectTypeName)

    if ISNULL(@OldClientName, '''') <> ISNULL(@NewClientName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''client'', @OldClientName, @NewClientName)

    if ISNULL(@OldDivisionName, '''') <> ISNULL(@NewDivisionName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''clientDivision'', @OldDivisionName, @NewDivisionName)

    if ISNULL(@OldProductName, '''') <> ISNULL(@NewProductName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''clientProduct'', @OldProductName, @NewProductName)

    if ISNULL(@OldOfficeName, '''') <> ISNULL(@NewOfficeName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''office'', @OldOfficeName, @NewOfficeName)

    if ISNULL(@OldGLCompanyName, '''') <> ISNULL(@NewGLCompanyName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''glCompany'', @OldGLCompanyName, @NewGLCompanyName)

    if ISNULL(@OldClassName, '''') <> ISNULL(@NewClassName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''class'', @OldClassName, @NewClassName)

    if ISNULL(@OldProjectColor, '''') <> ISNULL(@NewProjectColor, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''projectColor'', @OldProjectColor, @NewProjectColor)

    if ISNULL(@OldModelYear, '''') <> ISNULL(@NewModelYear, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''modelYear'', @OldModelYear, @NewModelYear)

    if ISNULL(@OldCampaignID, '''') <> ISNULL(@NewCampaignID, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''campaign'', @OldCampaignID, @NewCampaignID)

    if ISNULL(@OldAccountManagerName, '''') <> ISNULL(@NewAccountManagerName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''accountManager'', @OldAccountManagerName, @NewAccountManagerName)

    if ISNULL(@OldProjectManagerName, '''') <> ISNULL(@NewProjectManagerName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''projectManager'', @OldProjectManagerName, @NewProjectManagerName)

    if ISNULL(@OldTeamName, '''') <> ISNULL(@NewTeamName, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''team'', @OldTeamName, @NewTeamName)

    if ISNULL(@OldLeadSubject, '''') <> ISNULL(@NewLeadSubject, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''lead'', @OldLeadSubject, @NewLeadSubject)

    if ISNULL(@OldTemplate, 0) <> ISNULL(@NewTemplate, 0)
        insert into #changes (fieldName, oldValue, newValue) values (''template'', CAST(@OldTemplate as varchar), CAST(@NewTemplate as varchar))

    if ISNULL(@OldOpportunity, 0) <> ISNULL(@NewOpportunity, 0)
        insert into #changes (fieldName, oldValue, newValue) values (''opportunity'', CAST(@OldOpportunity as varchar), CAST(@NewOpportunity as varchar))

    if ISNULL(@OldStatusNotes, '''') <> ISNULL(@NewStatusNotes, '''')
        insert into #changes (fieldName, oldValue, newValue) values (''statusNotes'', LEFT(@OldStatusNotes, 500), LEFT(@NewStatusNotes, 500))

    -- ========================================
    -- LOG CHANGES TO tActionLog
    -- ========================================

    -- Only log if there were actual changes
    if exists (select 1 from #changes)
    begin
        DECLARE @ChangeFieldName nvarchar(100)
        DECLARE @ChangeOldValue nvarchar(500)
        DECLARE @ChangeNewValue nvarchar(500)
        DECLARE @ChangeComments nvarchar(4000)
        DECLARE @LogProjectNumber varchar(100)
        DECLARE @CurrentChangeID int
        DECLARE @MaxChangeID int

        -- Get the project number for logging
        select @LogProjectNumber = ProjectNumber
        from tProject (nolock)
        where ProjectKey = @NewProjectKey

        -- Get range of change IDs
        select @CurrentChangeID = MIN(ChangeID), @MaxChangeID = MAX(ChangeID)
        from #changes

        -- Loop through changes using WHILE instead of cursor
        WHILE @CurrentChangeID <= @MaxChangeID
        BEGIN
            -- Get the current change row
            select @ChangeFieldName = fieldName,
                   @ChangeOldValue = oldValue,
                   @ChangeNewValue = newValue
            from #changes
            where ChangeID = @CurrentChangeID

            -- Only process if row exists (handles gaps in identity values)
            if @@ROWCOUNT > 0
            begin
                -- Build human-readable comments based on field name
                if @ChangeFieldName = ''projectName''
                    select @ChangeComments = ''Project Name was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''projectStatus''
                    select @ChangeComments = ''Project Status was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''projectType''
                    select @ChangeComments = ''Project Type was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''client''
                    select @ChangeComments = ''Client was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''clientDivision''
                    select @ChangeComments = ''Client Division was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''clientProduct''
                    select @ChangeComments = ''Client Product was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''office''
                    select @ChangeComments = ''Office was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''glCompany''
                    select @ChangeComments = ''GL Company was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''class''
                    select @ChangeComments = ''Class was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''projectColor''
                    select @ChangeComments = ''Project Color was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''modelYear''
                    select @ChangeComments = ''Model Year was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''campaign''
                    select @ChangeComments = ''Campaign was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''accountManager''
                    select @ChangeComments = ''Account Manager was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''projectManager''
                    select @ChangeComments = ''Project Manager was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''team''
                    select @ChangeComments = ''Team was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''lead''
                    select @ChangeComments = ''Lead was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''
                else if @ChangeFieldName = ''template''
                    select @ChangeComments = ''Template flag was changed from '' + CASE WHEN @ChangeOldValue = ''1'' THEN ''Yes'' ELSE ''No'' END + '' to '' + CASE WHEN @ChangeNewValue = ''1'' THEN ''Yes'' ELSE ''No'' END
                else if @ChangeFieldName = ''opportunity''
                    select @ChangeComments = ''Opportunity flag was changed from '' + CASE WHEN @ChangeOldValue = ''1'' THEN ''Yes'' ELSE ''No'' END + '' to '' + CASE WHEN @ChangeNewValue = ''1'' THEN ''Yes'' ELSE ''No'' END
                else if @ChangeFieldName = ''statusNotes''
                    select @ChangeComments = ''Status Notes were updated''
                else
                    select @ChangeComments = @ChangeFieldName + '' was changed from "'' + ISNULL(@ChangeOldValue, ''(blank)'') + ''" to "'' + ISNULL(@ChangeNewValue, ''(blank)'') + ''"''

                -- Insert into tActionLog using sptActionLogInsert
                DECLARE @Now smalldatetime = getutcdate()

                EXEC sptActionLogInsert
                    @Entity = ''Project'',
                    @EntityKey = @NewProjectKey,
                    @CompanyKey = @CompanyKey,
                    @ProjectKey = @NewProjectKey,
                    @Action = ''Field Changed'',
                    @ActionDate = @Now, 
                    @ActionBy = NULL,
                    @Comments = @ChangeComments,
                    @Reference = @LogProjectNumber,
                    @SourceCompanyID = NULL,
                    @UserKey = @UserKey,
                    @CampaignKey = @CampaignKey
            end

            -- Move to next change
            select @CurrentChangeID = @CurrentChangeID + 1
        END
    end
end
else
begin
    -- CREATE new project via sptProjectCopy

    EXEC sptProjectCopy
        @UserKey = @UserKey,
        @ProjectName = @ProjectName,
        @ProjectNumber = @ProjectNumber,
        @CompanyKey = @CompanyKey,
        @ProjectStatusKey = @ProjectStatusKey,
        @ProjectTypeKey = @ProjectTypeKey,
        @ClientDivisionKey = @ClientDivisionKey,
        @ClientProductKey = @ClientProductKey,
        @OfficeKey = @OfficeKey,
        @GLCompanyKey = @GLCompanyKey,
        @ClassKey = @ClassKey,
        @ClientKey = @ClientKey,
        @RequestKey = @RequestKey,
        @CopyProjectKey = @CopyProjectKey,
        @CopyEstimate = @CopyEstimate,
        @CopyFrom = 0,
        @EstimateInternalApprover = @EstimateInternalApprover,
        @AccountManager = @AccountManagerKey,
        @TeamKey = @TeamKey,
        @LeadKey = @LeadKey,
        @ProjectColor = @ProjectColor,
        @ModelYear = @ModelYear,
        @CampaignKey = @CampaignKey,
        @DefaultRetainerKey = @DefaultRetainerKey,
        @Template = @Template,
        @Opportunity = @Opportunity,
        @RetainerKey = @RetainerKey,
        @Retainer = 0,
        @IsLegacy = 0,
        @ProjectManager = @ProjectManagerKey,
        @DoNotCopyAssignments = @DoNotCopyAssignments,
        @oIdentity = @NewProjectKey OUTPUT

    -- Check return value from sptProjectCopy
    DECLARE @ReturnValue int
    select @ReturnValue = @@ROWCOUNT

    if @NewProjectKey is null or @NewProjectKey <= 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''GENERAL'', ''Failed to create project. Please check input parameters.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from #errors
        order by errorType desc, fieldName

        drop table #errors
        return -102
    end

	 -- sptProjectCopy has no StatusNotes parameter; apply it here so tU_tProject''s
	 -- trigger logic stamps StatusNotesUpdated for us.
	 if @StatusNotes is not null and LTRIM(RTRIM(@StatusNotes)) <> ''''
	 begin
	     update tProject
	     set    StatusNotes = @StatusNotes
	     where  ProjectKey = @NewProjectKey
	       and  CompanyKey = @CompanyKey
	 end

	 -- Copy tasks + estimate from like project when specified and no copy source was used
    if @EstimateLikeProjectKey is not null and @CopyProjectKey is null
    begin
        exec sptProjectCopyTasks
            @ProjectKey = @NewProjectKey,
            @CopyProjectKey = @EstimateLikeProjectKey,
            @CopyEstimate = 1,
            @UserKey = @UserKey,
            @DoNotCopyAssignments = 1
    end

end

-- ========================================
-- RETURN SUCCESS WITH WARNINGS (IF ANY)
-- ========================================

-- Return any warnings
select errorType, errorCode, errorMessage, fieldName
from #errors
where errorType = ''warning''

-- Get the project details (created or updated)
select p.ProjectKey as projectKey,
       p.ProjectNumber as projectNumber,
       p.ProjectName as projectName,
       p.CompanyKey as companyKey,
       c.CustomerID as clientID,
       c.CompanyName as clientName,
       ps.ProjectStatusID as projectStatusID,
       ps.ProjectStatus as projectStatusName,
       pt.ProjectTypeName as projectTypeName,
       p.Active as active,
       p.CreatedDate as dateAdded,
       p.DateUpdated as dateUpdated,
       p.CustomFieldKey as customFieldKey,
       p.StatusNotes as statusNotes,
       p.StatusNotesUpdated as statusNotesUpdated,
       @IsUpdate as wasUpdated,
       @CopyProjectKey as copyProjectKey
from tProject p (nolock)
left join tCompany c (nolock) on p.ClientKey = c.CompanyKey
left join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
left join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
where p.ProjectKey = @NewProjectKey

-- Return change tracking (only for updates)
if @IsUpdate = 1
begin
    select fieldName,
           oldValue,
           newValue
    from #changes
    order by fieldName
end

drop table #errors
drop table #changes
return 1







'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetClientHealth]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetClientHealth]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIGetClientHealth]
(
    @CompanyKey     int,
    @UserKey        int,
    @AsOfDate       datetime    = null,   -- window end; defaults to today
    @TrailingMonths int         = 12,     -- window length when start/end omitted
    @StartDate      datetime    = null,
    @EndDate        datetime    = null,
    @GLCompanyID    varchar(50) = null,
    @TopN           int         = 50,
    @MinRevenue     money       = null    -- drop clients billed below this in the window
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GHL 26.xx      Created. Per-client health / strategic-value matrix for the AI CEO co-pilot.
||                          Composite over a trailing window (vs prior equal window): billed-revenue trend,
||                          project-volume trend, open-AR / slow-pay signal, lifetime margin from tProjectRollup,
||                          and a scope signal (approved change orders + over-budget project count). Clients are
||                          rolled up to their parent company (tCompany.ParentCompanyKey) like get_customer_concentration.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    ------------------------------------------------------------
    -- Rights (AR/client financials); admins bypass
    ------------------------------------------------------------
    declare @IsAdministrator tinyint, @SecurityGroupKey int
    select @IsAdministrator = ISNULL(Administrator,0), @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock) where UserKey = @UserKey and CompanyKey = @CompanyKey

    if @SecurityGroupKey is null and @IsAdministrator = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'',''NOT_FOUND'',''User not found or invalid UserKey.'',''general'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    if @IsAdministrator = 0
       and not exists (
           select 1 from tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where ra.EntityType = ''Security Group'' and ra.EntityKey = @SecurityGroupKey
             and r.RightID in (''acct_ar_aging'',''acct_ar_invoicesummary'',''acct_client_gl_pl_ytd'',''billingviewclientinvoice''))
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'',''ACCESS_DENIED'',''You do not have rights to view client financials.'',''general'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -103
    end

    ------------------------------------------------------------
    -- Windows
    ------------------------------------------------------------
    if @AsOfDate is null set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())
    if @EndDate is null set @EndDate = @AsOfDate
    if @StartDate is null set @StartDate = DATEADD(m, -ISNULL(NULLIF(@TrailingMonths,0),12), @EndDate)

    declare @WindowLen int = DATEDIFF(d, @StartDate, @EndDate) + 1
    declare @PriorEnd datetime   = DATEADD(d, -1, @StartDate)
    declare @PriorStart datetime = DATEADD(d, -@WindowLen, @StartDate)

    ------------------------------------------------------------
    -- GL company restriction + optional filter
    ------------------------------------------------------------
    declare @RestrictToGLCompany tinyint
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany,0) from tPreference (nolock) where CompanyKey = @CompanyKey

    declare @GLCompanyKey int = null
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
        select @GLCompanyKey = GLCompanyKey from tGLCompany (nolock)
        where CompanyKey = @CompanyKey and GLCompanyID = @GLCompanyID

    ------------------------------------------------------------
    -- Client -> parent rollup map (clients = companies with projects or invoices)
    ------------------------------------------------------------
    create table #clientMap (ClientKey int primary key, RollupKey int, RollupName varchar(400), RollupCustomerID varchar(50))

    insert into #clientMap (ClientKey, RollupKey, RollupName, RollupCustomerID)
    select c.CompanyKey,
           ISNULL(NULLIF(c.ParentCompanyKey,0), c.CompanyKey),
           ISNULL(pc.CompanyName, c.CompanyName),
           ISNULL(pc.CustomerID, c.CustomerID)
    from   tCompany c (nolock)
    left   join tCompany pc (nolock) on NULLIF(c.ParentCompanyKey,0) = pc.CompanyKey
    where  c.OwnerCompanyKey = @CompanyKey
      and  c.CompanyKey in (
            select ClientKey from tProject (nolock) where CompanyKey = @CompanyKey and ClientKey is not null
            union
            select ClientKey from tInvoice (nolock) where CompanyKey = @CompanyKey and ClientKey is not null)

    ------------------------------------------------------------
    -- Seed one row per rollup client
    ------------------------------------------------------------
    create table #health
    (
        RollupKey int primary key,
        RollupName varchar(400),
        CustomerID varchar(50),
        Revenue money default 0,
        PriorRevenue money default 0,
        ActiveProjects int default 0,
        StartedInWindow int default 0,
        PriorStarted int default 0,
        ChangeOrderAmount money default 0,
        OverBudgetProjects int default 0,
        GrossMargin money default 0,
        BilledLife money default 0,
        NetCostLife money default 0,
        OpenAR money default 0,
        AgedAR money default 0,
        OldestOpenInvoiceDays int default 0
    )

    insert into #health (RollupKey, RollupName, CustomerID)
    select RollupKey, MIN(RollupName), MIN(RollupCustomerID)
    from   #clientMap group by RollupKey

    ------------------------------------------------------------
    -- Billed revenue: current + prior window (posted, non-advance)
    ------------------------------------------------------------
    update h set Revenue = x.Rev
    from #health h
    inner join (
        select cm.RollupKey, SUM(il.TotalAmount) as Rev
        from   tInvoiceLine il (nolock)
        inner join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
        inner join #clientMap cm on i.ClientKey = cm.ClientKey
        where  i.CompanyKey = @CompanyKey and ISNULL(i.Posted,0)=1 and ISNULL(i.AdvanceBill,0)=0
          and  i.InvoiceDate >= @StartDate and i.InvoiceDate <= @EndDate
          and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0 or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey=@UserKey))
        group by cm.RollupKey) x on h.RollupKey = x.RollupKey

    update h set PriorRevenue = x.Rev
    from #health h
    inner join (
        select cm.RollupKey, SUM(il.TotalAmount) as Rev
        from   tInvoiceLine il (nolock)
        inner join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
        inner join #clientMap cm on i.ClientKey = cm.ClientKey
        where  i.CompanyKey = @CompanyKey and ISNULL(i.Posted,0)=1 and ISNULL(i.AdvanceBill,0)=0
          and  i.InvoiceDate >= @PriorStart and i.InvoiceDate <= @PriorEnd
          and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0 or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey=@UserKey))
        group by cm.RollupKey) x on h.RollupKey = x.RollupKey

    ------------------------------------------------------------
    -- Project volume + margin + scope (change orders, over budget)
    ------------------------------------------------------------
    update h set ActiveProjects = x.ActiveCnt, StartedInWindow = x.StartedCnt,
                 ChangeOrderAmount = x.CO, OverBudgetProjects = x.OverCnt,
                 BilledLife = x.Billed, NetCostLife = x.NetCost, GrossMargin = x.Billed - x.NetCost
    from #health h
    inner join (
        select cm.RollupKey,
               SUM(case when ISNULL(p.Closed,0)=0 then 1 else 0 end) as ActiveCnt,
               SUM(case when p.StartDate >= @StartDate and p.StartDate <= @EndDate then 1 else 0 end) as StartedCnt,
               SUM(ISNULL(p.ApprovedCOLabor,0) + ISNULL(p.ApprovedCOExpense,0)) as CO,
               SUM(case when (ISNULL(roll.LaborGross,0)+ISNULL(roll.MiscCostGross,0)+ISNULL(roll.ExpReceiptGross,0)+ISNULL(roll.VoucherOutsideCostsGross,0))
                             > (ISNULL(p.EstLabor,0)+ISNULL(p.ApprovedCOLabor,0)+ISNULL(p.EstExpenses,0)+ISNULL(p.ApprovedCOExpense,0))
                         and (ISNULL(p.EstLabor,0)+ISNULL(p.ApprovedCOLabor,0)+ISNULL(p.EstExpenses,0)+ISNULL(p.ApprovedCOExpense,0)) > 0
                         and ISNULL(p.Closed,0)=0
                        then 1 else 0 end) as OverCnt,
               SUM(ISNULL(roll.BilledAmount,0)) as Billed,
               SUM(ISNULL(roll.LaborNet,0)+ISNULL(roll.MiscCostNet,0)+ISNULL(roll.ExpReceiptNet,0)+ISNULL(roll.VoucherNet,0)) as NetCost
        from   tProject p (nolock)
        inner join #clientMap cm on p.ClientKey = cm.ClientKey
        left   join tProjectRollup roll (nolock) on p.ProjectKey = roll.ProjectKey
        where  p.CompanyKey = @CompanyKey and ISNULL(p.NonBillable,0)=0
          and  (@GLCompanyKey is null or p.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0 or p.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey=@UserKey))
        group by cm.RollupKey) x on h.RollupKey = x.RollupKey

    update h set PriorStarted = x.StartedCnt
    from #health h
    inner join (
        select cm.RollupKey,
               SUM(case when p.StartDate >= @PriorStart and p.StartDate <= @PriorEnd then 1 else 0 end) as StartedCnt
        from   tProject p (nolock)
        inner join #clientMap cm on p.ClientKey = cm.ClientKey
        where  p.CompanyKey = @CompanyKey and ISNULL(p.NonBillable,0)=0
        group by cm.RollupKey) x on h.RollupKey = x.RollupKey

    ------------------------------------------------------------
    -- Open AR + slow-pay signal (open balance as of window end)
    ------------------------------------------------------------
    update h set OpenAR = x.OpenAR, AgedAR = x.AgedAR, OldestOpenInvoiceDays = x.OldestDays
    from #health h
    inner join (
        select cm.RollupKey,
               SUM(ISNULL(i.InvoiceTotalAmount,0)-ISNULL(i.AmountReceived,0)-ISNULL(i.RetainerAmount,0)) as OpenAR,
               SUM(case when DATEDIFF(d, i.InvoiceDate, @EndDate) >= 60
                        then ISNULL(i.InvoiceTotalAmount,0)-ISNULL(i.AmountReceived,0)-ISNULL(i.RetainerAmount,0) else 0 end) as AgedAR,
               MAX(DATEDIFF(d, i.InvoiceDate, @EndDate)) as OldestDays
        from   tInvoice i (nolock)
        inner join #clientMap cm on i.ClientKey = cm.ClientKey
        where  i.CompanyKey = @CompanyKey and ISNULL(i.Posted,0)=1 and ISNULL(i.AdvanceBill,0)=0
          and  i.InvoiceDate <= @EndDate
          and  (ISNULL(i.InvoiceTotalAmount,0)-ISNULL(i.AmountReceived,0)-ISNULL(i.RetainerAmount,0)) > 0
          and  (@GLCompanyKey is null or i.GLCompanyKey = @GLCompanyKey)
          and  (@RestrictToGLCompany = 0 or i.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey=@UserKey))
        group by cm.RollupKey) x on h.RollupKey = x.RollupKey

    ------------------------------------------------------------
    -- Total revenue for share %
    ------------------------------------------------------------
    declare @TotalRevenue money
    select @TotalRevenue = ISNULL(SUM(Revenue),0) from #health

    ------------------------------------------------------------
    -- Warnings
    ------------------------------------------------------------
    if not exists (select 1 from #health where Revenue <> 0 or ActiveProjects > 0)
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'',''NOT_FOUND'',''No client activity in the window.'',''general'')

    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    ------------------------------------------------------------
    -- Result: ranked client health (severity + flag + score computed here)
    ------------------------------------------------------------
    select top (@TopN)
         h.RollupKey                                                        as clientKey
        ,h.CustomerID                                                       as clientID
        ,h.RollupName                                                       as clientName
        ,h.Revenue                                                          as revenue
        ,h.PriorRevenue                                                     as priorRevenue
        ,case when h.PriorRevenue <> 0 then CONVERT(decimal(9,2), 100.0*(h.Revenue-h.PriorRevenue)/ABS(h.PriorRevenue)) else null end as revenueDeltaPct
        ,case when @TotalRevenue > 0 then CONVERT(decimal(9,2), 100.0*h.Revenue/@TotalRevenue) else 0 end as percentOfTotal
        ,h.ActiveProjects                                                   as activeProjects
        ,h.StartedInWindow                                                  as projectsStartedInWindow
        ,h.PriorStarted                                                     as priorProjectsStarted
        ,h.GrossMargin                                                      as grossMarginLife
        ,case when h.BilledLife <> 0 then CONVERT(decimal(9,2), 100.0*h.GrossMargin/h.BilledLife) else 0 end as grossMarginPct
        ,h.ChangeOrderAmount                                               as changeOrderAmount
        ,h.OverBudgetProjects                                              as overBudgetProjects
        ,h.OpenAR                                                          as openAR
        ,h.AgedAR                                                          as agedAR60Plus
        ,h.OldestOpenInvoiceDays                                           as oldestOpenInvoiceDays
        -- severity: red if any red condition, else yellow if any yellow, else green
        ,case
            when (h.PriorRevenue > 0 and (h.Revenue-h.PriorRevenue)/h.PriorRevenue <= -0.25)
              or (h.OpenAR > 0 and h.OldestOpenInvoiceDays >= 90 and h.AgedAR > 0)
              or (h.BilledLife > 0 and (100.0*h.GrossMargin/h.BilledLife) < 15) then ''red''
            when (h.PriorRevenue > 0 and (h.Revenue-h.PriorRevenue)/h.PriorRevenue <= -0.10)
              or (h.OpenAR > 0 and h.OldestOpenInvoiceDays >= 60)
              or (h.BilledLife > 0 and (100.0*h.GrossMargin/h.BilledLife) < 30)
              or (h.OverBudgetProjects > 0)
              or (h.PriorStarted > 0 and h.StartedInWindow < h.PriorStarted) then ''yellow''
            else ''green''
         end                                                                as severity
        ,case
            when (h.PriorRevenue > 0 and (h.Revenue-h.PriorRevenue)/h.PriorRevenue <= -0.25) then ''revenue_declining''
            when (h.OpenAR > 0 and h.OldestOpenInvoiceDays >= 90 and h.AgedAR > 0)            then ''slow_pay''
            when (h.BilledLife > 0 and (100.0*h.GrossMargin/h.BilledLife) < 15)               then ''margin_low''
            when (h.OverBudgetProjects > 0)                                                   then ''delivery_risk''
            when (h.PriorStarted > 0 and h.StartedInWindow < h.PriorStarted)                  then ''volume_declining''
            when (h.PriorRevenue > 0 and (h.Revenue-h.PriorRevenue)/h.PriorRevenue <= -0.10)  then ''revenue_softening''
            else ''healthy''
         end                                                                as flag
        ,CONVERT(varchar(10), @StartDate, 120)                              as windowStart
        ,CONVERT(varchar(10), @EndDate, 120)                                as windowEnd
        ,CONVERT(varchar(10), @PriorStart, 120)                             as priorWindowStart
        ,CONVERT(varchar(10), @PriorEnd, 120)                               as priorWindowEnd
    from #health h
    where (@MinRevenue is null or h.Revenue >= @MinRevenue)
    order by h.Revenue desc

    drop table #health
    drop table #clientMap
    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActionLogGetDefaultsForTime]'
GO
IF OBJECT_ID(N'[dbo].[sptActionLogGetDefaultsForTime]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActionLogGetDefaultsForTime]
	@UserKey int,
	@WorkDate smalldatetime,
	@EndWorkDate smalldatetime,
	@UTCOffsetHours int = NULL

AS --Encrypt

/*
|| When      Who Rel      What
|| 02/22/16  GAR 10.6.0.1 (289869) Added for defaulting in projects / tasks in timesheet from action log.
|| 02/23/16  CRG 10.6.0.1 Added ProjectFullName, ClientName, CampaignFullName, ProjectStatus, and ProjectTypeName for grouping
|| 09/05/19  RLB 19.0.9.0 (476641) Added Account Manager and Project Manager to TimeEntry
|| 12/02/19  CRG 20.0.1.0 (466594) Added ProjectOrder
|| 06/09/21  RLB 21.07.18 (560785) Added UTC Off Set Hours add if to catch any nulls passed in
|| 03/29/23  CRG 23.04.16 (622919) Added check for NoTimeEntry
|| 08/11/23  CRG 23.09.17 (642807) Added ScheduleTask
|| 08/29/23  RLB 23.09.17 (649893) Added check for conversations to only pull tasks that tracking budget
|| 09/18/23  RLB 23.09.17 (651512) Added protection to pullconversation in with just a project and no task
|| 07/31/25  RLS 25.08.17 (707119) Added exclusion for project templates in the where clause
|| 07/16/26  RLB 26.08.16 (732714) Added right check so completed tasks are not defaulted for users without prjTimeCompletedTask
|| 07/17/26  RLB 26.08.17 (732714) Task-level PercComp=100 now always excludes regardless of PercCompSeparate, since that is the only signal spTaskValidatePercComp honors at save time; the PercCompSeparate/tu.PercComp check is now an additional restriction, not a replacement
*/

	DECLARE	@RateLevel int, @DefaultServiceKey int,
			@Administrator tinyint, @SecurityGroupKey int, @prjTimeCompletedTask tinyint

	SELECT	@RateLevel = RateLevel,
			@DefaultServiceKey = DefaultServiceKey,
			@Administrator = Administrator,
			@SecurityGroupKey = SecurityGroupKey
	FROM	tUser (nolock)
	WHERE	UserKey = @UserKey

	-- Determine if they can charge time to completed tasks
	SELECT @prjTimeCompletedTask = 0
	IF ISNULL(@Administrator, 0) = 1
		SELECT @prjTimeCompletedTask = 1
	ELSE
		IF EXISTS(SELECT 1 FROM tRightAssigned ra (nolock) WHERE ra.EntityType = ''Security Group'' AND ra.EntityKey = @SecurityGroupKey AND ra.RightKey = 90920)
			SELECT @prjTimeCompletedTask = 1


	DECLARE @NewWorkDate smalldatetime, @NewEndDate smalldatetime

	IF @UTCOffsetHours is not null
		begin
		SELECT @NewWorkDate = DATEADD(HOUR, (-1 * @UTCOffsetHours), @WorkDate)
		SELECT @NewEndDate = DATEADD(HOUR, (-1 * @UTCOffsetHours), @EndWorkDate)
		end
	else
		begin
		SELECT @NewWorkDate = @WorkDate
		SELECT @NewEndDate = @EndWorkDate
		end


	SELECT DISTINCT p.ProjectNumber,
				p.ProjectName,
				al.ProjectKey,
				t.TaskID,
				t.TaskName,
				a.TaskKey,
				t.ProjectOrder,
				@RateLevel AS RateLevel,
				ISNULL(tu.ServiceKey, @DefaultServiceKey) AS ServiceKey,
				s.Description AS ServiceDescription,
				ISNULL(p.ProjectNumber, '''') + ''-'' + ISNULL(p.ProjectName, '''') AS ProjectFullName,
				c.CompanyName AS ClientName,
				ISNULL(camp.CampaignID, '''') + ''-'' + ISNULL(camp.CampaignName, '''') AS CampaignFullName,
				ps.ProjectStatus,
				pt.ProjectTypeName,
				p.AccountManager,
				RTRIM(LTRIM(ISNULL(am.FirstName,'''') + '' '' + ISNULL(am.LastName, ''''))) as AccountManagerName,
				p.ProjectManager,
				RTRIM(LTRIM(ISNULL(pm.FirstName,'''') + '' '' + ISNULL(pm.LastName, ''''))) as ProjectManagerName,
				t.ScheduleTask
	FROM	vActionLog al
	INNER JOIN tProject p (nolock) ON al.ProjectKey = p.ProjectKey
	INNER JOIN tActivity a (nolock) ON al.EntityKey = a.ActivityKey
	LEFT OUTER JOIN tUser am (NOLOCK) on am.UserKey = p.AccountManager
	LEFT OUTER JOIN tUser pm (NOLOCK) on pm.UserKey = p.ProjectManager
	LEFT JOIN tTask t (nolock) ON a.TaskKey = t.TaskKey
	LEFT JOIN tTaskUser tu (nolock) ON t.TaskKey = tu.TaskKey AND tu.UserKey = @UserKey
	LEFT JOIN tService s (nolock) ON ISNULL(tu.ServiceKey, @DefaultServiceKey) = s.ServiceKey
	LEFT JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
	LEFT JOIN tCampaign camp (nolock) ON p.CampaignKey = camp.CampaignKey
	LEFT JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey
	LEFT JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey
	WHERE	al.UserKey = @UserKey
	AND		Entity = ''Activity''
	AND		ActionDate BETWEEN @NewWorkDate and @NewEndDate
	AND		ISNULL(al.ProjectKey, 0) > 0
	AND		ISNULL(t.NoTimeEntry, 0) = 0
	AND     (ISNULL(t.TaskKey, 0) = 0 OR (ISNULL(t.TaskKey, 0) > 0 AND ISNULL(t.TrackBudget, 0) = 1))
	AND		ISNULL(p.Template, 0) = 0
	AND		(ISNULL(t.TaskKey, 0) = 0 OR @prjTimeCompletedTask = 1
			OR (ISNULL(t.PercComp, 0) < 100 AND (ISNULL(t.PercCompSeparate, 0) = 0 OR ISNULL(tu.PercComp, 0) < 100)))

	UNION ALL

	SELECT DISTINCT p.ProjectNumber,
				p.ProjectName,
				al.ProjectKey,
				NULL AS TaskID,
				NULL AS TaskName,
				NULL AS TaskKey,
				0 AS ProjectOrder,
				@RateLevel AS RateLevel,
				@DefaultServiceKey AS ServiceKey,
				s.Description AS ServiceDescription,
				ISNULL(p.ProjectNumber, '''') + ''-'' + ISNULL(p.ProjectName, '''') AS ProjectFullName,
				c.CompanyName AS ClientName,
				ISNULL(camp.CampaignID, '''') + ''-'' + ISNULL(camp.CampaignName, '''') AS CampaignFullName,
				ps.ProjectStatus,
				pt.ProjectTypeName,
				p.AccountManager,
				RTRIM(LTRIM(ISNULL(am.FirstName,'''') + '' '' + ISNULL(am.LastName, ''''))) as AccountManagerName,
				p.ProjectManager,
				RTRIM(LTRIM(ISNULL(pm.FirstName,'''') + '' '' + ISNULL(pm.LastName, ''''))) as ProjectManagerName,
				NULL AS ScheduleTask
	FROM	vActionLog al
	INNER JOIN tProject p (nolock) ON al.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tUser am (NOLOCK) on am.UserKey = p.AccountManager
	LEFT OUTER JOIN tUser pm (NOLOCK) on pm.UserKey = p.ProjectManager
	LEFT JOIN tService s (nolock) ON @DefaultServiceKey = s.ServiceKey
	LEFT JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
	LEFT JOIN tCampaign camp (nolock) ON p.CampaignKey = camp.CampaignKey
	LEFT JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey
	LEFT JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey
	WHERE	al.UserKey = @UserKey
	AND		Entity <> ''Activity'' AND Entity <> ''Time''
	AND		ActionDate BETWEEN @NewWorkDate and @NewEndDate
	AND		ISNULL(al.ProjectKey, 0) > 0
	AND		ISNULL(p.Template, 0) = 0

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIProjectMargin]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIProjectMargin]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIProjectMargin]
(
    @CompanyKey      int,
    @UserKey         int,
    @ProjectNumber   varchar(50)  = null,   -- single project
    @ClientID        varchar(50)  = null,   -- CustomerID or CompanyName
    @ProjectType     varchar(100) = null,
    @ProjectStatus   varchar(50)  = null,
    @ProjectManager  varchar(200) = null,   -- UserID, email, or full name; scopes to this PM''s projects
    @AccountManager  varchar(200) = null,   -- UserID, email, or full name; scopes to this AM''s projects
    @IncludeClosed   tinyint      = 0,      -- 0 = open projects only (default)
    @MinRevenue      money        = null,   -- drop projects billed below this
    @RedMarginPct    decimal(9,4) = 20,     -- margin % at/below = red
    @YellowMarginPct decimal(9,4) = 35,     -- margin % at/below = yellow
    @NearBudgetPct   decimal(9,4) = 80,     -- cost/budget % at/above = yellow (near budget)
    @TopN            int          = 200     -- ceiling on returned rows
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GHL 26.xx      Created. Project profit margin for the AI CFO MCP tool.
||                          Reuses the tProjectRollup margin model from spApiAIProjectGetSummary
||                          (Margin = BilledAmount - net costs; BudgetRemaining = budget - gross costs)
||                          and the same GL-company + assignment security scaffolding.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @ProjectKey          int = null
    declare @ClientKey           int = null
    declare @ProjectTypeKey      int = null
    declare @ProjectStatusKey    int = null
    declare @RestrictToGLCompany int
    declare @CheckAssignment     int
    declare @SecurityGroupKey    int
    declare @AccessOK            int

    ------------------------------------------------------------
    -- 1. Validate user
    ------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if @SecurityGroupKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    from   tPreference (nolock) where CompanyKey = @CompanyKey

    ------------------------------------------------------------
    -- 2. Resolve string filters to keys
    ------------------------------------------------------------
    if @ProjectNumber is not null
        select @ProjectKey = ProjectKey
        from   tProject (nolock)
        where  CompanyKey = @CompanyKey and ProjectNumber = @ProjectNumber

    if @ClientID is not null
        select @ClientKey = CompanyKey
        from   tCompany (nolock)
        where  OwnerCompanyKey = @CompanyKey
          and  (CustomerID = @ClientID or CompanyName = @ClientID)

    if @ProjectType is not null
        select @ProjectTypeKey = ProjectTypeKey
        from   tProjectType (nolock)
        where  CompanyKey = @CompanyKey and ProjectTypeName = @ProjectType

    if @ProjectStatus is not null
        select @ProjectStatusKey = ProjectStatusKey
        from   tProjectStatus (nolock)
        where  CompanyKey = @CompanyKey
          and  (ProjectStatusID = @ProjectStatus or ProjectStatus = @ProjectStatus)

    -- Resolve PM / AM names to UserKeys (-1 = supplied-but-not-found → matches nothing)
    declare @PMKey int = null
    declare @AMKey int = null

    if @ProjectManager is not null and LTRIM(RTRIM(@ProjectManager)) <> ''''
    begin
        select @PMKey = MIN(UserKey) from tUser (nolock)
        where  ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
          and  (UserID = @ProjectManager or Email = @ProjectManager
                or LTRIM(RTRIM(ISNULL(FirstName,'''') + '' '' + ISNULL(LastName,''''))) = LTRIM(RTRIM(@ProjectManager)))
        if @PMKey is null
        begin
            set @PMKey = -1
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'',''NOT_FOUND'',''Project manager "'' + @ProjectManager + ''" not found; no projects matched that PM.'',''projectManager'')
        end
    end

    if @AccountManager is not null and LTRIM(RTRIM(@AccountManager)) <> ''''
    begin
        select @AMKey = MIN(UserKey) from tUser (nolock)
        where  ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
          and  (UserID = @AccountManager or Email = @AccountManager
                or LTRIM(RTRIM(ISNULL(FirstName,'''') + '' '' + ISNULL(LastName,''''))) = LTRIM(RTRIM(@AccountManager)))
        if @AMKey is null
        begin
            set @AMKey = -1
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'',''NOT_FOUND'',''Account manager "'' + @AccountManager + ''" not found; no projects matched that AM.'',''accountManager'')
        end
    end

    ------------------------------------------------------------
    -- 3. Single-project mode: hard-gate via spCheckAccess
    ------------------------------------------------------------
    if @ProjectNumber is not null and LTRIM(RTRIM(@ProjectNumber)) <> ''''
    begin
        if @ProjectKey is null
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', ''Project not found for projectNumber: '' + @ProjectNumber, ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName
            drop table #errors
            return -101
        end

        exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey

        if @AccessOK <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName
            drop table #errors
            return -103
        end
    end

    ------------------------------------------------------------
    -- 4. Candidate projects (billable only; margin is meaningless for non-billable)
    ------------------------------------------------------------
    create table #projectKeys (ProjectKey int not null primary key)

    insert into #projectKeys (ProjectKey)
    select pr.ProjectKey
    from   tProject pr (nolock)
    where  pr.CompanyKey    = @CompanyKey
      and  pr.NonBillable   = 0
      and  (@IncludeClosed = 1 or ISNULL(pr.Closed, 0) = 0)
      and  (@ProjectKey       is null or pr.ProjectKey       = @ProjectKey)
      and  (@ClientKey        is null or pr.ClientKey        = @ClientKey)
      and  (@ProjectTypeKey   is null or pr.ProjectTypeKey   = @ProjectTypeKey)
      and  (@ProjectStatusKey is null or pr.ProjectStatusKey = @ProjectStatusKey)
      and  (@ProjectKey is not null or @PMKey is null or ISNULL(pr.ProjectManager, 0) = @PMKey)
      and  (@ProjectKey is not null or @AMKey is null or ISNULL(pr.AccountManager, 0) = @AMKey)

    ------------------------------------------------------------
    -- 5. List-mode set-based GL company + assignment filter
    --    (single-project mode already passed spCheckAccess)
    ------------------------------------------------------------
    if @ProjectKey is null
    begin
        if @RestrictToGLCompany = 1
            delete pk
            from   #projectKeys pk
            inner join tProject pr (nolock) on pk.ProjectKey = pr.ProjectKey
            where  pr.GLCompanyKey not in (
                       select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)

        set @CheckAssignment = 1
        if exists (
            select 1 from tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where  ra.EntityType = ''Security Group''
              and  ra.EntityKey  = @SecurityGroupKey
              and  r.RightID     = ''prjAccessAny'')
            set @CheckAssignment = 0

        if @CheckAssignment = 1
            delete from #projectKeys
            where  ProjectKey not in (select ProjectKey from tAssignment where UserKey = @UserKey)
    end

    ------------------------------------------------------------
    -- 6. Warnings
    ------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from   #errors where errorType = ''warning''

    ------------------------------------------------------------
    -- 7. Margin rows (computed from tProjectRollup — lifetime to date)
    ------------------------------------------------------------
    ;with m as
    (
        select
             pr.ProjectKey
            ,pr.ProjectNumber
            ,ISNULL(pr.ProjectName, '''')                                     as ProjectName
            ,ISNULL(cl.CustomerID, '''')                                      as ClientID
            ,ISNULL(cl.CompanyName, '''')                                     as ClientName
            ,ISNULL(am.FirstName, '''') + '' '' + ISNULL(am.LastName, '''')       as AccountManager
            ,ISNULL(ps.ProjectStatus, '''')                                   as ProjectStatus
            ,ISNULL(pr.Closed, 0)                                           as Closed
            ,ISNULL(pr.EstHours, 0) + ISNULL(pr.ApprovedCOHours, 0)         as BudgetHours
            ,ISNULL(roll.Hours, 0)                                          as ActualHours
            ,ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)
               + ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0) as BudgetTotal
            ,ISNULL(roll.LaborNet, 0)                                       as LaborCost
            ,ISNULL(roll.MiscCostNet, 0) + ISNULL(roll.ExpReceiptNet, 0)
               + ISNULL(roll.VoucherNet, 0)                                  as ExpenseCost
            ,ISNULL(roll.LaborNet, 0) + ISNULL(roll.MiscCostNet, 0)
               + ISNULL(roll.ExpReceiptNet, 0) + ISNULL(roll.VoucherNet, 0)  as TotalCost
            ,ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0)
               + ISNULL(roll.ExpReceiptGross, 0)
               + ISNULL(roll.VoucherOutsideCostsGross, 0)                    as TotalCostGross
            ,ISNULL(roll.BilledAmount, 0)                                   as RevenueBilled
            ,ISNULL(roll.LaborUnbilled, 0) + ISNULL(roll.MiscCostUnbilled, 0)
               + ISNULL(roll.ExpReceiptUnbilled, 0)
               + ISNULL(roll.VoucherUnbilled, 0)                             as UnbilledTotal
        from   tProject pr (nolock)
        inner join #projectKeys pk on pr.ProjectKey = pk.ProjectKey
        left outer join tProjectRollup roll (nolock) on pr.ProjectKey = roll.ProjectKey
        left outer join tProjectStatus ps (nolock)   on pr.ProjectStatusKey = ps.ProjectStatusKey
        left outer join tCompany cl (nolock)          on pr.ClientKey = cl.CompanyKey
        left outer join tUser am (nolock)             on pr.AccountManager = am.UserKey
    )
    select top (@TopN)
         m.ProjectNumber                                                    as projectNumber
        ,m.ProjectName                                                      as projectName
        ,m.ClientID                                                         as clientID
        ,m.ClientName                                                       as clientName
        ,LTRIM(RTRIM(m.AccountManager))                                     as accountManager
        ,m.ProjectStatus                                                    as projectStatus
        ,m.Closed                                                           as closed
        ,m.BudgetHours                                                      as budgetHours
        ,m.ActualHours                                                      as actualHours
        ,m.BudgetTotal                                                      as budgetTotal
        ,m.LaborCost                                                        as laborCost
        ,m.ExpenseCost                                                      as expenseCost
        ,m.TotalCost                                                        as totalCost
        ,m.TotalCostGross                                                   as totalCostGross
        ,m.RevenueBilled                                                    as revenueBilled
        ,m.RevenueBilled - m.TotalCost                                      as grossMargin
        ,case when m.RevenueBilled <> 0
              then CONVERT(decimal(9,2), 100.0 * (m.RevenueBilled - m.TotalCost) / m.RevenueBilled)
              else 0 end                                                    as grossMarginPct
        ,m.UnbilledTotal                                                    as unbilledTotal
        ,m.BudgetTotal - m.TotalCostGross                                   as budgetRemaining
        ,case when m.BudgetTotal > 0
              then CONVERT(decimal(9,2), 100.0 * m.TotalCostGross / m.BudgetTotal)
              else 0 end                                                    as costVsBudgetPct
        ,case
            when m.RevenueBilled > 0 and (m.RevenueBilled - m.TotalCost) < 0        then ''red''
            when m.BudgetTotal > 0 and m.TotalCostGross > m.BudgetTotal             then ''red''
            when m.RevenueBilled > 0
                 and (100.0 * (m.RevenueBilled - m.TotalCost) / m.RevenueBilled) < @RedMarginPct    then ''red''
            when m.RevenueBilled > 0
                 and (100.0 * (m.RevenueBilled - m.TotalCost) / m.RevenueBilled) < @YellowMarginPct then ''yellow''
            when m.BudgetTotal > 0
                 and (100.0 * m.TotalCostGross / m.BudgetTotal) >= @NearBudgetPct   then ''yellow''
            when m.RevenueBilled = 0 and m.TotalCost > 0                            then ''yellow''
            else ''green''
         end                                                                as severity
        ,case
            when m.RevenueBilled > 0 and (m.RevenueBilled - m.TotalCost) < 0        then ''margin_negative''
            when m.BudgetTotal > 0 and m.TotalCostGross > m.BudgetTotal             then ''over_budget''
            when m.RevenueBilled > 0
                 and (100.0 * (m.RevenueBilled - m.TotalCost) / m.RevenueBilled) < @RedMarginPct    then ''margin_low''
            when m.RevenueBilled > 0
                 and (100.0 * (m.RevenueBilled - m.TotalCost) / m.RevenueBilled) < @YellowMarginPct then ''margin_watch''
            when m.BudgetTotal > 0
                 and (100.0 * m.TotalCostGross / m.BudgetTotal) >= @NearBudgetPct   then ''near_budget''
            when m.RevenueBilled = 0 and m.TotalCost > 0                            then ''unbilled_wip''
            else ''healthy''
         end                                                                as flag
    from   m
    where  (@MinRevenue is null or m.RevenueBilled >= @MinRevenue)
    order by m.RevenueBilled desc

    drop table #projectKeys
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIUtilizationGet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIUtilizationGet]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIUtilizationGet]
    (
        @CompanyKey int,                        -- always first
        @UserKey int,                           -- calling user (rights + GL security)
        @StartDate datetime,
        @EndDate datetime,
        @GroupBy varchar(20) = ''person'',        -- ''person'' | ''department'' | ''office'' | ''agency''
        @TargetUserID varchar(200) = NULL,      -- scope to a single resource (UserID, email, or full name)
        @DepartmentName varchar(200) = NULL,    -- scope to one department (partial match)
        @OfficeName varchar(200) = NULL,        -- scope to one office (partial match)
        @HoursPerDay decimal(9, 4) = 8,         -- capacity basis per weekday
        @TargetPct decimal(9, 4) = 77,          -- utilization target midpoint (for variance)
        @YellowLowPct decimal(9, 4) = 72,       -- below this = yellow (below target)
        @YellowHighPct decimal(9, 4) = 82,      -- above this = yellow (running hot)
        @RedLowPct decimal(9, 4) = 65,          -- below this = red (under-utilized)
        @RedHighPct decimal(9, 4) = 90,         -- above this = red (burnout risk)
        @IncludePriorPeriod tinyint = 1         -- 1 = compute equal-length prior window
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GHL 26.xx      Created. Agency utilization for the AI CFO MCP tool.
||                          Reuses the utilization definition from spRptProjectResourceUtilization:
||                          basis = weekdays * HoursPerDay - PTO; billable = time on projects where
||                          tProject.NonBillable = 0; non-billable split by tProject.UtilizationType.
*/

SET NOCOUNT ON

------------------------------------------------------------
-- Validation
------------------------------------------------------------
select * into #errors from tAPIErrorTemplate where 1 = 2

if @StartDate is null or @EndDate is null
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''startDate and endDate are required.'', ''startDate'')
end
else if @EndDate < @StartDate
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''INVALID_VALUE'', ''endDate must be on or after startDate.'', ''endDate'')
end

set @GroupBy = LOWER(LTRIM(RTRIM(ISNULL(@GroupBy, ''person''))))
if @GroupBy not in (''person'', ''department'', ''office'', ''agency'')
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''INVALID_VALUE'', ''groupBy must be person, department, office, or agency.'', ''groupBy'')
end

------------------------------------------------------------
-- Resolve @TargetUserID (UserID / email / full name) to a UserKey
------------------------------------------------------------
declare @TargetUserKey int = NULL
if @TargetUserID is not null and LTRIM(RTRIM(@TargetUserID)) <> ''''
begin
    select @TargetUserKey = MIN(u.UserKey)
    from tUser u (nolock)
    where ISNULL(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
      and (u.UserID = @TargetUserID
           or u.Email = @TargetUserID
           or LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, ''''))) = LTRIM(RTRIM(@TargetUserID)))

    if @TargetUserKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''No user found matching targetUserID.'', ''targetUserID'')
    end
end

------------------------------------------------------------
-- Rights: viewing other people''s time requires billingviewalltime (admins bypass)
------------------------------------------------------------
declare @IsAdministrator tinyint, @SecurityGroupKey int
select  @IsAdministrator = ISNULL(Administrator, 0), @SecurityGroupKey = SecurityGroupKey
from    tUser (nolock)
where   UserKey = @UserKey

declare @CanViewAllTime tinyint
select  @CanViewAllTime = case when @IsAdministrator = 1 then 1 else 0 end

if @IsAdministrator = 0
begin
    if exists (
        select 1
        from tRight r (nolock)
        inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
        where ra.EntityType = ''Security Group''
          and ra.EntityKey = @SecurityGroupKey
          and r.RightID = ''billingviewalltime'')
        select @CanViewAllTime = 1
end

-- Without the right, a caller may only see their own utilization.
if @CanViewAllTime = 0
begin
    if @TargetUserKey is not null and @TargetUserKey <> @UserKey
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''You do not have rights to view other users'''' utilization.'', ''targetUserID'')
    end
    else
    begin
        set @TargetUserKey = @UserKey
        set @GroupBy = ''person''
    end
end

declare @ErrorCount int
select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
if @ErrorCount > 0
begin
    select errorType, errorCode, errorMessage, fieldName
    from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
end

------------------------------------------------------------
-- Prior period = equal-length window immediately preceding the current one
------------------------------------------------------------
declare @PriorStartDate datetime, @PriorEndDate datetime, @WindowLen int
set @WindowLen = DATEDIFF(d, @StartDate, @EndDate) + 1
set @PriorEndDate = DATEADD(d, -1, @StartDate)
set @PriorStartDate = DATEADD(d, -@WindowLen, @StartDate)

------------------------------------------------------------
-- Weekday counts (Mon-Fri) for each window -> capacity basis driver
------------------------------------------------------------
declare @Cur datetime, @CurWeekdays int, @PriorWeekdays int
select @Cur = @StartDate, @CurWeekdays = 0
while @Cur <= @EndDate
begin
    if DATEPART(dw, @Cur) between 2 and 6 set @CurWeekdays = @CurWeekdays + 1
    set @Cur = DATEADD(d, 1, @Cur)
end

select @Cur = @PriorStartDate, @PriorWeekdays = 0
if @IncludePriorPeriod = 1
begin
    while @Cur <= @PriorEndDate
    begin
        if DATEPART(dw, @Cur) between 2 and 6 set @PriorWeekdays = @PriorWeekdays + 1
        set @Cur = DATEADD(d, 1, @Cur)
    end
end

------------------------------------------------------------
-- GL company restriction
------------------------------------------------------------
declare @RestrictToGLCompany tinyint
select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
from tPreference (nolock) where CompanyKey = @CompanyKey

------------------------------------------------------------
-- In-scope internal staff
------------------------------------------------------------
create table #staff
(
    UserKey int primary key,
    FullName varchar(400),
    Title varchar(200),
    DepartmentKey int,
    DepartmentName varchar(200),
    OfficeKey int,
    OfficeName varchar(200)
)

insert into #staff (UserKey, FullName, Title, DepartmentKey, DepartmentName, OfficeKey, OfficeName)
select  u.UserKey,
        LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, ''''))),
        u.Title,
        ISNULL(dp.DepartmentKey, 0),
        dp.DepartmentName,
        ISNULL(o.OfficeKey, 0),
        o.OfficeName
from    tUser u (nolock)
        left join tDepartment dp (nolock) on u.DepartmentKey = dp.DepartmentKey
        left join tOffice o (nolock) on u.OfficeKey = o.OfficeKey
where   ISNULL(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
    and ISNULL(u.Active, 0) = 1
    and ISNULL(u.ClientVendorLogin, 0) = 0
    and u.UserKey = ISNULL(@TargetUserKey, u.UserKey)
    and (@DepartmentName is null or dp.DepartmentName like ''%'' + @DepartmentName + ''%'')
    and (@OfficeName is null or o.OfficeName like ''%'' + @OfficeName + ''%'')
    and (@RestrictToGLCompany = 0
         or ISNULL(u.GLCompanyKey, 0) in (
                select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))

------------------------------------------------------------
-- Per-user hours for a window (helper via two passes into #hours)
------------------------------------------------------------
create table #hours
(
    Period char(1),                     -- ''C'' current, ''P'' prior
    UserKey int,
    BillableHours decimal(24, 4),
    PTOHours decimal(24, 4),
    InternalHours decimal(24, 4),
    OtherNonBillableHours decimal(24, 4),
    TotalHours decimal(24, 4)
)

insert into #hours (Period, UserKey, BillableHours, PTOHours, InternalHours, OtherNonBillableHours, TotalHours)
select  ''C'',
        t.UserKey,
        SUM(case when ISNULL(p.NonBillable, 0) = 0 then t.ActualHours else 0 end),
        SUM(case when p.UtilizationType = ''PTO'' then t.ActualHours else 0 end),
        SUM(case when ISNULL(p.NonBillable, 0) = 1 and p.UtilizationType in (''Internal'', ''GA'') then t.ActualHours else 0 end),
        SUM(case when ISNULL(p.NonBillable, 0) = 1 and ISNULL(p.UtilizationType, '''') not in (''PTO'', ''Internal'', ''GA'') then t.ActualHours else 0 end),
        SUM(t.ActualHours)
from    tTime t (nolock)
        inner join tProject p (nolock) on t.ProjectKey = p.ProjectKey
        inner join #staff s on t.UserKey = s.UserKey
where   t.WorkDate >= @StartDate and t.WorkDate <= @EndDate
    and p.CompanyKey = @CompanyKey
group by t.UserKey

if @IncludePriorPeriod = 1
begin
    insert into #hours (Period, UserKey, BillableHours, PTOHours, InternalHours, OtherNonBillableHours, TotalHours)
    select  ''P'',
            t.UserKey,
            SUM(case when ISNULL(p.NonBillable, 0) = 0 then t.ActualHours else 0 end),
            SUM(case when p.UtilizationType = ''PTO'' then t.ActualHours else 0 end),
            SUM(case when ISNULL(p.NonBillable, 0) = 1 and p.UtilizationType in (''Internal'', ''GA'') then t.ActualHours else 0 end),
            SUM(case when ISNULL(p.NonBillable, 0) = 1 and ISNULL(p.UtilizationType, '''') not in (''PTO'', ''Internal'', ''GA'') then t.ActualHours else 0 end),
            SUM(t.ActualHours)
    from    tTime t (nolock)
            inner join tProject p (nolock) on t.ProjectKey = p.ProjectKey
            inner join #staff s on t.UserKey = s.UserKey
    where   t.WorkDate >= @PriorStartDate and t.WorkDate <= @PriorEndDate
        and p.CompanyKey = @CompanyKey
    group by t.UserKey
end

------------------------------------------------------------
-- Per-user metrics (basis = weekdays*HoursPerDay - PTO, clamped at 0)
------------------------------------------------------------
create table #metrics
(
    UserKey int,
    FullName varchar(400),
    Title varchar(200),
    DepartmentKey int,
    DepartmentName varchar(200),
    OfficeKey int,
    OfficeName varchar(200),
    BasisHours decimal(24, 4),
    BillableHours decimal(24, 4),
    PTOHours decimal(24, 4),
    InternalHours decimal(24, 4),
    OtherNonBillableHours decimal(24, 4),
    TotalHours decimal(24, 4),
    PriorBasisHours decimal(24, 4),
    PriorBillableHours decimal(24, 4)
)

insert into #metrics
select  s.UserKey, s.FullName, s.Title, s.DepartmentKey, s.DepartmentName, s.OfficeKey, s.OfficeName,
        case when (@CurWeekdays * @HoursPerDay) - ISNULL(c.PTOHours, 0) > 0
             then (@CurWeekdays * @HoursPerDay) - ISNULL(c.PTOHours, 0) else 0 end,
        ISNULL(c.BillableHours, 0),
        ISNULL(c.PTOHours, 0),
        ISNULL(c.InternalHours, 0),
        ISNULL(c.OtherNonBillableHours, 0),
        ISNULL(c.TotalHours, 0),
        case when (@PriorWeekdays * @HoursPerDay) - ISNULL(pr.PTOHours, 0) > 0
             then (@PriorWeekdays * @HoursPerDay) - ISNULL(pr.PTOHours, 0) else 0 end,
        ISNULL(pr.BillableHours, 0)
from    #staff s
        left join #hours c on s.UserKey = c.UserKey and c.Period = ''C''
        left join #hours pr on s.UserKey = pr.UserKey and pr.Period = ''P''

------------------------------------------------------------
-- Roll up to the requested grain into #out
------------------------------------------------------------
create table #out
(
    Grain varchar(20),
    GroupID varchar(100),
    GroupName varchar(400),
    Title varchar(200),
    HeadCount int,
    BasisHours decimal(24, 4),
    BillableHours decimal(24, 4),
    PTOHours decimal(24, 4),
    InternalHours decimal(24, 4),
    OtherNonBillableHours decimal(24, 4),
    TotalHours decimal(24, 4),
    PriorBasisHours decimal(24, 4),
    PriorBillableHours decimal(24, 4),
    SortOrder int
)

if @GroupBy = ''person''
    insert into #out
    select ''person'', CONVERT(varchar(100), UserKey), FullName, Title, 1,
           BasisHours, BillableHours, PTOHours, InternalHours, OtherNonBillableHours, TotalHours,
           PriorBasisHours, PriorBillableHours, 2
    from #metrics
else if @GroupBy = ''department''
    insert into #out
    select ''department'', CONVERT(varchar(100), DepartmentKey), ISNULL(DepartmentName, ''(No Department)''), NULL, COUNT(*),
           SUM(BasisHours), SUM(BillableHours), SUM(PTOHours), SUM(InternalHours), SUM(OtherNonBillableHours), SUM(TotalHours),
           SUM(PriorBasisHours), SUM(PriorBillableHours), 2
    from #metrics group by DepartmentKey, DepartmentName
else if @GroupBy = ''office''
    insert into #out
    select ''office'', CONVERT(varchar(100), OfficeKey), ISNULL(OfficeName, ''(No Office)''), NULL, COUNT(*),
           SUM(BasisHours), SUM(BillableHours), SUM(PTOHours), SUM(InternalHours), SUM(OtherNonBillableHours), SUM(TotalHours),
           SUM(PriorBasisHours), SUM(PriorBillableHours), 2
    from #metrics group by OfficeKey, OfficeName

-- Always include the agency-wide total row (sort first)
insert into #out
select ''agency'', ''0'', ''Agency Total'', NULL, COUNT(*),
       SUM(BasisHours), SUM(BillableHours), SUM(PTOHours), SUM(InternalHours), SUM(OtherNonBillableHours), SUM(TotalHours),
       SUM(PriorBasisHours), SUM(PriorBillableHours), 1
from #metrics

------------------------------------------------------------
-- Warnings (non-fatal)
------------------------------------------------------------
if not exists (select 1 from #staff)
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''warning'', ''NOT_FOUND'', ''No active staff matched the requested scope.'', ''general'')

select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

------------------------------------------------------------
-- Final result set (camelCase aliases, severity computed server-side)
------------------------------------------------------------
select
    o.Grain as grain,
    o.GroupID as groupID,
    o.GroupName as groupName,
    o.Title as title,
    o.HeadCount as headCount,
    o.BasisHours as basisHours,
    o.BillableHours as billableHours,
    o.PTOHours as ptoHours,
    o.InternalHours as internalHours,
    o.OtherNonBillableHours as otherNonBillableHours,
    o.TotalHours as totalLoggedHours,
    case when o.BasisHours > 0 then CONVERT(decimal(9, 2), 100.0 * o.BillableHours / o.BasisHours) else 0 end as utilizationPct,
    o.PriorBasisHours as priorBasisHours,
    o.PriorBillableHours as priorBillableHours,
    case when o.PriorBasisHours > 0 then CONVERT(decimal(9, 2), 100.0 * o.PriorBillableHours / o.PriorBasisHours) else 0 end as priorUtilizationPct,
    case when o.BasisHours > 0 and o.PriorBasisHours > 0
         then CONVERT(decimal(9, 2), (100.0 * o.BillableHours / o.BasisHours) - (100.0 * o.PriorBillableHours / o.PriorBasisHours))
         else 0 end as utilizationDeltaPct,
    @TargetPct as targetPct,
    case when o.BasisHours > 0
         then CONVERT(decimal(9, 2), (100.0 * o.BillableHours / o.BasisHours) - @TargetPct)
         else 0 end as varianceVsTargetPct,
    -- severity + flag from thresholds
    case
        when o.BasisHours = 0 then ''gray''
        when (100.0 * o.BillableHours / o.BasisHours) < @RedLowPct then ''red''
        when (100.0 * o.BillableHours / o.BasisHours) > @RedHighPct then ''red''
        when (100.0 * o.BillableHours / o.BasisHours) < @YellowLowPct then ''yellow''
        when (100.0 * o.BillableHours / o.BasisHours) > @YellowHighPct then ''yellow''
        else ''green''
    end as severity,
    case
        when o.BasisHours = 0 then ''no_capacity''
        when (100.0 * o.BillableHours / o.BasisHours) < @RedLowPct then ''under_utilized''
        when (100.0 * o.BillableHours / o.BasisHours) > @RedHighPct then ''burnout_risk''
        when (100.0 * o.BillableHours / o.BasisHours) < @YellowLowPct then ''below_target''
        when (100.0 * o.BillableHours / o.BasisHours) > @YellowHighPct then ''running_hot''
        else ''on_target''
    end as flag,
    CONVERT(varchar(10), @StartDate, 120) as windowStart,
    CONVERT(varchar(10), @EndDate, 120) as windowEnd,
    CONVERT(varchar(10), @PriorStartDate, 120) as priorWindowStart,
    CONVERT(varchar(10), @PriorEndDate, 120) as priorWindowEnd
from #out o
order by o.SortOrder,
         case when o.BasisHours > 0 then 100.0 * o.BillableHours / o.BasisHours else 999 end,
         o.GroupName

drop table #out
drop table #metrics
drop table #hours
drop table #staff
drop table #errors
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptImportExportSeedApiDoco]'
GO
IF OBJECT_ID(N'[dbo].[sptImportExportSeedApiDoco]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptImportExportSeedApiDoco]

AS
/*
 exec sptImportExportSeedApiDoco
|| When			Who Rel      What

|| 01/05/24     AMP 24.01.21 (636149) Modified the Credit Card Charge for Item - If the pref is required the field will be displayed in the required field list on the import screen, also made Net Cost always a required field
|| 01/19/24     CRG 24.02.19 (655377) Added Weekly Hours to the Task Import
|| 02/21/24     CRG 24.03.17 (664040) Added CalendarApprover to the Employee Import
|| 02/21/24     RLB 24.03.17 (664982) adding Invoice Label
|| 03/20/24     MCM 24.04.xx (658620) Adding Hourly Cost for Service Rate Sheet
|| 04/05/24     MCM 24.05.19 (669368) Adding get by id for station and publication and searhFor PO and IO
|| 04/24/24		MCM 24.05.19 (670663) Adding currencyID to the glAccounts import
|| 08/08/24		MCM 24.09.x  (676638) Adding Retainer custom field entity
|| 08/20/24		MCM 24.09.x  (681078) Adding GL Company Exchange rate to the JE detail api
|| 08/21/24     GAR 24.10.x  (680406) Adding Avalara Tax Code to Services
|| 10/09/24     GAR 24.11.x  (684268) Adding a new endpoint for updating staff rates on projects
|| 11/19/24		MCM 24.12.x  (688332) Fixing the startdate and endDate for the timesheet to be header
|| 12/09/24     MCM 25.01.x  (682120) Added toCurrencyID to the Currency import
|| 12/17/24     MCM 24.17.x  (689256) Updated the GLCompanyKey to be GLCompanyID
|| 12/18/24		MCM 25.01.x  (689448) Added notes to the todo import
|| 01/10/25		MCM 25.02.x  (688779) Added additional fields for the view import
|| 03/04/25		MCM 25.04.x  (694525) Added custom fields to the activities import
|| 03/06/25		MCM 25.04.x  (692694) Added split billing to the project import
|| 04/16/25	    MCM 25.05.x  (696669) Added ability to update Credit Card Connector (Transactions aka ccEntry)
|| 05/14/25		MCM 25.06.x  (701811) Added the GL CompanyKey to the credit card connector
|| 05/30/25		MCM 25.06.x	 (702845) Added conversation search by projectNumber
|| 06/25/25		MCM 25.07.x  (700522) Added GL Budget export view
|| 07/11/25     MCM 25.08.x  (700243) Added HeaderID for PO, IO, BO
|| 08/11/25     MCM 25.09.x  (706891) Added ProjectColor to the Client import
|| 08/12/25		MCM 25.09.x  (705830) Added AssignedUserID to the todo import
|| 09/04/25     MCM 25.10.x  (709191) Added Address Name to client/company/vendor import
|| 10/07/25		MCM 25.11.x  (711735) Added Avalara Tax Code to project import
|| 10/10/25		MCM 25.11.x  (710932) Updated ToDo to allow updates and added completed field
|| 10/10/25		MCM 25.11.x  (709479) Updated timesheets with complete and reject options.
|| 12/31/25		MCM 26.01.x  (694595) Added Publication ID and Staion ID as conditionally required using SystemSettingFieldName
|| 01/14/26		MCM 26.02.x  (719575) Added Request ID to the Campaign import
|| 01/27/26		MCM 26.02.x  (719809) Added sendNotifications to the Task Import
|| 03/12/26		MCM 26.04.x  (723933) Added billable to the IO import
|| 03/18/26		MCM 26.04.x  (724666) Removed duplicate columns in the viewKey section
|| 03/24/26		MCM 26.04.x  (638176) Added Billing Schedule items
|| 04/14/26		MCM 26.05.x  (725995) Added comments to the credit card charge import
|| 04/21/26     GAR 26.05.x  (726790) Change the glCompanyKey in the Conversations import to glCompanyID
|| 05/28/26     AMP 26.06.14 (729025) Added Status to Project Requests
|| 07/08/26     MAS 26.07.19 (732561) Documented Media Plans atomic per-line validation error responses
|| 07/27/26     MCM 26.07.x  (733348) Added PO Type to Estimate Import
*/
BEGIN
/*************************************************************************************************************************
tImportExport and tImportExportDetail
**************************************************************************************************************************/
delete tImportExport
delete tImportExportDetail

DECLARE @ActivityKey int = 39
DECLARE @ActivityTypeKey int = 49
DECLARE @AddressKey int = 79
DECLARE @AvalaraTaxCodeKey int = 126
DECLARE @BillingGroupKey int = 61
DECLARE @BillingScheduleKey int = 135
DECLARE @BOKey int = 77
DECLARE @CampaignKey int = 124
DECLARE @ClientKey int = 71
DECLARE @ClientPaymentsKey int = 19  --To be deprecated 1/1/2020... Use Receipts instead
DECLARE @CompanyKey int = 37
DECLARE @ContactKey int = 1
DECLARE @ConversationKey int = 116
DECLARE @ConversationSearchKey int = 131
DECLARE @CreditCardCharge int = 57
DECLARE @CreditCardConnector int = 62
DECLARE @CurrencyRateKey int = 63
DECLARE @DeliverableKey int = 80
DECLARE @EmployeeKey int = 3
DECLARE @EstimateKey int = 16
DECLARE @ExpenseReportKey int = 22
DECLARE @GLAccountKey int = 6
DECLARE @GLBudget int = 60
DECLARE @InvoiceKey int = 11
DECLARE @ItemRateSheetKey int = 59
DECLARE @IOKey int = 34
DECLARE @JEKey int = 24
DECLARE @LeadKey int = 36
DECLARE @MediaPlanKey int select @MediaPlanKey = 111
DECLARE @MediaPlanReleaseKey int select @MediaPlanReleaseKey = 113
DECLARE @MediaPlanVoucherKey int select @MediaPlanVoucherKey = 112
DECLARE @OpportunitiesKey int = 38
DECLARE @POKey int = 18
DECLARE @ProjectKey int = 13
DECLARE @ProjectStaffRatesKey int = 127
DECLARE @ProjectStatusCodeKey int = 27
DECLARE @ProjectRequestKey int = 76
DECLARE @PublicationKey int = 120
DECLARE @ReceiptsKey int = 115
DECLARE @ReportKey int =  109
DECLARE @RetainerKey int = 118
DECLARE @ServiceRateSheetKey int = 58
DECLARE @StationKey int = 122
DECLARE @TaskKey int = 69
DECLARE @TimeSheetKey int = 21
DECLARE @TimeSheetTimeKey int = 107
DECLARE @TimeSheetCompleteKey int = 132
DECLARE @TimeSheetRejectKey int = 133
DECLARE @TimeKey int = 72
DECLARE @ToDoKey int = 84
DECLARE @VendorKey int = 70
DECLARE @VendorPaymentKey int = 20
DECLARE @ViewKey int = 78
DECLARE @VoucherKey int = 12



INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ContactKey, N''Contacts'', N''contacts'', NULL, NULL, N''Contact'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@EmployeeKey, N''Employees'', N''employees'', NULL, NULL, N''Employees'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (4, N''Expense Report Items'', N''expensereportitems'', NULL, NULL, NULL, N''vExport_ExpenseReportItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (5, N''Purchase Items'', N''purchaseitem'', NULL, NULL, NULL, N''vExport_PurchaseItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@GLAccountKey, N''GL Accounts'', N''glaccounts'', NULL, NULL, NULL, N''vExport_GLAccount'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (7, N''Payment Terms'', N''paymentterms'', NULL, NULL, NULL, N''tPaymentTerms'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (8, N''Sales Tax'', N''salestaxrates'', NULL, NULL, NULL, N''vExport_SalesTax'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (9, N''Services'', N''services'', NULL, NULL, NULL, N''vExport_Service'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (10, N''Billing Items'', N''billingitems'', NULL, NULL, NULL, N''vExport_WorkType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@InvoiceKey, N''Client Invoices'', N''invoices'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@VoucherKey, N''Vendor Invoices'', N''vouchers'', 1, N''details'', N''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectKey, N''Projects'', N''projects'', NULL, NULL, N''Project'', ''vExport_Project'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (16, N''Estimates'', N''estimates'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@POKey, N''Purchase Orders'', N''purchaseorders'', 1, N''details'', N''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ClientPaymentsKey, N''Client Payments'', N''clientpayments'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@VendorPaymentKey, N''Vendor Payments'', N''vendorpayments'', 1, N''details'',  NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@TimeSheetKey, N''Timesheets'', N''timesheets'', 1, N''time'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ExpenseReportKey, N''Expense Reports'', N''expensereports'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (23, N''Misc Project Costs'', N''misccosts'', NULL, NULL, NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@JEKey, N''Journal Entries'', N''journalentries'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (25, N''Project Types'', N''projecttypes'', NULL, NULL, NULL, N''tProjectType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectStatusCodeKey, N''Project Status'', N''projectstatuscodes'', NULL, NULL, NULL, N''tProjectStatus'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (28, N''Departments'', N''departments'', NULL, NULL, NULL, N''tDepartment'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (29, N''Project Billing Status'', N''projectbillingcodes'', NULL, NULL, NULL, N''tProjectBillingStatus'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (31, N''Broadcast Items'', N''broadcastitems'', NULL, NULL, NULL, N''vExport_BroadcastItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (32, N''Print Items'', N''printitems'', NULL, NULL, NULL, N''vExport_PrintItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (33, N''GL Companies'', N''glcompanies'', NULL, NULL, NULL, N''vExport_GLCompany'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@IOKey, N''Insertion Orders'', N''insertionorders'', 1, N''details'', N''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@LeadKey, N''Leads'', N''leads'', NULL, NULL, N''Company|Contact|Lead'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CompanyKey, N''Companies'', N''companies'', NULL, NULL, N''Company'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@OpportunitiesKey, N''Opportunities'', N''opportunities'', NULL, NULL, N''Lead'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ActivityKey, N''Activities'', N''activities'', NULL, NULL, ''Activity'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (40, N''Report Groups'', N''reportgroups'', NULL, NULL, NULL, N''tReportGroup'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (41, N''Opportunity Stages'', N''opportunitystages'', NULL, NULL, NULL, N''tLeadStage'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (42, N''Opportunity Status'', N''opportunitystatus'', NULL, NULL, NULL, N''tLeadStatus'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (43, N''Opportunity Outcome'', N''opportunityoutcome'', NULL, NULL, NULL, N''tLeadOutcome'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (44, N''Company Types'', N''companytypes'', NULL, NULL, NULL, N''tCompanyType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (45, N''Meeting Types'', N''calendartypes'', NULL, NULL, NULL, N''tCalendarType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (46, N''Calendar Resources'', N''calendarresources'', NULL, NULL, NULL, N''tCalendarResource'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (48, N''Sources'', N''sources'', NULL, NULL, NULL, N''tSource'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ActivityTypeKey, N''Conversation Types'', N''activitytypes'', NULL, NULL, NULL, N''tActivityType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (50, N''Payment Methods'', N''paymentmethods'', NULL, NULL, NULL, N''tCheckMethod'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (51, N''Write Off Reasons'', N''writeoffreasons'', NULL, NULL, NULL, N''tWriteOffReason'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (52, N''Standard Text'', N''standardtext'', NULL, NULL, NULL, N''tStandardText'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (53, N''Media Markets'', N''mediamarkets'', NULL, NULL, NULL, N''tMediaMarket'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (54, N''GL Classes'', N''glclasses'', NULL, NULL, NULL, N''vExport_GLClass'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (55, N''Offices'', N''offices'', NULL, NULL, NULL, N''tOffice'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (56, N''Teams'', N''teams'', NULL, NULL, NULL, N''vExport_Team'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CreditCardCharge, N''Credit Card Charges'', N''creditcardcharges'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ServiceRateSheetKey, N''Service Rate Sheets'', N''serviceratesheets'', 1, N''details'', NULL, N''vExport_ServiceRateSheet'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ItemRateSheetKey, N''Item Rate Sheets'', N''itemratesheets'', 1, N''details'', NULL, N''vExport_ItemRateSheet'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@GLBudget, N''Financial Budgets'', N''financialbudgets'', 1, N''details'', NULL, N''vExport_GLFinancialBudget'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@BillingGroupKey, N''Billing Groups'', N''billinggroups'', NULL, NULL, NULL, N''vExport_BillingGroup'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CreditCardConnector, N''Credit Card Connector'', N''creditcardtransactions'', NULL, NULL, NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CurrencyRateKey, N''Currency Rates'', N''currencyrates'', NULL, NULL, NULL, N''vExport_CurrencyRate'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [Condition]) VALUES (64, N''Titles'', N''titles'', NULL, NULL, NULL, N''vExport_Title'', 1, NULL, 1, 1, 0, 0, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [Condition]) VALUES (65, N''Title Rate Sheets'', N''titleratesheets'', 1, N''details'', NULL, N''vExport_TitleRateSheet'', 1, NULL, 1, 1, 0, 0, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (67, N''Request Reject Reasons'', N''requestrejectreasons'', NULL, NULL, NULL, N''tRequestRejectReason'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@TaskKey, N''Tasks'', N''tasks'', 1, N''assignments'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@VendorKey, N''Vendors'', N''vendors'', NULL, NULL, N''Company'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ClientKey, N''Clients'', N''clients'', NULL, NULL, N''Company'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@TimeKey, N''Time'', N''time'', NULL, NULL, NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (73, N''Project Spec Sheets'', N''projectspecsheets'', NULL, NULL, N''Spec'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (74, N''Request Spec Sheets'', N''requestspecsheets'', NULL, NULL, N''Spec'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (75, N''Labor Budgets'', N''laborbudgets'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectRequestKey, N''Project Request'', N''projectrequests'', NULL, NULL, N''RequestDef'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@BOKey, N''Broadcast Orders'', N''broadcastorders'', 1, N''details'', ''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ViewKey, N''View'', N''view'', NULL, Null, NULL, NULL, 1, ''Used to import data into the tReport table'', 0, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@AddressKey, N''Address'', N''address'', NULL, Null, NULL, NULL,1, ''Used to add an address to a company, vendor, or client'', 0, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@DeliverableKey, N''Deliverables'', N''deliverables'', NULL, Null, N''Deliverable|DeliverableType'', NULL,1, NULL, 0, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ToDoKey, N''To Do'', N''todos'', NULL, Null, N''To Do'', NULL,1, NULL, 1, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectStaffRatesKey, N''Project Staff Rates'', N''projectstaffrates'', NULL, Null, N''Project Staff Rates'', NULL,1, ''Used to update the staff rates on a project when the Get Rate From is Project User'', 1, 0, 1, 0)
--Just for API doco
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (100, N''Opportunities/List'', N''opportunities/list'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (101, N''Activities/Search'', N''activities/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (102, N''Companies/Search'', N''companies/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (103, N''Contacts/Search'', N''contacts/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (104, N''Employees/Search'', N''employees/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
--INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (105, N''JournalEntries/Search'', N''journalentries/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (106, N''Leads/Search'', N''leads/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@TimeSheetTimeKey, N''Timesheets/Time'', N''timesheets/time'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (108, N''Vendors/Search'', N''vendors/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@ReportKey, N''Reports'', N''reports'', NULL, Null, NULL, NULL,1 ,'''' , 1, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@MediaPlanKey, N''Media Plans'', N''mediaplans'', 1, ''details'', NULL, NULL,1 ,N''Create (POST) or update (PUT) a media plan and its detail lines. Validation is atomic: if any detail line fails validation, the entire request is rejected with HTTP 400 and nothing is saved. On failure the errors array contains one message per invalid line, each prefixed with the line number and SpotLinkID (for example: Line 2 (SpotLinkID 7308462): Invalid Item.). Possible line messages are: Invalid Item. (itemID does not match an active item for the company), Invalid Vendor. (vendorID was not found), Inactive vendor (the vendorID exists but is not active), and Invalid Station/Publication. (the stationID is not valid for the given vendor and item). Correct every reported line and resubmit; the plan is saved only when all lines are valid.'' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@MediaPlanVoucherKey, N''Media Plan Vendor Invoices'', N''mediaplanvouchers'', 1, ''details'', NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ReceiptsKey, N''Receipts'', N''receipts'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@MediaPlanReleaseKey, N''Media Plan Release'', N''mediaplanrelease'', NULL, Null, NULL, NULL,1 ,'''' , 0, 0, 1, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@RetainerKey, N''Retainer'', N''retainer'', NULL, Null, N''Retainer'', NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@PublicationKey, N''Publication'', N''publications'', NULL, Null, NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@StationKey, N''Station'', N''stations'', NULL, Null, NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CampaignKey, N''Campaign'', N''campaigns'', 1, N''details'', ''Campaign'', NULL,1 ,'''' , 1, 1, 1, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@ConversationKey, N''Conversation'', N''conversations'', NULL, Null, ''Activity'', NULL,1 ,''Used for import conversations.'' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@ConversationSearchKey, N''Conversations/Search'', N''Conversations/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly], [Condition]) VALUES (@AvalaraTaxCodeKey, N''AvalaraTaxCodes'', NULL, NULL, Null, NULL, ''tAvalaraTaxCode'', 1 ,''Used for importing and exporting Avalara Tax Codes.'' , 0, 0, 0, 0, 1, N''System.hasCustomization(''''avalara'''')'')
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@TimeSheetCompleteKey, N''Timesheets/Complete'', N''timesheets/complete'', NULL, Null, NULL, NULL,1, ''Used for submitting/approving the timesheet.  If user has right to approve it will be approved, otherwise, it will be submitted'', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@TimeSheetRejectKey, N''Timesheets/Reject'', N''timesheets/reject'', NULL, Null, NULL, NULL,1, ''Used for reject a timesheet.'', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@BillingScheduleKey, N''Billing Schedule'', N''billingSchedule'', NULL, Null, NULL, NULL,1, ''Billing Schedule for a specified Project/Campaign'', 1, 1, 1, 0)

SET IDENTITY_INSERT [dbo].[tImportExportDetail] ON 

--Activities
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7745, @ActivityKey, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7746, @ActivityKey, N''Activity Date'', N''activityDate'', NULL, NULL, N''Activity Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7747, @ActivityKey, N''Completed'', N''completed'', NULL, NULL, N''Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7748, @ActivityKey, N''Date Completed'', N''dateCompleted'', NULL, NULL, N''Date Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7749, @ActivityKey, N''Assigned To'', N''assignedUser'', NULL, NULL, N''Assigned To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7750, @ActivityKey, N''Private'', N''private'', NULL, NULL, N''Private'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7751, @ActivityKey, N''Folder'', N''cMFolderKey'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7752, @ActivityKey, N''Activity Type'', N''activityTypeKey'', NULL, NULL, N''Activity Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7753, @ActivityKey, N''Notes'', N''notes'', NULL, NULL, N''Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7754, @ActivityKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7755, @ActivityKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7756, @ActivityKey, N''Contact'', N''linkedContact'', NULL, NULL, N''Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7757, @ActivityKey, N''Company'', N''linkedCompany'', NULL, NULL, N''Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7758, @ActivityKey, N''Opportunity'', N''linkedLead'', NULL, NULL, N''Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7759, @ActivityKey, N''Lead'', N''linkedUserLead'', NULL, NULL, N''Lead'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7760, @ActivityKey, N''Start Time'', N''startTime'', NULL, NULL, N''Start Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7761, @ActivityKey, N''End Time'', N''endTime'', NULL, NULL, N''End Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7762, @ActivityKey, N''Reminder (minutes)'', N''reminderMinutes'', NULL, NULL, N''Reminder (minutes)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7763, @ActivityKey, N''Priority'', N''priority'', NULL, NULL, N''Priority'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7764, @ActivityKey, N''Originator'', N''originatorUserKey'', NULL, NULL, N''Originator'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7765, @ActivityKey, N''Visible To Client'', N''visibleToClient'', NULL, NULL, N''Visible To Client'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7766, @ActivityKey, N''View As'', N''activityEntity'', NULL, NULL, N''View As'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7767, @ActivityKey, N''Outcome'', N''outcome'', NULL, NULL, N''Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7768, @ActivityKey, N''GL Company'', N''glCompanyKey'', NULL, NULL, N''GL Company, Required if GL Company is required '', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
--Activity aka Conversation Types
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7769, @ActivityTypeKey, N''Type Name'', N''typeName'', NULL, N''TypeName'', N''Type Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7770, @ActivityTypeKey, N''Display Color'', N''typeColor'', NULL, N''TypeColor'', N''Display Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7771, @ActivityTypeKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7772, @ActivityTypeKey, N''Auto Roll Date'', N''autoRollDate'', NULL, N''AutoRollDate'', N''Auto Roll Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Address
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79001, @AddressKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79002, @AddressKey, N''Company Key'', N''companyKey'', NULL, NULL, N''Company Key'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79003, @AddressKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79004, @AddressKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79005, @AddressKey, N''Address Name'', N''addressName'', NULL, NULL, N''Address Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79006, @AddressKey, N''Address 1'', N''address1'', NULL, NULL, N''Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79007, @AddressKey, N''Address 2'', N''address2'', NULL, NULL, N''Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79008, @AddressKey, N''Address 3'', N''address3'', NULL, NULL, N''CAddress 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79009, @AddressKey, N''City'', N''city'', NULL, NULL, N''City'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79010, @AddressKey, N''State'', N''state'', NULL, NULL, N''State'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79011, @AddressKey, N''Postal Code'', N''postalCode'', NULL, NULL, N''Postal Code'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79012, @AddressKey, N''Country'', N''country'', NULL, NULL, N''Country'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
--Billing Group
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7773, @BillingGroupKey, N''Billing Group Code'', N''billingGroupCode'', NULL, N''BillingGroupCode'', N''Billing Group Code'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7774, @BillingGroupKey, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7775, @BillingGroupKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7776, @BillingGroupKey, N''Comments'', N''comments'', NULL, N''Comments'', N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7777, @BillingGroupKey, N''GLCompany'', N''glCompanyKey'', NULL, N''GLCompanyID'', N''GLCompany, required if GL Company is required'', NULL, 2, N''GLCompanyID'', NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
-- Billing Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7778, 10, N''ID'', N''workTypeID'', NULL, N''WorkTypeID'', N''ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7779, 10, N''Name'', N''workTypeName'', NULL, N''WorkTypeName'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7780, 10, N''Standard Price'', N''standardPrice'', NULL, N''StandardPrice'', N''Standard Price'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7781, 10, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7782, 10, N''Sales Account Number'', N''glAccountNumber'', NULL, N''GLAccountNumber'', N''Sales Account Number'', NULL, NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7783, 10, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7784, 10, N''Department'', N''departmentID'', NULL, N''DepartmentName'', N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7785, 10, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7786, 10, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7787, 10, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7788, 10, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID'', NULL, NULL, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (788800, 10, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')

-- Billing Schedule
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135001, @BillingScheduleKey, N''Project Number'', N''projectNumber'', NULL, N''Project Number'', N''Project Number'', NULL, 1, NULL, NULl, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135002, @BillingScheduleKey, N''Date to Bill'', N''nextBillDate'', NULL, N''Next Bill Date'', N''Date To Bill'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135003, @BillingScheduleKey, N''Task ID'', N''taskID'', NULL, N''Task ID'', N''Set Date to bill when this task is complete'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135004, @BillingScheduleKey, N''Billing Comments'', N''comments'', NULL, N''Billing Comments'', N''Billing Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135005, @BillingScheduleKey, N''Percent Budget'', N''percentBudget'', NULL, N''Percent Budget'', N''Percent of Budget to Bill'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135006, @BillingScheduleKey, N''Dollar Amount'', N''dollarAmount'', NULL, N''Dollar Amount'', N''Dollar Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135007, @BillingScheduleKey, N''Advance Bill'', N''advanceBill'', NULL, N''Advance Bill'', N''Advance Bill'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135008, @BillingScheduleKey, N''Campaign ID'', N''campaignID'', NULL, N''Campaign ID'', N''Campaign ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)

-- Broadcast Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7789, 31, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7790, 31, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7791, 31, N''Commission'', N''markup'', NULL, N''Markup'', N''Commission'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7792, 31, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7793, 31, N''Billing Item ID'', N''workType'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7794, 31, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department, required if departments are required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7795, 31, N''Expense Account Number'', N''expenseAccount'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7796, 31, N''Sales Account Number'', N''salesAccount'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7797, 31, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7798, 31, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7799, 31, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7800, 31, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID, required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (780100, 31, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')
--Calendar Resource
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7801, 46, N''Resource Name'', N''resourceName'', NULL, N''ResourceName'', N''Resource Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
-- Meeting aka Calendar Types
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7802, 45, N''Type Name'', N''typeName'', NULL, NULL, N''Type Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7803, 45, N''Type Color'', N''typeColor'', NULL, NULL, N''Type Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7804, 45, N''Display Order'', N''displayOrder'', NULL, NULL, N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Campaigns
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124001, @CampaignKey, N''Campaign ID'', N''campaignID'', NULL, NULL, N''Campaign ID'', N''header'', 0, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124002, @CampaignKey, N''Campaign Name'', N''campaignName'', NULL, NULL, N''Campaign Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124003, @CampaignKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124004, @CampaignKey, N''Description'', N''description'', NULL, NULL, N''description'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124005, @CampaignKey, N''objective'', N''objective'', NULL, NULL, N''objective'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124006, @CampaignKey, N''Start Date'', N''startDate'', NULL, NULL, N''Start Date'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124007, @CampaignKey, N''End Date'', N''endDate'', NULL, NULL, N''End Date'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124008, @CampaignKey, N''Account Manager'', N''accountManager'', NULL, NULL, N''Account Manager'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124009, @CampaignKey, N''Active'', N''active'', NULL, NULL, N''Active'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124010, @CampaignKey, N''Get Actuals By'', N''getActualsBy'', NULL, NULL, N''Get Actuals By'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124011, @CampaignKey, N''Layout'', N''layout'', NULL, NULL, N''Layout'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124012, @CampaignKey, N''multipleSegments;
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124013, @CampaignKey, N''Bill By'', N''billBy'', NULL, NULL, N''Bill By'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124014, @CampaignKey, N''One Line Per'', N''oneLinePer'', NULL, NULL, N''One Line Per'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124015, @CampaignKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124016, @CampaignKey, N''GL Company'', N''gLCompany'', NULL, NULL, N''GL Company'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124017, @CampaignKey, N''Client Division'', N''clientDivision'', NULL, NULL, N''clientDivision'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124018, @CampaignKey, N''Client Product'', N''clientProduct'', NULL, NULL, N''Client Product'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124019, @CampaignKey, N''Next Project Number'', N''nextProjectNum'', NULL, NULL, N''Next Project Number'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124020, @CampaignKey, N''Currency ID'', N''currencyID'', NULL, NULL, N''currency ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124021, @CampaignKey, N''Opportunity ID'', N''opportunityID'', NULL, NULL, N''Opportunity ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124022, @CampaignKey, N''Project Manager'', N''projectManager'', NULL, NULL, N''Project Manager'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124023, @CampaignKey, N''Use Campaign Budget'', N''useCampaignBudget'', NULL, NULL, N''Use Campaign Budget Manager'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124024, @CampaignKey, N''Expenses Not Included'', N''expensesNotIncluded'', NULL, NULL, N''Expenses Not Included'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124025, @CampaignKey, N''Bill by Percentage of'', N''billByFF'', NULL, NULL, N''Bill by Percentage of'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124030, @CampaignKey, N''Segment Name'', N''segmentName'', NULL, NULL, N''Segment Name'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124031, @CampaignKey, N''Segment Description'', N''segmentDescription'', NULL, NULL, N''segment Description'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124032, @CampaignKey, N''Segment Plan Start Date'', N''segmentPlanStartDate'', NULL, NULL, N''segment Plan Start Date'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124033, @CampaignKey, N''Segment Plan End Date'', N''segmentPlanEndDate'', NULL, NULL, N''segment Plan End Date'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124034, @CampaignKey, N''Segment Action'', N''action'', NULL, NULL, N''Segment Action - a/u/d for Add, Updated, or Delete to segment'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124040, @CampaignKey, N''Copy Campaign ID'', N''copyCampaignID'', NULL, NULL, N''Copy Campaign ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124041, @CampaignKey, N''Copy Projects'', N''copyProjects'', NULL, NULL, N''Copy Projects (yes/no) when copying a campaign'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124042, @CampaignKey, N''Copy Estimates'', N''copyEstimates'', NULL, NULL, N''Copy Estimates (yes/no) when copying a campaign'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124043, @CampaignKey, N''Client Campaign Number'', N''clientCampaignNumber'', NULL, NULL, N''Client Campaign Number'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124045, @CampaignKey, N''Campaign Request ID'', N''requestID'', NULL, NULL, N''Campaign Request ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)

-- Client Receipts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7805, @ClientPaymentsKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7806, @ClientPaymentsKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7807, @ClientPaymentsKey, N''Check Amount'', N''checkAmount'', NULL, NULL, N''Check Amount'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7808, @ClientPaymentsKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7809, @ClientPaymentsKey, N''Reference Number'', N''referenceNumber'', NULL, NULL, N''Reference Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7810, @ClientPaymentsKey, N''Payment Method'', N''paymentMethod'', NULL, NULL, N''Payment Method'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7811, @ClientPaymentsKey, N''Receipt Date'', N''checkDate'', NULL, NULL, N''Receipt Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7812, @ClientPaymentsKey, N''Deposit ID'', N''depositID'', NULL, NULL, N''Deposit ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7813, @ClientPaymentsKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7814, @ClientPaymentsKey, N''Cash Account Number'', N''cashAccountNumber'', NULL, NULL, N''Cash Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7815, @ClientPaymentsKey, N''Unapplied Payment Account Number'', N''prepayAccountNumber'', NULL, NULL, N''Unapplied Payment Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7816, @ClientPaymentsKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7817, @ClientPaymentsKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7818, @ClientPaymentsKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7819, @ClientPaymentsKey, N''GL Account'', N''glAccount'', NULL, NULL, N''GL Account'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7820, @ClientPaymentsKey, N''Description (Line)'', N''description'', NULL, NULL, N''Description (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7821, @ClientPaymentsKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7822, @ClientPaymentsKey, N''Department'', N''department'', NULL, NULL, N''Department. Required if Department is required.'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7823, @ClientPaymentsKey, N''Amount Applied'', N''amount'', NULL, NULL, N''Amount Applied'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7824, @ClientPaymentsKey, N''Office'', N''office'', NULL, NULL, N''Office. Required if Office ie required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7825, @ClientPaymentsKey, N''Target GL Company'', N''targetGLCompany'', NULL, NULL, N''Target GL Company. Required if GL Company is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7826, @ClientPaymentsKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7827, @ClientPaymentsKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7828, @ClientPaymentsKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7829, @ClientPaymentsKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
-- Clients
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7830, @ClientKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7831, @ClientKey, N''Primary Contact'', N''primaryContact'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7832, @ClientKey, N''Company Source'', N''companySource'', NULL, NULL, N''Company Source'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7833, @ClientKey, N''Company Type'', N''companyType'', NULL, NULL, N''Company Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7834, @ClientKey, N''Billing Manager'', N''billingManager'', NULL, NULL, N''Billing Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7835, @ClientKey, N''Phone'', N''phone'', NULL, NULL, N''Phone'', NULL, NULL, NULL, 4, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7836, @ClientKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7837, @ClientKey, N''Web Site'', N''website'', NULL, NULL, N''Web Site'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7838, @ClientKey, N''Twitter ID'', N''twitterID'', NULL, NULL, N''Twitter ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7839, @ClientKey, N''Company Address 1'', N''address1'', NULL, NULL, N''Company Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7840, @ClientKey, N''Company Address 2'', N''address2'', NULL, NULL, N''Company Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7841, @ClientKey, N''Company Address 3'', N''address3'', NULL, NULL, N''Company Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7842, @ClientKey, N''Company City'', N''city'', NULL, NULL, N''Company City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7843, @ClientKey, N''Company State'', N''state'', NULL, NULL, N''Company State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7844, @ClientKey, N''Company Postal Code'', N''postalCode'', NULL, NULL, N''Company Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7845, @ClientKey, N''Company Country'', N''country'', NULL, NULL, N''Company Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7846, @ClientKey, N''Company Owner'', N''companyOwner'', NULL, NULL, N''Company Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7847, @ClientKey, N''Account Manager'', N''accountManager'', NULL, NULL, N''Account Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7848, @ClientKey, N''Sales Person'', N''salesPerson'', NULL, NULL, N''Sales Person'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7849, @ClientKey, N''Folder'', N''folderName'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7850, @ClientKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7851, @ClientKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7852, @ClientKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7853, @ClientKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7854, @ClientKey, N''Is a Billable Client'', N''billableClient'', NULL, NULL, N''Is a Billable *[MediaPrint6]'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7855, @ClientKey, N''Client ID'', N''customerID'', NULL, NULL, N''Client ID. Required if Billable client is true'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7856, @ClientKey, N''Overhead'', N''overhead'', NULL, NULL, N''Overhead'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7857, @ClientKey, N''Is a Parent Company'', N''parentCompany'', NULL, NULL, N''Is a Parent Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7858, @ClientKey, N''Parent Company'', N''parentCompanyName'', NULL, NULL, N''Parent Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7859, @ClientKey, N''Downloaded'', N''clientDownloaded'', NULL, NULL, N''Downloaded'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7860, @ClientKey, N''Divisions'', N''divisions'', NULL, NULL, N''Divisions'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7861, @ClientKey, N''Products'', N''products'', NULL, NULL, N''Products'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7862, @ClientKey, N''Next Project Number'', N''nextProjectNum'', NULL, NULL, N''Next Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7863, @ClientKey, N''Next Campaign Number'', N''nextCampaignNum'', NULL, NULL, N''Next Campaign Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7864, @ClientKey, N''Default Sales Tax ID 1'', N''salesTaxID'', NULL, NULL, N''Default Sales Tax ID 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7865, @ClientKey, N''Default Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Default Sales Tax ID 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7866, @ClientKey, N''Default Sales GL Account Number'', N''defaultSalesAccount'', NULL, NULL, N''Default Sales GL Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7867, @ClientKey, N''Default AR Account Number'', N''defaultARAccount'', NULL, NULL, N''Default AR Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7868, @ClientKey, N''Invoice Template'', N''invoiceTemplate'', NULL, NULL, N''Invoice Template'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7869, @ClientKey, N''Layouts'', N''layout'', NULL, NULL, N''Default Invoice Layout'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7870, @ClientKey, N''Default Billing Method'', N''defaultBillingMethod'', NULL, NULL, N''Default Billing Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7871, @ClientKey, N''Expenses Not Included'', N''defaultExpensesNotIncluded'', NULL, NULL, N''Expenses Not Included'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7872, @ClientKey, N''Default Retainer'', N''defaultRetainer'', NULL, NULL, N''Default Retainer'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7873, @ClientKey, N''One Invoice Per'', N''oneInvoicePer'', NULL, NULL, N''One Invoice Per, possible values Project, Client, Parent Client, Division, Product, Campaign'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7874, @ClientKey, N''One Line Item Per'', N''defaultARLineFormat'', NULL, NULL, N''One Line Item Per'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7875, @ClientKey, N''Default Terms'', N''paymentTerms'', NULL, NULL, N''Default Terms'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7876, @ClientKey, N''Estimate Template'', N''estimateTemplate'', NULL, NULL, N''Estimate Template'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7877, @ClientKey, N''Card Holders Name'', N''cardHolderName'', NULL, NULL, N''Card Holders Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7878, @ClientKey, N''CC Number'', N''ccNumber'', NULL, NULL, N''CC Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7879, @ClientKey, N''CC Exp Month'', N''expMonth'', NULL, NULL, N''CC Exp Month'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7880, @ClientKey, N''CC Exp Year'', N''expYear'', NULL, NULL, N''CC Exp Year'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7881, @ClientKey, N''CC Verification Code'', N''cVV'', NULL, NULL, N''CC Verification Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7882, @ClientKey, N''Default Company GL'', N''glCompany'', NULL, NULL, N''Default Company GL'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7883, @ClientKey, N''Account Team'', N''defaultTeam'', NULL, NULL, N''Account Team'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7884, @ClientKey, N''Get Rate From'', N''getRateFrom'', NULL, NULL, N''Get Rate From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7885, @ClientKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7886, @ClientKey, N''Rate Sheet'', N''timeRateSheet'', NULL, NULL, N''Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7887, @ClientKey, N''Get Markup From'', N''getMarkupFrom'', NULL, NULL, N''Get Markup From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7888, @ClientKey, N''Markup Pct'', N''itemMarkup'', NULL, NULL, N''Markup Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7889, @ClientKey, N''IO Commission Pct'', N''ioCommission'', NULL, NULL, N''IO Commission Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7890, @ClientKey, N''BC Commission Pct'', N''bcCommission'', NULL, NULL, N''BC Commission Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7891, @ClientKey, N''Default Item Rate Sheet'', N''itemRateSheet'', NULL, NULL, N''Default Item Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7892, @ClientKey, N''Prebill Insertions At'', N''ioBillAt'', NULL, NULL, N''Prebill Insertions At'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7893, @ClientKey, N''Prebill Broadcast At'', N''bcBillAt'', NULL, NULL, N''Prebill Broadcast At'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7894, @ClientKey, N''Default Office'', N''office'', NULL, NULL, N''Default Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7895, @ClientKey, N''Lock Get Labor Rate'', N''lockLaborRate'', NULL, NULL, N''Lock Get Labor Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7896, @ClientKey, N''Lock Get Markup From'', N''lockMarkupFrom'', NULL, NULL, N''Lock Get Markup From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7897, @ClientKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7898, @ClientKey, N''Title Rate Sheet'', N''titleRateSheet'', NULL, NULL, N''Title Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71001, @ClientKey, N''Billing Address Name'', N''billingAddressName'', NULL, NULL, N''Billing Address Name.  Used to populate the Billing Address on the Billing Details'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71002, @ClientKey, N''Email Invoices To'', N''billingEmailContact'', NULL, NULL, N''Email Invoices To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71003, @ClientKey, N''Billing Name'', N''billingName'', NULL, NULL, N''Billing Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71004, @ClientKey, N''EIN Number'', N''einNumber'', NULL, NULL, N''EIN'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71005, @ClientKey, N''Estimate Labor Taxable'', N''estimateLaborTaxable'', NULL, NULL, N''Estimate Labor Taxable'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71006, @ClientKey, N''Project Manager'', N''projectManager'', NULL, NULL, N''Project Manager'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.ShowProjectManager == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71007, @ClientKey, N''One Line Item Per (Fixed Fee)'', N''defaultFFLineFormat'', NULL, NULL, N''One Line Item Per (Fixed Fee)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71008, @ClientKey, N''CC Receipts'', N''ccReceipts'', NULL, NULL, N''Allow Credit Card Payments Online'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71009, @ClientKey, N''ACH Receipts'', N''achReceipts'', NULL, NULL, N''Allow ACH Payments Online'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71010, @ClientKey, N''Primary Contact First Name'', N''primaryContactFirstName'', NULL, NULL, N''Primary Contact First Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71011, @ClientKey, N''Primary Contact Last Name'', N''primaryContactLastName'', NULL, NULL, N''Primary Contact Last Namee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71012, @ClientKey, N''Primary Contact Email'', N''primaryContactEmail'', NULL, NULL, N''Primary Contact Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71013, @ClientKey, N''Billing Contact First Name'', N''billingContactFirstName'', NULL, NULL, N''Billing Contact First Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71014, @ClientKey, N''Billing Contact Last Name'', N''billingContactLastName'', NULL, NULL, N''Billing Contact Last Namee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71015, @ClientKey, N''Billing Contact Email'', N''billingContactEmail'', NULL, NULL, N''Billing Contact Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71016, @ClientKey, N''Project Color'', N''projectColor'', NULL, NULL, N''Project Color in hex format (#FF0000)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71017, @ClientKey, N''Company Address Name'', N''addressName'', NULL, NULL, N''Company Address Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Companies
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7899, @CompanyKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 1, NULL, 2, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7900, @CompanyKey, N''Primary Contact'', N''primaryContact'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7901, @CompanyKey, N''Source'', N''companySource'', NULL, NULL, N''Source'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7902, @CompanyKey, N''Company Type'', N''companyType'', NULL, NULL, N''Company Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7903, @CompanyKey, N''Main Phone'', N''phone'', NULL, NULL, N''Main Phone'', NULL, NULL, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7904, @CompanyKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7905, @CompanyKey, N''WebSite'', N''website'', NULL, NULL, N''WebSite'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7906, @CompanyKey, N''Company Address 1'', N''address1'', NULL, NULL, N''Company Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7907, @CompanyKey, N''Company Address 2'', N''address2'', NULL, NULL, N''Company Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7908, @CompanyKey, N''Company Address 3'', N''address3'', NULL, NULL, N''Company Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7909, @CompanyKey, N''Company City'', N''city'', NULL, NULL, N''Company City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7910, @CompanyKey, N''Company State'', N''state'', NULL, NULL, N''Company State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7911, @CompanyKey, N''Company Postal Code'', N''postalCode'', NULL, NULL, N''Company Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7912, @CompanyKey, N''Company Country'', N''country'', NULL, NULL, N''Company Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7913, @CompanyKey, N''Company Owner'', N''companyOwner'', NULL, NULL, N''Company Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7914, @CompanyKey, N''Account Manager'', N''accountManager'', NULL, NULL, N''Account Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7915, @CompanyKey, N''Sales Person'', N''salesPerson'', NULL, NULL, N''Sales Person'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7916, @CompanyKey, N''Folder'', N''folderName'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7917, @CompanyKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7918, @CompanyKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7919, @CompanyKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7920, @CompanyKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7921, @CompanyKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7922, @CompanyKey, N''Title Rate Sheet'', N''titleRateSheet'', NULL, NULL, N''Title Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3701, @CompanyKey, N''Project Manager'', N''projectManager'', NULL, NULL, N''Project Manager'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.ShowProjectManager == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3702, @CompanyKey, N''Primary Contact First Name'', N''primaryContactFirstName'', NULL, NULL, N''Primary Contact First Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3703, @CompanyKey, N''Primary Contact Last Name'', N''primaryContactLastName'', NULL, NULL, N''Primary Contact Last Namee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3704, @CompanyKey, N''Primary Contact Email'', N''primaryContactEmail'', NULL, NULL, N''Primary Contact Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3705, @CompanyKey, N''Company Address Name'', N''addressName'', NULL, NULL, N''Company Address Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Company Type
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7923, 44, N''Company Type Name'', N''companyTypeName'', NULL, N''CompanyTypeName'', N''Company Type Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
--Contacts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7924, @ContactKey, N''Salutation'', N''salutation'', NULL, NULL, N''Salutation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7925, @ContactKey, N''First Name'', N''firstName'', NULL, NULL, N''First Name'', NULL, 1, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7926, @ContactKey, N''Middle Name'', N''middleName'', NULL, NULL, N''Middle Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7927, @ContactKey, N''Last Name'', N''lastName'', NULL, NULL, N''Last Name'', NULL, 1, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7928, @ContactKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7929, @ContactKey, N''Linked Company'', N''linkedCompanyName'', NULL, NULL, N''Linked Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7930, @ContactKey, N''Company Name'', N''userCompanyName'', NULL, NULL, N''Company Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7931, @ContactKey, N''Primary Contact'', N''primaryContact'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7932, @ContactKey, N''Twitter ID'', N''twitterID'', NULL, NULL, N''Twitter ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7933, @ContactKey, N''LinkedIn URL'', N''linkedInUrl'', NULL, NULL, N''LinkedIn URL'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7934, @ContactKey, N''Phone 1'', N''phone1'', NULL, NULL, N''Phone 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7935, @ContactKey, N''Phone 2'', N''phone2'', NULL, NULL, N''Phone 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7936, @ContactKey, N''Cell'', N''cell'', NULL, NULL, N''Cell'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7937, @ContactKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7938, @ContactKey, N''Phone Other'', N''pager'', NULL, NULL, N''Phone Other'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7939, @ContactKey, N''Email Address'', N''email'', NULL, NULL, N''Email Address'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7940, @ContactKey, N''Personal Work Address 1'', N''workAddress1'', NULL, NULL, N''Personal Work Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7941, @ContactKey, N''Personal Work Address 2'', N''workAddress2'', NULL, NULL, N''Personal Work Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7942, @ContactKey, N''Personal Work Address 3'', N''workAddress3'', NULL, NULL, N''Personal Work Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7943, @ContactKey, N''Personal Work City'', N''workCity'', NULL, NULL, N''Personal Work City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7944, @ContactKey, N''Personal Work State'', N''workState'', NULL, NULL, N''Personal Work State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7945, @ContactKey, N''Personal Work Postal Code'', N''workPostalCode'', NULL, NULL, N''Personal Work Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7946, @ContactKey, N''Personal Work Country'', N''workCountry'', NULL, NULL, N''Personal Work Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7947, @ContactKey, N''Home Address 1'', N''homeAddress1'', NULL, NULL, N''Home Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7948, @ContactKey, N''Home Address 2'', N''homeAddress2'', NULL, NULL, N''Home Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7949, @ContactKey, N''Home Address 3'', N''homeAddress3'', NULL, NULL, N''Home Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7950, @ContactKey, N''Home City'', N''homeCity'', NULL, NULL, N''Home City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7951, @ContactKey, N''Home State'', N''homeState'', NULL, NULL, N''Home State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7952, @ContactKey, N''Home Postal Code'', N''homePostalCode'', NULL, NULL, N''Home Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7953, @ContactKey, N''Home Country'', N''homeCountry'', NULL, NULL, N''Home Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7954, @ContactKey, N''Other Address 1'', N''otherAddress1'', NULL, NULL, N''Other Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7955, @ContactKey, N''Other Address 2'', N''otherAddress2'', NULL, NULL, N''Other Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7956, @ContactKey, N''Other Address 3'', N''otherAddress3'', NULL, NULL, N''Other Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7957, @ContactKey, N''Other City'', N''otherCity'', NULL, NULL, N''Other City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7958, @ContactKey, N''Other State'', N''otherState'', NULL, NULL, N''Other State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7959, @ContactKey, N''Other Postal Code'', N''otherPostalCode'', NULL, NULL, N''Other Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7960, @ContactKey, N''Other Country'', N''otherCountry'', NULL, NULL, N''Other Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7961, @ContactKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7962, @ContactKey, N''Date of Hire'', N''dateHired'', NULL, NULL, N''Date of Hire'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7963, @ContactKey, N''Department'', N''department'', NULL, NULL, N''Department'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7964, @ContactKey, N''Reports To'', N''reportsToName'', NULL, NULL, N''Reports To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7965, @ContactKey, N''Assistant'', N''assistant'', NULL, NULL, N''Assistant'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7966, @ContactKey, N''Assistant Phone'', N''assistantPhone'', NULL, NULL, N''Assistant Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7967, @ContactKey, N''Assistant Email'', N''assistantEmail'', NULL, NULL, N''Assistant Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7968, @ContactKey, N''Birthday'', N''birthday'', NULL, NULL, N''Birthday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7969, @ContactKey, N''Spouse/Partner'', N''spouseName'', NULL, NULL, N''Spouse/Partner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7970, @ContactKey, N''Children'', N''children'', NULL, NULL, N''Children'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7971, @ContactKey, N''Anniversary'', N''anniversary'', NULL, NULL, N''Anniversary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7972, @ContactKey, N''Hobbies'', N''hobbies'', NULL, NULL, N''Hobbies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7973, @ContactKey, N''Marketing Groups'', N''marketingLists'', NULL, NULL, N''Marketing Groups'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7974, @ContactKey, N''Preferred Contact Method'', N''contactMethod'', NULL, NULL, N''Preferred Contact Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7975, @ContactKey, N''Do Not Call'', N''doNotCall'', NULL, NULL, N''Do Not Call'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7976, @ContactKey, N''Do Not Email'', N''doNotEmail'', NULL, NULL, N''Do Not Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7977, @ContactKey, N''Do Not Mail'', N''doNotMail'', NULL, NULL, N''Do Not Mail'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7978, @ContactKey, N''Do Not Fax'', N''doNotFax'', NULL, NULL, N''Do Not Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7979, @ContactKey, N''Default GL Company'', N''glCompany'', NULL, NULL, N''Default GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7980, @ContactKey, N''Services'', N''services'', NULL, NULL, N''Services'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7981, @ContactKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7982, @ContactKey, N''Billing Title ID'', N''titleID'', NULL, NULL, N''Billing Title ID'', NULL, NULL, N''BillingTitleID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7983, @ContactKey, N''Invoice Email Name'', N''invoiceEmailName'', NULL, NULL, N''Invoice Email Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7984, @ContactKey, N''Invoice Email Address'', N''invoiceEmailAddress'', NULL, NULL, N''Invoice Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7985, @ContactKey, N''System ID'', N''systemID'', NULL, NULL, N''System ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7986, @ContactKey, N''Contact Owner'', N''contactOwner'', NULL, NULL, N''Contact Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7987, @ContactKey, N''Folder'', N''folder'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7988, @ContactKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7989, @ContactKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7990, @ContactKey, N''Password'', N''newPassword'', NULL, NULL, N''Password'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7991, @ContactKey, N''Security Group'', N''securityGroup'', NULL, NULL, N''Security Group'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7992, @ContactKey, N''Free Login'', N''clientVendorLogin'', NULL, NULL, N''Free Login'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7993, @ContactKey, N''Timezone Index'', N''timeZoneIndex'', NULL, NULL, N''Timezone Index'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7994, @ContactKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7995, @ContactKey, N''Role'', N''userRole'', NULL, NULL, N''Role'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyroles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7996, @ContactKey, N''Skills'', N''skills'', NULL, NULL, N''Skills'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyskills'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (100, @ContactKey, N''Division'', N''clientDivision'', NULL, NULL, N''Division'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (101, @ContactKey, N''Product'', N''clientProduct'', NULL, NULL, N''Product'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (102, @ContactKey, N''Invoice Exclude Attachments'', N''invoiceExcludeAttachment'', NULL, NULL, N''Invoice Exclude Attachments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (103, @ContactKey, N''Do Not Use SSO Auth'', N''doNotUseSSO'', NULL, NULL, N''Do Not Use SAML/SSO Authentication'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Credit Card Charges
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7997, @CreditCardCharge, N''Credit Card Account'', N''aPAccountNumber'', NULL, NULL, N''Credit Card Account'', N''header'', 1, N''Credit Card Account'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7998, @CreditCardCharge, N''Reference Number'', N''invoiceNumber'', NULL, NULL, N''Reference Number'', N''header'', NULL, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7999, @CreditCardCharge, N''Charge Date'', N''invoiceDate'', NULL, NULL, N''Charge Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8000, @CreditCardCharge, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8001, @CreditCardCharge, N''Purchased By'', N''boughtBy'', NULL, NULL, N''Purchased By'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8002, @CreditCardCharge, N''Purchased From'', N''boughtFromID'', NULL, NULL, N''Purchased From'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8003, @CreditCardCharge, N''Approved By'', N''approvedBy'', NULL, NULL, N''Approved By'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8004, @CreditCardCharge, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8007, @CreditCardCharge, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8008, @CreditCardCharge, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8009, @CreditCardCharge, N''Overhead Charge'', N''voucherType'', NULL, NULL, N''Overhead Charge'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8010, @CreditCardCharge, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8011, @CreditCardCharge, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8012, @CreditCardCharge, N''Office'', N''officeID'', NULL, NULL, N''Office. Required if office is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition],[SystemSettingFieldName]) VALUES (8013, @CreditCardCharge, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if item is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL, N''RequireItems'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8014, @CreditCardCharge, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8015, @CreditCardCharge, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8016, @CreditCardCharge, N''Unit Description'', N''unitDescription'', NULL, NULL, N''Unit Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8017, @CreditCardCharge, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8018, @CreditCardCharge, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8019, @CreditCardCharge, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8020, @CreditCardCharge, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8021, @CreditCardCharge, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8022, @CreditCardCharge, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8023, @CreditCardCharge, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8024, @CreditCardCharge, N''Expense Account'', N''expenseAccountNumber'', NULL, NULL, N''Expense Account. Required if GL Acounts are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8025, @CreditCardCharge, N''Department'', N''departmentID'', NULL, NULL, N''Department. Required if Departments are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8026, @CreditCardCharge, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8027, @CreditCardCharge, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57002, @CreditCardCharge, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57003, @CreditCardCharge, N''Sales Tax 2 ID'', N''salesTax2ID'', NULL, NULL, N''Sales Tax 2 ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57004, @CreditCardCharge, N''Sales Tax Amount (line)'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57005, @CreditCardCharge, N''Sales Tax Amount 2 (line)'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2 (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8028, @CreditCardCharge, N''Taxable (line)'', N''taxable'', NULL, NULL, N''Taxable (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8029, @CreditCardCharge, N''Taxable 2 (line)'', N''taxable2'', NULL, NULL, N''Taxable 2 (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8030, @CreditCardCharge, N''Line Description'', N''shortDescription'', NULL, NULL, N''Line Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8031, @CreditCardCharge, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8032, @CreditCardCharge, N''Project Exchange Rate (Line)'', N''pExchangeRateLine'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8033, @CreditCardCharge, N''Class ID'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'',  N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57001, @CreditCardCharge, N''Exclude from 1099'', N''exclude1099'', NULL, NULL, N''Exclude from 1099 Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL,NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57006, @CreditCardCharge, N''Class ID (Line)'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'',  N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57007, @CreditCardCharge, N''Voucher Invoice Number (Line)'', N''voucherInvoiceNumber'', NULL, NULL, N''Voucher Invoice Number (Line)'',  N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57008, @CreditCardCharge, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57009, @CreditCardCharge, N''Vendor ID (Line)'', N''vendorID'', NULL, NULL, N''Vendor ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57010, @CreditCardCharge, N''Markup From Project (Line)'', N''markupFromProject'', NULL, NULL, N''Markup from Project (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57011, @CreditCardCharge, N''Target GL Company (Line)'', N''targetGLCompanyID'', NULL, NULL, N''Target GL Copmpany ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57012, @CreditCardCharge, N''Office (Line)'', N''officeID'', NULL, NULL, N''Office (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57013, @CreditCardCharge, N''Amount to Bill'', N''amountToBill'', NULL, NULL, N''Amount to Bill'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57014, @CreditCardCharge, N''GL Company Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57015, @CreditCardCharge, N''Invoice Exchange Rate'', N''invoiceExchangeRate'', NULL, NULL, N''Invoice Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57016, @CreditCardCharge, N''Net Cost (HC)'', N''hcTotalCost'', NULL, NULL, N''Net Cost (Home Currency)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57017, @CreditCardCharge, N''Project Currency ID'', N''pCurrencyID'', NULL, NULL, N''Project Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57018, @CreditCardCharge, N''Project Currency ID (Line)'', N''pCurrencyLineID'', NULL, NULL, N''Project Currency ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57019, @CreditCardCharge, N''Project Exchange Rate'', N''projectExchangeRate'', NULL, NULL, N''Project Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57020, @CreditCardCharge, N''Project Net Cost'', N''pTotalCost'', NULL, NULL, N''Project Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57021, @CreditCardCharge, N''Invoice Currency ID'', N''currencyID'', NULL, NULL, N''Invoice Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57022, @CreditCardCharge, N''Comment'', N''comment'', NULL, NULL, N''Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)

--Credit Card Connector.. aka credit card transactions
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8034, @CreditCardConnector, N''GL Account Number'', N''glAccountNumber'', NULL, NULL, N''GL Account Number'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8035, @CreditCardConnector, N''Amount'', N''amount'', NULL, NULL, N''Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8037, @CreditCardConnector, N''FITID'', N''fITID'', NULL, NULL, N''FITID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8038, @CreditCardConnector, N''Payee Name'', N''payeeName'', NULL, NULL, N''Payee Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8039, @CreditCardConnector, N''Memo'', N''memo'', NULL, NULL, N''Memo'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8040, @CreditCardConnector, N''Date'', N''transactionPostedDate'', NULL, NULL, N''Date Posted'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8041, @CreditCardConnector, N''Transaction Type'', N''transactionType'', NULL, NULL, N''Transaction Type'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6201, @CreditCardConnector, N''Charged By'', N''chargedBy'', NULL, NULL, N''Charged By'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6202, @CreditCardConnector, N''Expense Account Number'', N''expenseAccount'', NULL, NULL, N''Expense Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6203, @CreditCardConnector, N''Item ID'', N''itemKey'', NULL, NULL, N''Item ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6204, @CreditCardConnector, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', NUll, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')

-- Currency Rates
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8042, @CurrencyRateKey, N''GL Company'', N''glCompanyName'', NULL, N''GLCompanyName'', N''GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8043, @CurrencyRateKey, N''Effective Date'', N''effectiveDate'', NULL, N''EffectiveDate'', N''Effective Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8044, @CurrencyRateKey, N''Exchange Rate'', N''exchangeRate'', NULL, N''ExchangeRate'', N''Exchange Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8045, @CurrencyRateKey, N''Currency'', N''currencyID'', NULL, N''CurrencyID'', N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (63001, @CurrencyRateKey, N''ToCurrency'', N''toCurrencyID'', NULL, N''ToCurrencyID'', N''ToCurrency'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Deliverables
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80001, @DeliverableKey, N''Deliverable ID'', N''deliverableID'', NULL, NULL, N''Deliverable ID'', NULL, NULL, NULL, 1, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80002, @DeliverableKey, N''Deliverable Name'', N''deliverableName'', NULL, NULL, N''Deliverable Name'', NULL, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80003, @DeliverableKey, N''Deliverable Status'', N''deliverableStatus'', NULL, NULL, N''Deliverable Status'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80004, @DeliverableKey, N''Deliverable Type'', N''deliverableType'', NULL, NULL, N''Deliverable Type'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80005, @DeliverableKey, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80006, @DeliverableKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80007, @DeliverableKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80008, @DeliverableKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80009, @DeliverableKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80010, @DeliverableKey, N''Approved Date'', N''approvedDate'', NULL, NULL, N''Approved Date'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80011, @DeliverableKey, N''Owner ID'', N''ownerID'', NULL, NULL, N''Owner User ID'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Department
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8046, 28, N''Department Name'', N''departmentName'', NULL, N''DepartmentName'', N''Department Name'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8047, 28, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Conversation
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11601, @ConversationKey, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11602, @ConversationKey, N''Activity Date'', N''activityDate'', NULL, NULL, N''Activity Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11603, @ConversationKey, N''Completed'', N''completed'', NULL, NULL, N''Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11604, @ConversationKey, N''Date Completed'', N''dateCompleted'', NULL, NULL, N''Date Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11605, @ConversationKey, N''Assigned To'', N''assignedUser'', NULL, NULL, N''Assigned To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11606, @ConversationKey, N''Private'', N''private'', NULL, NULL, N''Private'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11607, @ConversationKey, N''Folder'', N''cMFolderKey'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11608, @ConversationKey, N''Activity Type'', N''activityType'', NULL, NULL, N''Activity Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11609, @ConversationKey, N''Notes'', N''notes'', NULL, NULL, N''Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11610, @ConversationKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11611, @ConversationKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11612, @ConversationKey, N''Contact'', N''linkedContact'', NULL, NULL, N''Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11613, @ConversationKey, N''Company'', N''linkedCompany'', NULL, NULL, N''Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11614, @ConversationKey, N''Opportunity'', N''linkedLead'', NULL, NULL, N''Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11615, @ConversationKey, N''Lead'', N''linkedUserLead'', NULL, NULL, N''Lead'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11616, @ConversationKey, N''Start Time'', N''startTime'', NULL, NULL, N''Start Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11617, @ConversationKey, N''End Time'', N''endTime'', NULL, NULL, N''End Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11618, @ConversationKey, N''Reminder (minutes)'', N''reminderMinutes'', NULL, NULL, N''Reminder (minutes)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11619, @ConversationKey, N''Priority'', N''priority'', NULL, NULL, N''Priority'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11620, @ConversationKey, N''Originator'', N''originatorUserKey'', NULL, NULL, N''Originator'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11621, @ConversationKey, N''Visible To Client'', N''visibleToClient'', NULL, NULL, N''Visible To Client'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11622, @ConversationKey, N''View As'', N''activityEntity'', NULL, NULL, N''View As'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11623, @ConversationKey, N''Outcome'', N''outcome'', NULL, NULL, N''Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11624, @ConversationKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company, Required if GL Company is required '', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')

-- Employee
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8048, @EmployeeKey, N''First Name'', N''firstName'', NULL, NULL, N''First Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8049, @EmployeeKey, N''Middle Name'', N''middleName'', NULL, NULL, N''Middle Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8050, @EmployeeKey, N''Last Name'', N''lastName'', NULL, NULL, N''Last Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8051, @EmployeeKey, N''Salutation'', N''salutation'', NULL, NULL, N''Salutation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8052, @EmployeeKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8053, @EmployeeKey, N''Office'', N''office'', NULL, NULL, N''Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8054, @EmployeeKey, N''Department'', N''department'', NULL, NULL, N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8055, @EmployeeKey, N''Is Supervisor'', N''supervisor'', NULL, NULL, N''Is Supervisor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8056, @EmployeeKey, N''Timezone Index'', N''timeZoneIndex'', NULL, NULL, N''Timezone Index'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8057, @EmployeeKey, N''System ID'', N''systemID'', NULL, NULL, N''System ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8058, @EmployeeKey, N''Default Calendar Color'', N''defaultCalendarColor'', NULL, NULL, N''Default Calendar Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8059, @EmployeeKey, N''Phone'', N''phone'', NULL, NULL, N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8060, @EmployeeKey, N''Second Phone'', N''phone2'', NULL, NULL, N''Second Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8061, @EmployeeKey, N''Cell Phone'', N''cell'', NULL, NULL, N''Cell Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8062, @EmployeeKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8063, @EmployeeKey, N''Other'', N''pager'', NULL, NULL, N''Other'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8064, @EmployeeKey, N''Email'', N''email'', NULL, NULL, N''Email'', NULL, NULL, NULL, 2, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8065, @EmployeeKey, N''Hourly Cost'', N''hourlyCost'', NULL, NULL, N''Hourly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8066, @EmployeeKey, N''Monthly Cost'', N''monthlyCost'', NULL, NULL, N''Monthly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8067, @EmployeeKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8068, @EmployeeKey, N''Time Approver'', N''timeApprover'', NULL, NULL, N''Time Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810029, @EmployeeKey, N''Calendar Approver'', N''calendarApprover'', NULL, NULL, N''Meeting Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8069, @EmployeeKey, N''Expense Approver'', N''expenseApprover'', NULL, NULL, N''Expense Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8070, @EmployeeKey, N''Credit Card Approver'', N''creditCardApprover'', NULL, NULL, N''Credit Card Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8071, @EmployeeKey, N''Backup Approver'', N''backupApprover'', NULL, NULL, N''Backup Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8072, @EmployeeKey, N''Time Sheet Required'', N''timesheetRequired'', NULL, NULL, N''Time Sheet Required'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8073, @EmployeeKey, N''Require Times on Time Sheet'', N''requireUserTimeDetails'', NULL, NULL, N''Require Times on Time Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8074, @EmployeeKey, N''Require Minimum Hours'', N''requireMinimumHours'', NULL, NULL, N''Require Minimum Hours'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8075, @EmployeeKey, N''Minimum Hours Monday'', N''hoursMonday'', NULL, NULL, N''Minimum Hours Monday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8076, @EmployeeKey, N''Minimum Hours Tuesday'', N''hoursTuesday'', NULL, NULL, N''Minimum Hours Tuesday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8077, @EmployeeKey, N''Minimum Hours Wednesday'', N''hoursWednesday'', NULL, NULL, N''Minimum Hours Wednesday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8078, @EmployeeKey, N''Minimum Hours Thursday'', N''hoursThursday'', NULL, NULL, N''Minimum Hours Thursday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8079, @EmployeeKey, N''Minimum Hours Friday'', N''hoursFriday'', NULL, NULL, N''Minimum Hours Friday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8080, @EmployeeKey, N''Minimum Hours Saturday'', N''hoursSaturday'', NULL, NULL, N''Minimum Hours Saturday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8081, @EmployeeKey, N''Minimum Hours Sunday'', N''hoursSunday'', NULL, NULL, N''Minimum Hours Sunday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8082, @EmployeeKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8083, @EmployeeKey, N''Password'', N''password'', NULL, NULL, N''Password'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8084, @EmployeeKey, N''Security Group'', N''securityGroup'', NULL, NULL, N''Security Group'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8085, @EmployeeKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8086, @EmployeeKey, N''Locked'', N''locked'', NULL, NULL, N''Locked'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8087, @EmployeeKey, N''Subscribe to Diary'', N''subscribeDiary'', NULL, NULL, N''Subscribe to Diary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8088, @EmployeeKey, N''Subscribe to ToDo'', N''subscribeToDo'', NULL, NULL, N''Subscribe to ToDo'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8089, @EmployeeKey, N''Default Reviewer'', N''deliverableReviewer'', NULL, NULL, N''Default Reviewer'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8090, @EmployeeKey, N''Default Notify'', N''deliverableNotify'', NULL, NULL, N''Default Notify'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8091, @EmployeeKey, N''Date Hired'', N''dateHired'', NULL, NULL, N''Date Hired'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8092, @EmployeeKey, N''Anniversary'', N''anniversary'', NULL, NULL, N''Anniversary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8093, @EmployeeKey, N''Birthday'', N''birthday'', NULL, NULL, N''Birthday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8094, @EmployeeKey, N''Children'', N''children'', NULL, NULL, N''Children'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8095, @EmployeeKey, N''Spouse/Partner'', N''spouseName'', NULL, NULL, N''Spouse/Partner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8096, @EmployeeKey, N''Personal Work Address 1'', N''personalWorkAddress1'', NULL, NULL, N''Personal Work Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8097, @EmployeeKey, N''Personal Work Address 2'', N''personalWorkAddress2'', NULL, NULL, N''Personal Work Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8098, @EmployeeKey, N''Personal Work Address 3'', N''personalWorkAddress3'', NULL, NULL, N''Personal Work Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8099, @EmployeeKey, N''Personal Work City'', N''personalWorkCity'', NULL, NULL, N''Personal Work City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8100, @EmployeeKey, N''Personal Work State'', N''personalWorkState'', NULL, NULL, N''Personal Work State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8101, @EmployeeKey, N''Personal Work Postal Code'', N''personalWorkPostalCode'', NULL, NULL, N''Personal Work Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8102, @EmployeeKey, N''Personal Work Country'', N''personalWorkCountry'', NULL, NULL, N''Personal Work Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8103, @EmployeeKey, N''Home Address 1'', N''homeAddress1'', NULL, NULL, N''Home Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8104, @EmployeeKey, N''Home Address 2'', N''homeAddress2'', NULL, NULL, N''Home Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8105, @EmployeeKey, N''Home Address 3'', N''homeAddress3'', NULL, NULL, N''Home Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8106, @EmployeeKey, N''Home City'', N''homeCity'', NULL, NULL, N''Home City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8107, @EmployeeKey, N''Home State'', N''homeState'', NULL, NULL, N''Home State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8108, @EmployeeKey, N''Home Postal Code'', N''homePostalCode'', NULL, NULL, N''Home Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8109, @EmployeeKey, N''Home Country'', N''homeCountry'', NULL, NULL, N''Home Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8110, @EmployeeKey, N''Other Address 1'', N''otherAddress1'', NULL, NULL, N''Other Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8111, @EmployeeKey, N''Other Address 2'', N''otherAddress2'', NULL, NULL, N''Other Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8112, @EmployeeKey, N''Other Address 3'', N''otherAddress3'', NULL, NULL, N''Other Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8113, @EmployeeKey, N''Other City'', N''otherCity'', NULL, NULL, N''Other City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8114, @EmployeeKey, N''Other State'', N''otherState'', NULL, NULL, N''Other State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8115, @EmployeeKey, N''Other Postal Code'', N''otherPostalCode'', NULL, NULL, N''Other Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8116, @EmployeeKey, N''Other Country'', N''otherCountry'', NULL, NULL, N''Other Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8117, @EmployeeKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8118, @EmployeeKey, N''PO Order Limit'', N''poLimit'', NULL, NULL, N''PO Order Limit'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8119, @EmployeeKey, N''Insertion Order Limit'', N''ioLimit'', NULL, NULL, N''Insertion Order Limit'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8120, @EmployeeKey, N''Broadcast Order Limit'', N''bcLimit'', NULL, NULL, N''Broadcast Order Limit'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8121, @EmployeeKey, N''Default GL Company'', N''defaultGLCompany'', NULL, NULL, N''Default GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8122, @EmployeeKey, N''Services'', N''services'', NULL, NULL, N''Services, use ; to seperate multiple'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8123, @EmployeeKey, N''Default Service'', N''defaultService'', NULL, NULL, N''Default Service'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8124, @EmployeeKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8125, @EmployeeKey, N''Billing Title ID'', N''billingTitleID'', NULL, NULL, N''Billing Title ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3001, @EmployeeKey, N''Supervisor Name'', N''supervisorName'', NULL, NULL, N''Supervisor Name aka My Supervisor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3002, @EmployeeKey, N''Vendor Cost'', N''vendorCost'', NULL, NULL, N''Vendor Cost if user is a vendor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3003, @EmployeeKey, N''Require Min Hours Per Week'', N''requireMinHoursPerWeek'', NULL, NULL, N''Require Min Hours Per Week'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3004, @EmployeeKey, N''Min Hours Per Week'', N''minHoursPerWeek'', NULL, NULL, N''Minimum Hours Per Week'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3005, @EmployeeKey, N''Do Not Use SSO Auth'', N''doNotUseSSO'', NULL, NULL, N''Do Not Use SAML/SSO Authentication'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810026, @EmployeeKey, N''Overtime Cost'', N''overtimeCost'', NULL, NULL, N''Overtime Cost'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.TrackOvertime == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810027, @EmployeeKey, N''Overtime Vendor Cost'', N''overtimeVendorCost'', NULL, NULL, N''Overtime Vendor Cost'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.TrackOvertime == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810028, @EmployeeKey, N''Contractor'', N''contractor'', NULL, NULL, N''Contractor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Estimates
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8126, @EstimateKey, N''Estimate Number'', N''estimateNumber'', NULL, NULL, N''Estimate Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8127, @EstimateKey, N''Estimate Name'', N''estimateName'', NULL, NULL, N''Estimate Name'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8128, @EstimateKey, N''Estimate Type'', N''estType'', NULL, NULL, N''Estimate Type'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8129, @EstimateKey, N''Revision'', N''revision'', NULL, NULL, N''Revision'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8130, @EstimateKey, N''Change Order'', N''changeOrder'', NULL, NULL, N''Change Order'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8131, @EstimateKey, N''Contact Name'', N''contactName'', NULL, NULL, N''Contact Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8132, @EstimateKey, N''Project Number'', N''projectKey'', NULL, NULL, N''Project Number'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8133, @EstimateKey, N''Estimate Date'', N''estimateDate'', NULL, NULL, N''Estimate Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8134, @EstimateKey, N''Estimate Description'', N''estDescription'', NULL, NULL, N''Estimate Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8135, @EstimateKey, N''Estimate Template'', N''estimateTemplateName'', NULL, NULL, N''Estimate Template'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8136, @EstimateKey, N''User Defined 1'', N''userDefined1'', NULL, NULL, N''User Defined 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8137, @EstimateKey, N''User Defined 2'', N''userDefined2'', NULL, NULL, N''User Defined 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8138, @EstimateKey, N''User Defined 3'', N''userDefined3'', NULL, NULL, N''User Defined 3'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8139, @EstimateKey, N''User Defined 4'', N''userDefined4'', NULL, NULL, N''User Defined 4'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8140, @EstimateKey, N''User Defined 5'', N''userDefined5'', NULL, NULL, N''User Defined 5'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8141, @EstimateKey, N''User Defined 6'', N''userDefined6'', NULL, NULL, N''User Defined 6'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8142, @EstimateKey, N''User Defined 7'', N''userDefined7'', NULL, NULL, N''User Defined 7'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8143, @EstimateKey, N''User Defined 8'', N''userDefined8'', NULL, NULL, N''User Defined 8'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8144, @EstimateKey, N''User Defined 9'', N''userDefined9'', NULL, NULL, N''User Defined 9'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8145, @EstimateKey, N''User Defined 10'', N''userDefined10'', NULL, NULL, N''User Defined 10'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8146, @EstimateKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8147, @EstimateKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8148, @EstimateKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8149, @EstimateKey, N''Approver'', N''internalApprover'', NULL, NULL, N''Approver'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8150, @EstimateKey, N''Internal Comment'', N''internalComments'', NULL, NULL, N''Internal Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8151, @EstimateKey, N''Approval Date'', N''approvalDate'', NULL, NULL, N''Approval Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8152, @EstimateKey, N''Layout Name'', N''layoutKey'', NULL, NULL, N''Layout Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8153, @EstimateKey, N''Labor Taxable'', N''laborTaxable'', NULL, NULL, N''Labor Taxable'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8154, @EstimateKey, N''Contingency'', N''contingency'', NULL, NULL, N''Contingency'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8155, @EstimateKey, N''Line Type'', N''lineType'', NULL, NULL, N''Line Type'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8156, @EstimateKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8157, @EstimateKey, N''Service Code'', N''serviceCode'', NULL, NULL, N''Service Code. Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8158, @EstimateKey, N''Person'', N''userKey'', NULL, NULL, N''Person'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8159, @EstimateKey, N''Hours'', N''hours'', NULL, NULL, N''Hours'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8160, @EstimateKey, N''Labor Net'', N''laborNet'', NULL, NULL, N''Labor Net'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8161, @EstimateKey, N''Labor Gross'', N''laborGross'', NULL, NULL, N''Labor Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8162, @EstimateKey, N''Labor Rate Net'', N''laborRateNet'', NULL, NULL, N''Labor Rate Net'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8163, @EstimateKey, N''Labor Rate Gross'', N''laborRateGross'', NULL, NULL, N''Labor Rate Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8164, @EstimateKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8165, @EstimateKey, N''Expense Net'', N''expenseNet'', NULL, NULL, N''Expense Net'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8166, @EstimateKey, N''Expense Gross'', N''expenseGross'', NULL, NULL, N''Expense Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8167, @EstimateKey, N''Item ID (Expense)'', N''itemKey'', NULL, NULL, N''Item ID (Expense). Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8168, @EstimateKey, N''Vendor ID (Expense)'', N''vendorKey'', NULL, NULL, N''Vendor ID (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8169, @EstimateKey, N''Billable (Expense)'', N''billable'', NULL, NULL, N''Billable (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8170, @EstimateKey, N''Taxable (Expense)'', N''taxable'', NULL, NULL, N''Taxable (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8171, @EstimateKey, N''Taxable 2 (Expense)'', N''taxable2'', NULL, NULL, N''Taxable 2 (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8172, @EstimateKey, N''Quantity (Expense)'', N''quantity'', NULL, NULL, N''Quantity (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8173, @EstimateKey, N''Description (Expense)'', N''description'', NULL, NULL, N''Description (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8174, @EstimateKey, N''Unit Cost (Expense)'', N''unitCost'', NULL, NULL, N''Unit Cost (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8175, @EstimateKey, N''Unit Rate (Expense)'', N''unitRate'', NULL, NULL, N''Unit Rate (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8176, @EstimateKey, N''Unit Description (Expense)'', N''unitDescription'', NULL, NULL, N''Unit Description (Expense). Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8177, @EstimateKey, N''Display Order (Expense)'', N''displayOrder'', NULL, NULL, N''Display Order (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8178, @EstimateKey, N''Class ID (Expense)'', N''classKey'', NULL, NULL, N''Class ID (Expense). Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (16001, @EstimateKey, N''Long Description (Expense)'', N''longDescription'', NULL, NULL, N''Long Description (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (16002, @EstimateKey, N''Purchase Order Type'', N''purchaseOrderType'', NULL, NULL, N''Purchase Order Type)'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Expense Report Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8179, 4, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8180, 4, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8181, 4, N''Unit Cost'', N''unitCost'', NULL, N''UnitCost'', N''Unit Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8182, 4, N''Markup'', N''markup'', NULL, N''Markup'', N''Markup'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8183, 4, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8184, 4, N''Always use Unit Rate for Gross Amount'', N''useUnitRate'', NULL, N''UseUnitRate'', N''Always use Unit Rate for Gross Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8185, 4, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8186, 4, N''Use Description on Expense Report'', N''useDescription'', NULL, N''UseDescription'', N''Use Description on Expense Report'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8187, 4, N''Billing Item ID'', N''workTypeKey'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8188, 4, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8189, 4, N''Expense Account Number'', N''expenseAccountKey'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8190, 4, N''Sales Account Number'', N''salesAccountKey'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8191, 4, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8192, 4, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8193, 4, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8194, 4, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID'', NULL, NULL, N''ClassID. Required if Class is required'', NULL, 2, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (819400, 4, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')

-- Expense Reports
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8195, @ExpenseReportKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8196, @ExpenseReportKey, N''Report Number'', N''envelopeNumber'', NULL, NULL, N''Report Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8197, @ExpenseReportKey, N''Name'', N''userName'', NULL, NULL, N''Name'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8198, @ExpenseReportKey, N''Sales Tax 1'', N''salesTaxID'', NULL, NULL, N''Sales Tax 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8199, @ExpenseReportKey, N''Sales Tax 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8200, @ExpenseReportKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8201, @ExpenseReportKey, N''Date'', N''expenseDate'', NULL, NULL, N''Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8202, @ExpenseReportKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if Items are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8203, @ExpenseReportKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8204, @ExpenseReportKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8205, @ExpenseReportKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if tasks are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8206, @ExpenseReportKey, N''Paper Receipt'', N''paperReceipt'', NULL, NULL, N''Paper Receipt'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8207, @ExpenseReportKey, N''Quantity'', N''actualQty'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8208, @ExpenseReportKey, N''Unit Cost'', N''actualUnitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8209, @ExpenseReportKey, N''Net Cost'', N''actualCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8210, @ExpenseReportKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8211, @ExpenseReportKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8212, @ExpenseReportKey, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8213, @ExpenseReportKey, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8214, @ExpenseReportKey, N''Tax1 (Line)'', N''taxable'', NULL, NULL, N''Tax1 (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8215, @ExpenseReportKey, N''Tax2 (Line)'', N''taxable2'', NULL, NULL, N''Tax2 (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8216, @ExpenseReportKey, N''Sales Tax 1 Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax 1 Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8217, @ExpenseReportKey, N''Sales Tax 2 Amount'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax 2 Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8218, @ExpenseReportKey, N''Total Sales Tax Amount'', N''salesTaxAmount'', NULL, NULL, N''Total Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8219, @ExpenseReportKey, N''Comments (Line)'', N''commentsline'', NULL, NULL, N''Comments (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8220, @ExpenseReportKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8221, @ExpenseReportKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8222, @ExpenseReportKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (2201, @ExpenseReportKey, N''Approval Status'', N''approvalStatus'', NULL, NULL, N''Approval Staus - Unsubmitted, Submittted, Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- financial Budgets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8223, @GLBudget, N''Budget Name'', N''budgetName'', NULL, N''BudgetName'', N''Budget Name'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8224, @GLBudget, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8225, @GLBudget, N''GL Account'', N''glAccountNumber'', NULL, N''AccountNumber'', N''GL Account'', N''detail'', 1, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8226, @GLBudget, N''Client ID'', N''clientID'', NULL, N''ClientID'', N''Client ID'', N''detail'', NULL, N''CustomerID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8227, @GLBudget, N''GL Company'', N''glCompany'', NULL, N''GLCompanyID'', N''GL Company. Required if GL Company is required'', N''detail'', 2, N''GLCompanyName'', NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8228, @GLBudget, N''Office'', N''officeID'', NULL, N''OfficeID'', N''Office. Required if Office is required'', N''detail'', 2, N''OfficeName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8229, @GLBudget, N''Department'', N''department'', NULL, N''DepartmentName'', N''Department. Required if department is required'', N''detail'', 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8230, @GLBudget, N''Month 1'', N''month1'', NULL, N''Month1'', N''Month 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8231, @GLBudget, N''Month 2'', N''month2'', NULL, N''Month2'', N''Month 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8232, @GLBudget, N''Month 3'', N''month3'', NULL, N''Month3'', N''Month 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8233, @GLBudget, N''Month 4'', N''month4'', NULL, N''Month4'', N''Month 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8234, @GLBudget, N''Month 5'', N''month5'', NULL, N''Month5'', N''Month 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8235, @GLBudget, N''Month 6'', N''month6'', NULL, N''Month6'', N''Month 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8236, @GLBudget, N''Month 7'', N''month7'', NULL, N''Month7'', N''Month 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8237, @GLBudget, N''Month 8'', N''month8'', NULL, N''Month8'', N''Month 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8238, @GLBudget, N''Month 9'', N''month9'', NULL, N''Month9'', N''Month 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8239, @GLBudget, N''Month 10'', N''month10'', NULL, N''Month10'', N''Month 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8240, @GLBudget, N''Month 11'', N''month11'', NULL, N''Month11'', N''Month 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8241, @GLBudget, N''Month 12'', N''month12'', NULL, N''Month12'', N''Month 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8242, @GLBudget, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID. Required if Class is required'', N''detail'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
-- GL Accounts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8243, @GLAccountKey, N''Account Type'', N''accountType'', NULL, N''AccountTypeName'', N''Account Type'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8244, @GLAccountKey, N''Account Number'', N''accountNumber'', NULL, N''AccountNumber'', N''Account Number'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8245, @GLAccountKey, N''Account Name'', N''accountName'', NULL, N''AccountName'', N''Account Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8246, @GLAccountKey, N''Cash Account Type'', N''accountTypeCash'', NULL, N''AccountTypeNameCash'', N''Cash Account Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8247, @GLAccountKey, N''Payroll Expense Account'', N''payrollExpense'', NULL, N''PayrollExpenseYN'', N''Payroll Expense Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8248, @GLAccountKey, N''Facility Expense Account'', N''facilityExpense'', NULL, N''FacilityExpenseYN'', N''Facility Expense Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8249, @GLAccountKey, N''Labor Income'', N''laborIncome'', NULL, N''LaborIncome'', N''Labor Income'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8250, @GLAccountKey, N''Rollup Account'', N''rollup'', NULL, N''Rollup'', N''Rollup Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8251, @GLAccountKey, N''Sub Account Of'', N''parentAccountNumber'', NULL, N''ParentAccountNumber'', N''Sub Account Of (Enter ''''none'''', if changing from one to none)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8252, @GLAccountKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID. Required if the Account Type is credit card'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8253, @GLAccountKey, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8254, @GLAccountKey, N''Bank Account Number'', N''bankAccountNumber'', NULL, N''BankAccountNumber'', N''Bank Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8255, @GLAccountKey, N''Next Check Number'', N''nextCheckNumber'', NULL, N''NextCheckNumber'', N''Next Check Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8256, @GLAccountKey, N''No Journal Entries'', N''noJournalEntries'', NULL, N''NoJournalEntries'', N''No Journal Entries'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8257, @GLAccountKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (601, @GLAccountKey, N''EBITDA Account'', N''ebitdaaccount'', NULL, N''ebitdaaccount'', N''ebitdaaccount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (602, @GLAccountKey, N''Currency ID'', N''currencyID'', NULL, N''CurrencyID'', N''Currency ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- GL Classes
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8258, 54, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8259, 54, N''Class Name'', N''className'', NULL, N''ClassName'', N''Class Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8260, 54, N''Office'', N''officeID'', NULL, N''DepartmentName'', N''Office'', NULL, NULL, N''OfficeName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8261, 54, N''Department'', N''departmentID'', NULL, N''OfficeID'', N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8262, 54, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8263, 54, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--GL Companies
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8264, 33, N''Company Name'', N''glCompanyName'', NULL, N''GLCompanyName'', N''Company Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8265, 33, N''Company ID'', N''glCompanyID'', NULL, N''GLCompanyID'', N''Company ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8266, 33, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8268, 33, N''Printed Name'', N''printedName'', NULL, N''PrintedName'', N''Printed Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8269, 33, N''Phone'', N''phone'', NULL, N''Phone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8270, 33, N''Fax'', N''fax'', NULL, N''Fax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8271, 33, N''EIN Number'', N''eINNumber'', NULL, N''EINNumber'', N''EIN Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8272, 33, N''State EIN Number'', N''stateEINNumber'', NULL, N''StateEINNumber'', N''State EIN Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8273, 33, N''Web Site'', N''webSite'', NULL, N''WebSite'', N''Web Site'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8274, 33, N''Bank GL Account Number'', N''bankAccountNumber'', NULL, N''AccountNumber'', N''Bank GL Account Number'', NULL, NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
--Insertion Order
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8275, @IOKey, N''Order Number'', N''purchaseOrderNumber'', NULL, NULL, N''Order Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8276, @IOKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8277, @IOKey, N''Order Type'', N''purchaseOrderType'', NULL, NULL, N''Order Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8278, @IOKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number. Requierd if Link to Partner is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8279, @IOKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8280, @IOKey, N''Order Date'', N''pODate'', NULL, NULL, N''Order Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition], [SystemSettingFieldName]) VALUES (8281, @IOKey, N''Publication ID'', N''companyMediaID'', NULL, NULL, N''Publication ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL, N''IORequirePublications'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8282, @IOKey, N''Ordered By'', N''orderedBy'', NULL, NULL, N''Ordered By'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8283, @IOKey, N''Standard Header Text'', N''headerTextID'', NULL, NULL, N''Standard Header Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8284, @IOKey, N''Standard Footer Text'', N''footerTextID'', NULL, NULL, N''Standard Footer Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8285, @IOKey, N''Approver'', N''approvedBy'', NULL, NULL, N''Approver'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8286, @IOKey, N''Printing Mode'', N''orderDisplayMode'', NULL, NULL, N''Printing Mode'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8287, @IOKey, N''Print Client On Order'', N''printClientOnOrder'', NULL, NULL, N''Print Client On Order'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8288, @IOKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8289, @IOKey, N''Prebill At'', N''prebillAt'', NULL, NULL, N''Prebill At'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8290, @IOKey, N''Media Estimate ID'', N''mediaEstimateID'', NULL, NULL, N''Media Estimate ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8292, @IOKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8293, @IOKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line). Requierd if Link to Partner is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8294, @IOKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8295, @IOKey, N''Office ID'', N''officeID'', NULL, NULL, N''Office ID. Required if Office is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8296, @IOKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if item is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8298, @IOKey, N''Department'', N''departmentID'', NULL, NULL, N''Department'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8299, @IOKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Requierd if Link to Partner is required and task is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8300, @IOKey, N''Ad Number/Caption'', N''shortDescription'', NULL, NULL, N''Ad#/Caption'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8301, @IOKey, N''Comments'', N''longDescription'', NULL, NULL, N''Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8302, @IOKey, N''Gross'', N''grossAmount'', NULL, NULL, N''Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8303, @IOKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8304, @IOKey, N''Commission Pct'', N''markup'', NULL, NULL, N''Commission Pct'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8305, @IOKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8306, @IOKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8307, @IOKey, N''Space Close'', N''spaceClose'', NULL, NULL, N''Space Close'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8308, @IOKey, N''Materials Due'', N''materialsDue'', NULL, NULL, N''Materials Due'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8309, @IOKey, N''*[MediaPrint3]'', N''userDate3'', NULL, NULL, N''*[MediaPrint3]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8310, @IOKey, N''*[MediaPrint4]'', N''userDate4'', NULL, NULL, N''*[MediaPrint4]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8311, @IOKey, N''*[MediaPrint5]'', N''userDate5'', NULL, NULL, N''*[MediaPrint5]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8312, @IOKey, N''*[MediaPrint6]'', N''userDate6'', NULL, NULL, N''*[MediaPrint6]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34001, @IOKey, N''Traffic Instructions'', N''trafficInstructions'', NULL, NULL, N''Traffic Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34002, @IOKey, N''Special Instructions'', N''specialInstructions'', NULL, NULL, N''Special Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34003, @IOKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34004, @IOKey, N''Insertion Date'', N''detailOrderStartDate'', NULL, NULL, N''Insertion Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3406, @IOKey, N''Currency ID'', N''currencyID'', NULL, NULL, N''Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3407, @IOKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3408, @IOKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3409, @IOKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3410, @IOKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3411, @IOKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3412, @IOKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3413, @IOKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3414, @IOKey, N''Header ID'', N''headerID'', NULL, NULL, N''Header ID, used for associating header and detail fields when they do not pass in the PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3415, @IOKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- invoices aka client invoices
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8313, @InvoiceKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8314, @InvoiceKey, N''Client ID'', N''clientKey'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8315, @InvoiceKey, N''Contact Name'', N''contactName'', NULL, NULL, N''Contact Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8316, @InvoiceKey, N''Project Number'', N''projectKey'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8317, @InvoiceKey, N''Office'', N''officeKey'', NULL, NULL, N''Office'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8318, @InvoiceKey, N''Advance Bill'', N''advanceBill'', NULL, NULL, N''Advance Bill'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8319, @InvoiceKey, N''Invoice Date'', N''invoiceDate'', NULL, NULL, N''Invoice Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8320, @InvoiceKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8321, @InvoiceKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8322, @InvoiceKey, N''AR Account Number'', N''aRAccountKey'', NULL, NULL, N''AR Account Number. Required if GL account is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8323, @InvoiceKey, N''Terms Description'', N''termsKey'', NULL, NULL, N''Terms Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8324, @InvoiceKey, N''Invoice Comment'', N''headerComment'', NULL, NULL, N''Invoice Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8325, @InvoiceKey, N''Invoice Template'', N''invoiceTemplateKey'', NULL, NULL, N''Invoice Template'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8326, @InvoiceKey, N''User Defined 1'', N''userDefined1'', NULL, NULL, N''User Defined 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8327, @InvoiceKey, N''User Defined 2'', N''userDefined2'', NULL, NULL, N''User Defined 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8328, @InvoiceKey, N''User Defined 3'', N''userDefined3'', NULL, NULL, N''User Defined 3'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8329, @InvoiceKey, N''User Defined 4'', N''userDefined4'', NULL, NULL, N''User Defined 4'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8330, @InvoiceKey, N''User Defined 5'', N''userDefined5'', NULL, NULL, N''User Defined 5'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8331, @InvoiceKey, N''User Defined 6'', N''userDefined6'', NULL, NULL, N''User Defined 6'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8332, @InvoiceKey, N''User Defined 7'', N''userDefined7'', NULL, NULL, N''User Defined 7'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8333, @InvoiceKey, N''User Defined 8'', N''userDefined8'', NULL, NULL, N''User Defined 8'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8334, @InvoiceKey, N''User Defined 9'', N''userDefined9'', NULL, NULL, N''User Defined 9'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8335, @InvoiceKey, N''User Defined 10'', N''userDefined10'', NULL, NULL, N''User Defined 10'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8336, @InvoiceKey, N''Sales Tax ID'', N''salesTaxKey'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8337, @InvoiceKey, N''Sales Tax ID 2'', N''salesTax2Key'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8338, @InvoiceKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8339, @InvoiceKey, N''Approver'', N''approvedByKey'', NULL, NULL, N''Approver'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8340, @InvoiceKey, N''Approval Comment'', N''approvalComment'', NULL, NULL, N''Approval Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8341, @InvoiceKey, N''Approval Date'', N''approvalDate'', NULL, NULL, N''Approval Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8342, @InvoiceKey, N''GL Company'', N''glCompanyKey'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8343, @InvoiceKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8344, @InvoiceKey, N''Campaign ID'', N''campaignKey'', NULL, NULL, N''Campaign ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8345, @InvoiceKey, N''Layout Name'', N''layoutKey'', NULL, NULL, N''Layout Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8346, @InvoiceKey, N''Alternative Payer'', N''alternativePayer'', NULL, NULL, N''Alternative Payer'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8347, @InvoiceKey, N''Billing Group'', N''billingGroup'', NULL, NULL, N''Billing Group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8348, @InvoiceKey, N''Line Subject'', N''lineSubject'', NULL, NULL, N''Line Subject'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8349, @InvoiceKey, N''Line Description'', N''lineDescription'', NULL, NULL, N''Line Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8350, @InvoiceKey, N''Project Number (Line)'', N''projectKey'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8351, @InvoiceKey, N''Task ID'', N''taskKey'', NULL, NULL, N''Task ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8352, @InvoiceKey, N''Office (Line)'', N''officeKey'', NULL, NULL, N''Office (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8353, @InvoiceKey, N''Department'', N''departmentKey'', NULL, NULL, N''Department. Required if department is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8354, @InvoiceKey, N''Sales Account Number'', N''salesAccountKey'', NULL, NULL, N''Sales Account Number. Required if GL Account is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8355, @InvoiceKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8356, @InvoiceKey, N''Unit Amount'', N''unitAmount'', NULL, NULL, N''Unit Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8357, @InvoiceKey, N''Total Amount'', N''totalAmount'', NULL, NULL, N''Total Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110001, @InvoiceKey, N''Total Amount (Home Currency)'', N''hcTotalAmount'', NULL, NULL, N''Total Amount (Home Currency)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110002, @InvoiceKey, N''Class ID (line)'', N''classID'', NULL, NULL, N''Class ID (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110003, @InvoiceKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)

INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8358, @InvoiceKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8359, @InvoiceKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8360, @InvoiceKey, N''Taxable'', N''taxable'', NULL, NULL, N''Taxable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8361, @InvoiceKey, N''Taxable 2'', N''taxable2'', NULL, NULL, N''Taxable 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8362, @InvoiceKey, N''Segment Name'', N''campaignSegmentKey'', NULL, NULL, N''Segment Name'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8363, @InvoiceKey, N''Retainer Title'', N''retainerKey'', NULL, NULL, N''Retainer Title'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8364, @InvoiceKey, N''Billing Item ID'', N''workTypeKey'', NULL, NULL, N''Billing Item ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8365, @InvoiceKey, N''Item Type'', N''entity'', NULL, NULL, N''Item Type'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8366, @InvoiceKey, N''Item ID'', N''entityKey'', NULL, NULL, N''Item ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8367, @InvoiceKey, N''Display Option'', N''displayOption'', NULL, NULL, N''Display Option'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8368, @InvoiceKey, N''Target GL Company'', N''targetGLCompanyKey'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8369, @InvoiceKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8370, @InvoiceKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110011, @InvoiceKey, N''GL Company Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11001, @InvoiceKey, N''Posted'', N''posted'', NULL, NULL, N''Posted - this will posted the invoice if true'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Item Rate Sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8371, @ItemRateSheetKey, N''Rate Sheet Name'', N''rateSheetName'', NULL, N''RateSheetName'', N''Rate Sheet Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8372, @ItemRateSheetKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8373, @ItemRateSheetKey, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', N''detail'', 1, N''ItemID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8374, @ItemRateSheetKey, N''Markup'', N''markup'', NULL, N''Markup'', N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8375, @ItemRateSheetKey, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Journal Entries
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8376, @JEKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8377, @JEKey, N''Journal Number'', N''journalNumber'', NULL, NULL, N''Journal Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8378, @JEKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8379, @JEKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8380, @JEKey, N''Auto Reversing Entry'', N''autoReverse'', NULL, NULL, N''Auto Reversing Entry'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8381, @JEKey, N''Exclude From Cash Basis'', N''excludeCashBasis'', NULL, NULL, N''Exclude From Cash Basis'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8382, @JEKey, N''Exclude From Accrual Basis'', N''excludeAccrualBasis'', NULL, NULL, N''Exclude From Accrual Basis'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8383, @JEKey, N''Intercompany DT/DF Source'', N''intercompanyAccountSource'', NULL, NULL, N''Intercompany DT/DF Source'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8384, @JEKey, N''Account Number'', N''accountNumber'', NULL, NULL, N''Account Number'', N''detail'', 1, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8385, @JEKey, N''Client ID'', N''clientKey'', NULL, NULL, N''Client ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8386, @JEKey, N''Project'', N''projectKey'', NULL, NULL, N''Project'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8387, @JEKey, N''Office'', N''officeKey'', NULL, NULL, N''Office. Required if Office is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8388, @JEKey, N''Department'', N''departmentKey'', NULL, NULL, N''Department. Required if Department is required'', N''detail'', 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8389, @JEKey, N''Debit'', N''debitAmount'', NULL, NULL, N''Debit'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8390, @JEKey, N''Credit'', N''creditAmount'', NULL, NULL, N''Credit'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8391, @JEKey, N''Memo'', N''memo'', NULL, NULL, N''Memo'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8392, @JEKey, N''Target GL Company'', N''targetGLCompanyKey'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8393, @JEKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8394, @JEKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8395, @JEKey, N''Exchange Rate (Line)'', N''exchangeRateLine'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8396, @JEKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''detail'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (24001, @JEKey, N''Posted'', N''posted'', NULL, NULL, N''Posted - Yes Or No, to automatically post'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (24002, @JEKey, N''GLC Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')

-- Labor Budgets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8397, 75, N''Budget Name'', N''budgetName'', NULL, NULL, N''Budget Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8398, 75, N''Active'', N''active'', NULL, NULL, N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8399, 75, N''Employee Email'', N''email'', NULL, NULL, N''Employee Email'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8400, 75, N''Comments'', N''editComments'', NULL, NULL, N''Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8401, 75, N''Available Hours 1'', N''availableHours1'', NULL, NULL, N''Available Hours 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8402, 75, N''Target Hours 1'', N''targetHours1'', NULL, NULL, N''Target Hours 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8403, 75, N''Target Dollars 1'', N''targetDollars1'', NULL, NULL, N''Target Dollars 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8404, 75, N''Available Hours 2'', N''availableHours2'', NULL, NULL, N''Available Hours 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8405, 75, N''Target Hours 2'', N''targetHours2'', NULL, NULL, N''Target Hours 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8406, 75, N''Target Dollars 2'', N''targetDollars2'', NULL, NULL, N''Target Dollars 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8407, 75, N''Available Hours 3'', N''availableHours3'', NULL, NULL, N''Available Hours 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8408, 75, N''Target Hours 3'', N''targetHours3'', NULL, NULL, N''Target Hours 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8409, 75, N''Target Dollars 3'', N''targetDollars3'', NULL, NULL, N''Target Dollars 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8410, 75, N''Available Hours 4'', N''availableHours4'', NULL, NULL, N''Available Hours 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8411, 75, N''Target Hours 4'', N''targetHours4'', NULL, NULL, N''Target Hours 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8412, 75, N''Target Dollars 4'', N''targetDollars4'', NULL, NULL, N''Target Dollars 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8413, 75, N''Available Hours 5'', N''availableHours5'', NULL, NULL, N''Available Hours 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8414, 75, N''Target Hours 5'', N''targetHours5'', NULL, NULL, N''Target Hours 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8415, 75, N''Target Dollars 5'', N''targetDollars5'', NULL, NULL, N''Target Dollars 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8416, 75, N''Available Hours 6'', N''availableHours6'', NULL, NULL, N''Available Hours 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8417, 75, N''Target Hours 6'', N''targetHours6'', NULL, NULL, N''Target Hours 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8418, 75, N''Target Dollars 6'', N''targetDollars6'', NULL, NULL, N''Target Dollars 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8419, 75, N''Available Hours 7'', N''availableHours7'', NULL, NULL, N''Available Hours 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8420, 75, N''Target Hours 7'', N''targetHours7'', NULL, NULL, N''Target Hours 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8421, 75, N''Target Dollars 7'', N''targetDollars7'', NULL, NULL, N''Target Dollars 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8422, 75, N''Available Hours 8'', N''availableHours8'', NULL, NULL, N''Available Hours 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8423, 75, N''Target Hours 8'', N''targetHours8'', NULL, NULL, N''Target Hours 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8424, 75, N''Target Dollars 8'', N''targetDollars8'', NULL, NULL, N''Target Dollars 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8425, 75, N''Available Hours 9'', N''availableHours9'', NULL, NULL, N''Available Hours 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8426, 75, N''Target Hours 9'', N''targetHours9'', NULL, NULL, N''Target Hours 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8427, 75, N''Target Dollars 9'', N''targetDollars9'', NULL, NULL, N''Target Dollars 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8428, 75, N''Available Hours 10'', N''availableHours10'', NULL, NULL, N''Available Hours 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8429, 75, N''Target Hours 10'', N''targetHours10'', NULL, NULL, N''Target Hours 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8430, 75, N''Target Dollars 10'', N''targetDollars10'', NULL, NULL, N''Target Dollars 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8431, 75, N''Available Hours 11'', N''availableHours11'', NULL, NULL, N''Available Hours 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8432, 75, N''Target Hours 11'', N''targetHours11'', NULL, NULL, N''Target Hours 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8433, 75, N''Target Dollars 11'', N''targetDollars11'', NULL, NULL, N''Target Dollars 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8434, 75, N''Available Hours 12'', N''availableHours12'', NULL, NULL, N''Available Hours 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8435, 75, N''Target Hours 12'', N''targetHours12'', NULL, NULL, N''Target Hours 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8436, 75, N''Target Dollars 12'', N''targetDollars12'', NULL, NULL, N''Target Dollars 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--leads
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8437, @LeadKey, N''First Name'', N''firstName'', NULL, NULL, N''First Name'', NULL, NULL, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8438, @LeadKey, N''Middle Name'', N''middleName'', NULL, NULL, N''Middle Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8439, @LeadKey, N''Last Name'', N''lastName'', NULL, NULL, N''Last Name'', NULL, NULL, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8440, @LeadKey, N''Salutation'', N''salutation'', NULL, NULL, N''Salutation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8441, @LeadKey, N''Phone 1'', N''phone1'', NULL, NULL, N''Phone 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8442, @LeadKey, N''Phone 2'', N''phone2'', NULL, NULL, N''Phone 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8443, @LeadKey, N''Cell'', N''cell'', NULL, NULL, N''Cell'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8444, @LeadKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8445, @LeadKey, N''Pager'', N''pager'', NULL, NULL, N''Pager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8446, @LeadKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8447, @LeadKey, N''Email Address'', N''email'', NULL, NULL, N''Email Address'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8448, @LeadKey, N''Company'', N''companyName'', NULL, NULL, N''Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8449, @LeadKey, N''Company Main Phone'', N''companyPhone'', NULL, NULL, N''Company Main Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8450, @LeadKey, N''Company Fax'', N''companyFax'', NULL, NULL, N''Company Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8451, @LeadKey, N''Company Website'', N''companyWebsite'', NULL, NULL, N''Company Website'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8452, @LeadKey, N''Company Source'', N''companySourceKey'', NULL, NULL, N''Company Source'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8453, @LeadKey, N''Company Type'', N''companyTypeKey'', NULL, NULL, N''Company Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8454, @LeadKey, N''Business Address 1'', N''cAddress1'', NULL, NULL, N''Business Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8455, @LeadKey, N''Business Address 2'', N''cAddress2'', NULL, NULL, N''Business Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8456, @LeadKey, N''Business Address 3'', N''cAddress3'', NULL, NULL, N''Business Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8457, @LeadKey, N''Business City'', N''cCity'', NULL, NULL, N''Business City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8458, @LeadKey, N''Business State'', N''cState'', NULL, NULL, N''Business State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8459, @LeadKey, N''Business Postal Code'', N''cPostalCode'', NULL, NULL, N''Business Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8460, @LeadKey, N''Business Country'', N''cCountry'', NULL, NULL, N''Business Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8461, @LeadKey, N''Home Address 1'', N''hAddress1'', NULL, NULL, N''Home Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8462, @LeadKey, N''Home Address 2'', N''hAddress2'', NULL, NULL, N''Home Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8463, @LeadKey, N''Home Address 3'', N''hAddress3'', NULL, NULL, N''Home Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8464, @LeadKey, N''Home City'', N''hCity'', NULL, NULL, N''Home City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8465, @LeadKey, N''Home State'', N''hState'', NULL, NULL, N''Home State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8466, @LeadKey, N''Home Postal Code'', N''hPostalCode'', NULL, NULL, N''Home Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8467, @LeadKey, N''Home Country'', N''hCountry'', NULL, NULL, N''Home Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8468, @LeadKey, N''Other Address 1'', N''oAddress1'', NULL, NULL, N''Other Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8469, @LeadKey, N''Other Address 2'', N''oAddress2'', NULL, NULL, N''Other Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8470, @LeadKey, N''Other Address 3'', N''oAddress3'', NULL, NULL, N''Other Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8471, @LeadKey, N''Other City'', N''oCity'', NULL, NULL, N''Other City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8472, @LeadKey, N''Other State'', N''oState'', NULL, NULL, N''Other State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8473, @LeadKey, N''Other Postal Code'', N''oPostalCode'', NULL, NULL, N''Other Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8474, @LeadKey, N''Other Country'', N''oCountry'', NULL, NULL, N''Other Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8475, @LeadKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8476, @LeadKey, N''Department'', N''department'', NULL, NULL, N''Department'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8477, @LeadKey, N''Assistant'', N''assistant'', NULL, NULL, N''Assistant'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8478, @LeadKey, N''Assistant Phone'', N''assistantPhone'', NULL, NULL, N''Assistant Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8479, @LeadKey, N''Assistant Email'', N''assistantEmail'', NULL, NULL, N''Assistant Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8480, @LeadKey, N''Birthday'', N''birthday'', NULL, NULL, N''Birthday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8481, @LeadKey, N''Spouse/Partner'', N''spouseName'', NULL, NULL, N''Spouse/Partner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8482, @LeadKey, N''Children'', N''children'', NULL, NULL, N''Children'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8483, @LeadKey, N''Anniversary'', N''anniversary'', NULL, NULL, N''Anniversary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8484, @LeadKey, N''Hobbies'', N''hobbies'', NULL, NULL, N''Hobbies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8485, @LeadKey, N''Opportunity Subject'', N''opportunitySubject'', NULL, NULL, N''Opportunity Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8486, @LeadKey, N''Opportunity Amount'', N''opportunityAmount'', NULL, NULL, N''Opportunity Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8487, @LeadKey, N''Opportunity Project Type'', N''opportunityProjectTypeKey'', NULL, NULL, N''Opportunity Project Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8488, @LeadKey, N''Opportunity Description'', N''opportunityDescription'', NULL, NULL, N''Opportunity Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8489, @LeadKey, N''Lead Owner'', N''ownerKey'', NULL, NULL, N''Lead Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8490, @LeadKey, N''Folder'', N''cMFolderKey'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8491, @LeadKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8492, @LeadKey, N''Timezone Index'', N''timeZoneIndex'', NULL, NULL, N''Timezone Index'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8493, @LeadKey, N''Marketing Groups'', N''marketingLists'', NULL, NULL, N''Marketing Groups'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8494, @LeadKey, N''Preferred Contact Method'', N''contactMethod'', NULL, NULL, N''Preferred Contact Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8495, @LeadKey, N''Do Not Call'', N''doNotCall'', NULL, NULL, N''Do Not Call'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8496, @LeadKey, N''Do Not Email'', N''doNotEmail'', NULL, NULL, N''Do Not Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8497, @LeadKey, N''Do Not Mail'', N''doNotMail'', NULL, NULL, N''Do Not Mail'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8498, @LeadKey, N''Do Not Fax'', N''doNotFax'', NULL, NULL, N''Do Not Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8499, @LeadKey, N''GL Company'', N''glCompanyKey'', NULL, NULL, N''GL Company. Required if GL Company is required.'', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8500, @LeadKey, N''Role'', N''userRole'', NULL, NULL, N''Role'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyroles'''')'')
-- Media Market
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8501, 53, N''Market ID'', N''marketID'', NULL, N''MarketID'', N''Market ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8502, 53, N''Name'', N''marketName'', NULL, N''MarketName'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8503, 53, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Misc Costs
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8504, 23, N''Date'', N''expenseDate'', NULL, NULL, N''Date'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8505, 23, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8506, 23, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if "Require Tasks on Expenses" is set'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8507, 23, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if "Require Items" is set'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8508, 23, N''Department'', N''departmentID'', NULL, NULL, N''Department ID.  Required if "Require Departments" is set'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8509, 23, N''Description'', N''shortDescription'', NULL, NULL, N''Description'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8510, 23, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8511, 23, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8512, 23, N''Unit of Measure'', N''unitDescription'', NULL, NULL, N''Unit of Measure'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8513, 23, N''Net Amount'', N''totalCost'', NULL, NULL, N''Net Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8514, 23, N''Billable'', N''billable'', NULL, NULL, N''Billable'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8515, 23, N''Markup'', N''markup'', NULL, NULL, N''Markup'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8516, 23, N''Unit Billable Rate'', N''unitRate'', NULL, NULL, N''Unit Billable Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8517, 23, N''Gross Amount'', N''billableCost'', NULL, NULL, N''Gross Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8518, 23, N''Comments'', N''longDescription'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8519, 23, N''Billed'', N''billed'', NULL, NULL, N''Billed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8520, 23, N''Date Billed'', N''dateBilled'', NULL, NULL, N''Date Billed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8521, 23, N''Amount Billed'', N''amountBilled'', NULL, NULL, N''Amount Billed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8522, 23, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8523, 23, N''Class ID'', N''classID'', NULL, NULL, N''Class ID.  Required if "Require Class" is set'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8524, 55, N''Office ID'', N''officeID'', NULL, N''OfficeID'', N''Office ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8525, 55, N''Office Name'', N''officeName'', NULL, N''OfficeName'', N''Office Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8526, 55, N''Project Number Prefix'', N''projectNumPrefix'', NULL, N''ProjectNumPrefix'', N''Project Number Prefix'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8527, 55, N''Next Project Number'', N''nextProjectNum'', NULL, N''NextProjectNum'', N''Next Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8528, 55, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Opportunities
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8529, @OpportunitiesKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8530, @OpportunitiesKey, N''Primary Contact'', N''contactName'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8531, @OpportunitiesKey, N''Opportunity Name'', N''subject'', NULL, NULL, N''Opportunity Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8532, @OpportunitiesKey, N''Opportunity Owner'', N''opportunityOwner'', NULL, NULL, N''Opportunity Owner'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8533, @OpportunitiesKey, N''Project Type'', N''projectType'', NULL, NULL, N''Project Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8534, @OpportunitiesKey, N''Folder'', N''cMFolder'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8535, @OpportunitiesKey, N''Competitors'', N''competitors'', NULL, NULL, N''Competitors'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8536, @OpportunitiesKey, N''Description'', N''comments'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8537, @OpportunitiesKey, N''Stage'', N''leadStageName'', NULL, NULL, N''Stage. Requied if Stage is required'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8538, @OpportunitiesKey, N''Status'', N''leadStatusName'', NULL, NULL, N''Status'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8539, @OpportunitiesKey, N''Next Steps'', N''currentStatus'', NULL, NULL, N''Next Steps'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8540, @OpportunitiesKey, N''Probability'', N''probability'', NULL, NULL, N''Probability'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8541, @OpportunitiesKey, N''Revenue'', N''saleAmount'', NULL, NULL, N''Revenue'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8542, @OpportunitiesKey, N''Production'', N''outsideCostsGross'', NULL, NULL, N''Production'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8543, @OpportunitiesKey, N''Production Margin Pct'', N''outsideCostsPercentage'', NULL, NULL, N''Production Margin Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8544, @OpportunitiesKey, N''Media'', N''mediaGross'', NULL, NULL, N''Media'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8545, @OpportunitiesKey, N''Media Margin Pct'', N''mediaPercentage'', NULL, NULL, N''Media Margin Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8546, @OpportunitiesKey, N''Due Date of Estimate'', N''bidDate'', NULL, NULL, N''Due Date of Estimate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8547, @OpportunitiesKey, N''Forecasted Close Date'', N''estCloseDate'', NULL, NULL, N''Forecasted Close Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8548, @OpportunitiesKey, N''Outcome'', N''leadOutcome'', NULL, NULL, N''Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8549, @OpportunitiesKey, N''Actual Close Date'', N''actualCloseDate'', NULL, NULL, N''Actual Close Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8550, @OpportunitiesKey, N''Outcome Description'', N''outcomeComment'', NULL, NULL, N''Outcome Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8551, @OpportunitiesKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8552, @OpportunitiesKey, N''Sub Amount'', N''subAmount'', NULL, NULL, N''Sub Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8553, @OpportunitiesKey, N''Margin'', N''margin'', NULL, NULL, N''Margin'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8554, @OpportunitiesKey, N''Estimate Opportunity'', N''bid'', NULL, NULL, N''Estimate Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8555, @OpportunitiesKey, N''Start Date'', N''startDate'', NULL, NULL, N''Start Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8556, 38, N''WWP Need Supply'', N''wWPNeedSupply'', NULL, NULL, N''WWP Need Supply'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8557, 38, N''WWP Need Supply Comment'', N''wWPNeedSupplyComment'', NULL, NULL, N''WWP Need Supply Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8558, 38, N''WWP Timeline'', N''wWPTimeline'', NULL, NULL, N''WWP Timeline'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8559, 38, N''WWP Timeline Comment'', N''wWPTimelineComment'', NULL, NULL, N''WWP Timeline Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8560, 38, N''WWP Budget'', N''wWPBudget'', NULL, NULL, N''WWP Budget'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8561, 38, N''WWP Budget Comment'', N''wWPBudgetComment'', NULL, NULL, N''WWP Budget Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8562, 38, N''WWP Decision Makers'', N''wWPDecisionMakers'', NULL, NULL, N''WWP Decision Makers'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8563, 38, N''WWP Decision Makers Comment'', N''wWPDecisionMakersComment'', NULL, NULL, N''WWP Decision Makers Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8564, @OpportunitiesKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company. Required if GL company is required'', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38001, @OpportunitiesKey, N''Months'', N''months'', NULL, NULL, N''Months'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38002, @OpportunitiesKey, N''Labor'', N''labor'', NULL, NULL, N''Labor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38003, @OpportunitiesKey, N''Opportunity ID'', N''opportunityID'', NULL, NULL, N''Opportunity ID - cannot be set, it auto-increments.  Used for updating records'', NULL, NULL, NULL, 1, N''Opportunity ID'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38004, @OpportunitiesKey, N''Division'', N''clientDivision'', NULL, NULL, N''Client Division'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38005, @OpportunitiesKey, N''Product'', N''clientProduct'', NULL, NULL, N''Client Product'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Opportunity Stages
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8565, 41, N''Stage'', N''leadStageName'', NULL, N''LeadStageName'', N''Stage'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8566, 41, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8567, 41, N''Default Probability'', N''defaultProbability'', NULL, N''DefaultProbability'', N''Default Probability'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9410, 41, N''Display On Dashboard'', N''displayOnDashboard'', NULL, N''DisplayOnDashboard'', N''Display On Dashboard'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9411, 41, N''Use Default Probability'', N''useDefaultProbability'', NULL, N''UseDefaultProbability'', N''Default Probability'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Opportunity Status
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8568, 42, N''Status'', N''leadStatusName'', NULL, N''LeadStatusName'', N''Status'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8569, 42, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8570, 42, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Opportunity Outcome
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8571, 43, N''Outcome'', N''outcome'', NULL, N''Outcome'', N''Outcome'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8572, 43, N''Positive Outcome'', N''positiveOutcome'', NULL, N''PositiveOutcome'', N''Positive Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Payment Methods
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8573, 50, N''Payment Method'', N''checkMethod'', NULL, N''CheckMethod'', N''Payment Method'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8574, 50, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Payment Terms
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8575, 7, N''Payment Term'', N''termsDescription'', NULL, N''TermsDescription'', N''Payment Term'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8576, 7, N''Days'', N''dueDays'', NULL, N''DueDays'', N''Days'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Print Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8577, 32, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8578, 32, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8579, 32, N''Standard Gross'', N''unitRate'', NULL, N''UnitRate'', N''Standard Gross'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8580, 32, N''Commission'', N''markup'', NULL, N''Markup'', N''Commission'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8581, 32, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8582, 32, N''Billing Item ID'', N''workType'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8583, 32, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8584, 32, N''Expense Account Number'', N''expenseAccount'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8585, 32, N''Sales Account Number'', N''salesAccount'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8586, 32, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8587, 32, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8588, 32, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8589, 32, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID. Required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (32001, 32, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', NULL, NULL, Null, NULL, NULL, NULL, Null)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (32002, 32, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')

-- Project Billing Status
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8590, 29, N''Status ID'', N''projectBillingStatusID'', NULL, N''ProjectBillingStatusID'', N''Status ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8591, 29, N''Name'', N''projectBillingStatus'', NULL, N''ProjectBillingStatus'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8592, 29, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8593, 29, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Projects
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8594, @ProjectKey, N''Copy Tasks from Project Number'', N''copyProjectNumber'', NULL, NULL, N''Copy Tasks from Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8595, @ProjectKey, N''Copy Estimate'', N''copyEstimate'', NULL, NULL, N''Copy Estimate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8597, @ProjectKey, N''Project Name'', N''projectName'', NULL, N''ProjectName'', N''Project Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8598, @ProjectKey, N''Project Number'', N''projectNumber'', NULL, N''ProjectNumber'', N''Project Number'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8599, @ProjectKey, N''Project Type'', N''projectType'', NULL, N''ProjectTypeName'', N''Project Type. May be required based on project number style'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8600, @ProjectKey, N''Project Color'', N''projectColor'', NULL, N''ProjectColor'', N''Project Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8601, @ProjectKey, N''Client ID'', N''client'', NULL, N''CustomerID'', N''Client ID. May be required based on project number style'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8602, @ProjectKey, N''Campaign ID'', N''campaignID'', NULL, N''CampaignID'', N''Campaign ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8603, @ProjectKey, N''Segment Name'', N''campaignSegment'', NULL, N'''', N''Segment Name '', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8604, @ProjectKey, N''Account Manager User ID'', N''accountManager'', NULL, N''Account Manager'', N''Account Manager User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8605, @ProjectKey, N''Account Team'', N''team'', NULL, N''TeamName'', N''Account Team'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8606, @ProjectKey, N''Client Project Number'', N''clientProjectNumber'', NULL, N''ClientProjectNumber'', N''Client Project Number'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8607, @ProjectKey, N''Primary Contact Full Name'', N''billingContact'', NULL, N''BillingContact'', N''Primary Contact Full Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8608, @ProjectKey, N''Grant Contact Access Automatically'', N''assignBillingContact'', NULL, N''Billing Manager Name'', N''Grant Contact Access Automatically'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8609, @ProjectKey, N''Opportunity'', N''opportunityID'', NULL, N''Opportunity ID'', N''Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8610, @ProjectKey, N''Project Request ID'', N''requestID'', NULL, N''Project Request ID'', N''Project Request ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8611, @ProjectKey, N''GL Company'', N''glCompanyName'', NULL, N''Company ID'', N''GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8612, @ProjectKey, N''Office'', N''office'', NULL, N''Office ID'', N''Office. Required if Office is required'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8613, @ProjectKey, N''Billing Method'', N''billingMethod'', NULL, N''Billing Method'', N''Billing Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8614, @ProjectKey, N''Billing Group Code'', N''billingGroupCode'', NULL, N''Billing Group Code'', N''Billing Group Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8615, @ProjectKey, N''Billing Manager'', N''billingManager'', NULL, N''Billing Manager Name'', N''Billing Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8616, @ProjectKey, N''Expenses Not Included'', N''expensesNotIncluded'', NULL,N''ExpensesNotIncluded'', N''Expenses Not Included'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8617, @ProjectKey, N''Retainer'', N''retainerTitle'', NULL, N''Retainer Name'', N''Retainer'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8618, @ProjectKey, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8619, @ProjectKey, N''Status Notes'', N''statusNotes'', NULL, N''StatusNotes'', N''Status Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8620, @ProjectKey, N''Next Steps'', N''detailedNotes'', NULL, N''Next Steps'', N''Next Steps'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8621, @ProjectKey, N''Project Status ID'', N''projectStatus'', NULL, N''Project Status'', N''Project Status ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8622, @ProjectKey, N''Scheduling Direction'', N''scheduleDirection'', NULL, N''ScheduleDirection'', N''Scheduling Direction'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8623, @ProjectKey, N''Start Date'', N''startDate'', NULL, N''StartDate'', N''Start Date. Required if Schedule direction of from project start'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8624, @ProjectKey, N''Due Date'', N''completeDate'', NULL, N''CompleteDate'', N''Due Date. Required if schedule direction is from project completion'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8625, @ProjectKey, N''Flight Start Date'', N''flightStartDate'', NULL, N''FlightStartDate'', N''Flight Start Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8626, @ProjectKey, N''Flight End Date'', N''flightEndDate'', NULL, N''FlightEndDate'', N''Flight End Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8627, @ProjectKey, N''Flight Interval (D/W/S)'', N''flightInterval'', NULL, N''FlightInterval'', N''Flight Interval (D/W/S)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8628, @ProjectKey, N''Billing Status ID'', N''projectBillingStatus'', NULL, N''Project Billing Status'', N''Billing Status ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8629, @ProjectKey, N''Closed'', N''closed'', NULL, N''Closed'', N''Closed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8630, @ProjectKey, N''Non Billable'', N''nonBillable'', NULL, N''NonBillable'', N''Non Billable'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8632, @ProjectKey, N''Division Name'', N''clientDivision'', NULL, N''Client Division ID'', N''Division Name. May be required based on project number style'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8633, @ProjectKey, N''Product Name'', N''clientProduct'', NULL, N''Client Product ID'', N''Product Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8634, @ProjectKey, N''Get Rate From'', N''getRateFrom'', NULL, N''Get Labor Rate From'', N''Get Rate From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8635, @ProjectKey, N''Hourly Rate'', N''hourlyRate'', NULL, N''HourlyRate'', N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8636, @ProjectKey, N''Rate Sheet'', N''rateSheet'', NULL, N''Service Rate Sheet'', N''Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8637, @ProjectKey, N''Auto ID Task'', N''autoIDTask'', NULL, N''AutoIDTask'', N''Auto ID Task'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8638, @ProjectKey, N''Class ID'', N''classKey'', NULL, N''Class ID'', N''Class ID. Required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8639, @ProjectKey, N''*[KEYUSER1] User ID'', N''keyPeople1'', NULL, N''Key Person 1'', N''*[KEYUSER1] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8640, @ProjectKey, N''*[KEYUSER2] User ID'', N''keyPeople2'', NULL, N''Key Person 2'', N''*[KEYUSER2] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8641, @ProjectKey, N''*[KEYUSER3] User ID'', N''keyPeople3'', NULL, N''Key Person 3'', N''*[KEYUSER3] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8642, @ProjectKey, N''*[KEYUSER4] User ID'', N''keyPeople4'', NULL, N''Key Person 4'', N''*[KEYUSER4] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8643, @ProjectKey, N''*[KEYUSER5] User ID'', N''keyPeople5'', NULL, N''Key Person 5'', N''*[KEYUSER5] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8644, @ProjectKey, N''*[KEYUSER6] User ID'', N''keyPeople6'', NULL, N''Key Person 6'', N''*[KEYUSER6] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8645, @ProjectKey, N''Model Year'', N''modelYear'', NULL, N''ModeYear'', N''Model Year'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''spark44'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8646, @ProjectKey, N''Title Rate Sheet'', N''titleRateSheetKey'', NULL, N''Title Rate Sheet'', N''Title Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13001, @ProjectKey, N''Project Manager ID'', N''projectManager'', NULL, N''Project Manager'', N''Project Manager User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13002, @ProjectKey, N''Template'', N''template'', NULL, N''Template'', N''Template - yes or no'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13003, @ProjectKey, N''Get Markup From'', N''getMarkupFrom'', NULL, N''GetMarkupFrom'', N''Get Markup From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13004, @ProjectKey, N''Item Rate Sheet'', N''itemRateSheet'', NULL, N''Item Rate Sheet'', N''Item Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13005, @ProjectKey, N''Forecast As Fixed Fee'', N''forecastAsFixedFee'', NULL, N''Forecast As Fixed Fee'', N''Forecast As Fixed Fee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13006, @ProjectKey, N''Split Billing'', N''splitBilling'', NULL, N''splitBilling'', N''Split Billing. format clientID:# example(ACME:60|WMJ:40)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13007, @ProjectKey, N''Avalara Tax Code'', N''avalaraTaxCode'', NULL, N''Avalara Tax Code'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Project Spec Sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8647, 73, N''Spec Sheet ID Prefix'', N''specSheetPrefix'', NULL, NULL, N''Spec Sheet ID Prefix'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8648, 73, N''Project ID'', N''projectID'', NULL, NULL, N''Project ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8649, 73, N''Full Spec ID'', N''fullSpecID'', NULL, NULL, N''Full Spec ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8650, 73, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (73001, 73, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Project Staff Rates
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (127000, @ProjectStaffRatesKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (127001, @ProjectStaffRatesKey, N''User Name'', N''userName'', NULL, NULL, N''User Name'', NULL, 1, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (127002, @ProjectStaffRatesKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', NULL, 1, 1, NULL, NULL, NULL, NULL)

-- Project Status
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8651, @ProjectStatusCodeKey, N''Status ID'', N''projectStatusID'', NULL, N''ProjectStatusID'', N''Status ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8652, @ProjectStatusCodeKey, N''Name'', N''projectStatus'', NULL, N''ProjectStatus'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8653, @ProjectStatusCodeKey, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8654, @ProjectStatusCodeKey, N''Project is Active'', N''isActive'', NULL, N''IsActive'', N''Project is Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8655, @ProjectStatusCodeKey, N''Allow Time Entries'', N''timeActive'', NULL, N''TimeActive'', N''Allow Time Entries'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8656, @ProjectStatusCodeKey, N''Allow Expense Entries'', N''expenseActive'', NULL, N''ExpenseActive'', N''Allow Expense Entries'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8657, @ProjectStatusCodeKey, N''Lock Status'', N''locked'', NULL, N''Locked'', N''Lock Status'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8658, @ProjectStatusCodeKey, N''On Hold'', N''onHold'', NULL, N''OnHold'', N''On Hold'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9271, @ProjectStatusCodeKey, N''Include In Forecast'', N''includeInForecast'', NULL, N''IncludeInForecast'', N''Include In Forecast'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (27001, @ProjectStatusCodeKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Project Types
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8659, 25, N''Project Type'', N''projectTypeName'', NULL, N''ProjectTypeName'', N''Project Type'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8660, 25, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8661, 25, N''Project Number Prefix'', N''projectNumPrefix'', NULL, N''ProjectNumPrefix'', N''Project Number Prefix'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8662, 25, N''Next Project Number'', N''nextProjectNum'', NULL, N''NextProjectNum'', N''Next Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8663, 25, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8664, 25, N''Subject1'', N''subject1'', NULL, N''Subject1'', N''Subject1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8665, 25, N''Subject2'', N''subject2'', NULL, N''Subject2'', N''Subject2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8666, 25, N''Subject3'', N''subject3'', NULL, N''Subject3'', N''Subject3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8667, 25, N''Subject4'', N''subject4'', NULL, N''Subject4'', N''Subject4'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8668, 25, N''Subject5'', N''subject5'', NULL, N''Subject5'', N''Subject5'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8669, 25, N''Subject6'', N''subject6'', NULL, N''Subject6'', N''Subject6'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8670, 25, N''Subject7'', N''subject7'', NULL, N''Subject7'', N''Subject7'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8671, 25, N''Subject8'', N''subject8'', NULL, N''Subject8'', N''Subject8'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8672, 25, N''Subject9'', N''subject9'', NULL, N''Subject9'', N''Subject9'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8673, 25, N''Subject10'', N''subject10'', NULL, N''Subject10'', N''Subject10'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8674, 25, N''Subject11'', N''subject11'', NULL, N''Subject11'', N''Subject11'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8675, 25, N''Subject12'', N''subject12'', NULL, N''Subject12'', N''Subject12'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Publication
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12001, @PublicationKey, N''Publication Name'', N''name'', NULL, N''Publication'', N''Publication Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12002, @PublicationKey, N''Publication ID'', N''publicationID'', NULL, N''publicationID'', N''Publication ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12003, @PublicationKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12004, @PublicationKey, N''Media Market'', N''mediaMarket'', NULL, N''Media Market'', N''Media Market'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12005, @PublicationKey, N''Item ID'', N''item'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12006, @PublicationKey, N''ContactName'', N''contact'', NULL, N''Contact'', N''contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12007, @PublicationKey, N''Address 1'', N''address1'', NULL, N''address1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12008, @PublicationKey, N''Address 2'', N''address2'', NULL, N''address2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12009, @PublicationKey, N''Address 3'', N''address3'', NULL, N''address3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12010, @PublicationKey, N''City'', N''city'', NULL, N''city'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12011, @PublicationKey, N''State'', N''state'', NULL, N''State'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12012, @PublicationKey, N''Postal Code'', N''postalCode'', NULL, N''PostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12013, @PublicationKey, N''Country'', N''country'', NULL, N''Country'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12014, @PublicationKey, N''Phone'', N''phone'', NULL, N''Phone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12015, @PublicationKey, N''Fax'', N''fax'', NULL, N''Fax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12016, @PublicationKey, N''Material Address 1'', N''mAddress1'', NULL, N''mAddress1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12017, @PublicationKey, N''Material Address 2'', N''mAddress2'', NULL, N''mAddress2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12018, @PublicationKey, N''Material Address 3'', N''mAddress3'', NULL, N''mAddress3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12019, @PublicationKey, N''Material City'', N''mCity'', NULL, N''mCity'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12020, @PublicationKey, N''Material State'', N''mState'', NULL, N''mState'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12021, @PublicationKey, N''Material Postal Code'', N''mPostalCode'', NULL, N''mPostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12022, @PublicationKey, N''Material Country'', N''mCountry'', NULL, N''mCountry'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12023, @PublicationKey, N''Material Phone'', N''mPhone'', NULL, N''mPhone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12024, @PublicationKey, N''Material Fax'', N''mFax'', NULL, N''mFax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12025, @PublicationKey, N''Space Close Number'', N''spaceCloseNumDays'', NULL, N''spaceCloseNumDays'', N''Space Close Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12026, @PublicationKey, N''Material Due Number'', N''materailsDueNumDays'', NULL, N''materailsDueNumDays'', N''Material Due Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Purchase Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8676, 5, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8677, 5, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8678, 5, N''Unit Cost'', N''unitCost'', NULL, N''UnitCost'', N''Unit Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8679, 5, N''Markup'', N''markup'', NULL, N''Markup'', N''Markup'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8680, 5, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8681, 5, N''Always use Unit Rate for Gross Amount'', N''useUnitRate'', NULL, N''UseUnitRate'', N''Always use Unit Rate for Gross Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8682, 5, N''Unit Description'', N''unitDescription'', NULL, N''UnitDescription'', N''Unit Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8683, 5, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8684, 5, N''Billing Item ID'', N''billingItemID'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''BillingItemID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8685, 5, N''Department'', N''departmentName'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8686, 5, N''Expense Account Number'', N''expenseAccountNumber'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8687, 5, N''Sales Account Number'', N''salesAccountNumber'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8688, 5, N''Quantity On Hand'', N''quantityOnHand'', NULL, N''QuantityOnHand'', N''Quantity On Hand'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8689, 5, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8690, 5, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8691, 5, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8692, 5, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID. Required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (869200, 5, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')
--Purchase Order
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8693, @POKey, N''PO Number'', N''purchaseOrderNumber'', NULL, NULL, N''PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8694, @POKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8695, @POKey, N''PO Type'', N''purchaseOrderType'', NULL, NULL, N''PO Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8696, @POKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8697, @POKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8698, @POKey, N''PO Date'', N''pODate'', NULL, NULL, N''PO Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8699, @POKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8700, @POKey, N''Ordered By'', N''orderedBy'', NULL, NULL, N''Ordered By'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8701, @POKey, N''Standard Header Text'', N''headerTextID'', NULL, NULL, N''Standard Header Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8702, @POKey, N''Standard Footer Text'', N''footerTextID'', NULL, NULL, N''Standard Footer Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8703, @POKey, N''Approver'', N''approvedBy'', NULL, NULL, N''Approver'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8704, @POKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8705, @POKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8706, @POKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8707, @POKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8708, @POKey, N''Order Description'', N''description'', NULL, NULL, N''Order Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8709, @POKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8711, @POKey, N''Office'', N''officeKey'', NULL, NULL, N''Office'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8712, @POKey, N''Department'', N''departmentID'', NULL, NULL, N''Department'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8713, @POKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8714, @POKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8715, @POKey, N''Description'', N''shortDescription'', NULL, NULL, N''Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8716, @POKey, N''Long Description'', N''longDescription'', NULL, NULL, N''Long Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8719, @POKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8720, @POKey, N''Unit Desc'', N''unitDescription'', NULL, NULL, N''Unit Desc'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8721, @POKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8722, @POKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8723, @POKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8724, @POKey, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8725, @POKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8726, @POKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8727, @POKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8728, @POKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8729, @POKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8730, @POKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8731, @POKey, N''Class ID (Line)'', N''classID'', NULL, NULL, N''Class ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18001, @POKey, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18002, @POKey, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18003, @POKey, N''Traffic Instructions'', N''trafficInstructions'', NULL, NULL, N''Traffic Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18004, @POKey, N''Special Instructions'', N''specialInstructions'', NULL, NULL, N''Special Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18005, @POKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID, used for selecting appropriate field group'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18006, @POKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID, used for selecting appropriate field group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18007, @POKey, N''Header ID'', N''headerID'', NULL, NULL, N''Header ID, used for associating header and detail fields when they do not pass in the PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
-- Receipts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11501, @ReceiptsKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11502, @ReceiptsKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11503, @ReceiptsKey, N''Check Amount'', N''checkAmount'', NULL, NULL, N''Check Amount'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11504, @ReceiptsKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11505, @ReceiptsKey, N''Reference Number'', N''referenceNumber'', NULL, NULL, N''Reference Number'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11506, @ReceiptsKey, N''Payment Method'', N''paymentMethod'', NULL, NULL, N''Payment Method'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11507, @ReceiptsKey, N''Receipt Date'', N''checkDate'', NULL, NULL, N''Receipt Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11508, @ReceiptsKey, N''Deposit ID'', N''depositID'', NULL, NULL, N''Deposit ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11509, @ReceiptsKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11510, @ReceiptsKey, N''Cash Account Number'', N''cashAccountNumber'', NULL, NULL, N''Cash Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11511, @ReceiptsKey, N''Unapplied Payment Account Number'', N''prepayAccountNumber'', NULL, NULL, N''Unapplied Payment Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11512, @ReceiptsKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11513, @ReceiptsKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11514, @ReceiptsKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11515, @ReceiptsKey, N''GL Account'', N''glAccount'', NULL, NULL, N''GL Account'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11516, @ReceiptsKey, N''Description (Line)'', N''description'', NULL, NULL, N''Description (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11517, @ReceiptsKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11518, @ReceiptsKey, N''Department'', N''department'', NULL, NULL, N''Department. Required if Department is required.'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11519, @ReceiptsKey, N''Amount Applied'', N''amount'', NULL, NULL, N''Amount Applied'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11520, @ReceiptsKey, N''Office'', N''office'', NULL, NULL, N''Office. Required if Office ie required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11521, @ReceiptsKey, N''Target GL Company'', N''targetGLCompany'', NULL, NULL, N''Target GL Company. Required if GL Company is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11522, @ReceiptsKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11523, @ReceiptsKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11524, @ReceiptsKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11525, @ReceiptsKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11526, @ReceiptsKey, N''Receipt Key'', N''receiptKey'', NULL, NULL, N''Receipt Key'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11527, @ReceiptsKey, N''Action'', N''action'', NULL, NULL, N''Action - d for deleting a row'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- Report Groups
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8732, 40, N''Group Name'', N''groupName'', NULL, N''GroupName'', N''Group Name'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8733, 40, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Request Reject Reasons
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8734, 67, N''Request Reject Reason'', N''reasonName'', NULL, N''ReasonName'', N''Request Reject Reason'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8735, 67, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8736, 67, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Project Requests
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8737, @ProjectRequestKey, N''Request Prefix'', N''requestPrefix'', NULL, NULL, N''Spec Sheet ID Prefix'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8738, @ProjectRequestKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8740, @ProjectRequestKey, N''Notify Email'', N''notifyEmail'', NULL, NULL, N''Notify Email'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8741, @ProjectRequestKey, N''Project Due Date'', N''dueDate'', NULL, NULL, N''Project Due Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (1, @ProjectRequestKey, N''Client Project Number'', N''clientProjectNumber'', NULL, NULL, N''Client Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (2, @ProjectRequestKey, N''Campaign ID'', N''campaignID'', NULL, NULL, N''Campaign ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3, @ProjectRequestKey, N''Project Name'', N''subject'', NULL, NULL, N''Project Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (4, @ProjectRequestKey, N''Project Description'', N''projectDescription'', NULL, NULL, N''Project Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (5, @ProjectRequestKey, N''Requested By'', N''requestedBy'', NULL, NULL, N''Requested By'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6, @ProjectRequestKey, N''Request ID'', N''requestID'', NULL, NULL, N''Request ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7, @ProjectRequestKey, N''Status'', N''status'', NULL, NULL, N''Status'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (76007, @ProjectRequestKey, N''Skip Approval Process'', N''skipApprovalProcess'', NULL, NULL, N''Skip Approval Process (True or False) - If true, then will not send out new emails'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
-- Request Spec Sheets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8742, 74, N''Spec Sheet ID Prefix'', N''specSheetPrefix'', NULL, NULL, N''Spec Sheet ID Prefix'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8743, 74, N''Request ID'', N''requestID'', NULL, NULL, N''Request ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8744, 74, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8745, 74, N''Full Spec ID'', N''fullSpecID'', NULL, NULL, N''Full Spec ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8746, 74, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (10, 74, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Retainer
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11801, @RetainerKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11802, @RetainerKey, N''Amount Per Period'', N''amountPerPeriod'',NULL, NULL, N''Amount Per Period'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11803, @RetainerKey, N''Billing Manager'', N''billingManager'',NULL, NULL, N''Billing Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11804, @RetainerKey, N''Class'', N''classKey'',NULL, NULL, N''Class'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11805, @RetainerKey, N''Client ID'', N''client'', NULL, NULL, N''Client ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11806, @RetainerKey, N''Contact'', N''contact'',NULL, NULL, N''Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11807, @RetainerKey, N''Cost Per Period'', N''costPerPeriod'',NULL, NULL, N''Cost Per Period'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11808, @RetainerKey, N''Currency ID'', N''currencyID'',NULL, NULL, N''Currency ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11809, @RetainerKey, N''Description'', N''description'',NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11810, @RetainerKey, N''Frequency'', N''frequency'',NULL, NULL, N''Frequency (monthly, quarterly, yearly, weekly) '', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11811, @RetainerKey, N''Include Labor'', N''includeLabor'',NULL, NULL, N''Include Labor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11812, @RetainerKey, N''Include Expense'', N''includeExpense'',NULL, NULL, N''Include Expense'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11813, @RetainerKey, N''Invoice Approved By'', N''invoiceApprovedBy'',NULL, NULL, N''Invoice Approved By'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11814, @RetainerKey, N''Invoice Expenses Separate'', N''invoiceExpensesSeparate'',NULL, NULL, N''Invoice Expenses Separate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11815, @RetainerKey, N''Invoice Template'', N''invoiceTemplate'',NULL, NULL, N''Invoice Template'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11817, @RetainerKey, N''Last Billing Date'', N''lastBillingDate'',NULL, NULL, N''Last Billing Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11818, @RetainerKey, N''Layout'', N''layout'',NULL, NULL, N''Layout'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11819, @RetainerKey, N''Line Format'', N''lineFormat'',NULL, NULL, N''Line Format'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11820, @RetainerKey, N''Number Of Periods'', N''numberOfPeriods'',NULL, NULL, N''Number Of Periods'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11821, @RetainerKey, N''Office'', N''office'',NULL, NULL, N''Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11822, @RetainerKey, N''Sales Account'', N''salesAccount'',NULL, NULL, N''Sales Account'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11823, @RetainerKey, N''Start Date'', N''startDate'', NULL, NULL, N''Start Date'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11824, @RetainerKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11825, @RetainerKey, N''GL Company'', N''glCompany'',NULL, NULL, N''GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Sales Tax
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8747, 8, N''Sales Tax ID'', N''salesTaxID'', NULL, N''SalesTaxID'', N''Sales Tax ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8748, 8, N''Sales Tax Name'', N''salesTaxName'', NULL, N''SalesTaxName'', N''Sales Tax Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8749, 8, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8750, 8, N''Pay To Vendor ID'', N''payTo'', NULL, N''VendorID'', N''Pay To Vendor ID'', NULL, NULL, N''PayToID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8751, 8, N''Tax Payable GL Account Number'', N''payableGLAccountKey'', NULL, N''PayableAccountNumber'', N''Tax Payable GL Account Number'', NULL, NULL, N''PayableGLAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8752, 8, N''Tax AP GL Account Number'', N''aPPayableGLAccountKey'', NULL, N''APAccountNumber'', N''Tax AP GL Account Number'', NULL, NULL, N''APPayableGLAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8753, 8, N''Tax Rate Percentage'', N''taxRate'', NULL, N''TaxRate'', N''Tax Rate Percentage'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8754, 8, N''Piggy Back Tax'', N''piggyBackTax'', NULL, N''PiggyBackTax'', N''Piggy Back Tax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8755, 8, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Service Rate Sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8756, @ServiceRateSheetKey, N''Rate Sheet Name'', N''rateSheetName'', NULL, N''RateSheetName'', N''Rate Sheet Name'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8757, @ServiceRateSheetKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8758, @ServiceRateSheetKey, N''Service Code'', N''serviceCode'', NULL, N''ServiceCode'', N''Service Code'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8759, @ServiceRateSheetKey, N''Rate 1'', N''rate1'', NULL, N''HourlyRate1'', N''Rate 1'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8760, @ServiceRateSheetKey, N''Rate 2'', N''rate2'', NULL, N''HourlyRate2'', N''Rate 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8761, @ServiceRateSheetKey, N''Rate 3'', N''rate3'', NULL, N''HourlyRate3'', N''Rate 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8762, @ServiceRateSheetKey, N''Rate 4'', N''rate4'', NULL, N''HourlyRate4'', N''Rate 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8763, @ServiceRateSheetKey, N''Rate 5'', N''rate5'', NULL, N''HourlyRate5'', N''Rate 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (58004, @ServiceRateSheetKey, N''Description'', N''description'', NULL, N''Description'', N''Service Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (58005, @ServiceRateSheetKey, N''Invoice Label'', N''invoiceLabel'', NULL, N''InvoiceLabel'', N''Invoice Label'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (58003, @ServiceRateSheetKey, N''Hourly Cost'', N''hourlyCost'', NULL, N''HourlyCost'', N''Hourly Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Services
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8764, 9, N''Service Code'', N''serviceCode'', NULL, N''ServiceCode'', N''Service Code'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8765, 9, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8766, 9, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8767, 9, N''Billing Item ID'', N''workTypeKey'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8768, 9, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8769, 9, N''Sales Account Number'', N''glAccountKey'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8770, 9, N''Hourly Cost'', N''hourlyCost'', NULL, N''HourlyCost'', N''Hourly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8771, 9, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8772, 9, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8773, 9, N''Hourly Rate 1'', N''hourlyRate1'', NULL, N''HourlyRate1'', N''Hourly Rate 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8774, 9, N''Rate Description 1'', N''description1'', NULL, N''Description1'', N''Rate Description 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8775, 9, N''Hourly Rate 2'', N''hourlyRate2'', NULL, N''HourlyRate2'', N''Hourly Rate 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8776, 9, N''Rate Description 2'', N''description2'', NULL, N''Description2'', N''Rate Description 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8777, 9, N''Hourly Rate 3'', N''hourlyRate3'', NULL, N''HourlyRate3'', N''Hourly Rate 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8778, 9, N''Rate Description 3'', N''description3'', NULL, N''Description3'', N''Rate Description 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8779, 9, N''Hourly Rate 4'', N''hourlyRate4'', NULL, N''HourlyRate4'', N''Hourly Rate 4'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8780, 9, N''Rate Description 4'', N''description4'', NULL, N''Description4'', N''Rate Description 4'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8781, 9, N''Hourly Rate 5'', N''hourlyRate5'', NULL, N''HourlyRate5'', N''Hourly Rate 5'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8782, 9, N''Rate Description 5'', N''description5'', NULL, N''Description5'', N''Rate Description 5'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8783, 9, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID'', NULL, NULL, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (87840, 9, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')
-- Standard Text
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8784, 52, N''Type'', N''type'', NULL, N''Type'', N''Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8785, 52, N''Text Block Name'', N''textName'', NULL, N''TextName'', N''Text Block Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8786, 52, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8787, 52, N''Standard Text'', N''standardText'', NULL, N''StandardText'', N''Standard Text'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
-- Station
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12201, @StationKey, N''Station Name'', N''name'', NULL, N''StationName'', N''Station Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12202, @StationKey, N''Station ID'', N''stationID'', NULL, N''StationID'', N''Station ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12203, @StationKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12204, @StationKey, N''Media Market'', N''mediaMarket'', NULL, N''Media Market'', N''Media Market'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12205, @StationKey, N''Item ID'', N''item'', NULL, N''ItemID'', N''Item ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12206, @StationKey, N''ContactName'', N''contact'', NULL, N''Contact'', N''contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12207, @StationKey, N''Address 1'', N''address1'', NULL, N''address1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12208, @StationKey, N''Address 2'', N''address2'', NULL, N''address2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12209, @StationKey, N''Address 3'', N''address3'', NULL, N''address3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12210, @StationKey, N''City'', N''city'', NULL, N''city'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12211, @StationKey, N''State'', N''state'', NULL, N''State'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12212, @StationKey, N''Postal Code'', N''postalCode'', NULL, N''PostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12213, @StationKey, N''Country'', N''country'', NULL, N''Country'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12214, @StationKey, N''Phone'', N''phone'', NULL, N''Phone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12215, @StationKey, N''Fax'', N''fax'', NULL, N''Fax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12216, @StationKey, N''Material Address 1'', N''mAddress1'', NULL, N''mAddress1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12217, @StationKey, N''Material Address 2'', N''mAddress2'', NULL, N''mAddress2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12218, @StationKey, N''Material Address 3'', N''mAddress3'', NULL, N''mAddress3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12219, @StationKey, N''Material City'', N''mCity'', NULL, N''mCity'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12220, @StationKey, N''Material State'', N''mState'', NULL, N''mState'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12221, @StationKey, N''Material Postal Code'', N''mPostalCode'', NULL, N''mPostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12222, @StationKey, N''Material Country'', N''mCountry'', NULL, N''mCountry'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12223, @StationKey, N''Material Phone'', N''mPhone'', NULL, N''mPhone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12224, @StationKey, N''Material Fax'', N''mFax'', NULL, N''mFax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12225, @StationKey, N''Space Close Number'', N''spaceCloseNumDays'', NULL, N''spaceCloseNumDays'', N''Space Close Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12226, @StationKey, N''Material Due Number'', N''materailsDueNumDays'', NULL, N''materailsDueNumDays'', N''Material Due Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Sources
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8788, 48, N''Role'', N''sourceName'', NULL, N''SourceName'', N''Role'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8789, 48, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Tasks
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8792, @TaskKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', 1, NULL, 1, NULL, 2, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8794, @TaskKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', N''header'', NULL, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8795, @TaskKey, N''Task Name'', N''taskName'', NULL, NULL, N''Task Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8796, @TaskKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8798, @TaskKey, N''Summary Task ID'', N''summaryTaskID'', NULL, NULL, N''Summary Task ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8799, @TaskKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8800, @TaskKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8801, @TaskKey, N''IO Commission'', N''ioCommission'', NULL, NULL, N''IO Commission'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8802, @TaskKey, N''BC Commission'', N''bcCommission'', NULL, NULL, N''BC Commission'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8803, @TaskKey, N''Show Desc On Est'', N''showDescOnEst'', NULL, NULL, N''Show Desc On Est'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8805, @TaskKey, N''Taxable'', N''taxable'', NULL, NULL, N''Taxable'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8806, @TaskKey, N''Taxable2'', N''taxable2'', NULL, NULL, N''Taxable2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8807, @TaskKey, N''Billing Item ID'', N''workTypeID'', NULL, NULL, N''Billing Item ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8808, @TaskKey, N''Base Start'', N''baseStart'', NULL, NULL, N''Base Start'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8809, @TaskKey, N''Base Complete'', N''baseComplete'', NULL, NULL, N''Base Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8810, @TaskKey, N''Plan Start'', N''planStart'', NULL, NULL, N''Plan Start'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8811, @TaskKey, N''Plan Complete'', N''planComplete'', NULL, NULL, N''Plan Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8812, @TaskKey, N''Plan Duration'', N''planDuration'', NULL, NULL, N''Plan Duration'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8813, @TaskKey, N''Act Start'', N''actStart'', NULL, NULL, N''Act Start'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8814, @TaskKey, N''Act Complete'', N''actComplete'', NULL, NULL, N''Act Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8815, @TaskKey, N''Perc Comp'', N''percComp'', NULL, NULL, N''Perc Comp'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8816, @TaskKey, N''Task Constraint'', N''taskConstraint'', NULL, NULL, N''Task Constraint.  Possible values are:<br> As Soon As Possible<br> As Late As Possible<br> Must Start On<br> Must Finish On<br> Finish No Earlier Than<br> Finish No Later Than<br> Start No Earlier Than<br> Start No Later Than'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8817, @TaskKey, N''Status Comments'', N''comments'', NULL, NULL, N''Status Comments'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8818, @TaskKey, N''Schedule Task'', N''scheduleTask'', NULL, NULL, N''Schedule Task'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8819, @TaskKey, N''Track Budget'', N''trackBudget'', NULL, NULL, N''Track Budget'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8821, @TaskKey, N''Hide From Client'', N''hideFromClient'', NULL, NULL, N''Hide From Client'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8822, @TaskKey, N''Allow Anyone'', N''allowAnyone'', NULL, NULL, N''Allow Anyone'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8823, @TaskKey, N''Constraint Date'', N''constraintDate'', NULL, NULL, N''Constraint Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8824, @TaskKey, N''Work Any Day'', N''workAnyDay'', NULL, NULL, N''Work Any Day'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8825, @TaskKey, N''Perc Comp Separate'', N''percCompSeparate'', NULL, NULL, N''Track Actual Dates for Each Person'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8829, @TaskKey, N''Priority'', N''priority'', NULL, NULL, N''Priority. Use Priority Name value from Task Priority Setup.<br> Or use these values:<br>H<br>M<br>L'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8831, 69, N''Event Start Date and Time'', N''eventStart'', NULL, NULL, N''Event Start Date and Time'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8832, 69, N''Event End Date and Time'', N''eventEnd'', NULL, NULL, N''Event End Date and Time'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8834, @TaskKey, N''Due By Comments'', N''dueBy'', NULL, NULL, N''Due By Comments'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8835, @TaskKey, N''Reviewed By Traffic'', N''reviewedByTraffic'', NULL, NULL, N''Reviewed By Traffic'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8836, @TaskKey, N''Predecessors Complete'', N''predecessorsComplete'', NULL, NULL, N''Predecessors Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8838, @TaskKey, N''Schedule Notes'', N''scheduleNote'', NULL, NULL, N''Schedule Notes'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8839, @TaskKey, N''Constraint Day Of The Week'', N''constraintDayOfTheWeek'', NULL, NULL, N''Constraint Day Of The Week'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8840, @TaskKey, N''Exclude From Status'', N''excludeFromStatus'', NULL, NULL, N''Exclude From Status'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8841, @TaskKey, N''Allow Allocated Hours'', N''allowAllocatedHours'', NULL, NULL, N''Allow Allocated Hours'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (690, @TaskKey, N''Timeline Segment'', N''timelineSegment'', NULL, NULL, N''Timeline Segment'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (691, @TaskKey, N''Project Status When Task Complete'', N''taskCompleteProjectStatus'', NULL, NULL, N''Project Status When Task Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (692, 69, N''Assignment Comments'', N''aDescription'', NULL, NULL, N''Assignment Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8842, @TaskKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8843, @TaskKey, N''Detail Service Code'', N''detailServiceCode'', NULL, NULL, N''Detail Service Code'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8844, @TaskKey, N''Hours Allocated'', N''detailHours'', NULL, NULL, N''Hours Allocated'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69003, @TaskKey, N''Weekly Hours'', N''weeklyHours'', NULL, NULL, N''Weekly Bucket Hours (separate each weekly value with a | symbol). For example "2.2|3|4.55". If specified, Hours Allocated is calculated for this assignment, and the assignment will be makred as Manually Adjusted.'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8845, @TaskKey, N''Detail Perc Comp'', N''detailPercComp'', NULL, NULL, N''Detail Perc Comp'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8846, @TaskKey, N''Detail Act Start'', N''detailActStart'', NULL, NULL, N''Detail Act Start'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8847, @TaskKey, N''Detail Act Complete'', N''detailActComplete'', NULL, NULL, N''Detail Act Complete'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8848, 69, N''Detail Reviewed By Traffic'', N''detailReviewedByTraffic'', NULL, NULL, N''Detail Reviewed By Traffic'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8849, @TaskKey, N''Manual Adjustment'', N''manualAdjustment'', NULL, NULL, N''Manual Adjustment'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8850, @TaskKey, N''APlanStart'', N''aPlanStart'', NULL, NULL, N''APlanStart'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8852, @TaskKey, N''APlan Complete'', N''aPlanComplete'', NULL, NULL, N''APlan Complete'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8853, @TaskKey, N''Action'', N''action'', NULL, NULL, N''Action'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69001, @TaskKey, N''Predecessors'', N''predecessors'', NULL, NULL, N''Predecessors (lag), task ID comma seperated.  If want to add a lag please put it in () after the predecessor.  For example "2.1 (1)"'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69002, @TaskKey, N''Must Finish On Pred Complete'', N''mustFinishOnPredComplete'', NULL, NULL, N''Set to Must Finish On when Predecessor is Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69004, @TaskKey, N''Send Notifications'', N''sendNotifications'', NULL, NULL, N''Send Notifications to the user assigned to the task'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Teams
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8854, 56, N''Team Name'', N''teamName'', NULL, N''TeamName'', N''Team Name'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8855, 56, N''User ID'', N''userID'', NULL, N''UserID'', N''User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (56001, 56, N''User Name'', NULL, NULL, N''UserName'', N''User Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Time
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8856, @TimeKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8857, @TimeKey, N''Actual Hours'', N''hours'', NULL, NULL, N''Actual Hours'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8858, @TimeKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8859, @TimeKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8860, @TimeKey, N''Service Code'', N''serviceCode'', NULL, NULL, N''Service Code. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8861, @TimeKey, N''Date'', N''workDate'', NULL, NULL, N''Date'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8862, @TimeKey, N''Comments'', N''comments'', NULL, NULL, N''Comments. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (72100, @TimeKey, N''Overtime'', N''overtime'', NULL, NULL, N''Overtime'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)


 -- Time sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8863, @TimeSheetKey, N''Date'', N''workDate'', NULL, NULL, N''Date'', N''detail'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8864, @TimeSheetKey, N''Start Date & Time'', N''startDate'', NULL, NULL, N''Start Date & Time. May be required based on preferences'', N''header'', 2, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8865, @TimeSheetKey, N''End Date & Time'', N''endDate'', NULL, NULL, N''End Date & Time. May be required based on preferences'', N''header'', 2, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8866, @TimeSheetKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8867, @TimeSheetKey, N''Task ID'', N''taskId'', NULL, NULL, N''Task ID. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8868, @TimeSheetKey, N''Service Code'', N''serviceCode'', NULL, NULL, N''Service Code. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8869, @TimeSheetKey, N''Actual Hours'', N''hours'', NULL, NULL, N''Actual Hours'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8870, @TimeSheetKey, N''Actual Rate'', N''actualRate'', NULL, NULL, N''Actual Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8871, @TimeSheetKey, N''Comments'', N''comments'', NULL, NULL, N''Comments. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8872, @TimeSheetKey, N''Rate Level'', N''rateLevel'', NULL, NULL, N''Rate Level'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8873, @TimeSheetKey, N''Date Billed'', N''dateBilled'', NULL, NULL, N''Date Billed'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8874, @TimeSheetKey, N''Department'', N''departmentKey'', NULL, NULL, N''Department'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8875, @TimeSheetKey, N''Billing Title ID'', N''titleKey'', NULL, NULL, N''Billing Title ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8876, @TimeSheetKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8877, @TimeSheetKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (21001, 21, N''Start Date'', N''startdate'', NULL, NULL, N''These are api only fields... Not used on import'', N''header'', 2, NULL, NULL, NULL, 1, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (21002, 21, N''End Date'', N''enddate'', NULL, NULL, N''These are api only fields... Not used on import'', N''header'', 2, NULL, NULL, NULL, 1, NULL)

-- Time sheet / Complete
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13201, @TimeSheetCompleteKey, N''TimeSheetKey'', N''timesheetKey'', NULL, NULL, N''timesheeetKey'', NULL, 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13202, @TimeSheetCompleteKey, N''Comments'', N''comments'', NULL, NULL, N''Approval Comments'', NULL, NULL, NULL, NULL, NULL, 1, NULL)

-- Time sheet / Reject
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13301, @TimeSheetRejectKey, N''TimeSheetKey'', N''timesheetKey'', NULL, NULL, N''timesheeetKey'', NULL, 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13302, @TimeSheetRejectKey, N''Comments'', N''comments'', NULL, NULL, N''Rejection Comments'', NULL, NULL, NULL, NULL, NULL, 1, NULL)


-- Titles
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8878, 64, N''ID'', N''titleID'', NULL, N''TitleID'', N''ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8879, 64, N''Name'', N''titleName'', NULL, N''TitleName'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8880, 64, N''Hourly Rate'', N''hourlyRate'', NULL, N''HourlyRate'', N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8881, 64, N''Hourly Cost'', N''hourlyCost'', NULL, N''HourlyCost'', N''Hourly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8882, 64, N''Department'', N''departmentName'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8883, 64, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8884, 64, N''Billing Item ID'', N''workTypeID'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8885, 64, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8886, 64, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8887, 64, N''Service Code'', N''serviceKey'', NULL, N''ServiceCode'', N''Service Code'', NULL, NULL, N''ServiceCode'', NULL, NULL, NULL, NULL)
-- Title Rate Sheets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8888, 65, N''Rate Sheet Name'', N''rateSheetName'', NULL, N''RateSheetName'', N''Rate Sheet Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8889, 65, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8890, 65, N''Title ID'', N''titleID'', NULL, N''TitleID'', N''Title ID'', N''detail'', 1, N''TitleID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8891, 65, N''Hourly Rate'', N''hourlyRate'', NULL, N''HourlyRate'', N''Hourly Rate'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
-- To Dos
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84001, @ToDoKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84002, @ToDoKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84003, @ToDoKey, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84004, @ToDoKey, N''To Do Status'', N''status'', NULL, NULL, N''To Do Status'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84005, @ToDoKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84006, @ToDoKey, N''Notify Emails'', N''notifyEmails'', NULL, NULL, N''Notify Emails, separate with ; if multiple'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84007, @ToDoKey, N''To Do Type'', N''type'', NULL, NULL, N''To Do Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84008, @ToDoKey, N''Notes'', N''notes'', NULL, NULL, N''Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84009, @ToDoKey, N''Assigned User ID'', N''assignedUserID'', NULL, NULL, N''Assigned User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84010, @ToDoKey, N''Completed'', N''completed'', NULL, NULL, N''Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Vouchers
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8892, @VoucherKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8893, @VoucherKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8894, @VoucherKey, N''Invoice Date'', N''invoiceDate'', NULL, NULL, N''Invoice Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8895, @VoucherKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date. Required if posting'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8896, @VoucherKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8897, @VoucherKey, N''Date Received'', N''dateReceived'', NULL, NULL, N''Date Received'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8898, @VoucherKey, N''AP Account'', N''apAccountNumber'', NULL, NULL, N''AP Account. Required if GL Account is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8899, @VoucherKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8900, @VoucherKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8901, @VoucherKey, N''Approved By'', N''approvedByName'', NULL, NULL, N''Approved By'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8902, @VoucherKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8903, @VoucherKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8904, @VoucherKey, N''Sales Tax Rate'', N''salesTaxID'', NULL, NULL, N''Sales Tax Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8905, @VoucherKey, N''Sales Tax Rate 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax Rate 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8906, @VoucherKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8907, @VoucherKey, N''Office'', N''officeID'', NULL, NULL, N''Office. Required if Office is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8908, @VoucherKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8909, @VoucherKey, N''Overhead'', N''overhead'', NULL, NULL, N''Overhead'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8910, @VoucherKey, N''Invoice Currency ID'', N''currencyID'', NULL, NULL, N''Invoice Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8911, @VoucherKey, N''Invoice Exchange Rate'', N''invoiceExchangeRate'', NULL, NULL, N''Invoice Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8912, @VoucherKey, N''Project Exchange Rate'', N''projectExchangeRate'', NULL, NULL, N''Project Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8913, @VoucherKey, N''Terms Days'', N''termsDays'', NULL, NULL, N''Terms Days'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8914, @VoucherKey, N''Terms Net'', N''termsNet'', NULL, NULL, N''Terms Net'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8915, @VoucherKey, N''Terms Percent'', N''termsPercent'', NULL, NULL, N''Terms Percent'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8916, @VoucherKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required base on Voucher Type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8917, @VoucherKey, N''Description (Line)'', N''descriptionLine'', NULL, NULL, N''Description (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8918, @VoucherKey, N''GL Account'', N''expenseAccountNumber'', NULL, NULL, N''GL Account. Required if GL Acount is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8919, @VoucherKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8920, @VoucherKey, N''Unit Description'', N''unitDescription'', NULL, NULL, N''Unit Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8921, @VoucherKey, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8922, @VoucherKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8923, @VoucherKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8924, @VoucherKey, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8925, @VoucherKey, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8926, @VoucherKey, N''Amount to Bill'', N''amountToBill'', NULL, NULL, N''Amount to Bill'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8927, @VoucherKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8928, @VoucherKey, N''Taxable'', N''taxable'', NULL, NULL, N''Taxable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8929, @VoucherKey, N''Taxable 2'', N''taxable2'', NULL, NULL, N''Taxable 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8930, @VoucherKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8931, @VoucherKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8932, @VoucherKey, N''Purchase Order Number'', N''purchaseOrderNumber'', NULL, NULL, N''Purchase Order Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8933, @VoucherKey, N''Purchase Order Line Number'', N''purchaseOrderLineNumber'', NULL, NULL, N''Purchase Order Line Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8934, @VoucherKey, N''Last Voucher'', N''lastVoucher'', NULL, NULL, N''Last Voucher'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8935, @VoucherKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8936, @VoucherKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if has a project and task is required on teh project'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8937, @VoucherKey, N''Client ID (Line)'', N''clientID'', NULL, NULL, N''Client ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8938, @VoucherKey, N''Office (Line)'', N''officeID'', NULL, NULL, N''Office (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8939, @VoucherKey, N''Department (Line)'', N''department'', NULL, NULL, N''Department (Line). Required if Department is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8940, @VoucherKey, N''Target GL Company'', N''targetGLCompanyKey'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8941, @VoucherKey, N''Write Off'', N''writeOff'', NULL, NULL, N''Write Off'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8942, @VoucherKey, N''Date Billed'', N''dateBilled'', NULL, NULL, N''Date Billed'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8943, @VoucherKey, N''Amount Billed'', N''amountBilled'', NULL, NULL, N''Amount Billed'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8944, @VoucherKey, N''Flight Start Date'', N''startDate'', NULL, NULL, N''Flight Start Date'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8945, @VoucherKey, N''Flight End Date'', N''endDate'', NULL, NULL, N''Flight End Date'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8946, @VoucherKey, N''Close'', N''close'', NULL, NULL, N''Close'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8947, @VoucherKey, N''Project Currency ID'', N''pCurrencyID'', NULL, NULL, N''Project Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8948, @VoucherKey, N''Project Currency ID (Line)'', N''pCurrencyID'', NULL, NULL, N''Project Currency ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8949, @VoucherKey, N''Project Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Project Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8950, @VoucherKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8951, @VoucherKey, N''Class ID (Line)'', N''classID'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120001, @VoucherKey, N''Project Net Cost'', N''pTotalCost'', NULL, NULL, N''Project Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120002, @VoucherKey, N''Net Cost (HC)'', N''hcTotalCost'', NULL, NULL, N''Net Cost (Home Currency)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120003, @VoucherKey, N''GL Company Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120004, @VoucherKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID, used for selecting appropriate field group'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120005, @VoucherKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID, used for selecting appropriate field group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120006, @VoucherKey, N''Vendor Invoice Type'', N''voucherType'', NULL, NULL, N''Vendor Invoice Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--Vendor Payment
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8952, @VendorPaymentKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, N''VendorID'', 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8953, @VendorPaymentKey, N''Check Number'', N''checkNumber'', NULL, NULL, N''Check Number'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8954, @VendorPaymentKey, N''Check Amount'', N''checkAmount'', NULL, NULL, N''Check Amount'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8955, @VendorPaymentKey, N''Check Date'', N''paymentDate'', NULL, NULL, N''Check Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8956, @VendorPaymentKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8957, @VendorPaymentKey, N''Cash Account Number'', N''cashAccountID'', NULL, NULL, N''Cash Account Number'', N''header'', NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8958, @VendorPaymentKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, N''GLCompanyName'', NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8959, @VendorPaymentKey, N''Pay to Name'', N''payToName'', NULL, NULL, N''Pay to Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8960, @VendorPaymentKey, N''Pay to Address 1'', N''payToAddress1'', NULL, NULL, N''Pay to Address 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8961, @VendorPaymentKey, N''Pay to Address 2'', N''payToAddress2'', NULL, NULL, N''Pay to Address 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8962, @VendorPaymentKey, N''Pay to Address 3'', N''payToAddress3'', NULL, NULL, N''Pay to Address 3'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8963, @VendorPaymentKey, N''Pay to Address 4'', N''payToAddress4'', NULL, NULL, N''Pay to Address 4'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8964, @VendorPaymentKey, N''Pay to Address 5'', N''payToAddress5'', NULL, NULL, N''Pay to Address 5'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8965, @VendorPaymentKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8966, @VendorPaymentKey, N''Unapplied Payment Account Number'', N''unappliedPaymentAccountID'', NULL, NULL, N''Unapplied Payment Account Number'', N''header'', NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8967, @VendorPaymentKey, N''Check Memo'', N''memo'', NULL, NULL, N''Check Memo'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8968, @VendorPaymentKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8969, @VendorPaymentKey, N''GL Account Number'', N''glAccountID'', NULL, NULL, N''GL Account Number'', N''detail'', NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8970, @VendorPaymentKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''detail'', NULL, N''InvoiceNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8971, @VendorPaymentKey, N''Voucher ID'', N''voucherID'', NULL, NULL, N''Voucher ID'', N''detail'', NULL, N''VoucherID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8972, @VendorPaymentKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8973, @VendorPaymentKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8974, @VendorPaymentKey, N''Unit Amount'', N''unitAmount'', NULL, NULL, N''Unit Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8975, @VendorPaymentKey, N''Payment Amount'', N''paymentAmount'', NULL, NULL, N''Payment Amount'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8976, @VendorPaymentKey, N''Discount Amount'', N''discAmount'', NULL, NULL, N''Discount Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8977, @VendorPaymentKey, N''Office'', N''officeID'', NULL, NULL, N''Office. Required if Office is required'', N''detail'', 2, N''OfficeName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8978, @VendorPaymentKey, N''Department'', N''departmentID'', NULL, NULL, N''Department. Required if Department is required'', N''detail'', 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8979, @VendorPaymentKey, N''Exclude from 1099'', N''exclude1099'', NULL, NULL, N''Exclude from 1099'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8980, @VendorPaymentKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''detail'', NULL, N''SalesTaxID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8981, @VendorPaymentKey, N''Target GL Company'', N''targetGLCompanyID'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8982, @VendorPaymentKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8983, @VendorPaymentKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8984, @VendorPaymentKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8985, @VendorPaymentKey, N''Class ID (detail)'', N''classID'', NULL, NULL, N''Class ID (detail). Required if Class is required'', N''detail'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
-- Vendors
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8986, @VendorKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8987, @VendorKey, N''Phone'', N''phone'', NULL, NULL, N''Phone'', NULL, NULL, NULL, 4, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8988, @VendorKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8989, @VendorKey, N''Web Site'', N''webSite'', NULL, NULL, N''Web Site'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8990, @VendorKey, N''Company Address 1'', N''address1'', NULL, NULL, N''Company Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8991, @VendorKey, N''Company Address 2'', N''address2'', NULL, NULL, N''Company Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8992, @VendorKey, N''Company Address 3'', N''address3'', NULL, NULL, N''Company Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8993, @VendorKey, N''Company City'', N''city'', NULL, NULL, N''Company City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8994, @VendorKey, N''Company State'', N''state'', NULL, NULL, N''Company State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8995, @VendorKey, N''Company Postal Code'', N''postalCode'', NULL, NULL, N''Company Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8996, @VendorKey, N''Company Country'', N''country'', NULL, NULL, N''Company Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8997, @VendorKey, N''Folder'', N''folderName'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8998, @VendorKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8999, @VendorKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9000, @VendorKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9001, @VendorKey, N''Default Office'', N''office'', NULL, NULL, N''Default Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9002, @VendorKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID. Required if passing in a vendor'', NULL, 2, NULL, 2, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9003, @VendorKey, N''Overhead Vendor'', N''overheadVendor'', NULL, NULL, N''Overhead Vendor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9004, @VendorKey, N''On Hold'', N''onHold'', NULL, NULL, N''On Hold'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9005, @VendorKey, N''Vendor Downloaded'', N''vendorDownloaded'', NULL, NULL, N''Vendor Downloaded'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9006, @VendorKey, N''Terms Percent'', N''termsPercent'', NULL, NULL, N''Terms Percent'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9007, @VendorKey, N''Terms Days'', N''termsDays'', NULL, NULL, N''Terms Days'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9008, @VendorKey, N''Terms Net'', N''termsNet'', NULL, NULL, N''Terms Net'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9009, @VendorKey, N''Default Expense Account'', N''defaultExpenseAccount'', NULL, NULL, N''Default Expense Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9010, @VendorKey, N''Default AP Account'', N''defaultAPAccount'', NULL, NULL, N''Default AP Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9011, @VendorKey, N''Default AP Approver'', N''defaultAPApprover'', NULL, NULL, N''Default AP Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9012, @VendorKey, N''Default Sales Tax ID 1'', N''vendorSalesTax'', NULL, NULL, N''Default Sales Tax ID 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9013, @VendorKey, N''Default Sales Tax ID 2'', N''vendorSalesTax2'', NULL, NULL, N''Default Sales Tax ID 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9014, @VendorKey, N''1099 Form'', N''type1099'', NULL, NULL, N''1099 Form'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9015, @VendorKey, N''1099 Box'', N''box1099'', NULL, NULL, N''1099 Box'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9016, @VendorKey, N''FATCA Filing Requirement'', N''fATCAFilingRequirement'', NULL, NULL, N''FATCA Filing Requirement'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9017, @VendorKey, N''DBA'', N''dBA'', NULL, NULL, N''DBA'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9018, @VendorKey, N''Print DBA On Checks'', N''useDBAForPayment'', NULL, NULL, N''Print DBA On Checks'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9019, @VendorKey, N''Credit Card Account'', N''ccAccountNumber'', NULL, NULL, N''Credit Card Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9020, @VendorKey, N''Email Credit Card Info To'', N''emailCCToAddress'', NULL, NULL, N''Email Credit Card Info To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9021, @VendorKey, N''Credit Card Payee Name'', N''ccPayeeName'', NULL, NULL, N''Credit Card Payee Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9022, @VendorKey, N''Accepts VPay'', N''vCardAccepted'', NULL, NULL, N''Accepts VPay'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9023, @VendorKey, N''One Payment per Invoice'', N''onePaymentPerVoucher'', NULL, NULL, N''One Payment per Invoice'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9024, @VendorKey, N''EIN Number'', N''eINNumber'', NULL, NULL, N''EIN Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9025, @VendorKey, N''Default Memo'', N''defaultMemo'', NULL, NULL, N''Default Memo'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9026, @VendorKey, N''Payment Address'', N''paymentAddress'', NULL, NULL, N''Payment Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9027, @VendorKey, N''Accepts Credit Cards'', N''ccAccepted'', NULL, NULL, N''Accepts Credit Cards'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9028, @VendorKey, N''Bank Account Number'', N''bankAccountNumber'', NULL, NULL, N''Bank Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9029, @VendorKey, N''Bank Routing Number'', N''bankRoutingNumber'', NULL, NULL, N''Bank Routing Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9030, @VendorKey, N''Name on Bank Account'', N''bankAccountName'', NULL, NULL, N''Name on Bank Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9031, @VendorKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70001, @VendorKey, N''ACH Enabled'', N''achEnabled'', NULL, NULL, N''ACH Enabled'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70002, @VendorKey, N''Company Owner'', N''companyOwner'', NULL, NULL, N''Company Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70003, @VendorKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70004, @VendorKey, N''Email ACH Info To'', N''emailACHToAddress'', NULL, NULL, N''Email ACH Info To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70005, @VendorKey, N''Bank Account Type'', N''bankAccountType'', NULL, NULL, N''Bank Account Type (Checking or Saving)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70006, @VendorKey, N''Company Address Name'', N''addressName'', NULL, NULL, N''Company Address Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Write Off Reasons
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9032, 51, N''Write Off Reason'', N''reasonName'', NULL, N''ReasonName'', N''Write Off Reason'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9033, 51, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9034, 51, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Projects
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9035, 13, N''Invoice Layout'', N''invoiceLayout'', NULL, NULL, N''Invoice Layout'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9037, 13, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9039, 13, N''Anyone to Charge Time'', N''anyoneChargeTime'', NULL, NULL, N''Anyone to Charge Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9040, 13, N''Do Not Post WIP'', N''doNotPostWIP'', NULL, NULL, N''Do Not Post WIP'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Broadcast Orders
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7701, @BOKey, N''BO Number'', N''purchaseOrderNumber'', NULL, NULL, N''BO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7702, @BOKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7703, @BOKey, N''BO Type'', N''purchaseOrderType'', NULL, NULL, N''BO Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7704, @BOKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7705, @BOKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7706, @BOKey, N''BO Date'', N''pODate'', NULL, NULL, N''BO Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77007, @BOKey, N''Flight Start Date'', N''flightStartDate'', NULL, NULL, N''Flight Start Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77008, @BOKey, N''Flight End Date'', N''flightEndDate'', NULL, NULL, N''Flight End Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7709, @BOKey, N''Standard Header Text'', N''headerTextID'', NULL, NULL, N''Standard Header Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7710, @BOKey, N''Standard Footer Text'', N''footerTextID'', NULL, NULL, N''Standard Footer Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7711, @BOKey, N''Approver'', N''approvedBy'', NULL, NULL, N''Approver'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7712, @BOKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7713, @BOKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7714, @BOKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7715, @BOKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company. Required if GL Companies are required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7716, @BOKey, N''Order Description'', N''description'', NULL, NULL, N''Order Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7717, @BOKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7719, @BOKey, N''Office'', N''officeKey'', NULL, NULL, N''Office. Required if Office is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7720, @BOKey, N''Department'', N''departmentID'', NULL, NULL, N''Department. Required if Department is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7721, @BOKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if Item is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7722, @BOKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if Task is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7724, @BOKey, N''Comments'', N''longDescription'', NULL, NULL, N''Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7727, @BOKey, N''Spots'', N''spots'', NULL, NULL, N''Spots'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7728, @BOKey, N''Unit Desc'', N''unitDescription'', NULL, NULL, N''Unit Desc'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7729, @BOKey, N''Commission'', N''markup'', NULL, NULL, N''Commission'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7730, @BOKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7731, @BOKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7733, @BOKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7734, @BOKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7735, @BOKey, N''Currency ID'', N''currencyID'', NULL, NULL, N''Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7736, @BOKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7737, @BOKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7738, @BOKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required.'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7739, @BOKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7740, @BOKey, N''Space Close'', N''spaceClose'', NULL, NULL, N''Space Close'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7741, @BOKey, N''Materials Due'', N''materialsDue'', NULL, NULL, N''Materials Due'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7743, @BOKey, N''User Defined Date 3'', N''userDate3'', NULL, NULL, N''User Defined Date 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7744, @BOKey, N''User Defined Date 4'', N''userDate4'', NULL, NULL, N''User Defined Date 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77077, @BOKey, N''User Defined Date 5'', N''userDate5'', NULL, NULL, N''User Defined Date 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77078, @BOKey, N''User Defined Date 6'', N''userDate6'', NULL, NULL, N''User Defined Date 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77001, @BOKey, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77002, @BOKey, N''Gross Amount'', N''grossAmount'', NULL, NULL, N''Gross Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77003, @BOKey, N''Order Days'', N''orderDays'', NULL, NULL, N''Order Days'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77004, @BOKey, N''Order Time'', N''orderTime'', NULL, NULL, N''Order Time'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77005, @BOKey, N''Order Length'', N''orderLength'', NULL, NULL, N''Order Length'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77006, @BOKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID, used for selecting appropriate field group'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition], [SystemSettingFieldName]) VALUES (77009, @BOKey, N''Station ID'', N''stationID'', NULL, NULL, N''stationID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL, N''BCRequireStations'') 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77010, @BOKey, N''Media Estimate ID'', N''mediaEstimateID'', NULL, NULL, N''Media Estimate ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77011, @BOKey, N''Traffic Instructions'', N''trafficInstructions'', NULL, NULL, N''Traffic Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77012, @BOKey, N''Ordered By'', N''orderedBy'', NULL, NULL, N''Ordered By'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77013, @BOKey, N''Special Instructions'', N''specialInstructions'', NULL, NULL, N''Special Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77014, @BOKey, N''Detail Order Start Date'', N''detailOrderStartDate'', NULL, NULL, N''Detail Order Start Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77015, @BOKey, N''Detail Order End Date'', N''detailOrderEndDate'', NULL, NULL, N''Detail Order End Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77016, @BOKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID, used for selecting appropriate field group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77017, @BOKey, N''Item Name (Program)'', N''shortDescription'', NULL, NULL, N''Item Name (Program)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77018, @BOKey, N''Header ID'', N''headerID'', NULL, NULL, N''Header ID, used for associating header and detail fields when they do not pass in the PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
-- View
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78001, @ViewKey, N''ViewKey'', N''viewKey'', NULL, NULL, N''ViewKey'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78002, @ViewKey, N''Name'', N''name'', NULL, NULL, N''Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78003, @ViewKey, N''ReportType'', N''reportType'', NULL, NULL, N''ReportType'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78004, @ViewKey, N''ReportFilter'', N''reportFilter'', NULL, NULL, N''ReportFilter'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78005, @ViewKey, N''Definition'', N''definition'', NULL, NULL, N''Definition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78006, @ViewKey, N''FieldDefinition'', N''fieldDefinition'', NULL, NULL, N''FieldDefinition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78007, @ViewKey, N''ConditionDefinition'', N''conditionDefinition'', NULL, NULL, N''ConditionDefinition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78008, @ViewKey, N''Private'', N''private'', NULL, NULL, N''Private'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78009, @ViewKey, N''ReportHeading1'', N''reportHeading1'', NULL, NULL, N''ReportHeading1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78010, @ViewKey, N''ReportHeading1Align'', N''reportHeading1Align'', NULL, NULL, N''ReportHeading1Align'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78011, @ViewKey, N''ReportHeading2'', N''reportHeading2'', NULL, NULL, N''ReportHeading2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78012, @ViewKey, N''ReportHeading2Align'', N''reportHeading2Align'', NULL, NULL, N''ReportHeading2Align'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78013, @ViewKey, N''Orientation'', N''orientation'', NULL, NULL, N''Orientation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78014, @ViewKey, N''GroupBy'', N''groupBy'', NULL, NULL, N''GroupBy'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78015, @ViewKey, N''ShowConditions'', N''showConditions'', NULL, NULL, N''ShowConditions'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78016, @ViewKey, N''ReportID'', N''reportID'', NULL, NULL, N''ReportID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78017, @ViewKey, N''GroupByDefinition'', N''groupByDefinition'', NULL, NULL, N''GroupByDefinition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78018, @ViewKey, N''LockedColumns'', N''lockedColumns'', NULL, NULL, N''LockedColumns'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78020, @ViewKey, N''AutoExpandGroups'', N''autoExpandGroups'', NULL, NULL, N''AutoExpandGroups'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78021, @ViewKey, N''ApplicationVersion'', N''applicationVersion'', NULL, NULL, N''ApplicationVersion'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78022, @ViewKey, N''AutoRun'', N''autoRun'', NULL, NULL, N''AutoRun'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78023, @ViewKey, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78024, @ViewKey, N''DisplayType'', N''displayType'', NULL, NULL, N''DisplayType'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78025, @ViewKey, N''TabName'', N''tabName'', NULL, NULL, N''TabName'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78026, @ViewKey, N''DataTargetUpper'', N''dataTargetUpper'', NULL, NULL, N''DataTargetUpper'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78027, @ViewKey, N''DataTargetLower'', N''dataTargetLower'', NULL, NULL, N''DataTargetLower'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78028, @ViewKey, N''MaxItemCount'', N''maxItemCount'', NULL, NULL, N''MaxItemCount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78029, @ViewKey, N''XAxisLabel'', N''xAxisLabel'', NULL, NULL, N''XAxisLabel'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78030, @ViewKey, N''YAxisLabel'', N''yAxisLabel'', NULL, NULL, N''YAxisLabel'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78031, @ViewKey, N''ReportGroupName'', N''reportGroupName'', NULL, NULL, N''ReportGroupName'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78032, @ViewKey, N''XAxisHasCField'', N''xAxisHasCField'', NULL, NULL, N''XAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78033, @ViewKey, N''YAxisHasCField'', N''yAxisHasCField'', NULL, NULL, N''YAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78034, @ViewKey, N''SeriesHasCField'', N''seriesHasCField'', NULL, NULL, N''SeriesHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78035, @ViewKey, N''DefaultReportView'', N''sefaultReportView'', NULL, NULL, N''DefaultReportView'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78036, @ViewKey, N''PivotSettings'', N''pivotSettings'', NULL, NULL, N''PivotSettings'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78037, @ViewKey, N''XAxisHasCField'', N''xAxisHasCField'', NULL, NULL, N''XAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78038, @ViewKey, N''YAxisHasCField'', N''yAxisHasCField'', NULL, NULL, N''YAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78039, @ViewKey, N''SeriesHasCField'', N''seriesHasCField'', NULL, NULL, N''SeriesHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

--Media Plans
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80015, @MediaPlanKey, N''Plan ID'', N''planID'', NULL, N''PlanID'', N''Plan ID'', ''header'', 1, NULL, 1, NULL, 1, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80016, @MediaPlanKey, N''Media Plan Key'', N''mediaPlanKey'', NULL, N''MediaPlanKey'', N''Media Plan Key - only required in PUT'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80017, @MediaPlanKey, N''Plan Name'', N''planName'', NULL, N''PlanName'', N''Plan Name'', ''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80019, @MediaPlanKey, N''Project Number'', N''projectNumber'', NULL, N''ProjectKey'', N''Project number'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80020, @MediaPlanKey, N''Description'', N''description'', NULL, N''Description'', N''Description of the plan'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80021, @MediaPlanKey, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80022, @MediaPlanKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80023, @MediaPlanKey, N''Station ID'', N''stationID'', NULL, N''StationID'', N''Station ID'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80024, @MediaPlanKey, N''Spot Link ID'', N''spotLinkID'', NULL, N''SpotLinkID'', N''The ID of the media buy in your system'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80025, @MediaPlanKey, N''Description (Buy)'', N''description'', NULL, N''Description'', N''The description of the media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80026, @MediaPlanKey, N''Start Date'', N''startDate'', NULL, N''StartDate'', N''The start date of the media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80027, @MediaPlanKey, N''End Date'', N''endDate'', NULL, N''EndDate'', N''The end date of the media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80028, @MediaPlanKey, N''Order Days'', N''orderDays'', NULL, N''OrderDays'', N''Order Days'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80029, @MediaPlanKey, N''Order Time'', N''orderTime'', NULL, N''OrderTime'', N''Order Time'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80030, @MediaPlanKey, N''Order Length'', N''orderLength'', NULL, N''OrderLength'', N''Order Length'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80031, @MediaPlanKey, N''Space Close'', N''spaceClose'', NULL, N''Date1'', N''Space Close'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80032, @MediaPlanKey, N''Materials Due'', N''materialsDue'', NULL, N''Date2'', N''Materials Due'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80033, @MediaPlanKey, N''Quantity'', N''quantity'', NULL, N''Quantity'', N''The number of spots'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80034, @MediaPlanKey, N''Cost'', N''cost'', NULL, N''Cost'', N''The total net of the media buy'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80035, @MediaPlanKey, N''Commission'', N''commission'', NULL, N''Markup'', N''Commission'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80036, @MediaPlanKey, N''Unit Rate'', N''unitRate'', NULL, N''UnitCost'', N''Unit rate'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80037, @MediaPlanKey, N''Gross'', N''gross'', NULL, N''Gross'', N''The total gross of the media buy'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80038, @MediaPlanKey, N''Amount to Bill'', N''amountToBill'', NULL, N''AmountToBill'', N''The amount to bill of the media buy'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80039, @MediaPlanKey, N''Line Number'', N''lineNumber'', NULL, N''LineNumber'', N''The line number of the media buy'', ''detail'', Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80040, @MediaPlanKey, N''Action'', N''action'', NULL, N''Action'', N''The action on the media buy. Only supported action for PUT is delete'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80041, @MediaPlanKey, N''Order Link ID'', N''orderLinkID'', NULL, N''OrderLinkID'', N''The ID of the media buy  order in your system'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80041, @MediaPlanKey, N''Media Plan Detail Key'', N''mediaPlanDetailKey'', NULL, N''MediaPlanDetailKey'', N''Media Buy Key - only required in PUT'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- Media Plan Vouchers
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80050, @MediaPlanVoucherKey, N''Media Plan Vendor Invoice Key'', N''mediaPlanVoucherKey'', NULL, N''MediaPlanVoucherKey'', N''Media Plan Vendor Invoice Key - only required in PUT'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80051, @MediaPlanVoucherKey, N''Plan ID'', N''planID'', NULL, N''mediaPlanKey'', N''Plan ID'', ''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80052, @MediaPlanVoucherKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorKey'', N''Vendor ID'', ''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80053, @MediaPlanVoucherKey, N''Invoice Number'', N''invoiceNumber'', NULL, N''InvoiceNumber'', N''Invoice number'', ''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80054, @MediaPlanVoucherKey, N''Invoice Date'', N''invoiceDate'', NULL, N''InvoiceDate'', N''Invoice Date'', ''header'', 1, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80055, @MediaPlanVoucherKey, N''Media Plan Vendor Invoice Detail Key'', N''mediaPlanVoucherDetailKey'', NULL, N''MediaPlanVoucherDetailKey'', N''Vendor invoice detail Key - only required in PUT'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80055, @MediaPlanVoucherKey, N''Invoice Link ID'', N''invoiceLinkID'', NULL, N''InvoiceLinkID'', N''The ID of the vendor invoice in your system'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80067, @MediaPlanVoucherKey, N''Bottom Line Invoice'', N''bottomLineInvoice'', NULL,N''BottomLineInvoice'', N''Is this a Bottom Line Invoice?'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)

INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80056, @MediaPlanVoucherKey, N''Link ID'', N''linkID'', NULL, N''LinkID'', N''The ID of the media vendor invoice detail in your system'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80057, @MediaPlanVoucherKey, N''Spot Link ID'', N''spotLinkID'', NULL, N''Spot LinkID'', N''The ID of the media buy in your system'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80058, @MediaPlanVoucherKey, N''Description'', N''description'', NULL, N''Description'', N''The description of the vendor invoice detail'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80060, @MediaPlanVoucherKey, N''Cost'', N''appliedCost'', NULL, N''Cost'', N''The total net of the vendor invoice detail'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80065, @MediaPlanVoucherKey, N''Action'', N''action'', NULL, N''Action'', N''The action on the vendor invoice detail. Only supported action for PUT is delete'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80066, @MediaPlanVoucherKey, N''Last Invoice'', N''lastVoucher'', NULL, N''LastVoucher'', N''This indicates that this is the last vendor invoice detail applied to a media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80068, @MediaPlanVoucherKey, N''Order Link ID'', N''orderLinkID'', NULL, N''OrderLinkID'', N''The ID of the order in your system (POST and bottom line invoice only)'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80069, @MediaPlanVoucherKey, N''Invoice Total'', N''invoiceTotal'', NULL, N''InvoiceTotal'', N''The desired invoice total (POST and bottom line invoice only)'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- Media Plan release
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80070, @MediaPlanReleaseKey, N''Spot Link ID'', N''spotLinkID'', NULL, N''SpotLinkID'', N''The ID of the media buy in your system'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)


SET IDENTITY_INSERT [dbo].[tImportExportDetail] OFF

----------------------------------------------------------------------
------- Update Descriptions
----------------------------------------------------------------------
	--1 Contacts
	UPDATE tImportExport SET [Description] = ''Contacts is the location of all the people in the system except for those found in the Leads area. Most will be associated with a Company, but it is not required. You are able to keep track of multiple addresses and other pertinent contact information. You are also able to view a history of each Activity and Meeting associated with the contact.''
	WHERE ImportExportKey = 1

	--3  Employees
	UPDATE tImportExport SET [Description] = ''There are a number of basic fields that need to be entered on the employee record to ensure Projects, Billing and Reporting will contain the correct information for your staff.''
	WHERE ImportExportKey = 3

	--4 Expense Report Items
	UPDATE tImportExport SET [Description] = ''Expense Report items are used on to track and categorize personal expenses incurred on the agency''''s behalf by your staff. These will typically be entered via an Expense Report, but are also available via a Vendor Voucher.''
	WHERE ImportExportKey = 4

	--5 Purchase Items
	UPDATE tImportExport SET [Description] = N''Purchase Items allow you to track and categorize outside expenses for use in Purchase Orders, Vendor Vouchers, Misc. Project Costs and Client Invoices.''
	WHERE ImportExportKey = 5

	--6 GL Accounts
	UPDATE tImportExport SET [Description] = N''The General Ledger Accounts or Chart of Accounts, form the basis of your financial records in the system. By default, Workamajig has a chart of accounts already setup for you. These are based upon industry standards as provided by Second Wind.''
	WHERE ImportExportKey = 6

	 --7 Payment Terms
	 UPDATE tImportExport SET [Description] = ''This area allows you to set the various payment terms that may be used for your client invoices.''
	 WHERE ImportExportKey = 7

	 --8 Sales Tax
	UPDATE tImportExport SET [Description] = N''Sales Tax Rates are used to automatically calculate sales tax amounts on project estimates and client invoices. Sales Tax Rates can also be linked to vendors, so you can automatically determine the amount of sales tax due at the end of the year.''
	WHERE ImportExportKey = 8

	--9 Services
	UPDATE tImportExport SET [Description] = N''Services allows you to track and categorize employee labor for use in Task Assignments, Time Entry, Tracking/Reporting, and Client Invoices.''
	 WHERE ImportExportKey = 9

	--10 Billing Items
	UPDATE tImportExport SET [Description] = ''Billing items allow you to track and organize Services, Purchase Items, Expense Report Items, and Media Items for use in project reporting and Client Invoices. The billing items allow you to group similar services and expenses and create invoice lines based upon these groups. Billing items can also be used as a way to Post Sales Amounts, on an invoice to several sales GL Accounts from a single line item on an invoice''
	WHERE ImportExportKey = 10

	--11 Invoices
	UPDATE tImportExport SET [Description] = N''These can be created manually by Adding a New Client Invoice, or generated based on your client setup and billing process such as Billing Worksheets, Mass Billing or from the individual projects Billing screen. ''
	 WHERE ImportExportKey = 11

	--12 Vendor Invoices
	UPDATE tImportExport SET [Description] = N''The vendor invoice system integrates tightly with the purchase order system so that purchase order details can be easily pulled onto a vendor invoice. It helps the Accounts Payable processing system for recording expenses to projects as well as administrative invoices''
	 WHERE ImportExportKey = 12
	--13 Projects
	UPDATE tImportExport SET [Description] = N''While projects have many aspects to them, the main purpose of a project is to track, and manage timelines that tie directly into employee''''s timesheets, and can then determine how billing is to proceed.'' 
	WHERE ImportExportKey = @ProjectKey


	--16 Estimates
	UPDATE tImportExport SET [Description] = N''In Workamajig, there are two kinds of estimates. There is a Campaign-based estimate and a Project-based estimate. In this section, the project-based estimate will be discussed.''
	WHERE ImportExportKey = 16

	--18 Purchase Order
	UPDATE tImportExport SET [Description] = N''A purchase order is used to tell a vendor that you want to purchase some item; it acts like a contract with the vendor. It is helpful in tracking expenses incurred toward a project. It allows the company to set controls on things like who could purchase items or how much can be spent on something and therefore is good for budgeting and expense tracking purposes''
	WHERE ImportExportKey = 18

	--19 Receipts, aka Client Receipts, aka client payments
	UPDATE tImportExport SET [Description] = ''DEPRECATED 1/1/2019...Please use Receipts end point moving foward.  When entering a receipt, you are able to apply all, or a portion of the amount, towards open client invoices, a designated sales account or leave as an unapplied amount to be applied towards a future invoice.''
	WHERE ImportExportKey = @ClientPaymentsKey

	--20 Vendor Payments
	UPDATE tImportExport SET [Description] = ''Vendor Payments allow you to track how much you actually pay vendors and print checks directly from Workamajig. Payments will usually be created using Menu > Payments > Select Invoices For Payment screen''
	WHERE ImportExportKey = 20

	--21 Timesheets
	UPDATE tImportExport SET [Description] = N''While the Timesheets section from the main menu navigation will give you access to all of your timesheets entered in the system.  For the API to act on behalf of another person you will need the right "View anyone''''s timesheet" or be an administrator.''
	WHERE ImportExportKey = @TimeSheetKey

	--22 Expense Reports
	UPDATE tImportExport SET [Description] = N''Expense Reports are used for staff members to track out of pocket expenses incurred while working on the company''''s behalf. Each line of the expense report is treated much like a Purchase Order, in that it can be tracked to a client project for billing purposes. Following approval, the approver can convert the expense report into a vendor invoice for reimbursement. The vendor used for the vendor invoice is defaulted from the employee record, but ultimately must be specified at the top of the expense report.''
	WHERE ImportExportKey = 22

	--23 Misc Project Costs
	UPDATE tImportExport SET [Description] = N''This area allows you to enter expenses directly into the project. There is no approval process for these items. Typically, Misc Costs are a way to take items that have been purchased in bulk by your agency and associate a portion of the cost towards a client project, such as, stock photography, DVDs/Jewel case, and copies.''
	WHERE ImportExportKey = 23

	--24 Journal Entry
	UPDATE tImportExport SET [Description] = N''Workamajig allows you to create journal entries in order to account for transactions that are not connected to a Client Invoice or Vendor Voucher, such as rent and agency payroll, or to make adjustments to your General Ledger accounts. The Total Debits - Credits: must total $0.00 for the Journal Entry to be posted to the General Ledger.''
	WHERE ImportExportKey = 24

	--25 Project Types
	UPDATE tImportExport SET [Description] = N''Project types allow you to group your projects into different categories for reporting purposes.''
	WHERE ImportExportKey = 25

	--27 Project Status
	UPDATE tImportExport SET [Description] = N''Project status codes are used to determine where a project is in an overall production status.  While each project can have a unique schedule and set of tasks that need to be completed on the project, most projects move through a similar overall flow through the business.''
	WHERE ImportExportKey = 27

	--28 Departments
	UPDATE tImportExport SET [Description] = ''Departments are used to group your information into different functional areas.  Departments can be used on several reports for filtering and grouping data. Departments are global across a company and will be the same from office to office.''
	WHERE ImportExportKey = 28

	--29 Project Billing Status
	UPDATE tImportExport SET [Description] = N''Project billing status codes are most commonly used to help determine where a project is in the billing cycle.  The project billing status code can also be used to flag the accounting group as to which projects should be billed and when they should be billed.''
	WHERE ImportExportKey = 29

	--31 Broadcast items
	UPDATE tImportExport SET [Description] = ''Broadcast Items are used to categorize your purchases of different types of broadcast purchases. These would typically include Radio and Television. The item is also used to expense the purchase to the correct expense account when a vendor invoice is billed and WIP is tracked in the general ledger.''
	WHERE ImportExportKey = 31

	--32 Print Items
	UPDATE tImportExport SET [Description] = N''Print Items are used to categorize your purchases of different types of Print purchases. These would typically include Magazine, Newspaper and Outdoor. The item is also used to expense the purchase to the correct expense account when a vendor invoice is billed and WIP is tracked in the general ledger.''
	WHERE ImportExportKey = 32

	--33 GL Companies
	UPDATE tImportExport SET [Description] = N''Workamajig has always supported multiple GL Companies as a way of segregating data into specific GL Companies for tracking and reporting purposes.  Recently, the ability to handle Intercompany transactions was added to further advance the multiple company capabilities and in doing so, the need to secure data by GL Company became necessary. The Security and Access settings are only necessary if GL Companies are being used and access to data for specific companies needs to be secured for users.''
	WHERE ImportExportKey = 33

	--34 Insertion Orders
	UPDATE tImportExport SET [Description] = N''Insertion Orders are like Purchase Orders used to place orders to Publications. Insertion Orders are entered using the gross amount and a commission percentage to determine the net amount. Insertion orders also allow you to track user definable dates on each line item of the order.''
	WHERE ImportExportKey = 34

	--36 Leads
	UPDATE tImportExport SET [Description] = N''Leads is the area of Workamajig used to track your pre-sales efforts. A lead is considered a non-qualified contact, either client or vendor. A Lead record consists of contact information at the personal and company level. Lead records are created individually, via import or via the Web to Leads feature. You are also able to track the communication history. Once a Lead has been qualified, the Lead can be converted into a Contact/Company record. ''
	WHERE ImportExportKey = 36

	--37 Companies
	UPDATE tImportExport SET [Description] = ''The Company area includes all Companies in your system, including Clients and Vendors. This area will not include any data from the Leads area. To prevent duplication of Company and Contacts, it is recommended that you first create a company, then add contacts via the new company: Contacts area.''
	WHERE ImportExportKey = 37

	--38 Opportunities
	UPDATE tImportExport SET [Description] = N''The purpose of an Opportunity is to serve as a starting point and a tracing of your project proposal. It allows you to convert to a working project.''
	WHERE ImportExportKey = 38

	--39 Activities
	UPDATE tImportExport SET [Description] = ''An activity in Workamajig is used to document "touch points" regarding Clients, Vendors, Opportunities, Projects, and Leads. You are able to notify multiple people and link the activity to multiple projects, contacts, companies, etc. to increase the visibility of the necessary information your staff needs to get their job done.''
	WHERE ImportExportKey = 39

	--40 Report Groups
	UPDATE tImportExport SET [Description] = N''Report groups are used to organize different custom reports in the system.  On the reports page, the system allows you to create an unlimited number of custom reports.  You can set up different report groups here to better organize your custom reports.''
	WHERE ImportExportKey = 40

	--41 Opportunity Stages
	UPDATE tImportExport SET [Description] = N''Opportunity stages allow you to create a sales funnel through which you can track your different opportunities and determine which state in the sales process they are currently at.''
	WHERE ImportExportKey = 41

	--42 Opportunity Status
	UPDATE tImportExport SET [Description] = N''Opportunity Status allows you to define the status of the opportunity. Typical settings are Postponed, Closed or Open.''
	WHERE ImportExportKey = 42

	--43, N''Opportunity Outcome
	UPDATE tImportExport SET [Description] = N''When tracking opportunities in the contact management system, you can use opportunity outcomes to categorize the outcome of each opportunity you enter into the system.  This can give you valuable information on your conversion statistics, as well as, how many opportunities you win versus lose, and the reasons for winning and losing them.''
	WHERE ImportExportKey = 43

	--44 Company Types
	UPDATE tImportExport SET [Description] = ''Company types are used in contact management to segment your contact database. Company types can be used to quickly find different types of companies, vendors or clients. You can add as many company types as you would like and then use them in custom listings and reports.''
	WHERE ImportExportKey = 44

	--45 Meeting Types
	UPDATE tImportExport SET [Description] = ''These apply to calendar meetings in Workamajig and allow you to define the meeting without having to include this in the subject of the meeting.''
	WHERE ImportExportKey = 45

	--46 Calendar Resources  
	UPDATE tImportExport SET [Description] = ''This section contains a list of calendars associated with the various resources you need to schedule, Ex. conference rooms and OHPs.''
	WHERE ImportExportKey = 46

	-- 48 Sources  
	UPDATE tImportExport SET [Description] = N''Source is ultimately seen as being connected to a Company record. You are able to select a Source via a Lead record:Company Info area or from the Company record:Company Info area.  After defining the Source,  you are able to use this field for reporting and grouping of records in the listing screens and reports associated with Leads, Contacts, Companies, and Opportunities. ''
	WHERE ImportExportKey = 48

	-- 49 Conversation Types 
	UPDATE tImportExport SET [Description] = ''This allows you to create a custom dropdown when using Activities and Diary posts. The main benefit being that you can run reports based on which type was chosen by the one creating the activity or Diary post.''
	WHERE ImportExportKey = 49

	 -- 50 Payment Methods  
	UPDATE tImportExport SET [Description] = N''Payment methods are used to categorize receipts from clients. Typical options would include check, cash, credit card, EFT.''
	WHERE ImportExportKey = 50

	 -- 51 Write Off Reasons 
	UPDATE tImportExport SET [Description] = N''When closing out transactions on a project, you have several Form Actions to choose from: Bill Selected Items, Mark as Billed, or Write Them Off (to name just a few). When you write off the transaction in the billing worksheet, it does not have a direct impact on the general ledger unless you are??re tracking work in progress in the ledger''
	WHERE ImportExportKey = 51

	  -- 52 Standard Text  
	  UPDATE tImportExport SET [Description] = N''This is simply where you can create a Header and/or Footer Text that is then selectable for each order.''
	 WHERE ImportExportKey = 52

	  -- 53 Media Markets  
	  UPDATE tImportExport SET [Description] = ''Media Markets are used to track stations and publications to different areas of the country, and can be used when reporting on purchases.''
	  WHERE ImportExportKey = 53

	  -- 54 GL Classes  
	  UPDATE tImportExport SET [Description] = N''GL classes are used to segment transactions posted to the general ledger.  They can be used for several different types of needs.  The most common use of classes is to segment transactions by company, department or office.  When entering transactions such as vendor invoices or client invoices, you can select different classes on each transaction at the header and the line. When the transaction is posted to the general ledger, the system will add the class from the transaction on each entry that is posted.  When running your financial reports, you will be able to filter the transactions on the report by class.''
	  WHERE ImportExportKey = 54

	  -- 55 Offices  
	  UPDATE tImportExport SET [Description] = N''Workamajig allows you to separate out Employees, Projects and project file access using office. This can be useful when reporting on chargeability and project profitability reports and controlling access to your file storage server. Offices will flow through to the general ledger when posting transactions''
	  WHERE ImportExportKey = 55

	  -- 56 Teams  
	  UPDATE tImportExport SET [Description] = N''These are referred to as Account Teams in Client and Project setup.''
	  WHERE ImportExportKey = 56

	  -- 57 Credit Card Charges 
	  UPDATE tImportExport SET [Description] = ''The Credit Card Charges feature under the Purchasing menu allows you to pay vendor invoices using a credit card, add credit card charges for purchases, reconciling credit card statements and pay your credit card bills.  You can setup a supported provider to automatically download credit card charges, import .ofx files from the credit card, or setup an import file to quickly import numerous credit card charges at once.''
	  WHERE ImportExportKey = 57

	   -- 58 Service Rate Sheets  
	   UPDATE tImportExport SET [Description] = N''Service Rate Sheets allow you to create multiple billing rates for your services. A Service Rate Sheet can be pre-assigned to the client to be used as a default for the clients projects (additional workflow setup required). This can also be used for creating Rush Rates, etc''
	   WHERE ImportExportKey = 58

	   -- 59 Item Rate Sheets  
	   UPDATE tImportExport SET [Description] = N''Purchase Item Rate Sheets are used to standardize markups for items for different clients. Item rate sheets work the same way as service rate sheets. You can set different markups for the same item on each rate sheet and then on each project, select a different rate sheet based on the client.''
	   WHERE ImportExportKey = 59

	   -- 60 Financial Budgets  
	   UPDATE tImportExport SET [Description] = N''Workamajig allows for Financial Budgets to be put into the system at a number of different levels. The budget can be used for comparison purposes when running your P&L financial reports. The following dimensions can be defined on your financial budget: GL Company, Office, Department, GL Class and Client.''
	   WHERE ImportExportKey = @GLBudget

	   -- 61 Billing Groups  
	   UPDATE tImportExport SET [Description] = N''This feature is used to group together projects for billing purposes. Though the same Billing Group can be used to identify projects across multiple projects, Workamajig will generate a Master Billing Worksheet for each client and each Billing Group identified on the individual client projects.''
	   WHERE ImportExportKey = 61

	   -- 62 Credit Card Transactions  
	   UPDATE tImportExport SET [Description] = N''The purpose of the connector is to allow you a chance to review and code your incoming charges to the correct project and other settings.''
	   WHERE ImportExportKey = 62

	   -- 63 Currency Rates  
	   UPDATE tImportExport SET [Description] = N''When entering transactions in foreign currencies, a default currency rate is pulled from a table in the database. You can manage your own exchange rates under the Admin or System Setup/GL Settings/Currency Rates screen''
	   WHERE ImportExportKey = 63

	   -- 64 Titles  
	   UPDATE tImportExport SET [Description] = N''A service is what is being performed by the user. Think of them as job titles.''
	   WHERE ImportExportKey = 64

	   -- 65 Title Rate Sheets  
	   UPDATE tImportExport SET [Description] = N''Service Rate Sheets allow you to create multiple billing rates for your services. A Service Rate Sheet can be pre-assigned to the client to be used as a default for the clients projects (additional workflow setup required). This can also be used for creating Rush Rates, etc. ''
		WHERE ImportExportKey = 65

	   -- 67 Request Reject Reasons  
	   --UPDATE tImportExport SET 
	 	 --  WHERE ImportExportKey = 67

	   -- 69 Tasks  
	   UPDATE tImportExport SET [Description] = N''Master Tasks are used to create a standard list of tasks that are used on each project. Each master task can have assignments underneath it. On a master task, you can specify default accounting information and description of work performed. Keep in mind that when using master tasks, you can only enter a task once onto the project, so you may need a Review 1, or a Review 2 set of tasks if you commonly repeat certain activities.''
		WHERE ImportExportKey = 69

	   -- 70 Vendors  
	   UPDATE tImportExport SET [Description] = ''The Vendors section within Purchasing is designed to only pull the results of "companies" that are flagged as a vendor, in the company > vendor setup screen.''
		WHERE ImportExportKey = 70

	   -- 71 Clients 
	    UPDATE tImportExport SET [Description] = ''Client refers to the term of a company record that is setup as a client.''
		WHERE ImportExportKey = @ClientKey

	   -- 72 Time  
	   UPDATE tImportExport SET [Description] = N''While the Timesheets section from the main menu navigation will give you access to all of your timesheets entered in the system.  For the API to act on behalf of another person you will need the right "View anyone''''s timesheet" or be an administrator.''
	   WHERE ImportExportKey = @TimeKey

	   -- 73 Project Spec Sheets  
	   UPDATE tImportExport SET [Description] = N''Spec Sheets have a variety of uses, they can be applied to a Project, Project Request, Opportunity, Purchase Order. However they must have a layout defined, this is done by going to Menu > Admin > System Setup > Tracking > Define Spec Sheets.''
		WHERE ImportExportKey = 73

	   -- 74 Request Spec Sheets  
	   UPDATE tImportExport SET [Description] = N''Spec Sheets have a variety of uses, they can be applied to a Project, Project Request, Opportunity, Purchase Order. However they must have a layout defined, this is done by going to Menu > Admin > System Setup > Tracking > Define Spec Sheets.''
		WHERE ImportExportKey = 74

	   -- 75 Labor Budgets  
	   UPDATE tImportExport SET [Description] = ''Labor Budgets allow you to plan the amount of hours and billable dollars your staff will generate during the year. This is helpful for forecasting labor revenue when people may work more than a standard work week. These labor budgets are then used in the Chargeability Reports and Widgets.''
		WHERE ImportExportKey = 75

	   -- 76 Project Request  
	   UPDATE tImportExport SET [Description] = N''Project Requests allow your team and clients to initiate a request for something to be done by your team. You can define multiple Project Request forms, and in addition to our standard fields, you can add Custom Fields to the initial form and link pre-built specification sheets as the additional pages to fill out''
	 	   WHERE ImportExportKey = 76

	   -- 77 Broadcast Orders  
	   UPDATE tImportExport SET Description = ''Broadcast Orders are like Purchase Orders used to place orders to Stations for broadcasting. Broadcast Orders are entered by spots for each ad, either on a weekly, daily or summary basis using the gross amount and a commission percentage to determine the net amount. Broadcast orders also allow you to track user definable dates on each line item of the order.''
	   WHERE ImportExportKey = 77

	   --79 Address
	   UPDATE tImportExport SET Description = ''Address represents the phsyical location of a company''
	   WHERE ImportExportKey = @AddressKey

	   --80 Deliverables
	   UPDATE tImportExport SET Description = N''Digital artwork internally for review before sending to your clients for their comments''
	   WHERE ImportExportKey = @DeliverableKey

	   --100 Opportunties/List
		UPDATE tImportExport SET [Description] = N''The purpose of an Opportunity is to serve as a starting point and a tracing of your project proposal. It allows you to convert to a working project.''
		WHERE ImportExportKey = 100

		--109 Reports
		UPDATE tImportExport SET [Description] = N''The purpose of Reports is to pull data out of workamajig.''
		WHERE ImportExportKey = @ReportKey

		--115 Receipts, - replaceing client payments 1/1/2020
		UPDATE tImportExport SET [Description] = ''When entering a receipt, you are able to apply all, or a portion of the amount, towards open client invoices, a designated sales account or leave as an unapplied amount to be applied towards a future invoice.''
		WHERE ImportExportKey = @ReceiptsKey

		--118 Retainer
		UPDATE tImportExport SET [Description] = ''Client Retainers.''
		WHERE ImportExportKey = @RetainerKey

	--127 Project Staff Rates
	UPDATE tImportExport SET [Description] = N''The purpose of project staff rates is to update the hourly rates per user on a project that has the Get Rate From = Project User to a custom amount.  The PUT is the only method that works with this endpoint because you can only edit, not create staff rates.'' 
	WHERE ImportExportKey = @ProjectStaffRatesKey

		---------------------------------------------------------
		--tImportExportParms
		---------------------------------------------------------
		DELETE From [tImportExportParms]
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''id'', N''Project ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''key'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''projectkey'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''searchFor'', N''search for'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''searchField'', N''search field, including "projectnumber", "projectname", "companyname", "campaignname", "description"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeTeam'', N''Include project team, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''all'', N''include all details, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeDiary'', N''include diary, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeTodos'', N''include To Do''''s, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeTasks'', N''include Tasks, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeMiscCosts'', N''include Misc Costs, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeEstimates'', N''include Estimates, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeEstimateData'', N''include Estimate Data dataset, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeSpecSheets'', N''include Spec Sheets, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeSpecSheetData'', N''Project Spec Sheet Data dataset, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (39, N''activityKey'', N''Activity Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (61, N''billingGroupKey'', N''Billing Group Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (10, N''workTypeKey'', N''Billing Item Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (31, N''broadcastItemKey'', N''Broadcast Item Key'')
		--77 broadcast order
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@BOKey, N''searchfor'', N''will search what you enter in PO number, project, or vendor'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@BOKey, N''orderKey'', N''Broadcast Order Key'')

		--33 GL Company
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (33, N''glCompanyKey'', N''GL Company Key'')
		
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (46, N''calendarResourceKey'', N''Calendar Resource Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ClientPaymentsKey, N''checkKey'', N''Check Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ClientPaymentsKey, N''clientID'', N''Client ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ClientKey, N''companyKey'', N''Client Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (37, N''companyKey'', N''Company Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (44, N''companyTypeKey'', N''Company Type Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (1, N''search'', N''search fields: "name", "companyKey", "getFavorites", "getRecents", "dateUpdated"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (1, N''contactKey'', N''contact Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (49, N''activityTypeKey'', N''Activity Type Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (57, N''voucherKey'', N''Voucher Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (62, N''glAccountKey'', N''GL Account Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CurrencyRateKey, N''currencyID'', N''Currency ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CurrencyRateKey, N''startDate'', N''Start Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CurrencyRateKey, N''endDate'', N''End Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (28, N''departmentKey'', N''Department Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (3, N''employeeKey'', N''Employee Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (3, N''showInactive'', N''search Inactive'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (16, N''estimateKey'', N''Estimate Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (4, N''expenseReportItemKey'', N''Expense Report Item Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (22, N''expenseReportKey'', N''Expense Report Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@GLBudget, N''glBudgetKey'', N''GL Budget Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@GLAccountKey, N''glAccountKey'', N''GL Account Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@GLAccountKey, N''glAccountNumber'', N''GL Account Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (54, N''ClassKey'', N''Class Key'')
		
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@IOKey, N''searchfor'', N''will search what you enter in PO number, project, or vendor'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@IOKey, N''purchaseOrderKey'', N''Purchase Order Key'')

		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@InvoiceKey, N''invoiceNumber'', N''Invoice Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ItemRateSheetKey, N''itemRateSheetKey'', N''Item Rate Sheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (24, N''search'', N''Search'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (24, N''journalEntryKey'', N''Journal Entry Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (75, N''laborBudgetKey'', N''Labor Budget Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (36, N''userLeadKey'', N''User Lead Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (53, N''mediaMarketKey'', N''Media Market Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (23, N''projectNumber'', N''Project Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (23, N''miscCostKey'', N''Misc Cost Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (55, N''officeKey'', N''Office Key'')
		--INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (38, N''list'', N''List all opportunities, "type", "range"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (38, N''opportunityKey'', N''Opportunity Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (38, N''id'', N''Opportunity ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (43, N''opportunityOutcomeKey'', N''Opportunity Outcome Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (41, N''opportunityStageKey'', N''Opportunity Stage Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (42, N''opportunityStatusKey'', N''Opportunity Status Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (50, N''paymentMethodKey'', N''Payment Method Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (7, N''paymentTermsKey'', N''Payment Terms Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (32, N''printItemKey'', N''Print Item Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (29, N''projectBillingKey'', N''Project Billing Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (73, N''specID'', N''Spec Sheet ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (27, N''projectStatusKey'', N''Project Status Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (25, N''projectTypeKey'', N''Project Type Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (5, N''ItemID'', N''Item ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@POKey, N''searchfor'', N''will search what you enter in PO number, project, or vendor'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@POKey, N''purchaseOrderKey'', N''Purchase Order Key'')

		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (40, N''reportGroupKey'', N''Report Group Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectRequestKey, N''requestKey'', N''Request Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (74, N''specID'', N''Request Spec ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (8, N''salesTaxKey'', N''Sales Tax Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ServiceRateSheetKey, N''serviceRateSheetKey'', N''Service Rate Sheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (48, N''sourceKey'', N''Source Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (52, N''standardTextKey'', N''Standard Text Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''projectKey'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''includeTaskUser'', N''Include Task User, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''projectNumber'', N''Project Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''taskKey'', N''Task Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (56, N''teamKey'', N''Team Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (56, N''userId'', N''UserID of a team member'')
		-- 72 time
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''timesheetKey'', N''Timesheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''timeKey'', N''Time Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''status'', N''Status valid status include "unsubmitted", "submitted", "rejected", "approved"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''userKey'', N''User Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''startdate'', N''Start Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''enddate'', N''End Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''includeService'', N''Include Service'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''includeTime'', N''include Time'')
		--21 timesheet
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''timesheetKey'', N''Timesheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''status'', N''Status valid status include "unsubmitted", "submitted", "rejected", "approved"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''userKey'', N''User Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''startdate'', N''Start Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''enddate'', N''End Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''includeService'', N''Include Service, enter 1'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''includeTime'', N''Include Time, enter 1'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (65, N''titleRateSheetKey'', N''Title Rate Sheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (64, N''titleKey'', N''Title Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@VoucherKey, N''voucherKey'', N''Voucher Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@VendorPaymentKey, N''paymentKey'', N''Payment Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (70, N''companyKey'', N''Company Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (51, N''writeOffReasonKey'', N''Write Off Reason Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (5, N''itemID'', N''Purchase Item ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@AddressKey, N''addressKey'', N''Address Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@DeliverableKey, N''deliverableID'', N''Deliverable ID'')
		-- 84 to do
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ToDoKey, N''todokey'', N''To Do Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ToDoKey, N''projectkey'', N''Project Key'')
		--100 opportunities/list
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (100, N''type'', N''types include "byStage", "byLevel" and "byNeglected" '')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (100, N''range'', N''for "byStage", will be stage lead stage key, for "byLevel", 1:Unaware 2:Contemplating   3:Planning  4:Action,<br> for "byNeglected" 1: last 7 days, 2: last 30 days, 3 older than 30 days'')
		--101 activities/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (101, N''date'', N''activity date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (101, N''mode'', N''"today","thisweek", "unread", "open", "favorites"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (101, N''dateupdated'', N''activity date updated'')
		--102 companies/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''text'', N''searches company name, parent company name, vendor ID and client ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''getFavorites'', N''getFavorites - enter 1 to include your favorites'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''getRecents'', N''getRecents - enter 1 to include your recents'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''dateUpdated'', N''dateUpdated'')
		--103 contacts/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''name'', N''name'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''getFavorites'', N''getFavorites - enter 1 to include your favorites, only use with name, dateupdated or companyKey'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''getRecents'', N''getRecents - enter 1 to include your recents, only use with name, dateupdated or companyKey'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''dateUpdated'', N''dateUpdated'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''companyKey'', N''Company Key'')
		--104 employees/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''name'', N''Name. Can only search for one per request: name, email or userID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''showInactive'', N''Show Inactive employees'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''email'', N''employees email. Can only search for one per request: name, email or userID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''userID'', N''employees UserID. Can only search for one per request: name, email or userID '')
		--105 journalentries/search
		--Not yet implemented
		--106 leads/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''name'', N''lead name'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''getFavorites'', N''getFavorites - enter 1 to include your favorites, only use with name, dateupdated or companyKey'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''getRecents'', N''getRecents - enter 1 to include your recents, only use with name, dateupdated or companyKey'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''dateUpdated'', N''dateUpdated'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''companyKey'', N''Company Key'')
		--107 timesheets/time
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeSheetTimeKey, N''workdatemin'', N''start date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeSheetTimeKey, N''workdatemax'', N''end date'')
		--108 vendors/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''text'', N''will search company name and vendor ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''getFavorites'', N''getFavorites - enter 1 to include your favorites'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''getRecents'', N''getRecents - enter 1 to include your recents'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''dateUpdated'', N''dateUpdated'')
		--109 Reports
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReportKey, N''ReportKey'', N''ReportKey, also the API Access Key from setting screen of the view/report'')
		--111 Media Plans
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@MediaPlanKey, N''planID'', N''Plan ID'')
		--112 Media Plan Vouchers
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@MediaPlanVoucherKey, N''vendorID'', N''Vendor ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@MediaPlanVoucherKey, N''invoiceNumber'', N''InvoiceNumber'')
		--115 Receipts
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''receiptKey'', N''Receipt Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''clientID'', N''Client ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''depositID'', N''Deposit ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''referenceNumber'', N''Reference Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''receiptDate'', N''Receipt Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''invoiceNumber'', N''Invoice Number'')
		--116 Conversation
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationKey, N''conversationKey'', N''Conversation Key'')
		--118 Retainer
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationKey, N''retainerKey'', N''Retainer Key'')
		--120 PUblication
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@PublicationKey, N''publicationKey'', N''Publication Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@PublicationKey, N''publicationID'', N''Publication ID'')
		--122 Station
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@StationKey, N''stationKey'', N''Station Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@StationKey, N''stationID'', N''Station ID'')

		--124 Campaign
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CampaignKey, N''campaignKey'', N''Campaign Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CampaignKey, N''campaignID'', N''Campaign ID'')

		--127 Project Staff Rates
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectStaffRatesKey, N''projectKey'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectStaffRatesKey, N''projectNumber'', N''Project Number'')

		--131 Conversations/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''date'', N''activity date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''mode'', N''"today","thisweek", "unread", "open", "favorites"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''dateupdated'', N''activity date updated'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''projectNumber'', N''project number'')

		--135 Billing Schedule
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@BillingScheduleKey, N''billingScheduleKey'', N''Billing Schedule Key'')
exec sptImportExportSamplesSeedDoco

/*
|| 04/28/18		MCM 18.5.0.0 Created when removed doco fields from convert app seed
|| 05/03/18		MCM 18.5.0.0 Adding in Description field values\\

|| 01/24/18     MCM 19.0.2.0 Moving data from convertAppSeed since really belong in different locations
|| 01/25/18     MCM 19.0.0.0 (442119) Added Address Info
|| 02/08/19     MCM 19.0.3.0 (441055) Change name from client payments to client receipts
|| 02/20/19     MCM 19.0.3.0 (444534) Added Exclude 1099 to the credit card charges
|| 03/14/19     MCM 19.0.4.0 (450619) Added estimateLaborTaxable to the clients 
|| 05/16/19     MCM 19.0.6.0 (454943) Added void and get by Client ID for the client payments
|| 05/22/19     RLS 19.0.6.0 (459855) Added UserName to Teams
|| 06/27/19     MCM 19.0.7.0 (467154) Added Opportunity ID to the parmaters
|| 07/08/19     MCM 19.0.8.0 (465477) Added Opportunity ID as input field for Imports and we''ll match on it.
|| 08/15/19     MCM 19.0.9.0 (435391) Added Approved to be a link field on the timesheet import
|| 08/23/19     MCM 19.0.9.0 (475644) Added custom field header info for PO, IO and BO.
|| 09/12/19     MCM 19.1.0.0 (435391) Made workDate a link field for Timesheet
|| 09/19/19     MCM 19.1.0.0 (435391) Removed billing title and department from the timesheet import
|| 09/23/19     MCM 19.1.0.0 (476967) Added deliverable information
|| 09/25/19     GHL 19.1.0.0 Added media plan + media plan voucher doco fields
|| 10/10/19     MCM 19.1.1.0 (481271) Added receipts endpoint and started phasing out client payments
|| 10/21/19     GHL 19.1.1.0 (484211) Removed tMediaPlan.POKind, added tMediaPlanVoucherDetail.LastVoucher
|| 10/28/19     MCM 19.1.1.0 (465486) Added client division and client product to the opportunity import
|| 10/29/19     MCM 19.1.1.0 (468646) Added the Service Description for service rate sheet export
|| 11/04/19     MCM 19.1.2.0 (484799) Fixed spelling of address Name on the address import
|| 11/18/19     MCM 19.1.2.0 (488559) Fixed [DBFieldName] of ''Unit Rate'' to ''UnitRate'' having ImportExportDetailKey of 32001
|| 11/26/19     MCM 20.0.1.0 (489864) Added project status active field
|| 12/02/19     GHL 20.0.1.0 Added media plan release function
|| 12/19/19     RLS 20.0.1.0 (493105) Made NotifyEmail required for ProjectRequest
|| 12/27/19     MCM 20.0.1.0 (492818) Adding the diary endpoint
|| 12/30/19     GHL 20.0.1.0 Made media plans available for import
|| 01/07/20     GAR 20.0.2.0 (488171) Added project manager to the clients and companies imports
|| 01/09/20     GHL 20.0.2.0 Changes to media plans
|| 01/15/20     MCM 20.0.2.0 (496824) Fix the comments line field on the expense report
|| 01/22/20     MCM 20.0.2.0 (49218) Chaning info from diary endpoint to conversation Endpoint
|| 01/24/20     MCM 20.0.2.0 (494033) Updated GL Account comments for none if want to remove subaccount
|| 02/10/20     MCM 20.0.3.0 (501147) Fixed spelling and made @Client
|| 02/13/20     GHL 20.0.3.0 Removed keys for the API media plan updates (we use IDs now)
|| 02/13/20     MCM 20.0.3.0 (501440) Change PO, classKey to classID
|| 02/17/20     GHL 20.0.3.0 Setting MatchRow and Put on media plans/media plan vouchers to use in Update mode
|| 02/21/20     MCM 20.0.3.0 (496256) Adding the project manager to the projects
|| 02/28/20     MCM 20.0.4.0 (504341) Added @timeKey
|| 05/01/20     MCM 20.0.6.0 (501819) Added posted to the Journal Entry to automatically post the entry
|| 06/01/20     MCM 20.0.7.0 (517369) Added skipApprovalProcess to the Project Request update
|| 06/19/20     MCM 20.0.7.0 (518055) Added defaultFFLineFormat to the Client import
|| 06/24/20     MCM 20.0.7.0 (520218) Added info about employee service delimiter a '';''
|| 06/25/20     MCM 20.0.7.0 (519140) Added ''|DeliverableType'' to CustomFieldEntity in order for all custom fields to show up
|| 07/07/20     GHL 20.0.8.0 Added OrderLinkID, InvoiceLinkID, BottomLineInvoice, InvoiceTotal to media plans 
|| 07/14/20     MCM 20.0.8.0 (521779) Updated Opportunity ID desecription.
|| 07/17/20     MCM 20.0.8.0 (522660) Added template and getMarkupFrom as a field for the project import
|| 07/28/20     MCM 20.0.8.0 (479239) Added to do info
|| 07/31/20     MCM 20.0.9.0 (522660) Added Project fields
|| 09/03/20     MCM 20.0.9.0 (528216) Updated task perc comp seperate description to indicate it goes to "Track Actual Dates for Each Person"
|| 09/11/20     MCM 20.1.0.0 (529111) Updated project Rate Sheet from timeRateSheetKey to ratesheet.
|| 10/09/20     MCM 20.1.1.0 (531998) Added Predecessors to the task import
|| 10/23/20     MCM 20.1.1.0 (534675) Added ACHEnabled to the vendor Import
|| 10/26/20     MCM 20.1.1.0 (522683) Added Retainer Import
|| 10/28/20     MCM 20.1.1.0 (531964) Added company owner to vendor, updated field to be company owner on client and company from contactOwner
|| 11/13/20     MCM 20.1.2.0 (536745) Added invoiceExcludeAttachment to contacts
|| 11/16/20     MCM 20.1.2.0 (537251) Added notifyEmails to the ToDo''s
|| 04/07/21     MCM 21.04.18 (554094) Added toDoType to the ToDo''s
|| 04/19/21	    MCM 21.05.16 (551714) Added Stations and Publications
|| 05/27/21	    MCM 21.06.20 (556803) Added Campaigns
|| 06/09/21     MCM 21.07    (561292) Added Project Export Info
|| 06/24/21     MCM 21.07    (562794) Added copy campaign fields
|| 06/28/21     MCM 21.07    (560843) Updated Campaigns so that the segment supports add/update/delete
|| 06/29/21     GHL 21.07    (563439) Cleaned up duplicates/descriptions for currency on vendor invoices 
|| 07/09/21     MCM 21.07    (563565) Added Supervisor Name to the employee import
|| 07/16/21     GHL 21.08    (565228) Added Net Cost (HC) hcTotalCost to Vendor Invoices 
|| 07/16/21     GHL 21.08    (565228) Added Total Amount (HC) hcTotalAmount to Client Invoices 
|| 07/19/21     MCM 21.08    (565174) Added forecastAsFixedFee to project import
|| 07/22/21		MCM 21.08	 (563565) Added Get Campaign by ID
|| 08/12/21     MCM 21.09    (568099) Made the PO Linked fields required
|| 09/29/21		MCM 21.10.17 (571693) added ebitda to the glaccounts
|| 11/19/21		QMD 21.12.19 (577998) changed timesheet verbage
|| 11/23/21     MCM 21.12.19 (578655) added possible values for oneinvoiceper
|| 12/07/21		MCM 21.12.19 (579940) added classID to the invoice header and details
|| 01/10/22     MCM 22.02.   (581894) Added conversations
|| 01/19/22     MCM 22.02.   (583018) Added Vendor Cost to the Employee endpoint
|| 02/01/22		MCM 22.02.	 (585206) Added RequireMinHoursPerWeek MinHoursPerWeek to employee import
|| 02/15/22		MCM 22.03.x  (587517) added includeSpecSheets to the parameters
|| 02/21/22     MCM 22.03.   (588899) Added ACHRececipts and CCReceipts for the client import
|| 03/07/22     MCM 22.03.x  (585814) Added Estimate Data and Project Spec Sheet Data to the project parameters
|| 03/28/22     MCM 22.04.x  (589336) Added doNotUseSSO (screen calls is Do Not use SAML/SSO Authentication) to contact 
|| 03/30/22     MCM 22.04.17 (593606) Added clientCampaignNumber to the Campaign
|| 03/30/22     MCM 22.04.x  (593664) Added doNotUseSSO (screen calls is Do Not use SAML/SSO Authentication) to contact 
|| 05/25/22     GHL 22.06.x  (451878) Added glcExchangeRate for client and vendor invoices
|| 06/21/22     RLS 22.07.x  (603837) Added CopyCampaignFiles to the campaigns section
|| 07/07/22     QMD 22.07.24 (602949) Added userId to the Team endpoint
|| 07/11/22     MCM 22.08.x  (595350) Added GLCompanies to the vendor 
|| 07/26/22		MCM 22.08.x  (606848) Removed action from the task import. It was for assignments and causes confustion.
|| 07/22/22     GHL 22.08.00 (604153) Added tTime.Overtime
|| 08/10/22	    MCM 22.09.x  (606828) Updated Voucher to include custom fields on both header and detail
|| 08/10/22	    RLB 22.09.x  (607677) added tVendor.EmailACHToAddress
|| 09/08/22     RLB 22.10.x  (611239) Added Subject to project spec sheet import section
|| 09/21/22     MCM 22.10.x  (612989) Adding class ID Line back into the voucher.  Accidently got removed
|| 09/21/22     RLB 22.10.x  (611076) added Vendor Overtime Cost and Overtime Cost
|| 09/21/22     RLB 22.11.x  (607483) added Contractor to employee import
|| 10/11/22     MCM 22.11.x  (613579) Updated Credit card charge fields to allow for multiple details (expenses and vouchers)
|| 11/07/22     MCM 22.12.x  (618337) updated description to descriptionLine when have to map
|| 11/17/22     MCM 22.12.x  (619769) updated the linked fields (Reference Number in credit card charges and Check Number in vendor payment) to be required as well.
|| 11/30/22     MCM 22.12.x  (613579) Added office line for the credit card charges
|| 12/05/22     MCM 22.12.x  (622066) Removed the reference number as a required field.  The vb will fill on in if none passed in.
|| 01/06/23		MCM 23.02.x  (621970) Added Primary contact and billing contact to client/company
|| 01/30/23     MCM 23.02.x  (628296) Added update ability to vendor payment and receipts
|| 02/14/23     GAR 23.04.x  (DEV2605-MAIN) Added export for Avalara Tax Codes
|| 04/04/23     MCM 23.05.x  (636756) Added bank account type to the vendor import
|| 05/24/23     CRG 23.06.18 (604775) Added documentation for new Task Priority values
|| 06/02/23		MCM 23.06.18 (639431) Added new Credit Card charge fields for multicurrency fields
|| 07/17/23		MCM 23.08.x  (643701) Added long description to the estimate import
|| 08/21/23     MCM 23.09.x  (643543) Added Predecessor Lag field to the task Import
|| 09/07/23     MCM 23.10.x  (649355) Changed name on voucher from Department to "Department (Line)"
|| 10/31/23     RLB 23.11.19 (654959) added missing parms for graph import
|| 11/08/23		MCM 23.12.x  (655841) Added MustFinishOnPredComplete to the Task
*/





END



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAICompanyConvertToClient]'
GO
IF OBJECT_ID(N'[dbo].[spApiAICompanyConvertToClient]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[spApiAICompanyConvertToClient]
    @CompanyKey      int          = 0,
    @CompanyName     varchar(200) = NULL,
    @OwnerCompanyKey int,
    @UserKey         int,
    @ClientID        varchar(75),
    @GLCompanyName   varchar(500) = NULL

AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GAR 26.08.16   (731183) Created -- AI API helper to convert an existing tCompany record into a
||                           Billable Client. Requires both the ''addCompanies'' and ''cm_editacctinfo''
||                           rights (or Administrator, which bypasses both).
||                           Fails if the company is already a Billable Client, if @ClientID is
||                           blank, or if @ClientID is already assigned to another Billable Client
||                           in this tenant. If the tenant preference RequireGLCompany is enabled,
||                           @GLCompanyName is also required and resolved against tGLCompany.
||                           Deliberately does not replicate every side effect of the UI''s
||                           Modules.Billing.Client.updateData (notifications, audit log, credit
||                           card copy, tClientServices) -- only the core conversion plus the
||                           GL-company-access default-row insert so the converting user isn''t
||                           locked out under RestrictToGLCompany.
|| 07/10/26  GAR 26.08.16   Added spCheckAccess (tCompany) record-level gate after the addCompanies/cm_editacctinfo
||                                   right check -- mirrors spApiAIVoucherDetailUpdate / spApiAICompanyCustomFieldSave.
*/

  -- Set up error table
  select * into #errors from tAPIErrorTemplate where 1 = 2

  -- Validate required fields
  if (@CompanyKey is null or @CompanyKey = 0) and (@CompanyName is null or LTRIM(RTRIM(@CompanyName)) = '''')
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''companyKey or companyName is required.'', ''companyName'')

  if @OwnerCompanyKey is null or @OwnerCompanyKey = 0
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Owner Company is required.'', ''ownerCompanyKey'')

  if @ClientID is null or LTRIM(RTRIM(@ClientID)) = ''''
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''clientId is required to convert a company to a Billable Client.'', ''clientId'')

  declare @ErrorCount int
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  -- Resolve CompanyKey by name if not supplied directly
  if isnull(@CompanyKey, 0) = 0
  begin
    select @CompanyKey = CompanyKey
    from tCompany (nolock)
    where OwnerCompanyKey = @OwnerCompanyKey
      and CompanyName = @CompanyName
  end

  declare @CompanyDisplayName nvarchar(200), @BillableClient tinyint
  select @CompanyDisplayName = CompanyName, @BillableClient = isnull(BillableClient, 0)
  from tCompany (nolock)
  where CompanyKey = @CompanyKey
    and OwnerCompanyKey = @OwnerCompanyKey

  if @CompanyDisplayName is null
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Company not found: '' + isnull(@CompanyName, CAST(@CompanyKey as varchar(20))), ''companyName'')
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Everything below depends on the company having resolved -- accumulate together, check once.

  if @BillableClient = 1
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ALREADY_CONVERTED'', ''This company is already a Billable Client.'', ''companyName'')

  -- Rights: Administrator, or both ''addCompanies'' AND ''cm_editacctinfo''
  declare @IsAdministrator tinyint, @SecurityGroupKey int
  select @IsAdministrator = Administrator, @SecurityGroupKey = SecurityGroupKey
  from tUser (nolock)
  where UserKey = @UserKey

  if isnull(@IsAdministrator, 0) <> 1
  begin
    declare @HasAddCompanies bit = 0, @HasEditAcctInfo bit = 0

    select @HasAddCompanies = 1
    from tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where ra.EntityType = ''Security Group''
      and ra.EntityKey = @SecurityGroupKey
      and r.RightID = ''addCompanies''

    select @HasEditAcctInfo = 1
    from tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where ra.EntityType = ''Security Group''
      and ra.EntityKey = @SecurityGroupKey
      and r.RightID = ''cm_editacctinfo''

    if @HasAddCompanies = 0 or @HasEditAcctInfo = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You need both the ''''Add Companies'''' and ''''Edit Client and Vendor Accounting Information'''' rights to convert a company to a Billable Client.'', ''general'')
  end

  -- Record-level access gate via spCheckAccess (tCompany) -- catches folder security and GL
  -- company restrictions beyond the addCompanies/cm_editacctinfo right check above.
  declare @AccessOK int
  exec @AccessOK = spCheckAccess @UserKey, @OwnerCompanyKey, ''tCompany'', @CompanyKey
  if @AccessOK <> 1
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''You do not have access to modify this company.'', ''companyName'')

  -- GL Company: required if the tenant''s RequireGLCompany preference is on
  declare @RequireGLCompany tinyint
  select @RequireGLCompany = isnull(RequireGLCompany, 0)
  from tPreference (nolock)
  where CompanyKey = @OwnerCompanyKey

  declare @GLCompanyKey int
  if @GLCompanyName is not null and LTRIM(RTRIM(@GLCompanyName)) <> ''''
  begin
    select @GLCompanyKey = GLCompanyKey
    from tGLCompany (nolock)
    where CompanyKey = @OwnerCompanyKey
      and GLCompanyName like ''%'' + @GLCompanyName + ''%''

    if @GLCompanyKey is null or @GLCompanyKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyName, ''glCompany'')
  end
  else if @RequireGLCompany = 1
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''A GL Company is required to convert this company to a Billable Client (per your company''''s preferences).'', ''glCompany'')

  -- Duplicate Client ID check -- mirrors sptCompanyUpdateClient''s -400 rule
  if exists (
    select 1 from tCompany (nolock)
    where CompanyKey <> @CompanyKey
      and OwnerCompanyKey = @OwnerCompanyKey
      and BillableClient = 1
      and CustomerID = @ClientID
  )
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''DUPLICATE'', ''This Client ID has already been assigned to another Client.'', ''clientId'')

  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  begin try

    update tCompany
    set BillableClient = 1,
        CustomerID     = @ClientID,
        GLCompanyKey   = isnull(@GLCompanyKey, GLCompanyKey),
        LastModified   = GETUTCDATE(),
        DateUpdated    = GETUTCDATE()
    where CompanyKey = @CompanyKey

    -- Make sure the converting user isn''t locked out of this record if RestrictToGLCompany is on
    exec sptGLCompanyAccessInsertDefaults
        @Entity              = ''tCompany'',
        @EntityKey           = @CompanyKey,
        @UserKey             = @UserKey,
        @CompanyKey          = @OwnerCompanyKey,
        @CheckForExistingRow = 1

    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    select c.CompanyKey     as companyKey,
           c.CompanyName    as companyName,
           c.CustomerID     as clientId,
           c.BillableClient as billableClient,
           c.GLCompanyKey   as glCompanyKey,
           g.GLCompanyName  as glCompanyName
    from tCompany c (nolock)
    left join tGLCompany g (nolock) on g.GLCompanyKey = c.GLCompanyKey
    where c.CompanyKey = @CompanyKey

    drop table #errors

    RETURN @CompanyKey

  end try
  begin catch

    declare @ErrMsg nvarchar(4000) = ERROR_MESSAGE()
    declare @ErrSeverity int = ERROR_SEVERITY()

    if object_id(''tempdb..#errors'') is not null
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', @ErrMsg, ''general'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
    end

    RAISERROR(@ErrMsg, @ErrSeverity, 1)
    return -100

  end catch

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptCampaignUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptCampaignUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptCampaignUpdate]
	@CampaignKey int,
	@UserKey int,
	@CompanyKey int,
	@CampaignID varchar(50),
	@CampaignName nvarchar(200),
	@ClientKey int,
	@Description nvarchar(max),
	@Objective text,
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@AEKey int,
	@Active tinyint,
	@CustomFieldKey int,
	@GetActualsBy smallint,
	@LayoutKey int = null,
	@MultipleSegments tinyint = null,
	@BillBy smallint = null,
	@OneLinePer smallint = null,
	@ContactKey int = null,
	@GLCompanyKey int = null,
	@ClientDivisionKey int = null,
	@ClientProductKey int = null,
	@NextProjectNum int = 1,
	@CurrencyID varchar(10) = null,
	@LeadKey int = null,
	@PMKey int = null,
	@UseCampaignBudget int = NULL,
	@ExpensesNotIncluded tinyint = NULL,
	@BillExpensesByItem tinyint = NULL,
	@BillByFF smallint = 1,
	@ClientCampaignNumber nvarchar(200) = NULL,
	@AvalaraTaxCodeKey int = NULL,
	@RequestKey int = NULL,
	@OfficeKey int = null
AS --Encrypt

/*
|| When      Who Rel      What
|| 5/23/07   CRG 8.4.3    (9293) Added GetActualsBy
|| 12/15/09  CRG 10.5.1.5 Added insert logic
|| 1/19/10   CRG 10.5.1.7 Added @MultipleSegments parameter.  Also made @MultipleSegments and @LayoutKey optional for compatability with CMP and old WMJ screens.
|| 2/3/10    CRG 10.5.1.8 Added optional parameter @BillBy
|| 2/25/10   GWG 10.5.2.0 Added One line per optional param
|| 4/6/10    GHL 10.5.2.1 Added ContactKey param
|| 11/2/10   CRG 10.5.3.7 (92555) Now if MultipleSegments is turned off, we are setting the CampaignSegmentKey to NULL in tProject and deleting the Campaign Segments.
|| 03/02/11  GHL 10.5.4.1 (103729) Added logic to get a campaign id/number for enhancement
|| 04/25/12  GHL 10.5.5.5 Added GLCompanyKey param, the logic for the validation of the GLCompanyKey will be
||                        If GLCompanyKey is null, all projects must have a null GLCompanyKey
||                        If GLCompanyKey is >0, all projects must have the same GLCompanyKey Or 
||                        tGLCompanyMap.TargetGLCompanyKey where SourceGLCompanyKey = GLCompanyKey
|| 11/6/12   WDF 10.5.6.2 (157606) Added ClientDivisionKey and ClientProductKey parameters.
|| 01/22/13  MAS 10.5.6.4 Added UserKey parameters and logging when the active flag is changed
|| 06/18/13  GHL 10.5.6.9 (181721) Added next project number for new project numbers by campaign
|| 07/25/13  GHL 10.5.7.0 Error out if CampaignID is null
|| 10/07/13  GHL 10.5.7.3 Added currency ID to support multi currency
|| 11/07/13  WDF 10.5.7.4 (195877) Error Out if BillBy = 2 and Project Clients not equal Campaign Clients
|| 03/13/14  KMC 10.5.7.8 (209594) Remove the ISNULL check on the LayoutKey so it can be removed instead of just default back to the old LayoutKey
|| 10/13/15  RLB 10.5.9.7 added check for campainid matching any project numbers which can not be because of Plat changes
|| 10/14/15  CRG 10.5.9.7 Added call to sptCampaignWebDavSafeFolders
|| 11/28/17  WDF 10.6.6.6 (374150) Set MultipleSegments flag based on the Segment count for an existing Campaign
|| 09/19/18  RLB 18.9.1.0 (419876) move validation for projects to match campaign GL Company to Bill by Campaign
|| 12/10/18  RLS 19.1.0.0 (423384) Allow for CampaignID to be passed in for new campaigns (insert) (Added @CampaignIDForInsert)
|| 04/09/19  GAR 19.0.5.0 (442365) Adding ability to link opportunities to campaigns - added update of leadkey.
|| 04/16/20  GAR 19.0.5.0 (473704) Added Project Manager
|| 01/07/21  RLS 21.02.14 (535729) Changed @CampaignName to nvarchar
|| 01/27/21  RLS 21.0.2.0 (535729) Changed @Description to nvarchar
|| 04/12/21  MFT 21.0.5.0 (455922) Added UseCampaignBudget, ExpensesNotIncluded, BillByFF param/field
|| 11/01/21  RLS 21.12.19 (574953) Added DateCreated
|| 03/14/22  MFT 22.0.4.0 (578711) Added ClientCampaignNumber
|| 09/26/22  GAR 22.10.16 (DEV2605) Added AvalaraTaxCode
|| 04/04/23 CRG 23.05.14  (621941) Now checking tPreference.DefaultCampaignBillBy when adding a new campaign
|| 11/30/23 RLB 23.12.17  (649537) Added DefaultCampUseCampaignBudget and DefaultCampExpensesNotIncluded new campaign tPreference options on add
|| 02/06/24 RLB 24.03.17  (658052) adding requestkey on insert
|| 02/08/24 RLS 24.03.17  (664126) Fix isnull() param - change to 0 for DefaultCampUseCampaignBudget and DefaultCampExpensesNotIncluded
|| 05/30/24 MCM 24.07.x   (651173) Added OfficeKey
|| 02/19/26 RLS 26.03.15  (720383) Added RequestKey to the update section
|| 03/31/26 GAR 26.04.19  (721911) Allow projects that are child client projects if the client on the campaign is a parent company.
|| 07/08/26 MFT 26.08.01  (729267) Added BillExpensesByItem (Fixed Fee expenses billed one line per Item)
*/
	DECLARE	@OldGetActualsBy smallint,
			@OldLayoutKey int,
			@OldMultipleSegments tinyint,
			@OldBillBy smallint,
			@OldOneLinePer smallint,
			@RetVal	INTEGER,
			@NextTranNo VARCHAR(100),
			@OldActive tinyint,
			@Date smalldatetime,
			@MultiCurrency int,
			@OldCurrencyID varchar(10)

     SELECT @Date = GETUTCDATE()	
     
	 -- Get the next number
	 IF @CampaignID IS NULL OR @CampaignID = '''' -- Will be true for new Campaigns
	 BEGIN
		EXEC sptCampaignGetNextCampaignNum
			@CompanyKey,
			@ClientKey,
			@RetVal OUTPUT,
			@NextTranNo OUTPUT

		IF @RetVal <> 1
			RETURN -1

		IF @NextTranNo IS NULL
			RETURN -1
	END
	ELSE
	BEGIN
		-- Check for a duplicate campaign id/number
		if isnull(@CampaignKey,0) > 0 
		begin
			IF EXISTS(
				SELECT 1 FROM tCampaign (NOLOCK) 
				WHERE
					CampaignID = @CampaignID AND
					CompanyKey = @CompanyKey AND
					CampaignKey <> @CampaignKey
					)
				RETURN -2
			IF EXISTS(
				SELECT 1 FROM tProject (NOLOCK) 
				WHERE
					ProjectNumber = @CampaignID AND
					CompanyKey = @CompanyKey			
					)
				RETURN -7
		end
		ELSE
		begin
			IF EXISTS(
				SELECT 1 FROM tCampaign (NOLOCK) 
				WHERE
					CampaignID = @CampaignID AND
					CompanyKey = @CompanyKey
					)
				RETURN -2
		end

		IF EXISTS(
			SELECT 1 FROM tProject (NOLOCK) 
			WHERE
				ProjectNumber = @CampaignID AND
				CompanyKey = @CompanyKey			
				)
			RETURN -7

		SELECT @NextTranNo = @CampaignID
	END

	SELECT @NextTranNo = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(@NextTranNo, ''&'', ''''), '','', ''''), ''"'', ''''), '''''''', '''')))
 
	IF @CampaignKey > 0
	BEGIN
				
	SELECT	@OldGetActualsBy = GetActualsBy,
				@OldLayoutKey = LayoutKey,
				@OldMultipleSegments = MultipleSegments,
				@OldBillBy = BillBy,
				@OldOneLinePer = OneLinePer,
				@OldCurrencyID = CurrencyID
		FROM	tCampaign (nolock)
		WHERE	CampaignKey = @CampaignKey

		-- Validation of CurrencyID
		select @MultiCurrency = isnull(MultiCurrency, 0) from tPreference (nolock) where CompanyKey = @CompanyKey
		if @MultiCurrency = 1
		begin
			IF EXISTS (SELECT 1 FROM tProject (NOLOCK) 
						WHERE CampaignKey = @CampaignKey 
						AND   isnull(CurrencyID, '''') <> isnull(@CurrencyID, '''')
					)
					RETURN -4 
					
			IF isnull(@OldCurrencyID, '''') <> isnull(@CurrencyID, '''') AND EXISTS (SELECT 1 FROM tEstimate (NOLOCK)
				WHERE CompanyKey = @CompanyKey
				AND   CampaignKey = @CampaignKey
				)
				RETURN -5 
		end
	
		IF @BillBy = 2
		BEGIN
			--If BillBy was set to Campaign but projects are linked to it that have a different client than this campaign, then return error
			--721911-GAR - Change this to include all child client projects if this is a parent client
			IF EXISTS
					(SELECT	NULL
					FROM	tProject p (nolock)
						INNER JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
					WHERE	p.CampaignKey = @CampaignKey
					AND		p.ClientKey <> @ClientKey
					AND     p.ClientKey NOT IN (SELECT CompanyKey FROM tCompany (nolock) WHERE ParentCompanyKey = @ClientKey))
				RETURN -6

		-- Validation of GLCompanyKey this only applies when billing by campaign
		IF EXISTS (SELECT 1 FROM tProject (NOLOCK) WHERE CampaignKey = @CampaignKey AND NOT ISNULL(GLCompanyKey, 0) IN (
						SELECT ISNULL(@GLCompanyKey, 0) 
						UNION
						(SELECT TargetGLCompanyKey FROM tGLCompanyMap (NOLOCK) WHERE SourceGLCompanyKey =  @GLCompanyKey)
				  )
				)
				RETURN -3
		END

		SELECT	@MultipleSegments = (SELECT CASE WHEN (Select Count(*) from tCampaignSegment (nolock) WHERE CampaignKey = @CampaignKey) > 0 THEN 1 ELSE 0 END) 

		IF @MultipleSegments = 0 AND @OldMultipleSegments = 1
		BEGIN
			UPDATE	tProject
			SET		CampaignSegmentKey = NULL
			WHERE	CampaignKey = @CampaignKey

			DELETE	tCampaignSegment
			WHERE	CampaignKey = @CampaignKey
		END
		
		SELECT @OldActive = ISNULL(Active, 0)	
		FROM   tCampaign (nolock)
		WHERE  CampaignKey = @CampaignKey
			
		IF @OldActive <> @Active
		BEGIN
			IF @Active = 1
				EXEC sptActionLogInsert ''Campaign'',@CampaignKey, @CompanyKey, 0, ''Active'', @Date, NULL, ''Campaign marked active'', @CampaignID, NULL, @UserKey  
			ELSE
				EXEC sptActionLogInsert ''Campaign'',@CampaignKey, @CompanyKey, 0, ''Inactive'', @Date, NULL, ''Campaign marked inactive'', @CampaignID, NULL, @UserKey
		END

		-- Bill Expenses by Item only applies to Campaigns billed by Campaign, using the Campaign Budget, with Expenses Are Not Included
		IF ISNULL(@BillExpensesByItem, 0) = 1 AND (ISNULL(@BillBy, @OldBillBy) <> 2 OR ISNULL(@UseCampaignBudget, 0) <> 1 OR ISNULL(@ExpensesNotIncluded, 0) <> 1)
			SELECT @BillExpensesByItem = 0

		SELECT @BillExpensesByItem = ISNULL(@BillExpensesByItem, 0)

		UPDATE
			tCampaign
		SET
			CompanyKey = @CompanyKey,
			CampaignID = @NextTranNo, 
			CampaignName = @CampaignName,
			ClientKey = @ClientKey,
			Description = @Description,
			Objective = @Objective,
			StartDate = @StartDate,
			EndDate = @EndDate,
			AEKey = @AEKey,
			Active = @Active,
			CustomFieldKey = @CustomFieldKey,
			GetActualsBy = @GetActualsBy,
			LayoutKey = @LayoutKey,
			MultipleSegments = ISNULL(@MultipleSegments, @OldMultipleSegments),
			BillBy = ISNULL(@BillBy, @OldBillBy),
			UseCampaignBudget = @UseCampaignBudget,
			ExpensesNotIncluded = @ExpensesNotIncluded,
			BillExpensesByItem = @BillExpensesByItem,
			BillByFF = @BillByFF,
			OneLinePer = ISNULL(@OneLinePer, @OldOneLinePer),
			ContactKey = @ContactKey,
			GLCompanyKey = @GLCompanyKey,
			ClientDivisionKey = @ClientDivisionKey,
			ClientProductKey = @ClientProductKey,
			NextProjectNum = @NextProjectNum,
			CurrencyID = @CurrencyID,
			LeadKey = @LeadKey,
			PMKey = @PMKey,
			ClientCampaignNumber = @ClientCampaignNumber,
			AvalaraTaxCodeKey = @AvalaraTaxCodeKey,
			OfficeKey = @OfficeKey,
			RequestKey = @RequestKey
		WHERE
			CampaignKey = @CampaignKey 

		--If GetActualsBy has changed, clear the budget items
		IF @GetActualsBy <> @OldGetActualsBy
			DELETE	tCampaignBudgetItem
			WHERE	CampaignKey = @CampaignKey

		--If not using Project for Actuals, clear out any links from tProject
		IF @GetActualsBy < 3
			UPDATE	tProject
			SET		CampaignBudgetKey = NULL
			WHERE	CampaignKey = @CampaignKey	
		
		RETURN @CampaignKey
	END
	ELSE
	BEGIN
		-- New Campaign; a new CampaignID may have been passed in (423384). If so, use it. If not use @NextTranNo which was set above.
		 DECLARE @CampaignIDForInsert VARCHAR(100)
		 IF @CampaignID IS NOT NULL AND @CampaignID <> ''''
			SELECT @CampaignIDForInsert = @CampaignID
		 ELSE
			SELECT @CampaignIDForInsert = @NextTranNo

		SELECT	@BillBy = ISNULL(DefaultCampaignBillBy, 1), @UseCampaignBudget = ISNULL(DefaultCampUseCampaignBudget, 0), @ExpensesNotIncluded = ISNULL(DefaultCampExpensesNotIncluded, 0)
		FROM	tPreference (nolock)
		WHERE	CompanyKey = @CompanyKey
			
		INSERT tCampaign
			(
			CompanyKey,
			CampaignID,
			CampaignName,
			ClientKey,
			Description,
			Objective,
			StartDate,
			EndDate,
			AEKey,
			Active,
			CustomFieldKey,
			GetActualsBy,
			LayoutKey,
			MultipleSegments,
			BillBy,
			UseCampaignBudget,
			ExpensesNotIncluded,
			BillExpensesByItem,
			BillByFF,
			OneLinePer,
			ContactKey,
			GLCompanyKey,
			ClientDivisionKey,
			ClientProductKey,
			NextProjectNum,
			CurrencyID,
			LeadKey,
			PMKey,
			DateCreated,
			ClientCampaignNumber,
			AvalaraTaxCodeKey,
			RequestKey,
			OfficeKey
			)

		VALUES
			(
			@CompanyKey,
			@CampaignIDForInsert,
			@CampaignName,
			@ClientKey,
			@Description,
			@Objective,
			@StartDate,
			@EndDate,
			@AEKey,
			@Active,
			@CustomFieldKey,
			@GetActualsBy,
			@LayoutKey,
			@MultipleSegments,
			@BillBy,
			@UseCampaignBudget,
			@ExpensesNotIncluded,
			ISNULL(@BillExpensesByItem, 0),
			@BillByFF,
			@OneLinePer,
			@ContactKey,
			@GLCompanyKey,
			@ClientDivisionKey,
			@ClientProductKey,
			@NextProjectNum,
			@CurrencyID,
			@LeadKey,
			@PMKey,
			GETUTCDATE(),
			@ClientCampaignNumber,
			@AvalaraTaxCodeKey,
			@RequestKey,
			@OfficeKey
			)
	
		SELECT @CampaignKey = @@IDENTITY
		
		--Set the WebDav safe folder names
		EXEC sptCampaignWebDavSafeFolders @CampaignKey, 0
		
		RETURN @CampaignKey	
	END'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAICompanyConvertToVendor]'
GO
IF OBJECT_ID(N'[dbo].[spApiAICompanyConvertToVendor]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[spApiAICompanyConvertToVendor]
    @CompanyKey      int          = 0,
    @CompanyName     varchar(200) = NULL,
    @OwnerCompanyKey int,
    @UserKey         int,
    @VendorID        varchar(50),
    @GLCompanyName   varchar(500) = NULL

AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GAR 26.08.16   (731183) Created -- AI API helper to convert an existing tCompany record into a
||                           Vendor. Requires both the ''addCompanies'' and ''cm_editacctinfo'' rights
||                           (or Administrator, which bypasses both). Fails if
||                           the company is already a Vendor, if @VendorID is blank, or if
||                           @VendorID is already assigned to another Vendor in this tenant. If the
||                           tenant preference RequireGLCompany is enabled, @GLCompanyName is also
||                           required and resolved against tGLCompany.
||                           Deliberately does not replicate every side effect of the UI''s
||                           Modules.Purchasing.Vendor.updateData (notifications, audit log,
||                           banking/1099 fields, custom fields) -- only the core conversion plus
||                           the GL-company-access default-row insert so the converting user isn''t
||                           locked out under RestrictToGLCompany. Note: sptCompanyUpdateVendor
||                           itself no longer accepts a GLCompanyKey param (removed years ago) --
||                           GLCompanyKey is still a plain tCompany column, so it''s set directly
||                           here rather than via that SP.
|| 07/10/26  GAR 26.08.16   Added spCheckAccess (tCompany) record-level gate after the addCompanies/cm_editacctinfo
||                                   right check -- mirrors spApiAIVoucherDetailUpdate / spApiAICompanyCustomFieldSave.
*/

  -- Set up error table
  select * into #errors from tAPIErrorTemplate where 1 = 2

  -- Validate required fields
  if (@CompanyKey is null or @CompanyKey = 0) and (@CompanyName is null or LTRIM(RTRIM(@CompanyName)) = '''')
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''companyKey or companyName is required.'', ''companyName'')

  if @OwnerCompanyKey is null or @OwnerCompanyKey = 0
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Owner Company is required.'', ''ownerCompanyKey'')

  if @VendorID is null or LTRIM(RTRIM(@VendorID)) = ''''
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''vendorId is required to convert a company to a Vendor.'', ''vendorId'')

  declare @ErrorCount int
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  -- Resolve CompanyKey by name if not supplied directly
  if isnull(@CompanyKey, 0) = 0
  begin
    select @CompanyKey = CompanyKey
    from tCompany (nolock)
    where OwnerCompanyKey = @OwnerCompanyKey
      and CompanyName = @CompanyName
  end

  declare @CompanyDisplayName nvarchar(200), @Vendor tinyint
  select @CompanyDisplayName = CompanyName, @Vendor = isnull(Vendor, 0)
  from tCompany (nolock)
  where CompanyKey = @CompanyKey
    and OwnerCompanyKey = @OwnerCompanyKey

  if @CompanyDisplayName is null
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Company not found: '' + isnull(@CompanyName, CAST(@CompanyKey as varchar(20))), ''companyName'')
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Everything below depends on the company having resolved -- accumulate together, check once.

  if @Vendor = 1
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ALREADY_CONVERTED'', ''This company is already a Vendor.'', ''companyName'')

  -- Rights: Administrator, or both ''addCompanies'' AND ''cm_editacctinfo''
  declare @IsAdministrator tinyint, @SecurityGroupKey int
  select @IsAdministrator = Administrator, @SecurityGroupKey = SecurityGroupKey
  from tUser (nolock)
  where UserKey = @UserKey

  if isnull(@IsAdministrator, 0) <> 1
  begin
    declare @HasAddCompanies bit = 0, @HasEditAcctInfo bit = 0

    select @HasAddCompanies = 1
    from tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where ra.EntityType = ''Security Group''
      and ra.EntityKey = @SecurityGroupKey
      and r.RightID = ''addCompanies''

    select @HasEditAcctInfo = 1
    from tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where ra.EntityType = ''Security Group''
      and ra.EntityKey = @SecurityGroupKey
      and r.RightID = ''cm_editacctinfo''

    if @HasAddCompanies = 0 or @HasEditAcctInfo = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You need both the ''''Add Companies'''' and ''''Edit Client and Vendor Accounting Information'''' rights to convert a company to a Vendor.'', ''general'')
  end

  -- Record-level access gate via spCheckAccess (tCompany) -- catches folder security and GL
  -- company restrictions beyond the addCompanies/cm_editacctinfo right check above.
  declare @AccessOK int
  exec @AccessOK = spCheckAccess @UserKey, @OwnerCompanyKey, ''tCompany'', @CompanyKey
  if @AccessOK <> 1
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''You do not have access to modify this company.'', ''companyName'')

  -- GL Company: required if the tenant''s RequireGLCompany preference is on
  declare @RequireGLCompany tinyint
  select @RequireGLCompany = isnull(RequireGLCompany, 0)
  from tPreference (nolock)
  where CompanyKey = @OwnerCompanyKey

  declare @GLCompanyKey int
  if @GLCompanyName is not null and LTRIM(RTRIM(@GLCompanyName)) <> ''''
  begin
    select @GLCompanyKey = GLCompanyKey
    from tGLCompany (nolock)
    where CompanyKey = @OwnerCompanyKey
      and GLCompanyName like ''%'' + @GLCompanyName + ''%''

    if @GLCompanyKey is null or @GLCompanyKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyName, ''glCompany'')
  end
  else if @RequireGLCompany = 1
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''A GL Company is required to convert this company to a Vendor (per your company''''s preferences).'', ''glCompany'')

  -- Duplicate Vendor ID check -- mirrors sptCompanyUpdateVendor''s -500 rule
  if exists (
    select 1 from tCompany (nolock)
    where CompanyKey <> @CompanyKey
      and OwnerCompanyKey = @OwnerCompanyKey
      and Vendor = 1
      and VendorID = @VendorID
  )
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''DUPLICATE'', ''This Vendor ID has already been assigned to another Vendor.'', ''vendorId'')

  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  begin try

    update tCompany
    set Vendor       = 1,
        VendorID     = @VendorID,
        GLCompanyKey = isnull(@GLCompanyKey, GLCompanyKey),
        LastModified = GETUTCDATE(),
        DateUpdated  = GETUTCDATE()
    where CompanyKey = @CompanyKey

    -- Make sure the converting user isn''t locked out of this record if RestrictToGLCompany is on
    exec sptGLCompanyAccessInsertDefaults
        @Entity              = ''tCompany'',
        @EntityKey           = @CompanyKey,
        @UserKey             = @UserKey,
        @CompanyKey          = @OwnerCompanyKey,
        @CheckForExistingRow = 1

    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    select c.CompanyKey    as companyKey,
           c.CompanyName   as companyName,
           c.VendorID      as vendorId,
           c.Vendor        as vendor,
           c.GLCompanyKey  as glCompanyKey,
           g.GLCompanyName as glCompanyName
    from tCompany c (nolock)
    left join tGLCompany g (nolock) on g.GLCompanyKey = c.GLCompanyKey
    where c.CompanyKey = @CompanyKey

    drop table #errors

    RETURN @CompanyKey

  end try
  begin catch

    declare @ErrMsg nvarchar(4000) = ERROR_MESSAGE()
    declare @ErrSeverity int = ERROR_SEVERITY()

    if object_id(''tempdb..#errors'') is not null
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', @ErrMsg, ''general'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
    end

    RAISERROR(@ErrMsg, @ErrSeverity, 1)
    return -100

  end catch

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptLeadGetDashboard]'
GO
IF OBJECT_ID(N'[dbo].[sptLeadGetDashboard]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptLeadGetDashboard] 
	@CompanyKey INT,
	@AccountManagerKey INT,
	@OpportunityOwnerKey INT = -1,
	@CanViewOthersOpps BIT = 0

AS --Encrypt

/*
|| When     Who Rel			What
|| 09/22/15 GAR 10.5.9.6	Created for opportunities dashboard.
|| 05/25/16 GAR 10.6.0.4    (298864) Fixed issue where the display order was getting bad values which was affecting grouping.
|| 10/26/16 GWG 10.6.0.9    (318027) AGI was SaleAmount. Modified to be closer to the real amount they will make
|| 11/01/16 GAR 10.6.0.9    (318329) Add Forecasted Close Date to query for sorting purposes.
|| 11/09/16 GAR 10.6.0.9    (320118) Some stages were getting hidden on search.
|| 01/17/18 WDF 18.2.0      (379487) Added GLCompany Restrictions
|| 01/16/20 AMP 20.0.2.0    (496228) Added Lead ID, and CampaignKey to Display Opportunity Full Name on the Opportunity dashboard
|| 02/09/21 GAR 21.03.00    (547498) Apply folder security to opportunities being shown
|| 10/19/22 RLS 22.11.20    (615863) Add condition for tLeadStage.DisplayOnDashboard to the WHERE clauses
|| 02/05/25 RLB 25.03.16    (693471) when restricting by @OpportunityOwnerKey when pulling opps with stage need to pull all the stages which have a userkey 0
|| 06/20/25 RLB 25.07.20    (704448) added checks and handling if there are no stages
*/

DECLARE @RestrictToGLCompany int, @StageCount int, @CurrentDisplayOrder int

	Select @RestrictToGLCompany = isnull(RestrictToGLCompany, 0) from tPreference (nolock) where CompanyKey = @CompanyKey

	select @StageCount = count(*) from tLeadStage (nolock) where CompanyKey = @CompanyKey AND ISNULL(tLeadStage.DisplayOnDashboard,0) = 1
	
	select @CurrentDisplayOrder = @StageCount + 1

BEGIN 
 
	-- Get opportunities by stage. 
	-- Define the Users CTE. 
	WITH Users_CTE (UserKey, OpportunityOwnerName) 
	AS 
	( 
		SELECT  
		DISTINCT ISNULL(tUser1.UserKey, 0) AS UserKey,  
		(CASE WHEN ISNULL(tUser1.FirstName,'''') = '''' AND ISNULL(tUser1.LastName, '''') = '''' THEN NULL ELSE ISNULL(tUser1.FirstName,'''') + '' '' + ISNULL(tUser1.LastName, '''') END) AS OpportunityOwnerName 
		from tLead (nolock) 
			LEFT OUTER JOIN tCompany (nolock) ON tLead.ContactCompanyKey = tCompany.CompanyKey 
			LEFT OUTER JOIN tUser tUser1 (nolock) ON tLead.AccountManagerKey = tUser1.UserKey 
			LEFT OUTER JOIN tLeadStatus (nolock) ON tLead.LeadStatusKey = tLeadStatus.LeadStatusKey 
			LEFT OUTER JOIN tLeadStage (nolock) ON tLead.LeadStageKey = tLeadStage.LeadStageKey 
		WHERE tLead.CompanyKey = @CompanyKey  
			--AND CMFolderKey in (0)  
			AND tLeadStatus.Active = 1 
			AND tLead.AccountManagerKey > 0 
			AND (@StageCount = 0 OR ISNULL(tLeadStage.DisplayOnDashboard,0) = 1)
			AND (@RestrictToGLCompany = 0
			 OR  tLead.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (nolock) WHERE UserKey = @AccountManagerKey))
			 
		UNION 
		 
		SELECT 0, NULL 
		 
	) 
	 
	SELECT * INTO #UsersTemp FROM Users_CTE; 
	 
	-- Define the Stages CTE. 
	WITH Stages_CTE (LeadStageKey, DisplayOrder, LeadStageName) 
	AS 
	( 
		SELECT  
		DISTINCT tLeadStage.LeadStageKey, tLeadStage.DisplayOrder, tLeadStage.LeadStageName 
		FROM tLeadStage (nolock) 
		WHERE tLeadStage.CompanyKey = @CompanyKey  AND ISNULL(tLeadStage.DisplayOnDashboard,0) = 1

		UNION 
		 
		SELECT 0, @CurrentDisplayOrder, ''No Stage''
	) 
	 
	SELECT * INTO #StagesTemp FROM Stages_CTE 
 
	SELECT DISTINCT #StagesTemp.LeadStageKey,  
		#StagesTemp.DisplayOrder,  
		#StagesTemp.LeadStageName,  
		SUM(CASE WHEN (@CanViewOthersOpps = 1 OR tLead.AccountManagerKey = @AccountManagerKey) AND tLeadStatus.Active = 1 THEN ISNULL(tLead.AGI, 0) ELSE 0 END) AS Sales --AGI was SaleAmount. Modified to be closer to the real amount they will make 
	FROM #StagesTemp 
		LEFT OUTER JOIN tLead (nolock) ON #StagesTemp.LeadStageKey = ISNULL(tLead.LeadStageKey, 0) AND
			                             (@RestrictToGLCompany = 0 OR
			                              tLead.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (nolock) WHERE UserKey = @AccountManagerKey))
		LEFT OUTER JOIN tLeadStatus (nolock) ON tLead.LeadStatusKey = tLeadStatus.LeadStatusKey 
	GROUP BY #StagesTemp.LeadStageKey, #StagesTemp.DisplayOrder, #StagesTemp.LeadStageName 
	ORDER BY #StagesTemp.DisplayOrder, #StagesTemp.LeadStageKey 
	 
	SELECT * INTO #Temp FROM #UsersTemp CROSS JOIN #StagesTemp 
	 
	-- Get all opportunities summed by user and stage. 
	SELECT ISNULL(UserKey, 0) AS UserKey,  
		OpportunityOwnerName,  
		#Temp.LeadStageKey, 
		LeadStageName,  
		#Temp.DisplayOrder,  
		SUM(CASE WHEN (@CanViewOthersOpps = 1 OR tLead.AccountManagerKey = @AccountManagerKey) AND tLeadStatus.Active = 1 THEN ISNULL(tLead.AGI, 0) ELSE 0 END) AS SaleAmount 
	FROM #Temp 
			LEFT OUTER JOIN tLead (nolock) ON #Temp.UserKey = ISNULL(tLead.AccountManagerKey,0) AND 
			                                  #Temp.LeadStageKey = ISNULL(tLead.LeadStageKey, 0) AND
			                                 (@RestrictToGLCompany = 0 OR
			                                  tLead.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (nolock) WHERE UserKey = @AccountManagerKey))
			LEFT OUTER JOIN tLeadStatus (nolock) ON tLead.LeadStatusKey = tLeadStatus.LeadStatusKey 
	GROUP BY UserKey, OpportunityOwnerName, #Temp.LeadStageKey, LeadStageName, #Temp.DisplayOrder 
	ORDER BY #Temp.DisplayOrder, #Temp.LeadStageKey, OpportunityOwnerName 
	 
	-- Get all opportunities with stage. 
	SELECT  tLead.LeadKey,  
	        tLead.LeadID,
			tLead.CampaignKey,
		    #Temp.LeadStageKey,  
			#Temp.UserKey,  
			tLead.AccountManagerKey AS OpportunityOwnerKey, 
			OpportunityOwnerName,  
			#Temp.LeadStageName,  
			#Temp.DisplayOrder,  
			(CASE WHEN (@CanViewOthersOpps = 1 OR tLead.AccountManagerKey = @AccountManagerKey) AND tLeadStatus.Active = 1 THEN ISNULL(tLead.Subject, '''') ELSE '''' END) AS OpportunityName, 
			ISNULL(tCompany.CompanyName, '''') AS CompanyName,  
			(CASE WHEN (@CanViewOthersOpps = 1 OR tLead.AccountManagerKey = @AccountManagerKey) AND tLeadStatus.Active = 1 THEN ISNULL(tLead.AGI, 0) ELSE 0 END) AS SaleAmount, 
			ISNULL(tProjectType.ProjectTypeColor, ''#000000'') AS ProjectTypeColor, 
			#Temp.DisplayOrder AS Ordering, 
			tProject.ProjectNumber, 
			tProject.ProjectName, 
			(SELECT COUNT(*) FROM tAppFavorite WHERE ActionID = ''cm.opportunities'' AND UserKey = @AccountManagerKey AND ActionKey = tLead.LeadKey) AS IsFavorite, 
			tLead.EstCloseDate 
	FROM #Temp 
			LEFT OUTER JOIN tLead (nolock) ON #Temp.UserKey = ISNULL(tLead.AccountManagerKey, 0) AND 
			                                  #Temp.LeadStageKey = ISNULL(tLead.LeadStageKey, 0) AND
			                                 (@RestrictToGLCompany = 0 OR
			                                  tLead.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (nolock) WHERE UserKey = @AccountManagerKey))
			LEFT OUTER JOIN tCompany (nolock) ON tLead.ContactCompanyKey = tCompany.CompanyKey 
			LEFT OUTER JOIN tUser tUser1 (nolock) ON tLead.AccountManagerKey = tUser1.UserKey 
			Left OUTER JOIN tUser am (nolock) ON tCompany.AccountManagerKey = am.UserKey 
			LEFT OUTER JOIN tLeadStatus (nolock) ON tLead.LeadStatusKey = tLeadStatus.LeadStatusKey 
			LEFT OUTER JOIN tProjectType (nolock) ON tLead.ProjectTypeKey = tProjectType.ProjectTypeKey 
			LEFT OUTER JOIN tProject (nolock) ON tLead.ProjectKey = tProject.ProjectKey 
	WHERE (@OpportunityOwnerKey = -1 OR #Temp.UserKey = @OpportunityOwnerKey OR #Temp.UserKey = 0) 
	AND 
	--Folder restriction
	(
		ISNULL(tLead.CMFolderKey, 0) = 0 OR
		tLead.CMFolderKey IN (
			SELECT CMFolderKey
			FROM tCMFolderSecurity (nolock)
			WHERE
				(
					CanView = 1 AND
					Entity = ''tUser'' AND
					EntityKey = @AccountManagerKey
				) OR
				(
					CanView = 1 AND
					Entity = ''tSecurityGroup'' AND
					EntityKey IN (SELECT SecurityGroupKey FROM tUser (nolock) WHERE UserKey = @AccountManagerKey)
				)
			) OR
			EXISTS (
				SELECT CMFolderKey
				FROM tCMFolder (nolock)
				WHERE
					CMFolderKey = tLead.CMFolderKey AND
					UserKey = @AccountManagerKey AND
					Entity = ''tUser''
			)
	)
	ORDER BY #Temp.DisplayOrder, #Temp.LeadStageKey, OpportunityOwnerName, ISNULL(tLead.Subject, '''') 
 
	DROP TABLE #Temp 
	DROP TABLE #UsersTemp 
	DROP TABLE #StagesTemp 
 
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIClientUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIClientUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   PROCEDURE [dbo].[spApiAIClientUpdate]
	@CompanyKey int = 0,
	@CompanyName nvarchar(200) = NULL,
	@OwnerCompanyKey int,
	@UserKey int,

	@CustomerID varchar(75) = NULL,
	@BillableClient tinyint = NULL,
	@Phone varchar(50) = NULL,
	@Fax varchar(50) = NULL,
	@WebSite varchar(100) = NULL,
	@TwitterID varchar(50) = NULL,
	@Comments varchar(2000) = NULL,
	@CurrencyID varchar(10) = NULL,
	@EINNumber varchar(100) = NULL,
	@BillingName nvarchar(200) = NULL,

	@AddressName varchar(200) = NULL,
	@Address1 varchar(100) = NULL,
	@Address2 varchar(100) = NULL,
	@Address3 varchar(100) = NULL,
	@City varchar(100) = NULL,
	@State varchar(50) = NULL,
	@PostalCode varchar(20) = NULL,
	@Country varchar(50) = NULL,
	@DefaultAddressKey int = NULL,
	@BillingAddressKey int = NULL,

	@PrimaryContactName varchar(300) = NULL,
	@AccountManagerName varchar(300) = NULL,
	@SalesPersonName varchar(300) = NULL,
	@ContactOwnerName varchar(300) = NULL,
	@ProjectManagerName varchar(300) = NULL,
	@BillingManagerName varchar(300) = NULL,
	@PaymentTermsName varchar(100) = NULL,
	@GLCompanyName varchar(500) = NULL,
	@OfficeName nvarchar(200) = NULL,
	@ParentCompanyName nvarchar(200) = NULL,

	@GetRateFrom smallint = NULL,
	@TimeRateSheetKey int = NULL,
	@HourlyRate money = NULL,
	@GetMarkupFrom smallint = NULL,
	@ItemRateSheetKey int = NULL,
	@ItemMarkup decimal(24,4) = NULL,
	@IOCommission decimal(24,4) = NULL,
	@BCCommission decimal(24,4) = NULL,
	@IOBillAt smallint = NULL,
	@BCBillAt smallint = NULL,
	@DefaultBillingMethod smallint = NULL,
	@DefaultARLineFormat int = NULL,
	@DefaultFFLineFormat smallint = NULL,
	@DefaultRetainerKey int = NULL,
	@OneInvoicePer smallint = NULL,
	@DefaultExpensesNotIncluded tinyint = NULL,
	@DefaultSalesAccountKey int = NULL,
	@DefaultARAccountKey int = NULL,
	@SalesTaxKey int = NULL,
	@SalesTax2Key int = NULL,
	@InvoiceTemplateKey int = NULL,
	@EstimateTemplateKey int = NULL,
	@EstimateLaborTaxable smallint = NULL,
	@TitleRateSheetKey int = NULL,
	@DefaultTeamKey int = NULL,
	@NextProjectNum int = NULL,
	@NextCampaignNum int = NULL,
	@IncludeRetainerOnClientWorksheet tinyint = NULL,
	@Overhead tinyint = NULL,
	@ActiveClient tinyint = NULL,
	@DoNotUse tinyint = NULL,
	@CCReceipts tinyint = NULL,
	@DefaultProjectsNonBillable tinyint = NULL,
	@FixedFeeAddProjectLine tinyint = NULL,
	@ForecastForceToFF tinyint = NULL,
	@AllTrackBudgetTasksOnInvoice tinyint = NULL,
	@LockLaborRate tinyint = NULL,
	@LockMarkupFrom tinyint = NULL,
	@RequireCommentsOnTime tinyint = NULL,
	@BillingEmailContactKey int = NULL,
	@ProjectColor varchar(10) = NULL,
	@LayoutKey int = NULL,
	@AvalaraTaxExempt tinyint = NULL,
	@AvalaraTaxExemptReason nvarchar(50) = NULL,
	@AvalaraTaxCodeKey int = NULL,
	@KeyPeople1 int = NULL,
	@KeyPeople2 int = NULL,
	@KeyPeople3 int = NULL,
	@KeyPeople4 int = NULL,
	@KeyPeople5 int = NULL,
	@KeyPeople6 int = NULL,
	@DateConverted smalldatetime = NULL,
	@ParentCompanyDivisionKey int = NULL

AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GAR 26.08.16   (731183) Created -- AI/MCP-facing client-specific update, separate from
||                                   spApiAICompanyUpdate (general company add/update) and
||                                   spApiAICompanyConvertToClient (initial conversion to Billable Client).
||                                   Requires the target to already be an existing company (does not insert --
||                                   use add_update_company to create a company and convert_company_to_client
||                                   to make it a Billable Client first). Wraps sptCompanyUpdateClient with
||                                   AI-friendly name-based resolution, partial-update-safe defaults (seeded
||                                   from the current row so an update that only touches one field doesn''t
||                                   blank out the rest -- sptCompanyUpdateClient itself does a full-row
||                                   overwrite with no ISNULL preservation), and the standard #errors
||                                   validation/security pattern. Deliberately does not replicate every side
||                                   effect of the UI''s Modules.Billing.Client.updateData (WebDAV folder
||                                   rename, tClientServices reset, new-client email notifications) --
||                                   only the core field update plus the GL-company-access default-row
||                                   insert so the editing user isn''t locked out under RestrictToGLCompany.
||                                   Does not accept ACH bank account fields (ACHRoutingNumber/
||                                   ACHAccountNumber/ACHNameOnAccount/ACHAccountType) by design -- those
||                                   remain UI-only.
|| 07/09/26  GAR 26.08.20   Fixed: when @AddressName is supplied, resolve it against tAddress
||                                   (scoped to @CompanyKey) and use the matching AddressKey to set
||                                   @BillingAddressKey, instead of requiring the caller to already know
||                                   and pass the raw billingAddressKey. NOT_FOUND if no address on this
||                                   company matches the given name. Resolution wins over any explicit
||                                   billingAddressKey the caller also passed.
*/

  -- Set up error table
  select * into #errors from tAPIErrorTemplate where 1 = 2

  if @OwnerCompanyKey is null or @OwnerCompanyKey = 0
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Owner Company is required.'', ''ownerCompanyKey'')

  if (@CompanyKey is null or @CompanyKey = 0) and (@CompanyName is null or LTRIM(RTRIM(@CompanyName)) = '''')
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''companyKey or companyName is required.'', ''companyName'')

  declare @ErrorCount int
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  -- Resolve CompanyKey by name if not supplied directly. This tool only updates an EXISTING
  -- company -- it never inserts a new tCompany row.
  if isnull(@CompanyKey, 0) = 0
  begin
    select @CompanyKey = CompanyKey
    from tCompany (nolock)
    where OwnerCompanyKey = @OwnerCompanyKey
      and CompanyName = @CompanyName
  end

  if not exists (select 1 from tCompany (nolock) where CompanyKey = @CompanyKey and OwnerCompanyKey = @OwnerCompanyKey)
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Company not found: '' + isnull(@CompanyName, CAST(isnull(@CompanyKey,0) as varchar(20))) + ''. update_client only updates an existing company -- use add_update_company to create one first.'', ''companyName'')
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Rights: Administrator, or ''cm_editacctinfo'' -- mirrors Modules.Billing.Client.updateData''s
  -- update branch (WJAPP/billing/clients/Client.vb). This tool never inserts, so the
  -- ''addCompanies'' branch used for brand-new clients does not apply here.
  declare @IsAdministrator tinyint, @SecurityGroupKey int
  select @IsAdministrator = Administrator, @SecurityGroupKey = SecurityGroupKey
  from tUser (nolock)
  where UserKey = @UserKey

  if isnull(@IsAdministrator, 0) <> 1
  begin
    declare @HasEditAcctInfo bit = 0

    select @HasEditAcctInfo = 1
    from tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where ra.EntityType = ''Security Group''
      and ra.EntityKey = @SecurityGroupKey
      and r.RightID = ''cm_editacctinfo''

    if @HasEditAcctInfo = 0
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You do not have the ''''Edit Account Info'''' right required to update this client.'', ''general'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -103
    end
  end

  -- GL company restriction: same record-level check used by spApiAICompanyUpdate
  declare @RestrictToGLCompany int, @CompanyGLCompanyKey int
  select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
  from tPreference (nolock)
  where CompanyKey = @OwnerCompanyKey

  if @IsAdministrator <> 1 and @RestrictToGLCompany = 1
  begin
    select @CompanyGLCompanyKey = GLCompanyKey from tCompany (nolock) where CompanyKey = @CompanyKey

    if not exists (select 1 from tUserGLCompanyAccess (nolock) where UserKey = @UserKey and GLCompanyKey = @CompanyGLCompanyKey)
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You do not have access to this company based on your GL company restrictions.'', ''companyKey'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -103
    end
  end

  -- Name-based resolution for staff/entity references. Each is seeded from the current row
  -- when the caller doesn''t supply a name, so an update that only touches unrelated fields
  -- leaves these assignments unchanged.
  declare
    @PrimaryContact int, @AccountManagerKey int, @SalesPersonKey int, @ContactOwnerKey int,
    @ProjectManagerKey int, @BillingManagerKey int, @PaymentTermsKey int, @GLCompanyKey int,
    @OfficeKey int, @ParentCompanyKey int, @ParentCompany tinyint

  select @PrimaryContact = isnull(PrimaryContact, 0),
         @AccountManagerKey = isnull(AccountManagerKey, 0),
         @SalesPersonKey = isnull(SalesPersonKey, 0),
         @ContactOwnerKey = isnull(ContactOwnerKey, 0),
         @ProjectManagerKey = isnull(ProjectManagerKey, 0),
         @BillingManagerKey = isnull(BillingManagerKey, 0),
         @PaymentTermsKey = isnull(PaymentTermsKey, 0),
         @GLCompanyKey = isnull(GLCompanyKey, 0),
         @OfficeKey = isnull(OfficeKey, 0),
         @ParentCompanyKey = ParentCompanyKey,
         @ParentCompany = isnull(ParentCompany, 0)
  from tCompany (nolock)
  where CompanyKey = @CompanyKey

  if @PrimaryContactName is not null and LTRIM(RTRIM(@PrimaryContactName)) <> ''''
  begin
    select top 1 @PrimaryContact = UserKey from tUser (nolock)
      where OwnerCompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @PrimaryContactName order by UserKey
    if @PrimaryContact = 0
      select top 1 @PrimaryContact = UserKey from tUser (nolock)
        where OwnerCompanyKey = @OwnerCompanyKey and Active = 1 and Email = @PrimaryContactName order by UserKey
    if @PrimaryContact = 0
      select top 1 @PrimaryContact = UserKey from tUser (nolock)
        where OwnerCompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @PrimaryContactName order by UserKey
    if @PrimaryContact = 0
      select top 1 @PrimaryContact = UserKey from tUser (nolock)
        where OwnerCompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @PrimaryContactName + ''%'' order by UserKey
    if @PrimaryContact = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Contact not found for primaryContact: '' + @PrimaryContactName, ''primaryContact'')
  end

  if @AccountManagerName is not null and LTRIM(RTRIM(@AccountManagerName)) <> ''''
  begin
    select top 1 @AccountManagerKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @AccountManagerName order by UserKey
    if @AccountManagerKey = 0
      select top 1 @AccountManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @AccountManagerName order by UserKey
    if @AccountManagerKey = 0
      select top 1 @AccountManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @AccountManagerName order by UserKey
    if @AccountManagerKey = 0
      select top 1 @AccountManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @AccountManagerName + ''%'' order by UserKey
    if @AccountManagerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for accountManager: '' + @AccountManagerName, ''accountManager'')
  end

  if @SalesPersonName is not null and LTRIM(RTRIM(@SalesPersonName)) <> ''''
  begin
    select top 1 @SalesPersonKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @SalesPersonName order by UserKey
    if @SalesPersonKey = 0
      select top 1 @SalesPersonKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @SalesPersonName order by UserKey
    if @SalesPersonKey = 0
      select top 1 @SalesPersonKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @SalesPersonName order by UserKey
    if @SalesPersonKey = 0
      select top 1 @SalesPersonKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @SalesPersonName + ''%'' order by UserKey
    if @SalesPersonKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for salesPerson: '' + @SalesPersonName, ''salesPerson'')
  end

  if @ContactOwnerName is not null and LTRIM(RTRIM(@ContactOwnerName)) <> ''''
  begin
    select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @ContactOwnerName order by UserKey
    if @ContactOwnerKey = 0
      select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @ContactOwnerName order by UserKey
    if @ContactOwnerKey = 0
      select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @ContactOwnerName order by UserKey
    if @ContactOwnerKey = 0
      select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @ContactOwnerName + ''%'' order by UserKey
    if @ContactOwnerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for companyOwner: '' + @ContactOwnerName, ''companyOwner'')
  end

  if @ProjectManagerName is not null and LTRIM(RTRIM(@ProjectManagerName)) <> ''''
  begin
    select top 1 @ProjectManagerKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @ProjectManagerName order by UserKey
    if @ProjectManagerKey = 0
      select top 1 @ProjectManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @ProjectManagerName order by UserKey
    if @ProjectManagerKey = 0
      select top 1 @ProjectManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @ProjectManagerName order by UserKey
    if @ProjectManagerKey = 0
      select top 1 @ProjectManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @ProjectManagerName + ''%'' order by UserKey
    if @ProjectManagerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for projectManager: '' + @ProjectManagerName, ''projectManager'')
  end

  if @BillingManagerName is not null and LTRIM(RTRIM(@BillingManagerName)) <> ''''
  begin
    select top 1 @BillingManagerKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @BillingManagerName order by UserKey
    if @BillingManagerKey = 0
      select top 1 @BillingManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @BillingManagerName order by UserKey
    if @BillingManagerKey = 0
      select top 1 @BillingManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @BillingManagerName order by UserKey
    if @BillingManagerKey = 0
      select top 1 @BillingManagerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @BillingManagerName + ''%'' order by UserKey
    if @BillingManagerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for billingManager: '' + @BillingManagerName, ''billingManager'')
  end

  if @PaymentTermsName is not null and LTRIM(RTRIM(@PaymentTermsName)) <> ''''
  begin
    select @PaymentTermsKey = PaymentTermsKey from tPaymentTerms (nolock)
      where CompanyKey = @OwnerCompanyKey and TermsDescription = @PaymentTermsName
    if isnull(@PaymentTermsKey, 0) = 0
      select @PaymentTermsKey = PaymentTermsKey from tPaymentTerms (nolock)
        where CompanyKey = @OwnerCompanyKey and TermsDescription like ''%'' + @PaymentTermsName + ''%''
    if isnull(@PaymentTermsKey, 0) = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Payment terms not found: '' + @PaymentTermsName, ''paymentTerms'')
  end

  if @GLCompanyName is not null and LTRIM(RTRIM(@GLCompanyName)) <> ''''
  begin
    select @GLCompanyKey = GLCompanyKey from tGLCompany (nolock)
      where CompanyKey = @OwnerCompanyKey and GLCompanyName like ''%'' + @GLCompanyName + ''%''
    if isnull(@GLCompanyKey, 0) = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyName, ''glCompany'')
  end

  if @OfficeName is not null and LTRIM(RTRIM(@OfficeName)) <> ''''
  begin
    select @OfficeKey = OfficeKey from tOffice (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and OfficeName like ''%'' + @OfficeName + ''%''
    if isnull(@OfficeKey, 0) = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Office not found: '' + @OfficeName, ''office'')
  end

  if @ParentCompanyName is not null and LTRIM(RTRIM(@ParentCompanyName)) <> ''''
  begin
    select @ParentCompanyKey = CompanyKey from tCompany (nolock)
      where OwnerCompanyKey = @OwnerCompanyKey and CompanyKey <> @CompanyKey and CompanyName = @ParentCompanyName
    if isnull(@ParentCompanyKey, 0) = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Parent company not found: '' + @ParentCompanyName, ''parentCompany'')
    else
      select @ParentCompany = 1
  end

  -- Resolve BillingAddressKey by name: addressName is a lookup against this company''s existing
  -- addresses, not a raw key the caller has to already know. Wins over an explicit
  -- billingAddressKey param if both are supplied.
  declare @ResolvedBillingAddressKey int
  if @AddressName is not null and LTRIM(RTRIM(@AddressName)) <> ''''
  begin
    select @ResolvedBillingAddressKey = AddressKey
    from tAddress (nolock)
    where CompanyKey = @CompanyKey
      and AddressName = @AddressName

    if isnull(@ResolvedBillingAddressKey, 0) = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''Address not found for addressName: '' + @AddressName, ''addressName'')
  end

  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Partial-update-safe defaults: seed every remaining optional param from the current row so a
  -- caller that only supplies e.g. hourlyRate doesn''t blank out everything else --
  -- sptCompanyUpdateClient itself does a full-row overwrite with no ISNULL preservation.
  select
    @CustomerID = isnull(@CustomerID, CustomerID),
    @BillableClient = isnull(@BillableClient, isnull(BillableClient, 0)),
    @Phone = isnull(@Phone, Phone),
    @Fax = isnull(@Fax, Fax),
    @WebSite = isnull(@WebSite, WebSite),
    @TwitterID = isnull(@TwitterID, TwitterID),
    @Comments = isnull(@Comments, CAST(Comments as varchar(2000))),
    @CurrencyID = isnull(@CurrencyID, CurrencyID),
    @EINNumber = isnull(@EINNumber, EINNumber),
    @BillingName = isnull(@BillingName, BillingName),
    @DefaultAddressKey = isnull(@DefaultAddressKey, isnull(DefaultAddressKey, -1)),
    @BillingAddressKey = isnull(@ResolvedBillingAddressKey, isnull(@BillingAddressKey, isnull(BillingAddressKey, 0))),
    @GetRateFrom = isnull(@GetRateFrom, isnull(GetRateFrom, 1)),
    @TimeRateSheetKey = isnull(@TimeRateSheetKey, isnull(TimeRateSheetKey, 0)),
    @HourlyRate = isnull(@HourlyRate, isnull(HourlyRate, 0)),
    @GetMarkupFrom = isnull(@GetMarkupFrom, isnull(GetMarkupFrom, 1)),
    @ItemRateSheetKey = isnull(@ItemRateSheetKey, isnull(ItemRateSheetKey, 0)),
    @ItemMarkup = isnull(@ItemMarkup, isnull(ItemMarkup, 0)),
    @IOCommission = isnull(@IOCommission, isnull(IOCommission, 0)),
    @BCCommission = isnull(@BCCommission, isnull(BCCommission, 0)),
    @IOBillAt = isnull(@IOBillAt, isnull(IOBillAt, 0)),
    @BCBillAt = isnull(@BCBillAt, isnull(BCBillAt, 0)),
    @DefaultBillingMethod = isnull(@DefaultBillingMethod, isnull(DefaultBillingMethod, 1)),
    @DefaultARLineFormat = isnull(@DefaultARLineFormat, isnull(DefaultARLineFormat, 0)),
    @DefaultFFLineFormat = isnull(@DefaultFFLineFormat, DefaultFFLineFormat),
    @DefaultRetainerKey = isnull(@DefaultRetainerKey, isnull(DefaultRetainerKey, 0)),
    @OneInvoicePer = isnull(@OneInvoicePer, isnull(OneInvoicePer, 0)),
    @DefaultExpensesNotIncluded = isnull(@DefaultExpensesNotIncluded, isnull(DefaultExpensesNotIncluded, 0)),
    @DefaultSalesAccountKey = isnull(@DefaultSalesAccountKey, isnull(DefaultSalesAccountKey, 0)),
    @DefaultARAccountKey = isnull(@DefaultARAccountKey, isnull(DefaultARAccountKey, 0)),
    @SalesTaxKey = isnull(@SalesTaxKey, isnull(SalesTaxKey, 0)),
    @SalesTax2Key = isnull(@SalesTax2Key, isnull(SalesTax2Key, 0)),
    @InvoiceTemplateKey = isnull(@InvoiceTemplateKey, isnull(InvoiceTemplateKey, 0)),
    @EstimateTemplateKey = isnull(@EstimateTemplateKey, isnull(EstimateTemplateKey, 0)),
    @EstimateLaborTaxable = isnull(@EstimateLaborTaxable, EstimateLaborTaxable),
    @TitleRateSheetKey = isnull(@TitleRateSheetKey, isnull(TitleRateSheetKey, 0)),
    @DefaultTeamKey = isnull(@DefaultTeamKey, isnull(DefaultTeamKey, 0)),
    @NextProjectNum = isnull(@NextProjectNum, isnull(NextProjectNum, 1)),
    @NextCampaignNum = isnull(@NextCampaignNum, isnull(NextCampaignNum, 1)),
    @IncludeRetainerOnClientWorksheet = isnull(@IncludeRetainerOnClientWorksheet, isnull(IncludeRetainerOnClientWorksheet, 0)),
    @Overhead = isnull(@Overhead, isnull(Overhead, 0)),
    @ActiveClient = isnull(@ActiveClient, isnull(ActiveClient, 1)),
    @DoNotUse = isnull(@DoNotUse, DoNotUse),
    @CCReceipts = isnull(@CCReceipts, isnull(CCReceipts, 0)),
    @DefaultProjectsNonBillable = isnull(@DefaultProjectsNonBillable, isnull(DefaultProjectsNonBillable, 0)),
    @FixedFeeAddProjectLine = isnull(@FixedFeeAddProjectLine, isnull(FixedFeeAddProjectLine, 0)),
    @ForecastForceToFF = isnull(@ForecastForceToFF, isnull(ForecastForceToFF, 0)),
    @AllTrackBudgetTasksOnInvoice = isnull(@AllTrackBudgetTasksOnInvoice, isnull(AllTrackBudgetTasksOnInvoice, 0)),
    @LockLaborRate = isnull(@LockLaborRate, isnull(LockLaborRate, 0)),
    @LockMarkupFrom = isnull(@LockMarkupFrom, isnull(LockMarkupFrom, 0)),
    @RequireCommentsOnTime = isnull(@RequireCommentsOnTime, isnull(RequireCommentsOnTime, 0)),
    @BillingEmailContactKey = isnull(@BillingEmailContactKey, isnull(BillingEmailContact, 0)),
    @ProjectColor = isnull(@ProjectColor, ProjectColor),
    @LayoutKey = isnull(@LayoutKey, isnull(LayoutKey, 0)),
    @AvalaraTaxExempt = isnull(@AvalaraTaxExempt, isnull(AvalaraTaxExempt, 0)),
    @AvalaraTaxExemptReason = isnull(@AvalaraTaxExemptReason, AvalaraTaxExemptReason),
    @AvalaraTaxCodeKey = isnull(@AvalaraTaxCodeKey, AvalaraTaxCodeKey),
    @KeyPeople1 = isnull(@KeyPeople1, KeyPeople1),
    @KeyPeople2 = isnull(@KeyPeople2, KeyPeople2),
    @KeyPeople3 = isnull(@KeyPeople3, KeyPeople3),
    @KeyPeople4 = isnull(@KeyPeople4, KeyPeople4),
    @KeyPeople5 = isnull(@KeyPeople5, KeyPeople5),
    @KeyPeople6 = isnull(@KeyPeople6, KeyPeople6),
    @DateConverted = isnull(@DateConverted, DateConverted),
    @ParentCompanyDivisionKey = isnull(@ParentCompanyDivisionKey, ParentCompanyDivisionKey)
  from tCompany (nolock)
  where CompanyKey = @CompanyKey

  -- Default address merge: only when the caller is touching the address (AddressName supplied).
  -- Resolve which address is being edited, then fill in any field the caller omitted from the
  -- current row for that address so a partial address update doesn''t blank the rest.
  if @AddressName is not null
  begin
    declare @MergeAddressKey int = isnull(@DefaultAddressKey, -1)
    if @MergeAddressKey = -1
      select @MergeAddressKey = isnull(DefaultAddressKey, -1) from tCompany (nolock) where CompanyKey = @CompanyKey

    if @MergeAddressKey > 0
    begin
      select
        @Address1 = isnull(@Address1, Address1),
        @Address2 = isnull(@Address2, Address2),
        @Address3 = isnull(@Address3, Address3),
        @City = isnull(@City, City),
        @State = isnull(@State, State),
        @PostalCode = isnull(@PostalCode, PostalCode),
        @Country = isnull(@Country, Country)
      from tAddress (nolock)
      where AddressKey = @MergeAddressKey

      select @DefaultAddressKey = @MergeAddressKey
    end
    else
      select @DefaultAddressKey = -1
  end

  begin try

    exec @CompanyKey = sptCompanyUpdateClient
      @CompanyKey = @CompanyKey,
      @OwnerCompanyKey = @OwnerCompanyKey,
      @CompanyName = @CompanyName,
      @CustomerID = @CustomerID,
      @Address1 = @Address1,
      @Address2 = @Address2,
      @Address3 = @Address3,
      @City = @City,
      @State = @State,
      @PostalCode = @PostalCode,
      @Country = @Country,
      @PrimaryContact = @PrimaryContact,
      @BillableClient = @BillableClient,
      @DefaultSalesAccountKey = @DefaultSalesAccountKey,
      @GetRateFrom = @GetRateFrom,
      @TimeRateSheetKey = @TimeRateSheetKey,
      @HourlyRate = @HourlyRate,
      @GetMarkupFrom = @GetMarkupFrom,
      @ItemRateSheetKey = @ItemRateSheetKey,
      @ItemMarkup = @ItemMarkup,
      @IOCommission = @IOCommission,
      @BCCommission = @BCCommission,
      @BAddress1 = NULL, @BAddress2 = NULL, @BAddress3 = NULL, @BCity = NULL, @BState = NULL, @BPostalCode = NULL, @BCountry = NULL,
      @WebSite = @WebSite,
      @Phone = @Phone,
      @Fax = @Fax,
      @AccountManagerKey = @AccountManagerKey,
      @DefaultTeamKey = @DefaultTeamKey,
      @Comments = @Comments,
      @NextProjectNum = @NextProjectNum,
      @SalesTaxKey = @SalesTaxKey,
      @SalesTax2Key = @SalesTax2Key,
      @InvoiceTemplateKey = @InvoiceTemplateKey,
      @EstimateTemplateKey = @EstimateTemplateKey,
      @IOBillAt = @IOBillAt,
      @BCBillAt = @BCBillAt,
      @PaymentTermsKey = @PaymentTermsKey,
      @DefaultARLineFormat = @DefaultARLineFormat,
      @DefaultRetainerKey = @DefaultRetainerKey,
      @DefaultBillingMethod = @DefaultBillingMethod,
      @OneInvoicePer = @OneInvoicePer,
      @DefaultExpensesNotIncluded = @DefaultExpensesNotIncluded,
      @AddressName = @AddressName,
      @DefaultAddressKey = @DefaultAddressKey,
      @BillingAddressKey = @BillingAddressKey,
      @Overhead = @Overhead,
      @GLCompanyKey = @GLCompanyKey,
      @OfficeKey = @OfficeKey,
      @BillingManagerKey = @BillingManagerKey,
      @ProjectColor = @ProjectColor,
      @LockLaborRate = @LockLaborRate,
      @LockMarkupFrom = @LockMarkupFrom,
      @DateConverted = @DateConverted,
      @BillingName = @BillingName,
      @SalesPersonKey = @SalesPersonKey,
      @TwitterID = @TwitterID,
      @ContactOwnerKey = @ContactOwnerKey,
      @TitleRateSheetKey = @TitleRateSheetKey,
      @BillingEmailContact = @BillingEmailContactKey,
      @ParentCompany = @ParentCompany,
      @ParentCompanyKey = @ParentCompanyKey,
      @ParentCompanyDivisionKey = @ParentCompanyDivisionKey,
      @CurrencyID = @CurrencyID,
      @LayoutKey = @LayoutKey,
      @NextCampaignNum = @NextCampaignNum,
      @DefaultARAccountKey = @DefaultARAccountKey,
      @IncludeRetainerOnClientWorksheet = @IncludeRetainerOnClientWorksheet,
      @DefaultFFLineFormat = @DefaultFFLineFormat,
      @EINNumber = @EINNumber,
      @EstimateLaborTaxable = @EstimateLaborTaxable,
      @UserKey = @UserKey,
      @ProjectManagerKey = @ProjectManagerKey,
      @DoNotUse = @DoNotUse,
      @CCReceipts = @CCReceipts,
      @DefaultProjectsNonBillable = @DefaultProjectsNonBillable,
      @FixedFeeAddProjectLine = @FixedFeeAddProjectLine,
      @ForecastForceToFF = @ForecastForceToFF,
      @AllTrackBudgetTasksOnInvoice = @AllTrackBudgetTasksOnInvoice,
      @ActiveClient = @ActiveClient,
      @AvalaraTaxExempt = @AvalaraTaxExempt,
      @AvalaraTaxExemptReason = @AvalaraTaxExemptReason,
      @AvalaraTaxCodeKey = @AvalaraTaxCodeKey,
      @RequireCommentsOnTime = @RequireCommentsOnTime,
      @KeyPeople1 = @KeyPeople1,
      @KeyPeople2 = @KeyPeople2,
      @KeyPeople3 = @KeyPeople3,
      @KeyPeople4 = @KeyPeople4,
      @KeyPeople5 = @KeyPeople5,
      @KeyPeople6 = @KeyPeople6

    if @CompanyKey = -400
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''DUPLICATE'', ''This Client ID has already been assigned to another Billable Client.'', ''customerID'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -102
    end
    if @CompanyKey = -401
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''INVALID_VALUE'', ''Cannot deactivate this client as a Billable Client -- it has active projects.'', ''billableClient'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -102
    end
    if @CompanyKey = -402
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''INVALID_VALUE'', ''Cannot deactivate this client as a Billable Client -- it has invoices.'', ''billableClient'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -102
    end
    if @CompanyKey = -403
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''INVALID_VALUE'', ''Cannot deactivate this client as a Billable Client -- it has receipts/checks on file.'', ''billableClient'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -102
    end
    if isnull(@CompanyKey, 0) <= 0
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', ''Client update failed (code '' + CAST(isnull(@CompanyKey,0) as varchar(20)) + '').'', ''general'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -100
    end

    -- Make sure the editing user isn''t locked out of this record if RestrictToGLCompany is on
    exec sptGLCompanyAccessInsertDefaults
        @Entity              = ''tCompany'',
        @EntityKey           = @CompanyKey,
        @UserKey             = @UserKey,
        @CompanyKey          = @OwnerCompanyKey,
        @CheckForExistingRow = 1

    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    select c.CompanyKey        as companyKey,
           c.CompanyName       as companyName,
           c.CustomerID        as clientId,
           c.BillableClient    as billableClient,
           c.ActiveClient      as activeClient
    from tCompany c (nolock)
    where c.CompanyKey = @CompanyKey

    drop table #errors

    RETURN @CompanyKey

  end try
  begin catch

    declare @ErrMsg nvarchar(4000) = ERROR_MESSAGE()
    declare @ErrSeverity int = ERROR_SEVERITY()

    if object_id(''tempdb..#errors'') is not null
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', @ErrMsg, ''general'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
    end

    RAISERROR(@ErrMsg, @ErrSeverity, 1)
    return -100

  end catch
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectTimeLineGetApp]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectTimeLineGetApp]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptProjectTimeLineGetApp]
	@ProjectKey int,
	@UserKey int,
	@ShowTimeEntries int = 0
	
	
AS -- Encrypt

/*
  || When      Who  Rel       What
  || 02/19/13  RLB  10.5.6.5  Adding for new Project TimeLine
  || 01/19/16  GAR  10.6.0.0  Added sorting by comments as well so all feeds will be in the same order.
  || 07/23/18  RLS  18.8.0.0  (411662) Added Check for system setting as @ShowTimeEntries
  || 09/14/18  MAS  18.9.1.0  Copied from sptProjectTimeLineGet for Platinum to include Spec Sheet changes as well
  || 12/10/20  RLS  20.0.1.0  (539293) Removed AND Action NOT IN (''Spec Sheet Updated'') as well as AND al.Comments NOT LIKE ''Spec Sheet Updated%''
  || 02/11/21  KMC  21.03.14  Removed the tActionLog.Comments from the order by
  || 07/30/26  GWG  26.08.15  Added UserKey condition to specsheets 
*/

DECLARE @CompanyKey INT
SELECT @CompanyKey = CompanyKey From tProject WHERE ProjectKey = @ProjectKey
	
IF @ShowTimeEntries = 1
	SELECT *
	FROM vActionLog (nolock)
	WHERE ProjectKey = @ProjectKey
	AND CompanyKey = @CompanyKey
	and (@UserKey = 0 or UserKey = @UserKey)
	
	UNION

	SELECT al.*
	FROM vActionLog al (nolock)
	INNER JOIN tSpecSheet ss (nolock) ON SpecSheetKey = al.EntityKey
	WHERE al.Entity = ''Spec Sheets''
	AND al.CompanyKey = @CompanyKey
	and (@UserKey = 0 or al.UserKey = @UserKey)
	AND ss.Entity = ''Project'' AND ss.EntityKey = @ProjectKey

	Order By ActionDate DESC
	
ELSE
	SELECT *
	FROM vActionLog (nolock)
	WHERE ProjectKey = @ProjectKey
	AND CompanyKey = @CompanyKey
	and (@UserKey = 0 or UserKey = @UserKey)
	and Action <> ''Time Entered''

	UNION

	SELECT al.*
	FROM vActionLog al (nolock)
	INNER JOIN tSpecSheet ss (nolock) ON SpecSheetKey = al.EntityKey
	WHERE al.Entity = ''Spec Sheets''
	AND al.CompanyKey = @CompanyKey
	and (@UserKey = 0 or al.UserKey = @UserKey)
	AND ss.Entity = ''Project'' AND ss.EntityKey = @ProjectKey

	Order By ActionDate DESC

	RETURN 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptReportGroupGetList]'
GO
IF OBJECT_ID(N'[dbo].[sptReportGroupGetList]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptReportGroupGetList]

	@CompanyKey INT,
	@UserKey INT = 0,
	@GetMin TINYINT = 0


AS --Encrypt
/*
|| When      Who Rel      What
|| 03/12/20  RLB 20.0.4.0 (501851) added to pull report dash data
|| 03/19/20  RLB 20.0.4.0 fixed hasReport check
|| 05/24/21  AMP 21.06.20.0000 (559180) Bug Fix - Private reports were not being displayed unless your security group has at least one public report regardless of Report Groupings
||                                                Now the reports will be displayed if they are private and you are the owner.
|| 11/06/23  RLB 23.12.17 (655573) in has right added check for user security access
|| 12/06/23  RLS 23.12.17 (658188) Replaced hard-coded UserKey with  @UserKey
|| 07/30/26  RLB 26.08.16 (733986) Updated to break out the JOINS to three separate queries with the UNION ALL to increase performance
*/
	IF @GetMin = 0
		SELECT *
		FROM tReportGroup (NOLOCK)
		WHERE
		CompanyKey = @CompanyKey
		ORDER BY GroupType, DisplayOrder
	ELSE
	BEGIN
		DECLARE	@SecurityGroupKey INT
		SELECT @SecurityGroupKey = SecurityGroupKey
		FROM tUser (NOLOCK) 
		WHERE UserKey = @UserKey

		SELECT rg.*
			  ,ISNULL((SELECT TOP 1 1
		FROM tReport r (NOLOCK)
		WHERE rg.ReportGroupKey = r.ReportGroupKey), 0) AS HasReports
		, ISNULL(
		(
		SELECT TOP 1 1
		FROM (
			SELECT 1 as HasRight
			FROM tReport r (NOLOCK)
			JOIN tRptSecurityGroup sec (NOLOCK) ON sec.ReportKey = r.ReportKey
			WHERE r.ReportGroupKey = rg.ReportGroupKey
			AND sec.SecurityGroupKey = @SecurityGroupKey

			UNION ALL

			SELECT 1 as HasRight
			FROM tReport r (NOLOCK)
			WHERE r.ReportGroupKey = rg.ReportGroupKey
			AND r.UserKey = @UserKey

			UNION ALL

			SELECT 1 AS HasRight
			FROM tReport r (NOLOCK)
			JOIN tSecurityAccess seca (NOLOCK) ON seca.EntityKey = r.ReportKey AND seca.Entity = ''tReport''
			WHERE r.ReportGroupKey = rg.ReportGroupKey
			AND seca.UserKey = @UserKey
		) x
		), 0) AS HasRight
		FROM tReportGroup rg (NOLOCK)
		WHERE CompanyKey = @CompanyKey
		ORDER BY DisplayOrder
	END
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spMassBillingBillAdvance]'
GO
IF OBJECT_ID(N'[dbo].[spMassBillingBillAdvance]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[spMassBillingBillAdvance]
	(
	@CompanyKey int
	,@UserKey int
	,@InvoiceBy int -- 0 By Project, 1 By Client, 2 By Client Parent
	,@BillingStatusKey int
	,@InvoiceDate smalldatetime
	,@PostingDate smalldatetime
	,@DefaultUIClassKey INT = NULL	-- This is already validated on the screen
	,@DefaultUIOfficeKey INT = NULL	-- This is already validated on the screen
	,@CreateAsApproved INT = 0
	)

	as --Encrypt

 /*
  || When     Who Rel     What
  || 03/03/16 GHL 10.602  Creation for new mass billing
  ||                      For projects with billing schedule, we need to create an advance bill 
  || 07/21/16 GHL 10.606 Added action logging for MN''s ToDo 
  || 10/02/17 GHL 10.621 (363756) Added default AR account from client
  || 11/15/18 GHL 18.893 (431436) Added logic for Dollar Amount on the billing schedule
  || 01/07/19 GHL 19.100 (438663) Make sure that #project.GLCompanyKey = 0 instead of null to work correctly in the loops
  || 01/27/20 GHL 20.030 (495024) Get the invoice template from the GL company if tPreference.LayoutFromGLCompany = 1
  || 06/10/21 GHL 21.060 Fixed bad join when updating tProject.ProjectBillingStatusKey
  || 03/18/22 GHL 22.040 (590582) Added support for tProject.SetTaxableOnInvoice
  || 01/09/25 MFT 25.010 (691628) Override LayoutKey defaulting to the Client when billing by Project
  || 11/04/25 MCM 25.11.x (656423) Added Liability Account Key when calling sptInvoiceInsert
  || 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
  || 06/25/26 GAR 26.07.19 (729634) Added Comments from the billing schedule to the header comment of the invoice
  || 07/08/26 AMP 26.07.19 (729259) Populate BilledComment on tBillingSchedule when invoiced from T&M mass billing advance
 */

 /*
 Assume done and filled in vb

 create table #proj (ProjectKey int null, BillingScheduleKey int null)
 */


 create table #project (ProjectKey int null, BillingScheduleKey int null, BudgetAmount money null, BillAmount money null, TaskKey int null
	, ParentClientKey int null, ClientKey int null, LoopClientKey int null, GLCompanyKey int null, CurrencyID varchar(10) null, CurrencyKey int null)

 insert #project (ProjectKey, BillingScheduleKey, CurrencyKey)
 select ProjectKey, BillingScheduleKey, 0
 from   #proj

 update #project
 set    #project.BudgetAmount = ISNULL(p.EstLabor, 0) + ISNULL(ApprovedCOLabor, 0) + ISNULL(EstExpenses, 0) + ISNULL(ApprovedCOExpense, 0) 
       ,#project.ClientKey = p.ClientKey
	   ,#project.GLCompanyKey = isnull(p.GLCompanyKey, 0) -- not NULL for the loops
	   ,#project.CurrencyID = p.CurrencyID
 from   tProject p (nolock)
 where  p.ProjectKey = #project.ProjectKey

update #project
 set   #project.BillAmount = case when bs.PercentBudget is null then bs.DollarAmount else round((#project.BudgetAmount * bs.PercentBudget )/100.00, 2) end
      ,#project.TaskKey = bs.TaskKey
from   tBillingSchedule bs (nolock)
where  #project.BillingScheduleKey = bs.BillingScheduleKey

update #project
set    #project.ParentClientKey = c.ParentCompanyKey
from   tCompany c (nolock)
where  #project.ClientKey = c.CompanyKey 
  
If @InvoiceBy in (0, 1)
begin
	-- by project / client
	update #project
	set    LoopClientKey = ClientKey 
end

If @InvoiceBy = 2
begin
	-- by parent client
	update #project
	set    LoopClientKey = ParentClientKey

	update #project
	set    LoopClientKey = ClientKey
	where  isnull(LoopClientKey, 0) = 0 
end

-- cannot bill without a client
delete #project
where  isnull(LoopClientKey, 0) = 0 

declare @ProjectKey int
declare @GLCompanyKey int
declare @ClientKey int
declare @CurrencyID varchar(10)
declare @CurrencyKey int
declare @BillingScheduleKey int
declare @NewInvoiceKey int
declare @NewInvoiceLineKey int
declare @BillingContact varchar(100)
declare @PrimaryContactKey int 
declare @DefaultSalesAccountKey int
declare @RetVal int
declare @TodaysDate smalldatetime
declare @DueDate smalldatetime
declare @DueDays int
declare @LineSubject varchar(100)
declare @WorkTypeKey int
Declare @ARAccountKey int 
Declare @SalesGLAccountKey int 
Declare @InvoiceTemplateKey int
Declare @LayoutKey int
Declare @BillingAddressKey int
declare @CampaignKey int
declare @OfficeKey int
declare @ClassKey int
declare @BillAmount money
declare @TaskKey int
Declare @SalesTaxKey int, @SalesTax2Key int, @PaymentTermsKey int
declare @SetTaxableOnInvoice int

declare @NextTranNo varchar(100)
declare @InvoiceStatus int
declare @ApprovedByKey int

Declare @RequireClasses tinyint
declare @DefaultClassKey int
declare @DefaultARAccountKey int
declare @DefaultAdvBillAccountKey int
declare @DefaultPaymentTermsKey int
declare @PostSalesUsingDetail tinyint
declare @LayoutFromGLCompany int
declare @AdvBillAccountKey int
declare @LiabilityAccountKey int
declare @AdvanceBill tinyint

declare @HeaderComment varchar(4000)

-- Variables for logging 
declare	@Entity varchar(50),
		@EntityKey int,
		@Action varchar(200),
		@ActionDate smalldatetime,
		@ActionBy varchar(500),
		@Comments varchar(4000),
		@Reference varchar(200),
		@SourceCompanyID varchar(100),
		@LogCampaignKey int
	
	-- get company preferences
	Select @PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
			,@DefaultARAccountKey = DefaultARAccountKey
			,@DefaultAdvBillAccountKey = AdvBillAccountKey
			,@WorkTypeKey         = AdvBillItemKey
			,@RequireClasses      = ISNULL(RequireClasses, 0)
			,@DefaultClassKey     = DefaultClassKey
			,@DefaultPaymentTermsKey = PaymentTermsKey
			,@DefaultSalesAccountKey = DefaultSalesAccountKey
			,@LayoutFromGLCompany  = ISNULL(LayoutFromGLCompany,0)
			,@SetTaxableOnInvoice = isnull(SetTaxableOnInvoice, 0)
			,@AdvBillAccountKey = AdvBillAccountKey
	From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	-- We can manufacture CurrencyKey to use in the loops
	-- CurrencyKey initialized at 0 -- Home Currency
	select @CurrencyID = ''''
	Select @CurrencyKey = 1
	while (1=1)
	begin
		select @CurrencyID = min(CurrencyID)
		from   #project
		where  CurrencyID is not null
		and    CurrencyID > @CurrencyID

		if @CurrencyID is null
			break

		update #project
		set    CurrencyKey = @CurrencyKey 
		where  CurrencyID = @CurrencyID

		select @CurrencyKey = @CurrencyKey + 1
	end


	-- If Invoice By Project
	if @InvoiceBy = 0
	begin
		select @ProjectKey = -1
		while (1=1)
		begin
			select @ProjectKey = min(ProjectKey)
			from   #project
			where  ProjectKey > @ProjectKey
			 
			if @ProjectKey is null
				break

			select @ClientKey = ClientKey
			      ,@CurrencyID = CurrencyID
				  ,@BillAmount = BillAmount
				  ,@TaskKey = TaskKey
				  ,@BillingScheduleKey = BillingScheduleKey
			from   #project (nolock)
			where ProjectKey = @ProjectKey
		
			--get invoice defaults from project
			select @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
					,@PrimaryContactKey = u.UserKey
					,@LineSubject = p.ProjectName
					,@CampaignKey = p.CampaignKey
					,@GLCompanyKey = p.GLCompanyKey 
					,@OfficeKey = p.OfficeKey
					,@ClassKey = p.ClassKey
					,@LayoutKey = CASE WHEN p.LayoutKey = 0 THEN NULL ELSE p.LayoutKey END
			from tProject p (nolock) 
					left outer join tUser u (nolock) on p.BillingContact = u.UserKey
			where p.ProjectKey = @ProjectKey

			-- get other client defaults  
			Select @InvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
					,@SalesTaxKey = SalesTaxKey
					,@SalesTax2Key = SalesTax2Key
					,@SalesGLAccountKey = ISNULL(DefaultSalesAccountKey, 0)
					,@ARAccountKey = ISNULL(DefaultARAccountKey, 0)
					,@PaymentTermsKey = ISNULL(PaymentTermsKey, 0)
					,@BillingAddressKey = BillingAddressKey
					,@LayoutKey = ISNULL(@LayoutKey, LayoutKey)
			from tCompany (nolock)
			Where CompanyKey = @ClientKey

			-- get comments from the billing schedule
			Select @HeaderComment = Comments
			From tBillingSchedule (nolock)
			Where BillingScheduleKey = @BillingScheduleKey

			IF @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
				select @InvoiceTemplateKey = InvoiceTemplateKey 
				from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey

			if isnull(@ClassKey, 0) = 0 and @RequireClasses = 1
				select @ClassKey = @DefaultUIClassKey
			if isnull(@ClassKey, 0) = 0 and @RequireClasses = 1
				select @ClassKey = @DefaultClassKey

			if @PaymentTermsKey = 0
				select @PaymentTermsKey = @DefaultPaymentTermsKey

			IF ISNULL(@PaymentTermsKey, 0) > 0
			BEGIN
				SELECT @DueDays = ISNULL(DueDays, 0)  -- Why are they NULL in the database ???
				FROM   tPaymentTerms (NOLOCK)
				WHERE  PaymentTermsKey = @PaymentTermsKey
		 	
				SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate) 	
			END
			ELSE
				SELECT @DueDate = @InvoiceDate

			if isnull(@ARAccountKey, 0) = 0
				select @ARAccountKey = @DefaultARAccountKey

			-- create invoice
			-- Note: could have used sptInvoiceInsert-ProjectOneLine
			set @LiabilityAccountKey = @AdvBillAccountKey
			select @NewInvoiceKey = null

			exec @RetVal = sptInvoiceInsert
					@CompanyKey = @CompanyKey,
					@ClientKey = @ClientKey,
					@ContactName = @BillingContact,
					@PrimaryContactKey = @PrimaryContactKey,
					@AddressKey = @BillingAddressKey,
					@AdvanceBill = 1,
					@InvoiceNumber = null,
					@InvoiceDate = @InvoiceDate,
					@DueDate = @DueDate,
					@PostingDate = @PostingDate,
					@TermsKey = @PaymentTermsKey,
					@ARAccountKey = @ARAccountKey,
					@ClassKey = @ClassKey,
					@ProjectKey = @ProjectKey,
					@HeaderComment = @HeaderComment,
					@SalesTaxKey = @SalesTaxKey,
					@SalesTax2Key = @SalesTax2Key,
					@InvoiceTemplateKey = @InvoiceTemplateKey,
					@ApprovedByKey = @UserKey,
					@UserDefined1 = NULL,
					@UserDefined2 = NULL,
					@UserDefined3 = NULL,
					@UserDefined4 = NULL,
					@UserDefined5 = NULL,
					@UserDefined6 = NULL,
					@UserDefined7 = NULL,
					@UserDefined8 = NULL,
					@UserDefined9 = NULL,
					@UserDefined10 = NULL,
					@Downloaded = 0,
					@Printed = 0,
					@ParentInvoice = 0,
					@Emailed = 0,
					@CreatedByKey = @UserKey,
					@GLCompanyKey = @GLCompanyKey,
					@OfficeKey = @OfficeKey,
					@OpeningTransaction = 0,
					@LayoutKey = @LayoutKey,
					@CurrencyID = @CurrencyID,
					@ExchangeRate = 1,
					@RequestExchangeRate = 1, -- set exch rate
					@IsForRetainer = 0,
					@LiabilityAccountKey = @LiabilityAccountKey, -- **NEW PARAMETER ADDED**
					@oIdentity = @NewInvoiceKey OUTPUT -- Maps the output variable

				if @NewInvoiceKey > 0
				begin
					if @InvoiceBy in ( 0, 1) and isnull(@CampaignKey, 0) > 0 
					begin
						update tInvoice
						set    CampaignKey = @CampaignKey
						where  InvoiceKey = @NewInvoiceKey
					end

					If @CreateAsApproved = 1
					BEGIN
	
						--Check to see if the tInvoice Insert SP set the Invoice Number
						SELECT	@NextTranNo = InvoiceNumber,
						        @AdvanceBill = AdvanceBill
						FROM	tInvoice (nolock)
						WHERE	InvoiceKey = @NewInvoiceKey
	
						IF @NextTranNo IS NULL
						BEGIN
							--If the InvoiceNumber has not been set yet, get the next number
							DECLARE @TranType varchar(10) = CASE @AdvanceBill WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

							EXEC spGetNextTranNo
								@CompanyKey,
								@TranType,
								@RetVal		      OUTPUT,
								@NextTranNo 	  OUTPUT
		
							IF @RetVal <> 1
								RETURN -1
						END
	
						update tInvoice
						set	  ApprovedByKey = @UserKey
							 ,InvoiceStatus = 4 -- Approved
							 ,InvoiceNumber = @NextTranNo 
						where InvoiceKey = @NewInvoiceKey

					END
					ELSE
					BEGIN
		
						select @InvoiceStatus = InvoiceStatus
							  ,@ApprovedByKey = ApprovedByKey
						from   tInvoice (nolock)
						where  InvoiceKey = @NewInvoiceKey

						-- only if not already approved and the approver is valid, submit
						if @InvoiceStatus <> 4 And isnull(@ApprovedByKey, 0) > 0
							update tInvoice
							set    InvoiceStatus = 2
							where InvoiceKey = @NewInvoiceKey
					END -- created as approved 


					-- create invoice line
					--create single invoice line
					exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,@TaskKey							-- TaskKey
					  ,@LineSubject					-- Line Subject
					  ,null                 		-- Line description
					  ,1                    		-- Bill From 
					  ,1							-- Quantity
					  ,@BillAmount				-- Unit Amount
					  ,@BillAmount				-- Line Amount
					  ,2							-- line type
					  ,0							-- parent line key
					  ,@DefaultAdvBillAccountKey		-- Default Sales AccountKey
					  ,@ClassKey                    -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,NULL							-- Work TypeKey
					  ,0							-- PostInDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,@OfficeKey
					  ,null							--@DepartmentKey -- may need a department if department required
					  ,@NewInvoiceLineKey output

					 -- This will force the Taxable fields if the pref or the project requires them
					exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

					-- before we leave, better to recalc the amounts in the header  
					exec sptInvoiceRecalcAmounts @NewInvoiceKey 
	
					-- Calculate the line order and position
					exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0

					if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @NewInvoiceKey and ProjectKey = @ProjectKey)
					update tBillingSchedule
					set    InvoiceKey = @NewInvoiceKey
					where  BillingScheduleKey = @BillingScheduleKey 
					and    tBillingSchedule.BillingKey is null
					and    tBillingSchedule.InvoiceKey is null

					EXEC spFixedFeesUpdateBillingSchedule @NewInvoiceKey, @ProjectKey, @BillingScheduleKey

					if isnull(@BillingStatusKey, 0) > 0
					UPDATE tProject
					SET    tProject.ProjectBillingStatusKey = @BillingStatusKey
					WHERE  tProject.ProjectKey = @ProjectKey


					select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @LogCampaignKey = 0

					select @Reference = i.InvoiceNumber
						  ,@SourceCompanyID = c.CustomerID
					from   tInvoice i (nolock)
						left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
					where  i.InvoiceKey = @NewInvoiceKey

					select @Reference = isnull(@Reference,'''')
						  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
					-- the Invoice number may be missing if the user assign #s at approval time
					if len(@Reference) > 0
						select @Comments = ''Invoice '' + @Reference + '' was generated through mass billing as advance bill.''
					else
						select @Comments = ''Invoice was generated through mass billing as advance bill.''

					select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

					exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @LogCampaignKey

				end -- invoice created

		end -- project loop

	end -- by project


	if @InvoiceBy <> 0
	begin
		-- client or parent client

		-- Need to create an invoice per:
		-- GLCompanyKey/Currency/ClientKey

		-- then create an invoice line per project

		SELECT @GLCompanyKey = -1
		WHILE (1=1)
		BEGIN
			SELECT @GLCompanyKey = MIN(GLCompanyKey) FROM #project
			WHERE GLCompanyKey > @GLCompanyKey
		
			IF @GLCompanyKey IS NULL
				BREAK

			SELECT @CurrencyKey = -1
			WHILE (1=1)
			BEGIN
				SELECT @CurrencyKey = MIN(CurrencyKey)
				FROM   #project 
				WHERE  GLCompanyKey   =  @GLCompanyKey	
				AND    CurrencyKey    >  @CurrencyKey
					
				IF @CurrencyKey IS NULL
					BREAK

				select @CurrencyID = CurrencyID from #project
				where  CurrencyKey =  @CurrencyKey -- All same currency IDs should have same key

				SELECT @ClientKey = -1
				WHILE (1=1)
				BEGIN
					SELECT @ClientKey = MIN(LoopClientKey)
					FROM   #project 
					WHERE  GLCompanyKey   =  @GLCompanyKey	
					AND    CurrencyKey    =  @CurrencyKey
					AND    LoopClientKey > @ClientKey
					 
					IF @ClientKey IS NULL
						BREAK

					-- create an invoice for the client

					-- Get the billing contact as the primary contact from the client
					select @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
							,@PrimaryContactKey = u.UserKey
					from tCompany cl (nolock) 
						left outer join tUser u (nolock) on cl.PrimaryContact = u.UserKey
					Where cl.CompanyKey = @ClientKey

					-- get other client defaults  
					Select @InvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
							, @SalesTaxKey = SalesTaxKey
							, @SalesTax2Key = SalesTax2Key
							, @SalesGLAccountKey = ISNULL(DefaultSalesAccountKey, 0)
							, @PaymentTermsKey = ISNULL(PaymentTermsKey, 0)
							, @BillingAddressKey = BillingAddressKey
							, @LayoutKey = LayoutKey
					from tCompany (nolock)
					Where CompanyKey = @ClientKey

					if @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
						select @InvoiceTemplateKey = InvoiceTemplateKey
							  ,@LayoutKey = LayoutKey 
						from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey

					select @ClassKey = @DefaultUIClassKey
					if isnull(@ClassKey, 0) = 0 and @RequireClasses = 1
						select @ClassKey = @DefaultClassKey

					if @PaymentTermsKey = 0
						select @PaymentTermsKey = @DefaultPaymentTermsKey

					IF ISNULL(@PaymentTermsKey, 0) > 0
					BEGIN
						SELECT @DueDays = ISNULL(DueDays, 0)  -- Why are they NULL in the database ???
						FROM   tPaymentTerms (NOLOCK)
						WHERE  PaymentTermsKey = @PaymentTermsKey
		 	
						SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate) 	
					END
					ELSE
						SELECT @DueDate = @InvoiceDate

					exec @RetVal = sptInvoiceInsert
							@CompanyKey = @CompanyKey,
							@ClientKey = @ClientKey,
							@ContactName = @BillingContact,
							@PrimaryContactKey = @PrimaryContactKey,
							@AddressKey = @BillingAddressKey,
							@AdvanceBill = 1,
							@InvoiceNumber = null,
							@InvoiceDate = @InvoiceDate,
							@DueDate = @DueDate,
							@PostingDate = @PostingDate,
							@TermsKey = @PaymentTermsKey,
							@ARAccountKey = @DefaultARAccountKey,
							@ClassKey = @ClassKey,
							@ProjectKey = @ProjectKey,
							@HeaderComment = null,
							@SalesTaxKey = @SalesTaxKey,
							@SalesTax2Key = @SalesTax2Key,
							@InvoiceTemplateKey = @InvoiceTemplateKey,
							@ApprovedByKey = @UserKey,
							@UserDefined1 = NULL,
							@UserDefined2 = NULL,
							@UserDefined3 = NULL,
							@UserDefined4 = NULL,
							@UserDefined5 = NULL,
							@UserDefined6 = NULL,
							@UserDefined7 = NULL,
							@UserDefined8 = NULL,
							@UserDefined9 = NULL,
							@UserDefined10 = NULL,
							@Downloaded = 0,
							@Printed = 0,
							@ParentInvoice = 0,
							@Emailed = 0,
							@CreatedByKey = @UserKey,
							@GLCompanyKey = @GLCompanyKey,
							@OfficeKey = @DefaultUIOfficeKey,
							@OpeningTransaction = 0,
							@LayoutKey = @LayoutKey,
							@CurrencyID = @CurrencyID,
							@ExchangeRate = 1,
							@RequestExchangeRate = 1, -- set exch rate
							@IsForRetainer = 0,
							@LiabilityAccountKey = NULL, -- **NEW PARAMETER ADDED**
							@oIdentity = @NewInvoiceKey OUTPUT -- Maps the output variable
					 
					 if @NewInvoiceKey > 0
					 begin

						If @CreateAsApproved = 1
							BEGIN
	
								--Check to see if the tInvoice Insert SP set the Invoice Number
								SELECT	@NextTranNo = InvoiceNumber
								FROM	tInvoice (nolock)
								WHERE	InvoiceKey = @NewInvoiceKey
	
								IF @NextTranNo IS NULL
								BEGIN
									--If the InvoiceNumber has not been set yet, get the next number
									EXEC spGetNextTranNo
										@CompanyKey,
										''AR'',		-- TranType
										@RetVal		  OUTPUT,
										@NextTranNo   OUTPUT
		
									IF @RetVal <> 1
										RETURN -1
								END
	
								update tInvoice
								set	  ApprovedByKey = @UserKey
									 ,InvoiceStatus = 4 -- Approved
									 ,InvoiceNumber = @NextTranNo 
								where InvoiceKey = @NewInvoiceKey

							END
							ELSE
							BEGIN
		
								select @InvoiceStatus = InvoiceStatus
									  ,@ApprovedByKey = ApprovedByKey
								from   tInvoice (nolock)
								where  InvoiceKey = @NewInvoiceKey

								-- only if not already approved and the approver is valid, submit
								if @InvoiceStatus <> 4 And isnull(@ApprovedByKey, 0) > 0
									update tInvoice
									set    InvoiceStatus = 2
									where InvoiceKey = @NewInvoiceKey
							END -- created as approved 
					 
						-- now create 1 line per project 
						select @ProjectKey = -1

						WHILE (1=1)
						BEGIN
							SELECT @ProjectKey = MIN(ProjectKey)
							FROM   #project 
							WHERE  GLCompanyKey   =  @GLCompanyKey	
							AND    CurrencyKey    =  @CurrencyKey
							AND    LoopClientKey  = @ClientKey
							AND    ProjectKey > @ProjectKey

							IF @ProjectKey IS NULL
								BREAK
						
							select @BillAmount = BillAmount
							      ,@BillingScheduleKey = BillingScheduleKey
								  ,@TaskKey = TaskKey
							from   #project
							where  ProjectKey = @ProjectKey

							select @LineSubject = ProjectName 
							from tProject (nolock)
							where ProjectKey = @ProjectKey
							 
							 exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
							  ,@ProjectKey					-- ProjectKey
							  ,@TaskKey							-- TaskKey
							  ,@LineSubject					-- Line Subject
							  ,null                 		-- Line description
							  ,1                    		-- Bill From 
							  ,1							-- Quantity
							  ,@BillAmount				-- Unit Amount
							  ,@BillAmount				-- Line Amount
							  ,2							-- line type
							  ,0							-- parent line key
							  ,@DefaultAdvBillAccountKey		-- Default Sales AccountKey
							  ,@ClassKey                    -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,NULL							-- Work TypeKey
							  ,0							-- PostInDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,@OfficeKey
							  ,null							--@DepartmentKey -- may need a department if department required
							  ,@NewInvoiceLineKey output

							  update tBillingSchedule
								set    InvoiceKey = @NewInvoiceKey
								where  BillingScheduleKey = @BillingScheduleKey 


						  EXEC spFixedFeesUpdateBillingSchedule @NewInvoiceKey, @ProjectKey, @BillingScheduleKey
						end -- loop on project 

						 -- This will force the Taxable fields if the pref or the project requires them
						exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

						  -- before we leave, better to recalc the amounts in the header  
						exec sptInvoiceRecalcAmounts @NewInvoiceKey 
	
						-- Calculate the line order and position
						exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0
						
						IF @BillingStatusKey IS NOT NULL
							UPDATE tProject
							SET    tProject.ProjectBillingStatusKey = @BillingStatusKey
							FROM   #project b
							where  b.GLCompanyKey   =  @GLCompanyKey	
							AND    b.CurrencyKey    =  @CurrencyKey
							AND    b.LoopClientKey  = @ClientKey
							and    b.ProjectKey = tProject.ProjectKey 

						select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @LogCampaignKey = 0

						select @Reference = i.InvoiceNumber
							  ,@SourceCompanyID = c.CustomerID
						from   tInvoice i (nolock)
							left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
						where  i.InvoiceKey = @NewInvoiceKey

						select @Reference = isnull(@Reference,'''')
							  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
						-- the Invoice number may be missing if the user assign #s at approval time
						if len(@Reference) > 0
							select @Comments = ''Invoice '' + @Reference + '' was generated through mass billing as advance bill.''
						else
							select @Comments = ''Invoice was generated through mass billing as advance bill.''

						select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

						-- pass 0 for ProjectKey 
						exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, 0, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @LogCampaignKey


					 end -- invoice was created

				END -- loop on client
		
						
			END -- loop on Currency
										
		END -- loop on GLCompany
		

	end -- invoice by client/parent client
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_ProjectByItem]'
GO
IF OBJECT_ID(N'[dbo].[vReport_ProjectByItem]', 'V') IS NOT NULL
EXEC sp_executesql N'








ALTER VIEW [dbo].[vReport_ProjectByItem]
AS

/*
|| When      Who Rel     What
|| 10/30/07  CRG 8.5     Created for the custom report dataset: "Project Items/Services".
||                       Also used by spRptItemCampaignSummary.
|| 01/19/10 GHL 10.517  (72527) Added Billing Item info
|| 03/31/10 RLB 10.521  (78028) Added Project Primary Contact and Item Name 
|| 10/1/10  GWG 10.535   Added prebilled purchase orders to the Total Billable Costs
|| 04/07/11 RLB 10.543 (108045) Removed Project Short Name
|| 06/17/11 GHL 10.545  Added collate database_default when comparing entities
|| 07/27/11 RLB 10.546  (111324) Added Campaign Segment
|| 08/30/11 RLB 10.547  (117091) Added Client Full Name, Client ID and Account Manager
|| 08/30/11 RLB 10.547  (118280) Added Campaign Full Name and Campaign ID
|| 09/21/11 RLB 10.548 (119193) Added Project Close Date 
|| 10/10/11 RLB 10.549 (123136) wrapped Project Type Name with an ISNULL
|| 03/07/12 GHL 10.554 (103259) Added [Opportunity Name]
|| 04/24/12 GHL 10.555   Added GLCompanyKey in order to map/restrict
|| 02/13/13 WDF 10.565 (162946) Added Department Name
|| 03/25/13 GWG 10.565 Added Billing Method
|| 05/21/13 KMC 10.568 (178835) Added join to tItem (it2) by vProject_Items.EntityKey to include items not
||                     in tProjectEstByItem
|| 05/22/13 GHL 10.568 Added corrections for 178835 (basic idea is join with view v rather than ebi table)
|| 05/01/14 WDF 10.579 (209489) Added CreatedDate
|| 01/27/15 WDF 10.588 (Abelson Taylor) Added Division and Product ID
|| 11/19/15 MCM 10.598 (278455) Added Total Gross and Net PO 
|| 05/22/17 GHL 10.616 (325759) Added Open Orders Gross Unbilled
|| 04/25/18 RLS 18.5.0 (398138) Added CurrencyID
|| 05/15/18 GWG 18.5.0 added campaign active
|| 01/14/19 GHL 19.2.0 (440306) Added ''Marked as Billed'' amount
|| 05/24/19 AMP 19.0.6.0 (461393) Added Transaction Type
|| 01/29/20 AMP 20.0.2.0 (495852) Added total Allocated Hours for all services on a given project
|| 02/18/20 AMP 20.0.3.0 (500985) Added Campaign Start Date, Campaign End Date and Parent Client 
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 11/17/20 GAR 20.1.2.0 (533327) Added Hours Billed (from the project budget screen)
|| 02/17/21 AMP 21.03.14.0000 (544830) Added Campaign Custom Fields 
|| 02/18/21 GAR 21.03.14.0000 (548858) Added Project Manager
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color and department
|| 08/11/23 RLB 23.09.17 (648008) added project type color
|| 07/02/24 RLB 24.08.18 (672348) Added Labor Unbilled, Outside Costs Gross Unbilled and Total Gross Unbilled from Project Billing Schedule Data 
|| 04/30/26 RLB 26.05.17 (726209) Added Original, Approved and Current Item Budget Quantity. Added Item Quantity
|| 07/27/26 RLS 26.08.16 (731550) Added [Active Item]
*/ 

SELECT	v.CompanyKey
       , p.GLCompanyKey
		,v.Entity
		,v.EntityKey
		,v.ProjectKey
		,p.CustomFieldKey
		,p.ProjectName AS [Project Name]
		,p.ProjectNumber as [Project Number]
		,p.CurrencyID as [Currency]
		,cl.CompanyName as [Client Name]
		,cl.CustomerID as [Client ID]
		,cl.CustomerID + ''-'' + cl.CompanyName as [Client Full Name]
		,p.ClientProjectNumber [Client Project Number]
		,ps.ProjectStatus as [Project Status]
		,pbs.ProjectBillingStatus as [Project Billing Status]
		,ISNULL(pt.ProjectTypeName, '''') as [Project Type]
		,pt.ProjectTypeColor as [Project Type Color]
		,p.StatusNotes as [Project Status Note]
		,p.DetailedNotes as [Project Status Description]
		,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager]
		,cp.CampaignName as [Campaign Name]
		,cp.CampaignID as [Campaign ID]
		,cp.CampaignID + ''-'' + cp.CampaignName as [Campaign Full Name]
		,cp.StartDate as [Campaign Start Date]
		,cp.EndDate as [Campaign End Date]
		,cs.SegmentName as [Campaign Segment]
		,Case p.Active When 1 then ''YES'' else ''NO'' end as [Active]
		,Case cp.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active]
		,p.StartDate as [Project Start Date]
		,p.CompleteDate as [Project Due Date]
		,p.ProjectCloseDate as [Project Close Date]
		,p.CreatedDate as [Created Date]
		,Case p.BillingMethod 
			When 1 then ''Time and Materials''
			When 2 then ''Fixed Fee''
			When 3 then ''Retainer''
			end as [Billing Method]
		,cd.DivisionName as [Division Name]
		,cd.DivisionID as [Division ID]
		,pd.ProductName as [Product Name]
		,pd.ProductID as [Product ID]
	 	,kp1.UserName as [Key People 1]
		,kp2.UserName as [Key People 2]
		,kp3.UserName as [Key People 3]
		,kp4.UserName as [Key People 4]
		,kp5.UserName as [Key People 5]
		,kp6.UserName as [Key People 6]
		,u.FirstName + '' '' + u.LastName as [Primary Contact]
		,o.OfficeName as [Office]
		,o.OfficeColor as [Office Color]
		,v.ItemID AS [Item Service ID]
		,v.ItemName AS [Item Name]
	
		,CASE WHEN v.Entity = ''tService'' THEN ebi.Qty ELSE 0 END AS [Original Budget Hours]
		,CASE WHEN v.Entity = ''tService'' THEN ebi.Net ELSE 0 END AS [Original Budget Net Labor]
		,CASE WHEN v.Entity = ''tService'' THEN ebi.Gross ELSE 0 END AS [Original Budget Gross Labor]
		,CASE WHEN v.Entity = ''tItem'' THEN ebi.Net ELSE 0 END AS [Original Budget Net Expense]
		,CASE WHEN v.Entity = ''tItem'' THEN ebi.Gross ELSE 0 END AS [Original Budget Gross Expense]

		,CASE WHEN v.Entity = ''tService'' THEN ebi.COQty ELSE 0 END AS [Approved Change Order Hours]
		,CASE WHEN v.Entity = ''tService'' THEN ebi.CONet ELSE 0 END AS [Approved Change Order Net Labor]
		,CASE WHEN v.Entity = ''tService'' THEN ebi.COGross ELSE 0 END AS [Approved Change Order Gross Labor]
		,CASE WHEN v.Entity = ''tItem'' THEN ebi.CONet ELSE 0 END AS [Approved Change Order Net Expense]
		,CASE WHEN v.Entity = ''tItem'' THEN ebi.COGross ELSE 0 END AS [Approved Change Order Gross Expense]
		
		,CASE WHEN v.Entity = ''tService'' THEN ISNULL(ebi.Qty, 0) + ISNULL(ebi.COQty, 0) ELSE 0 END AS [Current Budget Hours]
		,CASE WHEN v.Entity = ''tService'' THEN ISNULL(ebi.Net, 0) + ISNULL(ebi.CONet, 0) ELSE 0 END AS [Current Budget Net Labor]
		,CASE WHEN v.Entity = ''tService'' THEN ISNULL(ebi.Gross, 0) + ISNULL(ebi.COGross, 0) ELSE 0 END AS [Current Budget Gross Labor]
		,CASE WHEN v.Entity = ''tItem'' THEN ISNULL(ebi.Net, 0) + ISNULL(ebi.CONet, 0) ELSE 0 END AS [Current Budget Net Expense]
		,CASE WHEN v.Entity = ''tItem'' THEN ISNULL(ebi.Gross, 0) + ISNULL(ebi.COGross, 0) ELSE 0 END AS [Current Budget Gross Expense]

		,CASE WHEN v.Entity = ''tItem'' THEN ebi.Qty ELSE 0 END AS [Original Item Budget Quantity]
		,CASE WHEN v.Entity = ''tItem'' THEN ebi.COQty ELSE 0 END AS [Approved Item Budget Quantity]
		,CASE WHEN v.Entity = ''tItem'' THEN ISNULL(ebi.Qty, 0) + ISNULL(ebi.COQty, 0) ELSE 0 END AS [Current Item Budget Quantity]

		,(Select ISNULL(Sum(ActualHours), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' AND tTime.ProjectKey = v.ProjectKey) as [Actual Hours]

		,(Select ISNULL(Sum(Quantity), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tMiscCost.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(ActualQty), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null AND tExpenseReceipt.ProjectKey = v.ProjectKey ) + 
		 (Select ISNULL(Sum(Quantity), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tVoucherDetail.ProjectKey = v.ProjectKey) 
			as [Item Quantity]

		,(Select ISNULL(Sum(Hours), 0)
			From tTaskUser tu (nolock)
			inner join tTask t (nolock) on tu.TaskKey = t.TaskKey
			inner join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where tu.ServiceKey = v.EntityKey
			AND v.Entity = ''tService'' 
			AND p.ProjectKey = v.ProjectKey) as [Allocated Hours]
		,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' AND tTime.ProjectKey = v.ProjectKey) as [Actual Labor]
		,(Select ISNULL(Sum(ROUND(ActualHours * CostRate, 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' AND tTime.ProjectKey = v.ProjectKey) as [Actual Labor Cost]
		,(Select ISNULL(Sum(TotalCost), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tMiscCost.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(ActualCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null AND tExpenseReceipt.ProjectKey = v.ProjectKey ) + 
		 (Select ISNULL(Sum(TotalCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tVoucherDetail.ProjectKey = v.ProjectKey) 
			as [Actual Net Expense]

		,(Select ISNULL(Sum(ROUND(ActualHours * CostRate, 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' AND tTime.ProjectKey = v.ProjectKey) +
		 (Select ISNULL(Sum(TotalCost), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tMiscCost.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(ActualCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null AND tExpenseReceipt.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(TotalCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tVoucherDetail.ProjectKey = v.ProjectKey) 
			as [Actual Total]
				
		,(Select ISNULL(Sum(BillableCost), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' AND tMiscCost.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(BillableCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null AND tExpenseReceipt.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(BillableCost), 0) from tPurchaseOrderDetail (nolock) Where tPurchaseOrderDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tPurchaseOrderDetail.InvoiceLineKey > 0 AND tPurchaseOrderDetail.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey =v.EntityKey AND v.Entity = ''tItem'' AND tVoucherDetail.ProjectKey = v.ProjectKey) 
			as [Actual Billable Expense]

		,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' and WriteOff = 1 AND tTime.ProjectKey = v.ProjectKey) +
		 (Select ISNULL(Sum(BillableCost), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and WriteOff = 1 AND tMiscCost.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(BillableCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null and WriteOff = 1 AND tExpenseReceipt.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and WriteOff = 1 AND tVoucherDetail.ProjectKey = v.ProjectKey) 
			as [Transaction Writeoff Amount]

		,(Select ISNULL(Sum(ROUND(isnull(BilledHours,ActualHours) * isnull(BilledRate,ActualRate), 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' and InvoiceLineKey = 0 AND tTime.ProjectKey = v.ProjectKey) +
		 (Select ISNULL(Sum(AmountBilled), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and InvoiceLineKey = 0 AND tMiscCost.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(AmountBilled), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null and InvoiceLineKey = 0 AND tExpenseReceipt.ProjectKey = v.ProjectKey) + 
		 (Select ISNULL(Sum(AmountBilled), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and InvoiceLineKey = 0 AND tVoucherDetail.ProjectKey = v.ProjectKey) +
		 (Select ISNULL(Sum(AmountBilled), 0) from tPurchaseOrderDetail (nolock) Where tPurchaseOrderDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and InvoiceLineKey = 0 AND tPurchaseOrderDetail.ProjectKey = v.ProjectKey) 
			as [Amount Marked as Billed]

		,(Select ISNULL(Sum(Amount), 0) from tInvoiceSummary (nolock) inner join tInvoice (nolock) on tInvoiceSummary.InvoiceKey = tInvoice.InvoiceKey Where tInvoice.AdvanceBill = 0 and tInvoiceSummary.Entity = v.Entity collate database_default AND tInvoiceSummary.EntityKey = v.EntityKey AND tInvoiceSummary.ProjectKey = v.ProjectKey) 
			as [Amount Billed]
		,(Select ISNULL(Sum(Amount), 0) from tInvoiceSummary (nolock) inner join tInvoice (nolock) on tInvoiceSummary.InvoiceKey = tInvoice.InvoiceKey Where tInvoice.AdvanceBill = 1 and tInvoiceSummary.Entity = v.Entity collate database_default AND tInvoiceSummary.EntityKey = v.EntityKey AND tInvoiceSummary.ProjectKey = v.ProjectKey) 
			as [Amount Advance Billed]
		,(Select Sum(ISNULL(TotalCost, 0) - ISNULL(AppliedCost, 0)) 
				from tPurchaseOrderDetail (nolock) 
				inner join tPurchaseOrder (nolock) on tPurchaseOrderDetail.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey
			 	Where tPurchaseOrderDetail.ItemKey = v.EntityKey 
				AND v.Entity = ''tItem''
				AND tPurchaseOrderDetail.ProjectKey = v.ProjectKey
				and tPurchaseOrderDetail.Closed = 0) as [Open Purchase Orders]
		,(SELECT ISNULL(Sum(TotalCost), 0) from tPurchaseOrderDetail (nolock) WHERE tPurchaseOrderDetail.ItemKey = v.EntityKey and v.Entity=''tItem''  and tPurchaseOrderDetail.ProjectKey = v.ProjectKey) as [Total Net PO]
		,(SELECT ISNULL(Sum(GrossAmount), 0) from tPurchaseOrderDetail (nolock) WHERE tPurchaseOrderDetail.ItemKey = v.EntityKey and v.Entity=''tItem''  and tPurchaseOrderDetail.ProjectKey = v.ProjectKey) as [Total Gross PO]
		,glc.GLCompanyID as [Company ID]
		,glc.GLCompanyName as [Company Name]
		,cla.ClassID as [Class ID]
		,cla.ClassName as [Class Name]
        ,case when p.LayoutKey is not null then wt.WorkTypeID 
		      else 
                  case when v.Entity = ''tItem'' then wti.WorkTypeID else wts.WorkTypeID end 
         end as [Billing Item ID] 
        ,case when p.LayoutKey is not null then isnull(wtcust.Subject, wt.WorkTypeName) 
		      else 
                  case when v.Entity = ''tItem'' then isnull(wtcusti.Subject, wti.WorkTypeName) else isnull(wtcusts.Subject, wts.WorkTypeName) end 
         end as [Billing Item Name] 
        ,l.Subject as [Opportunity Name]
        ,case v.Entity
           when ''tItem'' then dpt.DepartmentName
           else dpt2.DepartmentName
         end as [Department Name]
		,case v.Entity
           when ''tItem'' then dpt.DepartmentColor
           else dpt2.DepartmentColor
         end as [Department Color]

		 ,ISNULL((
				SELECT SUM(
						CASE 
							WHEN ABS(AppliedCost) >= ABS(TotalCost) THEN 0
							WHEN ABS(AppliedCost) > 0 AND ABS(AppliedCost) < ABS(TotalCost) AND TotalCost <> 0
								THEN NewBillableCost * (1 - cast(AppliedCost as Decimal(24,8) ) / cast(TotalCost as Decimal(24,8)))	
							ELSE NewBillableCost 
						END
					)
				FROM				
				(
				SELECT CASE po.BillAt 
						WHEN 0 THEN ISNULL(pod.BillableCost, 0)
						WHEN 1 THEN ISNULL(pod.PTotalCost,0) 
						WHEN 2 THEN ISNULL(pod.BillableCost,0) - ISNULL(pod.PTotalCost,0) 
						END AS NewBillableCost
						,isnull(pod.PTotalCost, 0) as TotalCost
						,isnull(pod.PAppliedCost, 0) as AppliedCost
				FROM	tPurchaseOrderDetail pod (NOLOCK)
					INNER JOIN tPurchaseOrder po (NOLOCK) ON pod.PurchaseOrderKey = po.PurchaseOrderKey
				WHERE	pod.Closed = 0					-- still open
				AND		pod.ProjectKey = v.ProjectKey
				AND     ISNULL(pod.ItemKey, 0) = v.EntityKey
				AND     v.Entity = ''tItem''
				AND     pod.DateBilled is null			-- Unbilled, like in the Project Budget Analysis, use DateBilled, not InvoiceLineKey 
				) AS OpenOrders			
						
			),0) As [Open Orders Gross Unbilled]
			,CASE v.Entity WHEN ''tItem'' THEN ''Expense'' ELSE ''Labor'' END AS [Transaction Type]
			,pcl.CompanyName as [Parent Client]
			,CASE WHEN v.Entity = ''tService'' THEN ISNULL(pir.HoursBilled,0) ELSE 0 END AS [Hours Billed]
			,cp.CustomFieldKey as [CustomFieldKey2]
			,pm.UserName as [Project Manager] 
			,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' AND tTime.ProjectKey = v.ProjectKey AND tTime.DateBilled IS NULL) as [Labor Unbilled]
			,(Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and tVoucherDetail.DateBilled Is NULL AND tVoucherDetail.ProjectKey = v.ProjectKey) as [Outside Costs Gross Unbilled]
			,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ServiceKey = v.EntityKey AND v.Entity = ''tService'' and tTime.DateBilled IS NULL AND tTime.ProjectKey = v.ProjectKey) +
			(Select ISNULL(Sum(BillableCost), 0) from tMiscCost (nolock) Where tMiscCost.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and tMiscCost.DateBilled IS NULL AND tMiscCost.ProjectKey = v.ProjectKey) + 
			(Select ISNULL(Sum(BillableCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ItemKey = v.EntityKey AND v.Entity = ''tItem'' And tExpenseReceipt.VoucherDetailKey is null and tExpenseReceipt.DateBilled  is null AND tExpenseReceipt.ProjectKey = v.ProjectKey) + 
			(Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ItemKey = v.EntityKey AND v.Entity = ''tItem'' and tVoucherDetail.DateBilled Is NULL AND tVoucherDetail.ProjectKey = v.ProjectKey) 
			as [Total Gross Unbilled]
,Case (Case v.Entity When ''tItem'' Then it.Active When ''tService'' Then s.Active End) When 1 then ''YES'' else ''NO'' end as [Active Item]
FROM	vProject_Items v
INNER JOIN tProject p (nolock) ON v.ProjectKey = p.ProjectKey
INNER JOIN tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
LEFT JOIN tProjectEstByItem ebi (nolock) ON v.ProjectKey = ebi.ProjectKey AND v.Entity = ebi.Entity collate database_default AND v.EntityKey = ebi.EntityKey
LEFT JOIN tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
LEFT JOIN tCompany pcl (nolock) on cl.ParentCompanyKey = pcl.CompanyKey
LEFT JOIN tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
LEFT JOIN tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
LEFT JOIN tOffice o (nolock) on p.OfficeKey = o.OfficeKey
LEFT JOIN tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
LEFT JOIN vUserName kp1 (nolock) on p.KeyPeople1 = kp1.UserKey
LEFT JOIN vUserName kp2 (nolock) on p.KeyPeople2 = kp2.UserKey
LEFT JOIN vUserName kp3 (nolock) on p.KeyPeople3 = kp3.UserKey
LEFT JOIN vUserName kp4 (nolock) on p.KeyPeople4 = kp4.UserKey
LEFT JOIN vUserName kp5 (nolock) on p.KeyPeople5 = kp5.UserKey
LEFT JOIN vUserName kp6 (nolock) on p.KeyPeople6 = kp6.UserKey
LEFT JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
LEFT JOIN tClientProduct pd (nolock) on p.ClientProductKey = pd.ClientProductKey
LEFT JOIN tClass cla (nolock) on p.ClassKey = cla.ClassKey
LEFT JOIN tGLCompany glc (nolock) on p.GLCompanyKey = glc.GLCompanyKey

left outer join tLayoutBilling lb (nolock) on p.LayoutKey = lb.LayoutKey and lb.Entity collate database_default = v.Entity and lb.EntityKey = v.EntityKey
left outer join tWorkType wt (nolock) on lb.ParentEntityKey = wt.WorkTypeKey and lb.ParentEntity = ''tWorkType''
left outer join tWorkTypeCustom wtcust (nolock) on lb.ParentEntityKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = p.ProjectKey

left outer join tItem it (nolock) on v.Entity = ''tItem'' and v.EntityKey = it.ItemKey
left outer join tDepartment dpt (nolock) on it.DepartmentKey = dpt.DepartmentKey
left outer join tWorkType wti (nolock) on it.WorkTypeKey = wti.WorkTypeKey 
left outer join tWorkTypeCustom wtcusti (nolock) on it.WorkTypeKey = wtcusti.WorkTypeKey and wtcusti.Entity = ''tProject'' and wtcusti.EntityKey = p.ProjectKey

left outer join tService s (nolock) on v.Entity = ''tService'' and v.EntityKey = s.ServiceKey
left outer join tDepartment dpt2 (nolock) on s.DepartmentKey = dpt2.DepartmentKey
left outer join tWorkType wts (nolock) on s.WorkTypeKey = wts.WorkTypeKey 
left outer join tWorkTypeCustom wtcusts (nolock) on s.WorkTypeKey = wtcusts.WorkTypeKey and wtcusts.Entity = ''tProject'' and wtcusts.EntityKey = p.ProjectKey

left outer join tUser u (nolock) on p.BillingContact = u.UserKey
left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey
left outer join tUser am (nolock) on p.AccountManager = am.UserKey
left outer join tLead l (nolock) on p.LeadKey = l.LeadKey

left outer join tProjectItemRollup pir (nolock) on v.ProjectKey = pir.ProjectKey AND v.Entity = pir.Entity collate database_default AND v.EntityKey = pir.EntityKey

left outer join vUserName pm (nolock) on p.ProjectManager = pm.UserKey 

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spConvertDBSeed]'
GO
IF OBJECT_ID(N'[dbo].[spConvertDBSeed]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[spConvertDBSeed]
(
	@LoadBeta int = 0
)
AS

/*
exec spConvertDBSeed 1
|| When      Who Rel      What
|| 8/21/09   CRG 10.5.0.8 Created to have all of the seed generating statements in one SP.
||                        Add comments here when you add a new seed value
|| 8/31/09   CRG 10.5.0.9 Added options for Today''s Meetings widget
|| 9/8/09    GWG 10.5.0.9 Added a right for editing notes for clients  (also changed some labels)
|| 10/06/09  GHL 10.5.1.2 (63999) Added prjAccessAny and prjChargeAny
|| 10/06/09  GHL 10.5.1.3 (47035) Added prjTimeCompletedTask and prjExpenseCompletedTask
|| 11/4/09   CRG 10.5.1.3 Fixed a spelling error in RightKey: 931506
|| 12/03/09  GHL 10.5.1.4 (64187) Added proj_projectscoreboard for project summary scoreboard
|| 02/08/10  GWG 10.5.1.8 Added the opportunity list as a legacy report
|| 02/10/10  GWG 10.5.1.8 Added new widget for recurring transactions (not active yet, commented out)
|| 03/18/10  MAS 10.5.2.0 Added Voucher Lab
|| 3/31/10   GWG 10.5.2.0 Fixed some wording and display orders for certain security groups
|| 04/08/10  RLB 10.5.2.1 Added Billing Add Transaction to Worksheet.
|| 04/24/10  GWG 10.5.2.1 Added a right for enabling labs and modified the labs
|| 04/27/10  GWG 10.5.2.1 Added right for CBRE report
|| 05/6/10   RLB 10.5.2.2 (80005)Changed Display Order on admin_employeehours
|| 06/17/10  GWG 10.5.3.1 Fixed a spelling error, moved schedule edit to beta and fixed a setting chargeability percentage
|| 06/17/10  GWG 10.5.3.2 Removed the client notes widget.
|| 7/8/10    GWG 10.5.3.2 Added GL Posting as a Lab
|| 08/26/10  RLB 10.5.3.4 (80063,69422)Added 2 new rights View invoice for child company and view invoices for assigned projects
|| 08/27/10  RLB 10.5.3.4 added right for new Overhead Allocation Details Report
|| 09/30/10  MFT 10.5.3.5 added Lab for Transactions and AcctRec
|| 10/03/10  MFT 10.5.3.6 added Lab for IO & PO
|| 10/10/10  GWG 10.5.3.6 Changed a description for adminviewcostrate and added some release comments
|| 10/27/10  RLB 10.5.3.7 Added a lab for WIP Aging
|| 10/28/10  GWG 10.5.3.7 Took items out of labs and rearanged stuff
|| 11/16/10  RLB 10.5.3.8 added new right group legacy
|| 12/3/10   CRG 10.5.3.9 Added labs for Diary and ToDos (commented out for now)
|| 12/10/10  GWG 10.5.3.9 Changed the default url for the rss widget
|| 01/14/11  MAS 10.5.?.? Added MobileMenu seed values
|| 02/01/11  GWG 10.5.4.0 Changed lab settings and removed a duplicate adminsetup_media in system setup
|| 03/20/11  GWG 10.5.4.2 Added a new notification (task reminder)
|| 04/18/11  GWG 10.5.4.3 Commented out project requests from the mobile menu for now
|| 06/02/11  RLB 10.5.4.5 (113014) added ProjectTypeKey for My Task widget
|| 06/28/11  RLB 10.5.4.5 (115163) added right to convert contacts and employees
|| 06/28/11  GHL 10.5.4.5 (60333) Added media billing report
|| 08/02/11  GHL 10.5.4.6 Added LabID for credit cards
|| 09/12/11  GHL 10.5.4.8 Added Rights for Credit Card charges
|| 09/22/11  GHL 10.5.4.8 (109668) Added right pyramidLaborRpt for a customization for Pyramid
|| 09/27/11  GWG 10.5.4.8 Made the metrics monitor resizable
|| 09/28/11  GHL 10.5.4.8 Added client_editprojectspecs for the Integer Group of Colorado for clients to edit project specs
||                        Added billingtimesheetunapprove for the Integer Group of Colorado to unapprove timesheets
|| 09/28/11  CRG 10.5.4.8 Removed WebDAV from the Labs. It will now just be an internal flag in tPreference that we turn on once they''re converted
|| 09/28/11  GHL 10.5.4.8 Changed wording of the right purch_usecreditcard to ''use credit card charge entry screens''
||                        to differentiate with right billingcreditcard
|| 10/25/11 RLB 10.5.4.9  (124610) Added right to edit other peoples Diary Posts
|| 11/4/11  GWG 10.5.4.9  Reordered the mobile menu
|| 11/8/11  RLB 10.5.5.0  Adding Retainer Lab
|| 12/7/11  RLB 10.5.5.1  (128080) Added openToDoOnly option on the My Task widget
|| 01/30/12 MAS 10.5.5.3  Added Financial Institution data for Credit Card downloads
|| 04/09/12 GHL 10.5.5.5  Added right to edit electronic signature on check formats
|| 04/09/12 GHL 10.5.5.5  (139284) Added rights billingtransfertran and billingwriteofftran 
|| 04/23/12 MAS 10.5.5.5  Added purch_usecreditcardconnect right
|| 05/04/12 MAS 10.5.5.5  Changed the URL connection string for AMEX
|| 6/1/12   CRG 10.5.5.6  Added publishCalendar lab
|| 6/6/12   RLB 10.5.5.6  (138325) Added Client right to see Project Misc Cost
|| 6/13/12  GHL 10.5.5.7  Added right adminsetup_glcompanyaccess to allow editing of gl compapanies access on company edit screen
|| 6/28/12  RLB 10.5.5.7  (147280) Added option on the active project widget
|| 7/16/12  CRG 10.5.5.8  Added lab for revenue forecast
|| 07/23/12 RLB 10.5.5.8  (149536) Added New right to view project revenue source
|| 07/25/12 MFT 10.5.5.8  Added new right for printing checks (purch_printchecks)
|| 07/27/12 RLB 10.5.5.8  Added new option in the Chargeablility Summary widget
|| 07/31/12 RLB 10.5.5.8  Added GL Company Option to the Cash on Hand widget
|| 07/31/12 RLB 10.5.5.8  Added GL Company Option to the Write Off Summary widget
|| 07/31/12 MFT 10.5.5.8  Added Settings value to the tWidget INSERT for Metrics Monitor
|| 07/31/12 RLB 10.5.5.8  Added GL Company Option to the Opp Pipeline widget
|| 08/07/12 RLB 10.5.5.8  Added GL Company Option to the Chargeablility percentage and HMI changes
|| 08/07/12 RLB 10.5.5.8  Added GL Company Option to the Rev Per Employee
|| 08/07/12 RLB 10.5.5.8  Added GL Company Option to the Opp Forecast widget and HMI changes
|| 08/07/12 RLB 10.5.5.8  Added GL Company Option to the Opp Outcome and HMI changes
|| 08/07/12 MFT 10.5.5.8  Added Settings value to the tWidget INSERT for Billable Efficiency
|| 08/08/12 RLB 10.5.5.8  Added GL Company Option to the Opp closed by person and HMI changes
|| 08/08/12 MFT 10.5.5.8  Added Settings value to the tWidget INSERT for Vulnerability to Loss
|| 08/08/12 RLB 10.5.5.8  Added GL Company Option to the Active Project widget
|| 08/10/12 RLB 10.5.5.8  Added GL Company Option to the Income By Service and HMI changes
|| 08/10/12 RLB 10.5.5.8  Added GL Company Option to the Repeat clients and HMI changes
|| 08/10/12 RLB 10.5.5.8  Added GL Company Option to the Revenue Trend and HMI changes
|| 08/11/12 QMD 10.5.5.9  Added lab for google contacts and google calendar v3
|| 08/15/12 KMC 10.5.5.9  (151654) Updated the insert into tWidget for Revenure Trend Widget (ID=36) and default
||                        the year node to blank in the XML string.  Also updated MetricsRevenueTrend.mxml to set the
||                        year to the current year if it is blank
|| 08/20/12 RLB 10.5.5.9  (152004) Added rights to merge Leads, Contacts and Companies
|| 08/20/12 MFT 10.5.5.9  Added GL Company Option to the tWidget for Markup By Item and Company Calendar
|| 09/11/12 CRG 10.5.6.0  Added lab for P&L Custom Layouts
|| 09/18/12 MFT 10.5.6.0  Added right hmiProjectResourceUtilization for HMI custom report
|| 09/24/12 RLB 10.5.6.0  Added right to Unpost for HMI
|| 10/02/12 KMC 10.5.6.0  (134065) Added Account Balances widget
|| 10/05/12 WDF 10.5.6.0  (150044) Added ''Project Billable Hours Summary'' report
|| 10/25/12 MFT 10.5.6.1  (156391) Added right for Project Reconciliation Summary
|| 11/20/12 WDF 10.5.6.2  Added Settings value ''ShowInActive''to the tWidget INSERT for Opportunity Pipeline, Opportunity Forecast, Revenue Trend, Activity Counts
|| 11/26/12 RLB 10.5.6.2  added description on Deliverable Lab stating that Web Dav Is required to use
|| 11/29/12 QMD 10.5.6.2  Added lab for new emma and google caldav
|| 12/7/12  GWG 10.5.6.3  Added All projects to the over budget calculation
|| 02/14/13 KMC 10.5.6.5  Removed googleCalendarV3 from Labs
|| 03/01/13 RLB 10.5.6.5  Add lab for project time line
|| 03/15/13 GWG 10.5.6.6  Pulled a number of things out of labs
|| 03/20/13 MAS 10.5.6.6  Added activity widget
|| 03/27/13 RLB 10.5.6.6  Added Timeline Widget and lab
|| 04/23/13 RLB 10.5.6.7  Added right to see non project related events on the dialy feed widget
|| 04/29/13 RLB 10.5.6.7  (175860) Added right to view Project Setup Accounting Tab
|| 06/06/13 MFT 10.5.6.9  Added lab for PrintMedia
|| 06/11/13 CRG 10.5.6.9  Added new Media rights
|| 07/03/13 QMD 10.5.6.9  Added new Mobile App (Expense Reports)
|| 07/09/13 MFT 10.5.6.9  Added new tFinancialInstitution row (13)
|| 07/09/13 KMC 10.5.7.0  (184557) Added new right purch_approvecreditcardcharge for approving credit card charges
|| 07/23/13 MFT 10.5.6.9  Added new tFinancialInstitution row (14)
|| 08/23/13 GHL 10.5.7.1  Added 2 multicurrency gains and losses reports
|| 08/26/13 GHL 10.5.7.1  Added right to view forecasts from other AEs
|| 08/27/13 GHL 10.5.7.1  Added right to view forecasts
|| 09/03/13 GHL 10.5.7.2  Added USD currency
|| 09/03/13 RLB 10.5.7.2  (187734) Added right to view customfields on project dashboard
|| 09/06/13 GHL 10.5.7.2  Added multicurrency lab
|| 09/17/13 MFT 10.5.7.2  Added right 61700/purch_approvemyprojectvoucher to approve vendor invoices on projects assigned to 
|| 09/17/13 CRG 10.5.7.2  Added LockQty to Pages value in tMediaUnitType
|| 10/21/13 GHL 10.5.7.3  Added right to maintain currency rates
|| 10/24/13 WDF 10.5.7.3  (171844) Added new right prjViewTran for viewing the Project Transaction screens 
|| 10/31/13 MFT 10.5.7.3  Added new right prjnotesedit and changed prjnotes to Add only, reorganized project, admin rights to be together
|| 11/07/13 MFT 10.5.7.4  Added new right media_printbuysched
|| 11/11/13 WDF 10.5.7.4  (195542) Added new rights specificially for ToDos
|| 02/06/14 MFT 10.5.7.7  Changed media_printbuysched to media_printbuycal;Added media_printbuyblock & media_printbuygrid
|| 02/18/14 CRG 10.5.7.7  Fixed the POKind on the tMediaUnitType seeding
|| 03/06/14 WDF 10.5.7.8  (124798) Added new right ''acct_client_gl_pl_ytd'' to split out Client P&L from Corp P&L
|| 03/25/14 GWG 10.5.7.8  Removed bank of america because of errors
|| 04/15/14 GWG 10.5.7.9  Added correct bofa url information
|| 04/17/14 KMC 10.5.7.9  (213294) Removed the lab/beta for deliverables
|| 04/29/14 MAS 10.5.7.9  Added adminUserSettings right 
|| 05/01/14 PLC 10.5.7.9  Added defaults Print USer dates 1 and 2 
|| 05/06/14 GHL 10.5.8.0  Changed INSERT 000 to INSERT (000) for media unit 
|| 05/14/14 GHL 10.5.8.0  Enabled the currency rate admin screen
|| 05/30/14 GHL 10.5.8.0  (218161) Removed lab NewLayoutBilling, we only use NewLayoutDesign now
|| 06/05/14 QMD 10.5.8.0  (218393) Added new right prjAssignTasksToMe
|| 06/09/14 RLB 10.5.8.1  (216811) Removed Bank of America from tFinancialInstitution
|| 06/26/14 KMC 10.5.8.1  (220472) Added right for viewing the Billing tab in project central, right ID 90926/prjDashBilling.
|| 07/02/14 QMD 10.5.8.1  (218393) Removed right prjAssignTasksToMe
|| 07/02/14 QMD 10.5.8.1  (220670) Added new right prjQuickAddTask and prjQuickAddActivity
|| 07/15/14 GWG 10.5.8.2  Changed the sort order of two rights for multi currency
|| 08/12/14 CRG 10.5.8.3  Added googleCalDAV Lab
|| 09/03/14 WDF 10.5.8.4  (225597) Added Custom Report (99000001)
|| 09/03/14 CRG 10.5.8.4  Removed googleCalDAV Lab
|| 09/23/14 MAS 10.5.8.4  Abelson & Taylor - added adminChangeBillingTitle right
|| 10/03/14 CRG 10.5.8.4  Added lab vPayment
|| 10/21/14 WDF 10.5.8.5  (231857) Added ''hideToDoNotes'' and ''hideDiaryNotes'' to tWidget.Settings where WidgetKey = 24 
|| 11/19/14 GAR 10.5.8.6  (236371) Added new security right.  Changed ''Edit Global Options'' to ''Allow Access to Global Options: System Options ''
||						  and added ''Allow Access to Global Options: Lists''.
|| 12/09/14 GHL 10.5.8.7  (229954) Added concentricChargeabilityRpt right for enhancement for Concentric 
|| 12/10/14 RLB 10.5.8.7  (239148) Removed Labs PO, Spec Sheet and Mass Billing
|| 01/09/15 GHL 10.5.8.8  (241893) Removed forecast lab, part of the general release now
|| 01/20/15 GHL 10.5.8.8  Added security right prjrecalclaborrates for Abelson Taylor
|| 01/26/15 GAR 10.5.8.8  (242601) Added jplChargeabilitySummary right for enhancement for JPL 
|| 01/26/15 GHL 10.5.8.8  Added prjChangeAnyoneCharges right to control the Anyone Allowed to Charge Time on projects for Abelson Taylor
|| 01/28/15 GHL 10.5.8.8  Added abelsonProjectResourceUtilization right to allow Abelson Taylor to use the HMI Project Resource Utilization rpt
|| 02/03/15 GAR 10.5.8.9  (244725) Changed Media Discrepancy Report to Media Details Report
|| 02/05/15 GWG 10.5.8.9  Move multi currency to labs
|| 02/09/15 GHL 10.5.8.9  Added right billingunwriteofftran to undo writeoffs for abelson taylor
|| 02/19/15 GHL 10.5.8.9  Added right prjViewTranAdjusted to view adjusted transactions for abelson Taylor
|| 03/05/15 GWG 10.5.9.0  Added Platinum review beta entry
|| 03/12/15 GHL 10.5.9.1  (241695) Added purch_viewbankinfo + purch_editbankinfo to control vendor''s bank info for Spark44 enh
|| 05/01/15 GWG 10.5.9.2  Removed a label from one of the rights.
|| 05/22/15 KMC 10.5.9.2  (257529) Added rights for view and editing of EIN Number
|| 09/17/15 GWG 10.5.9.6  Updated the WJ RSS Feed
|| 10/15/15 GHL 10.5.9.7  (271391) added right adminsetup_billing for a customization
|| 10/19/15 MCM 10.5.9.7  (273918) Updated description of two rights: "Allow Access to System Options" and "Allow Access to Lists"	
|| 11/14/15 GWG 10.5.9.8  Added Plat for Resource Managers lab
|| 12/02/15 MFT 10.5.9.8  Added platRedirectMobile lab
|| 12/03/15 MCM 10.5.9.8  (274460) Updated description for right 940700 (accteditanytime) by adding submission so it''s ''Edit transactions after submission/approval''
|| 02/09/16 GWG 10.6.0.1  Changed the label on edit billing info to edit accounting info for Mike.
|| 03/02/16 GWG 10.6.0.1  Removed platPO, folded under platPM
|| 03/30/16 GAR 10.6.0.2  Added status seeds for tTaskUserStatus table
|| 05/16/16 CRG 10.6.0.4  (295466) Added prjEditProjectNumber
|| 05/19/16 GAR 10.6.0.4  Removed unneeded statuses for tTaskUserStatus
|| 05/19/16 CRG 10.6.0.4  Removed duplicate platProjectRequest lab
|| 05/20/16 MAS 10.6.0.4  Added farmPostageAvailableReport
|| 05/26/16 CRG 10.6.0.4  (301321) Split Client Actual Hours and Dollars into two different rights
|| 06/06/16 RLB 10.6.0.5  (299542) Adding estimate approval notification
|| 06/27/16 RLB 10.6.0.5  (304632) Adding a right to see Plat project pm dashboard
|| 06/30/16 CRG 10.6.0.5  Added Platinum Resource Loading lab
|| 08/01/16 CRG 10.6.0.6  Removed Platinum Resource Loading lab
|| 08/25/16 GWG 10.0.6.7  Added a platinum specific section and rights for Today pages
|| 10/8/16  GWG 10.6.0.9  Added right for editing templates.
|| 11/16/16 MCM 10.6.1.0  Updated description for prjnotes and approveadd to say Addess instead of add 
|| 02/09/17 GWG 10.6.1.3  Remove lasalle bank
|| 05/16/17 WDF 10.6.1.6  (342677) Add ''View'' Right (20200) for Deliverables to the tRight table
|| 05/23/17 GHL 10.6.1.6  (345091) Added concentric client PL report
|| 05/30/17 GHL 10.6.1.6  (345091) Added concentric dept PL report
|| 06/09/17 RLB 10.6.1.7  Added right to use scheduled reports
|| 06/30/17 GWG 10.6.1.7  Add in the right for accounting today pages.
|| 07/20/17 GAR 10.6.1.8  (341612) Split the gl_post right out into 6 separate rights (gl_postvoucher, gl_postpayment, gl_postclientinvoice, gl_postreceipt, gl_postjournalentry, gl_postcreditcard)
|| 08/17/17 RLB 10.6.1.9  (356364) add barb group custom report right
|| 09/08/17 QMD 10.6.1.9  Add platImport screen lab
|| 09/15/17 GHL 10.6.2.0  (MN''s Todo) Rename ''Billing Worksheet'' to ''Billing Worksheet Report'' to differentiate from Electronic Billing Worksheets
|| 09/18/17 GHL 10.6.2.0  (MN''s Todo) Added ''Client'' to description for client right 501100 to differentiate from regular right
|| 10/05/17 RLB 10.6.2.1  Added right to only enter time against tasks where the predecessor is completed or has no pred/succ
|| 11/01/17 GAR 10.6.2.1  Added 2 rights for Platinum company notes
|| 11/8/17  GWG 10.6.2.2  Added lab for new creative today screen
|| 01/03/18 CRG 18.1.0    Added newSchedule lab
|| 02/20/18 WDF 18.3.0    (373099 ) Added ''NEWSPECSHEET'' to tNotification
|| 03/20/18 RLS 18.4.0    (392204) Changed DESCRIPTION verbage in tNotification for NotificationID TASKUPDATE
|| 04/04/18 GWG 18.4.0    Change Art Review to deliverable
|| 03/20/18 MAS 18.5.0    Added PlatMedia Lab
|| 04/10/18 RLS 18.5.0    (TODO DEV1784 - Round 2 Enhancement ) Added ''NEWOPPORTUNITY'' to tNotification
|| 04/12/18 MCM 18.5.0    (TODO 4430) Added right to import approved expense report
|| 04/18/18 GAR 18.5.0    Removed platReviews from tLab
|| 04/26/18 MAS 18.5.0    Removed PNC Bank from the Credit Card Connector list
|| 05/09/18 CRG 18.6.0    Added cross-project predecessor lab
|| 05/22/18  RLS 18.6.0.0 (402000) Change all labels that were ''timesheet to ''time sheet''. System-wide change
|| 05/25/18 MCM 18.6.0    (403146) Updated the description and hint for billing_expenserptapproveimported
|| 05/25/18  RLS 16.6.0   (403017) Change tTask Lookup descriptions to ''On or Before the Next X Days''
|| 06/07/18 CRG 18.7.0    Added officeBlockoutCalendars lab
|| 07/23/18 WDF 18.8.0    (411279) Modified Hint of right prjChangeAnyoneCharges to indicaate being visible/not visible rather than enabled/not enabled.
|| 10/12/18 AMP 18.9.2    (422151) Added a new Purchasing Right "View Vendor Invoices on Approval screen"
|| 10/17/18 GHL 18.9.2    (424497) Added rights to edit media orders after approval
|| 10/19/18 AMP 18.9.2    (424927) Added a new Purchasing Right "View Purchase Orders on Approvals"
|| 10/25/18 GHL 18.9.2    (423844) Added right questvouchersrpt to view custom vendor invoice report for Quest 
|| 11/7/18  GWG 18.9.3.0  (429573) Added specific rights to view each of the new dashboards and removed the dashboard lab/beta
|| 12/2/18  GWG 18.9.3.0  (429573) Remove rights for view todo dashboard.  based on view todo right.  Rename PM Dashboard right
|| 12/12/18 GWG 19.1.0    Fix the labels on the dashboard rights
|| 01/14/19 AMP 19.0.2.0  (438405) Added new Media rights "View Insertion Orders on Approvals" and "View Broadcast Orders on Approvals"
|| 01/24/19 RLS 19.0.2.0  (441481) Added adminsetup_changerequest
|| 02/08/19 GAR 19.0.3.0  (416773) Added tLab entry for globalFileSearch.
|| 02/13/19 RLB 19.0.3.0  Added client and user rights to tChange
|| 02/20/19 GWG 19.0.3.0  Move media out of beta
|| 03/13/19 GWG 19.0.4.0  Moving labs over to convertappseed
|| 04/30/19 CRG 19.0.5.0  Removed string numbers in hints
|| 05/20/19 GHL 19.0.6.0  (448693) Changed the description of view only AP transactions (removed on Approvals)
|| 05/24/19 AMP 19.0.6.0  (461647) Update for new graphs menus to say Graphs (instead of new dashboard)
|| 06/21/19 AMP 19.0.7.0  (461523) Changed wording on purch_usecreditcard right, and added new right (purch_viewcreditcard) for View Only on the credit card charge entry screens
|| 07/08/19 RLB 19.0.8.0  (441482) made some changes to CR''s rights wording
|| 07/16/19 GHL 19.0.8.0  (466585) Added billingenterlabornet for a customization for wongdoody to enter a net rate for OT in project billing
|| 09/18/19 GHL 19.1.0.0  (479811) Changed the wording of purch_editpo to Add and Edit Purchase Orders
|| 10/11/19 RLS 19.1.1.0  (462005) Added NEWCAMPAIGN to tNotifications
|| 11/21/19 GAR 19.1.2.0  (473697) Changed ''Projects where I am the account manager'' to ''Projects where I am the account manager or project manager'' on several notifications 
|| 12/16/19 RLB 20.0.1.0  (487336) added client right to access any project
|| 01/14/20 RLS 20.0.2.0  (494271) Moved the (Legacy) client rights into a new RightGroup named ClientLegacy
|| 01/16/20 CRG 20.0.2.0  (495703) Removed client_calendar from Legacy section
|| 01/30/20 GHL 20.0.2.0  (499146) Reordered the ''Contact Management'' or cm rights 
|| 02/28/20 GAR 20.0.4.0  (503817) Added a right for a client to delete their own project request
|| 03/06/20 AMP 20.0.4.0  (505412) Corrected BO/IO security rights descriptions
|| 03/06/20 AMP 20.0.4.0  (500075) Added a right for ''Edit Purchase Orders after Approval''
|| 04/03/20 AMP 20.0.5.0  (474467) Added a right under Billing to ''View Client Invoices''
|| 05/05/20 RLB 20.0.6.0  (494017) Added new overworked assignment
|| 07/27/20 RLB 20.0.8.0  (523358) removed beta in the descriptions on change requests
|| 07/31/20 GAR 20.0.9.0  (517761) Addded ''Projects where I am the account manager'' and ''Projects where I am the project manager'' to new campaigns and new projects notifications
|| 10/21/20 GAR 20.1.1.0  (534408) Removed PProject Change Requests lab
|| 10/22/20 RLS 20.1.1.1  (530775) Changed the verbiage in tNotification for NotificationID TASKUPDATE
|| 02/16/21 GAR 21.03.14  (546453) Changed the Chargeability Summary reports to Billable Summary.  
|| 04/07/21 RLS 21.0.5.0  (554335) Removed prjDashTeam. It wasn''t being used anywhere. Showing Teams is controlled by a system setting
|| 06/10/21 GHL 21.0.7.0  (561050) Changed the description for cm_editacctinfo to be more explicit
|| 06/22/21 AMP 21.07.18.0000 (561324) Modified the Description for ''Overdue Time Sheets'' Notification
|| 08/10/21 AMP 21.09.19.0000 (567102) Modified the description for ''Allow Access to Lists''
|| 08/18/21 RLB 21.09.19  (563856) Added ItemsToApprove To Notifications table
|| 08/23/21 AMP DEV2554   (498) - Added ''Changes in Project Settings'' to Email Notifications''
|| 09/02/21 GAR 21.10.17  (569710) Removed rights for prjDashSnapshot, dash_showsnapshot and dash_showprofit - using system settings for this
|| 09/27/21 AMP 22.01.16.0000 (569231) Added a new right called ''employee_project_time'' to allow access to the projects and time tab on the employee record
|| 09/30/21 GHL 21.11.14  (570696) Added deleteOpptyProject to delete oppty projects
|| 03/24/22 RLB 22.04.17  (592727) removed extra assignments on a notfication
|| 04/27/22 CRG 22.05.15  (574458) Added new right: adminsetup_security
|| 06/22/22 WDF 22.07.17  (602605) Moved prjEditProjectNumber from ''Platinum Specific Rights'' to ''Project Administration''
|| 06/24/22 WDF 22.07.17  (602792) Added group ''WMJ Desktop'' and moved various rights to it, moved other rights to different groups and 
||                                 changed the Description of some of the moved rights.
|| 06/30/22 RLS 22.07.24  (595958) Added new right: client_editconversations
|| 07/20/22 MCM 22.08.14  (593839) Added seed for new table tBankAccountType
|| 05/15/22 RLB 22.08.14 (598281) Added Employee notification for ToDoReminder
|| 09/13/22 RLB 22.10.16 (611729) added Employee notification for Campaign Over Budget
|| 12/05/22 RLS 23.01.15 (619626) added new right billingeditusersiapprove
|| 11/28/22 GAR 22.12.18 (615611) Added new right for RM Graphs menu dot
|| 02/07/23 RLB 23.03.19 (629182) Added Billing status notofication
|| 03/07/23 RLB 23.04.16 (630358) Added new right to edit Employee and Contact CF''s
|| 04/07/22 RLB 23.05.14 (629350) change right client_editconversations description to include change request conversations
|| 06/12/23 CRG 23.07.18 Added tTMLogService seeding
|| 06/21/23 MAS 23.07.16 Removed old media references, tMediaUnitType
|| 07/18/23 KMC 23.08.20 Added tHelpGuideLik
|| 11/09/23 CRG 23.12.17 (655963) Added new right: adminsetup_meetingrequest
|| 11/16/23 CRG 23.12.17 (644751) Changed the description of right: adminsetup_meetingrequest
|| 12/27/23 RLB 24.01.21 (658051) adding new right to add planning projects
|| 02/15/24 RLB 24.03.17 (663505) adding new right View Project Setup Billing Options
|| 04/03/24 RLB 24.05.19 (654860) created new right for new standard report Project Recap   tasks_Recap_Analysis
|| 05/30/24 GAR 24.07.14 (672150) Slightly change the names of the security rights so it''s easier to search for rights related to conversations (table in issue)
|| 06/05/24 MFT 24.07.00 (674224) Remove the " and Remove Items from Worksheets" verbiage from the billingremovefromsheet right, key 30902, and change ID to billingdeleteworksheet
|| 06/17/24 GAR 24.07.14 (672280) Added a new right - Transfer transactions to non-billable projects, changed other right to billable projects
|| 06/17/24 GAR 24.07.14 (670977) Added a new right - Approvers can View timesheets for people they approve
|| 07/01/24 MCM 24.08.x  (671239) Added new right - gl_approvejournalentry, to approve Journal Entries.  Only applies if have JEApprovalEnabled preference turned on
|| 07/02/24 GAR 24.08.18 (674308) Added a new right - Allows user to edit other people''s deliverable comments
|| 07/03/24 GAR 24.08.18 (674812) Added 2 new rights - Allows user to view custom fields on contacts and companies
|| 07/26/24 RLB 24.08.18 (653740) Added new right prjviewestimate to just view estimates
|| 08/27/24 CRG 24.09.15 (681708) Seeding tRTNActive table
|| 08/29/24 GAR 24.09.15 (681361) Added BillingManager as a contact option in UPDATESTATUS and UPDATEBILLINGSTATUS in user notifications 
|| 10/07/24 MCM 24.11.x  (676228) added a new right purch_approvevoucher to approve vendor invoices (aka voucher)
|| 01/21/25 GAR 25.02.x  (688217) Deleting the tWidget insert statements because the table definition changed.  We will add these back in once we have the new table set and widgets defined.
|| 02/17/25 AMP 25.03.16 (686463) Added new right - gl_view_journalentry, to view Journal Entries.
|| 05/28/25 RLB 25.06.15 (702747) Added new right - prjdeletespecs, to delete spec sheets.
|| 06/05/25 AMP 25.07.20 (697263) Added new rights - View Publications, View Stations
|| 07/10/25 GAR 25.08.17 (688217) Adding new seed scripts for the new project dashboard
|| 07/23/25 AMP 25.08.17 (697263) Added description to ''Edit Media Setup options'' to include Stations/Publications
|| 09/10/25 GAR 25.10.19 (710783) Adding new seed scripts for the new home dashboard
|| 10/1/25  GWG 25.10.19	      Removing the on off identity lines for widget defs (not needed).  also assigning a dash id
|| 09/10/25 GAR 25.11.17 (710783) Adding new seed scripts for the new home dashboard - Project dashboard graphs
|| 01/12/25 RLB 26.02.15 (718213) Added new right to add or edit media plans
|| 02/10/26 CRG 26.04.19 (721964) Added new right adminsetup_automation
|| 04/09/26 GAR 26.05.17 (722428) Added new right purch_deletepo
|| 06/03/26 MCM 26.07.x  (730018) Added new right acct_view_scheduledreports
|| 06/10/26 AMP 26.07.19 (730512) Added new right - viewAPITokens
|| 07/15/26 GWG 26.08.17 Added a new right - ''changeUserColors'', ''Change the visual appearance at the user level''
|| 07/16/26 RLB 26.08.17 (731962) Removed right Edit Digital Assets Options only used in Flex
*/

/*
Script for generating level specific rights
Select ''INSERT tRightLevel(RightKey, CompanyKey, Level) Values ('' + CAST(RightKey as Varchar) + '',100,1) --'' + RightID from tRight 
*/

DELETE tRight



if @LoadBeta = 1
BEGIN

-- Media Rights
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500070, ''media_viewWorksheet'', ''View the Media Worksheet'', ''media'', ''admin'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500080, ''media_editWorksheet'', ''Edit the Media Worksheet'', ''media'', ''admin'', 8, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303305, ''media_printbuycal'', ''Media Print Buy Calendar Report'', ''reports'', ''admin'', 6040, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303306, ''media_printbuyblock'', ''Media Print Buy Block Report'', ''reports'', ''admin'', 6041, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303307, ''media_printbuygrid'', ''Media Print Buy Grid Report'', ''reports'', ''admin'', 6042, 1, '''')

END

-- change requests
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10201, ''adminsetup_changerequest'', ''---- Edit Project Change Requests'', ''admin'', ''admin'', 17, 1, ''Allows access to Admin > System Setup > Tracking > Define Project Change Requests.<br>Add/edit/delete project change request forms, set up of custom fields, create an approval process and give different security groups access to those change requests.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (970000, ''cr_viewchanges'', ''View Project Change Request Forms'', ''changes'', ''admin'', 1, 1, ''User can view change requests and linked spec sheets. This also allows the user to Cancel  Change Request, which will cancel an approval and change the change request status to Not Sent For Approval. This setting also allows the user to Add Attachments.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (970010, ''cr_addchanges'', ''Add New Project Change Request Forms to the system'', ''changes'', ''admin'', 2, 1, ''Allows user to create new change requests, only if they belong in the Selected Security Groups defined in the change request form at the system setup level.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (970020, ''cr_editchanges'', ''Edit Project Change Request Forms'', ''changes'', ''admin'', 3, 1, ''Allows user to make and Save changes to project change requests and linked spec sheets that have not been submitted.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (970030, ''cr_deletechanges'', ''Delete Project Change Request Forms'', ''changes'', ''admin'', 4, 1, ''[Delete] button is now present.'')

-- WMJ Desktop
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (111, ''menu_todayAdmin'', ''View Today Managers'', ''desktop'', ''admin'', 10, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (109, ''menu_todayPurchasing'', ''View Today Purchasing'', ''desktop'', ''admin'', 20, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (110, ''menu_todayAccounting'', ''View Today Accounting'', ''desktop'', ''admin'', 30, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (114, ''menu_todayBill'', ''View Today Billing'', ''desktop'', ''admin'', 40, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (115, ''menu_dashBill'', ''View the Billing Dashboard'', ''desktop'', ''admin'', 50, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100, ''menu_todayCreative'', ''View Today Creatives'', ''desktop'', ''admin'', 60, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (102, ''menu_todaySales'', ''View Today Sales'', ''desktop'', ''admin'', 70, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (103, ''menu_todayPM'', ''View Today PM'', ''desktop'', ''admin'', 80, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (104, ''prjViewPMDashboard'', ''View the PM Dashboard'', ''desktop'', ''admin'', 90, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (117, ''notes_view'', ''View Notes'', ''desktop'', ''admin'', 100, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (118, ''notes_edit'', ''Edit Company Notes'', ''desktop'', ''admin'', 110, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (119, ''menu_todayMedia'', ''View Today Media'', ''desktop'', ''admin'', 120, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (130, ''viewDashCreative'', ''View the Creative Graphs'', ''desktop'', ''admin'', 130, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (131, ''viewDashSales'', ''View the Sales Graphs'', ''desktop'', ''admin'', 140, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (132, ''viewDashPM'', ''View the PM Graphs'', ''desktop'', ''admin'', 150, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (133, ''viewDashPurchasing'', ''View the Purchasing Graphs'', ''desktop'', ''admin'', 160, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (134, ''viewDashBilling'', ''View the Billing Graphs'', ''desktop'', ''admin'', 170, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (135, ''viewDashAccounting'', ''View the Accounting Graphs'', ''desktop'', ''admin'', 180, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (136, ''viewDashMedia'', ''View the Media Graphs'', ''desktop'', ''admin'', 190, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (137, ''viewDashManager'', ''View the Manager''''s Graphs'', ''desktop'', ''admin'', 200, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (138, ''viewDashOwner'', ''View the Owner''''s Graphs'', ''desktop'', ''admin'', 210, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (139, ''viewDashRM'', ''View the RM Graphs'', ''desktop'', ''admin'', 155, 1, '''')



-- Platinum specific section  exec spConvertDBSeed
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (105, ''menu_todayRM'', ''View Today for Resource Managers'', ''platinum'', ''admin'', 8, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11605, ''viewLegacyFields'', ''View Legacy Fields'', ''admin'', ''admin'', 25, 1, ''This setting is used to determine if a user can view fields that have been identified as legacy.  If this setting is not enabled then fields that have been tagged as legacy, will not be visible to the user.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10100, ''adminsetup'', ''Maintain Setup Information'', ''admin'', ''admin'', 1, 1, ''This works with the first 15 options under this heading (security setting right preceded by ---- ); if you want to allow access in the following areas, you must also check this box.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10101, ''adminsetup_acctinfo'', ''---- Edit Account Information'', ''admin'', ''admin'', 2, 1, ''Allows access to Admin > System Setup > Account Information.<br>Address Information: Edit company information such as website, phone numbers, EIN and addresses.<br>Visual Appearance: Customize the culture, font for report options and application name.<br>Activation Status: Lets you view active and deactivated users.<br>Workamajig Labs: You can turn on/off the Workamajig Labs.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10117, ''adminsetup_security'', ''---- Allow Access to Security Settings'', ''admin'', ''admin'', 3, 1, ''Allows access to Admin > System Setup > System Options.<br>Security Settings: This is where you grant user rights for security groups, control password settings and control folder and file rights.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10102, ''adminsetup_globaloptions'', ''---- Allow Access to System Options'', ''admin'', ''admin'', 4, 1, ''Allows access to Admin > System Setup > System Options.<br>Transaction Preferences: Edit settings for Contact Management, Clients, Projects, Campaigns, Estimates, Time Sheets, Expense Reports, Deliverables, Purchase Orders, Media, Client and Vendor Invoices and Daily Emails.<br>Custom Menu: Create a company menu for each security group.<br>Connections: Edit your Email settings, File Storage settings, API, Single Sign on and Credit Cards.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10115, ''adminsetup_globaloptionslists'', ''---- Allow Access to Lists'', ''admin'', ''admin'', 5, 1, ''Resource Manager >Assignment Mgmt: Edit Assignment Statuses<br>Departments: Add/edit/delete departments for use in projects.<br>Offices: Add/edit/delete offices within the company.<br>Project Billing Status Codes: Add/edit/delete project billing status codes for your projects.<br>Project Status Codes: Add/edit/delete project status codes for your projects and set which statuses are active.<br>Project Templates: Setup project templates to be used to quickly create projects.<br>Project Types: Add/edit/delete the Project Types (i.e. Collateral, Events, Print, Web, etc.).<br>Report Groups: Add/edit/delete the name and display order of the Custom Report Groups (i.e. Time Analysis, Purchasing, Billing, Contact, & Sales Lead).<br>Request Reject Reasons: Set up your standard reasons for rejecting project requests.<br>Schedule Column Sets: Set up pre-defined sets of columns that can be used with the project schedule.<br>Scheduled Reports: Set up start date, end date, export type and recurrence options for scheduled reports.<br>Teams: Add/edit/delete teams for projects.<br>Timeline Segments: Add/edit/delete segment names and colors to show on the schedule and gantt view.<br>To Do Status: Add/edit/delete status codes for managing to dos.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10103, ''adminsetup_dashboard'', ''---- Edit Dashboards'', ''admin'', ''admin'', 6, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10104, ''adminsetup_GLSettings'', ''---- Edit GL Settings'', ''admin'', ''admin'', 7, 1, ''Allows access to Admin > System Setup  > GL Settings.<br>GL Tracking Options: Set up GL tracking Options, GL Accounts, Prebilled Purchase Orders and Media, Advance Sales and Purchasing Tracking, Multicurrency Tracking, Revenue Forecast Tracking and Legacy Integration.<br>GL Accounts: Add/edit/delete your general ledger accounts to track your finances.<br>GL Companies: Add/edit/delete GL companies.<br>Check Formats: Add/edit/delete check options, layouts, stub layouts and grid columns.<br>Postive Pay Layouts: Add/edit/delete header fields, detail fields and footer fields for positive pay layouts.<br>Corporate Profit and Loss Layout: Allows you to create custom layouts for financial reporting.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10105, ''adminsetup_CM'', ''---- Edit Contact Management options'', ''admin'', ''admin'', 8, 1, ''Allows access to Admin > System Setup > Contact Management.<br>Add/edit/delete Opportunity Stages, Opportunity Status and Opportunity Outcomes.<br>Company Types: Add/edit/delete the defined company types; default company types have been set up.<br>Meeting Types: Add/edit/delete the defined calendar event types, and what color it will show up as on the calendar.<br>Calendar Resources: Add/edit/delete the defined calendar resources, like conference room and projector.<br>Define Source: This is used to identify how the relationship with a Lead or a Company is initially formed. You can add/edit/delete your sources here.<br>Conversation Types: Add/edit/delete the defined conversation types and set display colors.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10106, ''adminsetup_timeoptions'', ''---- Edit Time options'', ''admin'', ''admin'', 9, 1, ''Allows access to Admin > System Setup > Billing Options > Time Tracking.<br>Services: Add/edit/delete the different types of services in the system, this includes the service code, description, active status and hourly rate.<br>Service Rate Sheets: This is where you can set up special rates for services and added/edit/delete those rate sheets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10107, ''adminsetup_media'', ''---- Edit Media Setup options'', ''admin'', ''admin'', 10, 1, '' Allows access to Admin > System Setup > Media.<br>Broadcast Items: Add/edit/delete the different broadcast items in the system.<br>Print Items: Add/edit/delete the different print item types in the system.<br>Markets: Add/edit/delete the Media Markets used to define regions for media buying.<br>Revision Reasons: Add/edit/ delete the reasons why media had to be revised.<br>Publication/Station Items: Add/edit/delete the different publication and station items in the system.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10108, ''adminsetup_specsheet'', ''---- Edit Spec Sheets'', ''admin'', ''admin'', 11, 1, ''Allow access to Admin > System Setup > Tracking > Define Spec Sheets.<br>Add/edit/delete project spec sheets, define the fields and customize the spec sheets. The default spec sheets in the system are Photography, Printing, and Publication Specs and they can be attached to projects throughout the system.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10109, ''adminsetup_projrequest'', ''---- Edit Project Requests'', ''admin'', ''admin'', 12, 1, ''Allows access to Admin > System Setup > Tracking > Define Project Requests.<br>Add/edit/delete project request forms, set up of custom fields, add spec sheets, create an approval process and give different security groups access to those requests.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10110, ''adminsetup_forms'', ''---- Edit Tracking Forms'', ''admin'', ''admin'', 13, 1, ''Allows access to Admin > System Setup > Tracking > Define Tracking Forms|, gives the right to add/edit/delete forms, including the right to define the options and fields associated with the form and give access to the forms.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10111, ''adminsetup_purchasing'', ''---- Edit Purchasing Options'', ''admin'', ''admin'', 14, 1, ''Allows access to Admin > System Setup > Purchasing.<br>Order Header Customization: Define the blocks of text that will appear at the top or bottom of POs, add/edit/delete PO header field groups and add/edit/delete purchase order types.<br>Order Line Customization: Add/edit/delete PO detail field groups.<br>Purchasing: Add/edit/delete expense report items, purchase items and item rate sheets.'')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10112, ''adminsetup_da'', ''---- Edit Digital Assets Options'', ''admin'', ''admin'', 15, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10113, ''adminsetup_custfields'', ''---- Edit and Assign Custom Fields'', ''admin'', ''admin'', 16, 1, ''Allows access to Admin > System Setup > Custom Fields.<br>Custom Fields provides the ability to add customized input and reporting fields to key parts of the system. This setting allows access to setup company-wide custom fields that show up in the designated areas of your system for the following:<br>Employee Fields<br>Company Fields<br>Contact Fields<br>Project Fields<br>Campaign Fields<br>Retainer Fields<br>Conversation Fields<br>Opportunity Fields.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10114, ''adminsetup_glcompanyaccess'', ''---- Edit GL Company Access'', ''admin'', ''admin'', 17, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10116, ''adminsetup_billing'', ''---- Edit Billing options'', ''admin'', ''admin'', 18, 1, ''Allows access to Admin > System Setup > Billing Options > Billing Options.<br>Billing Items: Add/edit/delete the billing items in the system, set the default sales account, active status, etc.<br>Billing Groups: Add/edit/delete billing groups.<br>Sales Tax Rates:  Add/edit/delete the sales tax rates.<br>Payment Terms: Add/edit/delete the payment terms and corresponding days until an invoice is due.<br>Payment Methods: Add/edit/delete the accepted methods of payment for the company.<br>Write Off Reasons: Add/edit/delete the write off reasons.<br>Invoice Layouts: Add/edit/delete the invoice layouts. You can decide on how a particular invoice layout will print, where you set the margins, addresses to show, fonts, logos, etc.<br>Estimate Layouts: Add/edit/delete the estimate layout and determine how a particular estimate layout will print.<br>Credit Card Processing. the right to set up credit card processing.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10118, ''adminsetup_meetingrequest'', ''---- Edit Meeting Custom Fields'', ''admin'', ''admin'', 12, 1, ''Allows access to Meeting custom fields'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10200, ''admineditinout'', ''Edit Other Peoples In / Out Status'', ''admin'', ''admin'', 19, 1, ''Give access to change anyones status on the In/Out board (must have access to view and edit the in/out widget to see this right).'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10600, ''adminemployee'', ''Maintain Company Employees'', ''admin'', ''admin'', 20, 1, ''Allows access to Admin > Employees and the ability to Add New Employees and Delete Employees.  Can only see and edit Basic Info page and Notifications page.  Has access to the Actions: Reassign Assignments/ Assign to All Projects / Assign to All Active Projects / Assign to All Inactive Projects, but will not be able to reassign assignments unless you have those rights as well.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10610000, ''admin_edit_employee_contact_cf'', ''Edit Employee and Contact Custom Fields'', ''admin'', ''admin'', 21, 1, ''Allows access to Custom Field tab in Employees and Contacts. Must also have Maintain Company Employees checked to view this area.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10620, ''adminuserconvert'', ''Convert Contact to Employee or Employee to Contact'', ''admin'', ''admin'', 22, 1, ''Allows user to convert a Contact to an Employee or an Employee to a Contact.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10700, ''admineditlogin'', ''Edit Employee and Contact Login information'', ''admin'', ''admin'', 23, 1, ''Allows access to Security Controls/Login information tab in Employees and Contacts.  Must also have Maintain Company Employees checked to view this area.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10720, ''user_billing'', ''Edit Employee and Contact Accounting Information '', ''admin'', ''admin'', 24, 1, ''Allows access to Accounting tab in employees and Contacts. Must also have Maintain Company Employees checked to view this area.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10730, ''employee_project_time'', ''Edit Employee Projects and Time Information'', ''admin'', ''admin'', 25, 1, ''Allows access to Projects and Time tab on the Employee record. Must also have Maintain Company Employees checked to view this area.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10750, ''adminviewcostrate'', ''View labor net cost per hour in lookups and reports'', ''admin'', ''admin'', 26, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10800, ''adminedituserskills'', ''Maintain User Skill Levels'', ''admin'', ''admin'', 27, 1, ''Allows user access to view and edit in the Skill tab in employee records. Must also have Maintain Company Employees checked to view this area.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10805, ''admineditusercalendar'', ''Maintain Employee Calendar '', ''admin'', ''admin'', 28, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11200, ''reportsdesign'', ''Design custom reports'', ''admin'', ''admin'', 29, 1, ''Everyone > Reports (also need security rights in Reports). No Datasets available to create custom reports from when clicking on +New Custom Report.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11300, ''reportsrun'', ''Run custom reports'', ''admin'', ''admin'', 30, 1, ''Everyone > Reports. Access to Other Reports which is where custom reports reside.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11400, ''dataexchange'', ''Import and export data'', ''admin'', ''admin'', 31, 1, ''Admin > Import Data. This allows them to do any kind of data importing in the system.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11500, ''admineditlisting'', ''Edit Custom Listings'', ''admin'', ''admin'', 32, 1, ''Gives users the rights to Modify and Memorize (ex. on Project or Estimate listing screens).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11601, ''adminViewLog'', ''View the System Log'', ''admin'', ''admin'', 33, 1, ''Admin > Today-Managers > System Log. This is the log of what has been approved, unapproved, posted, unposted or deleted in the system. Only if you selected Enable Transaction Logging in your Transaction Preferences.  You cannot view or open any of these items, but you can see what was done, by whom and when.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11602, ''adminActivateMyLabs'', ''Allow a person to enable labs just for themselves'', ''admin'', ''admin'', 34, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11603, ''adminDisplayNonProjectLogs'', ''View Non Project Log '', ''admin'', ''admin'', 35, 1, ''Allows a person to view non project related events on The Daily Feed.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (601000, ''desktopEditSetup'', ''Edit the company settings for the desktop'', ''admin'', ''admin'', 36, 1, ''Makes Company Settings available in Configure Desktop options allowing the user to create/edit/delete desktop views for any security group in the company. The security group must also have the right to change Their Desktop Layout or they will not be able to get to the Configure Desktop at all.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11606, ''adminChangeBillingTitle'', ''Edit Employee Billing Title'', ''admin'', ''admin'', 37, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (108, ''adminUserSettings'', ''Set System Settings'', ''admin'', ''admin'', 38, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (106, ''menu_reportCenter'', ''View the Report Center'', ''admin'', ''admin'', 39, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (116, ''adminsetup_scheduleReports'', ''Schedule Reports'', ''admin'', ''admin'', 40, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10210, ''adminsetup_automation'', ''Edit Automation'', ''admin'', ''admin'', 41, 1, ''Allows access to Admin > System Setup > Automation<br>Add/edit/delete automations.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11700, ''viewAPITokens'', ''View API Tokens'', ''admin'', ''admin'', 42, 1, ''Allows users to access the API User Token and the API Company Token'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (11701, ''changeUserColors'', ''Change the visual appearance at the user level'', ''admin'', ''admin'', 43, 1, ''This allows users to modify the visual colors of the system at the user level'')



INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (101, ''menu_myProjects'', ''View Projects App'', ''project'', ''admin'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90100, ''adminCreateProject'', ''Create New Projects'', ''project'', ''admin'', 10, 1, ''Allows access to project listings for those projects the user is assigned to and to create a New project in the system (but cannot see that new project unless they have other rights as well). User who created new project is automatically assigned to the project team.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90200, ''prjInfo'', ''Maintain Project Setup'', ''project'', ''admin'', 20, 1, ''Allows the user access to Project Setup > Project Settings (user access in these areas may be limited by other security settings).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (903510, ''prjReopen'', ''Reopen Projects'', ''project'', ''admin'', 30, 1, ''Allows users to reopen Projects if they have this right on Projects > Setup > Project Settings > Accounting: they see a box next to Closed and they can close or open a project.  If it is not checked, they just see yes if it is closed, if it is not closed, there is a check box and they could close a project, then not have rights to re-open it. Must also have access to Maintain Project Setup.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90310, ''prjviewtasks'', ''View Task, Schedule Pages'', ''project'', ''admin'', 40, 1, ''Gives the user access to the Schedule tab in the project, but there are no options to add/edit or save.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90355, ''prjeditmastertaskdefs'', ''Edit Master Task defaults on task'', ''project'', ''admin'', 50, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90810, ''prjEditLocked'', ''Edit Projects in a Locked Status'', ''project'', ''admin'', 60, 1, ''There is a setting on a Project Status Codes that lets you put the project into a Locked Status. When a project is in this status you can not change the project status unless you have this right.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (107, ''prjEditProjectNumber'', ''Edit an existing Project Number'', ''project'', ''admin'', 65, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90315, ''prjviewbudget'', ''View Project Budget Page'', ''project'', ''admin'', 70, 1, ''Allows the user to view the Project Budget screen as well as view project budgets on the Campaign screen.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90320, ''prjedittasks'', ''Edit task information'', ''project'', ''admin'', 80, 1, ''User can edit tasks in the schedule and is granted access to all Detail tabs in the schedule screen (but not if schedule is locked and the user does not have the right  Override Scheduling Lock to Edit Projects in a Locked Status by Override).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90850, ''prjUnlockLocked'', ''Override Scheduling Lock'', ''project'', ''admin'', 90, 1, ''Allows user to Unlock a schedule.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90335, ''prjeditestimaterates'', ''Edit Rates on Estimates'', ''project'', ''admin'', 100, 1, ''Must have Edit Estimate Information checked to view this.  Allows user to click on the pencil icon for Estimating Services/Edit Service Rates on new or unapproved estimates (this includes a persons rate if doing a task/person estimate), but it only effects that project.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90336, ''prjrecalcrates'', ''Update Estimate Rates from Project'', ''project'', ''admin'', 110, 1, ''Must have Edit Estimate Information checked to view this, and the right to Edit Rates on Estimates.  Allows user to update the Estimating Services/Edit Service Rates on a new or unapproved estimate, and to Set Standard Rates pulling from Service Rates setup at the system level. '')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90337, ''prjrecalclaborrates'', ''Recalculate Labor Rates on Project'', ''project'', ''admin'', 111, 1, ''This will update the rate on unbilled time entries on a project from rates and settings defined on the project.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90330, ''prjeditestimate'', ''Edit Estimate Information'', ''project'', ''admin'', 120, 1, ''Must have this checked to get to the above 2 rights.  When checked you can view Project Central > Estimates, add new estimates, set approver on a new estimate, make changes to hours on unapproved estimates only and add expenses on unapproved estimate only.  If someone else approved the estimate, they cannot unapprove it.  They see Edit Service Rates but this only allows them to limit services available to put on the estimate, not change the rate offered for the service on that project.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90338, ''prjviewestimate'', ''View Estimate Information'', ''project'', ''admin'', 112, 1, ''When checked a PDF will be created of the estimate'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (1190930, ''prjnotes'', ''Access Project Conversations'', ''project'', ''admin'', 130, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (1190931, ''prjnotesedit'', ''Edit own Project Conversations'', ''project'', ''admin'', 140, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90922, ''prjEditOthersDiary'', ''Edit other peoples Project Conversations'', ''project'', ''admin'', 150, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (903500, ''adminDeleteProject'', ''Delete a Project'', ''project'', ''admin'', 160, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (112, ''adminsetup_templates'', ''Edit Project Templates'', ''project'', ''admin'', 165, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90600, ''prjviewcreativebrief'', ''View the Creative Brief'', ''project'', ''admin'', 170, 1, ''On the project dashboard.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90350, ''prjeditcreativebrief'', ''Edit the Creative Brief'', ''project'', ''admin'', 180, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90700, ''prjviewspecs'', ''View the Project Specifications'', ''project'', ''admin'', 190, 1, ''View only access to any attached spec sheets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90360, ''prjeditspecs'', ''Edit the Specifications'', ''project'', ''admin'', 200, 1, ''Allows user to add/edit spec sheets and Copy spec sheets from another project, must have the right to View the Project Specifications.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90365, ''prjdeletespecs'', ''Delete a Specification'', ''project'', ''admin'', 205, 1, ''Allows user to delete spec sheets, must have the right to View the Project Specifications.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90370, ''prjMiscExpense'', ''Add and Edit Misc Expenses'', ''project'', ''admin'', 210, 1, ''Grants access for Project Details > Misc Costs.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90340, ''prjunappestimate'', ''Unapprove estimate or change order '', ''project'', ''admin'', 220, 1, ''User can unapproved an estimate that had already been approved by the designated Internal Approver.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20100, ''approveadd'', ''Edit/Add Deliverables'', ''project'', ''admin'', 230, 1, ''Allow access in Project Central > Deliverables. User can setup a new review, update existing reviews and recall reviews previously sent for approval.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20200, ''approveview'', ''View Deliverables'', ''project'', ''admin'', 225, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20300, ''approvedelete'', ''Delete Deliverables'', ''project'', ''admin'', 240, 1, ''Allows user to delete an existing deliverable, whether it has been reviewed or not.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20400, ''approveeditcomment'', ''Edit Other People''''s Deliverable Comments'', ''project'', ''admin'', 245, 1, ''Allows user to edit another user''''s deliverable comments.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90905, ''prjViewTran'', ''View Project Transactions'', ''project'', ''admin'', 250, 1, ''This only allows a view of the Project Transaction screen.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90906, ''prjViewTranAdjusted'', ''View Project Adjusted Transactions'', ''project'', ''admin'', 251, 1, ''This allows a view of the adjusted transactions on the Project Transaction screen. Adjustments include transfers, transactions edited after posting to WIP and writeoffs undone after posting out of WIP. Users who do not have this right, can only see the most current transactions, i.e. no original or reversed transactions.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90900, ''prjViewCampaign'', ''View Campaigns'', ''project'', ''admin'', 260, 1, ''User can view a Campaign Listing from Projects.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90800, ''prjEditCampaign'', ''Edit Campaigns'', ''project'', ''admin'', 270, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90901, ''prjEditTeam'', ''Edit the Project Team'', ''project'', ''admin'', 280, 1, ''User can add and delete team members from the Project Setup > Team tab.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90911, ''prjDashStatus'', ''View the current status on the project dashboard'', ''project'', ''admin'', 290, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90912, ''prjDashDescription'', ''View the project description on the project dashboard'', ''project'', ''admin'', 300, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90913, ''prjDashSetup'', ''View the setup information on the project dashboard'', ''project'', ''admin'', 310, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90914, ''prjDashBrief'', ''View the creative brief on the project dashboard'', ''project'', ''admin'', 320, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90915, ''prjDashSpecs'', ''View the spec sheets on the project dashboard'', ''project'', ''admin'', 330, 1, '''')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90917, ''prjDashSnapshot'', ''View the project snapshot on the project dashboard'', ''project'', ''admin'', 350, 1, ''Must also have the security right setting under Dashboard for View the Project Snapshot.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90918, ''prjAccessAny'', ''Access any project'', ''project'', ''admin'', 360, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90919, ''prjChargeAny'', ''Charge any project'', ''project'', ''admin'', 370, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90923, ''prjViewRevenueSource'', ''View Project Revenue Source'', ''project'', ''admin'', 400, 1, ''This setting controls where the system looks to get the GL Company and Office for labor revenue. It can either get the company/office from the Project or the Person. If you select the person and if you use multiple GL companies, then you need to have intercompany journal entry mappings set up.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90924, ''prjViewSetupAccounting'', ''View Project Setup Accounting'', ''project'', ''admin'', 410, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90925, ''prjDashCustomFields'', ''View the Project Custom Fields'', ''project'', ''admin'', 420, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90930, ''prjViewToDos'', ''View To Dos'', ''project'', ''admin'', 430, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90931, ''prjEditToDos'', ''Add/Edit To Dos'', ''project'', ''admin'', 440, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90932, ''prjDeleteToDos'', ''Delete To Dos'', ''project'', ''admin'', 450, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90933, ''prjViewOtherToDos'', ''View To Dos Not Assigned To You'', ''project'', ''admin'', 460, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90934, ''prjEditOtherToDos'', ''Edit To Dos Not Assigned To You'', ''project'', ''admin'', 470, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90935, ''prjQuickAddTask'', ''Use Quick Task Add without being able to edit the schedule'', ''project'', ''admin'', 480, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90936, ''prjQuickAddActivity'', ''Use Quick Activity Conversation Add without being able to edit the schedule'', ''project'', ''admin'', 481, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90937, ''prjChangeAnyoneCharges'', ''Change Anyone Allowed to Charge Time on project'', ''project'', ''admin'', 371, 1, ''If you have this right the checkbox ''''Anyone Allowed to Charge Time'''' will become visible on the Project Accounting screen allowing changes to it.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90938, ''adminCreatePlanningProject'', ''Create New Planning Projects'', ''project'', ''admin'', 482, 1, ''Allows access to project listings for those projects the user is assigned to and to create a New planning project in the system (but cannot see that new project unless they have other rights as well). User who created new planning project is automatically assigned to the project team.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90939, ''prjViewBillingOptions'', ''View Project Setup Billing Options'', ''project'', ''admin'', 483, 1, ''Allows access to project setup billing options.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30000, ''billingviewclientinvoice'', ''View Client Invoices'', ''billing'', ''admin'', 1, 1, ''Allows access in Billing to view the Client Invoices.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30101, ''billingviewinvoice'', ''View the Invoice List '', ''billing'', ''admin'', 2, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30100, ''billingeditinvoice'', ''Add and Edit Client Invoices and Credits'', ''billing'', ''admin'', 3, 1, ''This grants the right to bill projects. If it is not turned on, the security group will not see any options related to billing. Allows access to Billing > Client Invoices to view existing invoices and create new. Also allows user access to electronic Billing Worksheets to Generate, Reassign, Approve, and Create Invoices from the billing worksheet. User can also do Fixed Fee Billing and Mass Billing for Production, Media, and Retainers.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30200, ''billingpayments'', ''Enter Receipts'', ''billing'', ''admin'', 4, 0, ''Allows access to Receipts (this option also shows Deposit, but there is not actually access to that screen).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30300, ''br_viewarreports'', ''-- View AR Reports --'', ''reports'', ''admin'', 4000, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30310, ''br_viewapreports'', ''-- View AP Reports --'', ''reports'', ''admin'', 5000, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30320, ''br_viewglfinancial'', ''-- View Company Financial Reports --'', ''reports'', ''admin'', 7000, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30330, ''br_viewmedia'', ''-- View Media Reports --'', ''reports'', ''admin'', 6000, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30700, ''billingdeposits'', ''Edit Deposit Slips'', ''billing'', ''admin'', 5, 0, ''Allows access to Deposits.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30800, ''billingcreditcard'', ''Edit and Charge Credit Cards'', ''billing'', ''admin'', 6, 0, ''Must also have System Setup in Time and Billing for Credit Card Processing in order to activate the Credit Card tab for receipts.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30900, ''billingretainers'', ''Edit Retainers'', ''billing'', ''admin'', 7, 1, ''Must have the right to View Retainers in order to setup and view details of how a Retainer is defined. This also allows access to the Status tab showing retainer history and performance.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30901, ''billingviewretainers'', ''View Retainers'', ''billing'', ''admin'', 8, 1, ''This only allows a view of the listing screen for Retainers.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30902, ''billingdeleteworksheet'', ''Delete Worksheets'', ''billing'', ''admin'', 9, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30903, ''billingedittran'', ''Edit Transactions on Projects'', ''billing'', ''admin'', 10, 1, ''Allows access to Billing > Time and Materials and The Project Transactions screen.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30904, ''billingaddtran'', ''Add Transactions to Worksheets'', ''billing'', ''admin'', 11, 1, ''Allows transactions to be added to a billing worksheets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30905, ''billingtransfertran'', ''Transfer Transactions to Billable Projects'', ''billing'', ''admin'', 12, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30906, ''billingwriteofftran'', ''Write Off Transactions'', ''billing'', ''admin'', 14, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30907, ''billingunwriteofftran'', ''Undo Write-off Transactions'', ''billing'', ''admin'', 15, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (30908, ''billingtransfertrannonbillable'', ''Transfer Transactions to Non Billable Projects'', ''billing'', ''admin'', 13, 1, '''')

-- Removed - issue #569710
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (40400, ''dash_showsnapshot'', ''View the Project Snapshot'', ''dashboard'', ''admin'', 1, 1, ''Must also have the Project Administration right to View the project snapshot on the project dashboard.'')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (40500, ''dash_showprofit'', ''View the Profit Snapshot'', ''dashboard'', ''admin'', 2, 1, ''Allows the user to view Project Profitability from the Project Dashboard. User must also have the right to Reports > Project Profitability, AND the Project Administration right to View the project snapshot on the project dashboard.'')


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (50100, ''fileAccess'', ''Access the File Folders'', ''file'', ''admin'', 1, 1, ''Grants full access to Files managed through Project Central.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (50110, ''fileSearchAll'', ''Search in projects you are not assigned to'', ''file'', ''admin'', 2, 1, ''In order to view files in projects that this user is not assigned to, security rights must be granted to this group within the project where the file resides.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60100, ''purch_editpo'', ''Add and Edit Purchase Orders'', ''purch'', ''admin'', 2, 1, ''Allows access in Purchasing to add and edit Purchase Orders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60101, ''purch_deletepo'', ''Delete Purchase Orders'', ''purch'', ''admin'', 3, 1, ''Allows access in Purchasing to delete Purchase Orders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60200, ''purch_editpo_approved'', ''Edit Purchase Orders after Approval'', ''purch'', ''admin'', 4, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60300, ''purch_editvoucher'', ''Add and Edit Vendor Invoices'', ''purch'', ''admin'', 4, 1, ''Allows access in Purchasing to add and edit Vendor Invoices.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60301, ''purch_viewvoucher'', ''View Vendor Invoices'', ''purch'', ''admin'', 4, 1, ''Allows access in Purchasing to view the Vendor Invoices.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60302, ''purch_viewpo'', ''View Purchase Orders'', ''purch'', ''admin'', 4, 1, ''Allows access in Purchasing to view Purchase Orders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60305, ''purch_approvevoucher'', ''Approve Vendor Invoices'', ''purch'', ''admin'', 4, 1, ''Allows access in Purchasing to approve Vendor Invoices.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60400, ''purch_usecreditcard'', ''Add and Edit credit card charge entry screens'', ''purch'', ''admin'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60401, ''purch_addothercreditcardcharge'', ''Add credit card charges for other employees'', ''purch'', ''admin'', 6, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60402, ''purch_editothercreditcardcharge'', ''Edit credit card charges of other employees'', ''purch'', ''admin'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60403, ''purch_approvecreditcardcharge'', ''Approve credit card charges'', ''purch'', ''admin'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60500, ''purch_usecreditcardconnect'', ''View and use the credit card connect screen'', ''purch'', ''admin'', 3, 1, ''Allows access to the Credit Card Connector screen.  From there you can download and apply credit card transactions.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (60501, ''purch_viewcreditcard'', ''View credit card charge entry screens'', ''purch'', ''admin'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61100, ''quote_edit'', ''Add and Edit Quotes'', ''purch'', ''admin'', 8, 1, ''Allows access to Purchasing > Quotes.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61200, ''quote_createpo'', ''Create PO''''s from Quotes'', ''purch'', ''admin'', 1, 1, ''Allows access to Purchasing > Quotes with access to the [Create PO] button in the Replies tab for Replies Completed. Must have the right to Add and Edit Quotes.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61300, ''purch_editpayment'', ''Add and Edit Payments'', ''purch'', ''admin'', 9, 0, ''Allows user access add and edit payments, to Select Invoices for Payment and to Print Checks.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61400, ''purch_viewiteminfo'', ''View Cost and Rate on Item Lookup '', ''purch'', ''admin'', 10, 1, ''Allows the user to see Unit Cost and Unit Rate setup for Purchase Items.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61500, ''purch_editsignatureoncheck'', ''Edit Electronic Signature on Checks'', ''purch'', ''admin'', 11, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61600, ''purch_printchecks'', ''Print Checks'', ''purch'', ''admin'', 12, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61700, ''purch_approvemyprojectvoucher'', ''Approve vendor invoices on your projects'', ''purch'', ''admin'', 13, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61800, ''purch_viewbankinfo'', ''View vendor bank information'', ''purch'', ''admin'', 14, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (61900, ''purch_editbankinfo'', ''Edit vendor bank information'', ''purch'', ''admin'', 15, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (70100, ''formuse'', ''Use forms'', ''form'', ''admin'', 1, 1, ''Allows access to Menu > Tracking forms for any tracking forms that their security group is assigned, but they cannot do anything else, unless they have the following rights; Add New Forms, View Forms or Delete Forms.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (70200, ''formadd'', ''Add new forms'', ''form'', ''admin'', 2, 1, ''Allows access to Menu > Tracking forms for any tracking forms that their security group is assigned to. The user can open a form > Add New and fill out that form. But once the form is saved, they will not be able to do anything else to it unless assigned to their self. The Assigned To field is required, if the user assigns it to someone other than themself, they will only have access as other security rights allow.'')
	
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (70300, ''formdelete'', ''Delete forms'', ''form'', ''admin'', 3, 1, ''Allows access to any tracking forms that the security group is assigned the right to Delete a form they created.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (70400, ''formviewall'', ''View forms not assigned to the user'', ''form'', ''admin'', 4, 1, ''Allows access to View any tracking forms that the security group is NOT assigned to. The user can re-open and Delete a form they created, but cannot Delete a form assigned to them that was authored by another user.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (70500, ''nonauthorformdelete'', ''Delete form if not author'', ''form'', ''admin'', 5, 1, ''If the user has the right to view forms not assigned to them, this allows the right to Delete a form they created, AND to re-open and Delete forms created by another user.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90300, ''prjviewprojectreports'', ''-- View Project Financial Reports --'', ''reports'', ''admin'', 2000, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100100, ''billingusetimesheet'', ''Use Time Sheets'', ''time'', ''admin'', 1, 1, ''Allows access to Time Sheets from main Menu dropdown.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100110, ''time_editratelevel'', ''Edit the rate level on the time sheet'', ''time'', ''admin'', 2, 1, ''Allows access to Time Sheets > Options > Show Rate Level > once that is checked, they can change their rate level from Level 1, to 2, 3, 4, 5, but cannot actually change the amount of those rates, that is an admin right.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100120, ''timeallservices'', ''Charge time to any service'', ''time'', ''admin'', 3, 1, ''This will make all services that are setup in the system available for the user to charge time against.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100130, ''timealltasks'', ''Charge time to tasks they are not assigned to'', ''time'', ''admin'', 4, 1, ''Allows the user to charge time to any tracking task whether assigned or not.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100950, ''timetotasksnocompletedpreds'', ''Charge time to tasks that do not have completed predecessors'', ''time'', ''admin'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90920, ''prjTimeCompletedTask'', ''Charge time to completed tasks'', ''time'', ''admin'', 6, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90921, ''prjExpenseCompletedTask'', ''Charge expense to completed tasks'', ''time'', ''admin'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100300, ''billingtimesheetrate'', ''View rates on the time sheet'', ''time'', ''admin'', 8, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100400, ''billingviewalltime'', ''View anyone''''s time sheet'', ''time'', ''admin'', 9, 1, ''Allows access to view other people''''s time sheets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100500, ''billinguseexpenses'', ''Use Expenses'', ''time'', ''admin'', 10, 1, ''The right to create and submit expense reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100700, ''billingviewallexpense'', ''View anyone''''s expense report'', ''time'', ''admin'', 11, 1, ''Right to view other peoples expense reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100800, ''billingeditanyone'', ''Edit Time Sheets and Expense Reports for anyone'', ''time'', ''admin'', 12, 1, ''Allows access to open, view and edit other peoples expense reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100801, ''billingeditusersiapprove'', ''Approvers can edit timesheets for people they approve'', ''time'', ''admin'', 13, 1, ''Allows users to edit timesheets for people under their approval.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100802, ''billingviewusersiapprove'', ''Approvers can view timesheets for people they approve'', ''time'', ''admin'', 14, 1, ''Allows users to view timesheets for people under their approval.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100900, ''billingtimesheetunapprove'', ''Unapprove the time sheets'', ''time'', ''admin'', 15, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (100905, ''billing_expenserptapproveimported'', ''Import Expense Reports as Approved'', ''time'', ''admin'', 16, 1, ''Allows user to import expense reports as approved when user does not have the ability to approve individual expense report.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (110300, ''traffic_viewschedule'', ''View Project Schedules'', ''traffic'', ''admin'', 1, 1, ''Allows access to Resource Manager > Traffic Calendar. Must also have Project Administration rights to View Task and Schedule pages.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (110900, ''traffic_viewstaff'', ''View Staff Scheduling and Loading'', ''traffic'', ''admin'', 2, 1, ''Allows access to Resource Manager > Staff Schedule. The Staff Schedule screen provides an overview of resource allocations.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (110950, ''traffic_viewassignment'', ''Traffic Assignment Review'', ''traffic'', ''admin'', 3, 1, ''Allows access to Project Manager > Today-PM > Views > Assignments. This provides a listing of assignments with filtering options and the ability to select and update Complete Dates for multiple assignments at once.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (110960, ''traffic_assignmentMgt'', ''Traffic Assignment Management Screen'', ''traffic'', ''admin'', 4, 1, '''')


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200100, ''proj_projectsummary'', ''Project Budget Analysis'', ''reports'', ''admin'', 2010, 1, ''Access to the Project Budget Analysis, which allows the user to view project budget drilldowns in summary or detail (by Project, Task, or Item) against the actuals.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200101, ''proj_projectscoreboard'', ''Project Summary Scoreboard'', ''reports'', ''admin'', 2011, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200200, ''time_productivity'', ''Time Productivity Analysis'', ''reports'', ''admin'', 2020, 1, ''Show total billable and non-billable hours with multiple grouping options.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200300, ''proj_billingworksheet'', ''Billing Worksheet Report'', ''reports'', ''admin'', 2200, 1, ''Shows all unbilled transactions by project. When this is selected for Project Financial Reports, it is also avialable for run in the AR Report Center'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200400, ''proj_projectpo'', ''Project Purchase Order Listing'', ''reports'', ''admin'', 2300, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200500, ''time_billablesummary_hours'', ''Billable Summary - Hours'', ''reports'', ''admin'', 2100, 1, ''Shows chargeable, non-chargeable and total hours with labor budget comparison.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200600, ''time_billablesummary_dollars'', ''Billable Summary - Dollars'', ''reports'', ''admin'', 2120, 1, ''Shows chargeable, non-chargeable and total dollars with labor budget comparison.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (200700, ''proj_actualsbymonth'', ''Project Actuals by Month'', ''reports'', ''admin'', 2121, 1, ''Shows actuals per project with a 12-month view and the amount billed.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300000, ''rpt_trafficreports'', ''--  View Traffic Reports --'', ''reports'', ''admin'', 3000, 1, ''These settings are limited to access through the main Menu > Reports, and not through the Projects module'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300100, ''proj_projectstatus'', ''Project Status'', ''reports'', ''admin'', 3100, 1, ''This Summary report shows project status, estimated and actual hours.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300200, ''tasks_byUser'', ''Project Tasks by Person'', ''reports'', ''admin'', 3200, 1, ''Shows all tasks by assigned user.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300300, ''tasks_byUserDate'', ''Project Tasks by Person and Date'', ''reports'', ''admin'', 3300, 1, ''Shows all tasks by assigned user within a date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300400, ''tasks_byDate'', ''Project Tasks by Date'', ''reports'', ''admin'', 3400, 1, ''Shows all tasks by specified due date.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300500, ''tasks_setup'', ''Project Setup'', ''reports'', ''admin'', 3500, 1, ''Shows Schedule information for one or more projects.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300600, ''tasks_gantt'', ''Project Gantt Charts'', ''reports'', ''admin'', 3600, 1, ''Project Timeline shows Gantt Chart view of schedule for one or more projects.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (300655, ''tasks_Recap_Analysis'', ''Project Recap Analysis'', ''reports'', ''admin'', 3700, 1, ''This report is designed to highlight sections of the projects schedule where labor dollars and hours are concerned. Along with how long it took to complete each task.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303301, ''media_recap'', ''Media Recap'', ''reports'', ''admin'', 6010, 1, ''Shows media orders with net and gross amounts, grouped by month and by client.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303302, ''media_discrepancy'', ''Media Details Report'', ''reports'', ''admin'', 6020, 1, ''Shows media order variances from actual vendor invoice with multiple grouping options.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303303, ''media_mixanalysis'', ''Media Mix Analysis'', ''reports'', ''admin'', 6030, 1, ''Shows media types for the year by quarter with mix percentage, grouped by client.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303304, ''media_billing'', ''Media Billing Report'', ''reports'', ''admin'', 6031, 1, '''')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303305, ''media_printbuycal'', ''Media Print Buy Calendar Report'', ''reports'', ''admin'', 6040, 1, '''')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303306, ''media_printbuyblock'', ''Media Print Buy Block Report'', ''reports'', ''admin'', 6041, 1, '''')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (303307, ''media_printbuygrid'', ''Media Print Buy Grid Report'', ''reports'', ''admin'', 6042, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (400100, ''acct_ar_aging'', ''AR Account Aging'', ''reports'', ''admin'', 4010, 1, ''Shows all accounts receivable with open balances and aging.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (401000, ''usereports'', ''View the reports menu'', ''reports'', ''admin'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (401100, ''rptViewCMReports'', ''-- View Contact Management Reports --'', ''reports'', ''admin'', 1000, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (401200, ''rptCMBusDev'', ''Business Development Meeting'', ''reports'', ''admin'', 1001, 1, ''The business development report follows the WWP methodology. It shows a summary count of contacts at different levels to better understand trends. It also includes a summary of late stage opportunities as well as activities that need to get completed.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (401300, ''rptCMDownOpps'', ''Downgraded Opportunities'', ''reports'', ''admin'', 1002, 1, ''Shows opportunities that have been downgraded due to a number of different criteria such as a delay in close date, reduced forecast amounts and more.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500010, ''media_editio'', ''Edit Insertion Orders'', ''media'', ''admin'', 4, 1, ''Allows full access to Insertion Orders: Order Info, Address/Instructions, Order Line Items, Vendor and Client Invoices, and Linked Specifications. User can also Send Order Copies to Selected Contacts.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500011, ''media_editio_approved'', ''Edit Insertion Orders after Approval'', ''media'', ''admin'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500020, ''media_editbc'', ''Edit Broadcast Orders'', ''media'', ''admin'', 6, 1, ''Allows full access to Broadcast Orders: Order Info, Address/Instructions, Order Line Items, Traffic, Vendor and Client Invoices, and Linked Specifications. User can also Send Order Copies to Selected Contacts.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500021, ''media_editbc_approved'', ''Edit Broadcast Orders after Approval'', ''media'', ''admin'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500030, ''media_editestimate'', ''Edit Media Estimates'', ''media'', ''admin'', 2, 1, ''Allows user access to Media Estimates, where they can add and edit estimates and Update Orders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500035, ''media_editplan'', ''Edit Media Plans'', ''media'', ''admin'', 3, 1, ''Allows user access to Media Plans, where they can add and edit plans.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500040, ''media_traffic'', ''View the Media Traffic Screen'', ''media'', ''admin'', 8, 1, ''User can access the Media Traffic screens for both Broadcast and Insertion Orders.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500050, ''media_viewio'', ''View Insertion Orders'', ''media'', ''admin'', 9, 1, ''Allows access in Media to view Insertion Orders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500060, ''media_viewbo'', ''View Broadcast Orders'', ''media'', ''admin'', 10, 1, ''Allows access in Media to view Broadcast Orders.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500090, ''media_viewpubs'', ''View Publications'', ''media'', ''admin'', 11, 1, ''Allows access in Media to view Publications.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500095, ''media_viewstations'', ''View Stations'', ''media'', ''admin'', 12, 1, ''Allows access in Media to view Stations.'')


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (40600, ''dash_editcompanynotes'', ''Edit the Company Wide Notes (CMP Only)'', ''legacy'', ''admin'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (40700, ''dash_editprojectnotes'', ''Edit the Project Notes (CMP Only)'', ''legacy'', ''admin'', 2, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (40800, ''dash_editcontactnotes'', ''Edit the Contact Notes (CMP Only) (in contact management)'', ''legacy'', ''admin'', 3, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (10500, ''admincontact'', ''View the Company Address Book (CM Only)'', ''legacy'', ''admin'', 4, 1, ''View the Company Address Book. Salesperson > Contacts and Companies. Can view contacts and companies owned by anyone in the company, but cannot make any changes.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930000, ''cm_editcontacts'', ''Edit contact information (CM Only)'', ''legacy'', ''admin'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930100, ''cm_viewothermanagers'', ''View Other Account Manager''''s Opportunities and Activity Conversations (CM Only)'', ''legacy'', ''admin'', 6, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930150, ''cm_dashboard'', ''View the contact management dashboard (CM Only)'', ''legacy'', ''admin'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930200, ''cm_viewleads'', ''View and Edit Opportunities (CM Only)'', ''legacy'', ''admin'', 8, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930400, ''cm_viewactivities'', ''View Contact Activity Conversations (CM Only)'', ''legacy'', ''admin'', 9, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930500, ''cm_allowdelete'', ''Delete contacts (CM Only)'', ''legacy'', ''admin'', 10, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930600, ''cm_showall'', ''See contacts they do not own (CM Only)'', ''legacy'', ''admin'', 11, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930700, ''cm_alldb'', ''See contacts in all databases (CM Only)'', ''legacy'', ''admin'', 12, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (120300, ''calviewcompany'', ''View Company Meetings (CM Only)'', ''legacy'', ''admin'', 13, 1, ''Allows access to Public Calendar company meetings/project meetings. Must also have the Security settings from calendar setup with the right to View.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20000000, ''br_viewlegacy'', ''-- View Legacy Reports --'', ''legacy'', ''admin'', 14, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20000001, ''legacy_proj_projectsummary'', ''Project Budget Summary (Legacy)'', ''legacy'', ''admin'', 15, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20000002, ''legacy_acct_projectprofit'', ''Project Profitability (Legacy)'', ''legacy'', ''admin'', 16, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20000003, ''legacy_acct_projectwip'', ''Project WIP Report (Legacy)'', ''legacy'', ''admin'', 17, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (20000004, ''legacy_acct_gl_pl_ytd'', ''Income Statement (Legacy)'', ''legacy'', ''admin'', 18, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (401301, ''rptCMLeadList'', ''Opportunity List (CMP Only)'', ''legacy'', ''admin'', 19, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (120100, ''calUseCalendar'', ''Access the calendar'', ''calendar'', ''admin'', 1, 1, ''Allows access to the enterprise calendar from the Menu dropdown.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (120200, ''caladdmeetings'', ''Add New Meetings'', ''calendar'', ''admin'', 2, 1, ''Gives the right to add and edit meetings, but only for those calendars where the Security setting has the right to Edit.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (120400, ''calBlockOutDays'', ''Mark Calendar Events to block out days on the schedule'', ''calendar'', ''admin'', 3, 1, ''Only for those calendars where the setup allows the right to Edit.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (120500, ''caleditglobalgroups'', ''Maintain Global Distribution Groups'', ''calendar'', ''admin'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (120600, ''foldersCalendar'', ''Add/Edit/Delete Public Calendars'', ''calendar'', ''admin'', 4, 1, ''Allows the user to create new public calendars, edit and delete calendars in the list of Public Calendars.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931600, ''useContacts'', ''Use Contacts'', ''cm'', ''admin'', 1, 1, ''This setting must be turned on for access to all other Contacts security settings and allows access to Salesperson > Contacts. Can only see folders assigned to themself, and the Contacts contained in those folders where this user is the Contact Owner, can also view options in Details windows for Contact,  Company, Opportunities, Projects, History and add New Activity. This setting also allows the user to open and Edit existing Contact records, make a selection of Contact and Change multiple contacts at once.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931601, ''viewOtherContacts'', ''View Contacts You Do Not Own'', ''cm'', ''admin'', 4, 1, ''Can see all Contacts, whether the Contact Owner or not.<br>This right determines whether or not a user can see Contacts whos Contact Owner is someone other than the user. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931602, ''editOtherContacts'', ''Edit Contacts You Do Not Own'', ''cm'', ''admin'', 5, 1, ''Allows the ability to open and Edit existing Contacts. View Contacts You Do Not Own must also be turned on.<br>This right determines whether or not a user can see Contacts whos Contact Owner is someone other than the user. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931603, ''addContacts'', ''Add New Contacts'', ''cm'', ''admin'', 2, 1, ''Allows user to Add individual Contact records, but not the ability to Import Contacts.<br>This right determines whether or not a user can create new Contacts for themselves or another user. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931604, ''deleteContacts'', ''Delete Public Contacts'', ''cm'', ''admin'', 3, 1, ''Allows the user to open and Delete Contacts, also gives access to the Remove Duplicate Contacts option (When given the right to View and Edit Contacts You Do Not Own).<br>This right determines whether or not a user can delete Contacts for which they are the Contact Owner and if the user has the Edit Contacts You Do Not Own right, they will be able to delete Contacts they do not own.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931605, ''moveFoldersContacts'', ''Move Public Contacts to Private Folders'', ''cm'', ''admin'', 6, 1, ''Allows the user to move a Contact record from a Public folder to their own Personal/Private folder that no other user will have access to.<br>The user must be have the right to edit that Public folder as well as edit that Contact record. Refer to the How to User Folders document for more information on setting, granting access, and deleting folders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931606, ''foldersContacts'', ''Add/Edit/Delete Public Contact Folders'', ''cm'', ''admin'', 7, 1, ''This right determines whether or not a user can Add/Edit/Delete Public Folders for Contacts.  This right is only used if the Global Setting in the Transaction Preferences are checked for the Use Contact Folders.  If the user does not have the security rights to Add the Contact Folder, then they will not be able to edit or delete the folder regardless of this setting. Refer to the How to User Folders document for more information on setting, granting access, and deleting folders.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931607, ''mergeContacts'', ''Merge Contacts'', ''cm'', ''admin'', 8, 1, ''This right determines whether or not a user can Merge Contacts.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931608, ''viewContactCustomFields'', ''View Contact Custom Fields'', ''cm'', ''admin'', 9, 1, ''This right determines whether or not a user can view custom fields on a contact.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931700, ''useCompanies'', ''Use Companies'', ''cm'', ''admin'', 9, 1, ''This setting must be turned on for access to all other Companies security settings and allows access to Salesperson > Companies. Can only see folders assigned to themself, and the Companies contained in those folders where this user is the Company Owner, can also view Company Details windows for Company, Contact, Opportunities, Forms, History, (can add New Activity), Projects Estimates, Invoices, Receipts, Vendor Invoices and Payment. This setting also allows the user to open and Edit existing Company records, make a selection of Companies and Change multiple companies at once.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931701, ''viewOtherCompanies'', ''View Companies You Do Not Own'', ''cm'', ''admin'', 12, 1, ''Can see all Companies, whether the Company Owner or not.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931702, ''editOtherCompanies'', ''Edit Companies You Do Not Own'', ''cm'', ''admin'', 13, 1, ''Allows the ability to open and Edit existing Company Records. View Companies You Do Not Own must also be turned on. Edit limited to Details, Contacts and History.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931703, ''addCompanies'', ''Add new Companies'', ''cm'', ''admin'', 10, 1, ''Allows user to Add New Company records, but not the ability to Import Companies.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931704, ''deleteCompanies'', ''Delete Companies'', ''cm'', ''admin'', 11, 1, ''Allows the user to open and Delete Companies, also gives access to the Remove Duplicate Companies option (When given the right to View and Edit Companies You Do Not Own).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931705, ''foldersCompanies'', ''Add/Edit/Delete Company Folders'', ''cm'', ''admin'', 14, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931706, ''cm_editacctinfo'', ''Edit Client and Vendor Accounting Information'', ''cm'', ''admin'', 16, 1, ''This allows access to the Client and Vendor Setup tabs in Company records.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931707, ''mergeCompanies'', ''Merge Companies'', ''cm'', ''admin'', 15, 1, ''This right determines whether or not a user can Merge Companies.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931708, ''viewEINNumber'', ''View Company EIN Number'', ''cm'', ''admin'', 41, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931709, ''editEINNumber'', ''Edit Company EIN Number'', ''cm'', ''admin'', 42, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931710, ''viewCompanyCustomFields'', ''View Company Custom Fields'', ''cm'', ''admin'', 16, 1, ''This right determines whether or not a user can view custom fields on a company.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931400, ''useLeads'', ''Use Lead'', ''cm'', ''admin'', 17, 1, ''This setting must be turned on for access to all other Leads security settings and allows access to Salesperson > Leads. Can only see folders assigned to themself, and the Leads contained in those folders where this user is the Lead Owner, can also view History and add New Activity. This setting also allows the user to open and Edit existing Lead records, make a selection of Leads and Change multiple leads at once.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931401, ''viewOtherLeads'', ''View Leads You Do Not Own'', ''cm'', ''admin'', 18, 1, ''Can see all Leads, whether the Lead Owner or not.<br>This right determines whether or not a user can see Leads whos Lead Owner is someone other than the user. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931402, ''editOtherLeads'', ''Edit Leads You Do Not Own'', ''cm'', ''admin'', 19, 1, ''Allows the ability to open and Edit existing Leads. View Leads You Do Not Own must also be turned on.<br>This right determines whether or not a user can edit or delete Leads whos Lead Owner is someone other than the user. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931403, ''addLeads'', ''Add Leads'', ''cm'', ''admin'', 20, 1, ''Allows user to Add individual Leads records, but not the ability to Import Leads.<br>This right determines whether or not a user can create new Leads for themselves or another user. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931404, ''deleteLeads'', ''Delete Leads'', ''cm'', ''admin'', 22, 1, ''Allows the user to open and Delete Leads, also gives access to the Remove Duplicate Leads option (When given the right to View and Edit Leads You do Not Own).<br>This right determines whether or not a user can delete Leads for which they are the Lead Owner and if the user has the Edit Leads You Do Not Own right, they will be able to delete Leads they do not own. If Folders are being used, then Folder security will be checked prior to checking record level security.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931405, ''foldersLeads'', ''Add/Edit/Delete Lead Folders'', ''cm'', ''admin'', 23, 1, ''This right determines whether or not a user can Add/Edit /Delete Public Folders for Leads.  This right is only used if the Global Setting in the Transaction Preferences are checked for the Use Lead Folders.  If the user does not have the security rights to Add the Lead Folder, then they will not be able to edit or delete the folder regardless of this setting.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931406, ''mergeLeads'', ''Merge Leads'', ''cm'', ''admin'', 21, 1, ''This right determines whether or not a user can Merge Leads.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931100, ''useOpp'', ''Use Opportunities'', ''cm'', ''admin'', 24, 1, ''This setting must be turned on for access to all other Opportunities security settings and allows access to Salesperson > Opportunities. Can only see folders assigned to themself, and the Opportunities contained in those folders where this user is the Opportunity Owner, can also view options in Details windows for Opportunity, Company, Contacts, History (can add a New Activity). This setting also allows the user to open and Edit existing Opportunities, make a selection of Opportunities and Change multiple opportunities at once.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931101, ''viewOtherOpp'', ''View Opportunities You Do Not Own'', ''cm'', ''admin'', 27, 1, ''Can see all Opportunities, whether the Owner or not.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931102, ''editOtherOpp'', ''Edit Opportunities You Do Not Own'', ''cm'', ''admin'', 28, 1, ''Allows the ability to open and Edit existing Opportunities.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931103, ''addOpp'', ''Add New Opportunities'', ''cm'', ''admin'', 25, 1, ''Allows user to Add New Opportunities, but not the ability to Import.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931104, ''deleteOpp'', ''Delete Opportunities'', ''cm'', ''admin'', 26, 1, ''Allows the user to open and Delete Opportunities (When given the right to View and Edit Companies You Do Not Own).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931105, ''foldersOpp'', ''Add/Edit/Delete Opportunity Folders'', ''cm'', ''admin'', 29, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931106, ''deleteOpptyProject'', ''Delete Opportunity Projects'', ''cm'', ''admin'', 29, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931500, ''useActivities'', ''Use Activity Conversations'', ''cm'', ''admin'', 30, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931501, ''viewOtherActivities'', ''View Activity Conversations Not Assigned To You'', ''cm'', ''admin'', 33, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931507, ''editActivities'', ''Edit Activity Conversations'', ''cm'', ''admin'', 31, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931502, ''editOtherActivities'', ''Edit Activity Conversations Not Assigned To You'', ''cm'', ''admin'', 34, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931503, ''deleteActivities'', ''Delete Activity Conversations'', ''cm'', ''admin'', 32, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931504, ''foldersActivities'', ''Add/Edit/Delete Public Activity Conversation Folders'', ''cm'', ''admin'', 35, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931505, ''moveFoldersActivities'', ''Move Public Activity Conversations to Private Folders'', ''cm'', ''admin'', 36, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931506, ''activityAllwaysCheckOpp'', ''Always Check for Opportunities on Activity Conversations'', ''cm'', ''admin'', 37, 1, '''')


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (931550, ''useMarketingLists'', ''Use Marketing Lists'', ''cm'', ''admin'', 38, 1, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930800, ''cm_viewclientlist'', ''View the client list'', ''cm'', ''admin'', 39, 1, ''Allows access to Menu > Billing > Clients to view the list of Clients.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (930900, ''cm_viewvendorlist'', ''View the vendor list'', ''cm'', ''admin'', 40, 1, ''Edit Accounting Information is required in order to view the Vendor Setup tab in the Company Record; this also makes Menu > Purchasing > Vendors available to view the list of Vendors.'')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940100, ''gl_glaccount'', ''Maintain GL Accounts'', ''acct'', ''admin'', 1, 1, ''Also need to System Administration  > Maintain Setup Information > Edit GL Settings. This allows complete access to System Setup > GL Accounts > GL Accounts, Control Accounts, GL Tracking Options, and Check Formats. This down allow access to the Accounting Module.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940200, ''gl_journalentry'', ''Enter Journal Entries'', ''acct'', ''admin'', 2, 0, ''Add/edit/delete Journal Entries. User can also view General Ledger Transactions.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940221, ''gl_view_journalentry'', ''View Journal Entries'', ''acct'', ''admin'', 5, 0, ''Allows the user to view Journal Entries. User can also view General Ledger Transactions.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940300, ''gl_budget'', ''Enter GL Budgets'', ''acct'', ''admin'', 3, 0, ''Allows the user to create and edit Financial Budgets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940321, ''gl_forecast'', ''Edit / View Revenue Forecasts'', ''acct'', ''admin'', 12, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940320, ''gl_view_forecast_others'', ''---- View Revenue Forecasts from other AEs'', ''acct'', ''admin'', 13, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940330, ''gl_currencyrates'', ''Maintain Currency Exchange Rates'', ''acct'', ''admin'', 13, 0, '''')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940400, ''gl_accountrecs'', ''Reconcile GL Accounts'', ''acct'', ''admin'', 7, 0, ''Allows full access to setup GL Account Reconciliation.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940445, ''gl_postvoucher'', ''Post Voucher to the General Ledger'', ''acct'', ''admin'', 9, 0, ''Allows user access to the Post Transactions screen, and to post Vouchers, and to run the Missing Transactions and Preposting reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940446, ''gl_postpayment'', ''Post Payment to the General Ledger'', ''acct'', ''admin'', 9, 0, ''Allows user access to the Post Transactions screen, and to post Payments, and to run the Missing Transactions and Preposting reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940447, ''gl_postclientinvoice'', ''Post Client Invoice to the General Ledger'', ''acct'', ''admin'', 9, 0, ''Allows user access to the Post Transactions screen, and to post Client Invoices, and to run the Missing Transactions and Preposting reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940448, ''gl_postreceipt'', ''Post Receipt to the General Ledger'', ''acct'', ''admin'', 9, 0, ''Allows user access to the Post Transactions screen, and to post Receipts, and to run the Missing Transactions and Preposting reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940449, ''gl_postjournalentry'', ''Post Journal Entry to the General Ledger'', ''acct'', ''admin'', 9, 0, ''Allows user access to the Post Transactions screen, and to post Journal Entries, and to run the Missing Transactions and Preposting reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940450, ''gl_postcreditcard'', ''Post Credit Card Transaction to the General Ledger'', ''acct'', ''admin'', 9, 0, ''Allows user access to the Post Transactions screen, and to post Credit Card Transactions, and to run the Missing Transactions and Preposting reports.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940455, ''gl_unpost'', ''Unpost Transaction to the General Ledger'', ''acct'', ''admin'', 10, 0, ''Allows user to the Unpost Transactions.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940460, ''gl_approvejournalentry'', ''Approve Journal Entries'', ''acct'', ''admin'', 11, 0, ''Allows user access to the approve Journal Entries.  Only applies if have preference turned on.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940500, ''gl_postwip'', ''Post WIP to GL'', ''acct'', ''admin'', 8, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940600, ''laborbud_edit'', ''Edit Labor Budgets'', ''acct'', ''admin'', 4, 1, ''Allow the user to create Labor Budgets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940610, ''laborbud_viewanyoffice'', ''---- Edit / View labor budgets for any office'', ''acct'', ''admin'', 5, 1, ''Access to labor budgets for staff assigned to any office.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940620, ''laborbud_viewanydept'', ''---- Edit / View labor budgets for any department'', ''acct'', ''admin'', 6, 1, ''Access to labor budgets for staff assigned to any department.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940630, ''chargesum_viewanyperson'', ''---- View any or all people on billable summary'', ''acct'', ''admin'', 7, 1, ''View Billable Summary in Hours and Dollars. You must have access to View the reports menu, -- View Project Financial Reports.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (940700, ''accteditanytime'', ''Edit transactions after submission/approval'', ''acct'', ''admin'', 11, 1, ''The right to unapprove and edit any transaction after approval.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950000, ''acct_ap_aging'', ''AP Account Aging'', ''reports'', ''admin'', 5010, 0, ''Shows all accounts payable aging with amount open and days old.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950001, ''acct_ap_listing'', ''AP Listing'', ''reports'', ''admin'', 5020, 1, ''Vendor Invoice Detail list shows all vendor invoice lines with expense account, project number and tasks.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950002, ''acct_ap_1099'', ''1099 Vendor Detail'', ''reports'', ''admin'', 5050, 1, ''Allows access to the following:<br>1099 (Misc/Form): prints 1099 (Misc/Int) Form matching the Federal form format.<br>1099 Vendor Detail: shows 1099 vendor detail information including a grand total for the report.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950003, ''acct_po_listing'', ''Purchase Order Listing'', ''reports'', ''admin'', 5060, 1, ''Shows order information grouped by vendors.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950004, ''acct_po_project'', ''Project PO Listing'', ''reports'', ''admin'', 5070, 1, ''Purchase Order By Projects shows order information grouped by vendors.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950005, ''acct_ap_checks'', ''Payment Listing'', ''reports'', ''admin'', 5080, 0, ''Check Listing shows all payment within a date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950006, ''acct_ar_invoicesummary'', ''Invoice Summary'', ''reports'', ''admin'', 4050, 1, ''Shows all invoices with totals, sales tax, gross labor and net expenses grouped by client.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950007, ''acct_ar_invoicelineitemsummary'', ''Invoice Line Item Summary'', ''reports'', ''admin'', 4060, 1, ''Shows all invoices with project number, subject, line total, gross labor and net expenses grouped by client.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950120, ''acct_projectprofit'', ''Project Profitability'', ''reports'', ''admin'', 7128, 0, ''The following reports are available when this is selected:<br>Project Profit and Loss (Detail View): shows profitability for a specific Project with breakdowns by GL Account and may include Overhead Allocation.<br>Project Profit and Loss (Multi View): shows profitability across multiple projects with ability to allocate overhead from the GL.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (400300, ''acct_projectwip'', ''Project WIP Analysis'', ''reports'', ''admin'', 2129, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950008, ''acct_gl_trailbal'', ''Trial Balance'', ''reports'', ''admin'', 7130, 0, ''Shows GL account balances with debits and credits.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950009, ''acct_gl_genledger'', ''General Ledger'', ''reports'', ''admin'', 7140, 0, ''Shows GL account activity by date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950010, ''acct_gl_genjournal'', ''General Journal'', ''reports'', ''admin'', 7150, 0, ''Shows journal entry transactions by date range.'')

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950011, ''acct_gl_pl_ytd'', ''Income Statement Corporate'', ''reports'', ''admin'', 7160, 0, ''The following report is available when this is selected:<br>Corporate Profit and Loss: Shows income statement for the company and/or GL Company, Office, GL Class and Department level.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950050, ''acct_client_gl_pl_ytd'', ''Income Statement Client'', ''reports'', ''admin'', 7165, 0, ''The following reports are available when this is selected:<br>Client Profit and Loss (Detail View): shows profitability for a specific client with breakdowns by GL Account or Project Type.<br>Client Profit and Loss (Multi View): shows profitability across multiple clients with ability to allocate overhead from the GL.'')


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950012, ''acct_gl_balsheet'', ''Balance Sheet'', ''reports'', ''admin'', 7170, 0, ''Shows assets, liabilities and equity balances as of a specified date.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950013, ''acct_ap_purchjournal'', ''Purchase Journal'', ''reports'', ''admin'', 5030, 0, ''Shows sub-ledger report of vendor invoices by date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950014, ''acct_ap_payjournal'', ''Cash Disbursements Journal'', ''reports'', ''admin'', 5040, 0, ''Shows sub-ledger report of payments by date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950015, ''acct_ar_salesjournal'', ''Sales Journal'', ''reports'', ''admin'', 4020, 1, ''Shows sales activity by client and posting date.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950016, ''acct_ar_cashjournal'', ''Cash Receipts Journal'', ''reports'', ''admin'', 4030, 1, ''Shows receipts received by client and posting date.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950020, ''acct_ar_statement'', ''Client Statements'', ''reports'', ''admin'', 4040, 1, ''Shows client transactions including amount billed, receipts, amount open and aging information.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950025, ''acct_inv_backup'', ''Invoice Backup'', ''reports'', ''admin'', 4045, 1, ''Shows the details of client invoices with actual labor, expenses and totals.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950030, ''acct_gl_excel'', ''Access Financials from Excel'', ''reports'', ''admin'', 7180, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950040, ''acct_ap_accruedorder'', ''AP Accrued Order Detail Report'', ''reports'', ''admin'', 5075, 0, ''Show all Orders with accrued balance as a result of Prebilling.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950045, ''acct_ap_exceptions'', ''AP Exceptions Report'', ''reports'', ''admin'', 5015, 1, ''Shows vendor invoices where there is a variance from the related PO amount.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950110, ''acct_salestaxanalysis'', ''Sales Tax Analysis Report'', ''reports'', ''admin'', 4070, 0, ''Shows taxable sales, tax amounts paid and collected, grouped by sales tax rate code.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950121, ''acct_projectrealization'', ''Project Hourly Realization Rate'', ''reports'', ''admin'', 2016, 1, ''Shows actual hourly rate earned on projects.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950130, ''acct_gl_statement_cashflow'', ''Statement of Cash Flows'', ''reports'', ''admin'', 7180, 0, ''Shows cash flow of company operating and investing activities by date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950135, ''acct_gl_cashprojection'', ''Cash Projection'', ''reports'', ''admin'', 7185, 0, ''Drill Down: Shows beginning and ending balances for AR, AP, Bank Accounts and projected balance for specified date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950136, ''acct_gl_uncleared'', ''Uncleared Transactions'', ''reports'', ''admin'', 7186, 0, ''Shows uncleared transactions for specified GL Account.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950137, ''rptOverheadAllocationDetail'', ''Overhead Allocation Details'', ''reports'', ''admin'', 7187, 0, ''Shows the transaction details that make up the overhead allocation total when running the Client P&L or Project P&L reports over the same date range.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (950140, ''acct_metrics'', ''Metrics Monitor'', ''reports'', ''admin'', 7190, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960000, ''pr_viewrequests'', ''View Project Requests'', ''requests'', ''admin'', 1, 1, ''User can view project requests and linked spec sheets. This also allows the user to Cancel Request, which will cancel an approval and change the request status to Not Sent For Approval. This setting also allows the user to Add Attachments.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960010, ''pr_addrequests'', ''Add New Requests to the system'', ''requests'', ''admin'', 2, 1, ''Allows user to create new project requests, only if they belong in the Selected Security Groups defined in the project request form at the system setup level.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960020, ''pr_editrequests'', ''Edit Existing Requests'', ''requests'', ''admin'', 3, 1, ''Allows user to make and Save changes to existing project requests and linked spec sheets.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960030, ''pr_deleterequests'', ''Delete Existing Requests'', ''requests'', ''admin'', 4, 1, ''[Delete] button is now present.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960040, ''pr_editapproval'', ''Edit the approval process'', ''requests'', ''admin'', 5, 1, ''[Approval Process] is now present in existing project requests allowing the user to add/edit/delete approval steps and change the order of defined approval steps.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960050, ''proj_projectassignments'', ''Assigned Tasks'', ''reports'', ''admin'', 3150, 1, ''Project Tasks. Shows all tasks by project.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960051, ''admin_employeehours'', ''Employee Actual Hours Report'', ''reports'', ''admin'', 2017, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960052, ''acct_gl_mc_realized'', ''Multicurrency Realized Gains and Losses'', ''reports'', ''admin'', 7191, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960053, ''acct_gl_mc_unrealized'', ''Multicurrency Unrealized Gains and Losses'', ''reports'', ''admin'', 7192, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (960054, ''acct_view_scheduledreports'', ''View Scheduled Transactions'', ''acct'', ''admin'', 7193, 1, '''')




INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90000001, ''cbeditbatch'', ''Edit Charge Back Batches'', ''billing'', ''ChargeCodes'', 1, 0, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (90000002, ''billingenterlabornet'', ''Enter Net Rate in Project Time and Material Billing'', ''billing'', ''billlabornet'', 1, 1, ''This right allows users to bill at a net cost different than the one on time entries on the Time and Material project billing for things like overtime.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (91000000, ''muddAMRpt'', ''AGI By Account Manager Report'', ''reports'', ''mudd'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (91000001, ''muddSMRpt'', ''AGI By Sales Manager'', ''reports'', ''mudd'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (91000002, ''muddAMClientRpt'', ''AGI By Account Manager or Client'', ''reports'', ''mudd'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (92000000, ''partnersnapierMonthyActualHours'', ''Retainer Monthly Actual Hours'', ''reports'', ''partnersnapier'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (92000001, ''partnersnapierMonthyActualHrsBudget'', ''Retainer Monthly Actual Hours with Budget'', ''reports'', ''partnersnapier'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (92000002, ''partnersnapierSalesJournal'', ''Custom Sales Journal'', ''reports'', ''partnersnapier'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (93000001, ''cbreSBRpt'', ''Custom Split Billing Invoice'', ''reports'', ''cbre'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (94000001, ''pyramidLaborRpt'', ''Custom Project Labor Analysis'', ''reports'', ''pyramid'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (95000001, ''hmiProjectResourceUtilization'', ''Custom Project Resource Utilization'', ''reports'', ''hmi'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (95000002, ''abelsonProjectResourceUtilization'', ''Custom Project Resource Utilization'', ''reports'', ''abelson'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (96000001, ''bgbBillableHours'', ''Project Billable Hours Summary'', ''reports'', ''bgb'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (97000001, ''bgbProjectReconciliationSummary'', ''Project Reconciliation Summary'', ''reports'', ''bgb'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (98000000, ''boyScoutExport'', ''Project Data Export'', ''reports'', ''boyscouts'', 999, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99000001, ''brittonTrafficRpt'', ''Custom Time Detail Data'', ''reports'', ''britton'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99100001, ''concentricChargeabilityRpt'', ''Custom Utilization Report'', ''reports'', ''concentric'', 1, 1, '''')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99100002, ''concentricClientPLRpt'', ''Custom Client PL Report'', ''reports'', ''concentric'', 1, 1, '''')
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99100003, ''concentricDeptPLRpt'', ''Custom Dept PL Report'', ''reports'', ''concentric'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99200001, ''jplChargeabilitySummary'', ''Custom Chargeability Summary'', ''reports'', ''jplcharge'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99300001, ''farmPostageAvailableReport'', ''Custom Postage Available Report'', ''reports'', ''farmPostage'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99400001, ''barbGroupCustomization'', ''Custom Barbarian Group Report'', ''reports'', ''barbGroup'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (99500001, ''questvouchersrpt'', ''Custom Quest Vendor Invoice Report'', ''reports'', ''questvouchersrpt'', 1, 1, '''')





INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500110, ''client_prjAccessAny'', ''Access all projects for client'', ''client'', ''client'', 1, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500100, ''client_calendar'', ''View the calendar'', ''client'', ''client'', 3, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500200, ''client_approvals'', ''View the approvals page (Legacy)'', ''clientLegacy'', ''client'', 4, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500300, ''client_schedule'', ''View the project schedule (Legacy)'', ''clientLegacy'', ''client'', 5, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500400, ''client_hours'', ''View hours on project budget (Legacy)'', ''clientLegacy'', ''client'', 9, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500500, ''client_budget'', ''View project budget page (Legacy)'', ''clientLegacy'', ''client'', 7, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500550, ''client_viewbudget'', ''View the project budget (Legacy)'', ''clientLegacy'', ''client'', 8, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500600, ''client_budgetdetail'', ''Drill down on budget transactions details (Legacy)'', ''clientLegacy'', ''client'', 10, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500650, ''client_budgetactuals'', ''View actuals on a project budget (Legacy)'', ''clientLegacy'', ''client'', 11, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500651, ''client_budgetactual_dollars'', ''View actual dollars on a project budget (Legacy)'', ''clientLegacy'', ''client'', 12, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500652, ''client_budgetactual_hours'', ''View actual hours on a project budget (Legacy)'', ''clientLegacy'', ''client'', 13, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500700, ''client_invoices'', ''View current invoices (Legacy)'', ''clientLegacy'', ''client'', 14, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500750, ''client_invoicespast'', ''View closed invoices (Legacy)'', ''clientLegacy'', ''client'', 15, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500775, ''client_invoicesassigned'', ''View Invoices for assigned projects (Legacy)'', ''clientLegacy'', ''client'', 16, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (500800, ''client_originalschedule'', ''View the original schedule (Legacy)'', ''clientLegacy'', ''client'', 6, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501100, ''client_prview'', ''Client can view Project Requests'', ''client'', ''client'', 17, 1, ''User can view project requests and linked spec sheets. This also allows the user to Cancel Request, which will cancel an approval and change the request status to Not Sent For Approval. This setting also allows the user to Add Attachment(s).'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501200, ''client_pradd'', ''Add New Project Requests'', ''client'', ''client'', 18, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501401, ''client_prdeleteown'', ''Delete Project Requests'', ''client'', ''client'', 19, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501300, ''client_predit'', ''Edit Project Requests from their company'', ''client'', ''client'', 20, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501400, ''client_prdelete'', ''Can delete requests from their company'', ''client'', ''client'', 21, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501450, ''client_praddnewspec'', ''Can add and delete spec sheets on project requests'', ''client'', ''client'', 27, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501500, ''client_dafiles'', ''Can View Digital Asset Files (Legacy)'', ''clientLegacy'', ''client'', 22, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501550, ''client_dafilesupload'', ''Can Upload Digital Asset Files (Legacy)'', ''clientLegacy'', ''client'', 23, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501600, ''client_projectlist'', ''View the list of assigned projects (Legacy)'', ''clientLegacy'', ''client'', 2, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501700, ''client_notes'', ''Add to the Project Diary (Legacy)'', ''clientLegacy'', ''client'', 24, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501710, ''client_editNotes'', ''Edit Diary Notes (Legacy)'', ''clientLegacy'', ''client'', 25, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501800, ''client_myinfo'', ''Change MyInfo data and password (Legacy)'', ''clientLegacy'', ''client'', 26, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501801, ''client_assignments'', ''View Assigned Tasks (Legacy)'', ''clientLegacy'', ''client'', 28, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501810, ''client_daviewprior'', ''Can view prior digital art reviews (Legacy)'', ''clientLegacy'', ''client'', 29, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501820, ''client_viewinvoicecompany'', ''View Invoices for Company (Legacy)'', ''clientLegacy'', ''client'', 30, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501830, ''client_viewinvoiceparentcompany'', ''View Invoices for Parent Company (Legacy)'', ''clientLegacy'', ''client'', 31, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501835, ''client_viewinvoicechildcompany'', ''View Invoices for Child Company (Legacy)'', ''clientLegacy'', ''client'', 32, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501840, ''client_projectdescription'', ''View the Project Description'', ''client'', ''client'', 33, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501850, ''client_projectteam'', ''View the Project Team (Legacy)'', ''clientLegacy'', ''client'', 34, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501860, ''client_creativebrief'', ''View the Project Creative Brief (Legacy)'', ''clientLegacy'', ''client'', 35, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501870, ''client_projectspecs'', ''View the Project Specifications (Legacy)'', ''clientLegacy'', ''client'', 36, 1, ''View only access to any attached spec sheet.'')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501880, ''client_editprojectspecs'', ''Edit the Project Specifications'', ''client'', ''client'', 37, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501890, ''client_viewprojectmisccost'', ''View the Project Misc Cost (Legacy)'', ''clientLegacy'', ''client'', 38, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501895, ''client_editconversations'', ''Use Project Request and Change Request Conversations'', ''client'', ''client'', 39, 1, '''')

if @LoadBeta = 1
BEGIN
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501900, ''client_crview'', ''Client Can View Project Change Request Forms'', ''client'', ''client'', 38, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501910, ''client_cradd'', ''Add New Project Change Request Forms'', ''client'', ''client'', 39, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501920, ''client_credit'', ''Edit Project Change Request Forms For Their Company'', ''client'', ''client'', 40, 1, '''')
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM, Hint) Values (501930, ''client_crdelete'', ''Can Delete Project Change Request Forms For Their Company'', ''client'', ''client'', 41, 1, '''')
END


-- 688217 (GAR) - Deleting the tWidget insert statements because the table definition changed.  We will add these back in once we have the new table set and widgets defined.
--DELETE tWidget Where CompanyKey is null

--INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (1, NULL, ''RSS Reader'', ''RSS Reader'', ''main'', 0, ''OtherRSSReader.swf'', ''widgetOther'', ''<settings><Title>RSS READER</Title><rssUrl>http://www.groupamajig.com/forum/feed.php</rssUrl></settings>'', 1, 1, 400, 400, 1, GETDATE())

-- 688217 (GAR) - Adding the new widget definitions here for the new project dashboards.
DELETE tWidgetDef
DELETE tWidgetEntity
DELETE tWidgetEntityAssigned


INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (1, NULL, N''OppByStage'', N''By Stage'', NULL, NULL, 0, 0, 1, 1, 1, N''HTML2'', N''loadOppByStage'', N''!System.session.salesDashboard.OppByStage'', N''dashboards.widgets.sales.oppByStage'', N''OppByStage'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (2, NULL, N''OppByWWP'', N''By WWP Level'', NULL, NULL, 0, 0, 1, 1, 1, N''HTML2'', N''loadOppByWWP'', N''!System.session.salesDashboard.OppByWWP'', N''dashboards.widgets.sales.oppByWWP'', N''OppByWWP'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (3, NULL, N''FavoriteUsers'', N''Twitter Feeds'', NULL, NULL, 0, 0, 1, 1, 1, N''HTML2'', N''loadFavoriteUsers'', N''!System.session.salesDashboard.OppTwitter'', N''dashboards.widgets.sales.twitter'', N''Twitter'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (4, NULL, N''FavoriteOpps'', N''Favorite Opportunities'', NULL, NULL, 0, 0, 1, 1, 1, N''HTML2'', N''loadFavoriteOpps'', N''!System.session.salesDashboard.Weighted'', N''dashboards.widgets.sales.favoriteOpps'', N''FavoriteOpps'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (5, NULL, N''NeglectedOpps'', N''Neglected Opportunities'', NULL, NULL, 0, 0, 1, 1, 1, N''HTML2'', N''loadNeglectedOpps'', N''!System.session.salesDashboard.NeglectedOpps'', N''dashboards.widgets.sales.neglectedOpps'', N''NeglectedOpps'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (6, NULL, N''SalesTarget'', N''Sales Target'', NULL, NULL, 0, 0, 1, 1, 1, N''HTML2'', N''loadSalesTarget'', N''!System.session.salesDashboard.SalesTarget'', N''dashboards.widgets.sales.salesTarget'', N''SalesTarget'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (7, NULL, N''ProjectChangeRequests'', N''Change Requests'', N''View a list of the current change requests on a project. You must have the right "View Project Change Request Forms" to see any request forms in this widget.'', NULL, 2, 3, 3, 3, 1, N''HTML2'', N''loadProjectChangeRequests'', NULL, N''dashboards.widgets.projects.projectChangeRequests'', N''ProjectChangeRequests'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (8, NULL, N''ProjectContactInfo'', N''Contact Info'', N''This shows information about the primary contact on the project as well as the project manager and billing manager.'', NULL, 0, 4, 2, 2, 1, N''HTML2'', N''loadProjectContactInfo'', NULL, N''dashboards.widgets.projects.projectContactInfo'', N''ProjectContactInfo'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class])
VALUES (9, NULL, N''ProjectCustomFields'', N''Custom Fields'', N''This shows the values of the custom fields on the project. You must have right to Maintain Project Setup in order to edit these values.'', NULL, 8, 3, 3, 3, 1, N''HTML2'', N''loadProjectCustomFields'', NULL, N''dashboards.widgets.projects.projectCustomFields'', N''ProjectCustomFields'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (10, NULL, N''ProjectDailyFeed'', N''Daily Feed'', N''Shows a list of all the current actions on a project. There are options to limit what kind of actions show up in the list.'', NULL, 2, 0, 3, 3, 1, N''HTML2'', N''loadProjectDailyFeed'', NULL, N''dashboards.widgets.projects.projectDailyFeed'', N''ProjectDailyFeed'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (11, NULL, N''ProjectDeliverables'', N''Deliverables'', N''Shows a list of all the deliverables added to the project. You must have the right View Deliverables in order to see any contents in this widget.'', NULL, 8, 0, 3, 3, 1, N''HTML2'', N''loadProjectDeliverables'', NULL, N''dashboards.widgets.projects.projectDeliverables'', N''ProjectDeliverables'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (12, NULL, N''ProjectDetails'', N''Project Details'', N''This shows the current status and other high level settings for a project. '', NULL, 0, 2, 2, 2, 1, N''HTML2'', N''loadProjectDetails'', NULL, N''dashboards.widgets.projects.projectDetails'', N''ProjectDetails'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (13, NULL, N''ProjectMenu'', N''Menu'', N''This shows the main jump menu for a project so that you can access all the different areas on a project. '', NULL, 0, 6, 2, 3, 1, N''HTML2'', N''loadProjectMenu'', NULL, N''dashboards.widgets.projects.projectMenu'', N''ProjectMenu'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (14, NULL, N''ProjectProfitability'', N''Project Profitability'', N''This widget shows a summary of the profitability of a project. These numbers are based on values posted to the general ledger. This is more sensitive information, so be careful which security groups you allow to see this widget.'', NULL, 0, 1, 5, 5, 1, N''HTML2'', N''loadProjectProfitability'', NULL, N''dashboards.widgets.projects.projectProfitability'', N''ProjectProfitability'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (15, NULL, N''ProjectRecentConversations'', N''Recent Conversations'', N''Shows a list of all the conversations that have been going on in the system. You must have the right to Access Project Conversations to see any details in this widget.'', NULL, 5, 3, 3, 3, 1, N''HTML2'', NULL, N''!System.session.salesDashboard.OppTwitter'', N''dashboards.widgets.projects.projectRecentConversations'', N''ProjectRecentConversations'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (16, NULL, N''ProjectSetup'', N''Setup'', N''This widget shows jump links to the different areas of project setup such as Schedule, Estimates, Project Setup and the Team.'', NULL, 0, 0, 2, 2, 1, N''HTML2'', N''loadProjectSetup'', NULL, N''dashboards.widgets.projects.projectSetup'', N''ProjectSetup'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (17, NULL, N''ProjectSnapshot'', N''Project Snapshot'', N''This widget shows a summary of transactions and budget of a project. These numbers are based on activity in the system and does not necessarily correspond to the ledger. This is more sensitive information, so be careful which security groups you allow to see this widget.'', NULL, 0, 4, 3, 4, 1, N''HTML2'', N''loadProjectSnapshot'', NULL, N''dashboards.widgets.projects.projectSnapshot'', N''ProjectSnapshot'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (18, NULL, N''ProjectSpecSheets'', N''Spec Sheets'', N''This widget shows a list of all of the spec sheets currently on the project. You need to have the right to View the Project Specifications to see any details in this widget.'', NULL, 5, 0, 3, 3, 1, N''HTML2'', N''loadProjectSpecSheets'', NULL, N''dashboards.widgets.projects.projectSpecSheets'', N''ProjectSpecSheets'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (19, NULL, N''ProjectTeam'', N''Team'', N''This widget shows a list of all the current team members, their contact information as well as the services that they have been assigned to handle on this project.'', NULL, 2, 6, 3, 3, 1, N''HTML2'', N''loadProjectTeam'', NULL, N''dashboards.widgets.projects.projectTeam'', N''ProjectTeam'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (20, NULL, N''DailyFeed'', N''Daily Feed'', N''Shows a list of all the current actions on a project. There are options to limit what kind of actions show up in the list.'', NULL, 1, 1, 3, 3, 1, N''HTML2'', N''loadDailyFeed'', NULL, N''dashboards.widgets.today.dailyFeed'', N''DailyFeed'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (21, NULL, N''Conversations'', N''Conversations'', N''Shows a list of recent converations.'', NULL, 1, 1, 3, 3, 1, N''HTML2'', N''loadConversations'', NULL, N''dashboards.widgets.today.conversations'', N''Conversations'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (22, NULL, N''NeglectedOpportunities'', N''Neglected Opportunities'', N''Shows a list of neglected opportunities.'', NULL, 1, 1, 3, 2, 1, N''HTML2'', N''loadNeglectedOpportunities'', NULL, N''dashboards.widgets.today.neglectedOpportunities'', N''NeglectedOpportunities'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (23, NULL, N''FavoriteOpportunities'', N''Favorite Opportunities'', N''Shows a list of favorite opportunities.'', NULL, 1, 1, 3, 3, 1, N''HTML2'', N''loadFavoriteOpportunities'', NULL, N''dashboards.widgets.today.favoriteOpportunities'', N''FavoriteOpportunities'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (24, NULL, N''TwitterFeeds'', N''Twitter Feeds'', N''Shows a list of twitter feeds from your favorite contacts.'', NULL, 1, 1, 3, 2, 1, N''HTML2'', N''loadTwitterFeeds'', NULL, N''dashboards.widgets.today.twitterFeeds'', N''TwitterFeeds'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (25, NULL, N''ProjectOpenItems'', N''Project Open Items'', N''Shows your open items for projects.'', NULL, 1, 1, 3, 3, 1, N''HTML2'', N''loadProjectOpenItems'', NULL, N''dashboards.widgets.today.projectOpenItems'', N''ProjectOpenItems'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (26, NULL, N''ProjectItemsNeedingAttention'', N''Project Items Needing Attention'', N''Shows all of your items needing attention for projects.'', NULL, 1, 1, 3, 3, 1, N''HTML2'', N''loadProjectItemsNeedingAttention'', NULL, N''dashboards.widgets.today.projectItemsNeedingAttention'', N''ProjectItemsNeedingAttention'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (27, NULL, N''BillingWorksheets'', N''Billing Worksheets'', N''Shows all billing worksheets.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingWorksheets'', NULL, N''dashboards.widgets.today.billingWorksheets'', N''BillingWorksheets'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (28, NULL, N''BillingToBillAsOf'', N''Billing To Bill As Of'', N''Shows items to bill as of a selected date.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingToBillAsOf'', NULL, N''dashboards.widgets.today.billingToBillAsOf'', N''BillingToBillAsOf'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (29, NULL, N''BillingInvoices'', N''Billing Invoices'', N''Shows all invoices.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingInvoices'', NULL, N''dashboards.widgets.today.billingInvoices'', N''BillingInvoices'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (30, NULL, N''PurchasingOpenItems'', N''Purchasing Open Items'', N''Shows open items for purchasing.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadPurchasingOpenItems'', NULL, N''dashboards.widgets.today.purchasingOpenItems'', N''PurchasingOpenItems'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (31, NULL, N''PurchasingIncomingCharges'', N''Purchasing Incoming Charges'', N''Shows incoming charges for purchasing.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadPurchasingIncomingCharges'', NULL, N''dashboards.widgets.today.purchasingIncomingCharges'', N''PurchasingIncomingCharges'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (32, NULL, N''PurchasingInvoices'', N''Purchasing Invoices'', N''Shows invoices for purchasing.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadPurchasingInvoices'', NULL, N''dashboards.widgets.today.purchasingInvoices'', N''PurchasingInvoices'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (33, NULL, N''PurchasingToPayAsOf'', N''Purchasing To Pay As Of'', N''Shows to pay as of items for purchasing.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadPurchasingToPayAsOf'', NULL, N''dashboards.widgets.today.purchasingToPayAsOf'', N''PurchasingToPayAsOf'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (34, NULL, N''PurchasingPayments'', N''Purchasing Payments'', N''Shows payment items for purchasing.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadPurchasingPayments'', NULL, N''dashboards.widgets.today.purchasingPayments'', N''PurchasingPayments'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (35, NULL, N''MediaOpenItems'', N''Media Open Items'', N''Shows open items for media.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadMediaOpenItems'', NULL, N''dashboards.widgets.today.mediaOpenItems'', N''MediaOpenItems'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (36, NULL, N''MediaOrdersNeedingAttention'', N''Media Orders Needing Attention'', N''Shows any media orders needing attention.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadMediaOrdersNeedingAttention'', NULL, N''dashboards.widgets.today.mediaOrdersNeedingAttention'', N''MediaOrdersNeedingAttention'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (37, NULL, N''AccountingItemsNeedingAttention'', N''Accounting Items Needing Attention'', N''Shows items needing attention for accounting.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadAccountingItemsNeedingAttention'', NULL, N''dashboards.widgets.today.accountingItemsNeedingAttention'', N''AccountingItemsNeedingAttention'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (38, NULL, N''AccountingAccountBalances'', N''Accounting Account Balances'', N''Shows your account balances.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadAccountingAccountBalances'', NULL, N''dashboards.widgets.today.accountingAccountBalances'', N''AccountingAccountBalances'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (40, NULL, N''Schedule'', N''Schedule'', N''Shows your upcoming schedule.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadSchedule'', NULL, N''dashboards.widgets.today.schedule'', N''Schedule'')

--INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
--VALUES (41, NULL, N''ProjectFiles'', N''Files'', N''This widget shows a list of all files stored in this project.'', NULL, 2, 6, 6, 3, 1, N''HTML2'', N''loadProjectFiles'', NULL, N''dashboards.widgets.projects.projectFiles'', N''ProjectFiles'')


-- ******************************* Project Dashboard Graphs -----------------------------------------
INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (60, NULL, N''ProjectRequestCounts'', N''Project Request Counts'', N''Shows metrics related to project requests.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadProjectRequestCounts'', NULL, N''dashboards.widgets.today.projectRequestCounts'', N''ProjectRequestCounts'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (61, NULL, N''ProjectSummary'', N''Project Summary'', N''Shows metrics related to projects like new, total, active, completed, and on time status.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadProjectSummary'', NULL, N''dashboards.widgets.today.projectSummary'', N''ProjectSummary'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (62, NULL, N''CompletedProjectByProjectType'', N''Completed Project by Project Type'', N''Shows Project Type Name and number of projects completed with the date range. Sorted by highest number of projects completed first.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadCompletedProjectByProjectType'', NULL, N''dashboards.widgets.today.completedProjectByProjectType'', N''CompletedProjectByProjectType'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (63, NULL, N''HoursByProjectType'', N''Hours by Project Type'', N''Shows Project Type Name and hours worked. Sorts by highest number of hours first.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadHoursByProjectType'', NULL, N''dashboards.widgets.today.hoursByProjectType'', N''HoursByProjectType'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (64, NULL, N''HoursByClient'', N''Hours by Client'', N''Shows client and hours worked. Sorts by highest number of hours first.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadHoursByClient'', NULL, N''dashboards.widgets.today.hoursByClient'', N''HoursByClient'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (65, NULL, N''HoursByDivision'', N''Hours by Division'', N''Shows division and hours worked. Sorts by highest number of hours first.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadHoursByDivision'', NULL, N''dashboards.widgets.today.hoursByDivision'', N''HoursByDivision'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (66, NULL, N''BillingsByClient'', N''Billings by Client'', N''Shows Client Name and total billed amount (within date range by invoice date). Client comes from the invoice. Sorts by highest number of hours first.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingsByClient'', NULL, N''dashboards.widgets.today.billingsByClient'', N''BillingsByClient'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (67, NULL, N''CompletedProjectDetails'', N''Completed Project Details'', N''Shows projects that have been completed and details about those.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadCompletedProjectDetails'', NULL, N''dashboards.widgets.today.completedProjectDetails'', N''CompletedProjectDetails'')
-- /////////////////////******************************* Project Dashboard Graphs -----------------------------------------

-- ******************************* Sales Dashboard Graphs -----------------------------------------
INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (70, NULL, N''SalesByStage'', N''Sales By Stage'', N''Shows metrics related to sales by stage.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadSalesByStage'', NULL, N''dashboards.widgets.today.salesByStage'', N''SalesByStage'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (71, NULL, N''SalesThisMonth'', N''Sales This Month'', N''Shows metrics related to sales this month.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadSalesThisMonth'', NULL, N''dashboards.widgets.today.salesThisMonth'', N''SalesThisMonth'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (72, NULL, N''SalesThisQuarter'', N''Sales This Quarter'', N''Shows metrics related to sales this quarter.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadSalesThisQuarter'', NULL, N''dashboards.widgets.today.salesThisQuarter'', N''SalesThisQuarter'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (73, NULL, N''SalesThisYear'', N''Sales This Year'', N''Shows metrics related to sales this year.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadSalesThisYear'', NULL, N''dashboards.widgets.today.salesThisYear'', N''SalesThisYear'')

-- /////////////////////******************************* Sales Dashboard Graphs -----------------------------------------

-- ******************************* Billing Dashboard Graphs -----------------------------------------
INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (80, NULL, N''BillingAging'', N''Billing Aging'', N''Shows aging metrics based on the aging periods.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingAging'', NULL, N''dashboards.widgets.today.billingAging'', N''BillingAging'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (81, NULL, N''BillingCurrentOpenAmounts'', N''Billing Current Open Amounts'', N''Shows current open amounts by client.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingCurrentOpenAmounts'', NULL, N''dashboards.widgets.today.billingCurrentOpenAmounts'', N''BillingCurrentOpenAmounts'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (82, NULL, N''BillingNotBilledThisMonth'', N''Billing Not Billed This Month'', N''Shows totals not billed this month by client.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingNotBilledThisMonth'', NULL, N''dashboards.widgets.today.billingNotBilledThisMonth'', N''BillingNotBilledThisMonth'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (83, NULL, N''BillingActionsForTheMonth'', N''Billing Actions For The Month'', N''Shows amounts billed / not billed for the month.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingActionsForTheMonth'', NULL, N''dashboards.widgets.today.billingActionsForTheMonth'', N''BillingActionsForTheMonth'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (84, NULL, N''BillingWriteOffsForTheMonthYear'', N''Billing Write Offs For The Month/Year'', N''Shows write offs for the month or year by reason.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingWriteOffsForTheMonthYear'', NULL, N''dashboards.widgets.today.billingWriteOffsForTheMonthYear'', N''BillingWriteOffsForTheMonthYear'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (85, NULL, N''BillingDifferenceFromOriginalForTheMonthYear'', N''Billing Difference From Original For The Month/Year'', N''Shows different for the month or year by client.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingDifferenceFromOriginalForTheMonthYear'', NULL, N''dashboards.widgets.today.billingDifferenceFromOriginalForTheMonthYear'', N''BillingDifferenceFromOriginalForTheMonthYear'')

INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
VALUES (86, NULL, N''BillingRevenueForTheMonthYear'', N''Billing Revenue For The Month/Year'', N''Shows revenue by client for the moth or year.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadBillingRevenueForTheMonthYear'', NULL, N''dashboards.widgets.today.billingRevenueForTheMonthYear'', N''BillingRevenueForTheMonthYear'')

-- /////////////////////******************************* Billing Dashboard Graphs -----------------------------------------

--INSERT [dbo].[tWidgetDef] ([WidgetDefKey], [CompanyKey], [WidgetID], [Name], [Description], [TabName], [XPos], [YPos], [Width], [Height], [Local], [DisplayClass], [LoadFunction], [Disabled], [WidgetLocation], [Class]) 
--VALUES (90, NULL, N''ReportingFavorites'', N''Favorite Reports'', N''Shows all of your favorite reports.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadReportingFavorites'', NULL, N''dashboards.widgets.today.reportingFavorites'', N''ReportingFavorites'')


Update tWidgetDef Set DashID = ''Project'' Where WidgetDefKey < 20

Update tWidgetDef Set DashID = ''Today'' Where WidgetDefKey >= 20

SET IDENTITY_INSERT [dbo].[tWidgetEntity] ON 
INSERT [dbo].[tWidgetEntity] ([WidgetEntityKey], [Entity], [EntityDescription]) 
VALUES (1, N''ProjectSingle'', N''This is the dashboard for a single project.'')
INSERT [dbo].[tWidgetEntity] ([WidgetEntityKey], [Entity], [EntityDescription]) 
VALUES (2, N''Sales'', N''This is the sales dashboard.'')
INSERT [dbo].[tWidgetEntity] ([WidgetEntityKey], [Entity], [EntityDescription]) 
VALUES (3, N''Home'', N''These widgets are for the main home dashboard.'')
SET IDENTITY_INSERT [dbo].[tWidgetEntity] OFF

SET IDENTITY_INSERT [dbo].[tWidgetEntityAssigned] ON 
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (1, 2, 1)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (2, 2, 2)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (3, 2, 3)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (4, 2, 4)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (5, 2, 5)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (6, 2, 6)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (7, 1, 7)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (8, 1, 8)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (9, 1, 9)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (10, 1, 10)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (11, 1, 11)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (12, 1, 12)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (13, 1, 13)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (14, 1, 14)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (15, 1, 15)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (16, 1, 16)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (17, 1, 17)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (18, 1, 18)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (19, 1, 19)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (20, 3, 20)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (21, 3, 21)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (22, 3, 22)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (23, 3, 23)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (24, 3, 24)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (25, 3, 25)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (26, 3, 26)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (27, 3, 27)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (28, 3, 28)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (29, 3, 29)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (30, 3, 30)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (31, 3, 31)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (32, 3, 32)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (33, 3, 33)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (34, 3, 34)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (35, 3, 35)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (36, 3, 36)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (37, 3, 37)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (38, 3, 38)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (40, 3, 40)
--INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
--VALUES (41, 1, 41)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (60, 3, 60)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (61, 3, 61)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (62, 3, 62)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (63, 3, 63)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (64, 3, 64)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (65, 3, 65)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (66, 3, 66)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (67, 3, 67)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (70, 3, 70)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (71, 3, 71)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (72, 3, 72)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (73, 3, 73)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (80, 3, 80)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (81, 3, 81)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (82, 3, 82)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (83, 3, 83)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (84, 3, 84)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (85, 3, 85)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (86, 3, 86)
--INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
--VALUES (90, 3, 90)
SET IDENTITY_INSERT [dbo].[tWidgetEntityAssigned] OFF

-- (688217)

DELETE tString
DELETE tStringGroup

INSERT tStringGroup(StringGroupKey, StringGroupName, DisplayOrder) Values (2, ''Projects'', 2)
INSERT tStringGroup(StringGroupKey, StringGroupName, DisplayOrder) Values (6, ''Publication Dates'', 6)
INSERT tStringGroup(StringGroupKey, StringGroupName, DisplayOrder) Values (7, ''Broadcast Dates'', 7)
INSERT tStringGroup(StringGroupKey, StringGroupName, DisplayOrder) Values (8, ''General'', 1)
INSERT tStringGroup(StringGroupKey, StringGroupName, DisplayOrder) Values (9, ''Digital Art Review Fields'', 8)

INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''KeyUser1'', 2, ''Key Person 1'', NULL, NULL, 2, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''KeyUser2'', 2, ''Key Person 2'', NULL, NULL, 3, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''KeyUser3'', 2, ''Key Person 3'', NULL, NULL, 4, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''KeyUser4'', 2, ''Key Person 4'', NULL, NULL, 5, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''KeyUser5'', 2, ''Key Person 5'', NULL, NULL, 6, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''KeyUser6'', 2, ''Key Person 6'', NULL, NULL, 7, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaPrint1'', 6, ''User Defined 1'', ''Order Close'', NULL, 1, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaPrint2'', 6, ''User Defined 2'', ''Material Close'', NULL, 2, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaPrint3'', 6, ''User Defined 3'', NULL, NULL, 3, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaPrint4'', 6, ''User Defined 4'', NULL, NULL, 4, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaPrint5'', 6, ''User Defined 5'', NULL, NULL, 5, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaPrint6'', 6, ''User Defined 6'', NULL, NULL, 6, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaBroadcast1'', 7, ''User Defined 1'', NULL, NULL, 1, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaBroadcast2'', 7, ''User Defined 2'', NULL, NULL, 2, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaBroadcast3'', 7, ''User Defined 3'', NULL, NULL, 3, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaBroadcast4'', 7, ''User Defined 4'', NULL, NULL, 4, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaBroadcast5'', 7, ''User Defined 5'', NULL, NULL, 5, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''MediaBroadcast6'', 7, ''User Defined 6'', NULL, NULL, 6, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''Client'', 8, ''Client'', ''Client'', ''Clients'', 1, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''DARApprovalOption1'', 9, ''Approval Status Option 1'', ''Approved As Is'', NULL, 1, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''DARApprovalOption2'', 9, ''Approval Status Option 2'', ''Approved With Comments'', NULL, 2, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''DARApprovalOption3'', 9, ''Approval Status Option 3'', ''See Comments and Resubmit'', NULL, 3, 0, NULL)
INSERT tString(StringID, StringGroupKey, DisplayName, StringSingular, StringPlural, DisplayOrder, AllowDD, DefaultDD) Values (''DARApprovalOption4'', 9, ''Approval Status Option 4'', ''Rejected'', NULL, 4, 0, NULL)

DELETE tNotification

INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''ODTIME'', ''Overdue Time Sheets'', 1, 2, ''This will notify you on a daily or weekly basis of any time sheets that should have been submitted, but have not yet been sent out.'', 1, NULL, ''1*All People|2*People where I approve their time|3*People I supervise'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NOHOURS'', ''Missing Time'', 1, 1, ''This will send you a daily email of all people who did not enter their hours the prior day'', 2, ''For'', ''1*All People|2*People where I approve their time|3*People I supervise'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''TASKUPDATE'', ''Task Completed Notification'', 2, 2, ''This will immediately send you an email whenever a task is completed.'', 2, ''For'', ''1*All Projects I am Assigned to|2*Projects where I am the account manager or project manager|3*Only Projects in my office'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NEWPROJECT'', ''New Projects'', 2, 1, ''This will immediately send you an email when a project is added to the system'', 1, ''for'', ''1*All Projects|2*Projects where I am the project manager|3*Projects where I am the account manager'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NEWSPECSHEET'', ''New Spec Sheet'', 2, 2, ''This will immediately send you an email when a spec sheet is added to any project you are assigned to'', 3, ''AnyOf'', NULL, NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NEWVENDOR'', ''New Vendors'', 2, 4, ''This will immediately send you an email when a vendor is added to the system'', 1, NULL, NULL, NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NEWCLIENT'', ''New Clients'', 2, 5, ''This will immediately send you an email when a client is added to the system'', 1, NULL, NULL, NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''UPDATESTATUS'', ''Changes in Project Status'', 2, 3, ''This will immediately notify you when the production status code changes on a project'', 2, ''for'', ''1*All Projects I am Assigned to|2*Projects where I am the account manager, project manager or billing manager|3*Only Projects in my office|4*All Projects'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''OVERBUDGET'', ''Overbudget Projects'', 1, 1, ''This will send you an email on a daily basis of all overbudget (in terms of total dollars) projects. This will only work on projects with an approved budget.'', 2, ''For'', ''1*My Projects|2*Projects where I am the account manager or project manager|3*Projects in my office|4*All Projects'', ''-30*Projects within 30% of Budget|-20*Projects within 20% of Budget|-10*Projects within 10% of Budget|-5*Projects within 5% of Budget|0*All Projects at budget|5*Projects 5 % over budget|10*Projects 10 % over budget|20*Projects 20 % over budget'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''OVERBUDGETTASK'', ''Overbudget Tasks'', 1, 2, ''This will send you an email on a daily basis of all overbudget (in terms of total dollars) tasks. This will only work on projects with an approved budget.'', 2, ''For'', ''1*My Projects|2*Projects where I am the account manager or project manager|3*Projects in my office|4*All Projects'', ''-30*Tasks within 30% of Budget|-20*Tasks within 20% of Budget|-10*Tasks within 10% of Budget|-5*Tasks within 5% of Budget|0*All Tasks at budget|5*Tasks 5 % over budget|10*Tasks 10 % over budget|20*Tasks 20 % over budget'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''OVERBUDGETSERVICE'', ''Overbudget by Service'', 1, 3, ''This will send you an email on a daily basis of all overbudget (in terms of total dollars) services. This will only work on projects with an approved budget.'', 2, ''For'', ''1*My Projects|2*Projects where I am the account manager or project manager|3*Projects in my office|4*All Projects'', ''-30*Services within 30% of Budget|-20*Services within 20% of Budget|-10*Services within 10% of Budget|-5*Services within 5% of Budget|0*All Services at budget|5*Services 5 % over budget|10*Services 10 % over budget|20*Services 20 % over budget'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''OVERBUDGETITEM'', ''Overbudget by Item'', 1, 4, ''This will send you an email on a daily basis of all overbudget (in terms of total dollars) items. This will only work on projects with an approved budget.'', 2, ''For'', ''1*My Projects|2*Projects where I am the account manager or project manager|3*Projects in my office'', ''-30*Items within 30% of Budget|-20*Items within 20% of Budget|-10*Items within 10% of Budget|-5*Items within 5% of Budget|0*All Items at budget|5*Items 5 % over budget|10*Items 10 % over budget|20*Items 20 % over budget'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''OVERWORKED'', ''Overworked Assignments'', 1, 5, ''This will send you an email on a daily basis of all overworked (in terms of actual hours have exceed allocated) assignments. This will only work on active, not completed projects with allocated hours on them.'', 4, ''For'', ''1*My Projects|2*Projects where I am the account manager or project manager|3*Projects in my office|4*All Projects'', ''-30*Tasks within 30% of task allocation|-20*Tasks within 20% of task allocation|-10*Tasks within 10% of task allocation|-5*Tasks within 5% of task allocation|0*All Tasks at task allocation|5*Tasks 5 % over task allocation|10*Tasks 10 % over task allocation|20*Tasks 20 % over task allocation'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''ODBILLING'', ''Overdue Billing Worksheets'', 1, 6, ''This will notify you on a daily basis of any billing worksheets that should have been approved, but have not yet been approved.'', 2, ''For'', ''1*My Billing Worksheets|2*All Billing Worksheets'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''ODESTIMATE'', ''Overdue Project Estimates'', 1, 7, ''This will notify you on a daily basis of any estimates that should have been approved, but have not yet been approved.'', 2, ''For'', ''1*My Estimates|2*All Estimates'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''TASKREMINDER'', ''Task Reminders'', 1, 8, ''This will notify you when tasks you are assigned to are about to be due. This email goes out once a day'', 2, ''For'', ''1*My Assigned Tasks on Active Projects|2*All Tasks on Active Projects I am assigned to|3*All Tasks on Active Projects I am the Account Manager or Project Manager'', ''0*Due On or Before Today|3*Due On or Before the Next 3 days|7*Due On or Before the Next 7 days|14*Due On or Before the Next 14 Days'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''DELIVERABLE'', ''Daily Deliverable Status'', 1, 9, ''This will send you a daily status email of all deliverables that have been sent for review and have approaching due dates'', 2, ''For'', ''1*All Deliverables I own on Active Projects|2*All Deliverables on Active Projects I am assigned to|3*All Deliverables on Active Projects I am the Account Manager or Project Manager'', ''0*Due On or Before Today|2*Due in the next 2 days|3*Due in the next 3 days|5*Due in the next 5 days'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''ESTIMATEAPPROVE'', ''Estimate Approval'', 2, 6, ''This will immediately notify you when the estimate has been approved'', 2, ''for'', ''1*All Projects|2*My Projects (where you are on the team)|3*Only Projects in my office'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NEWOPPORTUNITY'', ''New Opportunities'', 2, 7, ''This will immediately send you an email when an opportunity is added to the system'', 1, NULL, NULL, NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''NEWCAMPAIGN'', ''New Campaigns'', 2, 8, ''This will immediately send you an email when an campaign is added to the system'', 1, ''for'', ''1*All Campaigns|2*Campaigns where I am the project manager|3*Campaigns where I am the account manager'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''ITEMSTOAPPROVE'', ''Items To Approve'', 2, 9, ''This will notify you on a daily basis of any items to approve in the notification bell'', 1, NULL, NULL, NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''UPDATEPROJECTSETTING'', ''Changes in Project Settings'', 2, 1, ''This will immediately send you an email when a project setting is changed in the system'', 1, ''for'', ''1*All Projects|2*Projects where I am the project manager|3*Projects where I am the account manager'', NULL)
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''TODOREMINDER'', ''To Do Reminders'', 1, 10, ''This will notify you when a to do you are assigned to is about to be due. This email goes out once a day'', 2, ''For'', NULL , ''0*Due On or Before Today|3*Due On or Before the Next 3 days|7*Due On or Before the Next 7 days|14*Due On or Before the Next 14 Days'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''OVERBUDGETCAMPAIGN'', ''Overbudget Campaign'', 1, 11, ''This will send you an email on a daily basis of all overbudget (in terms of total dollars) campaigns. This will only work on campaigns with an approved budget.'', 2, ''For'', ''1*My Campaigns|2*Campaigns where I am the account manager or project manager|3*All Campaigns'', ''-30*Campaigns within 30% of Budget|-20*Campaigns within 20% of Budget|-10*Campaigns within 10% of Budget|-5*Campaigns within 5% of Budget|0*All Campaigns at budget|5*Campaigns 5 % over budget|10*Campaigns 10 % over budget|20*Campaigns 20 % over budget'')
INSERT tNotification(NotificationID, NotificationName, DisplayGroup, DisplayOrder, Description, ValueType, ValueLabel, ValueDropDown, ValueDropDown2) Values (''UPDATEBILLINGSTATUS'', ''Changes in Project Billing Status'', 2, 12, ''This will immediately notify you when the production billing status code changes on a project'', 2, ''for'', ''1*All Projects I am Assigned to|2*Projects where I am the account manager, project manager or billing manager|3*Only Projects in my office|4*All Projects'', NULL)


-- tMobileMenu
DELETE tMobileMenu
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (1,  1, 1,'''', ''Projects'', ''projects.aspx?m=searchPage'', ''projectSearchList'', ''menuProjects'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (2,  2, 1,'''', ''My Tasks'', ''tasks.aspx?m=searchPage'', ''taskSearchList'', ''menuMyTasks'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (3,  3, 1,''calUseCalendar'', ''Calendar'', ''calendar.aspx?m=mainUI'', ''mainCalendar'', ''menuCalendar'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (6,  4, 1, ''useCompanies'', ''Companies'', ''clients.aspx?m=searchPage'', ''clientSearchList'', ''menuCompanies'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (7,  5, 1,''useContacts'', ''Contacts'', ''contacts.aspx?m=searchPage'', ''contactSearchList'', ''menuContacts'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (8,  6, 1,''useActivities'', ''Activities'', ''activities.aspx?m=searchPage'', ''activitySearchList'', ''menuActivities'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (4,  7, 1,''billingusetimesheet'', ''Time sheets'', ''timeentry.aspx?m=searchPage'', ''timeSheetSearchList'', ''menuTimesheets'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (5,  8, 1,'''', ''Approvals'', ''approvals.aspx?m=searchPage'', ''approvalList'', ''menuApprovals'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (9,  9, 1,''useOpp'', ''Opportunities'', ''opportunities.aspx?m=searchPage'', ''opportunitySearchList'', ''menuOpportunities'')
--INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) Values (10,  10, 1,'''', ''Project Requests'', ''projectRequests.aspx?m=searchPage'', ''projectRequestSearch'', ''menuProjectRequests'')
INSERT tMobileMenu (MobileMenuKey, DefaultDisplayOrder, DefaultSelection, RightID, Label, DataURL, PageID, Class) VALUES (11, 11, 1, ''billinguseexpenses'', ''Expense Reports'', ''expenseReports.aspx?m=searchPage'', ''expenseReportSearchList'', ''menuExpenseReports'')

/*
Delete tMobileSearchCondition Where MobileSearchKey in (Select MobileSearchKey from tMobileSearch Where UserKey is NULL)
Delete tMobileSearch Where UserKey is NULL

set identity_insert tMobileSearch on
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (1, NULL, ''Project'', NULL, ''Due In the Next Two Weeks'', ''Project Due Date'', ''ASC'', ''Client ID and Name'', 1, 3, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (2, NULL, ''Project'', NULL, ''Active Projects By Client'', ''Project Number'', ''ASC'', ''Client ID and Name'', 2, 1, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (3, NULL, ''Project'', NULL, ''Active Projects By Status'', ''Project Number'', ''ASC'', ''Project Status'', 3, 2, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (4, NULL, ''Contact'', NULL, ''My Contacts'', ''LastName'', ''ASC'', ''None'', 1, 4, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (5, NULL, ''Contact'', NULL, ''Contacts with an Activity in the next Week'', ''Next Activity Date'', ''ASC'', NULL, 2, 5, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (6, NULL, ''Contact'', NULL, ''All Active Contacts'', ''Contact First Name'', ''ASC'', NULL, 3, 6, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (7, NULL, ''MyTasks'', NULL, ''Due In The Next 7 Days'', ''Task Plan Completion Date'', ''ASC'', ''Priority'', 1, 6, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (8, NULL, ''MyTasks'', NULL, ''By Priority'', ''Task Plan Completion Date'', ''ASC'', ''Priority'', 2, 7, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (9, NULL, ''Opportunity'', NULL, ''My Opportunities'', ''Forecasted Close Date'', ''ASC'', ''Stage Name'', 1, 8, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (10, NULL, ''Opportunity'', NULL, ''Opportunities By Stage'', ''Forecasted Close Date'', ''ASC'', ''Stage Name'', 2, 9, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (11, NULL, ''Opportunity'', NULL, ''Opportunities By Status'', ''Forecasted Close Date'', ''ASC'', ''Status'', 3, 10, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (13, NULL, ''Activity'', NULL, ''Due By Today'', ''Activity Date'', ''ASC'', ''Activity Priority'', 2, 12, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (14, NULL, ''Activity'', NULL, ''All Activities'', ''Activity Date'', ''ASC'', NULL, 3, 13, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (15, NULL, ''TimeSheet'', NULL, ''All Open'', ''Start Date'', ''DESC'', ''Approval Status'', 1, 14, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (16, NULL, ''TimeSheet'', NULL, ''All Completed'', ''Start Date'', ''DESC'', ''Name'', 2, 15, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (17, NULL, ''TimeSheet'', NULL, ''My Open Time Sheets'', ''Start Date'', ''DESC'', ''Approval Status'', 3, 16, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (18, NULL, ''TimeSheet'', NULL, ''My Completed Time Sheets'', ''Start Date'', ''DESC'', NULL, 4, 17, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (19, NULL, ''ProjectRequest'', NULL, ''Open Requests'', ''Date Added'', ''DESC'', ''Client ID and Name'', 1, 18, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (20, NULL, ''ProjectRequest'', NULL, ''All Requests'', ''Date Added'', ''DESC'', ''Client ID and Name'', 2, 19, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (21, NULL, ''Company'', NULL, ''My Companies'', ''Company Name'', ''ASC'', NULL, 1, 20, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (22, NULL, ''Company'', NULL, ''Clients'', ''Company Name'', ''ASC'', NULL, 2, 21, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (23, NULL, ''Company'', NULL, ''Vendors'', ''Vendor ID'', ''ASC'', NULL, 3, 22, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (24, NULL, ''Company'', NULL, ''All Companies'', ''Company Name'', ''ASC'', NULL, 23, NULL, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (12, NULL, ''Activity'', NULL, ''My Activities'', ''Activity Date'', ''DESC'', ''Assigned To'', 1, 11, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (25, NULL, ''ExpenseReport'', NULL, ''All Open'', ''Start Date'', ''DESC'', ''Full Name'', 1, 24, 1, 0, '''')
INSERT tMobileSearch(MobileSearchKey, CompanyKey, ListID, UserKey, SearchName, SortField, SortDirection, GroupField, DisplayOrder, StdSearchKey, StandardSearch, Deleted) Values (26, NULL, ''ExpenseReport'', NULL, ''My Expense Reports'', ''Start Date'', ''DESC'', NULL, 1, 25, 1, 0, '''')
set identity_insert tMobileSearch off


set identity_insert tMobileSearchCondition on
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (1, 1, ''Project Due Date'', ''Is On or Before 2 Weeks From Today'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (2, 2, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (3, 3, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (4, 4, ''Contact Owner'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (5, 5, ''Next Activity Date'', ''Is On or Before A Week From Today'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (6, 6, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (7, 7, ''Assigned Staff'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (8, 7, ''Percentage Complete'', ''Less Than'', ''100'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (9, 7, ''Task Plan Completion Date'', ''Is On or Before A Week From Today'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (10, 7, ''Active Project'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (11, 8, ''Percentage Complete'', ''Less Than'', ''100'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (12, 8, ''Predecessors Completed'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (13, 8, ''Active Project'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (14, 9, ''Opportunity Owner Name'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (15, 9, ''Actual Close Date'', ''Is Blank'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (16, 10, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (17, 11, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (18, 12, ''Assigned To'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (19, 12, ''Activity Date Completed'', ''Is Blank'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (20, 13, ''Assigned To'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (21, 13, ''Activity Date'', ''Is On or Before Today'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (22, 15, ''Edit Status'', ''Equal To'', ''Open'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (23, 16, ''Approval Status'', ''Equal To'', ''Approved'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (24, 17, ''Name'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (25, 17, ''Edit Status'', ''Equal To'', ''Open'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (26, 18, ''Name'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (27, 18, ''Approval Status'', ''Equal To'', ''Approved'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (28, 19, ''Request Status'', ''Not Equal To'', ''Completed'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (29, 21, ''Account Manager Full Name'', ''Equal to My Name'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (30, 21, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (31, 22, ''Client ID'', ''Is Not Blank'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (32, 22, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (33, 23, ''Vendor ID'', ''Is Not Blank'', NULL, NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (34, 23, ''Active'', ''Equal To'', ''YES'', NULL)
INSERT tMobileSearchCondition(MobileSearchConditionKey, MobileSearchKey, FieldName, Condition, Value1, Value2) Values (35, 26, ''Full Name'', ''Equal to My Name'', NULL, NULL)
set identity_insert tMobileSearchCondition off

*/

delete tFinancialInstitution
INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(1, ''American Express (credit card)'',''3101'',''AMEX'',''https://online.americanexpress.com/myca/ofxdl/desktop/desktopDownload.do?request_type=nl_ofxdownload'')

--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(4, ''Bank of America'',''5959'',''HAN'',''https://eftx.bankofamerica.com/eftxweb/access.ofx'')

--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(5, ''Capital One Bank'',''1001'',''Hibernia'',''https://onlinebanking.capitalone.com/ofx/process.ofx'')
--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(6, ''Chase (credit card)'',''10898'',''B1'',''https://ofx.chase.com'')
INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(7, ''Citi Bank (credit card)'',''24909'',''Citigroup'',''https://www.accountonline.com/cards/svc/citiofxmanager.do'')
--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(7, ''Citi Bank (credit card)'',''24909'',''Citigroup'',''https://secureofx2.bankhost.com/citi/cgi-forte/ofx_rt?servicename=ofx_rt&pagename=ofx'')
--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(8, ''Discover Card (credit card)'',''7101'',''Discover Financial Services'',''https://ofx.discovercard.com/'')
--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(9, ''LaSalle Bank'',''1101'',''LaSalleBankMidwest'',''https://www.oasis.cfree.com/1101.ofxgp'')
INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(10, ''National City'',''5860'',''NATIONAL CITY'',''https://ofx.nationalcity.com/ofx/OFXConsumer.aspx'')
--INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(11, ''PNC Bank'',''4501'',''ISC'',''https://www.oasis.cfree.com/test.ofxgp'')
INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(12, ''Wachovia'',''4309'',''Wachovia'',''https://pfmpw.wachovia.com/cgi-forte/fortecgi?servicename=ofx&pagename=PFM'')
INSERT tFinancialInstitution(FinancialInstitutionKey, FIName, FIID, FIOrg, FIUrl) Values(13, ''Union Bank of California'',''2901'',''Union Bank of California'',''https://www.oasis.cfree.com/2901.ofxgp'')

-- Run this on PAAdmin if more currencies are added
delete tCurrency

Insert tCurrency (CurrencyID, Description) Values(''AED'', ''Arab Emirates Dirham'')
Insert tCurrency (CurrencyID, Description) Values(''ARS'', ''Argentine Peso'')
Insert tCurrency (CurrencyID, Description) Values(''AUD'', ''Australian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''AWG'', ''Aruban Florin'')
Insert tCurrency (CurrencyID, Description) Values(''BAM'', ''Convertible Mark'')
Insert tCurrency (CurrencyID, Description) Values(''BBD'', ''Barbadian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''BDT'', ''Bangladeshi Taka'')
Insert tCurrency (CurrencyID, Description) Values(''BGN'', ''Bulgarian Lev'')
Insert tCurrency (CurrencyID, Description) Values(''BHD'', ''Bahraini Dinar'')
Insert tCurrency (CurrencyID, Description) Values(''BMD'', ''Bermudian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''BOB'', ''Bolivian Boliviano'')
Insert tCurrency (CurrencyID, Description) Values(''BRL'', ''Brazilian Real'')
Insert tCurrency (CurrencyID, Description) Values(''BSD'', ''Bahamian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''CAD'', ''Canadian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''CHF'', ''Swiss Franc'')
Insert tCurrency (CurrencyID, Description) Values(''CLP'', ''Chilean Peso'')
Insert tCurrency (CurrencyID, Description) Values(''CNY'', ''Chinese Yuan'')
Insert tCurrency (CurrencyID, Description) Values(''COP'', ''Colombian Peso'')
Insert tCurrency (CurrencyID, Description) Values(''CZK'', ''Czech Koruna'')
Insert tCurrency (CurrencyID, Description) Values(''DKK'', ''Danish Krone'')
Insert tCurrency (CurrencyID, Description) Values(''EGP'', ''Egyptian Pound'')
Insert tCurrency (CurrencyID, Description) Values(''EUR'', ''Euro'')
Insert tCurrency (CurrencyID, Description) Values(''FJD'', ''Fijian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''GBP'', ''British Pound Sterling'')
Insert tCurrency (CurrencyID, Description) Values(''GHS'', ''Ghana Cedi'')
Insert tCurrency (CurrencyID, Description) Values(''GMD'', ''Gambian Dalasi'')
Insert tCurrency (CurrencyID, Description) Values(''GTQ'', ''Guatemalan Quetzal'')
Insert tCurrency (CurrencyID, Description) Values(''HKD'', ''Hong Kong Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''HRK'', ''Croatian Kuna'')
Insert tCurrency (CurrencyID, Description) Values(''HUF'', ''Hungarian Forint'')
Insert tCurrency (CurrencyID, Description) Values(''IDR'', ''Indonesian Rupiah'')
Insert tCurrency (CurrencyID, Description) Values(''ILS'', ''Israeli Sheqel'')
Insert tCurrency (CurrencyID, Description) Values(''INR'', ''Indian Rupee'')
Insert tCurrency (CurrencyID, Description) Values(''ISK'', ''Icelandic Krona'')
Insert tCurrency (CurrencyID, Description) Values(''JMD'', ''Jamaican Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''JOD'', ''Jordanian Dinar'')
Insert tCurrency (CurrencyID, Description) Values(''JPY'', ''Japanese Yen'')
Insert tCurrency (CurrencyID, Description) Values(''KES'', ''Kenyan Shilling'')
Insert tCurrency (CurrencyID, Description) Values(''KHR'', ''Cambodian Riel'')
Insert tCurrency (CurrencyID, Description) Values(''KRW'', ''South Korean Won'')
Insert tCurrency (CurrencyID, Description) Values(''KWD'', ''Kuwaiti Dinar'')
Insert tCurrency (CurrencyID, Description) Values(''LAK'', ''Lao Kip'')
Insert tCurrency (CurrencyID, Description) Values(''LBP'', ''Lebanese Pound'')
Insert tCurrency (CurrencyID, Description) Values(''LKR'', ''Sri Lankan Rupee'')
Insert tCurrency (CurrencyID, Description) Values(''LTL'', ''Lithuanian Litas'')
Insert tCurrency (CurrencyID, Description) Values(''LVL'', ''Latvian Lats'')
Insert tCurrency (CurrencyID, Description) Values(''MAD'', ''Moroccan Dirham'')
Insert tCurrency (CurrencyID, Description) Values(''MDL'', ''Moldovan Leu'')
Insert tCurrency (CurrencyID, Description) Values(''MGA'', ''Malagasy Ariary'')
Insert tCurrency (CurrencyID, Description) Values(''MKD'', ''Macedonian Denar'')
Insert tCurrency (CurrencyID, Description) Values(''MUR'', ''Mauritian Rupee'')
Insert tCurrency (CurrencyID, Description) Values(''MVR'', ''Maldivian Rufiyaa'')
Insert tCurrency (CurrencyID, Description) Values(''MXN'', ''Mexican Peso'')
Insert tCurrency (CurrencyID, Description) Values(''MYR'', ''Malaysian Ringgit'')
Insert tCurrency (CurrencyID, Description) Values(''NAD'', ''Namibian Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''NGN'', ''Nigerian Naira'')
Insert tCurrency (CurrencyID, Description) Values(''NOK'', ''Norwegian Krone'')
Insert tCurrency (CurrencyID, Description) Values(''NPR'', ''Nepalese Rupee'')
Insert tCurrency (CurrencyID, Description) Values(''NZD'', ''New Zealand Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''OMR'', ''Omani Rial'')
Insert tCurrency (CurrencyID, Description) Values(''PAB'', ''Panamanian Balboa'')
Insert tCurrency (CurrencyID, Description) Values(''PEN'', ''Peruvian Sol'')
Insert tCurrency (CurrencyID, Description) Values(''PHP'', ''Philippine Peso'')
Insert tCurrency (CurrencyID, Description) Values(''PKR'', ''Pakistani Rupee'')
Insert tCurrency (CurrencyID, Description) Values(''PLN'', ''Polish Zloty'')
Insert tCurrency (CurrencyID, Description) Values(''PYG'', ''Paraguayan Guaraní'')
Insert tCurrency (CurrencyID, Description) Values(''QAR'', ''Qatari Riyal'')
Insert tCurrency (CurrencyID, Description) Values(''RON'', ''Romanian Leu'')
Insert tCurrency (CurrencyID, Description) Values(''RSD'', ''Serbian Dinar'')
Insert tCurrency (CurrencyID, Description) Values(''RUB'', ''Russian Rouble'')
Insert tCurrency (CurrencyID, Description) Values(''SAR'', ''Saudi Riyal'')
Insert tCurrency (CurrencyID, Description) Values(''SCR'', ''Seychellois Rupee'')
Insert tCurrency (CurrencyID, Description) Values(''SEK'', ''Swedish Krona'')
Insert tCurrency (CurrencyID, Description) Values(''SGD'', ''Singapore Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''SYP'', ''Syrian Pound'')
Insert tCurrency (CurrencyID, Description) Values(''THB'', ''Thai Baht'')
Insert tCurrency (CurrencyID, Description) Values(''TND'', ''Tunisian Dinar'')
Insert tCurrency (CurrencyID, Description) Values(''TRY'', ''Turkish Lira'')
Insert tCurrency (CurrencyID, Description) Values(''TWD'', ''Taiwanese Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''UAH'', ''Ukraine Hryvnia'')
Insert tCurrency (CurrencyID, Description) Values(''UGX'', ''Ugandan Shilling'')
Insert tCurrency (CurrencyID, Description) Values(''UYU'', ''Uruguayan Peso'')
Insert tCurrency (CurrencyID, Description) Values(''USD'', ''US Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''VEF'', ''Venezuelan Bolívar'')
Insert tCurrency (CurrencyID, Description) Values(''VND'', ''Vietnamese Dong'')
Insert tCurrency (CurrencyID, Description) Values(''XAF'', ''Central African Franc'')
Insert tCurrency (CurrencyID, Description) Values(''XCD'', ''East Caribbean Dollar'')
Insert tCurrency (CurrencyID, Description) Values(''XOF'', ''West African Franc'')
Insert tCurrency (CurrencyID, Description) Values(''XPF'', ''CFP Franc'')
Insert tCurrency (CurrencyID, Description) Values(''ZAR'', ''South African Rand'')

delete tTaskUserStatus Where TaskUserStatusKey < 1000
set identity_insert tTaskUserStatus on
Insert tTaskUserStatus (TaskUserStatusKey, EntityKey, Entity, StatusName, IsDefault, DisplayOrder, DefaultPercentComp) Values (1, NULL, NULL, ''Work to be Done'', 1, 1, 0)
Insert tTaskUserStatus (TaskUserStatusKey, EntityKey, Entity, StatusName, IsDefault, DisplayOrder, DefaultPercentComp) Values (2, NULL, NULL, ''Do This Today'', 0, 2, 0)
Insert tTaskUserStatus (TaskUserStatusKey, EntityKey, Entity, StatusName, IsDefault, DisplayOrder, DefaultPercentComp) Values (3, NULL, NULL, ''Completed'', 0, 3, 100)
set identity_insert tTaskUserStatus off

delete from tBankAccountType

set identity_insert dbo.tBankAccountType ON
Insert tBankAccountType (BankAccountTypeKey, BankAccountType) VALUES (1, ''Checking'')
Insert tBankAccountType (BankAccountTypeKey, BankAccountType) VALUES (2, ''Saving'')
set identity_insert dbo.tBankAccountType OFF

--Save off any current services that are logging
SELECT	TMServiceKey
INTO	#TMLogActive
FROM	tTMLogService (nolock)
WHERE	LogActive = 1

--Seed the TM services
DELETE	tTMLogService

INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(1, ''Calendar'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(2, ''CheckWebsite'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(3, ''SendNotifications'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(4, ''DeleteWebFiles'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(5, ''ScheduleUpdate'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(6, ''Import'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(7, ''ReadEmails'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(8, ''ReverseJournalEntries'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(9, ''EmailMarketing'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(10, ''GoogleSync'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(11, ''DailyTasks'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(12, ''ArcManager'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(14, ''ApiWebHooks'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(15, ''ProjectRollup'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(16, ''SMTP'')
INSERT	tTMLogService (TMServiceKey, ServiceName) VALUES(17, ''ProcessBase64Attachments'')

--Turn logging back on for any that were logging when the seed script ran
UPDATE	tTMLogService
SET		LogActive = 1
FROM	tTMLogService
INNER JOIN #TMLogActive tmp ON tTMLogService.TMServiceKey = tmp.TMServiceKey

IF NOT EXISTS 
		(SELECT NULL
		FROM	tRTNActive (nolock))
	INSERT	tRTNActive (Active) VALUES (1)

--Seed the help guide links
TRUNCATE TABLE tHelpGuideLink

INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.dashboard.dash'', ''Project dashboard [in-depth guide] – Workamajig'', ''Gain an in-depth understanding of project dashboards and learn how to customize yours for maximum benefit.'', ''https://support.workamajig.com/hc/en-us/articles/360022821011-Project-dashboard-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.dashboard.dash'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.schedule.edit2'', ''Project schedule overview [in-depth guide] – Workamajig'', ''Discover how to schedule your projects and understand how to use the more advanced features for your benefit.'', ''https://support.workamajig.com/hc/en-us/articles/360022860831-Project-schedule-overview-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.schedule.edit2'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.diary.thread'', ''Project conversation [in-depth guide] – Workamajig'', ''Enhance collaboration by learning how to easily create, reply to, view, and subscribe others to the conversations. Also learn how to choose which conversations will be visible to the client.'', ''https://support.workamajig.com/hc/en-us/articles/4409614779924-Project-conversation-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.diary.thread'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''today.creative'', ''Creatives > Today creatives page [guide] – Workamajig'', ''Easily and efficiently keep track of tasks with this basic guide for creative users.'', ''https://support.workamajig.com/hc/en-us/articles/360022619492-Creatives-Today-creatives-page-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=today.creative'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.files.list'', ''Project files [in-depth guide] – Workamajig'', ''Make the most of your Project files with this guide manage, navigate, and send files for review.'', ''https://support.workamajig.com/hc/en-us/articles/360022647752-Project-files-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.files.list'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''user.timeEntry.edit'', ''Everyone > Time sheet page [guide] – Workamajig'', ''Learn how to work your timer, submit hours and get time sheets approved.'', ''https://support.workamajig.com/hc/en-us/articles/360022808811-Everyone-Time-sheet-page-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=user.timeEntry.edit'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.setup.edit'', ''Project Manager > Projects page [guide] – Workamajig'', ''Easily set up projects with templates and pre-populated forms.'', ''https://support.workamajig.com/hc/en-us/articles/360022855111-New-project-in-depth-guide-#h_773936660461549305604323?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.setup.edit'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''user.editTime'', ''Everyone > Time sheet page [guide] – Workamajig'', ''Understanding the multiple places available for users to enter time, depending on your needs & preferences.'', ''https://support.workamajig.com/hc/en-us/articles/360022808811-Everyone-Time-sheet-page-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=user.editTime'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.deliverables.rounds.review'', ''Deliverables overview [in-depth guide] – Workamajig'', ''Your in-depth guide to project deliverables - setting them up, using advanced features, and sending for review.'', ''https://support.workamajig.com/hc/en-us/articles/360022648112-Deliverables-overview-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.deliverables.rounds.review'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.production.dash'', ''Project Manager > Projects page [guide] – Workamajig'', ''Project manager? Learn to navigate new projects, view financial status, project schedules, and more.'', ''https://support.workamajig.com/hc/en-us/articles/360022820951-Project-Manager-Projects-page-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.production.dash'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''purchasing.vouchers.edit'', ''Purchasing > Vendor Invoices [in-depth guide] - Workamajig'', ''Create vendor invoices with ease with this in-depth guide on how to create, edit, and schedule them.'', ''https://support.workamajig.com/hc/en-us/articles/360022665812-Vendor-invoices-overview-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=purchasing.vouchers.edit'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''billing.invoices.edit'', ''Billing > Indepth Guides for Billing - Workamajig'', ''Manually create and edit client invoices with this in-depth guide.'', ''https://support.workamajig.com/hc/en-us/articles/360033507972-Client-invoices-overview-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=billing.invoices.edit'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.diary.reply'', ''Project conversation [in-depth guide] – Workamajig'', ''Navigate project conversations with confidence - get familiar with how to use them in this guide.'', ''https://support.workamajig.com/hc/en-us/articles/4409614779924-Project-conversation-in-depth-guide-#h_01FM5EQ2MZ8YX295K16HJ431S9?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.diary.reply'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.diary.add'', ''Project conversation [in-depth guide] – Workamajig'', ''Navigate project conversations with confidence - get familiar with how to use them in this guide.'', ''https://support.workamajig.com/hc/en-us/articles/4409614779924-Project-conversation-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.diary.thread'')
INSERT tHelpGuideLink (PageAID, Title, Description, Link) VALUES (''projects.diary.dash'', ''Project conversation [in-depth guide] – Workamajig'', ''Enhance collaboration by learning how to easily create, reply to, view, and subscribe others to the conversations. Also learn how to choose which conversations will be visible to the client.'', ''https://support.workamajig.com/hc/en-us/articles/4409614779924-Project-conversation-in-depth-guide-?utm_source=app&utm_medium=click&utm_campaign=in-app-support&utm_page=projects.diary.thread'')
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserMyInfoUpdateWMJ]'
GO
IF OBJECT_ID(N'[dbo].[sptUserMyInfoUpdateWMJ]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptUserMyInfoUpdateWMJ]
 @UserKey int,
 @FirstName nvarchar(100),
 @LastName nvarchar(100),
 @Salutation varchar(10),
 @Phone1 varchar(50),
 @Phone2 varchar(50),
 @Cell varchar(50),
 @Fax varchar(50),
 @Pager varchar(50),
 @Title nvarchar(200),
 @Email varchar(100), 
 @Position varchar(50),
 @UserID varchar(100),
 @NewPassword varchar(500),
 @ContactMethod tinyint,
 @InOutStatus varchar(10),
 @BackupApprover int,
 @InOutNotes varchar(100),
 @TimeZoneIndex int,
 @DefaultReminderTime int,
 @SystemMessage tinyint,
 @SyncMLDirection smallint = 0, --Optional because of CMP90
 @CalendarReminder smallint = -1, --Optional because of CMP90
 @DefaultCalendarColor varchar(50) = NULL, --Optional because of CMP90
 @Signature varchar(max) = NULL,
 @TwoFactorSendPref smallint = 0,
 @Theme smallint = NULL,
 @SecurityChange smallint = 0,
 @SuspendAdmin tinyint = 0,
 @SecurityGroupKey int = NULL,
 @UserBackgroundColor varchar(30) = NULL,
 @UserBarColor varchar(30) = NULL,
 @UserMenuColor varchar(30) = NULL,
 @UserAccentColor varchar(30) = NULL,
 @UserBodyColor varchar(20) = NULL,
 @UserDarkMode varchar(10) = NULL
AS --Encrypt

/*
|| When      Who Rel      What
|| 06/13/11  RLB 10.545   Created for New Flex MyInfo
|| 10/28/11  RLB 10.549   FIxed Blanking of Email Sync Password 
|| 05/24/12  QMD 10.556   Added update to EmailLastSent and EmailAttempts
|| 09/19/12  KMC 10.5.6.0 Added BackupApprover
|| 06/06/14  RLB 10.5.8.1 (218791) added check for client login when adding to tACtivationLog
|| 08/09/17  GAR 10.6.1.9 (358450) Change update of my info to use a stored proc / needed to add signature
|| 02/17/21  RLS 21.0.3.0 (546075) Changed @FirstName and @LastName to nvarchar
|| 07/18/22  RLS 22.0.8.0 (606282) Changed @Title to nvarchar
|| 04/07/23  CRG 23.05.14 (630097) Added TwoFactorSendPref 
|| 06/19/23  CRG 23.06.18 (643647) Fixed Two Factor validation issue
|| 2/1/25    GWG 25.02.16  Added in Theme calls
|| 05/20/25  CRG 25.06.15 (699112) Added SecurityChange, SuspendAdmin, SecurityGroupKey
|| 10/10/25  KMC 25.11.16 (698233) Removed tUserPreference EmailMailBox, EmailUserID, and NewEmailPassword
*/

-- GHL: Patch for negative TimeZoneIndex!
IF @TimeZoneIndex < 0
	SELECT @TimeZoneIndex = 48
	

DECLARE @ClientVendorLogin tinyint

SELECT @ClientVendorLogin = ClientVendorLogin from tUser (nolock) where  UserKey = @UserKey

--if @Active <> @CurActive or @CurUserID <> @UserID
	if Len(@UserID) > 0 and @ClientVendorLogin = 0
	Begin
		If not exists(select 1 from tActivationLog (NOLOCK) where UserKey = @UserKey and DateDeactivated IS NULL)
			Insert tActivationLog
			(UserKey, DateActivated)
			Values (@UserKey, GETDATE())
	end
	else
		Update tActivationLog
		Set DateDeactivated = GETDATE()
		Where	UserKey = @UserKey and
				DateDeactivated IS NULL
				
				
 -- User IDs are unique if not null
 IF @UserID IS NOT NULL
 BEGIN
  IF EXISTS (SELECT 1
             FROM   tUser (NOLOCK)
             WHERE  UPPER(LTRIM(RTRIM(UserID))) = UPPER(LTRIM(RTRIM(@UserID)))
             AND    UserKey <> @UserKey)
   RETURN -1
 END

	
 DECLARE @RetVal int
 IF  Len(@NewPassword) > 0
 BEGIN
 
   EXEC @RetVal = sptUserUpdatePassword @UserKey, @NewPassword
   IF @RetVal <> 1
	  RETURN -2
 END

 --Check for two-factor auth
 IF ISNULL(@TwoFactorSendPref, 0) = 0
 BEGIN
	IF EXISTS(
			SELECT	NULL
			FROM	tUser u (nolock)
			INNER JOIN tCompany c (nolock) ON ISNULL(u.OwnerCompanyKey, u.CompanyKey) = c.CompanyKey
			INNER JOIN tPreference p (nolock) ON c.CompanyKey = p.CompanyKey
			WHERE	u.UserKey = @UserKey
			AND		p.TwoFactorAuth = 1)
		RETURN -3 --A two factor send preference is required
END
 
 IF @SyncMLDirection = 0
	SELECT	@SyncMLDirection = SyncMLDirection
	FROM	tUser (nolock)
	WHERE	UserKey = @UserKey
	
IF @CalendarReminder = -1
	SELECT	@CalendarReminder = CalendarReminder
	FROM	tUser (nolock)
	WHERE	UserKey = @UserKey
	
IF @DefaultCalendarColor IS NULL
	SELECT	@DefaultCalendarColor = DefaultCalendarColor
	FROM	tUser (nolock)
	WHERE	UserKey = @UserKey
	


 UPDATE
  tUser
 SET
  FirstName = @FirstName,
  LastName = @LastName,
  Salutation = @Salutation,
  Phone1 = @Phone1,
  Phone2 = @Phone2,
  Cell = @Cell,
  Fax = @Fax,
  Pager = @Pager,
  Title = @Title,
  Email = @Email,
  [Signature] = @Signature,
  UserID = @UserID,
  ContactMethod = @ContactMethod,
  InOutStatus = @InOutStatus,
  BackupApprover = @BackupApprover,
  InOutNotes = @InOutNotes,
  TimeZoneIndex = @TimeZoneIndex,
  DefaultReminderTime = @DefaultReminderTime,
  SystemMessage = @SystemMessage,
  SyncMLDirection = @SyncMLDirection,
  CalendarReminder = @CalendarReminder,
  DefaultCalendarColor = @DefaultCalendarColor,
  TwoFactorSendPref = @TwoFactorSendPref,
  Theme = @Theme,
  UserBackgroundColor = @UserBackgroundColor,
  UserBarColor = @UserBarColor,
  UserMenuColor = @UserMenuColor,
  UserAccentColor = @UserAccentColor,
  UserBodyColor = @UserBodyColor,
  UserDarkMode = @UserDarkMode
 WHERE
  UserKey = @UserKey

--Update Security Changes for Preview Security feature
IF @SecurityChange = 1
BEGIN
	--Make sure this user is either an Admin, or has suspended their Admin access (otherwise, they can''t change security)
	IF EXISTS(SELECT NULL FROM tUser WHERE UserKey = @UserKey AND (Administrator = 1 OR SuspendAdmin = 1))
		UPDATE	tUser
		SET		SecurityGroupKey = @SecurityGroupKey,
				SuspendAdmin = @SuspendAdmin,
				Administrator = CASE @SuspendAdmin
									WHEN 1 THEN 0 --If Admin is temporarily suspended, set Administrator flag to 0
									ELSE 1
								END
		WHERE	UserKey = @UserKey
END

    
 RETURN 1




'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserAnonymize]'
GO
IF OBJECT_ID(N'[dbo].[sptUserAnonymize]', 'P') IS NOT NULL
EXEC sp_executesql N'


ALTER Procedure [dbo].[sptUserAnonymize] 
(
	@CompanyKey int,
	@UserKey int,
	@ReplaceWith varchar(200)
)

as 

/*
  || When       Who Rel       What
  || 02/17/21   RLS 21.0.3.0  (546075) Changed @FirstName and @LastName to nvarchar
  || 07/30/25   AMP 25.08.17  (705266) Reviewed - No trigger change needed at this time - nothing applies here
*/

declare @FirstName nvarchar(300), @LastName nvarchar(300), @Email varchar(300)

Select @FirstName = FirstName, @LastName = LastName, @Email = Email from tUser (nolock) Where UserKey = @UserKey

Update tActionLog
Set ActionBy = @ReplaceWith 
Where ActionBy = @FirstName + '' '' + @LastName
and CompanyKey = @CompanyKey


Update tActionLog
Set Comments = Replace(Comments, @FirstName + '' '' + @LastName, @ReplaceWith)
Where Comments like ''%'' + @FirstName + '' '' + @LastName + ''%''
and CompanyKey = @CompanyKey

Update tActivity
Set Notes = Replace(Cast(Notes as varchar(max)), @FirstName + '' '' + @LastName, @ReplaceWith)
Where Cast(Notes as varchar(max)) like ''%'' + @FirstName + '' '' + @LastName + ''%''
and CompanyKey = @CompanyKey


Update tActivity
Set Notes = Replace(Cast(Notes as varchar(max)), @Email, @ReplaceWith)
Where Cast(Notes as varchar(max)) like ''%'' + @Email + ''%''
and CompanyKey = @CompanyKey

Update tApprovalStep
Set ApproverStatus = Replace(ApproverStatus, @FirstName + '' '' + @LastName, @ReplaceWith)
Where ApproverStatus like ''%'' + @FirstName + '' '' + @LastName + ''%''
and CompanyKey = @CompanyKey


Update tEmailSendLog Set EmailFromAddress = @ReplaceWith Where EmailFromAddress = @Email and CompanyKey = @CompanyKey

Update tEmailSendLog Set EmailToAddress = @ReplaceWith Where EmailToAddress = @Email and CompanyKey = @CompanyKey


Update tEmailSendLog
Set Body = Replace(Cast(Body as varchar(max)), @FirstName + '' '' + @LastName, @ReplaceWith)
Where Cast(Body as varchar(max)) like ''%'' + @FirstName + '' '' + @LastName + ''%''
and CompanyKey = @CompanyKey


Update tEmailSendLog
Set Body = Replace(Cast(Body as varchar(max)), @Email, @ReplaceWith)
Where Cast(Body as varchar(max)) like ''%'' + @Email + ''%''
and CompanyKey = @CompanyKey

Update tUser Set FirstName = @ReplaceWith, LastName = @ReplaceWith, Email = @ReplaceWith, Birthday = NULL, Children = NULL, SpouseName = NULL  Where UserKey = @UserKey

delete tAddress Where Entity = ''tUser'' and EntityKey = @UserKey and AddressName = ''Home'''
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityGetAllForEntity]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityGetAllForEntity]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityGetAllForEntity]
	(
		@Entity varchar(50),
		@EntityKey int
	)

AS

/*
|| When     Who Rel     What
|| 01/21/10 GHL 10.517	Reading now fields which are needed, not a.*
||                      Taking now 3 secs instead of 3 mins on APP2
|| 09/15/11 RLB 10.548  (121046) passing in DateUpdated to help figure out Last Activity
|| 10/05/18 MCM 18.9.2  (332662) adding lots of fields and join to tUser becausing using for adding conversations to vouchers/invoices
|| 02/17/23 RLB 23.03.19 (631465) added VisibleToClient for filtering
|| 05/27/26 RLB 26.06.14 (729333) added Private, EntityKey, AssignedUserKey and OriginatorUserKey for filtering private
|| 05/27/26 RLB 26.08.16 (733577) added ActivityEntity for filtering ToDo
*/ 
	
	select 
		a.ActivityKey
		, a.ActivityDate
		, a.Completed
		, a.DateCompleted
		, a.DateUpdated
		, a.DateAdded
		, a.ParentActivityKey
		, a.Subject
		, a.Notes
		,isnull(uadd.FirstName + '' '', '''') + isnull(uadd.LastName, '''') as AddedByUserName
		,ISNULL(a.VisibleToClient , 0) as VisibleToClient
		,a.Private
		,a.ActivityKey as EntityKey
		,a.AssignedUserKey
		,a.OriginatorUserKey
		,a.ActivityEntity
	From tActivity a (nolock) 
	Inner join tActivityLink al (nolock) on a.ActivityKey = al.ActivityKey
	left outer join tUser uadd (nolock) on a.AddedByKey = uadd.UserKey
	Where al.Entity = @Entity and al.EntityKey = @EntityKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAISearchContacts]'
GO
IF OBJECT_ID(N'[dbo].[spApiAISearchContacts]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAISearchContacts]
(
    @CompanyKey     int,
    @UserKey        int,
    @SearchTerm     nvarchar(500)
)
AS --Encrypt

/*
|| When      Who Rel        What
|| --        --  --         Created - contact search (set-based GL company filter)
|| 05/25/26  AI  26.05.25   Added standard #errors / warnings scaffold; required-field validation.
||                          Result-set shape now: [warnings, contacts] - handler updated to match.
|| 05/28/26  AI  26.05.28   Added #errors / warnings; required-field validation. Result-set shape now [warnings, contacts].
|| 06/24/26  AI  26.06.24   Added @CanViewOthers; restricts to OwnerKey = @UserKey when 0.
|| 07/10/26  GAR 26.07.19   Added gating security - requires useContacts. Removed @CanViewOthers param;
||                          viewOtherContacts right now checked inside the SP to gate contacts not owned by the caller.
*/

set nocount on

    -- ------------------------------------------------------------------
    -- Gating security: useContacts
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint
    declare @gsCanViewOthers    tinyint = 0

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''useContacts''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (useContacts).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    -- viewOtherContacts: without it (and not admin), restrict to contacts the caller owns.
    if @gsIsAdministrator = 1
        set @gsCanViewOthers = 1
    else if exists (
            select 1
            from   tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where  ra.EntityType = ''Security Group''
              and  ra.EntityKey  = @gsSecurityGroupKey
              and  r.RightID     = ''viewOtherContacts''
        )
        set @gsCanViewOthers = 1

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @RestrictToGLCompany int

    if @SearchTerm is null or LTRIM(RTRIM(@SearchTerm)) = ''''
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''searchTerm is required.'', ''searchTerm'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -100
    end

    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    from   tPreference (nolock) where CompanyKey = @CompanyKey

    -- Result set 1: warnings (consistent shape, even when empty)
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    -- Result set 2: contacts
    select
        v.UserKey       as contactKey,
        v.UserFullName  as fullName,
        v.Email         as email,
        v.UserName      as contactName,
        v.Phone1        as phone,
        v.Cell          as mobile,
        v.Title         as title,
        v.CompanyName   as companyName,
        v.Address1      as address1,
        v.Address2      as address2,
        v.City          as city,
        v.State         as state,
        v.PostalCode    as postalCode,
        v.Country       as country
    from   vUserName v (nolock)
    where  v.OwnerCompanyKey = @CompanyKey
      and  v.Active          = 1
      and  (
              v.UserFullName  like ''%'' + @SearchTerm + ''%''
           or v.Email         like ''%'' + @SearchTerm + ''%''
           or v.UserName      like ''%'' + @SearchTerm + ''%''
           or v.CompanyName   like ''%'' + @SearchTerm + ''%''
           )
      and  (@gsCanViewOthers = 1 or v.OwnerKey = @UserKey)
      and  (@RestrictToGLCompany = 0
            or v.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))
    order by v.UserFullName

    drop table #errors
    return 0

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAITimerInsert]'
GO
IF OBJECT_ID(N'[dbo].[spApiAITimerInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAITimerInsert]
(
    @CompanyKey    int,
    @UserKey       int,
    @ProjectNumber varchar(50)  = null,
    @TaskID        nvarchar(100) = null,
    @ServiceName   nvarchar(200) = null
)
AS --Encrypt

/*
|| When      Who Rel        What
|| --        --  --         Created - start a timer record
|| 05/25/26  AI  26.05.25   Replaced RAISERROR pattern with the standard #errors / warnings result
||                          set. Added spCheckAccess (tProject) gate when a project is supplied.
||                          Result-set shape is now [warnings, timer].
|| 05/28/26  AI  26.05.28   Replaced RAISERROR with #errors pattern; added spCheckAccess (tProject) when project supplied.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billingusetimesheet.
*/

set nocount on

    -- ------------------------------------------------------------------
    -- Gating security: billingusetimesheet
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billingusetimesheet''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billingusetimesheet).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @ProjectKey    int = null
    declare @TaskKey       int = null
    declare @ServiceKey    int = null
    declare @StartTimeUTC  datetime
    declare @AccessOK      int
    declare @ErrorCount    int

    set @StartTimeUTC = GETUTCDATE()

    -- ------------------------------------------------------------------
    -- Resolve project (optional)
    -- ------------------------------------------------------------------
    if @ProjectNumber is not null
    begin
        select @ProjectKey = ProjectKey
        from   tProject (nolock)
        where  ProjectNumber = @ProjectNumber and CompanyKey = @CompanyKey

        if @ProjectKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', ''Project not found for projectNumber: '' + @ProjectNumber, ''projectNumber'')
    end

    -- ------------------------------------------------------------------
    -- Resolve task (optional, only when project known)
    -- ------------------------------------------------------------------
    if @TaskID is not null and @ProjectKey is not null
    begin
        select @TaskKey = TaskKey
        from   tTask (nolock)
        where  TaskID = @TaskID and ProjectKey = @ProjectKey

        if @TaskKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', ''Task not found for taskID: '' + @TaskID, ''taskID'')
    end

    -- ------------------------------------------------------------------
    -- Resolve service (optional)
    -- ------------------------------------------------------------------
    if @ServiceName is not null
    begin
        select @ServiceKey = ServiceKey
        from   tService (nolock)
        where  (ServiceCode = @ServiceName or Description = @ServiceName)
          and  Active = 1

        if @ServiceKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', ''Service not found for serviceName: '' + @ServiceName, ''serviceName'')
    end

    -- ------------------------------------------------------------------
    -- Surface lookup errors
    -- ------------------------------------------------------------------
    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- Project access gate (only when a project is supplied)
    -- ------------------------------------------------------------------
    if @ProjectKey is not null
    begin
        exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey
        if @AccessOK <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''You do not have access to this project.'', ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
            drop table #errors
            return -103
        end
    end

    -- ------------------------------------------------------------------
    -- Insert timer record
    -- ------------------------------------------------------------------
    insert into tTimer (
        CompanyKey, UserKey, ProjectKey, TaskKey, ServiceKey,
        StartTime, PauseSeconds, Paused, RateLevel
    )
    values (
        @CompanyKey, @UserKey, @ProjectKey, @TaskKey, @ServiceKey,
        @StartTimeUTC, 0, 0, 1
    )

    -- Result set 1: warnings
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    -- Result set 2: new TimerKey
    select SCOPE_IDENTITY() as TimerKey

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptRetainerInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptRetainerInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptRetainerInsert]
	@CompanyKey int,
	@ClientKey int,
	@Title varchar(200),
	@StartDate smalldatetime,
	@Frequency smallint,
	@NumberOfPeriods int,
	@AmountPerPeriod money,
	@LastBillingDate smalldatetime,
	@IncludeLabor tinyint,
	@IncludeExpense tinyint,
	@CustomFieldKey int,
	@LineFormat smallint,
	@InvoiceApprovedBy int,
	@Active tinyint,
	@InvoiceExpensesSeperate tinyint,
	@SalesAccountKey int,
	@GLCompanyKey int,
	@OfficeKey int,
	@Description text,
	@ClassKey int,
	@oIdentity INT OUTPUT,
	@BillExpensesByItem tinyint = NULL
AS --Encrypt

  /*
  || When     Who Rel   What
  || 07/05/07 GHL 8.5   Added GLCompanyKey + office          
  || 09/20/07 GHL 8.437 (Enh 13169) Added new field Description
  || 12/17/07 GHL 8.5   (Enh 17879) Added ClassKey       
  || 06/19/08 GHL 8.514 (13169) Changed description to text from varchar(1500)
  || 03/25/21 GHL 21.04.18 (553141) Limit the number of periods to avoid overflows in forecasts
  ||                       for quarters limit is 120
  || 07/28/26 MFT 26.08.01 (708954) Added BillExpensesByItem (Retainer extra charges billed one line per Item/Service)
  */

   -- small dates are limited to 2079
   -- limit to 30 years or 360 months or  90 quarters or 1560 weeks

	if @Frequency = 1 and @NumberOfPeriods > 360
		select @NumberOfPeriods = 0 -- no limit

	if @Frequency = 2 and @NumberOfPeriods > 120
		select @NumberOfPeriods = 0 -- no limit

	if @Frequency = 3 and @NumberOfPeriods > 30
		select @NumberOfPeriods = 0 -- no limit

	if @Frequency = 4 and @NumberOfPeriods > 1560
		select @NumberOfPeriods = 0 -- no limit

	INSERT tRetainer
		(
		CompanyKey,
		ClientKey,
		Title,
		StartDate,
		Frequency,
		NumberOfPeriods,
		AmountPerPeriod,
		LastBillingDate,
		IncludeLabor,
		IncludeExpense,
		CustomFieldKey,
		LineFormat,
		InvoiceApprovedBy,
		Active,
		InvoiceExpensesSeperate,
		SalesAccountKey,
		GLCompanyKey,
		OfficeKey,
		Description,
		ClassKey,
		BillExpensesByItem
		)

	VALUES
		(
		@CompanyKey,
		@ClientKey,
		@Title,
		@StartDate,
		@Frequency,
		@NumberOfPeriods,
		@AmountPerPeriod,
		@LastBillingDate,
		@IncludeLabor,
		@IncludeExpense,
		@CustomFieldKey,
		@LineFormat,
		@InvoiceApprovedBy,
		@Active,
		@InvoiceExpensesSeperate,
		@SalesAccountKey,
		@GLCompanyKey,
		@OfficeKey,
		@Description,
		@ClassKey,
		ISNULL(@BillExpensesByItem, 0)
		)

	SELECT @oIdentity = @@IDENTITY

	RETURN 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetActionLog]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetActionLog]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIGetActionLog]
(

    @CompanyKey         int,
    @UserKey            int,
    @Entity             varchar(50)  = null,    -- Caller-facing entity name. One of:
                                                --   Project, Contact, Company, Invoice, Vendor Invoice,
                                                --   Payment, Receipt, Lead, Opportunity.
                                                --   Required when @ProjectNumber is not supplied.
                                                --   Any other value -> ''This entity is currently not supported.''
    @EntityID           varchar(100) = null,    -- Business identifier for that entity. Required when @Entity is
                                                --   supplied. Per entity:
                                                --     Project        -> ProjectNumber
                                                --     Contact        -> full name or email
                                                --     Company        -> CustomerID, VendorID, or CompanyName
                                                --     Invoice        -> client InvoiceNumber
                                                --     Vendor Invoice -> vendor InvoiceNumber
                                                --     Payment        -> CheckNumber
                                                --     Receipt        -> DepositID
                                                --     Lead           -> full name or email (tUserLead)
                                                --     Opportunity    -> LeadID (tLead)
    @ProjectNumber      varchar(100) = null,    -- Alternate scope. Returns ALL action log entries linked to the
                                                --   project via vActionLog.ProjectKey, regardless of the recorded
                                                --   Entity (Estimates, Vouchers, Tasks, etc. associated with that
                                                --   project all flow through). If supplied, @Entity/@EntityID are
                                                --   ignored. Passing @Entity=''Project'' + @EntityID is equivalent.
    @StartDate          datetime     = null,
    @EndDate            datetime     = null,
    @UTCOffsetHours     int          = 0,
    @MaxRows            int          = 500
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 07/10/25  AI  25.07.10   Created - AI action log query by project or user with date range
|| 07/10/25  AI  25.07.10   Added @UTCOffsetHours to convert local dates to UTC before comparing ActionDate
|| 05/25/26  AI  26.05.25   Replaced project/user-only filtering with generic @Entity + @EntityKey path.
|| 05/25/26  AI  26.05.25   Record-level access delegated to spCheckAccess.
|| 05/28/26  AI  26.05.28   spCheckAccess gating per resolved entity.
|| 05/28/26  AI  26.05.28   Reworked to match spApiAIGetConversations: dropped @Username and switched
||                          @EntityKey (int) -> @EntityID (business id).
|| 05/28/26  AI  26.05.28   Re-added @ProjectNumber as a separate scope path using vActionLog.ProjectKey.
|| 05/28/26  AI  26.05.28   Locked supported entity list to: Project, Contact, Company, Invoice,
||                          Vendor Invoice, Payment, Receipt, Lead, Opportunity. Unsupported entities
||                          return INVALID_VALUE ''This entity is currently not supported.''
||                          @Entity=''Project'' now folds into the @ProjectNumber path so a single
||                          code path covers project-wide queries.
*/

set nocount on

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @SecurityGroupKey       int
    declare @LogEntity              varchar(50)     -- literal value stored in tActionLog.Entity (no ''t'' prefix)
    declare @LogEntityAlt           varchar(50)     -- optional alternate literal for the same logical entity
    declare @CheckEntity            varchar(50)     -- entity name passed to spCheckAccess (with ''t'' prefix)
    declare @EffectiveEntityKey     int             -- resolved internal key
    declare @ProjectKey             int             -- resolved ProjectKey when @ProjectNumber path is used
    declare @AccessOK               int
    declare @ErrorCount             int
    declare @UTCStartDate           datetime
    declare @UTCEndDate             datetime

    -- ------------------------------------------------------------------
    -- 2. Defaults
    -- ------------------------------------------------------------------
    if @StartDate is null
        set @StartDate = DATEADD(YEAR, -10, GETUTCDATE())

    if @EndDate is null
        set @EndDate = DATEADD(YEAR, 1, GETUTCDATE())

    if @MaxRows is null or @MaxRows <= 0
        set @MaxRows = 500

    -- Same UTC adjustment as sptActionLogGetList
    set @UTCStartDate = DATEADD(HOUR, (-1 * @UTCOffsetHours), @StartDate)
    set @UTCEndDate   = DATEADD(HOUR, (-1 * @UTCOffsetHours), @EndDate)

    -- ------------------------------------------------------------------
    -- 3. Validate the user (spCheckAccess handles per-entity access below)
    -- ------------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock)
    where  UserKey    = @UserKey
      and  CompanyKey = @CompanyKey

    if @SecurityGroupKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 4. Fold @Entity=''Project'' into the @ProjectNumber path.
    --    After this block: either @ProjectNumber is set (project path) or
    --    @Entity/@EntityID drive the entity path.
    -- ------------------------------------------------------------------
    if (@ProjectNumber is null or LTRIM(RTRIM(@ProjectNumber)) = '''')
       and @Entity is not null
       and UPPER(LTRIM(RTRIM(@Entity))) = ''PROJECT''
    begin
        set @ProjectNumber = @EntityID
        set @Entity        = null
        set @EntityID      = null
    end

    declare @HasEntityScope  bit = case when @Entity        is not null and LTRIM(RTRIM(@Entity))        <> '''' then 1 else 0 end
    declare @HasProjectScope bit = case when @ProjectNumber is not null and LTRIM(RTRIM(@ProjectNumber)) <> '''' then 1 else 0 end

    if @HasProjectScope = 0 and @HasEntityScope = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'',
                ''Either projectNumber, or entity + entityID, is required.'', ''entity'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -100
    end

    -- When projectNumber is supplied, entity/entityID are ignored.
    -- Otherwise both entity and entityID are required.
    if @HasProjectScope = 0
       and @HasEntityScope = 1
       and (@EntityID is null or LTRIM(RTRIM(@EntityID)) = '''')
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''entityID is required when entity is supplied.'', ''entityID'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -100
    end

    -- ------------------------------------------------------------------
    -- 5a. @ProjectNumber path: resolve ProjectKey, gate via spCheckAccess,
    --     then filter on vActionLog.ProjectKey (returns every action
    --     linked to the project, including Estimate/Voucher/Task rows).
    -- ------------------------------------------------------------------
    if @HasProjectScope = 1
    begin
        select @ProjectKey = ProjectKey
        from   tProject (nolock)
        where  CompanyKey    = @CompanyKey
          and  ProjectNumber = @ProjectNumber

        if @ProjectKey is null
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', ''Project not found for projectNumber: '' + @ProjectNumber, ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName

            drop table #errors
            return -101
        end

        exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey

        if @AccessOK <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''User does not have access to this Project.'', ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName

            drop table #errors
            return -103
        end

        -- Warnings (consistent shape; usually empty here)
        select errorType, errorCode, errorMessage, fieldName
        from   #errors where errorType = ''warning''

        -- Data: filter on vActionLog.ProjectKey, not Entity/EntityKey
        select top (@MaxRows)
                al.Action                as action,
                al.ActionDate            as actionDate,
                al.ActionBy              as actionBy,
                al.Comments              as comments,
                al.Reference             as reference,
                al.FullProjectName       as fullProjectName,
                al.ClientName            as clientName,
                ''Project''                as requestedEntity,
                @ProjectNumber           as requestedEntityID
        from    vActionLog al (nolock)
        where   al.CompanyKey   = @CompanyKey
          and   al.ProjectKey   = @ProjectKey
          and   al.ActionDate  >= @UTCStartDate
          and   al.ActionDate  <= @UTCEndDate
        order by al.ActionDate desc

        drop table #errors
        return 0
    end

    -- ------------------------------------------------------------------
    -- 5b. Resolve @Entity + @EntityID -> @LogEntity (+ optional @LogEntityAlt)
    --     + @CheckEntity + @EffectiveEntityKey.
    --     @LogEntity is the literal string stored in tActionLog.Entity (no ''t'').
    --     @CheckEntity is the spCheckAccess entity name (with ''t'').
    -- ------------------------------------------------------------------
    declare @EntityNorm varchar(50) = UPPER(LTRIM(RTRIM(@Entity)))

    -- ---- Contact (record lives in tUser) ------------------------------
    if @EntityNorm = ''CONTACT''
    begin
        set @LogEntity   = ''Contact''
        set @CheckEntity = ''tUser_Contact''

        select top 1 @EffectiveEntityKey = UserKey
        from   tUser (nolock)
        where  CompanyKey = @CompanyKey
          and  (   UPPER(FirstName + '' '' + LastName) = UPPER(@EntityID)
                or UPPER(Email) = UPPER(@EntityID) )
    end

    -- ---- Company (client or vendor) -----------------------------------
    else if @EntityNorm = ''COMPANY''
    begin
        set @LogEntity   = ''Company''
        set @CheckEntity = ''tCompany''

        select @EffectiveEntityKey = CompanyKey
        from   tCompany (nolock)
        where  OwnerCompanyKey = @CompanyKey
          and  (   UPPER(CustomerID)  = UPPER(@EntityID)
                or UPPER(VendorID)    = UPPER(@EntityID)
                or UPPER(CompanyName) = UPPER(@EntityID) )
    end

    -- ---- Invoice (client InvoiceNumber) -------------------------------
    else if @EntityNorm = ''INVOICE''
    begin
        set @LogEntity    = ''Invoice''
        set @LogEntityAlt = ''Client Invoice''
        set @CheckEntity  = ''tInvoice''

        select @EffectiveEntityKey = MAX(InvoiceKey)
        from   tInvoice (nolock)
        where  CompanyKey    = @CompanyKey
          and  InvoiceNumber = @EntityID

    end

    -- ---- Vendor Invoice = Voucher (vendor InvoiceNumber) --------------
    else if @EntityNorm = ''VENDOR INVOICE'' or @EntityNorm = ''VOUCHER''
    begin
        set @LogEntity    = ''Voucher''
        set @LogEntityAlt = ''Vendor Invoice''
        set @CheckEntity  = ''tVoucher''

        select @EffectiveEntityKey = MAX(VoucherKey)
        from   tVoucher (nolock)
        where  CompanyKey    = @CompanyKey
          and  InvoiceNumber = @EntityID
    end

    -- ---- Payment (CheckNumber) ----------------------------------------
    else if @EntityNorm = ''PAYMENT''
    begin
        set @LogEntity   = ''Payment''
        set @CheckEntity = ''tPayment''

        select @EffectiveEntityKey = MAX(PaymentKey)
        from   tPayment (nolock)
        where  CompanyKey  = @CompanyKey
          and  CheckNumber = @EntityID
    end

    -- ---- Receipt (record lives in tDeposit, DepositID) ----------------
    else if @EntityNorm = ''RECEIPT''
    begin
        set @LogEntity    = ''Receipt''
        set @LogEntityAlt = ''Deposit''
        set @CheckEntity  = ''tDeposit''

        select @EffectiveEntityKey = DepositKey
        from   tDeposit (nolock)
        where  CompanyKey = @CompanyKey
          and  UPPER(DepositID) = UPPER(@EntityID)
    end

    -- ---- Lead (a person/contact in tUserLead) -------------------------
    else if @EntityNorm = ''LEAD''
    begin
        set @LogEntity   = ''Lead''
        set @CheckEntity = ''tUserLead''

        select top 1 @EffectiveEntityKey = UserLeadKey
        from   tUserLead (nolock)
        where  CompanyKey = @CompanyKey
          and  (   UPPER(FirstName + '' '' + LastName) = UPPER(@EntityID)
                or UPPER(Email) = UPPER(@EntityID) )
    end

    -- ---- Opportunity (record lives in tLead) --------------------------
    else if @EntityNorm = ''OPPORTUNITY''
    begin
        set @LogEntity   = ''Opportunity''
        set @CheckEntity = ''tLead''

        select @EffectiveEntityKey = LeadKey
        from   tLead (nolock)
        where  CompanyKey = @CompanyKey
          and  LeadID     = TRY_CONVERT(int, @EntityID)
    end

    -- ---- Unsupported entity -------------------------------------------
    else
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''This entity is currently not supported.'', ''entity'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -102
    end

    -- ---- Not-found check ----------------------------------------------
    if @EffectiveEntityKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', @Entity + '' not found for entityID: '' + @EntityID, ''entityID'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ---- Record-level access gate (universal) -------------------------
    exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, @CheckEntity, @EffectiveEntityKey

    if @AccessOK <> 1
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have access to this '' + @Entity + ''.'', ''entityID'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 6. Result set 1: warnings (non-fatal)
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from   #errors where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 7. Result set 2: action log for the resolved entity
    --    Filter on tActionLog.Entity = @LogEntity (or @LogEntityAlt when set)
    --    and EntityKey = @EffectiveEntityKey.
    -- ------------------------------------------------------------------
    select top (@MaxRows)

            al.Action                as action,
            al.ActionDate            as actionDate,
            al.ActionBy              as actionBy,
            al.Comments              as comments,
            al.Reference             as reference,
            al.FullProjectName       as fullProjectName,
            al.ClientName            as clientName,
            @Entity                  as requestedEntity,
            @EntityID                as requestedEntityID
    from    vActionLog al (nolock)
    where   al.CompanyKey   = @CompanyKey
      and   (al.Entity = @LogEntity or (@LogEntityAlt is not null and al.Entity = @LogEntityAlt))
      and   al.EntityKey    = @EffectiveEntityKey
      and   al.ActionDate  >= @UTCStartDate
      and   al.ActionDate  <= @UTCEndDate
    order by al.ActionDate desc

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptReportGetGraphs]'
GO
IF OBJECT_ID(N'[dbo].[sptReportGetGraphs]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptReportGetGraphs]  
 @ReportID varchar(50),  
 @UserKey int,  
 @ReportKey int = 0,  
 @AsSecurityGroupKey int = 0  
AS   
  
/*  
|| When      Who Rel      What  
|| 01/16/18  CRG 18.1.0   Added optional @ReportKey  
|| 05/11/18  GWG 18.5.0   Add new fields for the graphs  
|| 06/20/18  GWG 18.6.0   Remove any graphs with no field definition.  these are created, but not saved.  really needs to be handled differently  
|| 02/01/22  RJE 20.2.0   Add BuiltIn Widgets and support for defining reports by security group with company defaults and overrides  
|| 06/20/25  GAR 25.07.20 (688217) Adding the TabName to Widgets so they can live on a tab too
|| 08/03/26  RLS 26.09.20 (734022) Added DISTINCT to the select in the ELSE of CASE WHEN @Admin = 1
*/  
  
 DECLARE @SecurityGroupKey int,  @CompanyKey int, @Admin TINYINT, @InitialLoad TINYINT
  
 SELECT @CompanyKey = ISNULL(OwnerCompanyKey, CompanyKey)  
     ,@SecurityGroupKey = IIF(@AsSecurityGroupKey = 0, SecurityGroupKey, @AsSecurityGroupKey)  
     ,@Admin = ISNULL(Administrator, 0)  
 FROM tUser (NOLOCK)   
 WHERE UserKey = @UserKey  

 -- Checks to see if any widgets are loaded for the company and if not pre-loads for all security groups.
 IF @ReportID = ''ProjectDashboard''
 BEGIN
	 SELECT @InitialLoad = (CASE WHEN COUNT(*) > 0 THEN 0 ELSE 1 END) FROM tReport WHERE CompanyKey = @CompanyKey AND ReportID = ''ProjectDashboard'' AND ReportType IN (3,4)

	 IF @InitialLoad = 1
	 BEGIN
		 INSERT INTO tReport
				   ([Name], ReportType, Private, UserKey, CompanyKey, ReportGroupKey, ReportHeading1Align, ReportHeading2Align, Orientation, GroupBy, ShowConditions, ReportID, LockedColumns
				   , DefaultReportKey, AutoExpandGroups, ApplicationVersion, AutoRun, AddedBy, XPos, YPos, Width, Height, DisplayType, MaxItemCount, DataTargetUpper, DataTargetLower
				   , XAxisHasCField, YAxisHasCField, SeriesHasCField, DefaultReportView, WidgetEntityKey)
			 SELECT
				   [Name], 4, 0, @UserKey, @CompanyKey, 0, 1, 1, 0, 0, 0, ''ProjectDashboard'', 0
				   , 0, 1, 2, 0, @UserKey, XPos, YPos, Width, Height, WidgetID, 12, 0, 0
				   , 0, 0, 0, 0, 0
		FROM tWidgetDef wd (nolock)
			INNER JOIN tWidgetEntityAssigned wea (nolock) ON wd.WidgetDefKey = wea.WidgetDefKey
			INNER JOIN tWidgetEntity we (nolock) ON wea.WidgetEntityKey = we.WidgetEntityKey
		WHERE we.WidgetEntityKey = 1 --ProjectSingle
			AND wd.WidgetID NOT IN (''ProjectSnapshot'', ''ProjectProfitability'')

		INSERT INTO tRptSecurityGroup (ReportKey, SecurityGroupKey)
		SELECT rpt.ReportKey, sg.SecurityGroupKey FROM tSecurityGroup sg,  tReport rpt
		WHERE sg.CompanyKey = @CompanyKey AND rpt.CompanyKey = @CompanyKey AND sg.Active = 1 AND rpt.ReportType = 4 AND ReportID = ''ProjectDashboard'' -- Widget
	END
END  
 
 Delete tReport Where ReportType = 3 and Cast(ISNULL(FieldDefinition, '''') as varchar) = '''' and ReportID = @ReportID and CompanyKey = @CompanyKey  
   
   
   
   
 /*Standard Report Graphs - Overrides*/  
 SELECT r.ReportKey, r.Name, ISNULL(r.XPos, 0) as XPos, ISNULL(r.YPos, 999) as YPos, r.Width, r.Height, r.DisplayType, r.TabName, r.DataTargetUpper, r.DataTargetLower, MaxItemCount, XAxisLabel, YAxisLabel, SecurityGroupKey, 1 AS HasAccess  
 FROM tReport r (NOLOCK)   
 WHERE r.CompanyKey = @CompanyKey  
 and (@ReportKey = 0 OR @ReportKey = r.ReportKey)  
 and r.ReportID = @ReportID   
 and r.ReportType= 3  
 and r.SecurityGroupKey = @SecurityGroupKey   
 Order By r.TabName, ISNULL(r.XPos, 0), ISNULL(r.YPos, 999)  
   
   
 /*Standard Report Graphs - Company Defaults*/  
 SELECT r.ReportKey, r.Name, ISNULL(r.XPos, 0) as XPos, ISNULL(r.YPos, 999) as YPos, r.Width, r.Height, r.DisplayType, r.TabName, r.DataTargetUpper, r.DataTargetLower, MaxItemCount, XAxisLabel, YAxisLabel, 0 AS SecurityGroupKey,  
  CASE WHEN @Admin = 1 THEN 1  
  ELSE ISNULL((SELECT DISTINCT 1 FROM tRptSecurityGroup rsg (NOLOCK) WHERE  rsg.SecurityGroupKey = @SecurityGroupKey and ReportKey = r.ReportKey), 0) END as HasAccess  
 FROM tReport r (NOLOCK)   
 WHERE r.CompanyKey = @CompanyKey  
 and (@ReportKey = 0 OR @ReportKey = r.ReportKey)  
 and r.ReportID = @ReportID   
 and r.ReportType= 3  
 and r.SecurityGroupKey IS NULL   
 Order By r.TabName, ISNULL(r.XPos, 0), ISNULL(r.YPos, 999)   
   
   
 /*BuiltIn Widgets - Overrides*/  
 SELECT r.ReportKey, r.Name, ISNULL(r.XPos, 0) as XPos, ISNULL(r.YPos, 999) as YPos, r.Width, r.Height, r.DisplayType, r.Definition, SecurityGroupKey, r.TabName 
 FROM tReport r (NOLOCK)   
 WHERE r.CompanyKey = @CompanyKey  
 and r.ReportID = @ReportID   
 and r.ReportType= 4  
 and r.SecurityGroupKey = @SecurityGroupKey   
 Order By r.TabName, ISNULL(r.XPos, 0), ISNULL(r.YPos, 999)  
  
  
 /*BuiltIn Widgets - Company Defaults*/  
 SELECT r.ReportKey, r.Name, ISNULL(r.XPos, 0) as XPos, ISNULL(r.YPos, 999) as YPos, r.Width, r.Height, r.DisplayType, r.Definition, 0 AS SecurityGroupKey, r.TabName    
 FROM tReport r (NOLOCK)   
 WHERE r.CompanyKey = @CompanyKey  
 and r.ReportID = @ReportID   
 and r.ReportType= 4  
 and r.SecurityGroupKey IS NULL   
 -- THIS IS GAR CODE TO RESTRICT WIDGETS TO CERTAIN SECURITY GROUPS
 and (ISNULL((SELECT DISTINCT 1 FROM tRptSecurityGroup rsg (NOLOCK) WHERE  rsg.SecurityGroupKey = @SecurityGroupKey and ReportKey = r.ReportKey), 0) = 1 or @Admin = 1)
 Order By r.TabName, ISNULL(r.XPos, 0), ISNULL(r.YPos, 999)  
   
  
 /*All SecurityGroups with indicator for overrides*/  
 --IF @Admin = 1   
  SELECT sg.SecurityGroupKey, sg.GroupName,  
  ISNULL((SELECT DISTINCT 1 FROM tReport r (NOLOCK) WHERE  r.SecurityGroupKey = sg.SecurityGroupKey AND r.ReportID = @ReportID AND r.CompanyKey = sg.CompanyKey GROUP BY r.SecurityGroupKey), 0) as HasOverrides  
  FROM  tSecurityGroup sg (NOLOCK)   
  WHERE Active = 1  
  AND CompanyKey = @CompanyKey  '
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptRetainerUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptRetainerUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptRetainerUpdate]
	@RetainerKey int,
	@UserKey int,
	@CompanyKey int,
	@ClientKey int,
	@Title varchar(200),
	@StartDate smalldatetime,
	@Frequency smallint,
	@NumberOfPeriods int,
	@AmountPerPeriod money,
	@LastBillingDate smalldatetime,
	@IncludeLabor tinyint,
	@IncludeExpense tinyint,
	@CustomFieldKey int,
	@LineFormat smallint,
	@InvoiceApprovedBy int,
	@Active tinyint,
	@InvoiceExpensesSeperate tinyint,
	@SalesAccountKey int,
	@GLCompanyKey int,
	@OfficeKey int,
	@Description text,
	@ClassKey int,
	@ContactKey int,
	@BillingManagerKey int,
	@CurrencyID varchar(10) = null,
	@CostPerPeriod money = null,
	@InvoiceTemplateKey int = null,
	@LayoutKey int = null,
	@DepartmentKey int,
	@AvalaraTaxCodeKey int = NULL,
	@BillExpensesByItem tinyint = NULL

AS --Encrypt

  /*
  || When     Who Rel   What
  || 07/05/07 GHL 8.5   Added GLCompanyKey + OfficeKey  
  || 09/20/07 GHL 8.437 (Enh 13169) Added new field Description
  || 12/17/07 GHL 8.5   (Enh 17879) Added ClassKey
  || 06/19/08 GHL 8.514 (13169) Changed description to text from varchar(1500)
  || 11/04/11 RLB 10549 Added insert logic 
  || 08/15/12 GHL 10559 Added check of GL company on projects  
  || 08/22/12 RLB 10559 (87856) Added ContactKey  
  || 11/06/12 GHL 10562 Added update of tForecast.RegenerateNeeded
  || 01/21/13 MAS 10564 Added logging
  || 10/07/13 GHL 10573 Added CurrencyID for multi currency
  || 12/20/13 WDF 10575 (198697) Added BillingManagerKey
  || 04/07/14 GHL 10579 Added CostPerPeriod for revenue forecast
  || 04/15/16 MFT 10602 Added @SetAllServices and logic to default in all Services when @IncludeLabor has been selected
  || 03/24/17 MFT 10614 Added @SetAllExpenses and logic to default in all Expenses when @IncludeExpense has been selected
  || 11/07/17 DDM DEV1784 (todo) Add InvoiceTemplateKey and LayoutKey
  || 05/12/18 GWG 18.6  Adding Retainer ID
  || 03/25/21 GHL 21.04.18 (553141) Limit the number of periods to avoid overflows in forecasts
  ||                       for quarters, limit is 120
  || 08/15/22 AMP 22.09.18 (604178) Added Department as an option on the Retainer Setup if GL Tracking Options has Show/Require Depts enabled
  || 02/19/24 GAR 24.03.17 (665083) Added AvalaraTaxCodeKey
  || 07/28/26 MFT 26.08.01 (708954) Added BillExpensesByItem (Retainer extra charges billed one line per Item/Service)
  */

DECLARE @Date smalldatetime, @SetAllServices bit, @SetAllExpenses bit

SELECT @Date = GETUTCDATE(), @SetAllServices = 0, @SetAllExpenses = 0

SELECT @BillExpensesByItem = ISNULL(@BillExpensesByItem, 0)

-- small dates are limited to 2079
-- limit to 30 years or 360 months or  120 quarters or 1560 weeks

if @Frequency = 1 and @NumberOfPeriods > 360
	select @NumberOfPeriods = 0 -- no limit

if @Frequency = 2 and @NumberOfPeriods > 120
	select @NumberOfPeriods = 0 -- no limit

if @Frequency = 3 and @NumberOfPeriods > 30
	select @NumberOfPeriods = 0 -- no limit

if @Frequency = 4 and @NumberOfPeriods > 1560
	select @NumberOfPeriods = 0 -- no limit

if @RetainerKey > 0
BEGIN
	DECLARE @UseGLCompany INT
	DECLARE @OldGLCompanyKey INT
	DECLARE @OldActive INT
	DECLARE @MultiCurrency INT
	DECLARE @OldIncludeLabor tinyint
	DECLARE @OldIncludeExpense tinyint
	
	SELECT @UseGLCompany = isnull(UseGLCompany, 0)
	      ,@MultiCurrency = isnull(MultiCurrency, 0) 
	FROM tPreference (nolock)  where CompanyKey = @CompanyKey 

	IF @UseGLCompany = 1
	BEGIN
		IF EXISTS (SELECT 1 FROM tProject (NOLOCK) 
			WHERE CompanyKey = @CompanyKey
			AND   BillingMethod = 3 -- retainer
			AND   RetainerKey = @RetainerKey
			AND   isnull(GLCompanyKey, 0) <> isnull(@GLCompanyKey, 0) )
			RETURN -1
	END

	IF @MultiCurrency = 1
	BEGIN
		IF EXISTS (SELECT 1 FROM tProject (NOLOCK) 
			WHERE CompanyKey = @CompanyKey
			AND   BillingMethod = 3 -- retainer
			AND   RetainerKey = @RetainerKey
			AND   isnull(CurrencyID, '''') <> isnull(@CurrencyID, '''') )
			RETURN -2

		IF EXISTS (SELECT 1 FROM tInvoiceLine il (NOLOCK)
				INNER JOIN tInvoice i (NOLOCK) on il.InvoiceKey = i.InvoiceKey 
			WHERE i.CompanyKey = @CompanyKey
			AND   il.RetainerKey = @RetainerKey
			AND   isnull(i.CurrencyID, '''') <> isnull(@CurrencyID, '''') )
			RETURN -3

	END

	SELECT @OldGLCompanyKey = GLCompanyKey,
		   @OldActive = ISNULL(Active, 0),
		   @OldIncludeLabor = ISNULL(IncludeLabor, 0),
		   @OldIncludeExpense = ISNULL(IncludeExpense, 0)
	FROM   tRetainer (nolock)
	WHERE  RetainerKey = @RetainerKey
	
	IF @OldActive <> @Active
	BEGIN
		IF @Active = 1
			EXEC sptActionLogInsert ''Retainer'',@RetainerKey, @CompanyKey, 0, ''Active'', @Date, NULL, ''Retainer marked active'', @Title, NULL, @UserKey  
		ELSE
			EXEC sptActionLogInsert ''Retainer'',@RetainerKey, @CompanyKey, 0, ''Inactive'', @Date, NULL, ''Retainer marked inactive'', @Title, NULL, @UserKey  
	END
	
	IF @OldIncludeLabor = 0 AND @IncludeLabor = 1
		SET @SetAllServices = 1
	IF @OldIncludeExpense = 0 AND @IncludeExpense = 1
		SET @SetAllExpenses = 1
	
	UPDATE
		tRetainer
	SET
		CompanyKey = @CompanyKey,
		ClientKey = @ClientKey,
		Title = @Title,
		StartDate = @StartDate,
		Frequency = @Frequency,
		NumberOfPeriods = @NumberOfPeriods,
		AmountPerPeriod = @AmountPerPeriod,
		LastBillingDate = @LastBillingDate,
		IncludeLabor = @IncludeLabor,
		IncludeExpense = @IncludeExpense,
		BillExpensesByItem = @BillExpensesByItem,
		CustomFieldKey = @CustomFieldKey,
		Active = @Active,
		LineFormat = @LineFormat,
		InvoiceApprovedBy = @InvoiceApprovedBy,
		InvoiceExpensesSeperate = @InvoiceExpensesSeperate,
		SalesAccountKey = @SalesAccountKey,
		GLCompanyKey = @GLCompanyKey,
		OfficeKey = @OfficeKey,
		Description = @Description,
		ClassKey = @ClassKey,
		ContactKey = @ContactKey,
		BillingManagerKey = @BillingManagerKey,
		CurrencyID = @CurrencyID,
		CostPerPeriod = @CostPerPeriod,
		InvoiceTemplateKey = @InvoiceTemplateKey,
		LayoutKey = @LayoutKey,
		DepartmentKey = @DepartmentKey,
		AvalaraTaxCodeKey = @AvalaraTaxCodeKey
	WHERE
		RetainerKey = @RetainerKey
		
	if isnull(@OldGLCompanyKey, 0) <> isnull(@GLCompanyKey, 0)
		delete tForecastDetail
		where  Entity = ''tRetainer''
		and    EntityKey = @RetainerKey
	else		 
		update tForecastDetail
		set    tForecastDetail.RegenerateNeeded = 1
		where  Entity = ''tRetainer''
		and    EntityKey = @RetainerKey
			 
END
ELSE
BEGIN

	Declare @RetainerID int
	Select @RetainerID = ISNULL(Max(RetainerID), 0) + 1 from tRetainer (nolock) 
	Where CompanyKey = @CompanyKey   

	INSERT tRetainer
		(
		CompanyKey,
		ClientKey,
		Title,
		StartDate,
		Frequency,
		NumberOfPeriods,
		AmountPerPeriod,
		LastBillingDate,
		IncludeLabor,
		IncludeExpense,
		BillExpensesByItem,
		CustomFieldKey,
		LineFormat,
		InvoiceApprovedBy,
		Active,
		InvoiceExpensesSeperate,
		SalesAccountKey,
		GLCompanyKey,
		OfficeKey,
		Description,
		ClassKey,
		ContactKey,
		BillingManagerKey,
		CurrencyID,
		CostPerPeriod, 
		InvoiceTemplateKey,
		LayoutKey,
		RetainerID,
		DepartmentKey,
		AvalaraTaxCodeKey
		)

	VALUES
		(
		@CompanyKey,
		@ClientKey,
		@Title,
		@StartDate,
		@Frequency,
		@NumberOfPeriods,
		@AmountPerPeriod,
		@LastBillingDate,
		@IncludeLabor,
		@IncludeExpense,
		@BillExpensesByItem,
		@CustomFieldKey,
		@LineFormat,
		@InvoiceApprovedBy,
		@Active,
		@InvoiceExpensesSeperate,
		@SalesAccountKey,
		@GLCompanyKey,
		@OfficeKey,
		@Description,
		@ClassKey,
		@ContactKey,
		@BillingManagerKey,
		@CurrencyID,
		@CostPerPeriod,
		@InvoiceTemplateKey,
		@LayoutKey,
		@RetainerID,
		@DepartmentKey,
		@AvalaraTaxCodeKey
		)

	SELECT
		@RetainerKey = @@IDENTITY,
		@SetAllServices = @IncludeLabor,
		@SetAllExpenses = @IncludeExpense
	
	EXEC sptActionLogInsert ''Retainer'',@RetainerKey, @CompanyKey, 0, ''Created'', @Date, NULL, ''Retainer Created'', @Title, NULL, @UserKey  
END

	
IF @SetAllServices = 1
	BEGIN
		INSERT INTO tRetainerItems
		SELECT
			@RetainerKey,
			ServiceKey,
			''tService''
		FROM tService (nolock)
		WHERE
			CompanyKey = @CompanyKey AND
			Active = 1 AND
			ServiceKey NOT IN (SELECT EntityKey FROM tRetainerItems (nolock) WHERE RetainerKey = @RetainerKey AND Entity = ''tService'')
	END

IF @SetAllExpenses = 1
	BEGIN
		INSERT INTO tRetainerItems
		SELECT
			@RetainerKey,
			ItemKey,
			''tItem''
		FROM tItem (nolock)
		WHERE
			CompanyKey = @CompanyKey AND
			Active = 1 AND
			ItemKey NOT IN (SELECT EntityKey FROM tRetainerItems (nolock) WHERE RetainerKey = @RetainerKey AND Entity = ''tItem'')
	END
	RETURN @RetainerKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptBillingScheduleGetList]'
GO
IF OBJECT_ID(N'[dbo].[sptBillingScheduleGetList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptBillingScheduleGetList]
	@ProjectKey int = NULL,
	@CampaignKey int = NULL

AS --Encrypt

  /*
  || When     Who Rel    What
  || 07/15/13 GHL 10.570 (182036) Added PercentBudget 
  || 01/15/16 MFT 10.600 Added tInvoice join & fields
  || 10/06/17 GHL 10.621 (366896) Added invoice info from tBillingSchedule.InvoiceKey 
  || 10/25/17 MCM 10.621 (ToDo 312844) Adding DollarAmount field
  || 10/31/17 GHL 10.621 Changed display order, no date at the end
  || 09/25/18 GHL 18.910 (403873) Include now an estimated dollar amount when there is a % budget
  || 10/03/18 GHL 18.920 (396483) Added the project''s billing method to show the advance bill flag on the bill schedule grid
  || 04/15/20 GHL 20.050 (510216) Added invoiced amount to display on the billing schedule grid
  || 06/18/20 GHL 20.080 (519568) Added mention ''Pending Invoice'' when InvoiceNumber is blank (only set at approval)
  || 04/12/21 MFT 21.050 (455922) Added @CampaignKey and Campaign query
  || 06/18/21 GHL 21.070 (562337) When the users bill projects by client, the Invoiced Amount should be recalculated
  ||                     based on the project. i.e. do not take the invoiced amounts
  ||11/29/23 AMP 23.12.17 (643007) Added Invoiced Amount to display on the billing schedule grid for Campaigns
  ||12/21/23 AMP 24.01.21 (628292) For the campaign billing schedule display the original scheduled amount even after an invoice has been applied
  ||07/08/26 AMP 26.07.19 (729259) Return BilledComment for project billing schedule rows
  ||07/14/26 AMP 26.07.19 (729259) Return BilledComment for campaign billing schedule rows
  ||07/30/26 MFT 26.07.30 (729259) Change "Pending Invoice" to "Invoice" and date for consistency with the project billing schedule.
  */

	declare @BudgetAmount money
	declare @LaborBudget money
	declare @ExpensesBudget money
	declare @ExpensesNotIncluded int
	declare @BillingMethod int

	IF ISNULL(@ProjectKey , 0) > 0

		select @ExpensesNotIncluded = isnull(ExpensesNotIncluded, 0)
					,@LaborBudget = ISNULL(EstLabor, 0) + ISNULL(ApprovedCOLabor, 0)
				,@ExpensesBudget = ISNULL(EstExpenses, 0) + ISNULL(ApprovedCOExpense, 0)
				,@BillingMethod = isnull(BillingMethod, 0) 
		from   tProject (nolock)
		where  ProjectKey = @ProjectKey
	ELSE
		SELECT
			@ExpensesNotIncluded = ISNULL(ExpensesNotIncluded, 0),
			@LaborBudget = ISNULL(EstLabor, 0) + ISNULL(ApprovedCOLabor, 0),
			@ExpensesBudget = ISNULL(EstExpenses, 0) + ISNULL(ApprovedCOExpense, 0),
			@BillingMethod = isnull(UseCampaignBudget, 0)
		FROM tCampaign (nolock)
		WHERE CampaignKey = @CampaignKey

	if @ExpensesNotIncluded = 0
		-- expenses are included
		select @BudgetAmount = isnull(@LaborBudget,0) + isnull(@ExpensesBudget,0)
	else
		-- expenses are not included
		select @BudgetAmount = isnull(@LaborBudget,0) 

	IF ISNULL(@ProjectKey , 0) > 0

		select bs.BillingScheduleKey
					,bs.NextBillDate
					,case when bs.NextBillDate is null then 99
					else 1 end as DisplayOrder
					,bs.TaskKey
					,t.TaskID
					,t.TaskName
					,case 
				when t.TaskID is null then TaskName 
				else t.TaskID + '' '' + t.TaskName 
				 end as TaskFullName
					,bs.Comments
				,bs.PercentBudget
				,bs.BilledComment

		  -- if there is an invoice we will show the invoiced amount, so calc the estimate amount if we have no invoices
		  ,case when i.InvoiceKey is null and i2.InvoiceKey is null then
			round((bs.PercentBudget * @BudgetAmount) / 100.00, 2) 
			end as EstimatedDollarAmount

				,bs.DollarAmount

				,bs.BillingKey
				,isnull(bs.AdvanceBill,0) as AdvanceBill 
					,b.BillingID
					,@ProjectKey as ProjectKey
				,@BillingMethod as BillingMethod

				-- invoice tied to the billing worksheet on the schedule
				-- OR
				-- invoice tied directly to the schedule
					,isnull(i.InvoiceKey, i2.InvoiceKey) as InvoiceKey 		
					,isnull(i.InvoiceDate,i2.InvoiceDate) as InvoiceDate

		  -- Invoice numbers may be null/missing if set on approval only.
		  -- Return the raw value; the UI shows "Invoice [InvoiceDate]" when it is blank.
		  ,case when i.InvoiceKey is not null then i.InvoiceNumber
		        else
					case when i2.InvoiceKey is not null then i2.InvoiceNumber
					else null
					end
				end as InvoiceNumber

		-- pull the total amount without taxes because budget amounts are displayed without taxes 
		
		--,case when i.InvoiceKey is not null then i.TotalNonTaxAmount  -- This is not true when they bill by client
		--		else i2.TotalNonTaxAmount
		--	end as InvoicedAmount

		-- when they bill by client, use the billed amount we calculated below
		,case when i.InvoiceKey is not null then billed.BilledAmount
				else billed2.BilledAmount
			end as InvoicedAmount

		from tBillingSchedule bs (nolock) 
			left outer join tTask t (nolock) on bs.TaskKey = t.TaskKey
			left outer join tBilling b (nolock) on bs.BillingKey = b.BillingKey
			left outer join tInvoice i (nolock) on b.InvoiceKey = i.InvoiceKey
			left outer join tInvoice i2 (nolock) on bs.InvoiceKey = i2.InvoiceKey 

			-- contribution for that project to the invoice on tBilling
			left outer join (
			select sum(isumm.Amount) as BilledAmount, isumm.InvoiceKey
			from tInvoiceSummary isumm (nolock)
			where isumm.ProjectKey = @ProjectKey
			group by isumm.InvoiceKey
			) as billed on b.InvoiceKey  = billed.InvoiceKey

			-- contribution for that project to the invoice on tBillingSchedule
			left outer join (
			select sum(isumm.Amount) as BilledAmount, isumm.InvoiceKey
			from tInvoiceSummary isumm (nolock)
			where isumm.ProjectKey = @ProjectKey
			group by isumm.InvoiceKey
			) as billed2 on bs.InvoiceKey  = billed2.InvoiceKey

		 where bs.ProjectKey = @ProjectKey
		order by DisplayOrder, bs.NextBillDate, TaskFullName
	ELSE
		SELECT
			bs.BillingScheduleKey,
			bs.NextBillDate,
			CASE WHEN bs.NextBillDate IS NULL THEN 99 ELSE 1 END AS DisplayOrder,
			bs.Comments,
			bs.PercentBudget,
			--#628292-AP - Calculate the estimated dollar amount; null if already billed (consistent with project billing schedule)
			case when i.InvoiceKey is null and i2.InvoiceKey is null then
				round((bs.PercentBudget * @BudgetAmount) / 100.00, 2)
				end as EstimatedDollarAmount,
			bs.DollarAmount,
			bs.BillingKey,
			ISNULL(bs.AdvanceBill,0) AS AdvanceBill,
			b.BillingID,
			@CampaignKey AS CampaignKey,
			@BillingMethod AS BillingMethod, --Set by UseCampaignBudget on tCampaign
			-- invoice tied to the billing worksheet on the schedule
			-- OR
			-- invoice tied directly to the schedule
			ISNULL(i.InvoiceKey, i2.InvoiceKey) AS InvoiceKey,
			ISNULL(i.InvoiceDate,i2.InvoiceDate) AS InvoiceDate,
			-- Invoice numbers may be missing if set on approval only
			CASE WHEN i.InvoiceKey IS NOT NULL THEN i.InvoiceNumber ELSE i2.InvoiceNumber END AS InvoiceNumber
	       ,CASE WHEN i.InvoiceKey IS NOT NULL THEN i.InvoiceTotalAmount ELSE i2.InvoiceTotalAmount END AS InvoicedAmount
	       ,bs.BilledComment
		FROM
			tBillingSchedule bs (nolock)
			LEFT JOIN tBilling b (nolock) ON bs.BillingKey = b.BillingKey
			LEFT JOIN tInvoice i (nolock) ON b.InvoiceKey = i.InvoiceKey
			LEFT JOIN tInvoice i2 (nolock) ON bs.InvoiceKey = i2.InvoiceKey
		WHERE bs.CampaignKey = @CampaignKey
		ORDER BY DisplayOrder, bs.NextBillDate

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptRetainerGetAmount]'
GO
IF OBJECT_ID(N'[dbo].[sptRetainerGetAmount]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptRetainerGetAmount]
	(
		@RetainerKey INT
	    ,@InvoiceDate DATETIME
	    ,@RetainerAmount MONEY OUTPUT
	)
AS --Encrypt

  /*
  || When     Who Rel   What
  || 08/15/08 GHL 10.006 And GWG and RB. Corrected @NumberOfPeriodsBilled       
  || 09/15/08 GHL 10.008 (34396) Number of periods billed was incorrect 
  ||                     when users enter fixed fee manually
  || 10/02/08 GHL 10.010 (36622) Basing now decision to bill retainer upon LastBillingDate only 
  ||                     and not the number of invoices per period since Hawse Design keeps on
  ||                     entering fixed fee invoices for the current period
  || 
  ||                     tRetainer.LastBillingDate is set by:
  ||                     1) mass billing: spMassBillingBillRetainer --> spProcessWIPWorksheetRetainer
  ||                     2) billing WS:   spBillingInvoiceBill	    --> spBillingInvoiceRetainer  
  ||                     OR on the retainer detail 
  || 01/02/09 GHL 10.015 (43190) In the case of Yearly frequency, consider LastBillingDate + 1 year
  ||                     instead of LastBillingDate + 1 year then January 1st for that year
  || 08/28/09 GHL 10.5   (60241) Return now -1 when not the time to bill, we allow now for 0 amount
  || 01/22/10 GHL 10.517 (69011) Using now the stored procedure return to determine whether it is
  ||                      time to bill or not since we can now have retainer amounts <0, =0, >0
  ||                      1 -- Can Bill
  ||                      0 -- Cannot Bill
  || 10/06/11 GHL 10.549 (122952) when StartDate = 10/13/2010, EndDate should be 10/13/2011 not 10/1/2011
  ||                     Removed change of 10/13/2011 to 10/1/2011
  || 12/04/17 GHL 10.622  Limit #Periods to 1000 to prevent overflows
  || 03/13/18 GHL 18.4.0 (390830) After 10 years of operation, the logic for NumberOfPeriodsBilled is back
  ||                      Spawn/Nerland has a retainer start date 10/26/17 and # of periods = 4
  ||                      They are able to bill 5 invoices using billing worksheets, invoice dates are
  ||                      10/31/17, 11/20/17, 12/15/17, 1/17/18, 2/22/18
  ||                      The problem is that the first billing should have been on 11/20/17. A possible fix
  ||                      is to calculate the NumberOfPeriodsBilled from invoices linked to billing worksheets
  || 05/08/18 GHL 18.6.0  (400364) When calculating NumberOfPeriodsBilled, make sure that BillFrom = 1  No Transactions
  ||                       if BillFrom = 2 Use Transactions, that means extra expenses/labor
  || 03/13/19 GHL 19.4.0  (436087) Added support for weekly retainer
  || 09/13/19 GHL 19.1.0  (478241) For monthly retainers, they should not show up until they are due
  ||                       Ex: LastBillingDate = 8/15/19, show retainers if date >= 9/15/19 (not date >= 9/1/19)  
  || 10/02/19 GHL 19.1.0  (481941) When calculating NumberOfPeriodsBilled, filter out lines with projects
  ||                       The retainer amount is entered on a line without project. If there is a project, that was entered 
  ||                       manually by the users.
  || 02/22/22 GHL 22.3.0  (585318) Added frequency = twice a year
  || 05/12/22 MFT 22.6.0  (598581) bringing NumberOfPeriodsBilled into alignment with sptRetainerSnapshot and the Retainer edit screen
  || 06/03/22 GHL 22.6.0  (601725) For NumberOfPeriodsBilled put back the i.BillingKey > 0 and ProjectKey > 0
  ||                       because this is changing the way users doing mass billing do business (vs BWS people)
  ||                       and there should not be a project on the line if this is a true retainer billing line
  ||                       The thing that I keep from 598581 is that we should not be taking duplicate invoices
  || 04/02/26 MFT 26.5.0  (665301) Set monthly billing retainer bill date based on the day of the StartDate, not the LastBilledDate
  || 08/06/26 MCM 26.9.x  (734708) Updated logic on the NextBillingDate to allow for the invoice date to be on the same day as the NextBillingDate
  */
  

	SET NOCOUNT ON
	
	DECLARE @kCAN_BILL INT SELECT @kCAN_BILL = 1
	DECLARE @kCANNOT_BILL INT SELECT @kCANNOT_BILL = 0
	
	DECLARE @CompanyKey INT
			,@NumberOfPeriods INT		-- If 0 means infinite
			,@NumberOfPeriodsBilled INT
			,@Frequency SMALLINT		-- 1: monthly, 2: quaterly, 3: yearly, 4:weekly
			,@LastBillingDate DATETIME
			,@StartDate DATETIME
			,@NextBillingDate DATETIME
			,@NextEndBillingDate DATETIME
			,@EndDate DATETIME -- This will be the final billing date + 1 day. We will abort if @InvoiceDate >= @EndDate
			,@BillDay tinyint
			
		SELECT @CompanyKey = CompanyKey
			   ,@NumberOfPeriods = NumberOfPeriods
			   ,@RetainerAmount = AmountPerPeriod
			   ,@Frequency = Frequency
			   ,@LastBillingDate = LastBillingDate
			   ,@StartDate = StartDate
			   ,@BillDay = DAY(StartDate)
		FROM   tRetainer (NOLOCK) 
		WHERE  RetainerKey = @RetainerKey
			
		-- Abort if the invoice date is before the start	
		IF @InvoiceDate < @StartDate
		begin
			--select 1 as debug
			RETURN @kCANNOT_BILL
		end

		-- Calculate the end date, if number of periods > 0 (number of periods = 0, we allow invoice)
		IF @NumberOfPeriods > 0
		BEGIN
			-- datetime are limited to 12/31/9999
			if @NumberOfPeriods >= 1000
					select @NumberOfPeriods = 1000

			IF @Frequency = 1
			BEGIN
				SELECT @EndDate = DATEADD(m, @NumberOfPeriods, @StartDate) 
				--SELECT @EndDate = CAST(DATEPART(m, @EndDate) AS VARCHAR(2)) + ''/1/''+CAST(DATEPART(yy, @EndDate) AS VARCHAR(4))  
			END
			
			IF @Frequency = 2
			BEGIN
			    SELECT @EndDate = DATEADD(m, 3 * @NumberOfPeriods, @StartDate) -- Add 3 months * # of periods
				SELECT @EndDate = CAST(DATEPART(m, @EndDate) AS VARCHAR(2)) + ''/1/''+CAST(DATEPART(yy, @EndDate) AS VARCHAR(4))  
				
			END
			
			IF @Frequency = 3
			BEGIN
				SELECT @EndDate = DATEADD(yy, @NumberOfPeriods, @StartDate) -- Add 1 year * # of periods
				SELECT @EndDate =  ''1/1/''+CAST(DATEPART(yy, @EndDate) AS VARCHAR(4))  
			END
			
			IF @Frequency = 4
			BEGIN
				SELECT @EndDate = DATEADD(wk, @NumberOfPeriods, @StartDate) 
			END
			
			-- Twice a year =  6 months
			IF @Frequency = 5
			BEGIN
			    SELECT @EndDate = DATEADD(m, 6 * @NumberOfPeriods, @StartDate) -- Add 3 months * # of periods
				SELECT @EndDate = CAST(DATEPART(m, @EndDate) AS VARCHAR(2)) + ''/1/''+CAST(DATEPART(yy, @EndDate) AS VARCHAR(4))  
				
			END

			-- Abort, if the invoice date is after or ON the end date of the last period	
			IF @InvoiceDate >= @EndDate
			begin
				--select 2 as debug
				RETURN @kCANNOT_BILL
			end

			/*
			-- fix for 390830
			SELECT @NumberOfPeriodsBilled = COUNT(il.InvoiceLineKey)
			FROM tInvoiceLine il (NOLOCK)
			INNER JOIN tInvoice i (NOLOCK) ON il.InvoiceKey = i.InvoiceKey
			WHERE il.RetainerKey = @RetainerKey -- there is an index on Retainer
			AND   isnull(il.ProjectKey, 0) = 0 -- the retainer amount should not have a project. If there is a project, that has been entered manually by user
			AND   il.BillFrom = 1  -- must have a invoice line that does NOT use transactions -- fix for 400364
			AND   i.BillingKey > 0 -- must be linked to a EBWS
			*/
			
			--598581, 579419; counting Invoices, not lines; not requiring a BWS; allowing a Project; not allowing AB
			SELECT @NumberOfPeriodsBilled = COUNT(*)
			FROM
				tInvoice i (nolock)
				INNER JOIN (
					SELECT InvoiceKey, RetainerKey
					FROM tInvoiceLine (nolock)
					WHERE	BillFrom = 1 AND RetainerKey = @RetainerKey
					-- put back line below for issue 601725
					AND   isnull(ProjectKey, 0) = 0 -- the retainer amount should not have a project. If there is a project, that has been entered manually by user
					GROUP BY InvoiceKey, RetainerKey
				) il ON i.InvoiceKey = il.InvoiceKey
			WHERE i.AdvanceBill = 0
			AND   i.BillingKey > 0 -- must be linked to a EBWS ... put back for issue 601725

			--select @NumberOfPeriodsBilled as NumberOfPeriodsBilled, @NumberOfPeriods as NumberOfPeriods-
			IF @NumberOfPeriodsBilled > @NumberOfPeriods
			begin
				--select 3 as debug
				RETURN @kCANNOT_BILL
			end
		END

		IF @LastBillingDate IS NOT NULL
		BEGIN
			IF @Frequency = 1
			BEGIN
				DECLARE @NextMonth datetime
				SELECT  @NextMonth = DATEADD(m, 1, @LastBillingDate)
				SELECT  @NextBillingDate = LTRIM(STR(MONTH(@NextMonth))) + ''/'' + LTRIM(STR(@BillDay)) + ''/'' + LTRIM(STR(YEAR(@NextMonth)))
				IF @LastBillingDate >= @NextBillingDate
					BEGIN
						RETURN @kCANNOT_BILL
					END

				SELECT @NextEndBillingDate = DATEADD(m, 1,@NextBillingDate)
				SELECT @NextEndBillingDate = DATEADD(d, -1,@NextEndBillingDate)
			END
			IF @Frequency = 2
			BEGIN
				-- Add a quarter or 3 months
				SELECT @NextBillingDate = DATEADD(m, 3, @LastBillingDate)
				-- Any invoice date after or on the first of the MONTH will be fine
				SELECT @NextBillingDate = CAST(DATEPART(m, @NextBillingDate) AS VARCHAR(2)) + ''/1/''+CAST(DATEPART(yy, @NextBillingDate) AS VARCHAR(4))  
				SELECT @NextEndBillingDate = DATEADD(m, 3,@NextBillingDate)
				SELECT @NextEndBillingDate = DATEADD(d, -1,@NextEndBillingDate)
			END
			IF @Frequency = 3
			BEGIN
				-- Add a year
				SELECT @NextBillingDate = DATEADD(yy, 1, @LastBillingDate)
				-- Any invoice date after or on the first of the YEAR  will be fine
				--SELECT @NextBillingDate = ''1/1/''+CAST(DATEPART(yy, @NextBillingDate) AS VARCHAR(4))  
				SELECT @NextEndBillingDate = ''12/31/''+CAST(DATEPART(yy, @NextBillingDate) AS VARCHAR(4))  
			
			END
			
			IF @Frequency = 4
			BEGIN
				-- Add a week
				SELECT @NextBillingDate = DATEADD(wk, 1, @LastBillingDate) 
			END

			IF @Frequency = 5
			BEGIN
				-- Add a 1/2 year or 6 months
				SELECT @NextBillingDate = DATEADD(m, 6, @LastBillingDate)
				-- Any invoice date after or on the first of the MONTH will be fine
				SELECT @NextBillingDate = CAST(DATEPART(m, @NextBillingDate) AS VARCHAR(2)) + ''/1/''+CAST(DATEPART(yy, @NextBillingDate) AS VARCHAR(4))  
				SELECT @NextEndBillingDate = DATEADD(m, 6,@NextBillingDate)
				SELECT @NextEndBillingDate = DATEADD(d, -1,@NextEndBillingDate)
			END

			-- Do not create if not in range
			IF @InvoiceDate < @NextBillingDate
			begin
				--select 4 as debug
				RETURN @kCANNOT_BILL 
			end
		END	
		
		RETURN @kCAN_BILL'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateFromHistory]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateFromHistory]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateFromHistory]
	@ActivityKey int,
	@UpdateField varchar(50),
	@Completed tinyint,
	@UserKey int,
	@Subject nvarchar(4000) = null,
	@AssignedUserKey int = null,
	@ActivityTypeKey int = null,
	@ActivityDate smalldatetime = null,
	@Notes nvarchar(max) = null,
	@TaskKey int = null,
	@DisplayOrder int = null
AS

/*
|| When      Who Rel      What
|| 5/4/10    CRG 10.5.2.1 Created to update only one field at a time from the Activity History screen. Other than ActivityKey and Completed,
||                        a maximum of only one parm will be NOT NULL at a time, and that field will be the one that is updated.
|| 7/16/10   CRG 10.5.3.2 Added UpdateField and TaskKey. UpdateField is used to determine which field was updated, rather than just checking for NOT NULL from the fields.
||                        Otherwise, a field could never be blanked out from the History component.
|| 3/21/12   RLB 10.5.5.4 Adding Display Order to be updated
|| 4/20/12   RLB 10.5.5.5 Made some Changes on how to handle if a null TaskKey is passed in 
|| 03/03/14  GWG 10.5.7.8 Added support for clearing the read flag
|| 08/17/16  KMC 10.6.0.7 (310534) Added update to DateUpdated and UpdatedByKey
|| 05/26/20  CRG 20.0.7.0 (516752) Converted Notes to nvarchar
|| 06/23/20  RLS 20.0.7.0 (518686) Converted Subject to nvarchar
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time/this proc seems to be no longer used
*/

	IF @UpdateField = ''Completed''
	BEGIN
		DECLARE @DateCompleted smalldatetime
		IF @Completed = 1
			SELECT @DateCompleted = dbo.fFormatDateNoTime(GETDATE())
	
		UPDATE	tActivity
		SET		Completed = @Completed,
				DateCompleted = @DateCompleted,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey
	END

	IF @UpdateField = ''Subject''
		UPDATE	tActivity
		SET		Subject = @Subject,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey

	IF @UpdateField = ''AssignedUserKey''
		UPDATE	tActivity
		SET		AssignedUserKey = @AssignedUserKey,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey
		
	IF @UpdateField = ''ActivityTypeKey''
		UPDATE	tActivity
		SET		ActivityTypeKey = @ActivityTypeKey,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey
		
	IF @UpdateField = ''ActivityDate''
		UPDATE	tActivity
		SET		ActivityDate = @ActivityDate,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey

	IF @UpdateField = ''Notes''
		UPDATE	tActivity
		SET		Notes = @Notes,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey

	IF @UpdateField = ''DisplayOrder''
		UPDATE	tActivity
		SET		DisplayOrder = @DisplayOrder,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey
		WHERE	ActivityKey = @ActivityKey

	IF @UpdateField = ''TaskKey''
	BEGIN
		DECLARE	@OldTaskKey int
		SELECT	@OldTaskKey = TaskKey
		FROM	tActivity (nolock)
		WHERE	ActivityKey = @ActivityKey

		IF ISNULL(@TaskKey, 0) <> ISNULL(@OldTaskKey, 0)
		BEGIN
			UPDATE	tActivity
			SET		TaskKey = @TaskKey,
					DateUpdated = GETUTCDATE(),
					UpdatedByKey = @UserKey
			WHERE	ActivityKey = @ActivityKey

			IF @OldTaskKey IS NOT NULL
				EXEC sptActivityLinkUpdate @ActivityKey, ''tTask'', @OldTaskKey, ''delete''

			IF @TaskKey IS NOT NULL
				EXEC sptActivityLinkUpdate @ActivityKey, ''tTask'', @TaskKey, ''insert''
		END
	END		
		
	--Increment the Sequence number
	EXEC sptActivityIncrementSequence @ActivityKey	
	
	--Clear any read flags
	exec sptAppReadClearRead @UserKey, ''tActivity'', @ActivityKey
	
		
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptReviewCommentFixThis]'
GO
IF OBJECT_ID(N'[dbo].[sptReviewCommentFixThis]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptReviewCommentFixThis]
 @CompanyKey int,
 @UserKey int,
 @ReviewCommentKey INT,
 @ActivityCompleted int,
 @ActivityStatusKey int = NULL 
 
AS --Encrypt

  /*
  || When		Who Rel			What
  || 05/30/14	QMD 10.5.8.0	Created for round review (wjapp)
  || 11/05/15   GWG 10.5.9.7    Added handling for Fix this and adding a todo.
  || 12/03/15   GHL 10.5.9.8    Removed init of @ReviewDeliverableKey = null, this syntax crashes 20005 servers  
  || 01/06/15   GWG 10.5.9.9    Made assigned user null
  || 01/25/17   RLB 10.6.1.2    If notes contains <div> i take the first one and make that subject and the rest after that is set as the note. 
  || 12/26/17   DDM 18.1.0.0    Added @ActivityCompleted parameter when review comment is ''in progress'' and clicked mark the todo completed.
  || 05/14/18   RLB 18.6.0.0    To Do Enhancement to add activity status to fix this option
  || 09/25/18   RLB 18.9.1.0    Added a check for if div was first as to no create a To Do with no subject
  || 04/27/23   RLB 23.05.14    Only Defualt a activity status when the option in pref is checked
  || 07/30/25   AMP 25.08.17    (705266) Reviewed - No trigger change needed at this time 
  */
 
Declare @ProjectKey int,
@TaskKey int,
@AssignedUserKey int,
@Subject varchar(2000),
@Notes varchar(max),
@ActivityDate smalldatetime,
@ReviewDeliverableKey int , --= null
@ActivityKey int, 
@DefaultActivityStatusKey int,
@ActivityTypeKey int,
@StartOfSubject int,
@StartOfNotes int,
@UseStatusOnToDo tinyint

Select  @UseStatusOnToDo = ISNULL(UseStatusOnToDo, 0) from tPreference where CompanyKey = @CompanyKey

Select @ProjectKey = rd.ProjectKey, @TaskKey = rr.TaskKey,@ActivityKey = rc.ActivityKey, @Notes = rc.Comment, @ActivityDate = dbo.fFormatDateNoTime(GETDATE()), @ReviewDeliverableKey = rd.ReviewDeliverableKey
From tReviewComment rc (nolock)
inner join tReviewRound rr (nolock) on rc.ReviewRoundKey = rr.ReviewRoundKey
inner join tReviewDeliverable rd (nolock) on rr.ReviewDeliverableKey = rd.ReviewDeliverableKey
Where rc.ReviewCommentKey = @ReviewCommentKey

Select @DefaultActivityStatusKey = Min(ActivityStatusKey) from tActivityStatus (nolock) Where CompanyKey = @CompanyKey and IsDefault = 1
Select @ActivityTypeKey = DefaultToDoTypeKey from tPreference (nolock) Where CompanyKey = @CompanyKey
Select @StartOfSubject = CharIndex(''<div>'', @Notes)
IF @StartOfSubject - 1 > 0
	BEGIN
		Select @Subject = SUBSTRING(ISNULL(@Notes, ''''), 0, @StartOfSubject -1)
		Select @StartOfNotes = CharIndex(''<div>'', @Notes)
		Select @Notes = SUBSTRING(ISNULL(@Notes, ''''), @StartOfNotes + 5, LEN(@Notes))
	END
ELSE
	Select @Subject = SUBSTRING(ISNULL(@Notes, ''''), 0, 100)

--if no activity status passed in then set default one
IF ISNULL(@ActivityStatusKey, 0) = 0 and @UseStatusOnToDo = 1
	SELECT @ActivityStatusKey = @DefaultActivityStatusKey


exec @ActivityKey = sptActivityUpdateToDo @CompanyKey, @ActivityKey, @UserKey, @ProjectKey, @TaskKey, NULL, @Subject, @Notes, @ActivityDate, @ActivityCompleted, 0, 0, @ActivityTypeKey, 0, @ActivityStatusKey, @ReviewDeliverableKey

Update tActivity Set ReviewCommentKey = @ReviewCommentKey Where ActivityKey = @ActivityKey
IF @ActivityCompleted = 0
 UPDATE tReviewComment
 SET	FixThis  = 1, FixedDate = NULL, ActivityKey = @ActivityKey
 WHERE	ReviewCommentKey = @ReviewCommentKey
 ELSE
 UPDATE tReviewComment
 SET	FixedDate = GETUTCDATE() , ActivityKey = @ActivityKey
 WHERE	ReviewCommentKey = @ReviewCommentKey

 RETURN @ActivityKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateSlackThreadTS]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateSlackThreadTS]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateSlackThreadTS]
	@ActivityKey int,
	@SlackThreadTS nvarchar(50) = NULL
AS

/*
|| When      Who Rel       What
|| 02/08/22  GAR 22.03.20  (DEV2501-586-GAR) Created to update the SlackThreadTS that comes back from Slack when adding a new message.  We use this to thread replies to Slack
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time, this is an internal sync proc
*/

	UPDATE	tActivity
	SET		SlackThreadTS = @SlackThreadTS
	WHERE	ActivityKey = @ActivityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIVoucherUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIVoucherUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spApiAIVoucherUpdate]
(
    @CompanyKey         int,
    @UserKey            int,
    @VendorName         nvarchar(200)   = null,     -- vendor company name (used for lookup)
    @VendorID           nvarchar(50)    = null,      -- vendor ID (alternative to name)
    @InvoiceNumber      varchar(100)    = null,
    @InvoiceDate        smalldatetime   = null,      -- defaults to today on insert; not changed on update
    @PostingDate        smalldatetime   = null,      -- defaults to InvoiceDate on insert
    @DateReceived       smalldatetime   = null,      -- date invoice physically received; defaults to InvoiceDate on insert
    @DueDate            smalldatetime   = null,      -- payment due date
    @Description        nvarchar(max)   = null,
    @ProjectNumber      varchar(50)     = null,
    @GLCompanyID        varchar(50)     = null,      -- defaults to system/project preference on insert
    @APAccountNumber    varchar(100)    = null,      -- override default AP account from preference
    @ClassID            varchar(50)     = null,      -- GL class code
    @OfficeID           nvarchar(50)    = null,      -- office assignment
    @CurrencyID         varchar(10)     = null,      -- invoice currency (multi-currency companies)
    @ExchangeRate       decimal(24,7)   = null       -- exchange rate for CurrencyID
)

as --Encrypt

/*
|| When      Who Rel        What
|| 05/20/26  GRR 26.05.20   Created - insert vendor invoice (tVoucher) via AI
|| 05/20/26  GRR 26.05.20   Update existing invoice if InvoiceNumber already exists for the vendor
|| 05/28/26  AI  26.05.28   spCheckAccess (tVoucher) on update path; preserved set-based GL check for insert mode.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right purch_editvoucher.
*/

    -- ----------------------------------------------------------------
    -- Setup
    -- ----------------------------------------------------------------
    Declare @SecurityGroupKey           int
    Declare @IsAdministrator            bit
    Declare @RestrictToGLCompany        int
    Declare @CanEditVoucher             bit
    Declare @VendorKey                  int
    Declare @ProjectKey                 int
    Declare @GLCompanyKey               int
    Declare @APAccountKey               int
    Declare @DefaultAPApproverKey       int
    Declare @DefaultAPApprover          smallint
    Declare @DuplicateVendorInvoiceNbr  tinyint
    Declare @TermsPercent               decimal(24,4)
    Declare @TermsDays                  int
    Declare @TermsNet                   int
    Declare @SalesTaxKey                int
    Declare @SalesTax2Key               int
    Declare @ClassKey                   int
    Declare @OfficeKey                  int
    Declare @VoucherKey                 int
    Declare @VendorName_Out             nvarchar(200)
    Declare @ProjectNumber_Out          varchar(50)
    Declare @ErrorCount                 int

    -- Update-path state
    Declare @IsUpdate                   bit
    Declare @ExistingGLCompanyKey       int
    Declare @ExistingPosted             tinyint
    Declare @ExistingProjectKey         int

    -- Track which optional fields were explicitly provided by the caller
    -- (needed so UPDATE does not overwrite existing values with defaults)
    Declare @PostingDateProvided        bit
    Declare @DateReceivedProvided       bit
    Declare @ProjectNumberProvided      bit

    Set @IsUpdate               = 0
    Set @PostingDateProvided    = Case When @PostingDate    Is Not Null Then 1 Else 0 End
    Set @DateReceivedProvided   = Case When @DateReceived   Is Not Null Then 1 Else 0 End
    Set @ProjectNumberProvided  = Case When @ProjectNumber  Is Not Null And LTRIM(RTRIM(@ProjectNumber)) <> '''' Then 1 Else 0 End

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- ----------------------------------------------------------------
    -- Security: resolve user''s security group and administrator flag
    -- ----------------------------------------------------------------
    Select  @SecurityGroupKey   = SecurityGroupKey
           ,@IsAdministrator    = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
      And   CompanyKey  = @CompanyKey

    Set @CanEditVoucher = 0

    If @IsAdministrator = 1
        Set @CanEditVoucher = 1
    Else If Exists (
        Select  1
        From    tRight r (nolock)
                Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
        Where   ra.EntityType   = ''Security Group''
          And   ra.EntityKey    = @SecurityGroupKey
          And   r.RightID       = ''purch_editvoucher''
    )
        Set @CanEditVoucher = 1

    If @CanEditVoucher = 0
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You do not have permission to add or edit vendor invoices.'', ''general'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Required field validation
    -- ----------------------------------------------------------------
    If @VendorName Is Null And @VendorID Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'',
                ''Either vendorName or vendorID is required.'', ''vendorName'')
    End

    If @InvoiceNumber Is Null Or LTRIM(RTRIM(@InvoiceNumber)) = ''''
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''InvoiceNumber is required.'', ''invoiceNumber'')
    End

    Select @ErrorCount = COUNT(*) From #errors Where errorType = ''error''
    If @ErrorCount > 0 Goto ReturnResult

    -- ----------------------------------------------------------------
    -- Normalize dates (strip time component)
    -- Defaults for InvoiceDate, PostingDate, DateReceived are applied
    -- only on the INSERT path; UPDATE uses CASE to preserve existing values
    -- ----------------------------------------------------------------
    If @InvoiceDate Is Null
        Set @InvoiceDate = dbo.fFormatDateNoTime(GETUTCDATE())
    Else
        Set @InvoiceDate = dbo.fFormatDateNoTime(@InvoiceDate)

    If @PostingDate Is Not Null
        Set @PostingDate = dbo.fFormatDateNoTime(@PostingDate)

    If @DateReceived Is Not Null
        Set @DateReceived = dbo.fFormatDateNoTime(@DateReceived)

    If @DueDate Is Not Null
        Set @DueDate = dbo.fFormatDateNoTime(@DueDate)

    -- ----------------------------------------------------------------
    -- Load company preferences
    -- ----------------------------------------------------------------
    Select  @APAccountKey               = DefaultAPAccountKey
           ,@DefaultAPApprover          = ISNULL(DefaultAPApprover, 0)
           ,@DefaultAPApproverKey       = ISNULL(DefaultAPApproverKey, 0)
           ,@DuplicateVendorInvoiceNbr  = ISNULL(DuplicateVendorInvoiceNbr, 0)
           ,@RestrictToGLCompany        = ISNULL(RestrictToGLCompany, 0)
    From    tPreference (nolock)
    Where   CompanyKey = @CompanyKey

    -- ----------------------------------------------------------------
    -- AP account override
    -- ----------------------------------------------------------------
    If @APAccountNumber Is Not Null And LTRIM(RTRIM(@APAccountNumber)) <> ''''
    Begin
        Declare @OverrideAPAccountKey int

        Select  @OverrideAPAccountKey = GLAccountKey
        From    tGLAccount (nolock)
        Where   CompanyKey      = @CompanyKey
          And   AccountNumber   = @APAccountNumber

        If @OverrideAPAccountKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''AP account not found: '' + @APAccountNumber + ''.'', ''apAccountNumber'')
            Goto ReturnResult
        End

        Set @APAccountKey = @OverrideAPAccountKey
    End

    -- ----------------------------------------------------------------
    -- GL class lookup
    -- ----------------------------------------------------------------
    If @ClassID Is Not Null And LTRIM(RTRIM(@ClassID)) <> ''''
    Begin
        Select  @ClassKey = ClassKey
        From    tClass (nolock)
        Where   CompanyKey  = @CompanyKey
          And   ClassID     = @ClassID

        If @ClassKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Class not found: '' + @ClassID + ''.'', ''classID'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Office lookup
    -- ----------------------------------------------------------------
    If @OfficeID Is Not Null And LTRIM(RTRIM(@OfficeID)) <> ''''
    Begin
        Select  @OfficeKey = OfficeKey
        From    tOffice (nolock)
        Where   CompanyKey  = @CompanyKey
          And   OfficeID    = @OfficeID

        If @OfficeKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Office not found: '' + @OfficeID + ''.'', ''officeID'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Resolve GL company (when explicitly specified by caller)
    -- ----------------------------------------------------------------
    If @GLCompanyID Is Not Null And LTRIM(RTRIM(@GLCompanyID)) <> ''''
    Begin
        Select @GLCompanyKey = GLCompanyKey
        From   tGLCompany (nolock)
        Where  CompanyKey   = @CompanyKey
          And  GLCompanyID  = @GLCompanyID

        If @GLCompanyKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''GL company not found: '' + @GLCompanyID + ''.'', ''glCompanyID'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Vendor lookup by VendorID or name
    -- ----------------------------------------------------------------
    If @VendorID Is Not Null And LTRIM(RTRIM(@VendorID)) <> ''''
    Begin
        Select  @VendorKey      = CompanyKey
               ,@VendorName_Out = CompanyName
               ,@TermsPercent   = TermsPercent
               ,@TermsDays      = TermsDays
               ,@TermsNet       = TermsNet
               ,@SalesTaxKey    = SalesTaxKey
               ,@SalesTax2Key   = SalesTax2Key
        From    tCompany (nolock)
        Where   OwnerCompanyKey = @CompanyKey
          And   VendorID        = @VendorID
          And   ISNULL(Vendor, 0) = 1
    End
    Else
    Begin
        Select  @VendorKey      = CompanyKey
               ,@VendorName_Out = CompanyName
               ,@TermsPercent   = TermsPercent
               ,@TermsDays      = TermsDays
               ,@TermsNet       = TermsNet
               ,@SalesTaxKey    = SalesTaxKey
               ,@SalesTax2Key   = SalesTax2Key
        From    tCompany (nolock)
        Where   OwnerCompanyKey = @CompanyKey
          And   CompanyName     = @VendorName
          And   ISNULL(Vendor, 0) = 1
    End

    If @VendorKey Is Null
    Begin
        Declare @VendorSearchTerm nvarchar(250)
        Set @VendorSearchTerm = ISNULL(@VendorID, @VendorName)
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'',
                ''Vendor not found: '' + @VendorSearchTerm + ''. Verify the vendor name or ID.'', ''vendorName'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Determine INSERT vs UPDATE
    -- If the invoice number already exists for this vendor, update it
    -- ----------------------------------------------------------------
    Select  @VoucherKey             = VoucherKey
           ,@ExistingGLCompanyKey   = GLCompanyKey
           ,@ExistingPosted         = ISNULL(Posted, 0)
           ,@ExistingProjectKey     = ProjectKey
    From    tVoucher (nolock)
    Where   InvoiceNumber           = @InvoiceNumber
      And   VendorKey               = @VendorKey
      And   CompanyKey              = @CompanyKey
      And   ISNULL(CreditCard, 0)   = 0

    If @VoucherKey Is Not Null
        Set @IsUpdate = 1

    -- ----------------------------------------------------------------
    -- If updating: block edits to posted invoices
    -- ----------------------------------------------------------------
    If @IsUpdate = 1 And @ExistingPosted = 1
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
                ''Vendor invoice '' + @InvoiceNumber + '' has already been posted and cannot be modified.'', ''invoiceNumber'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Record-level access gate.
    -- Update mode: delegate to spCheckAccess (tVoucher) for the per-entity
    -- GL company / admin bypass rules. Insert mode: validate the supplied
    -- GL company against the caller''s GLCompanyAccess (no existing record
    -- to gate on yet).
    -- ----------------------------------------------------------------
    If @IsUpdate = 1
    Begin
        Declare @AccessOK int
        Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tVoucher'', @VoucherKey
        If @AccessOK <> 1
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'',
                    ''You do not have access to this vendor invoice.'', ''invoiceNumber'')
            Goto ReturnResult
        End
    End
    Else
    Begin
        -- Insert mode: ensure the caller can post into the supplied GL company
        If @IsAdministrator = 0 And @RestrictToGLCompany = 1 And @GLCompanyKey Is Not Null
        Begin
            If Not Exists (
                Select  1
                From    tUserGLCompanyAccess (nolock)
                Where   UserKey      = @UserKey
                  And   GLCompanyKey = @GLCompanyKey
            )
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''ACCESS_DENIED'',
                        ''You do not have GL company access to post this vendor invoice.'', ''glCompanyID'')
                Goto ReturnResult
            End
        End
    End

    -- ----------------------------------------------------------------
    -- Project lookup (optional - applies to both INSERT and UPDATE)
    -- ----------------------------------------------------------------
    If @ProjectNumberProvided = 1
    Begin
        Select  @ProjectKey         = p.ProjectKey
               ,@ProjectNumber_Out  = p.ProjectNumber
        From    tProject p (nolock)
        Where   p.CompanyKey    = @CompanyKey
          And   p.ProjectNumber = @ProjectNumber

        If @ProjectKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''warning'', ''NOT_FOUND'',
                    ''Project not found: '' + @ProjectNumber + ''. Invoice will be saved without a project link.'', ''projectNumber'')
        End
        Else
        Begin
            -- Inherit GL company from project when not explicitly specified (INSERT only)
            If @IsUpdate = 0 And @GLCompanyKey Is Null
                Select @GLCompanyKey = GLCompanyKey From tProject (nolock)
                Where  ProjectKey = @ProjectKey

            -- Verify project has an active expense status
            If Not Exists (
                Select  1
                From    tProject p2 (nolock)
                        Inner Join tProjectStatus ps (nolock) On p2.ProjectStatusKey = ps.ProjectStatusKey
                Where   p2.ProjectKey   = @ProjectKey
                  And   ps.ExpenseActive = 1
            )
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''INVALID_VALUE'',
                        ''Project '' + @ProjectNumber + '' does not have an active expense status.'', ''projectNumber'')
                Goto ReturnResult
            End
        End
    End

    -- ========================================================
    -- UPDATE PATH
    -- ========================================================
    If @IsUpdate = 1
    Begin
        Update tVoucher Set
            PostingDate     = Case When @PostingDateProvided   = 1 Then @PostingDate   Else PostingDate   End,
            DateReceived    = Case When @DateReceivedProvided  = 1 Then @DateReceived  Else DateReceived  End,
            DueDate         = Case When @DueDate      Is Not Null  Then @DueDate       Else DueDate       End,
            Description     = Case When @Description  Is Not Null  Then @Description   Else Description   End,
            ProjectKey      = Case When @ProjectNumberProvided = 1 Then @ProjectKey    Else ProjectKey    End,
            APAccountKey    = Case When @APAccountNumber Is Not Null And LTRIM(RTRIM(@APAccountNumber)) <> ''''
                                   Then @APAccountKey   Else APAccountKey   End,
            ClassKey        = Case When @ClassID    Is Not Null And LTRIM(RTRIM(@ClassID))    <> ''''
                                   Then @ClassKey    Else ClassKey    End,
            OfficeKey       = Case When @OfficeID   Is Not Null And LTRIM(RTRIM(@OfficeID))   <> ''''
                                   Then @OfficeKey   Else OfficeKey   End,
            GLCompanyKey    = Case When @GLCompanyKey Is Not Null Then @GLCompanyKey Else GLCompanyKey End,
            CurrencyID      = Case When @CurrencyID Is Not Null  Then @CurrencyID    Else CurrencyID    End,
            ExchangeRate    = Case When @ExchangeRate Is Not Null Then @ExchangeRate  Else ExchangeRate  End,
            DateUpdated     = GETUTCDATE()
        Where VoucherKey = @VoucherKey

        -- Resolve project number for return row
        If @ProjectNumberProvided = 0
            Select @ProjectNumber_Out = p.ProjectNumber
            From   tProject p (nolock)
            Where  p.ProjectKey = @ExistingProjectKey

        Goto LogAndReturn
    End

    -- ========================================================
    -- INSERT PATH
    -- ========================================================

    -- Apply INSERT-specific date defaults now that the update branch is past
    If @PostingDate Is Null
        Set @PostingDate = @InvoiceDate

    If @DateReceived Is Null
        Set @DateReceived = @InvoiceDate

    -- Default GL company from preference when still undetermined
    If @GLCompanyKey Is Null
    Begin
        Select  @GLCompanyKey = DefaultGLCompanyKey
        From    tPreference (nolock)
        Where   CompanyKey = @CompanyKey

        -- If restricted user can''t access the default, fall back to their first accessible GL company
        If @IsAdministrator = 0 And @RestrictToGLCompany = 1 And @GLCompanyKey Is Not Null
        Begin
            If Not Exists (
                Select  1
                From    tUserGLCompanyAccess (nolock)
                Where   UserKey     = @UserKey
                  And   GLCompanyKey = @GLCompanyKey
            )
            Begin
                Select  Top 1 @GLCompanyKey = GLCompanyKey
                From    tUserGLCompanyAccess (nolock)
                Where   UserKey = @UserKey
            End
        End
    End

    -- Duplicate check (only when the system setting disallows duplicate invoice numbers)
    If @DuplicateVendorInvoiceNbr = 0
    Begin
        If Exists (
            Select 1 From tVoucher (nolock)
            Where  InvoiceNumber        = @InvoiceNumber
              And  VendorKey            = @VendorKey
              And  CompanyKey           = @CompanyKey
              And  ISNULL(CreditCard, 0) = 0
        )
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''DUPLICATE'',
                    ''Vendor invoice number '' + @InvoiceNumber + '' already exists for this vendor.'', ''invoiceNumber'')
            Goto ReturnResult
        End
    End

    -- Normalize exchange rate
    If @CurrencyID Is Not Null And (@ExchangeRate Is Null Or @ExchangeRate <= 0)
        Set @ExchangeRate = 1

    Declare @oIdentity int

    Exec sptVoucherInsert
         @CompanyKey         = @CompanyKey
        ,@VendorKey          = @VendorKey
        ,@InvoiceDate        = @InvoiceDate
        ,@PostingDate        = @PostingDate
        ,@InvoiceNumber      = @InvoiceNumber
        ,@DateReceived       = @DateReceived
        ,@CreatedByKey       = @UserKey
        ,@TermsPercent       = @TermsPercent
        ,@TermsDays          = @TermsDays
        ,@TermsNet           = @TermsNet
        ,@DueDate            = @DueDate
        ,@Description        = @Description
        ,@ProjectKey         = @ProjectKey
        ,@ApprovedByKey      = @UserKey
        ,@APAccountKey       = @APAccountKey
        ,@ClassKey           = @ClassKey
        ,@SalesTaxKey        = @SalesTaxKey
        ,@SalesTax2Key       = @SalesTax2Key
        ,@GLCompanyKey       = @GLCompanyKey
        ,@OfficeKey          = @OfficeKey
        ,@OpeningTransaction = 0
        ,@VoucherType        = 0
        ,@CurrencyID         = @CurrencyID
        ,@ExchangeRate       = @ExchangeRate
        ,@oIdentity          = @oIdentity Output

    Set @VoucherKey = @oIdentity

    If @VoucherKey Is Null Or @VoucherKey <= 0
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
                ''Vendor invoice could not be created. The invoice number may be a duplicate.'', ''general'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Shared action log + return
    -- ----------------------------------------------------------------
LogAndReturn:

    Declare @Now            datetime
    Declare @ActionComments nvarchar(4000)
    Declare @ActionVerb     varchar(20)
    Declare @ActionLabel    varchar(50)

    Set @Now         = GETUTCDATE()
    Set @ActionVerb  = Case When @IsUpdate = 1 Then ''updated'' Else ''created'' End
    Set @ActionLabel = Case When @IsUpdate = 1 Then ''Vendor Invoice Updated'' Else ''Vendor Invoice Created'' End

    Set @ActionComments = ''Vendor invoice '' + @ActionVerb + '' via AI. Invoice number: ''
                        + @InvoiceNumber + '', Vendor: '' + @VendorName_Out

    Exec sptActionLogInsert
         @Entity            = ''Voucher''
        ,@EntityKey         = @VoucherKey
        ,@CompanyKey        = @CompanyKey
        ,@ProjectKey        = @ProjectKey
        ,@Action            = @ActionLabel
        ,@ActionDate        = @Now
        ,@ActionBy          = null
        ,@Comments          = @ActionComments
        ,@Reference         = @InvoiceNumber
        ,@SourceCompanyID   = null
        ,@UserKey           = @UserKey
        ,@CampaignKey       = null

    -- ----------------------------------------------------------------
    -- Return
    -- ----------------------------------------------------------------
ReturnResult:

    -- Table[0]: errors and warnings (always returned)
    Select  errorType
           ,errorCode
           ,errorMessage
           ,fieldName
    From    #errors
    Order By errorType desc, fieldName

    -- Table[1]: success row (only when no fatal errors)
    Select @ErrorCount = COUNT(*) From #errors Where errorType = ''error''
    If @ErrorCount = 0
    Begin
        Select  @VoucherKey                             as voucherKey
               ,@InvoiceNumber                          as invoiceNumber
               ,@VendorName_Out                         as vendorName
               ,ISNULL(@ProjectNumber_Out, '''')          as projectNumber
               ,Convert(varchar(10), @InvoiceDate, 101) as invoiceDate
               ,Convert(varchar(10), @DueDate, 101)     as dueDate
               ,Case When @IsUpdate = 1 Then ''Updated'' Else ''Created'' End as statusLabel
    End

    Drop Table #errors


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIVoucherDetailUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIVoucherDetailUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spApiAIVoucherDetailUpdate]
(
    @CompanyKey             int,
    @UserKey                int,
    @VoucherKey             int             = null,         -- from spApiAIVoucherUpdate; OR use InvoiceNumber
    @InvoiceNumber          varchar(100)    = null,         -- alternative to VoucherKey for header lookup
    @VendorName             nvarchar(200)   = null,         -- disambiguates InvoiceNumber when multiple vendors match
    @VendorID               nvarchar(50)    = null,         -- disambiguates InvoiceNumber when multiple vendors match
    @LineNumber             int             = null,         -- existing line number to update; omit to always insert
    @TotalCost              money           = null,         -- required on insert; optional on update
    @ShortDescription       nvarchar(2000)  = null,         -- line description
    @ProjectNumber          varchar(50)     = null,         -- project to link the line to
    @TaskID                 nvarchar(30)    = null,         -- task (requires projectNumber)
    @ItemID                 nvarchar(50)    = null,         -- purchase item code
    @ExpenseAccountNumber   varchar(100)    = null,         -- override expense GL account
    @ClassID                varchar(50)     = null,         -- GL class code
    @OfficeID               nvarchar(50)    = null,         -- office assignment
    @DepartmentName         nvarchar(200)   = null,         -- department name (looked up in tDepartment)
    @Quantity               decimal(24,4)   = null,         -- defaults to 1 on insert
    @UnitCost               money           = null,         -- defaults to TotalCost on insert
    @UnitDescription        varchar(30)     = null,         -- unit label (e.g. ''EA'', ''HR'')
    @UnitRate               money           = null,         -- billing rate per unit
    @Billable               tinyint         = null,         -- null = keep existing on update; defaults to 0 on insert
    @Markup                 decimal(24,4)   = null,         -- markup percentage (e.g. 15.00 = 15%)
    @BillableCost           money           = null,         -- override calculated billable amount
    @Taxable                tinyint         = null,         -- null = keep existing on update; defaults to 0 on insert
    @Taxable2               tinyint         = null,         -- null = keep existing on update; defaults to 0 on insert
    @LastVoucher            tinyint         = null,         -- null = keep existing on update; defaults to 0 on insert
    @PurchaseOrderDetailKey int             = null          -- PO detail line key to link this voucher line to the originating PO line
)

as --Encrypt

/*
|| When      Who Rel        What
|| 05/20/26  GRR 26.05.20   Created - insert vendor invoice detail line (tVoucherDetail) via AI
|| 05/20/26  GRR 26.05.20   Update existing line when InvoiceNumber + LineNumber match an existing record
|| 05/21/26  GRR 26.05.xx   Added @PurchaseOrderDetailKey - links voucher detail line to originating PO line
|| 05/28/26  AI  26.05.28   spCheckAccess (tVoucher) replaces inline GL company check.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right purch_editvoucher.
*/

    -- ----------------------------------------------------------------
    -- Setup
    -- ----------------------------------------------------------------
    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @CanEditVoucher         bit
    Declare @VoucherGLCompanyKey    int
    Declare @VoucherPosted          tinyint
    Declare @VoucherStatus          smallint
    Declare @VoucherInvoiceNumber   varchar(100)
    Declare @ProjectKey             int
    Declare @TaskKey                int
    Declare @ItemKey                int
    Declare @ClassKey               int
    Declare @OfficeKey              int
    Declare @DepartmentKey          int
    Declare @ExpenseAccountKey      int
    Declare @VoucherDetailKey       int
    Declare @ErrorCount             int

    -- Update-path state
    Declare @IsUpdate               bit

    -- Track which optional fields were explicitly provided
    Declare @ProjectNumberProvided  bit
    Declare @TaskIDProvided         bit
    Declare @ItemIDProvided         bit
    Declare @ExpenseAccountProvided bit
    Declare @ClassIDProvided        bit
    Declare @OfficeIDProvided       bit
    Declare @DepartmentProvided     bit
    Declare @QuantityProvided       bit
    Declare @UnitCostProvided       bit
    Declare @UnitDescProvided       bit
    Declare @UnitRateProvided       bit
    Declare @MarkupProvided         bit
    Declare @BillableCostProvided   bit

    Set @IsUpdate               = 0
    Set @ProjectNumberProvided  = Case When @ProjectNumber      Is Not Null And LTRIM(RTRIM(@ProjectNumber))      <> '''' Then 1 Else 0 End
    Set @TaskIDProvided         = Case When @TaskID             Is Not Null And LTRIM(RTRIM(@TaskID))             <> '''' Then 1 Else 0 End
    Set @ItemIDProvided         = Case When @ItemID             Is Not Null And LTRIM(RTRIM(@ItemID))             <> '''' Then 1 Else 0 End
    Set @ExpenseAccountProvided = Case When @ExpenseAccountNumber Is Not Null And LTRIM(RTRIM(@ExpenseAccountNumber)) <> '''' Then 1 Else 0 End
    Set @ClassIDProvided        = Case When @ClassID            Is Not Null And LTRIM(RTRIM(@ClassID))            <> '''' Then 1 Else 0 End
    Set @OfficeIDProvided       = Case When @OfficeID           Is Not Null And LTRIM(RTRIM(@OfficeID))           <> '''' Then 1 Else 0 End
    Set @DepartmentProvided     = Case When @DepartmentName     Is Not Null And LTRIM(RTRIM(@DepartmentName))     <> '''' Then 1 Else 0 End
    Set @QuantityProvided       = Case When @Quantity           Is Not Null Then 1 Else 0 End
    Set @UnitCostProvided       = Case When @UnitCost           Is Not Null Then 1 Else 0 End
    Set @UnitDescProvided       = Case When @UnitDescription    Is Not Null Then 1 Else 0 End
    Set @UnitRateProvided       = Case When @UnitRate           Is Not Null Then 1 Else 0 End
    Set @MarkupProvided         = Case When @Markup             Is Not Null Then 1 Else 0 End
    Set @BillableCostProvided   = Case When @BillableCost       Is Not Null Then 1 Else 0 End

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- ----------------------------------------------------------------
    -- Security: resolve user''s security group and administrator flag
    -- ----------------------------------------------------------------
    Select  @SecurityGroupKey   = SecurityGroupKey
           ,@IsAdministrator    = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
      And   CompanyKey  = @CompanyKey

    Set @CanEditVoucher = 0

    If @IsAdministrator = 1
        Set @CanEditVoucher = 1
    Else If Exists (
        Select  1
        From    tRight r (nolock)
                Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
        Where   ra.EntityType   = ''Security Group''
          And   ra.EntityKey    = @SecurityGroupKey
          And   r.RightID       = ''purch_editvoucher''
    )
        Set @CanEditVoucher = 1

    If @CanEditVoucher = 0
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You do not have permission to add or edit vendor invoice lines.'', ''general'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Required field validation - must supply VoucherKey or InvoiceNumber
    -- ----------------------------------------------------------------
    If (@VoucherKey Is Null Or @VoucherKey <= 0) And (@InvoiceNumber Is Null Or LTRIM(RTRIM(@InvoiceNumber)) = '''')
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'',
                ''Either voucherKey or invoiceNumber is required.'', ''voucherKey'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Resolve VoucherKey from InvoiceNumber when not directly supplied
    -- ----------------------------------------------------------------
    If @VoucherKey Is Null Or @VoucherKey <= 0
    Begin
        Declare @VendorKey int

        -- Vendor lookup for disambiguation (optional but recommended)
        If @VendorID Is Not Null And LTRIM(RTRIM(@VendorID)) <> ''''
            Select @VendorKey = CompanyKey From tCompany (nolock)
            Where  OwnerCompanyKey = @CompanyKey And VendorID = @VendorID And ISNULL(Vendor, 0) = 1

        If @VendorKey Is Null And @VendorName Is Not Null And LTRIM(RTRIM(@VendorName)) <> ''''
            Select @VendorKey = CompanyKey From tCompany (nolock)
            Where  OwnerCompanyKey = @CompanyKey And CompanyName = @VendorName And ISNULL(Vendor, 0) = 1

        If @VendorKey Is Not Null
            -- Vendor identified - find the voucher for this vendor + invoice number
            Select  @VoucherKey = VoucherKey
            From    tVoucher (nolock)
            Where   InvoiceNumber           = @InvoiceNumber
              And   VendorKey               = @VendorKey
              And   CompanyKey              = @CompanyKey
              And   ISNULL(CreditCard, 0)   = 0
        Else
        Begin
            -- No vendor specified - find the voucher by invoice number alone;
            -- fail if ambiguous (multiple vendors with the same invoice number)
            Declare @MatchCount int
            Select  @MatchCount = COUNT(*)
            From    tVoucher (nolock)
            Where   InvoiceNumber           = @InvoiceNumber
              And   CompanyKey              = @CompanyKey
              And   ISNULL(CreditCard, 0)   = 0

            If @MatchCount > 1
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''DUPLICATE'',
                        ''Multiple invoices found with number '' + @InvoiceNumber + ''. Provide vendorName or vendorID to identify the correct invoice.'', ''invoiceNumber'')
                Goto ReturnResult
            End

            Select  @VoucherKey = VoucherKey
            From    tVoucher (nolock)
            Where   InvoiceNumber           = @InvoiceNumber
              And   CompanyKey              = @CompanyKey
              And   ISNULL(CreditCard, 0)   = 0
        End

        If @VoucherKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Vendor invoice not found: '' + @InvoiceNumber + ''.'', ''invoiceNumber'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Verify the voucher exists, belongs to this company, and is not posted
    -- ----------------------------------------------------------------
    Select  @VoucherPosted          = ISNULL(Posted, 0)
           ,@VoucherStatus          = Status
           ,@VoucherGLCompanyKey    = GLCompanyKey
           ,@VoucherInvoiceNumber   = InvoiceNumber
    From    tVoucher (nolock)
    Where   VoucherKey  = @VoucherKey
      And   CompanyKey  = @CompanyKey
      And   ISNULL(CreditCard, 0) = 0

    If @VoucherInvoiceNumber Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Vendor invoice not found.'', ''voucherKey'')
        Goto ReturnResult
    End

    If @VoucherPosted = 1
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
                ''Vendor invoice '' + @VoucherInvoiceNumber + '' has already been posted and cannot be modified.'', ''voucherKey'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Record-level access gate via spCheckAccess (tVoucher)
    -- ----------------------------------------------------------------
    Declare @AccessOK int
    Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tVoucher'', @VoucherKey
    If @AccessOK <> 1
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You do not have access to modify this vendor invoice.'', ''voucherKey'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Determine INSERT vs UPDATE via LineNumber
    -- ----------------------------------------------------------------
    If @LineNumber Is Not Null And @LineNumber > 0
    Begin
        Select  @VoucherDetailKey = VoucherDetailKey
        From    tVoucherDetail (nolock)
        Where   VoucherKey  = @VoucherKey
          And   LineNumber  = @LineNumber

        If @VoucherDetailKey Is Not Null
            Set @IsUpdate = 1
    End

    -- ----------------------------------------------------------------
    -- Validate TotalCost - required on insert, optional on update
    -- ----------------------------------------------------------------
    If @IsUpdate = 0 And @TotalCost Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''TotalCost is required.'', ''totalCost'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Lookup: project
    -- ----------------------------------------------------------------
    If @ProjectNumberProvided = 1
    Begin
        Select  @ProjectKey = ProjectKey
        From    tProject (nolock)
        Where   CompanyKey    = @CompanyKey
          And   ProjectNumber = @ProjectNumber

        If @ProjectKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Project not found: '' + @ProjectNumber + ''.'', ''projectNumber'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Lookup: task (requires project)
    -- ----------------------------------------------------------------
    If @TaskIDProvided = 1
    Begin
        If @ProjectKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''warning'', ''INVALID_VALUE'',
                    ''TaskID was provided but projectNumber is missing. Task will be ignored.'', ''taskID'')
            Set @TaskIDProvided = 0
        End
        Else
        Begin
            Select  @TaskKey = TaskKey
            From    tTask (nolock)
            Where   ProjectKey  = @ProjectKey
              And   TaskID      = @TaskID

            If @TaskKey Is Null
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''warning'', ''NOT_FOUND'',
                        ''Task not found: '' + @TaskID + ''. Line will be saved without a task link.'', ''taskID'')
                Set @TaskIDProvided = 0
            End
        End
    End

    -- ----------------------------------------------------------------
    -- Lookup: item - also inherits ExpenseAccountKey if not overridden
    -- ----------------------------------------------------------------
    If @ItemIDProvided = 1
    Begin
        Select  @ItemKey            = ItemKey
               ,@ExpenseAccountKey  = ExpenseAccountKey
        From    tItem (nolock)
        Where   CompanyKey  = @CompanyKey
          And   ItemID      = @ItemID

        If @ItemKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''warning'', ''NOT_FOUND'',
                    ''Item not found: '' + @ItemID + ''. Line will be saved without an item link.'', ''itemID'')
            Set @ItemIDProvided = 0
        End
    End

    -- ----------------------------------------------------------------
    -- Lookup: expense account (overrides item default if provided)
    -- ----------------------------------------------------------------
    If @ExpenseAccountProvided = 1
    Begin
        Declare @LookedUpExpenseAccountKey int

        Select  @LookedUpExpenseAccountKey = GLAccountKey
        From    tGLAccount (nolock)
        Where   CompanyKey    = @CompanyKey
          And   AccountNumber = @ExpenseAccountNumber

        If @LookedUpExpenseAccountKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Expense account not found: '' + @ExpenseAccountNumber + ''.'', ''expenseAccountNumber'')
            Goto ReturnResult
        End

        Set @ExpenseAccountKey = @LookedUpExpenseAccountKey
    End

    -- ----------------------------------------------------------------
    -- Lookup: GL class
    -- ----------------------------------------------------------------
    If @ClassIDProvided = 1
    Begin
        Select  @ClassKey = ClassKey
        From    tClass (nolock)
        Where   CompanyKey  = @CompanyKey
          And   ClassID     = @ClassID

        If @ClassKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Class not found: '' + @ClassID + ''.'', ''classID'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Lookup: office
    -- ----------------------------------------------------------------
    If @OfficeIDProvided = 1
    Begin
        Select  @OfficeKey = OfficeKey
        From    tOffice (nolock)
        Where   CompanyKey  = @CompanyKey
          And   OfficeID    = @OfficeID

        If @OfficeKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Office not found: '' + @OfficeID + ''.'', ''officeID'')
            Goto ReturnResult
        End
    End

    -- ----------------------------------------------------------------
    -- Lookup: department
    -- ----------------------------------------------------------------
    If @DepartmentProvided = 1
    Begin
        Select  @DepartmentKey = DepartmentKey
        From    tDepartment (nolock)
        Where   CompanyKey      = @CompanyKey
          And   DepartmentName  = @DepartmentName

        If @DepartmentKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'',
                    ''Department not found: '' + @DepartmentName + ''.'', ''departmentName'')
            Goto ReturnResult
        End
    End

    -- ========================================================
    -- UPDATE PATH
    -- ========================================================
    If @IsUpdate = 1
    Begin
        -- Recalculate GrossAmount if Billable + Markup are both being set
        Declare @GrossAmount money
        If @Billable = 1 And @MarkupProvided = 1 And @TotalCost Is Not Null
            Set @GrossAmount = ROUND(@TotalCost * (1 + @Markup / 100), 2)

        Update tVoucherDetail Set
            ShortDescription    = Case When @ShortDescription  Is Not Null  Then @ShortDescription  Else ShortDescription  End,
            TotalCost           = Case When @TotalCost         Is Not Null  Then @TotalCost          Else TotalCost          End,
            Quantity            = Case When @QuantityProvided  = 1          Then @Quantity           Else Quantity           End,
            UnitCost            = Case When @UnitCostProvided  = 1          Then @UnitCost           Else UnitCost           End,
            UnitDescription     = Case When @UnitDescProvided  = 1          Then @UnitDescription    Else UnitDescription    End,
            UnitRate            = Case When @UnitRateProvided  = 1          Then @UnitRate           Else UnitRate           End,
            ProjectKey          = Case When @ProjectNumberProvided = 1      Then @ProjectKey         Else ProjectKey         End,
            TaskKey             = Case When @TaskIDProvided    = 1          Then @TaskKey            Else TaskKey            End,
            ItemKey             = Case When @ItemIDProvided    = 1          Then @ItemKey            Else ItemKey            End,
            ExpenseAccountKey   = Case When @ExpenseAccountProvided = 1
                                        Or  @ItemIDProvided   = 1          Then @ExpenseAccountKey  Else ExpenseAccountKey  End,
            ClassKey            = Case When @ClassIDProvided   = 1          Then @ClassKey           Else ClassKey           End,
            OfficeKey           = Case When @OfficeIDProvided  = 1          Then @OfficeKey          Else OfficeKey          End,
            DepartmentKey       = Case When @DepartmentProvided = 1         Then @DepartmentKey      Else DepartmentKey      End,
            Billable            = Case When @Billable          Is Not Null  Then @Billable           Else Billable           End,
            Markup              = Case When @MarkupProvided    = 1          Then @Markup             Else Markup             End,
            BillableCost        = Case When @BillableCostProvided = 1       Then @BillableCost
                                        When @GrossAmount     Is Not Null  Then @GrossAmount
                                        Else BillableCost End,
            GrossAmount         = Case When @GrossAmount       Is Not Null  Then @GrossAmount        Else GrossAmount        End,
            Taxable             = Case When @Taxable           Is Not Null  Then @Taxable            Else Taxable            End,
            Taxable2            = Case When @Taxable2          Is Not Null  Then @Taxable2           Else Taxable2           End,
            LastVoucher             = Case When @LastVoucher           Is Not Null  Then @LastVoucher            Else LastVoucher            End,
            PurchaseOrderDetailKey  = Case When @PurchaseOrderDetailKey Is Not Null  Then @PurchaseOrderDetailKey Else PurchaseOrderDetailKey  End
        Where VoucherDetailKey = @VoucherDetailKey

        -- Recalculate line amounts (sales tax, totals) after any cost change
        Exec sptVoucherRecalcLineAmounts @VoucherKey, @VoucherDetailKey

        Goto LogAndReturn
    End

    -- ========================================================
    -- INSERT PATH
    -- ========================================================

    -- Apply insert-specific defaults for fields that were null
    If @Quantity Is Null Or @Quantity = 0
        Set @Quantity = 1

    If @UnitCost Is Null
        Set @UnitCost = @TotalCost / @Quantity

    If @Billable  Is Null Set @Billable  = 0
    If @Taxable   Is Null Set @Taxable   = 0
    If @Taxable2  Is Null Set @Taxable2  = 0
    If @LastVoucher Is Null Set @LastVoucher = 0

    Declare @oIdentity int

    Exec sptVoucherDetailInsert
         @VoucherKey                = @VoucherKey
        ,@PurchaseOrderDetailKey    = @PurchaseOrderDetailKey
        ,@ClientKey                 = null
        ,@ProjectKey                = @ProjectKey
        ,@TaskKey                   = @TaskKey
        ,@ItemKey                   = @ItemKey
        ,@ClassKey                  = @ClassKey
        ,@ShortDescription          = @ShortDescription
        ,@Quantity                  = @Quantity
        ,@UnitCost                  = @UnitCost
        ,@UnitDescription           = @UnitDescription
        ,@TotalCost                 = @TotalCost
        ,@UnitRate                  = @UnitRate
        ,@Billable                  = @Billable
        ,@Markup                    = @Markup
        ,@BillableCost              = @BillableCost
        ,@ExpenseAccountKey         = @ExpenseAccountKey
        ,@Taxable                   = @Taxable
        ,@Taxable2                  = @Taxable2
        ,@LastVoucher               = @LastVoucher
        ,@OfficeKey                 = @OfficeKey
        ,@DepartmentKey             = @DepartmentKey
        ,@CheckProject              = 1
        ,@oIdentity                 = @oIdentity Output

    Set @VoucherDetailKey = @oIdentity

    If @VoucherDetailKey Is Null Or @VoucherDetailKey <= 0
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
                ''Vendor invoice line could not be created. The invoice may have been posted or the project status may not allow expenses.'', ''general'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Shared action log + return
    -- ----------------------------------------------------------------
LogAndReturn:

    Declare @Now            datetime
    Declare @ActionComments nvarchar(4000)
    Declare @ActionLabel    varchar(50)
    Declare @ActionVerb     varchar(20)

    Set @Now         = GETUTCDATE()
    Set @ActionVerb  = Case When @IsUpdate = 1 Then ''updated'' Else ''added'' End
    Set @ActionLabel = Case When @IsUpdate = 1 Then ''Line Updated'' Else ''Line Added'' End

    Set @ActionComments = ''Vendor invoice line '' + @ActionVerb + '' via AI.''
                        + '' Invoice: ''     + @VoucherInvoiceNumber
                        + '', Line: ''       + CAST(ISNULL(@LineNumber, 0) as varchar(10))
                        + '', Description: '' + ISNULL(@ShortDescription, ''(none)'')
                        + '', Amount: ''     + CAST(ISNULL(@TotalCost, 0) as varchar(30))

    Exec sptActionLogInsert
         @Entity            = ''Voucher''
        ,@EntityKey         = @VoucherKey
        ,@CompanyKey        = @CompanyKey
        ,@ProjectKey        = @ProjectKey
        ,@Action            = @ActionLabel
        ,@ActionDate        = @Now
        ,@ActionBy          = null
        ,@Comments          = @ActionComments
        ,@Reference         = @VoucherInvoiceNumber
        ,@SourceCompanyID   = null
        ,@UserKey           = @UserKey
        ,@CampaignKey       = null

    -- ----------------------------------------------------------------
    -- Return
    -- ----------------------------------------------------------------
ReturnResult:

    -- Table[0]: errors and warnings (always returned)
    Select  errorType
           ,errorCode
           ,errorMessage
           ,fieldName
    From    #errors
    Order By errorType desc, fieldName

    -- Table[1]: success row (only when no fatal errors)
    Select @ErrorCount = COUNT(*) From #errors Where errorType = ''error''
    If @ErrorCount = 0
    Begin
        Select  @VoucherDetailKey                               as voucherDetailKey
               ,@VoucherKey                                     as voucherKey
               ,@VoucherInvoiceNumber                           as invoiceNumber
               ,ISNULL(@LineNumber, 0)                          as lineNumber
               ,ISNULL(@ShortDescription, '''')                   as shortDescription
               ,@TotalCost                                      as totalCost
               ,@Quantity                                       as quantity
               ,ISNULL(@Billable, 0)                            as billable
               ,ISNULL(@BillableCost, 0)                        as billableCost
               ,Case When @IsUpdate = 1 Then ''Updated'' Else ''Created'' End as statusLabel
    End

    Drop Table #errors


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIPurchaseOrderGet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIPurchaseOrderGet]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spApiAIPurchaseOrderGet]
(
    @CompanyKey             int,
    @UserKey                int,
    @PurchaseOrderNumber    varchar(30)
)

as --Encrypt

/*
|| When      Who Rel        What
|| 05/21/26  GRR 26.05.xx   Created - load PO header + open detail lines for vendor invoice pre-population.
||                          Called by the MCP add_vendor_invoice tool when orderNumber is supplied.
||                          Returns three result sets:
||                            Table[0]: errors / warnings (e.g. PO not found, not approved, PO closed)
||                            Table[1]: single header row with vendor, project, and GL context fields
||                            Table[2]: open (non-closed, non-cancelled) detail lines with names resolved
|| 05/21/26  GRR 26.05.xx   Added approval status check - PO must be approved (Status = 4) to create a vendor invoice.
|| 05/28/26  AI  26.05.28   spCheckAccess (tPurchaseOrder) replaces inline GL company check.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right purch_editpo.
*/

    Declare @PurchaseOrderKey       int
    Declare @POStatus               smallint
    Declare @POGLCompanyKey         int
    Declare @RestrictToGLCompany    int

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- ------------------------------------------------------------------
    -- Gating security: purch_editpo
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''purch_viewpo''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (purch_editpo).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    -- ----------------------------------------------------------------
    -- Validate input
    -- ----------------------------------------------------------------
    If @PurchaseOrderNumber Is Null Or LTRIM(RTRIM(@PurchaseOrderNumber)) = ''''
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''PurchaseOrderNumber is required.'', ''orderNumber'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Resolve PO number  key and status
    -- ----------------------------------------------------------------
    Select  @PurchaseOrderKey = PurchaseOrderKey
           ,@POStatus         = Status
           ,@POGLCompanyKey   = GLCompanyKey
    From    tPurchaseOrder (nolock)
    Where   CompanyKey          = @CompanyKey
    And     PurchaseOrderNumber = @PurchaseOrderNumber

    If @PurchaseOrderKey Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'',
                ''Purchase order not found: '' + @PurchaseOrderNumber + ''.'', ''orderNumber'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Approval check - PO must be approved (Status = 4) before a
    -- vendor invoice can be created against it.
    -- ----------------------------------------------------------------
    If ISNULL(@POStatus, 0) <> 4
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
                ''Purchase order '' + @PurchaseOrderNumber + '' is not approved. Only approved purchase orders can be used to create a vendor invoice.'',
                ''orderNumber'')
        Goto ReturnResult
    End

    -- ----------------------------------------------------------------
    -- Record-level access gate via spCheckAccess (tPurchaseOrder).
    -- spCheckAccess applies GL company restriction + admin bypass per entity.
    -- ----------------------------------------------------------------
    Declare @AccessOK int
    Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tPurchaseOrder'', @PurchaseOrderKey
    If @AccessOK <> 1
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You do not have access to purchase order '' + @PurchaseOrderNumber + ''.'',
                ''orderNumber'')
        Goto ReturnResult
    End

    -- Warn when the PO is closed (invoice creation is still allowed)
    If Exists (
        Select 1 From tPurchaseOrder (nolock)
        Where PurchaseOrderKey  = @PurchaseOrderKey
        And   ISNULL(Closed, 0) = 1
    )
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''warning'', ''INVALID_VALUE'',
                ''Purchase order '' + @PurchaseOrderNumber + '' is closed. The vendor invoice will still be created.'',
                ''orderNumber'')
    End

    -- ----------------------------------------------------------------
    -- Return
    -- ----------------------------------------------------------------
ReturnResult:

    -- Table[0]: errors / warnings
    Select  errorType, errorCode, errorMessage, fieldName
    From    #errors
    Order By errorType desc, fieldName

    -- Only return header + lines when there are no fatal errors
    Declare @ErrorCount int
    Select  @ErrorCount = COUNT(*) From #errors Where errorType = ''error''

    Drop Table #errors

    If @PurchaseOrderKey Is Null Or @ErrorCount > 0 Return

    -- Table[1]: PO header - fields that pre-populate the vendor invoice header
    Select  po.PurchaseOrderKey         as purchaseOrderKey
           ,po.PurchaseOrderNumber      as purchaseOrderNumber
           ,po.Description              as description
           ,po.DueDate                  as dueDate
           ,po.CurrencyID               as currencyID
           ,po.ExchangeRate             as exchangeRate
           ,po.Status                   as status
           ,ISNULL(po.Closed, 0)        as closed
           ,c.VendorID                  as vendorID
           ,c.CompanyName               as vendorName
           ,p.ProjectNumber             as projectNumber
           ,glc.GLCompanyID             as glCompanyID
           ,cl.ClassID                  as classID
           ,o.OfficeID                  as officeID
    From    tPurchaseOrder po (nolock)
            Inner Join tCompany c (nolock)
                On po.VendorKey = c.CompanyKey
            Left Outer Join tProject p (nolock)
                On po.ProjectKey = p.ProjectKey
            Left Outer Join tGLCompany glc (nolock)
                On po.GLCompanyKey = glc.GLCompanyKey
            Left Outer Join tClass cl (nolock)
                On po.ClassKey = cl.ClassKey
            Left Outer Join tOffice o (nolock)
                On p.OfficeKey = o.OfficeKey     -- office comes from the project, not the PO header
    Where   po.PurchaseOrderKey = @PurchaseOrderKey

    -- Table[2]: open PO detail lines - fields that pre-populate vendor invoice lines
    --          Only non-closed, non-cancelled lines are included.
    Select  pod.PurchaseOrderDetailKey  as purchaseOrderDetailKey
           ,pod.LineNumber              as lineNumber
           ,pod.ShortDescription        as shortDescription
           ,pod.TotalCost               as totalCost
           ,pod.Quantity                as quantity
           ,pod.UnitCost                as unitCost
           ,pod.UnitDescription         as unitDescription
           ,pod.UnitRate                as unitRate
           ,pod.Billable                as billable
           ,pod.Markup                  as markup
           ,pod.BillableCost            as billableCost
           ,pod.Taxable                 as taxable
           ,pod.Taxable2                as taxable2
           ,ISNULL(pod.AppliedCost, 0)  as appliedCost
           ,p.ProjectNumber             as projectNumber
           ,t.TaskID                    as taskID
           ,i.ItemID                    as itemID
           ,cl.ClassID                  as classID
           ,o.OfficeID                  as officeID
           ,dept.DepartmentName         as departmentName
    From    tPurchaseOrderDetail pod (nolock)
            Left Outer Join tProject p (nolock)
                On pod.ProjectKey = p.ProjectKey
            Left Outer Join tTask t (nolock)
                On pod.TaskKey = t.TaskKey
            Left Outer Join tItem i (nolock)
                On pod.ItemKey = i.ItemKey
            Left Outer Join tClass cl (nolock)
                On pod.ClassKey = cl.ClassKey
            Left Outer Join tOffice o (nolock)
                On pod.OfficeKey = o.OfficeKey
            Left Outer Join tDepartment dept (nolock)
                On pod.DepartmentKey = dept.DepartmentKey
    Where   pod.PurchaseOrderKey        = @PurchaseOrderKey
    And     ISNULL(pod.Closed, 0)       = 0
    And     ISNULL(pod.Cancelled, 0)    = 0
    Order By pod.LineNumber



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetConversations]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetConversations]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIGetConversations]
(
    @CompanyKey     int,
    @UserKey        int,
    @Entity         varchar(50)  = null,    -- REQUIRED. Caller-facing entity name: ''Project'', ''Company'',
                                            --   ''Voucher'', ''Invoice'', ''Campaign'', ''Contact'', ''User'', and the
                                            --   alias ''Opportunity'' (-> tLead).
    @EntityID       varchar(100) = null,    -- REQUIRED. Business identifier for that entity (e.g. ProjectNumber
                                            --   ''AB-2344-22''). Resolved to the internal key per @Entity.
    @StartDate      datetime     = null,
    @EndDate        datetime     = null,
    @MaxRows        int          = 500
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 04/29/26  AI  26.05.xx   Created for AI project conversations tool
|| 05/25/26  AI  26.05.25   Reworked to standards: #errors reporting + hard ACCESS_DENIED gate.
||                          Generic entity scoping via tActivityLink. Caller passes @Entity (table
||                          name minus ''t'') + @EntityID (business id); SP resolves to the internal key
||                          and matches tActivityLink.Entity (which stores the lookup table name,
||                          e.g. ''tProject''). ''Opportunity'' is an alias that resolves in tLead.
||                          Supported @Entity values: Project, Opportunity, Company, Campaign,
||                          Voucher, Invoice, Contact. (Retainer/Task intentionally excluded.)
|| 05/25/26  AI  26.05.25   Record-level access now delegated to spCheckAccess (per-entity GL company /
||                          assignment / folder / client-login rules) instead of inline filters. The
||                          spCheckAccess entity name = @LinkEntity, except Contact -> ''tUser_Contact''.
|| 07/10/26  GAR 26.07.19   Added gating security - requires useActivities; viewOtherActivities gates activities not assigned to the caller.
|| 07/15/26  GAR 26.08.16   (730928) Added ''User'' entity (internal employees, resolved by CompanyKey/OwnerCompanyKey
||                          same as Contact but scoped to staff). spCheckAccess entity = ''tUser_Employee''.
|| 07/16/26  GAR 26.08.16   (730928) For entity = User/Contact, result set 2 now also surfaces activities addressed
||                          to that person via tActivityEmail (email recipients), excluding ActivityEntity
||                          = ''ToDo'', in addition to the existing tActivityLink match.
*/

set nocount on

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @SecurityGroupKey       int
    declare @LinkEntity             varchar(50)     -- literal value stored in tActivityLink.Entity (e.g. ''tProject'')
    declare @CheckEntity            varchar(50)     -- entity name passed to spCheckAccess (usually = @LinkEntity;
                                                    --   differs for Contact -> ''tUser_Contact'' and
                                                    --   User -> ''tUser_Employee'')
    declare @EffectiveEntityKey     int             -- resolved internal key
    declare @AccessOK               int
    declare @ErrorCount             int

    if @MaxRows is null or @MaxRows <= 0
        set @MaxRows = 500

    -- ------------------------------------------------------------------
    -- 2. Validate the user (spCheckAccess handles per-entity access below)
    -- ------------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock)
    where  UserKey    = @UserKey
      and  CompanyKey = @CompanyKey

    if @SecurityGroupKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- Gating security: useActivities (base right to view conversations).
    -- viewOtherActivities controls whether activities NOT assigned to the
    -- caller are visible; without it, results are restricted to the caller''s
    -- own activities (see WHERE clause below).
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint
    declare @gsCanViewOthers    tinyint = 0

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''useActivities''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (useActivities).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    -- Admins and users with viewOtherActivities can see activities assigned to anyone.
    if @gsIsAdministrator = 1
        set @gsCanViewOthers = 1
    else if exists (
            select 1
            from   tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where  ra.EntityType = ''Security Group''
              and  ra.EntityKey  = @gsSecurityGroupKey
              and  r.RightID     = ''viewOtherActivities''
        )
        set @gsCanViewOthers = 1

    -- ------------------------------------------------------------------
    -- 3. entity + entityID are REQUIRED
    -- ------------------------------------------------------------------
    if @Entity is null or LTRIM(RTRIM(@Entity)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''entity is required.'', ''entity'')

    if @EntityID is null or LTRIM(RTRIM(@EntityID)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''entityID is required.'', ''entityID'')

    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -100
    end

    -- ------------------------------------------------------------------
    -- 4. Resolve @Entity + @EntityID -> @LinkEntity + @EffectiveEntityKey
    --    @LinkEntity is the literal string in tActivityLink.Entity (with ''t'').
    -- ------------------------------------------------------------------
    begin
        -- ---- Project --------------------------------------------------
        if @Entity = ''Project''
        begin
            set @LinkEntity = ''tProject''

            select @EffectiveEntityKey = ProjectKey
            from   tProject (nolock)
            where  CompanyKey    = @CompanyKey
              and  ProjectNumber = @EntityID
        end

        -- ---- Opportunity (record lives in tLead) ----------------------
        else if @Entity = ''Opportunity''
        begin
            set @LinkEntity = ''tLead''

            select @EffectiveEntityKey = LeadKey
            from   tLead (nolock)
            where  CompanyKey = @CompanyKey
              and  LeadID     = TRY_CONVERT(int, @EntityID)
        end

        -- ---- Company (client or vendor) -------------------------------
        else if @Entity = ''Company''
        begin
            set @LinkEntity = ''tCompany''

            select @EffectiveEntityKey = CompanyKey
            from   tCompany (nolock)
            where  OwnerCompanyKey = @CompanyKey
              and  (   UPPER(CustomerID)  = UPPER(@EntityID)
                    or UPPER(VendorID)    = UPPER(@EntityID)
                    or UPPER(CompanyName) = UPPER(@EntityID) )
        end

        -- ---- Campaign -------------------------------------------------
        else if @Entity = ''Campaign''
        begin
            set @LinkEntity = ''tCampaign''

            select @EffectiveEntityKey = CampaignKey
            from   tCampaign (nolock)
            where  CompanyKey = @CompanyKey
              and  UPPER(CampaignID) = UPPER(@EntityID)
        end

        -- ---- Voucher (resolve on the vendor InvoiceNumber) ------------
        else if @Entity = ''Voucher''
        begin
            set @LinkEntity = ''tVoucher''

            select @EffectiveEntityKey = MAX(VoucherKey)
            from   tVoucher (nolock)
            where  CompanyKey    = @CompanyKey
              and  InvoiceNumber = @EntityID
        end

        -- ---- Invoice (resolve on the client InvoiceNumber) ------------
        else if @Entity = ''Invoice''
        begin
            set @LinkEntity = ''tInvoice''

            select @EffectiveEntityKey = MAX(InvoiceKey)
            from   tInvoice (nolock)
            where  CompanyKey    = @CompanyKey
              and  InvoiceNumber = @EntityID
        end

        -- ---- Contact (record lives in tUser) --------------------------
        --  NOTE: link string still to be confirmed - earlier guidance said
        --  the literal is ''Contact'', but the table-name rule would make it
        --  ''tUser''. Using ''tUser'' for now to match the other branches.
        else if @Entity = ''Contact''
        begin
            set @LinkEntity = ''tUser''

            select top 1 @EffectiveEntityKey = UserKey
            from   tUser (nolock)
            where  OwnerCompanyKey = @CompanyKey
              and  (   UPPER(FirstName + '' '' + LastName) = UPPER(@EntityID)
                    or UPPER(Email) = UPPER(@EntityID) )
        end

        -- ---- User (internal employee; record also lives in tUser) -----
        --  Same underlying table as Contact, but scoped by CompanyKey
        --  (staff belong to the tenant company) instead of OwnerCompanyKey
        --  (contacts belong to a client/vendor the tenant owns). Uses
        --  ISNULL(OwnerCompanyKey, CompanyKey) to match the identity
        --  predicate used by the ''tUser_Employee'' access check below.
        else if @Entity = ''User''
        begin
            set @LinkEntity = ''tUser''

            select top 1 @EffectiveEntityKey = UserKey
            from   tUser (nolock)
            where  ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
              and  (   UPPER(FirstName + '' '' + LastName) = UPPER(@EntityID)
                    or UPPER(Email) = UPPER(@EntityID) )
        end

        -- ---- Unsupported ----------------------------------------------
        else
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''INVALID_VALUE'',
                    ''Entity not supported. Valid values: Project, Opportunity, Company, Campaign, Voucher, Invoice, Contact, User.'',
                    ''entity'')
        end

        -- Not-found check (shared across the resolved entities above)
        if @LinkEntity is not null and @EffectiveEntityKey is null
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', @Entity + '' not found for entityID: '' + @EntityID, ''entityID'')
        end

        -- Stop on resolution errors (not found / unsupported)
        select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
        if @ErrorCount > 0
        begin
            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName

            drop table #errors
            return -101
        end

        -- ---- Record-level access gate (universal) ---------------------
        --  spCheckAccess encodes the per-entity GL company / assignment /
        --  folder / client-login rules. Its @Entity name usually equals
        --  @LinkEntity; Contact and User are exceptions (both link ''tUser''
        --  but check ''tUser_Contact'' / ''tUser_Employee'' respectively).
        set @CheckEntity = @LinkEntity
        if @Entity = ''Contact''
            set @CheckEntity = ''tUser_Contact''
        if @Entity = ''User''
            set @CheckEntity = ''tUser_Employee''

        exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, @CheckEntity, @EffectiveEntityKey

        if @AccessOK <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''User does not have access to this '' + @Entity + ''.'', ''entityID'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName

            drop table #errors
            return -103
        end
    end

    -- ------------------------------------------------------------------
    -- 5. Result set 1: warnings (non-fatal)
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from   #errors where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 6. Result set 2: conversations (diary activities)
    --    The user''s access to the entity was already gated by spCheckAccess
    --    above, so this just scopes to the resolved entity via tActivityLink
    --    (al.Entity = @LinkEntity, al.EntityKey = resolved key) and narrows by
    --    @StartDate/@EndDate. The tActivityLink PK is (ActivityKey, Entity,
    --    EntityKey), so the left join yields at most one row per activity
    --    from that side.
    --    For entity = User/Contact, an activity also qualifies if it''s
    --    addressed to that person via tActivityEmail (ae.UserKey - same
    --    tUser key space Contact/User resolve to), excluding ActivityEntity
    --    = ''ToDo''. This surfaces emails/notes naming the person even when
    --    they were never explicitly tActivityLink''d to their tUser record.
    --    Combined with an OR (not a join) so each activity still returns
    --    at most one row.
    -- ------------------------------------------------------------------
    select top (@MaxRows)
            a.ActivityKey        as activityKey,
            a.Subject            as subject,
            a.Notes              as notes,
            a.ActivityDate       as activityDate,
            a.DateUpdated        as dateUpdated,
            a.RootActivityKey    as rootActivityKey,
            a.ParentActivityKey  as parentActivityKey,
            a.ProjectKey         as projectKey,
            p.ProjectNumber      as projectNumber,
            @Entity              as entity,
            @EntityID            as entityID,
            @EffectiveEntityKey  as entityKey
    from    tActivity a (nolock)
    left join tActivityLink al (nolock)
            on al.ActivityKey = a.ActivityKey
           and al.Entity      = @LinkEntity
           and al.EntityKey   = @EffectiveEntityKey
    left join tProject p (nolock) on a.ProjectKey = p.ProjectKey
    where   a.CompanyKey   = @CompanyKey
      and   (
                al.ActivityKey is not null
                or (
                        @Entity in (''User'', ''Contact'')
                    and ISNULL(a.ActivityEntity, '''') <> ''ToDo''
                    and exists (
                            select 1
                            from   tActivityEmail ae (nolock)
                            where  ae.ActivityKey = a.ActivityKey
                              and  ae.UserKey      = @EffectiveEntityKey
                        )
                )
            )
      and   (@StartDate is null or a.ActivityDate >= @StartDate)
      and   (@EndDate   is null or a.ActivityDate <= @EndDate)
      and   (@gsCanViewOthers = 1 or a.AssignedUserKey = @UserKey)
    order by a.ActivityDate desc, a.ActivityKey desc

    drop table #errors
    return 0


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPreferenceUpdateVisualApp]'
GO
IF OBJECT_ID(N'[dbo].[sptPreferenceUpdateVisualApp]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[sptPreferenceUpdateVisualApp] (
	@CompanyKey int,
	@ReportFont varchar(100),
	@ReportTitleFontSize int,
	@ReportConditionsFontSize int,
	@ReportTopLabelsFontSize int,
	@ReportGroupFontSize int,
	@ReportDetailFontSize int,
	@ReportSubTotalFontSize int,
	@ReportGrandTotalFontSize int,
	@ReportPageFooterFontSize int,
	@Culture int,
	@ApplicationName varchar(200),
	@DesktopImageSetting varchar(30),
	@DesktopImageIndex int,
	@DesktopLogoPosition int,
	@TimeZoneIndex int,
	@LanguageID varchar(10) = NULL,
	@ShowClientPortalLogo int,
	@Theme smallint = 1,
	@AppBackgroundColor varchar(30) = NULL,
	@AppBarColor varchar(30) = NULL,
	@AppMenuColor varchar(30) = NULL,
	@AppAccentColor varchar(30) = NULL,
	@AppBodyColor varchar(20) = NULL,
	@AppDarkMode varchar(10) = ''light''
)
AS
/*
|| When      Who Rel               What
|| 11/30/23  AMP 23.12.17 (651842) Added @ShowClientPortalLogo to hide/show the Report Logo on the Client Portal
|| 2/1/25   GWG 25.02.16  Added in Theme calls
|| 7/7/26   GWG           WJ 2026 application color tweaks + light/dark surface mode
|| 7/8/26   GWG           Added @AppBodyColor tweak (page body background)
*/

	UPDATE
		tPreference
	SET
		ReportFont = @ReportFont,
		ReportTitleFontSize = @ReportTitleFontSize,
		ReportConditionsFontSize = @ReportConditionsFontSize,
		ReportTopLabelsFontSize = @ReportTopLabelsFontSize,
		ReportGroupFontSize = @ReportGroupFontSize,
		ReportDetailFontSize = @ReportDetailFontSize,
		ReportSubTotalFontSize = @ReportSubTotalFontSize,
		ReportGrandTotalFontSize = @ReportGrandTotalFontSize,
		ReportPageFooterFontSize = @ReportPageFooterFontSize,
		Culture = @Culture,
		ApplicationName = @ApplicationName,
		DesktopImageSetting = @DesktopImageSetting,
		DesktopImageIndex = @DesktopImageIndex,
		DesktopLogoPosition = @DesktopLogoPosition,
	    ShowClientPortalLogo = @ShowClientPortalLogo,
		LanguageID = @LanguageID,
		Theme = @Theme,
		AppBackgroundColor = @AppBackgroundColor,
		AppBarColor = @AppBarColor,
		AppMenuColor = @AppMenuColor,
		AppAccentColor = @AppAccentColor,
		AppBodyColor = @AppBodyColor,
		AppDarkMode = @AppDarkMode
	WHERE
		CompanyKey = @CompanyKey

	UPDATE
		tCompany
	SET
		TimeZoneIndex = @TimeZoneIndex
	WHERE
		CompanyKey = @CompanyKey 



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCF_tFieldDefInsert]'
GO
IF OBJECT_ID(N'[dbo].[spCF_tFieldDefInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spCF_tFieldDefInsert]
 @OwnerEntityKey int,
 @AssociatedEntity varchar(50),
 @FieldName varchar(75),
 @Description varchar(300),
 @DisplayType smallint,
 @Caption varchar(1000),
 @Hint varchar(1000),
 @Size int,
 @MinSize int,
 @MaxSize int,
 @TextRows int,
 @ValueList text,
 @Required tinyint,
 @Active tinyint,
 @OnlyAuthorEdit tinyint,
 @MapTo int,
 @DisplayViewMode tinyint,
 @DisplayWhen tinyint,
 @DisplayWhenFieldDefKey int,
 @DisplayWhenValue nvarchar(1000),
 @DefaultValue nvarchar(max) = NULL,
 @DoNotCopy tinyint = 0, 
 @DisplayWhenMatchType tinyint = 0,
 @ParentFieldDefKey int = NULL,
 @DecimalPlaces int = 0,
 @oIdentity INT OUTPUT
AS --Encrypt

/*
|| When      Who Rel     What
|| 07/23/10  GHL 10.532  Added MapTo param...FieldDef for RequestDef can be mapped to a FieldDef for projects 
|| 06/22/11  GHL 10.545  (114355) Changed @ValueList from varchar(4000) to text
|| 11/15/13  RLB 10.574  (190288) increaded Hint to varchar(300)
|| 03/04/14  MFT 10.577  (207360) Set the Return param as expected by code
|| 11/19/15  MAS 10.599  (278451) Added DisplayViewMode to support display only CF
|| 02/25/15  MAS 10.601  (278448) Added DisplayWhen, DisplayWhenFieldDefKey & @DisplayWhenValue to support conditional CFs
|| 05/18/16  MCM 10.606  (295808) Increased size of Caption and Hint to 1000 Characters
|| 01/10/17  GWG 18.2	 Added default value and do not copy
|| 08/24/18  WDF 18.9.0  (416610) Change ''DisplayWhenValue'' from varchar(50) to varchar(1000)
|| 12/18/18  WDF 19.02.0 (416610) Added ''DisplayWhenMatchType''
|| 1/22/19   GWG 19.0.2  (440922) Adding parent field capability
|| 2/22/19   GWG 19.0.3   Adding decimal places
|| 06/26/20  RLS 20.0.7  (518686) Converted DisplayWhenValue and DefaultValue to nvarchar
*/

SELECT @oIdentity = FieldDefKey
FROM tFieldDef (nolock)
WHERE
	FieldName = @FieldName AND
  OwnerEntityKey = @OwnerEntityKey AND
  AssociatedEntity = @AssociatedEntity

IF ISNULL(@oIdentity, 0) > 0
  RETURN -1

INSERT tFieldDef
  (
  OwnerEntityKey,
  AssociatedEntity,
  FieldName,
  Description,
  DisplayType,
  Caption,
  Hint,
  Size,
  MinSize,
  MaxSize,
  TextRows,
  ValueList,
  Required,
  Active,
  OnlyAuthorEdit,
  MapTo,
  DisplayViewMode,
  DisplayWhen,
  DisplayWhenFieldDefKey,
  DisplayWhenValue,
  DefaultValue,
  DoNotCopy,
  DisplayWhenMatchType,
  ParentFieldDefKey,
  DecimalPlaces
  )
 VALUES
  (
  @OwnerEntityKey,
  @AssociatedEntity,
  @FieldName,
  @Description,
  @DisplayType,
  @Caption,
  @Hint,
  @Size,
  @MinSize,
  @MaxSize,
  @TextRows,
  @ValueList,
  @Required,
  @Active,
  @OnlyAuthorEdit,
  @MapTo,
  @DisplayViewMode,
  @DisplayWhen,
  @DisplayWhenFieldDefKey,
  @DisplayWhenValue,
  @DefaultValue,
  @DoNotCopy,
  @DisplayWhenMatchType,
  @ParentFieldDefKey,
  @DecimalPlaces
  )
 
SELECT @oIdentity = @@IDENTITY

RETURN @oIdentity'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAISpecSheetGetList]'
GO
IF OBJECT_ID(N'[dbo].[spApiAISpecSheetGetList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAISpecSheetGetList]
(
    @CompanyKey     int,
    @UserKey        int,
    @Entity         varchar(50),
    @EntityNumber   varchar(100)
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/01/26  GRR 26.05.xx   Created
|| 05/04/26  GRR 26.05.xx   Accept EntityNumber instead of EntityKey; resolve key from entity table
|| 05/25/26  AI  26.05.25   Replaced inline Project-only access check with spCheckAccess. Lead /
||                          ProjectRequest / Campaign are now access-gated too (they had no check
||                          previously beyond CompanyKey isolation).
|| 05/28/26  AI  26.05.28   spCheckAccess per entity (Project/Lead/ProjectRequest/Campaign) replaces inline Project-only check.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right prjviewspecs.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @EntityKey   int
    declare @CheckEntity varchar(50)
    declare @AccessOK    int
    declare @ErrorCount  int

    -- Required-field validation
    if @Entity is null or LTRIM(RTRIM(@Entity)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''Entity is required.'', ''entity'')

    if @EntityNumber is null or LTRIM(RTRIM(@EntityNumber)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''EntityNumber is required.'', ''entityNumber'')

    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -100
    end

    if @Entity not in (''Project'', ''Lead'', ''Leads'', ''ProjectRequest'', ''Campaign'')
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''Entity must be one of: Project, Lead, ProjectRequest, Campaign.'', ''entity'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -102
    end

    -- Validate user
    if not exists (
        select 1 from tUser (nolock) where UserKey = @UserKey and CompanyKey = @CompanyKey
    )
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- Gating security: prjviewspecs
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''prjviewspecs''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (prjviewspecs).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    -- ------------------------------------------------------------------
    -- Resolve entity number -> entity key + pick spCheckAccess entity name
    -- ------------------------------------------------------------------
    if @Entity = ''Project''
    begin
        select @EntityKey = ProjectKey
        from   tProject (nolock)
        where  CompanyKey = @CompanyKey and ProjectNumber = @EntityNumber

        set @CheckEntity = ''tProject''
    end
    else if @Entity in (''Lead'', ''Leads'')
    begin
        select @EntityKey = LeadKey
        from   tLead (nolock)
        where  CompanyKey = @CompanyKey and LeadID = TRY_CAST(@EntityNumber as int)

        set @CheckEntity = ''tLead''
    end
    else if @Entity = ''ProjectRequest''
    begin
        select @EntityKey = RequestKey
        from   tRequest (nolock)
        where  CompanyKey = @CompanyKey and RequestID = @EntityNumber

        set @CheckEntity = ''tRequest''
    end
    else if @Entity = ''Campaign''
    begin
        select @EntityKey = CampaignKey
        from   tCampaign (nolock)
        where  CompanyKey = @CompanyKey and CampaignID = @EntityNumber

        set @CheckEntity = ''tCampaign''
    end

    if @EntityKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', @Entity + '' not found for entityNumber: '' + @EntityNumber, ''entityNumber'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- spCheckAccess gate (covers GL company, assignment, folder rules)
    -- ------------------------------------------------------------------
    exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, @CheckEntity, @EntityKey

    if @AccessOK <> 1
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''You do not have access to this '' + @Entity + ''.'', ''entityNumber'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- Warnings + spec sheets
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    select  ss.SpecSheetKey     as specSheetKey,
            ss.Subject          as subject,
            ss.Description      as description,
            ss.SpecID           as specID,
            ss.Version          as version,
            ss.Status           as status,
            ss.DraftMode        as draftMode,
            ss.DisplayOrder     as displayOrder,
            ss.CreatedByDate    as createdByDate,
            ss.DateUpdated      as dateUpdated
    from    tSpecSheet ss (nolock)
    where   ss.Entity    = @Entity
      and   ss.EntityKey = @EntityKey
    order by ss.DisplayOrder, ss.Subject

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIExpenseEnvelopeGetList]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseEnvelopeGetList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIExpenseEnvelopeGetList]
    (
        @CompanyKey     int,
        @UserKey        int,
        @TargetUserName varchar(100) = NULL,
        @Status         varchar(20)  = NULL   -- Unsubmitted, Submitted, Rejected, Approved; NULL returns Unsubmitted/Submitted/Rejected
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/05/26  GRR 26.05.xx   Created
|| 05/28/26  AI  26.05.28   spCheckAccess (tUser_Contact) replaces inline GL company check on the target user case. Includes tGLCompanyAccess + folder fallback.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billingviewallexpense.
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @TargetUserKey          int
    Declare @TargetGLCompanyKey     int
    Declare @StatusNum              smallint

    -- ------------------------------------------------------------------
    -- Gating security: billingviewallexpense
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billingviewallexpense''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billingviewallexpense).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- Convert status text to numeric value
    If @Status Is Not Null And LTRIM(RTRIM(@Status)) <> ''''
    Begin
        Select @StatusNum = Case LOWER(LTRIM(RTRIM(@Status)))
                                When ''unsubmitted'' Then 1
                                When ''submitted''   Then 2
                                When ''rejected''    Then 3
                                When ''approved''    Then 4
                                Else Null
                            End

        If @StatusNum Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''INVALID_VALUE'', ''Status must be one of: Unsubmitted, Submitted, Rejected, Approved.'', ''status'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -102
        End
    End

    -- Load user security context
    Select  @SecurityGroupKey   = SecurityGroupKey,
            @IsAdministrator    = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
    And     CompanyKey  = @CompanyKey

    -- Determine target user
    If @TargetUserName Is Not Null And LTRIM(RTRIM(@TargetUserName)) <> ''''
    Begin
        -- Caller must have billingviewallexpense right (or be an admin) to view another user''s expenses
        If @IsAdministrator = 0
        Begin
            If Not Exists (
                Select  1
                From    tRight r (nolock)
                Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
                Where   ra.EntityType   = ''Security Group''
                And     ra.EntityKey    = @SecurityGroupKey
                And     r.RightID       = ''billingviewallexpense''
            )
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to view other users'''' expense reports.'', ''userName'')

                Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                Drop Table #errors
                Return -103
            End
        End

        -- Resolve TargetUserName by searching UserID, full name, and Email
        Declare @MatchCount int

        Select  @MatchCount = COUNT(*)
        From    tUser (nolock)
        Where CompanyKey = @CompanyKey
		And ISNULL(Active,0) = 1
		And (FirstName + '' '' + LastName LIKE ''%'' + @TargetUserName + ''%''
				Or UserID Like ''%'' + @TargetUserName + ''%''
				Or Email Like ''%'' + @TargetUserName + ''%''
			)

        If @MatchCount > 1
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''INVALID_VALUE'', ''Multiple users matched. Please use a unique identifier such as UserID or email address.'', ''userName'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -102
        End

        Select  @TargetUserKey      = UserKey,
                @TargetGLCompanyKey = GLCompanyKey
        From    tUser (nolock)
        Where   CompanyKey  = @CompanyKey
        And ISNULL(Active,0) = 1
		And (FirstName + '' '' + LastName LIKE ''%'' + @TargetUserName + ''%''
				Or UserID Like ''%'' + @TargetUserName + ''%''
				Or Email Like ''%'' + @TargetUserName + ''%''
			)

        If @TargetUserKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''User not found.'', ''userName'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -101
        End

        -- Record-level access gate via spCheckAccess (tUser_Employee) - replaces
        -- the inline GL company check with the per-entity rules (tGLCompanyAccess
        -- fallback + folder security + admin bypass).
        Declare @AccessOK int
        Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tUser_Employee'', @TargetUserKey
        If @AccessOK <> 1
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'', ''You do not have access to view this user''''s expense reports.'', ''userName'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -103
        End
    End
    Else
    Begin
        -- No target user specified: return the calling user''s own expense reports
        Set @TargetUserKey = @UserKey
    End

    -- Return expense envelopes for the target user
    Select  e.ExpenseEnvelopeKey    as expenseEnvelopeKey,
            e.EnvelopeNumber        as envelopeNumber,
            e.StartDate             as startDate,
            e.EndDate               as endDate,
            e.Status                as status,
            e.Paid                  as paid,
            e.DateCreated           as dateCreated,
            e.DateSubmitted         as dateSubmitted,
            e.DateApproved          as dateApproved,
            e.ApprovalComments      as approvalComments,
            e.Comments              as comments,
            e.UserKey               as userKey,
            u.UserName              as userName
    From    tExpenseEnvelope e (nolock)
    Inner Join vUserName u On e.UserKey = u.UserKey
    Where   e.CompanyKey    = @CompanyKey
    And     e.UserKey       = @TargetUserKey
    And     (@StatusNum Is Not Null And e.Status = @StatusNum
             Or @StatusNum Is Null  And e.Status In (1, 2, 3))
    Order By e.DateCreated Desc

    Drop Table #errors


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserAssignToAllProjects]'
GO
IF OBJECT_ID(N'[dbo].[sptUserAssignToAllProjects]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptUserAssignToAllProjects]

	(
		@UserKey int
		,@Active int = 1	-- 1 Active, 0 Inactive, -1 All
		,@SpecificClientKey int = 0
		,@SpecificStatusKey int = 0
		,@ProjectTypeKey int = 0
		,@SameAsPersonKey int = 0
		,@ReplacePerson int = 0
		,@SpecificGLKey int = 0
		,@SpecificCampaignKey int = 0
	)

AS --Encrypt

/*
|| When      Who Rel		What
|| 10/24/09  MAS 10.5.1.3   Added additonal options for WMJ to assign to specific Client, Project or "Same As person"
|| 05/04/10  MAS 10.5.2.1   (79102)Fixed two issues;  Added "and tAssignment.UserKey <> @UserKey" to the tAssignment Join
							replaced @ReplacePerson with @SameAsPersonKey in the spProjectReassignUser call
|| 12/1/10   RLB 10.5.3.9   (94833) Just adding default service for new user on projects
|| 02/6/12   RLB 10.5.6.5   (167736) Added by project type to list
|| 09/01/17  GAR 10.6.1.9   (361121) When replacing person, honor active parameter in projects loop
|| 02/15/23  RLB 23.03.19   (630130) added option from gl company
|| 07/01/26  RLB 26.07.01   (730767) Added Specific Campaign option. When set, assigns to every project on the campaign (direct or via segment), combines with @Active options
*/

Declare @CompanyKey int, @Rate money, @DefaultServiceKey int

Select @CompanyKey = ISNULL(OwnerCompanyKey, CompanyKey), @Rate = HourlyRate, @DefaultServiceKey = DefaultServiceKey 
From tUser (nolock)
Where UserKey = @UserKey

if @ReplacePerson = 0 
	Begin
		if @DefaultServiceKey IS NOT NULL
				BEGIN
					Insert	tProjectUserServices (ProjectKey, UserKey, ServiceKey)
					Select ProjectKey, @UserKey, @DefaultServiceKey
					 From 
						(select	DISTINCT tProject.ProjectKey
							from	tProject (NOLOCK)
							Left Outer Join tAssignment (Nolock) on tProject.ProjectKey = tAssignment.ProjectKey
							Left Outer Join tCampaignSegment (NOLOCK) on tProject.CampaignSegmentKey = tCampaignSegment.CampaignSegmentKey
							Where	tProject.CompanyKey = @CompanyKey
							And tProject.ProjectKey NOT IN ( Select DISTINCT tProject.ProjectKey
							  from tProject (NOLOCK)
							  Join tAssignment (NOLOCK) on tAssignment.ProjectKey = tProject.ProjectKey And tAssignment.UserKey = @UserKey
							  Where CompanyKey = @CompanyKey )
							And	((@Active = 1 And tProject.Active = 1) Or (@Active = 0 And tProject.Active = 0)
								Or (@Active = -1))
							And ( ISNULL(@SpecificClientKey,0) > 0 and tProject.ClientKey = ISNULL(@SpecificClientKey,0)
								or (ISNULL(@SpecificClientKey,0) = 0 ))
							And ( ISNULL(@SpecificStatusKey,0) > 0 and tProject.ProjectStatusKey = ISNULL(@SpecificStatusKey,0)
								or (ISNULL(@SpecificStatusKey,0) = 0 ))
							And ( ISNULL(@ProjectTypeKey,0) > 0 and tProject.ProjectTypeKey = ISNULL(@ProjectTypeKey,0)
								or (ISNULL(@ProjectTypeKey,0) = 0 ))
							And ( ISNULL(@SameAsPersonKey,0) > 0 and tAssignment.UserKey = ISNULL(@SameAsPersonKey,0)
								or (ISNULL(@SameAsPersonKey,0) = 0  ))
							And ( ISNULL(@SpecificGLKey,0) > 0 and tProject.GLCompanyKey = ISNULL(@SpecificGLKey,0)
								or (ISNULL(@SpecificGLKey,0) = 0 ))
							And ( ISNULL(@SpecificCampaignKey,0) > 0 and (tProject.CampaignKey = ISNULL(@SpecificCampaignKey,0) Or tCampaignSegment.CampaignKey = ISNULL(@SpecificCampaignKey,0))
								or (ISNULL(@SpecificCampaignKey,0) = 0 ))
						) as tAs2
				END

		Insert	tAssignment (ProjectKey, UserKey, HourlyRate)
		Select ProjectKey, @UserKey, @Rate
		 From 
			(select	DISTINCT tProject.ProjectKey
				from	tProject (NOLOCK)
				Left Outer Join tAssignment (Nolock) on tProject.ProjectKey = tAssignment.ProjectKey
				Left Outer Join tCampaignSegment (NOLOCK) on tProject.CampaignSegmentKey = tCampaignSegment.CampaignSegmentKey
				Where	tProject.CompanyKey = @CompanyKey
				And tProject.ProjectKey NOT IN ( Select DISTINCT tProject.ProjectKey
				  from tProject (NOLOCK)
				  Join tAssignment (NOLOCK) on tAssignment.ProjectKey = tProject.ProjectKey And tAssignment.UserKey = @UserKey
				  Where CompanyKey = @CompanyKey )
				And	((@Active = 1 And tProject.Active = 1) Or (@Active = 0 And tProject.Active = 0)
					Or (@Active = -1))
				And ( ISNULL(@SpecificClientKey,0) > 0 and tProject.ClientKey = ISNULL(@SpecificClientKey,0)
					or (ISNULL(@SpecificClientKey,0) = 0 ))
				And ( ISNULL(@SpecificStatusKey,0) > 0 and tProject.ProjectStatusKey = ISNULL(@SpecificStatusKey,0)
					or (ISNULL(@SpecificStatusKey,0) = 0 ))
				And ( ISNULL(@ProjectTypeKey,0) > 0 and tProject.ProjectTypeKey = ISNULL(@ProjectTypeKey,0)
								or (ISNULL(@ProjectTypeKey,0) = 0 ))
				And ( ISNULL(@SameAsPersonKey,0) > 0 and tAssignment.UserKey = ISNULL(@SameAsPersonKey,0)
					or (ISNULL(@SameAsPersonKey,0) = 0  ))
				And ( ISNULL(@SpecificGLKey,0) > 0 and tProject.GLCompanyKey = ISNULL(@SpecificGLKey,0)
								or (ISNULL(@SpecificGLKey,0) = 0 ))
				And ( ISNULL(@SpecificCampaignKey,0) > 0 and (tProject.CampaignKey = ISNULL(@SpecificCampaignKey,0) Or tCampaignSegment.CampaignKey = ISNULL(@SpecificCampaignKey,0))
					or (ISNULL(@SpecificCampaignKey,0) = 0 ))
			) as tAs

			
	End
    
Else
	Begin
	-- Replace @SameAsPersonKey records with @UserKey and @Rate
	Declare @CurKey int, @RetVal int
				 
		Select @CurKey = -1
			While 1=1
			begin
				Select @CurKey = Min(ProjectKey) from tProject (NOLOCK) Where ProjectKey > @CurKey and tProject.CompanyKey = @CompanyKey 
					And	((@Active = 1 And tProject.Active = 1) Or (@Active = 0 And tProject.Active = 0) Or (@Active = -1))
				if @CurKey is null
					Break

				--             spProjectReassignUser ProjectKey, OldUserKey, NewUserKey
				exec @RetVal = spProjectReassignUser @CurKey, @SameAsPersonKey, @UserKey
				if @RetVal = -1
					return @CurKey
			end

		return 0	
	End

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIExpenseEnvelopeGet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseEnvelopeGet]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIExpenseEnvelopeGet]
    (
        @CompanyKey     int,
        @UserKey        int,
        @EnvelopeNumber varchar(100)
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/05/26  GRR 26.05.xx   Created
|| 05/28/26  AI  26.05.28   spCheckAccess (tExpenseEnvelope) replaces inline GL company check.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billinguseexpenses.
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @ExpenseEnvelopeKey     int
    Declare @EnvelopeUserKey        int
    Declare @EnvelopeGLCompanyKey   int

    -- ------------------------------------------------------------------
    -- Gating security: billinguseexpenses
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billinguseexpenses''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billinguseexpenses).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- Validate required parameter
    If @EnvelopeNumber Is Null Or LTRIM(RTRIM(@EnvelopeNumber)) = ''''
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''EnvelopeNumber is required.'', ''envelopeNumber'')

        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -100
    End

    -- Resolve EnvelopeNumber to key; capture the owner''s UserKey and GLCompanyKey for security checks
    Select  @ExpenseEnvelopeKey   = e.ExpenseEnvelopeKey,
            @EnvelopeUserKey      = e.UserKey,
            @EnvelopeGLCompanyKey = u.GLCompanyKey
    From    tExpenseEnvelope e (nolock)
    Inner Join tUser u (nolock) On e.UserKey = u.UserKey
    Where   e.CompanyKey    = @CompanyKey
    And     e.EnvelopeNumber = @EnvelopeNumber

    If @ExpenseEnvelopeKey Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Expense envelope not found.'', ''envelopeNumber'')

        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -101
    End

    -- Load calling user''s security context
    Select  @SecurityGroupKey   = SecurityGroupKey,
            @IsAdministrator    = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
    And     CompanyKey  = @CompanyKey

    -- Users may always view their own envelopes; only enforce extra checks for other users'' envelopes
    If @EnvelopeUserKey <> @UserKey
    Begin
        -- Must have billingviewallexpense right (or be an admin) to view another user''s envelope
        If @IsAdministrator = 0
        Begin
            If Not Exists (
                Select  1
                From    tRight r (nolock)
                Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
                Where   ra.EntityType   = ''Security Group''
                And     ra.EntityKey    = @SecurityGroupKey
                And     r.RightID       = ''billingviewallexpense''
            )
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to view other users'''' expense reports.'', ''envelopeNumber'')

                Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                Drop Table #errors
                Return -103
            End
        End

        -- Record-level access gate via spCheckAccess (tExpenseEnvelope) - replaces the
        -- inline GL company check with the per-entity rules in spCheckAccess.
        Declare @AccessOK int
        Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tExpenseEnvelope'', @ExpenseEnvelopeKey
        If @AccessOK <> 1
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'', ''You do not have access to this expense report.'', ''envelopeNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -103
        End
    End

    -- Result set 1: Envelope header with totals
    Select  e.ExpenseEnvelopeKey    as expenseEnvelopeKey,
            e.EnvelopeNumber        as envelopeNumber,
            e.StartDate             as startDate,
            e.EndDate               as endDate,
            e.Status                as status,
            Case e.Status
                When 1 Then ''Unsubmitted''
                When 2 Then ''Submitted''
                When 3 Then ''Rejected''
                When 4 Then ''Approved''
            End                     as statusLabel,
            e.Paid                  as paid,
            e.DateCreated           as dateCreated,
            e.DateSubmitted         as dateSubmitted,
            e.DateApproved          as dateApproved,
            e.ApprovalComments      as approvalComments,
            e.Comments              as comments,
            e.UserKey               as userKey,
            u.UserName              as userName,
            ISNULL((Select SUM(r.ActualCost)
                    From tExpenseReceipt r (nolock)
                    Where r.ExpenseEnvelopeKey = e.ExpenseEnvelopeKey), 0)   as totalActualCost,
            ISNULL((Select SUM(r.BillableCost)
                    From tExpenseReceipt r (nolock)
                    Where r.ExpenseEnvelopeKey = e.ExpenseEnvelopeKey), 0)   as totalBillableCost,
            ISNULL((Select COUNT(*)
                    From tExpenseReceipt r (nolock)
                    Where r.ExpenseEnvelopeKey = e.ExpenseEnvelopeKey), 0)   as receiptCount
    From    tExpenseEnvelope e (nolock)
    Inner Join vUserName u (nolock) On e.UserKey = u.UserKey
    Where   e.ExpenseEnvelopeKey = @ExpenseEnvelopeKey

    -- Result set 2: Individual expense receipts
    Select  er.ExpenseReceiptKey    as expenseReceiptKey,
            er.ExpenseDate          as expenseDate,
            et.Description          as expenseType,
            er.Description          as description,
            er.Comments             as comments,
            p.ProjectNumber         as projectNumber,
            p.ProjectName           as projectName,
            t.TaskID                as taskID,
            t.TaskName              as taskName,
            er.ActualCost           as actualCost,
            er.BillableCost         as billableCost,
            er.AmountBilled         as amountBilled,
            er.Billable             as billable,
            er.PaperReceipt         as paperReceipt,
            er.WriteOff             as writeOff
    From    tExpenseReceipt er (nolock)
    Left Join tExpenseType et (nolock) On er.ExpenseType = et.ExpenseTypeKey
    Left Join tProject p (nolock) On er.ProjectKey = p.ProjectKey
    Left Join tTask t (nolock) On er.TaskKey = t.TaskKey
    Where   er.ExpenseEnvelopeKey = @ExpenseEnvelopeKey
    Order By er.ExpenseDate, er.ExpenseReceiptKey

    Drop Table #errors

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIExpenseReceiptInsert]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseReceiptInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIExpenseReceiptInsert]
    (
        @CompanyKey             int,
        @UserKey                int,
        @ExpenseEnvelopeNumber  varchar(50)     = null,
        @ExpenseDate            smalldatetime,
        @ItemCode               nvarchar(50)    = null,
        @ProjectNumber          varchar(50)     = null,
        @TaskID                 varchar(50)     = null,
        @PaperReceipt           tinyint         = 0,
        @Taxable                tinyint         = 0,
        @Taxable2               tinyint         = 0,
        @ActualQty              decimal(24,4)   = 1,
        @ActualUnitCost         money           = null,
        @ActualCost             money,
        @Description            varchar(100)    = null,
        @Comments               nvarchar(500)   = null,
        @UnitRate               money           = null,
        @Markup                 decimal(24,4)   = 0,
        @Billable               tinyint         = 0,
        @BillableCost           money           = null,
        @SalesTaxAmount         money           = null,
        @SalesTax1Amount        money           = null,
        @SalesTax2Amount        money           = null,
        @DoProjectRollup        int             = 1,
        @PCurrencyID            varchar(10)     = null,
        @PExchangeRate          decimal(24,7)   = 1,
        @PTotalCost             money           = null,
        @GrossAmount            money           = null,
        @OfficeKey              int             = null,
        @ClassKey               int             = null
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/06/26  GRR 26.05.xx   Created
|| 05/28/26  AI  26.05.28   spCheckAccess (tExpenseEnvelope) replaces inline GL company check for other-user envelopes.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billinguseexpenses.
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @RequireItems           tinyint
    Declare @ExpenseEnvelopeKey     int
    Declare @EnvelopeUserKey        int
    Declare @EnvelopeGLCompanyKey   int
    Declare @EnvelopeStatus         smallint
    Declare @ItemKey                int
    Declare @ProjectKey             int
    Declare @TaskKey                int
    Declare @ExpenseReceiptKey      int
    Declare @NextTranNo             varchar(100)
    Declare @ReturnEnvelopeNumber   varchar(100)
    Declare @RetVal                 int

    -- ------------------------------------------------------------------
    -- Gating security: billinguseexpenses
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billinguseexpenses''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billinguseexpenses).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- Validate required parameters
    If @ExpenseDate Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''ExpenseDate is required.'', ''expenseDate'')
    End

    If @ActualCost Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''ActualCost is required.'', ''actualCost'')
    End

    -- Item code is required only when the RequireItems system preference is enabled
    Select @RequireItems = ISNULL((Select RequireItems From tPreference (nolock) Where CompanyKey = @CompanyKey), 0)

    If @RequireItems = 1 And (@ItemCode Is Null Or LTRIM(RTRIM(@ItemCode)) = '''')
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''ItemCode is required when the RequireItems system preference is enabled.'', ''itemCode'')
    End

    Declare @ErrorCount int
    Select @ErrorCount = COUNT(*) From #errors Where errorType = ''error''
    If @ErrorCount > 0
    Begin
        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -100
    End

    -- Load calling user''s security context
    Select  @SecurityGroupKey   = SecurityGroupKey,
            @IsAdministrator    = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
    And     CompanyKey  = @CompanyKey

    -- Resolve ItemCode to ItemKey (expense items have ItemType = 3)
    If @ItemCode Is Not Null And LTRIM(RTRIM(@ItemCode)) <> ''''
    Begin
        Select  @ItemKey = ItemKey
        From    tItem (nolock)
        Where   CompanyKey  = @CompanyKey
        And     (ItemID = @ItemCode OR ItemName = @ItemCode)
        And     ItemType = 3

        If @ItemKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''Expense item code not found. Verify the Item Code exists and is an expense type.'', ''itemCode'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -105
        End
    End

    -- Resolve ProjectNumber to ProjectKey
    If @ProjectNumber Is Not Null And LTRIM(RTRIM(@ProjectNumber)) <> ''''
    Begin
        Select  @ProjectKey = ProjectKey
        From    tProject (nolock)
        Where   CompanyKey      = @CompanyKey
        And     ProjectNumber   = @ProjectNumber

        If @ProjectKey Is Null
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''warning'', ''NOT_FOUND'', ''Project not found - receipt will be created without a project link.'', ''projectNumber'')
    End

    -- Resolve TaskID to TaskKey (only when project was found)
    If @TaskID Is Not Null And LTRIM(RTRIM(@TaskID)) <> '''' And @ProjectKey Is Not Null
    Begin
        Select  @TaskKey = TaskKey
        From    tTask (nolock)
        Where   ProjectKey  = @ProjectKey
        And     TaskID      = @TaskID

        If @TaskKey Is Null
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''warning'', ''NOT_FOUND'', ''Task not found - receipt will be created without a task link.'', ''taskID'')
    End

    -- Resolve envelope number to key, or create a new envelope
    If @ExpenseEnvelopeNumber Is Not Null And LTRIM(RTRIM(@ExpenseEnvelopeNumber)) <> ''''
    Begin
        Select  @ExpenseEnvelopeKey     = e.ExpenseEnvelopeKey,
                @EnvelopeUserKey        = e.UserKey,
                @EnvelopeStatus         = e.Status,
                @EnvelopeGLCompanyKey   = u.GLCompanyKey,
                @ReturnEnvelopeNumber   = e.EnvelopeNumber
        From    tExpenseEnvelope e (nolock)
        Inner Join tUser u (nolock) On e.UserKey = u.UserKey
        Where   e.CompanyKey        = @CompanyKey
        And     e.EnvelopeNumber    = @ExpenseEnvelopeNumber

        If @ExpenseEnvelopeKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''Expense envelope not found.'', ''expenseEnvelopeNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -101
        End

        -- Only Unsubmitted envelopes (Status = 1) may receive new receipts
        If @EnvelopeStatus <> 1
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''INVALID_VALUE'', ''Expense receipts can only be added to Unsubmitted expense envelopes.'', ''expenseEnvelopeNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -102
        End

        -- Security: accessing another user''s envelope requires billingviewallexpense
        If @EnvelopeUserKey <> @UserKey
        Begin
            If @IsAdministrator = 0
            Begin
                If Not Exists (
                    Select  1
                    From    tRight r (nolock)
                    Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
                    Where   ra.EntityType   = ''Security Group''
                    And     ra.EntityKey    = @SecurityGroupKey
                    And     r.RightID       = ''billingviewallexpense''
                )
                Begin
                    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                    Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to add receipts to another user''''s expense envelope.'', ''expenseEnvelopeNumber'')

                    Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                    Drop Table #errors
                    Return -103
                End

                -- Record-level access gate via spCheckAccess (tExpenseEnvelope) -
                -- replaces the inline GL company check with the per-entity rules.
                Declare @AccessOK int
                Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tExpenseEnvelope'', @ExpenseEnvelopeKey
                If @AccessOK <> 1
                Begin
                    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                    Values (''error'', ''ACCESS_DENIED'', ''You do not have access to this expense envelope.'', ''expenseEnvelopeNumber'')

                    Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                    Drop Table #errors
                    Return -103
                End
            End
        End
    End
    Else
    Begin
        -- No envelope number supplied: reuse the calling user''s oldest Unsubmitted envelope if one exists
        Select  @ExpenseEnvelopeKey     = ExpenseEnvelopeKey,
                @ReturnEnvelopeNumber   = EnvelopeNumber
        From    tExpenseEnvelope (nolock)
        Where   CompanyKey          = @CompanyKey
        And     UserKey             = @UserKey
        And     Status              = 1
        And     ExpenseEnvelopeKey  = (
                    Select MIN(ExpenseEnvelopeKey)
                    From   tExpenseEnvelope (nolock)
                    Where  CompanyKey   = @CompanyKey
                    And    UserKey      = @UserKey
                    And    Status       = 1
                )

        If @ExpenseEnvelopeKey Is Null
        Begin
            -- No reusable envelope - create a new Unsubmitted one for the calling user
            Exec spGetNextTranNo
                @CompanyKey,
                ''Expense'',
                @RetVal         Output,
                @NextTranNo     Output

            If @RetVal <> 1
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''INTERNAL_ERROR'', ''Could not generate a new expense envelope number.'', ''general'')

                Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                Drop Table #errors
                Return -104
            End

            Insert Into tExpenseEnvelope
                (UserKey, CompanyKey, EnvelopeNumber, StartDate, EndDate, Status, DateCreated)
            Values
                (@UserKey, @CompanyKey, RTRIM(@NextTranNo), @ExpenseDate, @ExpenseDate, 1, GETDATE())

            Select  @ExpenseEnvelopeKey     = @@IDENTITY,
                    @ReturnEnvelopeNumber   = RTRIM(@NextTranNo)
        End
    End

    -- Normalize cost fields
    If @ActualQty Is Null Or @ActualQty <= 0
        Select @ActualQty = 1
    If @ActualUnitCost Is Null And @ActualCost Is Not Null
        Select @ActualUnitCost = @ActualCost / @ActualQty

    -- Force billable when the receipt is linked to a project
    If @ProjectKey Is Not Null
        Select @Billable = 1

    -- Resolve markup / billable cost. Markup is stored as a percent (e.g. 25 = 25%).
    -- Step 1: determine @Markup. If neither markup nor billable cost was supplied,
    --         defer to spMarkupGet. If only billable cost was supplied, derive markup
    --         from it. Otherwise the caller-supplied markup is kept as-is.
    -- Step 2: derive @BillableCost from @Markup when it wasn''t supplied.
    If @Billable = 1 And ISNULL(@ActualCost, 0) > 0
    Begin
        If ISNULL(@Markup, 0) = 0
        Begin
            If ISNULL(@BillableCost, 0) = 0
            Begin
                -- Neither supplied: look up markup via spMarkupGet
                Declare @MarkupResult table (Markup decimal(24,4))

                Insert Into @MarkupResult (Markup)
                Exec spMarkupGet
                    @CompanyKey  = @CompanyKey,
                    @ProjectKey  = @ProjectKey,
                    @ItemKey     = @ItemKey,
                    @TaskKey     = @TaskKey,
                    @CCEntryKey  = 0

                Select @Markup = ISNULL(Markup, 0) From @MarkupResult
                Select @Markup = ISNULL(@Markup, 0)
            End
            Else
            Begin
                -- BillableCost supplied without markup: derive markup
                Select @Markup = (@BillableCost / @ActualCost - 1) * 100.0
            End
        End

        -- Step 2: compute BillableCost from the resolved markup if it wasn''t supplied
        If ISNULL(@BillableCost, 0) = 0
            Select @BillableCost = ROUND(@ActualCost * (1 + @Markup / 100.0), 2)
    End

    If @PTotalCost Is Null And @ActualCost Is Not Null
        Select @PTotalCost = @ActualCost
    If @GrossAmount Is Null And @BillableCost Is Not Null
        Select @GrossAmount = @BillableCost
    If ISNULL(@PExchangeRate, 0) <= 0
        Select @PExchangeRate = 1

    -- Insert the expense receipt
    Insert Into tExpenseReceipt
        (
        ExpenseEnvelopeKey, UserKey,        ExpenseDate,    ItemKey,
        ProjectKey,         TaskKey,        PaperReceipt,   Taxable,
        Taxable2,           ActualQty,      ActualUnitCost, ActualCost,
        Description,        Comments,       UnitRate,       Markup,
        Billable,           BillableCost,   SalesTaxAmount, SalesTax1Amount,
        SalesTax2Amount,    PCurrencyID,    PExchangeRate,  PTotalCost,
        GrossAmount,        OfficeKey,      ClassKey
        )
    Values
        (
        @ExpenseEnvelopeKey, @UserKey,      @ExpenseDate,   @ItemKey,
        @ProjectKey,        @TaskKey,        @PaperReceipt,  @Taxable,
        @Taxable2,          @ActualQty,      @ActualUnitCost, @ActualCost,
        @Description,       @Comments,       @UnitRate,      @Markup,
        @Billable,          @BillableCost,   @SalesTaxAmount, @SalesTax1Amount,
        @SalesTax2Amount,   @PCurrencyID,    @PExchangeRate, @PTotalCost,
        @GrossAmount,       @OfficeKey,      @ClassKey
        )

    Select @ExpenseReceiptKey = @@IDENTITY

    -- Result set 1: success row
    Select  @ExpenseReceiptKey      as expenseReceiptKey,
            @ExpenseEnvelopeKey     as expenseEnvelopeKey,
            @ReturnEnvelopeNumber   as envelopeNumber

    -- Result set 2: warnings (only if any exist)
    If Exists (Select 1 From #errors Where errorType = ''warning'')
        Select errorType, errorCode, errorMessage, fieldName
        From   #errors
        Where  errorType = ''warning''

    Drop Table #errors

    -- Project rollup
    If @DoProjectRollup = 1 And @ProjectKey Is Not Null
    Begin
        Declare @TranType   int
        Declare @BaseRollup int
        Declare @Approved   int
        Declare @Unbilled   int
        Declare @WriteOff   int

        Select  @TranType   = 3,
                @BaseRollup = 1,
                @Approved   = 1,
                @Unbilled   = 1,
                @WriteOff   = 0

        Exec sptProjectRollupUpdate @ProjectKey, @TranType, @BaseRollup, @Approved, @Unbilled, @WriteOff
    End

    Return 1


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptCompanyMerge]'
GO
IF OBJECT_ID(N'[dbo].[sptCompanyMerge]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptCompanyMerge]
	(
	@OldCompanyKey int,
	@NewCompanyKey int,
	@MergedBy int
	)
AS --Encrypt

	SET NOCOUNT ON
	
/*
|| When     Who Rel     What
|| 05/19/09 GHL 10.5  Creation. 
||                    User CompanyKey index when possible
||                    Look for ClientKey, ContactCompanyKey, VendorKey, CompanyKey 
||                    For large tables, perform lookup
|| 07/31/09 RLB 10.506 (58715) fixed CalendarLink insert to CalendarKey from ActivityKey
|| 2/28/10  GWG 10.519 Fixed the updating of company keys in tTran and tCashTran
|| 12/22/10 GHL 10.539 (97815) Added updating of client key in retainers
|| 5/27/11  RLB 10.544 (304675) Added a check for Clients that are on same GL Accounts on a GL Budget
|| 03/25/15 WDF 10.590 (250961) Added UpdatedByKey and DateUpdated to tRequest
|| 04/30/15 GHL 10.591 (254920) Added update of tGLAccount.VendorKey
|| 07/30/25 AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time

*/	

	declare @CompanyKey int
	declare	@OldDefaultAddressKey int
	declare	@OldBillingAddressKey int
	declare	@OldPaymentAddressKey int
	declare @OldCustomFieldKey int
	declare @CompanyKey2 int
	declare	@NewDefaultAddressKey int
	declare	@NewBillingAddressKey int
	declare	@NewPaymentAddressKey int
	declare @NewCustomFieldKey int
	
	
	select @CompanyKey = OwnerCompanyKey
	      ,@OldCustomFieldKey = CustomFieldKey
		  ,@OldDefaultAddressKey = DefaultAddressKey
		  ,@OldBillingAddressKey = BillingAddressKey
		  ,@OldPaymentAddressKey = PaymentAddressKey
	from   tCompany (nolock)
	where  CompanyKey = @OldCompanyKey
	
	if @@ROWCOUNT = 0
		return -100
		
	select @CompanyKey2 = OwnerCompanyKey
	      ,@NewCustomFieldKey = CustomFieldKey
		  ,@NewDefaultAddressKey = DefaultAddressKey
		  ,@NewBillingAddressKey = BillingAddressKey
		  ,@NewPaymentAddressKey = PaymentAddressKey
	from   tCompany (nolock)
	where  CompanyKey = @NewCompanyKey
		
	if @@ROWCOUNT = 0
		return -101
	
	if @CompanyKey <> @CompanyKey2
		return -104

	-- this is for the links with projects, estimates, etc...use GP General Purpose stuff 
	CREATE TABLE #link (LinkKey int null, GPKey int null, GPFlag int null, GPDec Decimal(24,4) null, GPMoney money null, GPMoney2 money null)

	if exists(Select 1 from tGLBudgetDetail (nolock) where ClientKey = @OldCompanyKey and GLAccountKey in (Select GLAccountKey from tGLBudgetDetail (nolock) where ClientKey = @NewCompanyKey))
				return -110
		

		 
		
	/*
	|| ClientKey
	*/
	
	if exists (select 1 from tBilling (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
		update tBilling set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
			
	if exists (select 1 from tCampaign (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
		update tCampaign set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
			
	if exists (select 1 from tCashTransaction (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
		update tCashTransaction set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
			
	if exists (select 1 from tCashTransactionLine (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
		update tCashTransactionLine set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
			
	if exists (select 1 from tCheck (nolock) where ClientKey = @OldCompanyKey)
		update tCheck set ClientKey = @NewCompanyKey where ClientKey = @OldCompanyKey
			
	-- small tables, no lookup		
	update tClientDivision set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
	update tClientProduct set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
	update tRetainer set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey	
			
	if exists (select 1 from tGLBudgetDetail (nolock) where ClientKey = @OldCompanyKey)
		update tGLBudgetDetail set ClientKey = @NewCompanyKey where ClientKey = @OldCompanyKey
			
	if exists (select 1 from tInvoice (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
		update tInvoice set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey

	if exists (select 1 from tJournalEntryDetail (nolock) where ClientKey = @OldCompanyKey)
		update tJournalEntryDetail set ClientKey = @NewCompanyKey where ClientKey = @OldCompanyKey

	-- small tables, no lookup		
	update tMediaEstimate set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey

	if exists (select 1 from tProject (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
		update tProject set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
		
		
	-- small tables, no lookup		
	update tProjectSplitBilling set ClientKey = @NewCompanyKey where ClientKey = @OldCompanyKey
			
	update tRequest set ClientKey = @NewCompanyKey, UpdatedByKey = @MergedBy, DateUpdated = GETUTCDATE() 
	 where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
			
	if exists (select 1 from tTransaction (nolock) where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey)
	BEGIN
		update tTransaction set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
		update tCashTransaction set ClientKey = @NewCompanyKey where CompanyKey = @CompanyKey and ClientKey = @OldCompanyKey
	END
	if exists (select 1 from tTransaction (nolock) where CompanyKey = @CompanyKey and SourceCompanyKey = @OldCompanyKey)
	BEGIN
		update tTransaction set SourceCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and SourceCompanyKey = @OldCompanyKey
		update tCashTransaction set SourceCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and SourceCompanyKey = @OldCompanyKey
	END	
	if exists (select 1 from tVoucher v (nolock)
				inner join tVoucherDetail vd (nolock) on v.VoucherKey = vd.VoucherKey
				where v.CompanyKey = @CompanyKey and vd.ClientKey = @OldCompanyKey)
		update tVoucherDetail
		set    tVoucherDetail.ClientKey = @NewCompanyKey
		from   tVoucher v (nolock)
		where  tVoucherDetail.VoucherKey = v.VoucherKey
	    and    v.CompanyKey = @CompanyKey 
	    and    tVoucherDetail.ClientKey = @OldCompanyKey				
				
	/*
	|| ContactCompanyKey
	*/
	
	if exists (select 1 from tCalendar (nolock) where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey)
		update tCalendar set ContactCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey

	--tCalendarLink
	truncate table #link
	
	-- place old records first
	insert #link (LinkKey,GPFlag)
	select CalendarKey, 0
	from   tCalendarLink (NOLOCK)
	where  EntityKey = @OldCompanyKey
	and    Entity = ''tCompany''
	
	if (select count(*) from #link) > 0
	begin
		-- update where match with new user
		update #link
		set    #link.GPFlag = 1
		from   tCalendarLink cl (NOLOCK)
		where  cl.EntityKey = @NewCompanyKey
		and    cl.CalendarKey = #link.LinkKey
		and    cl.Entity = ''tCompany''
		
		delete #link where GPFlag = 1
		
		insert tCalendarLink (CalendarKey, Entity, EntityKey)
		select LinkKey, ''tCompany'', @NewCompanyKey
		from   #link
			
		delete tCalendarLink where Entity=''tCompany'' and EntityKey = @OldCompanyKey
	end
		
	-- small table, no lookup				
	update tForm set ContactCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey
	
	if exists (select 1 from tLead (nolock) where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey)
		update tLead set ContactCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey
							
	if exists (select 1 from tActivity (nolock) where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey)
		update tActivity set ContactCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey

	if exists (select 1 from tContactActivity (nolock) where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey)
		update tContactActivity set ContactCompanyKey = @NewCompanyKey where CompanyKey = @CompanyKey and ContactCompanyKey = @OldCompanyKey


	--tActivityLink
	truncate table #link
	
	-- place old records first
	insert #link (LinkKey,GPFlag)
	select ActivityKey, 0
	from   tActivityLink (NOLOCK)
	where  EntityKey = @OldCompanyKey
	and    Entity = ''tCompany''
	
	if (select count(*) from #link) > 0
	begin
		-- update where match with new user
		update #link
		set    #link.GPFlag = 1
		from   tActivityLink al (NOLOCK)
		where  al.EntityKey = @NewCompanyKey
		and    al.ActivityKey = #link.LinkKey
		and    al.Entity = ''tCompany''
		
		delete #link where GPFlag = 1
		
		insert tActivityLink (ActivityKey, Entity, EntityKey)
		select LinkKey, ''tCompany'', @NewCompanyKey
		from   #link
			
		delete tActivityLink where Entity=''tCompany'' and EntityKey = @OldCompanyKey
	end
	
	DELETE tLevelHistory WHERE Entity = ''tCompany'' AND EntityKey = @OldCompanyKey

	
	/*
	|| VendorKey
	*/
	-- small table, no lookup				
	update tCompanyMedia set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey
	
	if exists (select 1 from tProject p (nolock)
	            inner join tEstimate e (nolock) on p.ProjectKey = e.ProjectKey
				inner join tEstimateTaskExpense ete (nolock) on ete.EstimateKey = e.EstimateKey
				where p.CompanyKey = @CompanyKey and ete.VendorKey = @OldCompanyKey)
		update tEstimateTaskExpense
		set    tEstimateTaskExpense.VendorKey = @NewCompanyKey
		from   tEstimate e (nolock)
		       ,tProject p (nolock)
		where  tEstimateTaskExpense.EstimateKey = e.EstimateKey
	    and    e.ProjectKey = p.ProjectKey 
	    and    p.CompanyKey = @CompanyKey 
	    and    tEstimateTaskExpense.VendorKey = @OldCompanyKey				
	
	if exists (select 1 from tExpenseEnvelope (nolock) where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey)
		update tExpenseEnvelope set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey
	
	if exists (select 1 from tPayment (nolock) where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey)
		update tPayment set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey

	if exists (select 1 from tPurchaseOrder (nolock) where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey)
		update tPurchaseOrder set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey
	
	-- small table, no lookup				
	update tQuoteReply set VendorKey = @NewCompanyKey where VendorKey = @OldCompanyKey
	
	if exists (select 1 from tVoucher (nolock) where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey)
		update tVoucher set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey

	if exists (select 1 from tUser (nolock) where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey)
		update tUser set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey

	-- small table, no lookup				
	update tGLAccount set VendorKey = @NewCompanyKey where CompanyKey = @CompanyKey and VendorKey = @OldCompanyKey and AccountType = 23 -- Credit cards account type
							
	/*
	|| Final cleanup
	*/
	
	if exists (select 1 from tUser (nolock) where OwnerCompanyKey = @CompanyKey and CompanyKey = @OldCompanyKey)
		update tUser set CompanyKey = @NewCompanyKey where OwnerCompanyKey = @CompanyKey and CompanyKey = @OldCompanyKey
		
	if exists (select 1 from tCompany (nolock) where OwnerCompanyKey = @CompanyKey and ParentCompanyKey = @OldCompanyKey)
		update tCompany set ParentCompanyKey = @NewCompanyKey where OwnerCompanyKey = @CompanyKey and ParentCompanyKey = @OldCompanyKey
		
	update tAddress 
	set    CompanyKey = @NewCompanyKey  
	      ,EntityKey =
	      case when Entity is null then @NewCompanyKey -- 10.5 updates this field also
	      else EntityKey end  
	where  OwnerCompanyKey = @CompanyKey
	and    Entity is null
	and    CompanyKey = @OldCompanyKey
		
		
	if isnull(@OldCustomFieldKey, 0) > 0 and isnull(@NewCustomFieldKey, 0) = 0
	begin
		select @NewCustomFieldKey = @OldCustomFieldKey
	    select @OldCustomFieldKey = null
	end
	
	if isnull(@OldDefaultAddressKey, 0) > 0 and isnull(@NewDefaultAddressKey, 0) = 0
		select @NewDefaultAddressKey = @OldDefaultAddressKey
	if isnull(@OldBillingAddressKey, 0) > 0 and isnull(@NewBillingAddressKey, 0) = 0
		select @NewBillingAddressKey = @OldBillingAddressKey
	if isnull(@OldPaymentAddressKey, 0) > 0 and isnull(@NewPaymentAddressKey, 0) = 0
		select @NewPaymentAddressKey = @OldPaymentAddressKey
	
	IF ISNULL(@OldCustomFieldKey, 0) > 0
		exec spCF_tObjectFieldSetDelete @OldCustomFieldKey
	
	update tCompany 
	set    CustomFieldKey = @NewCustomFieldKey
	      ,DefaultAddressKey = @NewDefaultAddressKey
	      ,BillingAddressKey = @NewBillingAddressKey
	      ,PaymentAddressKey = @NewPaymentAddressKey	        
	where  CompanyKey = @NewCompanyKey
	
	begin tran
	
	delete tCompany where CompanyKey = @OldCompanyKey
	
	if @@error <> 0
	begin
		rollback tran
		return -102	
	end
	
	insert tMergeContactLog (OwnerCompanyKey, OldUserKey, OldCompanyKey, NewUserKey, NewCompanyKey, MergedBy)  
	values (isnull(@CompanyKey, 0), null, isnull(@OldCompanyKey, 0), null, isnull(@NewCompanyKey, 0), isnull(@MergedBy, 0))

	if @@error <> 0
	begin
		rollback tran
		return -103
	end
		
	commit tran
		
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIExpenseEnvelopeSubmit]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseEnvelopeSubmit]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIExpenseEnvelopeSubmit]
    (
        @CompanyKey             int,
        @UserKey                int,
        @ExpenseEnvelopeNumber  varchar(100),
        @ApprovalComments       nvarchar(300)   = null,
        @SubmittedByUserName    nvarchar(200)   = null
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/06/26  GRR 26.05.xx   Created
|| 05/28/26  AI  26.05.28   spCheckAccess (tExpenseEnvelope) replaces inline GL company check.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billinguseexpenses.
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @ExpenseEnvelopeKey     int
    Declare @EnvelopeUserKey        int
    Declare @EnvelopeGLCompanyKey   int
    Declare @EnvelopeStatus         smallint
    Declare @SubmittedByUserKey     int
    Declare @EnvelopeOwnerApprover  int
    Declare @StartDate              smalldatetime
    Declare @EndDate                smalldatetime
    Declare @FinalStatus            tinyint
    Declare @DateApproved           smalldatetime

    -- ------------------------------------------------------------------
    -- Gating security: billinguseexpenses
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billinguseexpenses''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billinguseexpenses).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- Validate required parameter
    If @ExpenseEnvelopeNumber Is Null Or LTRIM(RTRIM(@ExpenseEnvelopeNumber)) = ''''
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''REQUIRED_FIELD'', ''ExpenseEnvelopeNumber is required.'', ''expenseEnvelopeNumber'')

        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -100
    End

    -- Resolve envelope number to key; capture the owner and GL company for security checks
    Select  @ExpenseEnvelopeKey   = e.ExpenseEnvelopeKey,
            @EnvelopeUserKey      = e.UserKey,
            @EnvelopeStatus       = e.Status,
            @EnvelopeGLCompanyKey = u.GLCompanyKey
    From    tExpenseEnvelope e (nolock)
    Inner Join tUser u (nolock) On e.UserKey = u.UserKey
    Where   e.CompanyKey      = @CompanyKey
    And     e.EnvelopeNumber  = @ExpenseEnvelopeNumber

    If @ExpenseEnvelopeKey Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Expense envelope not found.'', ''expenseEnvelopeNumber'')

        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -101
    End

    -- Envelope must be Unsubmitted (1) or Rejected (3) to allow submission
    If @EnvelopeStatus Not In (1, 3)
    Begin
        Declare @StatusLabel varchar(20)
        Select @StatusLabel = Case @EnvelopeStatus
            When 2 Then ''Submitted''
            When 4 Then ''Approved''
            Else ''unknown''
        End

        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
            ''Only Unsubmitted or Rejected expense envelopes can be submitted. This envelope is currently '' + @StatusLabel + ''.'',
            ''expenseEnvelopeNumber'')

        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -102
    End

    -- Envelope must contain at least one receipt
    If Not Exists (
        Select  1
        From    tExpenseReceipt (nolock)
        Where   ExpenseEnvelopeKey = @ExpenseEnvelopeKey
    )
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Cannot submit an expense envelope with no receipts.'', ''expenseEnvelopeNumber'')

        Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
        Drop Table #errors
        Return -102
    End

    -- Load calling user''s security context
    Select  @SecurityGroupKey = SecurityGroupKey,
            @IsAdministrator  = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
    And     CompanyKey  = @CompanyKey

    -- Users may always submit their own envelopes; submitting another user''s requires billingviewallexpense
    If @EnvelopeUserKey <> @UserKey
    Begin
        If @IsAdministrator = 0
        Begin
            If Not Exists (
                Select  1
                From    tRight r (nolock)
                Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
                Where   ra.EntityType   = ''Security Group''
                And     ra.EntityKey    = @SecurityGroupKey
                And     r.RightID       = ''billingviewallexpense''
            )
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to submit another user''''s expense envelope.'', ''expenseEnvelopeNumber'')

                Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                Drop Table #errors
                Return -103
            End

            -- Record-level access gate via spCheckAccess (tExpenseEnvelope) -
            -- replaces the inline GL company check with the per-entity rules.
            Declare @AccessOK int
            Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tExpenseEnvelope'', @ExpenseEnvelopeKey
            If @AccessOK <> 1
            Begin
                Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                Values (''error'', ''ACCESS_DENIED'', ''You do not have access to this expense envelope.'', ''expenseEnvelopeNumber'')

                Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                Drop Table #errors
                Return -103
            End
        End
    End

    -- Resolve SubmittedByUserName to a UserKey if provided.
    -- Match against UserID, Email, or FirstName + LastName (case-insensitive).
    If @SubmittedByUserName Is Not Null And LTRIM(RTRIM(@SubmittedByUserName)) <> ''''
    Begin
        Select Top 1
                @SubmittedByUserKey = UserKey
        From    tUser (nolock)
        Where   CompanyKey  = @CompanyKey
        And     Active      = 1
        And     (
                    UserID                              = @SubmittedByUserName
                Or  Email                               = @SubmittedByUserName
                Or  LTRIM(RTRIM(FirstName + '' '' + LastName)) = LTRIM(RTRIM(@SubmittedByUserName))
                )

        If @SubmittedByUserKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''warning'', ''NOT_FOUND'', ''SubmittedByUserName not found - envelope will be submitted without a SubmittedBy user.'', ''submittedByUserName'')
        End
    End

    -- Determine date range from receipts
    Select  @StartDate = Min(ExpenseDate),
            @EndDate   = Max(ExpenseDate)
    From    tExpenseReceipt (nolock)
    Where   ExpenseEnvelopeKey = @ExpenseEnvelopeKey

    -- Submit the envelope (Status = 2)
    Set @FinalStatus = 2

    Update  tExpenseEnvelope
    Set     Status          = 2,
            StartDate       = @StartDate,
            EndDate         = @EndDate,
            ApprovalComments = @ApprovalComments,
            SubmittedByKey  = @SubmittedByUserKey,
            DateSubmitted   = GETDATE()
    Where   ExpenseEnvelopeKey = @ExpenseEnvelopeKey

    -- Auto-approve if the SubmittedBy user is the expense approver for the envelope owner,
    -- or if the envelope owner''s approver is themselves (same as core submit behavior).
    Select  @EnvelopeOwnerApprover = ExpenseApprover
    From    tUser (nolock)
    Where   UserKey = @EnvelopeUserKey

    If (@EnvelopeOwnerApprover Is Not Null And @EnvelopeOwnerApprover = @EnvelopeUserKey)
    Or (@SubmittedByUserKey Is Not Null And @EnvelopeOwnerApprover = @SubmittedByUserKey)
    Begin
        Set @FinalStatus  = 4
        Set @DateApproved = CAST(
            CAST(MONTH(GETDATE()) as varchar) + ''/'' +
            CAST(DAY(GETDATE())   as varchar) + ''/'' +
            CAST(YEAR(GETDATE())  as varchar) as smalldatetime)

        Update  tExpenseEnvelope
        Set     Status       = 4,
                DateApproved = @DateApproved
        Where   ExpenseEnvelopeKey = @ExpenseEnvelopeKey
    End

    -- Project rollup for all linked projects
    Declare @ProjectKey int
    Select  @ProjectKey = -1

    While (1 = 1)
    Begin
        Select  @ProjectKey = MIN(ProjectKey)
        From    tExpenseReceipt (nolock)
        Where   ExpenseEnvelopeKey = @ExpenseEnvelopeKey
        And     ProjectKey > @ProjectKey

        If @ProjectKey Is Null
            Break

        -- TranType = 3 (ExpenseReceipt), approved rollup
        Exec sptProjectRollupUpdate @ProjectKey, 3, 0, 1, 0, 0
    End

    -- Result set 1: warnings (may be empty)
    Select  errorType, errorCode, errorMessage, fieldName
    From    #errors
    Where   errorType = ''warning''

    -- Result set 2: success row
    Select  @ExpenseEnvelopeKey     as expenseEnvelopeKey,
            @ExpenseEnvelopeNumber  as envelopeNumber,
            @FinalStatus            as status,
            Case @FinalStatus
                When 2 Then ''Submitted''
                When 4 Then ''Approved''
            End                     as statusLabel,
            @SubmittedByUserKey     as submittedByUserKey

    Drop Table #errors

    Return @FinalStatus

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesCampaignUpdateBillingSchedule]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCampaignUpdateBillingSchedule]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER procedure [dbo].[spFixedFeesCampaignUpdateBillingSchedule]
	(
	@InvoiceKey int
	,@CampaignKey int
	,@BillingScheduleKey int = null
	)

	as --encrypt
begin

SET NOCOUNT ON

	/*
    || When     Who Rel     What
	|| 10/20/20 GHL 20.110 (533381) Creation for FF Campaign single mode
	|| 05/03/22 GHL 22.050 (597757) Made change to get the @NextBillDate with min instead of max
	|| 07/14/26 AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
	*/

	if @BillingScheduleKey > 0
	begin
		if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @InvoiceKey and CampaignKey = @CampaignKey)
		update tBillingSchedule
		set   InvoiceKey = @InvoiceKey
		     ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
		                                   then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
		                                            case when isnull(c.ExpensesNotIncluded, 0) = 0
		                                                 then isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0) + isnull(c.EstExpenses, 0) + isnull(c.ApprovedCOExpense, 0)
		                                                 else isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0)
		                                            end) / 100.00, 2), ''N2'')
		                                   else null end
		                        from  tBillingSchedule bs (nolock)
		                        join  tCampaign c (nolock) on c.CampaignKey = bs.CampaignKey
		                        where bs.BillingScheduleKey = @BillingScheduleKey)
		where BillingScheduleKey = @BillingScheduleKey
		and   CampaignKey = @CampaignKey
		and    BillingKey is null
		and    InvoiceKey is null

		return 1
	end

declare @AdvanceBill int
declare @InvoiceDate smalldatetime
declare @NextBillDate smalldatetime

	if exists (select 1 from tBillingSchedule (nolock) where CampaignKey = @CampaignKey) 
	begin
		select @InvoiceDate = InvoiceDate
		      ,@AdvanceBill = AdvanceBill
		from tInvoice (nolock)
		where InvoiceKey = @InvoiceKey 

		--if @AdvanceBill = 1
		--	return 1

		select @NextBillDate = min(NextBillDate) -- changed from max to min for 597757
		from   tBillingSchedule (nolock) 
		where  CampaignKey = @CampaignKey
		and    NextBillDate <= @InvoiceDate
		and    BillingKey is null
		and    InvoiceKey is null
		and    isnull(AdvanceBill, 0) = @AdvanceBill

		if @@rowcount = 0
			return 1

		if @NextBillDate is null
			return 1

		-- there are some users or testers using the same NextBillDate
		-- so pickup just one tBillingSchedule record
		select @BillingScheduleKey = min(BillingScheduleKey)
		from  tBillingSchedule (nolock)
		where  CampaignKey = @CampaignKey
		and    NextBillDate = @NextBillDate
		and    BillingKey is null
		and    InvoiceKey is null
		and    isnull(AdvanceBill, 0) = @AdvanceBill

		if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @InvoiceKey and CampaignKey = @CampaignKey)
		update tBillingSchedule
		set    InvoiceKey = @InvoiceKey
		      ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
		                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
		                                             case when isnull(c.ExpensesNotIncluded, 0) = 0
		                                                  then isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0) + isnull(c.EstExpenses, 0) + isnull(c.ApprovedCOExpense, 0)
		                                                  else isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0)
		                                             end) / 100.00, 2), ''N2'')
		                                    else null end
		                         from  tBillingSchedule bs (nolock)
		                         join  tCampaign c (nolock) on c.CampaignKey = bs.CampaignKey
		                         where bs.BillingScheduleKey = @BillingScheduleKey)
		where  BillingScheduleKey = @BillingScheduleKey
	

	end

end


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spConvertDashSeed]'
GO
IF OBJECT_ID(N'[dbo].[spConvertDashSeed]', 'P') IS NULL
EXEC sp_executesql N'
CREATE Procedure [dbo].[spConvertDashSeed] 
(
	@CompanyKey int,
	@UserKey int,
	@DashID varchar(100)
)

As 

Declare @NewDashKey int, @NewTabKey int

if exists(Select 1 from tWidgetDash Where CompanyKey = @CompanyKey and DashID = @DashID)
	return 1

IF @DashID = ''Today''
BEGIN
	INSERT INTO [tWidgetDash] ([CompanyKey],[DashID] ,[UserKey] ,[Label])
	VALUES ( @CompanyKey, ''Today'', 0, ''Home'' )

	Select @NewDashKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, Entity, EntityKey, SecurityGroupKey, UserKey)
		Select @CompanyKey, ''tWidgetDash'', @NewDashKey, SecurityGroupKey, 0 from tSecurityGroup (nolock) Where CompanyKey = @CompanyKey


	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Creative'', 1)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 100 and sg.CompanyKey = @CompanyKey

	--select [Name], ReportType, XPos, YPos, Width, Height, DisplayType from tReport Where WidgetTabKey = 44
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 0, 0, 7, 8, ''Conversations'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Daily Feed'' ,4, @CompanyKey, @UserKey, 7, 4, 2, 4, ''DailyFeed'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 7, 0, 2, 4, ''Schedule'', @NewTabKey)

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Project Management'', 2)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 103 and sg.CompanyKey = @CompanyKey

	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Daily Feed'' ,4, @CompanyKey, @UserKey, 9, 3, 2, 3, ''DailyFeed'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 9, 0, 2, 3, ''Schedule'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Project Open Items'' ,4, @CompanyKey, @UserKey, 0, 0, 2, 3, ''ProjectOpenItems'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Project Items Needing Attention'' ,4, @CompanyKey, @UserKey, 0, 3, 2, 3, ''ProjectItemsNeedingAttention'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 2, 0, 7, 6, ''Conversations'', @NewTabKey)

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Sales'', 3)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 102 and sg.CompanyKey = @CompanyKey

	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Twitter Feeds'' ,4, @CompanyKey, @UserKey, 0, 0, 3, 2, ''TwitterFeeds'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Favorite Opportunities'' ,4, @CompanyKey, @UserKey, 0, 2, 3, 3, ''FavoriteOpportunities'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Favorite Reports'' ,4, @CompanyKey, @UserKey, 0, 5, 3, 3, ''ReportingFavorites'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 3, 0, 5, 8, ''Conversations'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 8, 0, 3, 8, ''Schedule'', @NewTabKey)

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Purchasing'', 4)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 109 and sg.CompanyKey = @CompanyKey

	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Open Items'' ,4, @CompanyKey, @UserKey, 0, 0, 2, 2, ''PurchasingOpenItems'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Incoming Charges'' ,4, @CompanyKey, @UserKey, 2, 0, 2, 2, ''PurchasingIncomingCharges'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Invoices'' ,4, @CompanyKey, @UserKey, 4, 0, 2, 2, ''PurchasingInvoices'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Payments'' ,4, @CompanyKey, @UserKey, 8, 0, 2, 2, ''PurchasingPayments'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''To Pay As Of'' ,4, @CompanyKey, @UserKey, 6, 0, 2, 2, ''PurchasingToPayAsOf'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 0, 2, 8, 4, ''Conversations'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 8, 2, 2, 4, ''Schedule'', @NewTabKey)

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Billing'', 5)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 114 and sg.CompanyKey = @CompanyKey

	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Billing Worksheets'' ,4, @CompanyKey, @UserKey, 0, 0, 2, 2, ''BillingWorksheets'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''To Bill As Of'' ,4, @CompanyKey, @UserKey, 0, 2, 2, 3, ''BillingToBillAsOf'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Client Invoices'' ,4, @CompanyKey, @UserKey, 0, 5, 2, 2, ''BillingInvoices'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 2, 0, 6, 7, ''Conversations'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 8, 0, 2, 7, ''Schedule'', @NewTabKey)

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Media'', 6)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 119 and sg.CompanyKey = @CompanyKey

	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Media Open Items'' ,4, @CompanyKey, @UserKey, 0, 0, 2, 3, ''MediaOpenItems'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Media Orders Needing Attention'' ,4, @CompanyKey, @UserKey, 0, 3, 2, 3, ''MediaOrdersNeedingAttention'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Favorite Reports'' ,4, @CompanyKey, @UserKey, 0, 6, 2, 3, ''ReportingFavorites'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 2, 0, 7, 9, ''Conversations'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 9, 0, 2, 9, ''Schedule'', @NewTabKey)

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Accounting'', 7)
	Select @NewTabKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, EntityKey, Entity, SecurityGroupKey)
	Select @CompanyKey, @NewTabKey, ''tWidgetTab'', SecurityGroupKey 
	from tRightAssigned ra (nolock) inner join tSecurityGroup sg (nolock) on ra.EntityKey = sg.SecurityGroupKey
	Where ra.RightKey = 110 and sg.CompanyKey = @CompanyKey

	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Accounting Items Needing Attention'' ,4, @CompanyKey, @UserKey, 0, 0, 3, 3, ''AccountingItemsNeedingAttention'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Account Balances'' ,4, @CompanyKey, @UserKey, 0, 3, 3, 3, ''AccountingAccountBalances'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Favorite Reports'' ,4, @CompanyKey, @UserKey, 0, 6, 3, 3, ''ReportingFavorites'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Conversations'' ,4, @CompanyKey, @UserKey, 3, 0, 6, 9, ''Conversations'', @NewTabKey)
	INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Schedule'' ,4, @CompanyKey, @UserKey, 9, 0, 2, 9, ''Schedule'', @NewTabKey)

END

IF @DashID = ''Project''
BEGIN

	INSERT INTO [tWidgetDash] ([CompanyKey],[DashID] ,[UserKey] ,[Label])
	VALUES ( @CompanyKey, ''Project'', 0, ''Dashboard'' )
	Select @NewDashKey = @@IDENTITY

	Insert Into tSecurityAccess (CompanyKey, Entity, EntityKey, SecurityGroupKey, UserKey)
		Select @CompanyKey, ''tWidgetDash'', @NewDashKey, SecurityGroupKey, 0 from tSecurityGroup (nolock) Where CompanyKey = @CompanyKey

	INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Home'', 1)
	Select @NewTabKey = @@IDENTITY

	if exists(Select * from tReport (nolock) Where CompanyKey = @CompanyKey AND ReportType = 4 AND ReportID = ''ProjectDashboard'')
	BEGIN
	--We need to convert the existing dashboard.
		Update tReport Set WidgetTabKey = @NewTabKey Where CompanyKey = @CompanyKey AND ReportType = 4 AND ReportID = ''ProjectDashboard''

	END
	ELSE
	BEGIN

		INSERT INTO [tWidgetDash] ([CompanyKey],[DashID] ,[UserKey] ,[Label])
		VALUES ( @CompanyKey, ''Project'', 0, ''Dashboard'' )
		Select @NewDashKey = @@IDENTITY

		Insert Into tSecurityAccess (CompanyKey, Entity, EntityKey, SecurityGroupKey, UserKey)
			Select @CompanyKey, ''tWidgetDash'', @NewDashKey, SecurityGroupKey, 0 from tSecurityGroup (nolock) Where CompanyKey = @CompanyKey

		INSERT INTO [tWidgetTab] ([WidgetDashKey] ,[Label] ,[DisplayOrder])  VALUES (@NewDashKey, ''Home'', 1)
		Select @NewTabKey = @@IDENTITY

		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Menu'' ,4, @CompanyKey, @UserKey, 0, 5, 2, 5, ''ProjectMenu'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Project Details'' ,4, @CompanyKey, @UserKey, 0, 2, 2, 3, ''ProjectDetails'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Contact Info'' ,4, @CompanyKey, @UserKey, 0, 10, 2, 4, ''ProjectContactInfo'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Daily Feed'' ,4, @CompanyKey, @UserKey, 2, 0, 4, 3, ''ProjectDailyFeed'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Deliverables'' ,4, @CompanyKey, @UserKey, 6, 0, 5, 3, ''ProjectDeliverables'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Recent Conversations'' ,4, @CompanyKey, @UserKey, 6, 3, 5, 3, ''ProjectRecentConversations'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Setup'' ,4, @CompanyKey, @UserKey, 0, 0, 2, 2, ''ProjectSetup'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Spec Sheets'' ,4, @CompanyKey, @UserKey, 2, 3, 4, 3, ''ProjectSpecSheets'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Team'' ,4, @CompanyKey, @UserKey, 2, 6, 4, 3, ''ProjectTeam'', @NewTabKey)
		INSERT INTO tReport ([Name], ReportType, CompanyKey, AddedBy, XPos, YPos, Width, Height, DisplayType, WidgetTabKey) VALUES (''Custom Fields'' ,4, @CompanyKey, @UserKey, 6, 6, 5, 3, ''ProjectCustomFields'', @NewTabKey)
	END
END

Return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptWidgetDashLoad]'
GO
IF OBJECT_ID(N'[dbo].[sptWidgetDashLoad]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[sptWidgetDashLoad]
(
	@CompanyKey int,
	@UserKey int,
	@DashID varchar(50)
)

as

Declare @SGKey int, @Admin tinyint, @SuspendAdmin tinyint, @InitialLoad tinyint, @NewDashKey int, @NewTabKey int
--Get the rights group and admin level
Select @SGKey = SecurityGroupKey, @Admin = ISNULL(Administrator, 0), @SuspendAdmin = ISNULL(SuspendAdmin, 0) from tUser (Nolock) Where UserKey = @UserKey
if @SuspendAdmin = 1 
	Select @Admin = 0


Exec spConvertDashSeed @CompanyKey, @UserKey, @DashID

		
Create Table #tmpKeys ( wtKey int )
delete #tmpKeys

-- Holds the WidgetDashKeys this user is allowed to see (mirrors the dashboards
-- select in each branch below). Used to filter the Recent / Favorite result sets.
Create Table #visibleDash ( WidgetDashKey int )

if @Admin = 0
BEGIN

	-- get a basic list of widgets with the restriction of what you can see for your security group. admin see all.
	-- probably defer this call till they edit the layout
	Select wd.* from tWidgetDef wd (nolock) 
	left outer join tSecurityAccess sa (nolock) on wd.WidgetDefKey = sa.EntityKey and sa.Entity = ''tWidgetDef''
	Where DashID = @DashID and sa.SecurityGroupKey = @SGKey
	Order by Name


	-- load the top level of the dashboards for this dash company or personal that they have right to see.
	Select wd.*, case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private  from tWidgetDash wd (nolock) 
	left outer join tSecurityAccess sa (nolock) on wd.WidgetDashKey = sa.EntityKey and sa.Entity = ''tWidgetDash''
	Where DashID = @DashID and wd.CompanyKey = @CompanyKey and ((ISNULL(wd.UserKey, 0) = 0 and sa.SecurityGroupKey = @SGKey) or wd.UserKey = @UserKey)

		-- capture the visible dashboards for the Recent / Favorite filtering below
		Insert Into #visibleDash ( WidgetDashKey )
		Select distinct wd.WidgetDashKey from tWidgetDash wd (nolock)
		left outer join tSecurityAccess sa (nolock) on wd.WidgetDashKey = sa.EntityKey and sa.Entity = ''tWidgetDash''
		Where DashID = @DashID and wd.CompanyKey = @CompanyKey and ((ISNULL(wd.UserKey, 0) = 0 and sa.SecurityGroupKey = @SGKey) or wd.UserKey = @UserKey)


	-- need to union together the tabs they specifically have rights to see and any tabs with no security tied to dashboards they can see
	Insert Into #tmpKeys ( wtKey )
	Select wt.WidgetTabKey
	from tWidgetTab wt (nolock) 
	inner join tWidgetDash wd (nolock) on wt.WidgetDashKey = wd.WidgetDashKey 
	left outer join tSecurityAccess sa (nolock) on wt.WidgetTabKey = sa.EntityKey and sa.Entity = ''tWidgetTab''
	Where wd.DashID = @DashID and wd.CompanyKey = @CompanyKey and ((ISNULL(wd.UserKey, 0) = 0 and sa.SecurityGroupKey = @SGKey) or wd.UserKey = @UserKey)


	Insert Into #tmpKeys ( wtKey )
	Select wt.WidgetTabKey
	from tWidgetTab wt (nolock) 
	inner join tWidgetDash wd (nolock) on wt.WidgetDashKey = wd.WidgetDashKey 
	left outer join tSecurityAccess sad (nolock) on wd.WidgetDashKey = sad.EntityKey and sad.Entity = ''tWidgetDash''
	left outer join tSecurityAccess sa (nolock) on wt.WidgetTabKey = sa.EntityKey and sa.Entity = ''tWidgetTab''
	Where wd.DashID = @DashID and wd.CompanyKey = @CompanyKey
	and sad.SecurityGroupKey = @SGKey and sa.SecurityGroupKey is null and wt.WidgetTabKey not in (Select wtKey from #tmpKeys)

	Select wt.* 
	from tWidgetTab wt (nolock) 
	inner join #tmpKeys on wt.WidgetTabKey = #tmpKeys.wtKey

	-- this probably needs to get more complicated
	Select r.*, rus.Settings from tReport r (nolock) 
	Inner join #tmpKeys (nolock) on r.WidgetTabKey = #tmpKeys.wtKey
	left outer join tReportUserSetting rus (nolock) on r.ReportKey = rus.ReportKey and rus.UserKey = @UserKey


END

ELSE
BEGIN
	Select wd.* from tWidgetDef wd (nolock) 
	Where DashID = @DashID
	Order by Name

	-- load the top level of the dashboards for this dash company or personal that they have right to see.
	Select wd.*, case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private from tWidgetDash wd (nolock) 
	Where DashID = @DashID and wd.CompanyKey = @CompanyKey and (ISNULL(wd.UserKey, 0) = 0 or wd.UserKey = @UserKey)

		-- capture the visible dashboards for the Recent / Favorite filtering below
		Insert Into #visibleDash ( WidgetDashKey )
		Select distinct wd.WidgetDashKey from tWidgetDash wd (nolock)
		Where DashID = @DashID and wd.CompanyKey = @CompanyKey and (ISNULL(wd.UserKey, 0) = 0 or wd.UserKey = @UserKey)



	-- need to union together the tabs they specifically have rights to see and any tabs with no security tied to dashboards they can see
	Insert Into #tmpKeys ( wtKey )
	Select wt.WidgetTabKey
	from tWidgetTab wt (nolock) 
	inner join tWidgetDash wd (nolock) on wt.WidgetDashKey = wd.WidgetDashKey 
	Where wd.DashID = @DashID and wd.CompanyKey = @CompanyKey


	Insert Into #tmpKeys ( wtKey )
	Select wt.WidgetTabKey
	from tWidgetTab wt (nolock) 
	inner join tWidgetDash wd (nolock) on wt.WidgetDashKey = wd.WidgetDashKey 
	left outer join tSecurityAccess sad (nolock) on wd.WidgetDashKey = sad.EntityKey and sad.Entity = ''tWidgetDash''
	left outer join tSecurityAccess sa (nolock) on wt.WidgetTabKey = sa.EntityKey and sa.Entity = ''tWidgetTab''
	Where wd.DashID = @DashID and wd.CompanyKey = @CompanyKey
	and sa.SecurityGroupKey is null and wt.WidgetTabKey not in (Select wtKey from #tmpKeys)

	Select wt.* 
	from tWidgetTab wt (nolock) 
	inner join #tmpKeys on wt.WidgetTabKey = #tmpKeys.wtKey

	-- this probably needs to get more complicated
	Select r.*, rus.Settings from tReport r (nolock) 
	Inner join #tmpKeys (nolock) on r.WidgetTabKey = #tmpKeys.wtKey
	left outer join tReportUserSetting rus (nolock) on r.ReportKey = rus.ReportKey and rus.UserKey = @UserKey
	

END


Select SecurityGroupKey, GroupName, 0 as Selected from tSecurityGroup (nolock) Where CompanyKey = @CompanyKey

select sa.*, sg.GroupName from tSecurityAccess sa (nolock) 
inner join tSecurityGroup sg (nolock) on sa.SecurityGroupKey = sg.SecurityGroupKey
Where sa.Entity = ''tWidgetDash'' and sg.CompanyKey = @CompanyKey

select sa.*, sg.GroupName from tSecurityAccess sa (nolock)
inner join tSecurityGroup sg (nolock) on sa.SecurityGroupKey = sg.SecurityGroupKey
Where sa.Entity = ''tWidgetTab'' and sg.CompanyKey = @CompanyKey


-- Recent dashboards: this user''s most-recently-accessed, newest first, capped at 10,
-- limited to dashboards they can still see (#visibleDash).
-- Sourced from the generic tRecentFavorite (Entity = ''tWidgetDash'').
Select top 10 wd.*, case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private, r.DateRecent as DateLastAccessed
from tRecentFavorite r (nolock)
inner join tWidgetDash wd (nolock) on r.EntityKey = wd.WidgetDashKey
inner join #visibleDash vd (nolock) on wd.WidgetDashKey = vd.WidgetDashKey
Where r.CompanyKey = @CompanyKey and r.UserKey = @UserKey and r.Entity = ''tWidgetDash'' and ISNULL(r.Recent, 0) = 1
Order by r.DateRecent desc

-- Favorite dashboards: this user''s pinned dashboards, alpha by Label,
-- limited to dashboards they can still see (#visibleDash).
-- Sourced from the generic tRecentFavorite (Entity = ''tWidgetDash'').
Select wd.*, case when ISNULL(wd.UserKey, 0) > 0 then 1 else 0 end as Private
from tRecentFavorite f (nolock)
inner join tWidgetDash wd (nolock) on f.EntityKey = wd.WidgetDashKey
inner join #visibleDash vd (nolock) on wd.WidgetDashKey = vd.WidgetDashKey
Where f.CompanyKey = @CompanyKey and f.UserKey = @UserKey and f.Entity = ''tWidgetDash'' and ISNULL(f.Favorite, 0) = 1
Order by wd.Label
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spConvertDB10500]'
GO
IF OBJECT_ID(N'[dbo].[spConvertDB10500]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spConvertDB10500]
(
@SeedOnly tinyint = 0
)
AS


Delete tRight


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (11605, ''viewLegacyFields'', ''View Legacy Fields'', ''admin'', ''admin'', 25, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90901, ''prjEditTeam'', ''Edit the Project Team (Workamajig Only)'', ''project'', ''admin'', 52, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10100, ''adminsetup'', ''Maintain Setup Information'', ''admin'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10101, ''adminsetup_acctinfo'', ''---- Edit Account Information'', ''admin'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10102, ''adminsetup_globaloptions'', ''---- Edit Global Options'', ''admin'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10103, ''adminsetup_dashboard'', ''---- Edit Dashboards'', ''admin'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10104, ''adminsetup_GLSettings'', ''---- Edit GL Settings'', ''admin'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10105, ''adminsetup_CM'', ''---- Edit Contact Management options'', ''admin'', ''admin'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10106, ''adminsetup_timeoptions'', ''---- Edit Time, Expense & Billing options'', ''admin'', ''admin'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10107, ''adminsetup_media'', ''---- Edit Media Setup options'', ''admin'', ''admin'', 8, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10108, ''adminsetup_specsheet'', ''---- Edit Spec Sheets'', ''admin'', ''admin'', 9, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10109, ''adminsetup_projrequest'', ''---- Edit Project Requests'', ''admin'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10110, ''adminsetup_forms'', ''---- Edit Tracking Forms'', ''admin'', ''admin'', 11, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10111, ''adminsetup_purchasing'', ''---- Edit Purchasing Options'', ''admin'', ''admin'', 12, 1)
--INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10112, ''adminsetup_da'', ''---- Edit Digital Assets Options'', ''admin'', ''admin'', 13, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10113, ''adminsetup_custfields'', ''---- Edit and Assign Custom Fields'', ''admin'', ''admin'', 14, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10200, ''admineditinout'', ''Edit Other Peoples In / Out Status'', ''admin'', ''admin'', 15, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10600, ''adminemployee'', ''Maintain Company Employees'', ''admin'', ''admin'', 16, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10700, ''admineditlogin'', ''Edit Employee and Contact Login information'', ''admin'', ''admin'', 17, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10720, ''user_billing'', ''Edit Employee and Contact Billing Information '', ''admin'', ''admin'', 18, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10750, ''adminviewcostrate'', ''View Staff cost per hour in the User Lookup'', ''admin'', ''admin'', 19, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10800, ''adminedituserskills'', ''Maintain User Skill Levels'', ''admin'', ''admin'', 20, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10805, ''admineditusercalendar'', ''Maintain Employee Calendar '', ''admin'', ''admin'', 20, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (11200, ''reportsdesign'', ''Design custom reports'', ''admin'', ''admin'', 22, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (11300, ''reportsrun'', ''Run custom reports'', ''admin'', ''admin'', 23, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (11400, ''dataexchange'', ''Import and export data'', ''admin'', ''admin'', 24, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (11500, ''admineditlisting'', ''Edit Custom Listings'', ''admin'', ''admin'', 21, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (11601, ''adminViewLog'', ''View the System Log'', ''admin'', ''admin'', 26, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20100, ''approveadd'', ''Add and Edit Digital Art Reviews'', ''project'', ''admin'', 21, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20300, ''approvedelete'', ''Delete a Digital Art Reviews'', ''project'', ''admin'', 22, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30100, ''billingeditinvoice'', ''Add and Edit Client Invoices and Credits'', ''billing'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30200, ''billingpayments'', ''Enter Receipts'', ''billing'', ''admin'', 2, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30300, ''br_viewarreports'', ''-- View AR Reports --'', ''reports'', ''admin'', 4000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30310, ''br_viewapreports'', ''-- View AP Reports --'', ''reports'', ''admin'', 5000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30320, ''br_viewglfinancial'', ''-- View Company Financial Reports --'', ''reports'', ''admin'', 7000, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30330, ''br_viewmedia'', ''-- View Media Reports --'', ''reports'', ''admin'', 6000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30700, ''billingdeposits'', ''Edit Deposit Slips'', ''billing'', ''admin'', 3, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30800, ''billingcreditcard'', ''Edit and Charge Credit Cards'', ''billing'', ''admin'', 4, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30900, ''billingretainers'', ''Edit Retainers'', ''billing'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30901, ''billingviewretainers'', ''View Retainers'', ''billing'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30902, ''billingremovefromsheet'', ''Delete Worksheets and Remove Items from Worksheets'', ''billing'', ''admin'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (30903, ''billingedittran'', ''Edit and Move Transactions on Projects'', ''billing'', ''admin'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (40400, ''dash_showsnapshot'', ''View the Project Snapshot'', ''dashboard'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (40500, ''dash_showprofit'', ''View the Profit Snapshot'', ''dashboard'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (40600, ''dash_editcompanynotes'', ''Edit the Company Wide Notes'', ''dashboard'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (40700, ''dash_editprojectnotes'', ''Edit the Project Notes'', ''dashboard'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (40800, ''dash_editcontactnotes'', ''Edit the Contact Notes (in contact management)'', ''dashboard'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (50100, ''fileAccess'', ''Access the File Folders'', ''file'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (50110, ''fileSearchAll'', ''Search in projects you are not assigned to'', ''file'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (60100, ''purch_editpo'', ''Add and Edit PO''''s'', ''purch'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (60300, ''purch_editvoucher'', ''Add and Edit Vendor Invoices'', ''purch'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (61100, ''quote_edit'', ''Add and Edit Quotes'', ''purch'', ''admin'', 8, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (61200, ''quote_createpo'', ''Create PO''''s from Quotes'', ''purch'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (61300, ''purch_editpayment'', ''Add and Edit Payments'', ''purch'', ''admin'', 9, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (61400, ''purch_viewiteminfo'', ''View Cost and Rate on Item Lookup '', ''purch'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (70100, ''formuse'', ''Use forms'', ''form'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (70200, ''formadd'', ''Add new forms'', ''form'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (70300, ''formdelete'', ''Delete forms'', ''form'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (70400, ''formviewall'', ''View forms not assigned to the user'', ''form'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (70500, ''nonauthorformdelete'', ''Delete form if not author'', ''form'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90100, ''adminCreateProject'', ''Create New Projects'', ''project'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90200, ''prjInfo'', ''Maintain Project Setup'', ''project'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90300, ''prjviewprojectreports'', ''-- View Project Financial Reports --'', ''reports'', ''admin'', 2000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90310, ''prjviewtasks'', ''View Task, Schedule Pages'', ''project'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90315, ''prjviewbudget'', ''View Project Budget Page'', ''project'', ''admin'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90320, ''prjedittasks'', ''Edit task information'', ''project'', ''admin'', 8, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90330, ''prjeditestimate'', ''Edit Estimate Information'', ''project'', ''admin'', 12, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90335, ''prjeditestimaterates'', ''Edit Rates on Estimates'', ''project'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90336, ''prjrecalcrates'', ''Update Estimate Rates from Project'', ''project'', ''admin'', 11, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90340, ''prjunappestimate'', ''Unapprove estimate or change order '', ''project'', ''admin'', 20, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90350, ''prjeditcreativebrief'', ''Edit the Creative Brief'', ''project'', ''admin'', 16, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90355, ''prjeditmastertaskdefs'', ''Edit Master Task defaults on task'', ''project'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90360, ''prjeditspecs'', ''Edit the Specifications'', ''project'', ''admin'', 18, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90370, ''prjMiscExpense'', ''Add and Edit Misc Expenses'', ''project'', ''admin'', 19, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90600, ''prjviewcreativebrief'', ''View the Creative Brief'', ''project'', ''admin'', 15, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90700, ''prjviewspecs'', ''View the Project Specifications'', ''project'', ''admin'', 17, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90800, ''prjEditCampaign'', ''Edit Campaigns'', ''project'', ''admin'', 51, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90810, ''prjEditLocked'', ''Edit Projects in a Locked Status'', ''project'', ''admin'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90850, ''prjUnlockLocked'', ''Override Scheduling Lock'', ''project'', ''admin'', 9, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90900, ''prjViewCampaign'', ''View Campaigns'', ''project'', ''admin'', 50, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100100, ''billingusetimesheet'', ''Use Timesheets'', ''time'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100110, ''time_editratelevel'', ''Edit the rate level on the time sheet'', ''time'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100120, ''timeallservices'', ''Charge time to any service'', ''time'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100130, ''timealltasks'', ''Charge time to any task'', ''time'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100300, ''billingtimesheetrate'', ''View rates on the timesheet'', ''time'', ''admin'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100400, ''billingviewalltime'', ''View anyone''''s timesheet'', ''time'', ''admin'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100500, ''billinguseexpenses'', ''Use Expenses'', ''time'', ''admin'', 8, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100700, ''billingviewallexpense'', ''View anyone''''s expense report'', ''time'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (100800, ''billingeditanyone'', ''Edit Time Sheets and Expense Reports for anyone'', ''time'', ''admin'', 11, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (110300, ''traffic_viewschedule'', ''View Project Schedules'', ''traffic'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (110900, ''traffic_viewstaff'', ''View Staff Scheduling and Loading'', ''traffic'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (110950, ''traffic_viewassignment'', ''Traffic Assignment Review'', ''traffic'', ''admin'', 3, 1)


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200100, ''proj_projectsummary'', ''Project Budget Summary'', ''reports'', ''admin'', 2010, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200200, ''time_productivity'', ''Time Productivity Analysis'', ''reports'', ''admin'', 2020, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200300, ''proj_billingworksheet'', ''Billing Worksheet'', ''reports'', ''admin'', 2200, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200400, ''proj_projectpo'', ''Project Purchase Order Listing'', ''reports'', ''admin'', 2300, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200500, ''time_chargeabilitysummary_hours'', ''Chargeability Summary - Hours'', ''reports'', ''admin'', 2100, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200600, ''time_chargeabilitysummary_dollars'', ''Chargeability Summary - Dollars'', ''reports'', ''admin'', 2120, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (200700, ''proj_actualsbymonth'', ''Project Actuals by Month'', ''reports'', ''admin'', 2121, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300000, ''rpt_trafficreports'', ''--  View Traffic Reports --'', ''reports'', ''admin'', 3000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300100, ''proj_projectstatus'', ''Project Status'', ''reports'', ''admin'', 3100, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300200, ''tasks_byUser'', ''Project Tasks by Person'', ''reports'', ''admin'', 3200, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300300, ''tasks_byUserDate'', ''Project Tasks by Person and Date'', ''reports'', ''admin'', 3300, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300400, ''tasks_byDate'', ''Project Tasks by Date'', ''reports'', ''admin'', 3400, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300500, ''tasks_setup'', ''Project Setup'', ''reports'', ''admin'', 3500, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (300600, ''tasks_gantt'', ''Project Gantt Charts'', ''reports'', ''admin'', 3600, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (303301, ''media_recap'', ''Media Recap'', ''reports'', ''admin'', 6010, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (303302, ''media_discrepancy'', ''Media Discrepancy Report'', ''reports'', ''admin'', 6020, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (303303, ''media_mixanalysis'', ''Media Mix Analysis'', ''reports'', ''admin'', 6030, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (400100, ''acct_ar_aging'', ''AR Account Aging'', ''reports'', ''admin'', 4010, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (400300, ''acct_projectwip'', ''Project WIP Report'', ''reports'', ''admin'', 2150, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (401000, ''usereports'', ''View the reports menu'', ''reports'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (401100, ''rptViewCMReports'', ''-- View Contact Management Reports --'', ''reports'', ''admin'', 1000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (401200, ''rptCMBusDev'', ''Business Development Meeting'', ''reports'', ''admin'', 1001, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (401300, ''rptCMDownOpps'', ''Downgraded Opportunities'', ''reports'', ''admin'', 1002, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500000, ''adminsetup_media'', ''Edit the Media setup files'', ''media'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500010, ''media_editio'', ''Edit Insertion Orders'', ''media'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500020, ''media_editbc'', ''Edit Broadcast Orders'', ''media'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500030, ''media_editestimate'', ''Edit Media Estimates'', ''media'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500040, ''media_traffic'', ''View the Media Traffic Screen'', ''media'', ''admin'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500100, ''client_calendar'', ''View the calendar'', ''client'', ''client'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500200, ''client_approvals'', ''View the approvals page'', ''client'', ''client'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500300, ''client_schedule'', ''View the project schedule'', ''client'', ''client'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500400, ''client_hours'', ''View hours on project budget '', ''client'', ''client'', 8, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500500, ''client_budget'', ''View project budget page'', ''client'', ''client'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500550, ''client_viewbudget'', ''View the project budget'', ''client'', ''client'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500600, ''client_budgetdetail'', ''Drill down on budget transactions details '', ''client'', ''client'', 9, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500650, ''client_budgetactuals'', ''View actual dollars and hours on a project budget'', ''client'', ''client'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500700, ''client_invoices'', ''View current invoices'', ''client'', ''client'', 11, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500750, ''client_invoicespast'', ''View closed invoices'', ''client'', ''client'', 12, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (500800, ''client_originalschedule'', ''View the original schedule'', ''client'', ''client'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501100, ''client_prview'', ''View Project Requests'', ''client'', ''client'', 13, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501200, ''client_pradd'', ''Add New Project Requests'', ''client'', ''client'', 14, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501300, ''client_predit'', ''Edit Project Requests from their company'', ''client'', ''client'', 15, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501400, ''client_prdelete'', ''Can delete requests from their company'', ''client'', ''client'', 16, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501450, ''client_praddnewspec'', ''Can add and delete spec sheets on project requests'', ''client'', ''client'', 23, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501500, ''client_dafiles'', ''Can View Digital Asset Files'', ''client'', ''client'', 17, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501550, ''client_dafilesupload'', ''Can Upload Digital Asset Files'', ''client'', ''client'', 18, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501600, ''client_projectlist'', ''View the list of assigned projects'', ''client'', ''client'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501700, ''client_notes'', ''Add and Edit the Project Diary'', ''client'', ''client'', 19, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501800, ''client_myinfo'', ''Change MyInfo data and password'', ''client'', ''client'', 20, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501801, ''client_assignments'', ''View Assigned Tasks'', ''client'', ''client'', 21, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501810, ''client_daviewprior'', ''Can view prior digital art reviews'', ''client'', ''client'', 22, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501820, ''client_viewinvoicecompany'', ''View Invoices for Company'', ''client'', ''client'', 23, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501830, ''client_viewinvoiceparentcompany'', ''View Invoices for Parent Company'', ''client'', ''client'', 24, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501840, ''client_projectdescription'', ''View the Project Description'', ''client'', ''client'', 25, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501850, ''client_projectteam'', ''View the Project Team'', ''client'', ''client'', 26, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501860, ''client_creativebrief'', ''View the Project Creative Brief'', ''client'', ''client'', 27, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (501870, ''client_projectspecs'', ''View the Project Specifications'', ''client'', ''client'', 28, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (601000, ''desktopEditSetup'', ''Edit the company settings for the desktop (Workamajig Only)'', ''desktop'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (903500, ''adminDeleteProject'', ''Delete a Project'', ''project'', ''admin'', 14, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (903510, ''prjReopen'', ''Reopen Projects'', ''project'', ''admin'', 3, 1)


INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (10500, ''admincontact'', ''View the Company Address Book (CM Only)'', ''cm'', ''admin'', 1, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930000, ''cm_editcontacts'', ''Edit contact information (CM Only)'', ''cm'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930100, ''cm_viewothermanagers'', ''View Other Account Manager''''s Opportunities and Activities (CM Only)'', ''cm'', ''admin'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930150, ''cm_dashboard'', ''View the contact management dashboard (CM Only)'', ''cm'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930200, ''cm_viewleads'', ''View and Edit Opportunities (CM Only)'', ''cm'', ''admin'', 8, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930400, ''cm_viewactivities'', ''View Contact Activites (CM Only)'', ''cm'', ''admin'', 9, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930500, ''cm_allowdelete'', ''Delete contacts (CM Only)'', ''cm'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930600, ''cm_showall'', ''See contacts they do not own (CM Only)'', ''cm'', ''admin'', 11, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930700, ''cm_alldb'', ''See contacts in all databases (CM Only)'', ''cm'', ''admin'', 12, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (120100, ''calUseCalendar'', ''Access the calendar'', ''calendar'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (120200, ''caladdmeetings'', ''Add New Meetings'', ''calendar'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (120300, ''calviewcompany'', ''View Company Meetings (CM Only)'', ''calendar'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (120400, ''calBlockOutDays'', ''Mark Calendar Events to block out days on the schedule'', ''calendar'', ''admin'', 72, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (120500, ''caleditglobalgroups'', ''Maintain Global Distribution Groups'', ''calendar'', ''admin'', 73, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (120600, ''foldersCalendar'', ''Add/Edit/Delete Public Calendars'', ''calendar'', ''admin'', 71, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931400, ''useLeads'', ''Use Lead'', ''cm'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931401, ''viewOtherLeads'', ''View Leads You Do Not Own'', ''cm'', ''admin'', 11, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931402, ''editOtherLeads'', ''Edit Leads You Do Not Own'', ''cm'', ''admin'', 12, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931403, ''addLeads'', ''Add Leads'', ''cm'', ''admin'', 13, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931404, ''deleteLeads'', ''Delete Leads'', ''cm'', ''admin'', 14, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931405, ''foldersLeads'', ''Add/Edit/Delete Lead Folders'', ''cm'', ''admin'', 15, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931600, ''useContacts'', ''Use Contacts'', ''cm'', ''admin'', 20, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931601, ''viewOtherContacts'', ''View Contacts You Do Not Own'', ''cm'', ''admin'', 21, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931602, ''editOtherContacts'', ''Edit Contacts You Do Not Own'', ''cm'', ''admin'', 22, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931603, ''addContacts'', ''Add New Contacts'', ''cm'', ''admin'', 23, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931604, ''deleteContacts'', ''Delete Public Contacts'', ''cm'', ''admin'', 24, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931605, ''moveFoldersContacts'', ''Move Public Contacts to Private Folders'', ''cm'', ''admin'', 25, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931606, ''foldersContacts'', ''Add/Edit/Delete Public Contact Folders'', ''cm'', ''admin'', 26, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931700, ''useCompanies'', ''Use Companies'', ''cm'', ''admin'', 30, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931701, ''viewOtherCompanies'', ''View Companies You Do Not Own'', ''cm'', ''admin'', 31, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931702, ''editOtherCompanies'', ''Edit Companies You Do Not Own'', ''cm'', ''admin'', 32, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931703, ''addCompanies'', ''Add new Companies'', ''cm'', ''admin'', 33, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931704, ''deleteCompanies'', ''Delete Companies'', ''cm'', ''admin'', 34, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931705, ''foldersCompanies'', ''Add/Edit/Delete Company Folders'', ''cm'', ''admin'', 35, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931706, ''cm_editacctinfo'', ''Edit Accounting Information'', ''cm'', ''admin'', 36, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931100, ''useOpp'', ''Use Opportunities'', ''cm'', ''admin'', 40, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931101, ''viewOtherOpp'', ''View Opportunities You Do Not Own'', ''cm'', ''admin'', 41, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931102, ''editOtherOpp'', ''Edit Opportunities You Do Not Own'', ''cm'', ''admin'', 42, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931103, ''addOpp'', ''Add New Opportunities'', ''cm'', ''admin'', 43, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931104, ''deleteOpp'', ''Delete Opportunities'', ''cm'', ''admin'', 44, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931105, ''foldersOpp'', ''Add/Edit/Delete Opportunity Folders'', ''cm'', ''admin'', 45, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931500, ''useActivities'', ''Use Activities'', ''cm'', ''admin'', 50, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931501, ''viewOtherActivities'', ''View Activities Not Assigned To You'', ''cm'', ''admin'', 51, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931502, ''editOtherActivities'', ''Edit Activities Not Assigned To You'', ''cm'', ''admin'', 52, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931503, ''deleteActivities'', ''Delete Activities'', ''cm'', ''admin'', 53, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931504, ''foldersActivities'', ''Add/Edit/Delete Public Activity Folders'', ''cm'', ''admin'', 54, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931505, ''moveFoldersActivities'', ''Move Public Activities to Private Folders'', ''cm'', ''admin'', 55, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931506, ''activityAllwaysCheckOpp'', ''Always Check for Opportunities on Actvities'', ''cm'', ''admin'', 56, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (931550, ''useMarketingLists'', ''Use Marketing Lists'', ''cm'', ''admin'', 60, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930800, ''cm_viewclientlist'', ''View the client list'', ''cm'', ''admin'', 34, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (930900, ''cm_viewvendorlist'', ''View the vendor list'', ''cm'', ''admin'', 35, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940100, ''gl_glaccount'', ''Maintain GL Accounts'', ''acct'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940200, ''gl_journalentry'', ''Enter Journal Entries'', ''acct'', ''admin'', 2, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940300, ''gl_budget'', ''Enter GL Budgets'', ''acct'', ''admin'', 3, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940400, ''gl_accountrecs'', ''Reconcile GL Accounts'', ''acct'', ''admin'', 7, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940450, ''gl_post'', ''Post Transaction to the General Ledger'', ''acct'', ''admin'', 9, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940500, ''gl_postwip'', ''Post WIP to GL'', ''acct'', ''admin'', 8, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940600, ''laborbud_edit'', ''Edit Labor Budgets'', ''acct'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940610, ''laborbud_viewanyoffice'', ''---- Edit / View labor budgets for any office'', ''acct'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940620, ''laborbud_viewanydept'', ''---- Edit / View labor budgets for any department'', ''acct'', ''admin'', 6, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940630, ''chargesum_viewanyperson'', ''---- View any or all people on chargeability summary'', ''acct'', ''admin'', 7, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940700, ''accteditanytime'', ''Edit transactions after approval'', ''acct'', ''admin'', 10, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (940800, ''gl_editgross'', ''Edit Gross Amounts on Transactions'', ''acct'', ''admin'', 11, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950000, ''acct_ap_aging'', ''AP Account Aging'', ''reports'', ''admin'', 5010, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950001, ''acct_ap_listing'', ''AP Listing'', ''reports'', ''admin'', 5020, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950002, ''acct_ap_1099'', ''1099 Vendor Detail'', ''reports'', ''admin'', 5050, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950003, ''acct_po_listing'', ''Purchase Order Listing'', ''reports'', ''admin'', 5060, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950004, ''acct_po_project'', ''Project PO Listing'', ''reports'', ''admin'', 5070, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950005, ''acct_ap_checks'', ''Payment Listing'', ''reports'', ''admin'', 5080, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950006, ''acct_ar_invoicesummary'', ''Invoice Summary'', ''reports'', ''admin'', 4050, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950007, ''acct_ar_invoicelineitemsummary'', ''Invoice Line Item Summary'', ''reports'', ''admin'', 4060, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950008, ''acct_gl_trailbal'', ''Trial Balance'', ''reports'', ''admin'', 7130, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950009, ''acct_gl_genledger'', ''General Ledger'', ''reports'', ''admin'', 7140, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950010, ''acct_gl_genjournal'', ''General Journal'', ''reports'', ''admin'', 7150, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950011, ''acct_gl_pl_ytd'', ''Income Statement'', ''reports'', ''admin'', 7160, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950012, ''acct_gl_balsheet'', ''Balance Sheet'', ''reports'', ''admin'', 7170, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950013, ''acct_ap_purchjournal'', ''Purchase Journal'', ''reports'', ''admin'', 5030, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950014, ''acct_ap_payjournal'', ''Cash Disbursements Journal'', ''reports'', ''admin'', 5040, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950015, ''acct_ar_salesjournal'', ''Sales Journal'', ''reports'', ''admin'', 4020, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950016, ''acct_ar_cashjournal'', ''Cash Receipts Journal'', ''reports'', ''admin'', 4030, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950020, ''acct_ar_statement'', ''Client Statements'', ''reports'', ''admin'', 4040, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950025, ''acct_inv_backup'', ''Invoice Backup'', ''reports'', ''admin'', 4045, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950030, ''acct_gl_excel'', ''Access Financials from Excel'', ''reports'', ''admin'', 7180, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950040, ''acct_ap_accruedorder'', ''AP Accrued Order Detail Report'', ''reports'', ''admin'', 5075, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950045, ''acct_ap_exceptions'', ''AP Exceptions Report'', ''reports'', ''admin'', 5015, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950110, ''acct_salestaxanalysis'', ''Sales Tax Analysis Report'', ''reports'', ''admin'', 4070, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950120, ''acct_projectprofit'', ''Project Profitability'', ''reports'', ''admin'', 2015, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950121, ''acct_projectrealization'', ''Project Hourly Realization Rate'', ''reports'', ''admin'', 2016, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950130, ''acct_gl_statement_cashflow'', ''Statement of Cash Flows'', ''reports'', ''admin'', 7180, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950135, ''acct_gl_cashprojection'', ''Cash Projection'', ''reports'', ''admin'', 7185, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950136, ''acct_gl_uncleared'', ''Uncleared Transactions'', ''reports'', ''admin'', 7186, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (950140, ''acct_metrics'', ''Metrics Monitor'', ''reports'', ''admin'', 7190, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960000, ''pr_viewrequests'', ''View Project Requests'', ''requests'', ''admin'', 1, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960010, ''pr_addrequests'', ''Add New Requests to the system'', ''requests'', ''admin'', 2, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960020, ''pr_editrequests'', ''Edit Existing Requests'', ''requests'', ''admin'', 3, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960030, ''pr_deleterequests'', ''Delete Existing Requests'', ''requests'', ''admin'', 4, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960040, ''pr_editapproval'', ''Edit the approval process'', ''requests'', ''admin'', 5, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960050, ''proj_projectassignments'', ''Assigned Tasks'', ''reports'', ''admin'', 3150, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (960051, ''admin_employeehours'', ''Employee Actual Hours Report'', ''reports'', ''admin'', 5076, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (1190930, ''prjnotes'', ''Add and Edit Project Diary Notes'', ''project'', ''admin'', 13, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20000000, ''br_viewlegacy'', ''-- View Legacy Reports --'', ''reports'', ''admin'', 9000, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20000001, ''legacy_proj_projectsummary'', ''Project Budget Summary (Legacy)'', ''reports'', ''admin'', 9001, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20000002, ''legacy_acct_projectprofit'', ''Project Profitability (Legacy)'', ''reports'', ''admin'', 9002, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20000003, ''legacy_acct_projectwip'', ''Project WIP Report (Legacy)'', ''reports'', ''admin'', 9003, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (20000004, ''legacy_acct_gl_pl_ytd'', ''Income Statement (Legacy)'', ''reports'', ''admin'', 9004, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90000001, ''cbeditbatch'', ''Edit Charge Back Batches'', ''billing'', ''ChargeCodes'', 1, 0)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (91000000, ''muddAMRpt'', ''AGI By Account Manager Report'', ''reports'', ''mudd'', 999, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (91000001, ''muddSMRpt'', ''AGI By Sales Manager'', ''reports'', ''mudd'', 999, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (91000002, ''muddAMClientRpt'', ''AGI By Account Manager or Client'', ''reports'', ''mudd'', 999, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (92000000, ''partnersnapierMonthyActualHours'', ''Retainer Monthly Actual Hours'', ''reports'', ''partnersnapier'', 999, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (92000001, ''partnersnapierMonthyActualHrsBudget'', ''Retainer Monthly Actual Hours with Budget'', ''reports'', ''partnersnapier'', 999, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (92000002, ''partnersnapierSalesJournal'', ''Custom Sales Journal'', ''reports'', ''partnersnapier'', 999, 1)

INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90911, ''prjDashStatus'', ''View the current status on the project dashboard'', ''project'', ''admin'', 100, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90912, ''prjDashDescription'', ''View the project description on the project dashboard'', ''project'', ''admin'', 101, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90913, ''prjDashSetup'', ''View the setup information on the project dashboard'', ''project'', ''admin'', 102, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90914, ''prjDashBrief'', ''View the creative brief on the project dashboard'', ''project'', ''admin'', 103, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90915, ''prjDashSpecs'', ''View the spec sheets on the project dashboard'', ''project'', ''admin'', 104, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90916, ''prjDashTeam'', ''View the team list on the project dashboard'', ''project'', ''admin'', 105, 1)
INSERT tRight(RightKey, RightID, Description, RightGroup, SetGroup, DisplayOrder, CPM) Values (90917, ''prjDashSnapshot'', ''View the project snapshot on the project dashboard'', ''project'', ''admin'', 106, 1)



Delete tWidget

INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (1, NULL, ''RSS Reader'', ''RSS Reader'', ''main'', 0, ''OtherRSSReader.swf'', ''widgetOther'', ''<settings><Title>RSS READER</Title><rssUrl></rssUrl></settings>'', 1, 1, 400, 400, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (2, NULL, ''Chargeability Summary'', ''Displays the chargeability summary'', ''main'', 0, ''MetricsChargeabilitySummary.swf'', ''widgetMetric'', ''<settings><title>CHARGEABILITY SUMMARY</title><laborBudgetKey>-1</laborBudgetKey><officeKey>-1</officeKey><departmentKey>-1</departmentKey><userKey>-1</userKey></settings>'', 1, 1, 295, 400, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (3, NULL, ''Metrics Monitor'', ''Displays a single snapshot of all the metrics in the monitor'', ''main'', 0, ''MetricsMonitorSummary.swf'', ''widgetMetric'', '''', 1, 1, 450, 325, 0, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (4, NULL, ''Income By Service'', ''Displays income by service'', ''main'', 0, ''MetricsIncomeByService.swf'', ''widgetMetric'', ''<settings><title>INCOME BY SERVICE</title><numServices>5</numServices><dateRange>0</dateRange></settings>'', 1, 1, 285, 410, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (5, NULL, ''Vulnerability To Loss'', ''Displays your revenue allocation by client'', ''main'', 0, ''MetricsVulnerabilityToLoss.swf'', ''widgetMetric'', ''<settings><title>VULNERABILITY TO LOSS</title><dateRange>1</dateRange></settings>'', 1, 1, 290, 480, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (6, NULL, ''Cash On Hand'', ''Displays the amount of cash on hand'', ''main'', 0, ''MetricsCashOnHand.swf'', ''widgetMetric'', ''<settings><title>CASH ON HAND</title><upperTarget>0</upperTarget><lowerTarget>0</lowerTarget></settings>'', 1, 1, 285, 345, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (7, NULL, ''Revenue Per Employee'', ''Displays the amount of revenue per employee'', ''main'', 0, ''MetricsRevenuePerEmployee.swf'', ''widgetMetric'', ''<settings><title>REVENUE PER EMPLOYEE</title><laborBudgetKey>0</laborBudgetKey><fullTimeHours>2080</fullTimeHours><upperTarget>8500</upperTarget><lowerTarget>6000</lowerTarget></settings>'', 1, 1, 285, 345, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (8, NULL, ''Repeat Clients'', ''Displays the percentage of repeat clients'', ''main'', 0, ''MetricsRepeatClients.swf'', ''widgetMetric'', ''<settings><title>REPEAT CLIENTS</title><upperTarget>80</upperTarget><lowerTarget>50</lowerTarget><dateRange>0</dateRange></settings>'', 1, 1, 300, 330, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (9, NULL, ''Markup By Item'', ''Displays the Markup for each item'', ''main'', 0, ''MetricsMarkupByItem.swf'', ''widgetMetric'', ''<settings><title>MARKUP BY ITEM</title><numItems>5</numItems><target>25</target><dateRange>1</dateRange></settings>'', 1, 1, 285, 345, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (10, NULL, ''Chargeability Percentage'', ''Displays the percentage of billable hours divided by total hours'', ''main'', 0, ''MetricsChargeabilityPercentage.swf'', ''widgetMetric'', ''<settings><title>CHARGEABILITY PERCENTAGE</title><userKey>-1</userKey><upperTarget>75</upperTarget><lowerTarget>50</lowerTarget><dateRange>-1</dateRange></settings>'', 1, 1, 295, 360, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (11, NULL, ''Write Off Summary'', ''Displays the labor written off and the associated reason'', ''main'', 0, ''MetricsWriteOffSummary.swf'', ''widgetMetric'', ''<settings><title>WRITE OFF SUMMARY</title><officeKey>-1</officeKey><departmentKey>-1</departmentKey><userKey>-1</userKey><dateRange>0</dateRange></settings>'', 1, 1, 320, 410, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (12, NULL, ''Billable Efficiency'', ''Compares how much of your billable time you able to realize against your targets'', ''main'', 0, ''MetricsBillingEfficiency.swf'', ''widgetMetric'', ''<settings><title>BILLABLE EFFICIENCY</title><laborBudgetKey>0</laborBudgetKey><dateRange>1</dateRange></settings>'', 1, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (15, NULL, ''Tracking Forms'', ''Displays a summary of any tracking forms that have been assigned to you'', ''main'', 0, ''OperationalForms.swf'', ''widgetOperational'', '''', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (16, NULL, ''Active Projects'', ''Diplays a list of all active projects you are assigned to'', ''main'', 0, ''OperationalActiveProjects.swf'', ''widgetOperational'', ''<settings><title>ACTIVE PROJECTS</title><openAssignmentsOnly>0</openAssignmentsOnly><groupBy>None</groupBy><groupByOrder>ASC</groupByOrder><sortBy>None</sortBy><sortByOrder>ASC</sortByOrder><projectStatus>-1</projectStatus><billingStatus>-1</billingStatus><warningPercent>80</warningPercent><layout></layout></settings>'', 0, 1, 400, 630, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (17, NULL, ''My Tasks'', ''Displays a summary of any tracking forms that have been assigned to you'', ''main'', 0, ''OperationalMyTasks.swf'', ''widgetOperational'', ''<settings><title>MY TASKS</title><dateRange>0</dateRange><showOnRight>0</showOnRight><defaultSort>ProjectNumber</defaultSort><layout></layout><direction>Asc</direction><warningPerc>75</warningPerc><completedOnly>0</completedOnly><groupBy>NoGrouping</groupBy><groupByOrder>Asc</groupByOrder></settings>'', 0, 1, 400, 700, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (21, NULL, ''My Items to Approve'', ''View a summary of all the items you have to approve'', ''main'', 0, ''OperationalMyApprovals.swf'', ''widgetOperational'', '''', 0, 1, 500, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (22, NULL, ''My Notes'', ''Allows you to add a personal note to your desktop'', ''main'', 0, ''OperationalMyNote.swf'', ''widgetOperational'', ''<settings><title>MY NOTES</title></settings>'', 0, 1, 500, 500, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (23, NULL, ''Company Notes'', ''View the company message on your desktop'', ''main'', 0, ''OperationalCompanyNote.swf'', ''widgetOperational'', ''<settings><title>COMPANY NOTES</title></settings>'', 0, 0, 500, 500, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (24, NULL, ''My Activities'', ''View and update your contact management activities'', ''main'', 0, ''OperationalMyActivities.swf'', ''widgetOperational'', ''<settings><title>MY ACTIVITIES</title><dateRange>1</dateRange><hideActivityNotes>0</hideActivityNotes><direction>ASC</direction></settings>'', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (25, NULL, ''In Out Board'', ''View who is in and out of the office'', ''main'', 0, ''OperationalInOutBoard.swf'', ''widgetOperational'', ''<settings><title>IN/OUT BOARD</title></settings>'', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (26, NULL, ''Today''''s Meetings'', ''View the events for today'', ''main'', 0, ''OperationalTodaysEvents.swf'', ''widgetOperational'', ''<settings><title>TODAY''''S MEETINGS</title></settings>'', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (27, NULL, ''Today''''s Time'', ''View all your time entries for today'', ''main'', 0, ''OperationalTodaysTime.swf'', ''widgetOperational'', ''<settings><title>TODAY''''S TIME</title></settings>'', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (28, NULL, ''Client Notes'', ''Allows you to view notes setup for a client. This is only visible to the actual client when the log in'', ''main'', 0, ''OperationalClientNote.swf'', ''widgetOperational'', '''', 0, 1, 500, 500, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (29, NULL, ''Opportunity Pipeline'', ''View the opportunity pipeline'', ''main'', 0, ''OpportunityPipeline.swf'', ''widgetOperational'', ''<settings><title>OPPORTUNITY PIPELINE</title><accountManagerKey></accountManagerKey><entityValues>0</entityValues><entityText></entityText><ProjectTypeKey>-1</ProjectTypeKey><LeadStatusKey>-1</LeadStatusKey><AmountType>0</AmountType><GroupBy>1</GroupBy><ShowAs>0</ShowAs></settings>'', 0, 1, 250, 540, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (30, NULL, ''Opportunity Forecast'', ''View the opportunity forecast'', ''main'', 0, ''OpportunityForecast.swf'', ''widgetOperational'', ''<settings><title>OPPORTUNITY FORECAST</title><entityValues></entityValues><entityText></entityText><GroupedBy>1</GroupedBy></settings>'', 0, 1, 250, 540, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (31, NULL, ''Opportunity Outcome'', ''View the opportunity pipeline'', ''main'', 0, ''OpportunityOutcome.swf'', ''widgetOperational'', ''<settings><title>OPPORTUNITY OUTCOME</title><dateRange>1</dateRange></settings>'', 0, 1, 245, 445, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (32, NULL, ''Opportunity Closed By Person'', ''View the opportunity pipeline'', ''main'', 0, ''OpportunityClosedByPerson.swf'', ''widgetOperational'', ''<settings><title>OPPORTUNITY CLOSED BY PERSON</title><dateRange>1</dateRange></settings>'', 0, 1, 245, 445, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (33, NULL, ''Weather'', ''Weather'', ''main'', 0, ''OtherWeather.swf'', ''widgetOther'', ''<settings><title></title><city/><unittype>0</unittype><citycode/><country/><state/><location/><zipcode>000000</zipcode></settings>'', 1, 1, 302, 280, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (34, NULL, ''Company Calendar'', ''View all staff members'''' calendars that you have access to.'', ''main'', 0, ''OperationalCompanyCalendar.swf'', ''widgetOperational'', ''<settings><title>COMPANY CALENDAR</title><IncludePersonal>1</IncludePersonal><IncludePublic>0</IncludePublic><IncludeActivities>0</IncludeActivities><IncludeTasks>0</IncludeTasks><GroupBy>0</GroupBy></settings>'', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (35, NULL, ''Revenue By Account Manager'', ''Displays the amount of revenue by account manager'', ''main'', 0, ''MetricsRevenueByAccountManager.swf'', ''widgetMetric'', ''<settings><title>REVENUE BY ACCOUNT MANAGER</title><dateRange>0</dateRange></settings>'', 0, 1, 300, 300, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (36, NULL, ''Revenue Trend'', ''Displays the cumulative revenue trend for a twelve month period'', ''main'', 0, ''MetricsRevenueTrend.swf'', ''widgetMetric'', ''<settings><title>REVENUE TREND</title><month>1</month><year>2009</year><firstTarget>0</firstTarget><secondTarget>0</secondTarget><thirdTarget>0</thirdTarget><fourthTarget>0</fourthTarget><entityValues></entityValues><entityText></entityText></settings>'', 0, 1, 285, 345, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (37, NULL, ''Activity Counts'', ''View a summary of the activities'', ''main'', 0, ''ActivityCounts.swf'', ''widgetMetric'', ''<settings><title>ACTIVITY COUNTS</title><activityTypeKeys></activityTypeKeys><assignedUserKeys></assignedUserKeys></settings>'', 1, 1, 300, 345, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (99, NULL, ''Sticky Note'', ''Allows you to add a sticky note to your desktop'', ''main'', 0, ''OperationalStickyNote.swf'', ''widgetOperational'', ''<settings><title>STICKY NOTE</title><noteText></noteText></settings>'', 0, 1, 500, 500, 1, GETDATE())
INSERT tWidget(WidgetKey, CompanyKey, DisplayName, Description, WidgetType, WidgetGroup, SourceFile, Icon, Settings, UserEdit, HasSettings, Height, Width, CanResize, LastModified) Values (10000, 75557, ''ww'', '''', ''main'', 0, ''OtherSWFLoader.swf'', ''widgetOther'', NULL, 0, 0, 100, 300, 1, GETDATE())





if @SeedOnly = 1   -- ***********************************************************************************************************
	return


Update tUser Set UserCompanyName = tCompany.CompanyName, OwnerKey = tCompany.ContactOwnerKey
from tCompany Where tUser.CompanyKey = tCompany.CompanyKey


Update tAddress Set CompanyKey = 0 Where Entity = ''tUser''


--Convert Calendar Events
exec spConvertDB10500Calendar


--Convert Contact Databases
exec spConvertDB10500ContactDatabase


Update tProject
Set LeadKey = tLead.LeadKey
from tLead
Where tProject.ProjectKey = tLead.ProjectKey



/*
This converts the tStringCompany field currently used for Activity Type
to a seperate table tActivityType.  Once the table is populated for each 
company, it will then update all tActivity rows with the proper 
tActivityType.ActivityTypeKey. 
*/

declare @Values varchar(4000)
declare @CurrSearchIdx int 
declare @DelimIdx int
declare @ValuesLength int
declare @Value varchar(100)
declare @CompanyKey int

select @CompanyKey = -1

while 1=1
	begin 
		select @CompanyKey = min(CompanyKey) 
		from tStringCompany (nolock)
		where CompanyKey > @CompanyKey
		and StringID = ''CMActityType''
		and StringDropDown is not null
	
		if @CompanyKey is null
			break

		select @Values = ltrim(rtrim(StringDropDown)) from tStringCompany
		where StringID = ''CMActityType''
		and CompanyKey = @CompanyKey

		select @ValuesLength = len(@Values)
		--print ''Total Length = '' + cast(@ValuesLength as varchar(10))
		 
		select @CurrSearchIdx = 1

		while 1=1
			begin
				select @DelimIdx = charindex(''|'', @Values, @CurrSearchIdx)
				if @DelimIdx > 0
					begin
						select @Value = substring(@Values, @CurrSearchIdx, @DelimIdx - @CurrSearchIdx)
						select @CurrSearchIdx = @DelimIdx + 1
						--print @Value
						insert tActivityType (TypeName, CompanyKey, Active)
						values (@Value, @CompanyKey, 1)
					end
				else
					begin
						select @Value = substring(@Values, @CurrSearchIdx, @ValuesLength - @CurrSearchIdx + 1)
						--print @Value
						insert tActivityType (TypeName, CompanyKey, Active)
						values (@Value, @CompanyKey, 1)
						break
					end
			end
	end



update tActivity
set ActivityTypeKey = at.ActivityTypeKey
from tActivityType at (nolock)
where tActivity.CompanyKey = at.CompanyKey 
and tActivity.Type = at.TypeName


update tActivityType
set LastModified = getdate()



--#### begin default all Custom Field Single Checkboxes to value ''NO'' ####
create table #CFDefCB (CustomFieldKey int not null)

insert #CFDefCB (CustomFieldKey)
select distinct(ofs.ObjectFieldSetKey)
from tObjectFieldSet ofs (nolock) inner join tFieldSet fs (nolock) on ofs.FieldSetKey = fs.FieldSetKey
inner join tFieldSetField fsf (nolock) on fs.FieldSetKey = fsf.FieldSetKey
inner join tFieldDef fd (nolock) on fsf.FieldDefKey = fd.FieldDefKey
where isnull(fs.Active, 0) = 1
and fd.DisplayType = 9


declare @CFKey int
select @CFKey = -1
while 1=1
	begin
		select @CFKey = min(CustomFieldKey)
		from #CFDefCB
		where CustomFieldKey > @CFKey
		
		if @CFKey is null
			break
			
		exec spCF_tFieldValueSetDefaults @CFKey
	end
--#### end default all Custom Field Single Checkboxes to value ''NO''	####


INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931700 From tRightAssigned Where RightKey = 10500  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931700)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931704 From tRightAssigned Where RightKey = 10500  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931704)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931703 From tRightAssigned Where RightKey = 10500  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931703)


INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931600 From tRightAssigned Where RightKey = 930000  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931600)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931603 From tRightAssigned Where RightKey = 930000  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931603)

INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931604 From tRightAssigned Where RightKey = 930500  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931604)

INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931101 From tRightAssigned Where RightKey = 930100  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931101)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931501 From tRightAssigned Where RightKey = 930100  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931501)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931502 From tRightAssigned Where RightKey = 930100  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931502)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931102 From tRightAssigned Where RightKey = 930100  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931102)


INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931100 From tRightAssigned Where RightKey = 930200  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931100)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931103 From tRightAssigned Where RightKey = 930200  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931103)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931104 From tRightAssigned Where RightKey = 930200  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931104)



INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931500 From tRightAssigned Where RightKey = 930400  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931500)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931503 From tRightAssigned Where RightKey = 930400  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931503)


INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931601 From tRightAssigned Where RightKey = 930600  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931601)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931701 From tRightAssigned Where RightKey = 930600  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931701)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931702 From tRightAssigned Where RightKey = 930600  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931702)
INSERT INTO [tRightAssigned] ([EntityType],[EntityKey],[RightKey]) Select ''Security Group'', EntityKey, 931602 From tRightAssigned Where RightKey = 930600  and EntityKey > 0 and EntityKey not in (Select EntityKey from tRightAssigned Where RightKey = 931602)



























'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateIssue]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateIssue]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER Procedure [dbo].[sptActivityUpdateIssue]
	(
		@CompanyKey INT,
		@ActivityKey INT,
		@UserKey INT,
		@ReviewDeliverableKey INT,
		@Subject nvarchar(4000),
		@Notes nvarchar(max),
		@ActivityTypeKey INT,
		@ActivityStatusKey INT,
		@AssignedUserKey INT,
		@ProjectKey INT,
		@Completed TINYINT
	)

  AS
	/*  
	|| When      Who Rel      What  
	|| 05/15/15  RLB 10.5.9.2 Created to reply to deliverable issues
	|| 05/26/20  CRG 20.0.7.0 (516752) Converted Notes to nvarchar
	|| 06/23/20  RLS 20.0.7.0 (518686) Converted Subject to nvarchar
	|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time - this proc no longer being used 
	*/  

	UPDATE tActivity
			SET
				ReviewDeliverableKey = @ReviewDeliverableKey,
				Subject = @Subject,
				Notes = @Notes,
				ActivityTypeKey = @ActivityTypeKey,
				ActivityStatusKey = @ActivityStatusKey,
				AssignedUserKey = @AssignedUserKey,
				ProjectKey = @ProjectKey,
				DateUpdated = GETUTCDATE(),
				UpdatedByKey = @UserKey,
				Completed = @Completed
	WHERE ActivityKey = @ActivityKey



	Return @ActivityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserGet]'
GO
IF OBJECT_ID(N'[dbo].[sptUserGet]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptUserGet]
  @UserKey int = 0,
  @UserID nvarchar(100) = NULL
AS --Encrypt

/*
  || When     Who Rel   What
  || 10/04/06 WES 8.35  Added ISNULL(u.AddressKey, c.DefaultAddressKey)
  || 7/17/07  CRG 8.5   (9833) Added UserName.
  || 06/23/08 GHL 10.500 Changed inner join with tCompany c to left outer join for contacts
  ||                    since u.CompanyKey is nullable now
  || 08/01/08 GWG 10.5  Added hooks to the folder
  || 06/18/09 QMD 10.5  Added join to tUserPreference to get Email info
  || 08/25/09 MFT 10.508 Added get by UserID logic
  || 02/09/11 RLB 10.542 (100772)Added vendor sales tax defaults
  || 04/14/11 GWG 10.543 Added default service
  || 08/31/11 GHL 10.547 Added ExpenseApprover name
  || 09/04/12 RLB 10.560 Added ServiceCode
  || 09/19/12 GHL 10.560 (154716) Added credit card approver name 
  || 12/15/13 GWG 10.575 Added Timezone to default over to the company
  || 04/23/14 QMD 10.579 Added UserToken
  || 05/22/14 CRG 10.580 Added DefaultCalendarName
  || 12/03/14 QMD 10.586 Changed UserToken to PublicUserToken
  || 02/10/15 GHL 10.589 Added billing title info for Abelson Taylor
  || 09/15/15 GWG 10.596 Added GL Company
  || 06/06/16 CRG 10.604 Added join to tCompany on OwnerCompanyKey for the TimeZone 
  ||                     (if a client user doesn''t have a TimeZone, and their Company doesn''t have a TimeZone, use the Owner Company''s TimeZone)
  || 12/09/16 GAR 10.611 Added security level for use in SecurityGroup lookup
  || 04/12/17 RLB 10.615 since files will blow an error if there is no timezone. if we do not find one i default EST
  || 04/17/17 GAR 10.615 (341152) Add office key, office ID, and office name for defaulting in new projects
  || 04/25/17 GWG 10.615 Added UserTimeZoneIndex to properly default through the levels of timezone.
  || 06/14/17 GAR 10.617 (349653) Added reminder type and backup approver for user settings.
  || 01/22/18 GWG 18.2.0 Added change desktop
  || 03/22/18 GHL 18.4.0 Removed OfficeKey because it is already part of tUser
  ||                     Added ClassName to set on lookups in Plat 
  || 04/05/18 GWG 18.5.0 Added Culture waterfall. User > Office > Preferences  (fixed to be userculture and office culture)
  || 04/30/18 GAR 18.5.0 (398155) Grab security group name for logging.
  || 05/03/18 GHL 18.5.0 (386867) Added department name to default it on expense receipts
  || 06/25/18 GHL 18.7.0 (407650) Added TimeApproverBackupApprover, this is the BackupApprover on the time approver user
  ||                     not the BackupApprover on the user
  || 7/26/19  RLS 19.0.8 (471116) Added cascading ActionID and ActionName
  || 12/06/19 RLB 20.0.1 (491317) changed action name to max because planning project is not getting displayed
  || 02/27/20 CRG 20.0.3.0 (503419) Added NULLIF to TimeZone column to handle if a user''s time zone is blanked out in the UI and a 0 is saved.
  || 05/15/20 KMC 20.0.7.0 Added GoogleCalendarAuthToken from tUserPreference for changes to Google OAuth
  || 08/01/20 MAS 20.0.8.0 Added APIAccessToken 
  || 08/25/21 WDF 21.0.9.0 (569419) Added UserFullName
  || 09/13/22 AMP 22.10.16 (612089) Removed u.* to eliminate the Encrypted Password from being returned
  || 04/07/23 CRG 23.05.14 (630097) Added TwoFactorAuth and TwoFactorSendPref 
  || 02/26/24 MCM 24.03.17 (664040) Made userID parameter a nvarchar
  || 12/18/20 RLB 25.01.19 (688771) added new fields SubscribeDiaryPA and SubscribeToDoPA
  || 2/1/25   GWG 25.02.16  Added in Theme calls
  || 05/20/25 CRG 25.06.15 (699112) Added SuspendAdmin
  || 10/10/25 KMC 25.11.16 (698233) Removed tUserPreference EmailMailBox, EmailUserID, and EmailPassword
  || 03/27/26 RLB 26.04.19 (720867) Added PrintCulture for printing
  || 06/12/26 GAR 26.07.19 (730742) Adding a user level permission, EnableAPIMCPUse, to allow a user to use the API or MCP
*/

 IF @UserKey = 0
 	BEGIN
		SELECT @UserKey = UserKey
		FROM tUser (nolock)
		WHERE UserID = @UserID
 	END

	SELECT
	 u.UserKey
	,u.CompanyKey
    ,u.FirstName
    ,u.MiddleName
    ,u.LastName
    ,u.Salutation
    ,u.DepartmentKey
    ,u.Phone1
    ,u.Phone2
    ,u.Cell
    ,u.Fax
    ,u.Pager
    ,u.Title
    ,u.Email
    ,u.SecurityGroupKey
    ,u.Administrator
    ,u.UserID    
    ,u.SystemID
    ,u.OwnerCompanyKey
    ,u.LastLogin
    ,u.ContactMethod
    ,u.Active
    ,u.AutoAssign
    ,u.NoUnassign
    ,u.HourlyRate
    ,u.HourlyCost
    ,u.TimeApprover
    ,u.ExpenseApprover
    ,u.POLimit
    ,u.BCLimit
    ,u.IOLimit
    ,u.VendorKey
    ,u.ClassKey
    ,u.CustomFieldKey
    ,u.InOutStatus
    ,u.InOutNotes
    ,u.UserDefined1
    ,u.UserDefined2
    ,u.UserDefined3
    ,u.UserDefined4
    ,u.UserDefined5
    ,u.UserDefined6
    ,u.UserDefined7
    ,u.UserDefined8
    ,u.UserDefined9
    ,u.UserDefined10
    ,u.OfficeKey
    ,u.RateLevel
    ,u.TrafficNotification
    ,u.ClientVendorLogin
    ,u.DateAdded
    ,u.DateUpdated
    ,u.TimeZoneIndex
    ,u.NumberOfAttempts
    ,u.Locked
    ,u.LastPwdChange
    ,u.Supervisor
    ,u.DefaultReminderTime
    ,u.LinkID
    ,u.AddressKey
    ,u.DefaultServiceKey
    ,u.SystemMessage
    ,u.GLCompanyKey
    ,u.MonthlyCost
    ,u.LastModified
    ,u.OwnerKey
    ,u.CMFolderKey
    ,u.DoNotCall
    ,u.DoNotEmail
    ,u.DoNotMail
    ,u.DoNotFax
    ,u.AddedByKey
    ,u.UpdatedByKey
    ,u.HomeAddressKey
    ,u.OtherAddressKey
    ,u.ClientDivisionKey
    ,u.ClientProductKey
    ,u.Department
    ,u.UserRole
    ,u.ReportsToKey
    ,u.Assistant
    ,u.AssistantPhone
    ,u.AssistantEmail
    ,u.Birthday
    ,u.SpouseName
    ,u.Children
    ,u.Anniversary
    ,u.Hobbies
    ,u.Comments
    ,u.UserCompanyName
    ,u.LastActivityKey
    ,u.NextActivityKey
    ,u.DefaultCMFolderKey
    ,u.WWPCurrentLevel
    ,u.DefaultCalendarColor
    ,u.DateConverted
    ,u.DefaultContactCMFolderKey
    ,u.SyncMLDirection
    ,u.CalendarReminder
    ,u.DateLeadCreated
    ,u.QuickMeeting
    ,u.LinkedCompanyAddressKey
    ,u.MarketingMessage
    ,u.SubscribeDiary
    ,u.SubscribeToDo
	,u.SubscribeDiaryPA
    ,u.SubscribeToDoPA
    ,u.DeliverableReviewer
    ,u.DeliverableNotify
    ,u.RightLevel
    ,u.Contractor
    ,u.RequireUserTimeDetails
    ,u.CreditCardApprover
    ,u.BackupApprover
    ,u.DateHired
    ,u.ExternalMarketingKey
    ,u.LanguageID
    ,u.ForcePwdChangeOnNextLogin
    ,u.Uid
    ,u.OriginalVCard
    ,u.GoogleAuthToken
    ,u.GoogleAuthTokenExpires
    ,u.GoogleRefreshToken
    ,u.GoogleRefreshTokenExpires
    ,u.TitleKey
    ,u.InvoiceEmails
    ,u.TwitterID
    ,u.LinkedInURL
    ,u.Signature
    ,u.DefaultActionID
    ,u.SignatureFont
    ,u.LoggedOut
    ,u.RequestToken
    ,u.UserDesktopImage
    ,u.UserCulture
    ,u.SSOAutoUpdateOff
    ,u.SupervisorKey
    ,u.SubscribeFileUpload
    ,u.SlackMemberID
    ,u.SSOAuthenticationOff
    ,u.VendorCost
    ,u.OvertimeCost
    ,u.OvertimeVendorCost
    ,u.UserBackgroundColor
    ,u.UserBarColor
    ,u.UserMenuColor
    ,u.UserAccentColor
    ,u.UserBodyColor
    ,u.UserDarkMode,
	ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, '''') AS UserName,
	CASE
		WHEN u.FirstName IS NULL AND u.LastName IS NULL THEN NULL
		ELSE
		CASE 
			WHEN u.MiddleName IS NULL THEN LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,''''))) 
			ELSE LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + SUBSTRING(u.MiddleName, 1, 1) + '' '' + ISNULL(u.LastName,''''))) 
		END 
	END AS UserFullName,			
	v.VendorID,
	v.CompanyName as VendorName,
	cl.ClassID,
	cl.ClassName,
	c.CustomerID as ClientID,
	c.CompanyName,
	c.CustomLogo,
	v.VendorSalesTaxKey,
	v.VendorSalesTax2Key,
	st.SalesTaxID,
	st.SalesTaxName,
	st.TaxRate,
	st.PiggyBackTax,
	st2.SalesTaxID as SaleTax2ID,
	st2.SalesTaxName as SaleTax2Name,
	st2.TaxRate as TaxRate2,
	st2.PiggyBackTax as PiggyBackTax2,
	ad.AddressName,
	ad.Address1,
	ad.Address2,
	ad.Address3,
	ad.City,
	ad.State,
	ad.Country,
	ad.PostalCode,
	c.Phone,
	f.UserKey as FolderUserKey,
	s.ServiceKey,
	s.Description as ServiceDescription,
	s.ServiceCode,
	ISNULL(uea.FirstName, '''') + '' '' + ISNULL(uea.LastName, '''') AS ExpenseApproverName,
	ISNULL(ucca.FirstName, '''') + '' '' + ISNULL(ucca.LastName, '''') AS CreditCardApproverName,
	ISNULL(uba.FirstName, '''') + '' '' + ISNULL(uba.LastName, '''') AS BackupApproverName,
	ISNULL(ISNULL(ISNULL(NULLIF(u.TimeZoneIndex, 0), c.TimeZoneIndex), oc.TimeZoneIndex), 35) as TimeZone,
	ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture)) as Culture,
	ISNULL(o.OfficeCulture, p.Culture) as PrintCulture,
	up.PublicUserToken,
	p.APIAccessToken,
	cal.FolderName AS DefaultCalendarName,
	t.TitleID,
	t.TitleName,
	ISNULL(u.DefaultActionID, ISNULL(sg.DefaultActionID,''today.creative'')) as ActionID,
	ISNULL((Select Max(Label) from tAppMenu (nolock) Where Entity = ''System'' and ActionID = ISNULL(u.DefaultActionID, sg.DefaultActionID)), ''Today - Creative'') as ActionName,
	gl.GLCompanyID,
	gl.GLCompanyName,
	sg.SecurityLevel,
	sg.ChangeDesktop,
	o.OfficeID,
	o.OfficeName,
	CASE 
		WHEN ISNULL(u.CalendarReminder,0) = 0 THEN ''Both Email and Popup'' 
		WHEN ISNULL(u.CalendarReminder,0) = 1 THEN ''Email Only'' 
		WHEN ISNULL(u.CalendarReminder,0) = 2 THEN ''Popup Only'' 
		WHEN ISNULL(u.CalendarReminder,0) = 3 THEN ''None'' 
		ELSE ''Both Email and Popup''
	END AS ReminderType,
	sg.GroupName,
	d.DepartmentName,
	uta.BackupApprover as TimeApproverBackupApprover,
	ISNULL(up.GoogleCalendarAuthToken, u.GoogleAuthToken) AS GoogleCalendarAuthToken,
	p.TwoFactorAuth,
	u.TwoFactorSendPref,
	ISNULL(u.Theme, 0) as Theme,
	Case ISNULL(u.Theme, 0) When 1 then ''Next Era'' when 2 then ''Next Era Dark'' when 3 then ''Moody Blues'' when 4 then ''Workamajig Classic'' end as ThemeName,
	u.SuspendAdmin,
	u.EnableAPIMCPUse
	FROM	tUser u (nolock)
			left outer join tCompany c (NOLOCK) on u.CompanyKey = c.CompanyKey
			left outer join tCompany oc (nolock) ON u.OwnerCompanyKey = oc.CompanyKey
			left outer join tCompany v (NOLOCK) on u.VendorKey = v.CompanyKey
			left outer join tClass cl (NOLOCK) on u.ClassKey = cl.ClassKey
			left outer join tAddress ad (nolock) on ISNULL(u.AddressKey, c.DefaultAddressKey) = ad.AddressKey
			left outer join tCMFolder f (nolock) on u.CMFolderKey = f.CMFolderKey
			left outer join tUserPreference up (nolock) on u.UserKey = up.UserKey
			left outer join tSalesTax st (nolock) on v.VendorSalesTaxKey = st.SalesTaxKey
			Left outer join tSalesTax st2 (nolock) on v.VendorSalesTax2Key = st2.SalesTaxKey
			left outer join tService s (nolock) on u.DefaultServiceKey = s.ServiceKey
			left outer join tUser uea (nolock) on u.ExpenseApprover = uea.UserKey
			left outer join tUser ucca (nolock) on u.CreditCardApprover = ucca.UserKey
			left outer join tUser uba (nolock) on u.BackupApprover = uba.UserKey
			left outer join tUser uta (nolock) on u.TimeApprover = uta.UserKey  -- this is to get to the backup of the time approver
			left outer join tPreference p (nolock) on ISNULL(u.OwnerCompanyKey, u.CompanyKey) = p.CompanyKey
			left outer join tCMFolder cal (nolock) ON u.DefaultCMFolderKey = cal.CMFolderKey
			left outer join tTitle t (nolock) on u.TitleKey = t.TitleKey
			left outer join tGLCompany gl (nolock) on u.GLCompanyKey = gl.GLCompanyKey
			left outer join tSecurityGroup sg (nolock) on u.SecurityGroupKey = sg.SecurityGroupKey
			left outer join tOffice o (nolock) on u.OfficeKey = o.OfficeKey
			LEFT OUTER JOIN tDepartment d (NOLOCK) ON u.DepartmentKey = d.DepartmentKey
	WHERE	u.UserKey = @UserKey

 RETURN 1



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetCorporatePL]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetCorporatePL]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER Procedure [dbo].[spApiAIGetCorporatePL]
(
    @CompanyKey            int,
    @UserKey               int,
    @StartDate             datetime,                       -- required: period start
    @EndDate               datetime,                       -- required: period end
    @PriorStartDate        datetime    = null,             -- optional: prior-period start (drives comparison)
    @PriorEndDate          datetime    = null,             -- optional: prior-period end
    @GLCompanyIDs          varchar(max) = null,            -- comma/pipe list of tGLCompany.GLCompanyID
    @OfficeIDs             varchar(max) = null,            -- comma/pipe list of tOffice.OfficeID
    @ClassIDs              varchar(max) = null,            -- comma/pipe list of tClass.ClassID
    @DepartmentNames       varchar(max) = null,            -- comma/pipe list of tDepartment.DepartmentName  (no ID column)
    @AccrualBasis          bit         = 1,                -- 1 = accrual (default), 0 = cash basis
    @CashBasisLegacy       bit         = 0,                -- cash-basis variant (engine-specific)
    @RunInGLCHomeCurrency  bit         = 0                 -- 1 = report in GLCompany home currency (single-company filter only)
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — API-friendly wrapper around spRptCorpPLAccrual / spRptCorpPLCash.
||                          Returns 3 result sets: warnings, meta, lines.
||                          All filters accept string IDs (or names for departments); resolved internally.
||                          Computes synthetic subtotal rows: Gross Profit, Net Operating Income, Net Income.
|| 07/07/26  MCM 26.07.x    (732349) Updated case for the raw.Minor gorup for Expenses and OtherIncome 
*/

set nocount on

    declare @SecurityGroupKey    int
    declare @IsAdministrator     bit
    declare @RestrictToGLCompany tinyint
    declare @MultiCurrency       tinyint
    declare @HomeCurrencyID      varchar(10)
    declare @EffectiveCurrencyID varchar(10)
    declare @CanRunPL            bit
    declare @ErrorCount          int
    declare @ResolvedGLCount     int
    declare @SingleGLCompanyKey  int
    declare @GLCHomeCurrencyID   varchar(10)

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Validate required inputs
    -- ------------------------------------------------------------------
    if @StartDate is null or @EndDate is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''startDate and endDate are required.'', ''startDate'')
    end
    else if @EndDate < @StartDate
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''endDate must be on or after startDate.'', ''endDate'')
    end

    if (@PriorStartDate is null and @PriorEndDate is not null)
        or (@PriorStartDate is not null and @PriorEndDate is null)
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''priorStartDate and priorEndDate must be supplied together.'', ''priorStartDate'')
    end
    else if @PriorStartDate is not null and @PriorEndDate < @PriorStartDate
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''priorEndDate must be on or after priorStartDate.'', ''priorEndDate'')
    end

    -- ------------------------------------------------------------------
    -- 3. Load user + security context
    -- ------------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey,
           @IsAdministrator  = Administrator
    from tUser (nolock)
    where UserKey    = @UserKey
      and CompanyKey = @CompanyKey

    if @SecurityGroupKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from #errors
        order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 4. Right check: acct_gl_pl_ytd (admin bypass)
    -- ------------------------------------------------------------------
    set @CanRunPL = 0
    if @IsAdministrator = 1
        set @CanRunPL = 1
    else if exists (
        select 1
        from tRight r (nolock)
        inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
        where ra.EntityType = ''Security Group''
          and ra.EntityKey  = @SecurityGroupKey
          and r.RightID     = ''acct_gl_pl_ytd''
    )
        set @CanRunPL = 1

    if @CanRunPL = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to run the Corporate P&L (acct_gl_pl_ytd).'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from #errors
        order by errorType desc, fieldName

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 5. Bail on validation errors
    -- ------------------------------------------------------------------
    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName
        from #errors
        order by errorType desc, fieldName

        drop table #errors
        return -102
    end

    -- ------------------------------------------------------------------
    -- 6. Preferences
    -- ------------------------------------------------------------------
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0),
           @MultiCurrency       = ISNULL(MultiCurrency, 0),
           @HomeCurrencyID      = CurrencyID
    from tPreference (nolock)
    where CompanyKey = @CompanyKey

    set @RestrictToGLCompany = ISNULL(@RestrictToGLCompany, 0)
    set @MultiCurrency       = ISNULL(@MultiCurrency, 0)
    set @EffectiveCurrencyID = @HomeCurrencyID

    -- ------------------------------------------------------------------
    -- 7. Build the four engine temp tables. Empty = "all".
    -- ------------------------------------------------------------------
    create table #GLCompanyKeys  (GLCompanyKey  int null)
    create table #OfficeKeys     (OfficeKey     int null)
    create table #ClassKeys      (ClassKey      int null)
    create table #DepartmentKeys (DepartmentKey int null)

    -- Required by spRptBalanceSheetRevaluation (called inside spRptCorpPLAccrual
    -- when MultiCurrency = 1). Engine will populate from exchange table if empty.
    create table #revaluerate (
        CurrencyID    varchar(10)   null,
        PreviousRate  decimal(24,7) null,
        CurrentRate   decimal(24,7) null
    )

    -- GL Companies
    if @GLCompanyIDs is not null and LTRIM(RTRIM(@GLCompanyIDs)) <> ''''
    begin
        set @GLCompanyIDs = replace(@GLCompanyIDs, ''|'', '','')

        insert into #GLCompanyKeys (GLCompanyKey)
        select gc.GLCompanyKey
        from tGLCompany gc (nolock)
        inner join dbo.fSplitVals(@GLCompanyIDs, '','') s
            on UPPER(LTRIM(RTRIM(gc.GLCompanyID))) = UPPER(LTRIM(RTRIM(s.value)))
        where gc.CompanyKey = @CompanyKey

        if not exists (select 1 from #GLCompanyKeys)
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''No GL companies matched the supplied glCompanyIDs.'', ''glCompanyIDs'')
    end

    -- Offices
    if @OfficeIDs is not null and LTRIM(RTRIM(@OfficeIDs)) <> ''''
    begin
        set @OfficeIDs = replace(@OfficeIDs, ''|'', '','')

        insert into #OfficeKeys (OfficeKey)
        select o.OfficeKey
        from tOffice o (nolock)
        inner join dbo.fSplitVals(@OfficeIDs, '','') s
            on UPPER(LTRIM(RTRIM(o.OfficeID))) = UPPER(LTRIM(RTRIM(s.value)))
        where o.CompanyKey = @CompanyKey

        if not exists (select 1 from #OfficeKeys)
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''No offices matched the supplied officeIDs.'', ''officeIDs'')
    end

    -- Classes
    if @ClassIDs is not null and LTRIM(RTRIM(@ClassIDs)) <> ''''
    begin
        set @ClassIDs = replace(@ClassIDs, ''|'', '','')

        insert into #ClassKeys (ClassKey)
        select c.ClassKey
        from tClass c (nolock)
        inner join dbo.fSplitVals(@ClassIDs, '','') s
            on UPPER(LTRIM(RTRIM(c.ClassID))) = UPPER(LTRIM(RTRIM(s.value)))
        where c.CompanyKey = @CompanyKey

        if not exists (select 1 from #ClassKeys)
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''No GL classes matched the supplied classIDs.'', ''classIDs'')
    end

    -- Departments (resolved by name; tDepartment has no ID column)
    if @DepartmentNames is not null and LTRIM(RTRIM(@DepartmentNames)) <> ''''
    begin
        set @DepartmentNames = replace(@DepartmentNames, ''|'', '','')

        insert into #DepartmentKeys (DepartmentKey)
        select d.DepartmentKey
        from tDepartment d (nolock)
        inner join dbo.fSplitVals(@DepartmentNames, '','') s
            on UPPER(LTRIM(RTRIM(d.DepartmentName))) = UPPER(LTRIM(RTRIM(s.value)))
        where d.CompanyKey = @CompanyKey

        if not exists (select 1 from #DepartmentKeys)
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''No departments matched the supplied departmentNames.'', ''departmentNames'')
    end

    -- ------------------------------------------------------------------
    -- 8. Validate @RunInGLCHomeCurrency request
    --    Engine only supports it for exactly one GLCompany whose home
    --    currency differs from the main co''s home currency.
    -- ------------------------------------------------------------------
    if @RunInGLCHomeCurrency = 1
    begin
        select @ResolvedGLCount = COUNT(*),
               @SingleGLCompanyKey = MAX(GLCompanyKey)
        from #GLCompanyKeys

        if @ResolvedGLCount <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''INVALID_VALUE'',
                    ''runInGLCHomeCurrency requires exactly one glCompanyID. Falling back to main home currency.'',
                    ''runInGLCHomeCurrency'')
            set @RunInGLCHomeCurrency = 0
        end
        else
        begin
            select @GLCHomeCurrencyID = CurrencyID
            from tGLCompany (nolock)
            where GLCompanyKey = @SingleGLCompanyKey

            if @GLCHomeCurrencyID is null or @GLCHomeCurrencyID = @HomeCurrencyID
            begin
                insert into #errors (errorType, errorCode, errorMessage, fieldName)
                values (''warning'', ''INVALID_VALUE'',
                        ''The chosen GL company does not have a distinct home currency. Reporting in main home currency.'',
                        ''runInGLCHomeCurrency'')
                set @RunInGLCHomeCurrency = 0
            end
            else
                set @EffectiveCurrencyID = @GLCHomeCurrencyID
        end
    end

    -- ------------------------------------------------------------------
    -- 9. Pull current-period totals into #PLRaw
    -- ------------------------------------------------------------------
    create table #PLRaw (
        GLAccountKey      int          null,
        ParentAccountKey  int          null,
        DisplayOrder      int          null,
        DisplayLevel      int          null,
        Rollup            tinyint      null,
        EBITDAAccount     tinyint      null,
        MinorGroup        int          null,
        Amount            decimal(20,4) null
    )

    if @AccrualBasis = 1
    begin
        insert into #PLRaw (GLAccountKey, ParentAccountKey, DisplayOrder, DisplayLevel, Rollup, EBITDAAccount, MinorGroup, Amount)
        exec spRptCorpPLAccrual
             @CompanyKey           = @CompanyKey,
             @StartDate            = @StartDate,
             @EndDate              = @EndDate,
             @UserKey              = @UserKey,
             @TranCountOnly        = 0,
             @RunInGLCHomeCurrency = @RunInGLCHomeCurrency
    end
    else
    begin
        insert into #PLRaw (GLAccountKey, ParentAccountKey, DisplayOrder, DisplayLevel, Rollup, EBITDAAccount, MinorGroup, Amount)
        exec spRptCorpPLCash
             @CompanyKey      = @CompanyKey,
             @StartDate       = @StartDate,
             @EndDate         = @EndDate,
             @UserKey         = @UserKey,
             @TranCountOnly   = 0,
             @CashBasisLegacy = @CashBasisLegacy
    end

    -- ------------------------------------------------------------------
    -- 10. Optional prior-period pull (for delta display)
    -- ------------------------------------------------------------------
    create table #PLPrior (
        GLAccountKey int          null,
        Amount       decimal(20,4) null
    )

    if @PriorStartDate is not null
    begin
        declare @TmpPrior table (
            GLAccountKey      int,
            ParentAccountKey  int,
            DisplayOrder      int,
            DisplayLevel      int,
            Rollup            tinyint,
            EBITDAAccount     tinyint,
            MinorGroup        int,
            Amount            decimal(20,4)
        )

        if @AccrualBasis = 1
        begin
            insert into @TmpPrior (GLAccountKey, ParentAccountKey, DisplayOrder, DisplayLevel, Rollup, EBITDAAccount, MinorGroup, Amount)
            exec spRptCorpPLAccrual
                 @CompanyKey           = @CompanyKey,
                 @StartDate            = @PriorStartDate,
                 @EndDate              = @PriorEndDate,
                 @UserKey              = @UserKey,
                 @TranCountOnly        = 0,
                 @RunInGLCHomeCurrency = @RunInGLCHomeCurrency
        end
        else
        begin
            insert into @TmpPrior (GLAccountKey, ParentAccountKey, DisplayOrder, DisplayLevel, Rollup, EBITDAAccount, MinorGroup, Amount)
            exec spRptCorpPLCash
                 @CompanyKey      = @CompanyKey,
                 @StartDate       = @PriorStartDate,
                 @EndDate         = @PriorEndDate,
                 @UserKey         = @UserKey,
                 @TranCountOnly   = 0,
                 @CashBasisLegacy = @CashBasisLegacy
        end

        insert into #PLPrior (GLAccountKey, Amount)
        select GLAccountKey, Amount
        from @TmpPrior
    end

    -- ------------------------------------------------------------------
    -- 11. Build the decorated line set (account info + amount + prior)
    -- ------------------------------------------------------------------
    create table #Lines (
        ord                int,
        accountKey         int            null,
        accountNumber      varchar(100)   null,
        accountName        nvarchar(200)  null,
        accountType        varchar(20)    null,
        section            varchar(20)    null,
        parentAccountKey   int            null,
        level              int            null,
        displayOrder       int            null,
        isRollup           bit            null,
        isEBITDA           bit            null,
        amount             decimal(20,4)  null,
        priorPeriodAmount  decimal(20,4)  null
    )

    insert into #Lines
        (ord, accountKey, accountNumber, accountName, accountType, section,
         parentAccountKey, level, displayOrder, isRollup, isEBITDA, amount, priorPeriodAmount)
    select
        -- Order: MinorGroup × 1000 leaves room to splice subtotal rows in step 12
        (raw.MinorGroup * 1000) + raw.DisplayOrder                        as ord,
        case when raw.GLAccountKey < 0 then null else raw.GLAccountKey end as accountKey,
        gl.AccountNumber                                                  as accountNumber,
        case
            when raw.GLAccountKey = -1 then ''Bank Revaluation''
            when raw.GLAccountKey = -2 then ''Unrealized Currency Gains''
            else gl.AccountName
        end                                                               as accountName,
        case raw.MinorGroup
            when 1 then ''Income''
            when 2 then ''COGS''
            when 3 then ''Expense''
            when 4 then ''OtherIncome''
            when 5 then ''OtherExpense''
        end                                                               as accountType,
        case raw.MinorGroup
            when 1 then ''Income''
            when 2 then ''COGS''
            when 3 then ''Expense''
            when 4 then ''OtherIncome''
            when 5 then ''OtherExpense''
        end                                                               as section,
        ISNULL(raw.ParentAccountKey, 0)                                   as parentAccountKey,
        ISNULL(raw.DisplayLevel, 0)                                       as [level],
        raw.DisplayOrder                                                  as displayOrder,
        cast(ISNULL(raw.Rollup, 0)        as bit)                         as isRollup,
        cast(ISNULL(raw.EBITDAAccount, 0) as bit)                         as isEBITDA,
        ROUND(ISNULL(raw.Amount, 0), 2)                                   as amount,
        ROUND(prior.Amount, 2)                                            as priorPeriodAmount
    from #PLRaw raw
    left join tGLAccount gl (nolock) on raw.GLAccountKey = gl.GLAccountKey
                                    and gl.CompanyKey   = @CompanyKey
    left join #PLPrior  prior        on raw.GLAccountKey = prior.GLAccountKey

    -- ------------------------------------------------------------------
    -- 12. Synthetic subtotal rows: Gross Profit, Net Operating Income, Net Income
    --     Sign convention: income/COGS/expense already returned positive by
    --     the engine; signs below reflect the natural P&L roll-up.
    -- ------------------------------------------------------------------
    declare @Income       decimal(20,4),
            @COGS         decimal(20,4),
            @OtherIncome  decimal(20,4),
            @Expense      decimal(20,4),
            @OtherExpense decimal(20,4),
            @PriorIncome       decimal(20,4),
            @PriorCOGS         decimal(20,4),
            @PriorOtherIncome  decimal(20,4),
            @PriorExpense      decimal(20,4),
            @PriorOtherExpense decimal(20,4)

    -- Section totals = sum of LEAF rows only (parent rows are already rolled up
    -- and would double-count if added).
    select
        @Income       = SUM(case when section = ''Income''       and isRollup = 0 then amount else 0 end),
        @COGS         = SUM(case when section = ''COGS''         and isRollup = 0 then amount else 0 end),
        @OtherIncome  = SUM(case when section = ''OtherIncome''  and isRollup = 0 then amount else 0 end),
        @Expense      = SUM(case when section = ''Expense''      and isRollup = 0 then amount else 0 end),
        @OtherExpense = SUM(case when section = ''OtherExpense'' and isRollup = 0 then amount else 0 end),
        @PriorIncome       = SUM(case when section = ''Income''       and isRollup = 0 then ISNULL(priorPeriodAmount, 0) else 0 end),
        @PriorCOGS         = SUM(case when section = ''COGS''         and isRollup = 0 then ISNULL(priorPeriodAmount, 0) else 0 end),
        @PriorOtherIncome  = SUM(case when section = ''OtherIncome''  and isRollup = 0 then ISNULL(priorPeriodAmount, 0) else 0 end),
        @PriorExpense      = SUM(case when section = ''Expense''      and isRollup = 0 then ISNULL(priorPeriodAmount, 0) else 0 end),
        @PriorOtherExpense = SUM(case when section = ''OtherExpense'' and isRollup = 0 then ISNULL(priorPeriodAmount, 0) else 0 end)
    from #Lines

    -- Insert subtotals between sections.  ord values are chosen to fall between
    -- MinorGroup boundaries so the final ORDER BY interleaves them correctly.
    insert into #Lines
        (ord, accountKey, accountNumber, accountName, accountType, section,
         parentAccountKey, level, displayOrder, isRollup, isEBITDA, amount, priorPeriodAmount)
    values
        (2500, null, null, ''Gross Profit'',          ''Subtotal'', ''GrossProfit'',  0, 0, 0, 1, 0,
            ISNULL(@Income, 0)      - ISNULL(@COGS, 0),
            case when @PriorStartDate is null then null else ISNULL(@PriorIncome, 0) - ISNULL(@PriorCOGS, 0) end),
        (4500, null, null, ''Net Operating Income'', ''Subtotal'', ''NetOperating'', 0, 0, 0, 1, 0,
            ISNULL(@Income, 0) + ISNULL(@OtherIncome, 0) - ISNULL(@COGS, 0) - ISNULL(@Expense, 0),
            case when @PriorStartDate is null then null else
                 ISNULL(@PriorIncome, 0) + ISNULL(@PriorOtherIncome, 0) - ISNULL(@PriorCOGS, 0) - ISNULL(@PriorExpense, 0) end),
        (5500, null, null, ''Net Income'',            ''Subtotal'', ''NetIncome'',    0, 0, 0, 1, 0,
            ISNULL(@Income, 0) + ISNULL(@OtherIncome, 0) - ISNULL(@COGS, 0) - ISNULL(@Expense, 0) - ISNULL(@OtherExpense, 0),
            case when @PriorStartDate is null then null else
                 ISNULL(@PriorIncome, 0) + ISNULL(@PriorOtherIncome, 0) - ISNULL(@PriorCOGS, 0) - ISNULL(@PriorExpense, 0) - ISNULL(@PriorOtherExpense, 0) end)

    -- ------------------------------------------------------------------
    -- 13. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 14. Result set 2: meta (single row)
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), getutcdate(), 126) + ''Z''                     as asOf,
        @CompanyKey                                                       as companyKey,
        ISNULL(@EffectiveCurrencyID, '''')                                  as currency,
        convert(varchar(10), @StartDate,      23)                         as windowStart,
        convert(varchar(10), @EndDate,        23)                         as windowEnd,
        convert(varchar(10), @PriorStartDate, 23)                         as comparisonWindowStart,
        convert(varchar(10), @PriorEndDate,   23)                         as comparisonWindowEnd,
        case when @AccrualBasis = 1 then ''accrual'' else ''cash'' end        as basis,
        cast(@RunInGLCHomeCurrency as bit)                                as isGLCHomeCurrency,
        (select COUNT(*) from #Lines)                                     as [rowCount],
        cast(0 as bit)                                                    as truncated,
        cast(null as int)                                                 as nextCursor

    -- ------------------------------------------------------------------
    -- 15. Result set 3: lines (full GL tree + subtotals, ordered)
    -- ------------------------------------------------------------------
    select
        accountKey         as accountKey,
        accountNumber      as accountNumber,
        accountName        as accountName,
        accountType        as accountType,
        section            as section,
        parentAccountKey   as parentAccountKey,
        level              as [level],
        displayOrder       as displayOrder,
        isRollup           as isRollup,
        isEBITDA           as isEBITDA,
        amount             as amount,
        priorPeriodAmount  as priorPeriodAmount
    from #Lines
    order by ord

    -- ------------------------------------------------------------------
    drop table #Lines
    drop table #PLPrior
    drop table #PLRaw
    drop table #DepartmentKeys
    drop table #ClassKeys
    drop table #OfficeKeys
    drop table #GLCompanyKeys
    drop table #revaluerate
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityAutoRoll]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityAutoRoll]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityAutoRoll]
	@RollDate smalldatetime
AS

/*
|| When      Who Rel      What
|| 5/29/09   CRG 10.5.0.0 Created for the task manager to auto roll activities.
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time - this is for the nightly process
*/

	UPDATE	tActivity
	SET		ActivityDate = @RollDate
	FROM	tActivity a
	INNER JOIN tActivityType type ON a.ActivityTypeKey = type.ActivityTypeKey
	WHERE	type.AutoRollDate = 1
	AND		ISNULL(a.Completed, 0) = 0
	AND		a.ActivityDate < @RollDate'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserGetFavoriteContactWithTwitterIDs]'
GO
IF OBJECT_ID(N'[dbo].[sptUserGetFavoriteContactWithTwitterIDs]', 'P') IS NOT NULL
EXEC sp_executesql N'


ALTER PROCEDURE [dbo].[sptUserGetFavoriteContactWithTwitterIDs]
	@CompanyKey int,
	@AccountManagerKey int,
	@NameFilter varchar(50) = null
	
	AS --Encrypt

	/*
	  || When     Who Rel   What
	  || 01/16/15 RLB 10588 Added to sales dashboard to pull an account manager favorite contacts with twitter id
	  || 03/11/15 RLB 10590 Fixed blank twitter id''s getting pulled into twitter feed
	  || 06/30/23 RLB 23.07.16 (631684) adding company wide option when @AccountManagerKey < 0
	  || 02/13/25 GAR 25.XX.XX (688217) Added a name filter for the new dashboards
	*/
 
 if @AccountManagerKey > 0
	 SELECT u.*, ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, '''') as FormattedName 
	 FROM tUser u (NOLOCK)
	 INNER JOIN tAppFavorite af (NOLOCK) on u.UserKey = af.ActionKey and af.ActionID = ''cm.contacts''
	 WHERE af.CompanyKey = @CompanyKey
	 AND af.UserKey = @AccountManagerKey
	 AND ISNULL(u.TwitterID, '''') <> ''''
	 AND (ISNULL(@NameFilter, '''') = '''' OR (u.FirstName LIKE ''%'' + @NameFilter + ''%'' OR u.LastName LIKE ''%'' + @NameFilter + ''%''))
	 ORDER BY u.LastName
else
	SELECT u.*, ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, '''') as FormattedName 
	 FROM tUser u (NOLOCK)
	 INNER JOIN tAppFavorite af (NOLOCK) on u.UserKey = af.ActionKey and af.ActionID = ''cm.contacts''
	 WHERE af.CompanyKey = @CompanyKey
	 AND af.UserKey in (SELECT UserKey from tUser (nolock) where CompanyKey = @CompanyKey and ISNULL(SalesPerson, 0) = 1)
	 AND ISNULL(u.TwitterID, '''') <> ''''
	 AND (ISNULL(@NameFilter, '''') = '''' OR (u.FirstName LIKE ''%'' + @NameFilter + ''%'' OR u.LastName LIKE ''%'' + @NameFilter + ''%''))
	 ORDER BY u.LastName
	 
	 RETURN 1





'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserGetInfo]'
GO
IF OBJECT_ID(N'[dbo].[sptUserGetInfo]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER Procedure [dbo].[sptUserGetInfo]
 (
  @UserKey int
 )
AS --Encrypt

  /*
  || 11/27/07 GHL 8.5		removed *= join for SQL 2005
  || 12/21/07 GHL 8.5		Added comments after logo because Task Manager looks for go+CR
  || 10/1/08  GWG 10.5		Added Client ID and removed the inner join to tCompany
  || 11/08/11 GHL 10.5.5.0	(114741) Added Security Level
  || 11/07/13 RLB 10.5.7.4	(195465) Added CompanyTimeZoneIndex
  || 07/31/14 QMD 10.5.8.2	changed the default action to today.creative
  || 10/20/14 GWG 10.5.8.5	Added company language ID
  || 10/30/14 MAS 10.5.8.5	Removed stand alone p.LanguageID column, Using ISNULL(ISNULL(u.LanguageID, p.LanguageID), ''EN'') as LanguageID
  || 07/28/15 GWG 10.5.9.4  Added Customizations to the call
  || 12/15/15 GWG 10.5.9.9 Added inactivetimeout to the final get
  || 5/15/18  GWG 18.6.0    Added cascading culture
  || 7/26/19  RLS 19.0.8    (471116) Added cascading ActionID
  || 10/25/19 GWG 19.1.1	Added calls for lab strings so they dont have to be loaded on pages where needed like customizations
  || 2/1/25   GWG 25.02.16  Added in Theme calls
  || 03/25/26 CRG 26.04.19  (721964) Added HasAutomation
  || 07/10/26 GWG 26.08.19  Added DateInputMode for date pickers
  || 07/07/26 GWG           WJ 2026 app color tweaks + light/dark surface mode
  */
  
 Declare @OwnerCompanyKey INT, @ClientLogin tinyint, @DefaultAction varchar(300)
 
 SELECT @OwnerCompanyKey = OwnerCompanyKey, @ClientLogin = ISNULL(ClientVendorLogin, 0)
 FROM tUser (nolock)
 WHERE UserKey = @UserKey
 
 Select @DefaultAction = ''today.creative''
 
 if @ClientLogin = 1
	Select @DefaultAction = ''someaction''
 
 IF @OwnerCompanyKey IS NULL

  SELECT  u.*
         ,c.CompanyName AS CompanyName
         ,c.CustomerID as ClientID
		 ,c.TimeZoneIndex AS CompanyTimeZoneIndex
         ,u.CompanyKey AS LoggedCompanyKey
         ,sg.GroupName    AS SecurityGroupName
		 ,sg.SecurityLevel
         ,p.StyleSheetKey
         ,p.ShowLogo--Trick Task Manager during Installs
         ,c.WebSite
         ,c.CustomLogo--Trick Task Manager during Installs
         ,p.AffiliateKey
         ,p.ReportLogo--Trick Task Manager during Installs
         ,p.SmallLogo--Trick Task Manager during Installs
		 ,p.Customizations
         ,ISNULL(p.ProductVersion, ''CM'') as ProductVersion
         ,ISNULL(ISNULL(u.LanguageID, p.LanguageID), ''EN'') as LangID
         ,p.ApplicationName
         ,ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture)) as Culture
		 ,p.IdleLogout
		 ,ISNULL(u.DefaultActionID, ISNULL(sg.DefaultActionID,@DefaultAction)) as ActionID

		 ,(Select ''|''+ LabID  AS [text()]   
            From tLab l inner join tLabCompany lc on l.LabKey = lc.LabKey Where lc.CompanyKey = u.CompanyKey
            For XML PATH ('''')) as CompanyLabs
	  	 ,(Select ''|''+ SUBSTRING(SessionID, 5, 4000)  AS [text()]   
            From tAppSession Where Entity = ''user'' and EntityKey = u.UserKey and SessionID like ''LAB_%'' and Value = 1
            For XML PATH ('''')) as UserLabs
		 ,ISNULL(ISNULL(u.Theme, p.Theme), 1) as ColorTheme
		 ,CASE
			WHEN EXISTS (SELECT 1 
						FROM	tAutoRule ar (nolock) 
						WHERE	ar.CompanyKey = u.CompanyKey 
						AND		ar.Active = 1 
						AND		ar.IsDeleted <> 1
						AND		(ar.Private <> 1 OR ar.CreatedBy = @UserKey)) THEN 1
			ELSE 0
		  END AS HasAutomation
          ,ISNULL(u.DateInputMode, ISNULL(p.DateInputMode, ''smarttext'')) as DateInputMode
          ,ISNULL(u.UserBackgroundColor, p.AppBackgroundColor) as AppBackgroundColor
          ,ISNULL(u.UserBarColor, p.AppBarColor) as AppBarColor
          ,ISNULL(u.UserMenuColor, p.AppMenuColor) as AppMenuColor
          ,ISNULL(u.UserAccentColor, p.AppAccentColor) as AppAccentColor
          ,ISNULL(u.UserDarkMode, p.AppDarkMode) as AppDarkMode
          ,ISNULL(u.UserBodyColor, p.AppBodyColor) as AppBodyColor
  FROM    tUser u (NOLOCK)
          LEFT OUTER JOIN tCompany c (NOLOCK) ON u.CompanyKey = c.CompanyKey
          LEFT OUTER JOIN tSecurityGroup  sg (NOLOCK) ON u.SecurityGroupKey = sg.SecurityGroupKey
          INNER JOIN tPreference p (NOLOCK) ON u.CompanyKey = p.CompanyKey
		  LEFT OUTER JOIN tOffice o (nolock) on u.OfficeKey = o.OfficeKey
  WHERE   u.UserKey           = @UserKey
 
 ELSE
 
  SELECT  u.*
         ,c.CompanyName AS CompanyName
         ,c.CustomerID as ClientID
		 ,c.TimeZoneIndex AS CompanyTimeZoneIndex
         ,u.OwnerCompanyKey AS LoggedCompanyKey
         ,sg.GroupName    AS SecurityGroupName
         ,sg.SecurityLevel
         ,p.StyleSheetKey
         ,p.ShowLogo--Trick Task Manager during Installs
         ,c.WebSite
         ,ISNULL(cl.CustomLogo, c.CustomLogo) as CustomLogo--Trick Task Manager during Installs
         ,p.AffiliateKey
         ,p.ReportLogo--Trick Task Manager during Installs
         ,p.SmallLogo--Trick Task Manager during Installs
		 ,p.Customizations
         ,ISNULL(p.ProductVersion, ''CM'') as ProductVersion 
         ,ISNULL(ISNULL(u.LanguageID, p.LanguageID), ''EN'') as LangID
         ,p.ApplicationName
         ,ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture)) as Culture
		 ,p.IdleLogout
		 ,ISNULL(u.DefaultActionID, ISNULL(sg.DefaultActionID,@DefaultAction)) as ActionID
		 ,(Select ''|''+ LabID  AS [text()]   
            From tLab l inner join tLabCompany lc on l.LabKey = lc.LabKey Where lc.CompanyKey = u.OwnerCompanyKey
            For XML PATH ('''')) as CompanyLabs
	  	 ,(Select ''|''+ SUBSTRING(SessionID, 5, 4000)  AS [text()]   
            From tAppSession Where Entity = ''user'' and EntityKey = u.UserKey and SessionID like ''LAB_%'' and Value = 1
            For XML PATH ('''')) as UserLabs
		 ,ISNULL(ISNULL(u.Theme, p.Theme), 1) as ColorTheme
		 ,CASE
			WHEN EXISTS (SELECT 1
						FROM	tAutoRule ar (nolock) 
						WHERE	ar.CompanyKey = u.OwnerCompanyKey 
						AND		ar.Active = 1 
						AND		ar.IsDeleted <> 1
						AND		(ar.Private <> 1 OR ar.CreatedBy = @UserKey)) THEN 1
			ELSE 0
		  END AS HasAutomation
          ,ISNULL(u.DateInputMode, ISNULL(p.DateInputMode, ''smarttext'')) as DateInputMode
          ,ISNULL(u.UserBackgroundColor, p.AppBackgroundColor) as AppBackgroundColor
          ,ISNULL(u.UserBarColor, p.AppBarColor) as AppBarColor
          ,ISNULL(u.UserMenuColor, p.AppMenuColor) as AppMenuColor
          ,ISNULL(u.UserAccentColor, p.AppAccentColor) as AppAccentColor
          ,ISNULL(u.UserDarkMode, p.AppDarkMode) as AppDarkMode
          ,ISNULL(u.UserBodyColor, p.AppBodyColor) as AppBodyColor
  FROM    tUser u (NOLOCK)
          INNER JOIN tCompany c (NOLOCK) ON u.OwnerCompanyKey = c.CompanyKey
          LEFT OUTER JOIN tCompany cl (NOLOCK) ON u.CompanyKey = cl.CompanyKey
          LEFT OUTER JOIN tSecurityGroup sg (NOLOCK) ON u.SecurityGroupKey = sg.SecurityGroupKey
          INNER JOIN tPreference p  (NOLOCK) ON u.OwnerCompanyKey = p.CompanyKey
		  LEFT OUTER JOIN tOffice o (nolock) on u.OfficeKey = o.OfficeKey
  WHERE   u.UserKey = @UserKey
 

 return 1 


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spConvertDBDiaryToDo]'
GO
IF OBJECT_ID(N'[dbo].[spConvertDBDiaryToDo]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spConvertDBDiaryToDo]
	@CompanyKey int = -1
AS

/*
|| When      Who Rel      What
|| 3/9/11    CRG 10.5.4.2 I have copied this from spConvertDB10539 so we can call this when the lab is turned on for a specific company.
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time
*/

	SET NOCOUNT ON

	update	tActivity 
	set		ActivityEntity = ''ToDo''
	where	(@CompanyKey = -1 OR CompanyKey = @CompanyKey)
	and		isnull(ProjectKey, 0) > 0
	and		isnull(TaskKey, 0) > 0


	update	tActivity 
	set		ActivityEntity = ''Diary''
	where	(@CompanyKey = -1 OR CompanyKey = @CompanyKey)
	and		isnull(ProjectKey, 0) > 0
	and		isnull(TaskKey, 0) = 0
	and		ISNULL(ActivityEntity, ''Activity'') <> ''ToDo'' 

	update	tActivity 
	set		ActivityEntity = ''Activity''
	where	(@CompanyKey = -1 OR CompanyKey = @CompanyKey)
	and		ActivityEntity is null

	Update tPreference Set UseToDo = 1 Where @CompanyKey = -1 OR CompanyKey = @CompanyKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceSetAmount]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceSetAmount]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER procedure [dbo].[sptInvoiceSetAmount]
	(
	@InvoiceKey int
	,@BillAmount money
	)
as --Encrypt

 /*
  || When     Who Rel    What
  || 08/22/16 GHL 10.607 (MN''s Todo) creation to set the total amount without taxes to a certain bill amount
  ||                      If there was a rounding error, try to change the AmountBilled of an expense
  ||                      If there are no expenses, try to change BilledHours, BilledRate of a time entry
  ||                      Taxes are not changed
  || 06/14/17 GHL 10.617 (349610) If there is still a rounding error after changing a time entry
  ||                      update the line total amount by the rounding diff (but the Total will not match the sum of time entries)
  || 08/24/17 GHL 10.619 (360412) If there are no expenses and we cannot modify the time entries adequately, do not change tInvoiceLine and tInvoice
  ||                      because of posting error if PostSalesUsingDetail = 1
  || 11/21/17 GHL 10.622 (373142) Still some rounding errors. Removed recalc of @NewBilledHours after the recalc of @NewBilledRate
  || 02/11/21 MCM 21.02.14 (547873) For parent invoices updating logic to use sum of TotalAmount on invoicesLine WHERE LineType = 2 (ie detail)
  || 07/22/26 MFT 26.05.18 (733513) Bug fix for split-billing
  */

declare @TotalNonTaxAmount money
declare @DiffAmount money -- difference between BillAmount the user wanted and the effective amount on the invoice, a rounding error usually

declare @POAmount money
declare @MiscCostAmount money
declare @ERAmount money
declare @VoucherAmount money
declare @LaborAmount money
declare @TranKey int
declare @TimeKey uniqueidentifier
declare @InvoiceLineKey int
declare @ParentInvoice int

select @TotalNonTaxAmount = TotalNonTaxAmount
		,@ParentInvoice = ISNULL(ParentInvoice, 0)
from   tInvoice (nolock)
where  InvoiceKey = @InvoiceKey

if @@ROWCOUNT = 0
	return 1

if @ParentInvoice = 1
	select @TotalNonTaxAmount  = sum(TotalAmount)
	from   tInvoiceLine (nolock)
	where  InvoiceKey = @InvoiceKey
	and LineType = 2

select @DiffAmount = isnull(@BillAmount, 0) - isnull(@TotalNonTaxAmount, 0)

-- if no difference, abort
if @DiffAmount = 0
	return 1

-- something when wrong with the invoice creation
if  isnull(@TotalNonTaxAmount, 0) = 0
	return 1

-- if this is not a rounding error, abort
if ABS(@DiffAmount) > 100
	return 1


-- there is a rounding error, try to apply it to an expense because the AmountBilled is easily changed

select @MiscCostAmount = sum(mc.AmountBilled)
from   tMiscCost mc (nolock)
inner join tInvoiceLine il (nolock) on mc.InvoiceLineKey = il.InvoiceLineKey
where il.InvoiceKey = @InvoiceKey

if @@ROWCOUNT > 0 and isnull(@MiscCostAmount, 0) <> 0
begin
	select @TranKey = max(mc.MiscCostKey)
	from   tMiscCost mc (nolock)
	inner join tInvoiceLine il (nolock) on mc.InvoiceLineKey = il.InvoiceLineKey
	where il.InvoiceKey = @InvoiceKey

	if isnull(@TranKey,0) > 0
	begin
		update tMiscCost
		set    AmountBilled = isnull(AmountBilled, 0) + @DiffAmount
		where  MiscCostKey = @TranKey

		select @InvoiceLineKey =  InvoiceLineKey from tMiscCost (nolock) where MiscCostKey = @TranKey

		update tInvoiceLine
		set    TotalAmount = isnull(TotalAmount, 0) + @DiffAmount
		where  InvoiceLineKey = @InvoiceLineKey

		if @ParentInvoice = 0
		begin
			update tInvoice
			set    TotalNonTaxAmount = isnull(TotalNonTaxAmount, 0) + @DiffAmount
				  ,InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0) + @DiffAmount
			where  InvoiceKey = @InvoiceKey

			exec sptInvoiceSummary @InvoiceKey
		end
		else
			exec sptInvoiceRecalcAmounts @InvoiceKey

		return 1
	end
end

select @ERAmount = sum(er.AmountBilled)
from   tExpenseReceipt er (nolock)
inner join tInvoiceLine il (nolock) on er.InvoiceLineKey = il.InvoiceLineKey
where il.InvoiceKey = @InvoiceKey

if @@ROWCOUNT > 0 and isnull(@ERAmount, 0) <> 0
begin
	select @TranKey = max(er.ExpenseReceiptKey)
	from    tExpenseReceipt er (nolock)
	inner join tInvoiceLine il (nolock) on er.InvoiceLineKey = il.InvoiceLineKey
	where il.InvoiceKey = @InvoiceKey

	if isnull(@TranKey,0) > 0
	begin
		update tExpenseReceipt
		set    AmountBilled = isnull(AmountBilled, 0) + @DiffAmount
		where  ExpenseReceiptKey = @TranKey

		select @InvoiceLineKey =  InvoiceLineKey from tExpenseReceipt (nolock) where ExpenseReceiptKey = @TranKey

		update tInvoiceLine
		set    TotalAmount = isnull(TotalAmount, 0) + @DiffAmount
		where  InvoiceLineKey = @InvoiceLineKey

		if @ParentInvoice = 0
		begin
			update tInvoice
			set    TotalNonTaxAmount = isnull(TotalNonTaxAmount, 0) + @DiffAmount
				  ,InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0) + @DiffAmount
			where  InvoiceKey = @InvoiceKey

			exec sptInvoiceSummary @InvoiceKey
		end
		else
			exec sptInvoiceRecalcAmounts @InvoiceKey

		return 1
	end
end



select @POAmount = sum(pod.AmountBilled)
from   tPurchaseOrderDetail pod (nolock)
inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
where il.InvoiceKey = @InvoiceKey

if @@ROWCOUNT > 0 and isnull(@POAmount, 0) <> 0
begin
	select @TranKey = max(pod.PurchaseOrderDetailKey)
	from    tPurchaseOrderDetail pod (nolock)
	inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
	where il.InvoiceKey = @InvoiceKey

	if isnull(@TranKey,0) > 0
	begin
		update tPurchaseOrderDetail
		set    AmountBilled = isnull(AmountBilled, 0) + @DiffAmount
		where  PurchaseOrderDetailKey = @TranKey

		select @InvoiceLineKey =  InvoiceLineKey from tPurchaseOrderDetail (nolock) where PurchaseOrderDetailKey = @TranKey

		update tInvoiceLine
		set    TotalAmount = isnull(TotalAmount, 0) + @DiffAmount
		where  InvoiceLineKey = @InvoiceLineKey

		if @ParentInvoice = 0
		begin
			update tInvoice
			set    TotalNonTaxAmount = isnull(TotalNonTaxAmount, 0) + @DiffAmount
				  ,InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0) + @DiffAmount
			where  InvoiceKey = @InvoiceKey

			exec sptInvoiceSummary @InvoiceKey
		end
		else
			exec sptInvoiceRecalcAmounts @InvoiceKey

		return 1
	end
end


select @VoucherAmount = sum(vd.AmountBilled)
from   tVoucherDetail vd (nolock)
inner join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
where il.InvoiceKey = @InvoiceKey

if @@ROWCOUNT > 0 and isnull(@VoucherAmount, 0) <> 0
begin
	select @TranKey = max(vd.VoucherDetailKey)
	from    tVoucherDetail vd (nolock)
	inner join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
	where il.InvoiceKey = @InvoiceKey

	if isnull(@TranKey,0) > 0
	begin
		update tVoucherDetail
		set    AmountBilled = isnull(AmountBilled, 0) + @DiffAmount
		where  VoucherDetailKey = @TranKey

		select @InvoiceLineKey =  InvoiceLineKey from tVoucherDetail (nolock) where VoucherDetailKey = @TranKey

		update tInvoiceLine
		set    TotalAmount = isnull(TotalAmount, 0) + @DiffAmount
		where  InvoiceLineKey = @InvoiceLineKey

		if @ParentInvoice = 0
		begin
			update tInvoice
			set    TotalNonTaxAmount = isnull(TotalNonTaxAmount, 0) + @DiffAmount
				  ,InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0) + @DiffAmount
			where  InvoiceKey = @InvoiceKey

			exec sptInvoiceSummary @InvoiceKey
		end
		else
			exec sptInvoiceRecalcAmounts @InvoiceKey

		return 1
	end
end

-- there was no expense, find a time entry to modify the rate
-- this is more difficult because we do not have 1 AmountBilled but, 2 fields BilledHours and BilledRate

create table #time (TimeKey uniqueidentifier
    , InvoiceLineKey int null
	, OrigBilledHours decimal(24,4) null
	, OrigBilledRate money null
	, NewBilledHours decimal(24,4) null
	, NewBilledRate money null
	, OrigAmountBilled money null
	, NewAmountBilled money null
	, UpdateFlag int null
	)

insert #time (TimeKey, InvoiceLineKey, OrigBilledHours, OrigBilledRate, OrigAmountBilled, NewBilledHours, NewBilledRate, NewAmountBilled)
select t.TimeKey, t.InvoiceLineKey, t.BilledHours, t.BilledRate, round(t.BilledHours * t.BilledRate, 2), t.BilledHours, t.BilledRate, round(t.BilledHours * t.BilledRate, 2)
from   tTime t (nolock)
	inner join tInvoiceLine il (nolock) on t.InvoiceLineKey = il.InvoiceLineKey
where  il.InvoiceKey = @InvoiceKey

declare @OrigAmountBilled money
declare @OrigBilledHours decimal(24,4)
declare @OrigBilledRate money

declare @NewAmountBilled money
declare @NewBilledHours decimal(24,4)
declare @NewBilledRate money
declare @NewAmountBilledWithTaxes money
-- Added for 349610
declare @LineTotalAmount money

if exists (select 1 from #time)
begin
	-- try to apply it to the greatest amount billed
	select @OrigAmountBilled = max(OrigAmountBilled)
	from   #time
	where  OrigAmountBilled > 0

	update #time
	set    UpdateFlag = 1 -- we could update several time entries
	where  OrigAmountBilled = @OrigAmountBilled

	select @TimeKey = TimeKey -- pick one
	from   #time
	where  UpdateFlag = 1

	if @TimeKey is not null
	begin

		select @OrigBilledHours = OrigBilledHours
			  ,@OrigBilledRate = OrigBilledRate
			  ,@InvoiceLineKey = InvoiceLineKey
		from   #time
		where  TimeKey = @TimeKey

		select @NewAmountBilled = isnull(@OrigAmountBilled, 0) + @DiffAmount

		-- @NewBilledRate should be calculated with 4 digits
		if @OrigBilledHours <> 0
		begin
			select @NewBilledRate = @NewAmountBilled / @OrigBilledHours
			select @NewBilledHours = @OrigBilledHours
		end
		else
		begin
			--@OrigBilledHours = 0, unlikely since we take OrigAmountBilled <> 0
			select @NewBilledRate = @NewAmountBilled
			select @NewBilledHours = 1
		end

		-- recalc again in case there are still some rounding errors
		select @NewAmountBilled = round(@NewBilledHours * @NewBilledRate, 2)

		update #time
		set    NewBilledHours = @NewBilledHours
			  ,NewBilledRate = @NewBilledRate
			  ,NewAmountBilled = @NewAmountBilled
		where  TimeKey = @TimeKey

		update tTime
		set    BilledHours = @NewBilledHours
			  ,BilledRate = @NewBilledRate
		where  TimeKey = @TimeKey

		-- now update the Invoice line
		select @NewAmountBilled = sum(round(NewBilledHours * NewBilledRate, 2))
		from   #time
		where  InvoiceLineKey = @InvoiceLineKey

		-- Added for 349610
		select @LineTotalAmount = @NewAmountBilled

		update tInvoiceLine
		set    TotalAmount = @NewAmountBilled
		where  InvoiceLineKey = @InvoiceLineKey

		select @NewAmountBilled = sum(TotalAmount)
			  ,@NewAmountBilledWithTaxes = sum(isnull(TotalAmount,0) + isnull(SalesTaxAmount, 0))
		from tInvoiceLine (nolock)
		where  InvoiceKey = @InvoiceKey

		-- Added for 349610
		-- if we still have a problem, change the line we were working on
		-- but it will not match the sum billed on time entries

		-- only do this is PostSalesUsingDetail = 0, because that would create posting error (360412)
		declare @PostSalesUsingDetail int
		select @PostSalesUsingDetail = PostSalesUsingDetail from tInvoiceLine (nolock) where InvoiceLineKey = @InvoiceLineKey

		if @NewAmountBilled <> @BillAmount and @PostSalesUsingDetail = 0
		begin
			declare @DiffAmount2 money
			select @DiffAmount2 = isnull(@BillAmount, 0) - isnull(@NewAmountBilled, 0)

			if abs(@DiffAmount2) < .05 -- if too big, leave it to the user to fix it
			begin
				select @NewAmountBilled = isnull(@LineTotalAmount, 0) + @DiffAmount2

				update tInvoiceLine
				set    TotalAmount = @NewAmountBilled
				where  InvoiceLineKey = @InvoiceLineKey

				select @NewAmountBilled = sum(TotalAmount)
				  ,@NewAmountBilledWithTaxes = sum(isnull(TotalAmount,0) + isnull(SalesTaxAmount, 0))
				from tInvoiceLine (nolock)
				where  InvoiceKey = @InvoiceKey

			end
		end
		if @ParentInvoice = 0
		begin
			update tInvoice
			set    TotalNonTaxAmount = @NewAmountBilled
					,InvoiceTotalAmount = @NewAmountBilledWithTaxes
			where  InvoiceKey = @InvoiceKey

			exec sptInvoiceSummary @InvoiceKey
		end
		else
			exec sptInvoiceRecalcAmounts @InvoiceKey

		-- for Abelson Taylor
		if exists (select 1 from #time where isnull(OrigBilledHours, 0) <> isnull(NewBilledHours, 0))
			exec sptInvoiceLineSetHours @InvoiceKey

		return 1
	end
end

return 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIProjectGetSummary]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIProjectGetSummary]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIProjectGetSummary]
(
    @CompanyKey     int,
    @UserKey        int,
    @ProjectNumber  varchar(50)  = null,
    @ClientID       varchar(50)  = null,
    @ProjectType    varchar(100) = null,
    @ProjectStatus  varchar(50)  = null,
    @Filter         varchar(50)  = null,   -- ''over_budget'' | ''behind_schedule'' | ''near_overbudget''
    @ProjectManager varchar(200) = null,   -- UserID, email, or full name; scopes to this PM''s projects
    @AccountManager varchar(200) = null    -- UserID, email, or full name; scopes to this AM''s projects
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 03/10/26  QMD 26.03.15   Created for AI project summary tool
|| 03/10/26  QMD 26.03.15   Switched from @ProjectKey to @ProjectNumber; lookup now done inside proc
|| 03/10/26  QMD 26.03.15   Added @ClientID, @ProjectType, @ProjectStatus for list queries
|| 03/10/26  QMD 26.03.15   Added key lookups for ClientID, ProjectType, ProjectStatus (name or id)
|| 03/10/26  QMD 26.03.15   Added @Filter for over_budget / behind_schedule / near_overbudget
|| 05/25/26  AI  26.05.25   Added #errors standard error logging and user-validity check.
||                          When @ProjectNumber identifies a single project, access is gated through
||                          spCheckAccess (tProject). List mode (no @ProjectNumber) keeps the set-based
||                          GL company + assignment filter - calling spCheckAccess per row would be N
||                          proc calls.
|| 05/28/26  AI  26.05.28   Added #errors / warnings; spCheckAccess (tProject) for single-project mode. Result-set shape now [warnings, projects].
|| 06/18/26  GAR 26.07.19   (730520) Added custom field key so we can get custom fields on the front end.
|| 07/21/26  GAR 26.08.16   (732526) Added ProjectKey to result set so MCP can surface an unencrypted projectKey for client use in follow-up queries.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @ProjectKey          int = null
    declare @ClientKey           int = null
    declare @ProjectTypeKey      int = null
    declare @ProjectStatusKey    int = null
    declare @RestrictToGLCompany int
    declare @CheckAssignment     int
    declare @SecurityGroupKey    int
    declare @AccessOK            int
    declare @ErrorCount          int

    -- ------------------------------------------------------------------
    -- 1. Validate user
    -- ------------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey
    from   tUser (nolock)
    where  UserKey    = @UserKey
      and  CompanyKey = @CompanyKey

    if @SecurityGroupKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    from   tPreference (nolock) where CompanyKey = @CompanyKey

    -- ------------------------------------------------------------------
    -- 2. Resolve string filters
    -- ------------------------------------------------------------------
    if @ProjectNumber is not null
        select @ProjectKey = ProjectKey
        from   tProject (nolock)
        where  CompanyKey    = @CompanyKey
          and  ProjectNumber = @ProjectNumber

    if @ClientID is not null
        select @ClientKey = CompanyKey
        from   tCompany (nolock)
        where  OwnerCompanyKey = @CompanyKey
          and  (CustomerID = @ClientID or CompanyName = @ClientID)

    if @ProjectType is not null
        select @ProjectTypeKey = ProjectTypeKey
        from   tProjectType (nolock)
        where  CompanyKey      = @CompanyKey
          and  ProjectTypeName = @ProjectType

    if @ProjectStatus is not null
        select @ProjectStatusKey = ProjectStatusKey
        from   tProjectStatus (nolock)
        where  CompanyKey = @CompanyKey
          and  (ProjectStatusID = @ProjectStatus or ProjectStatus = @ProjectStatus)

    -- Resolve PM / AM names to UserKeys. If a name was supplied but not found,
    -- use -1 so the filter matches nothing (rather than silently returning all).
    declare @PMKey int = null
    declare @AMKey int = null

    if @ProjectManager is not null and LTRIM(RTRIM(@ProjectManager)) <> ''''
    begin
        select @PMKey = MIN(UserKey) from tUser (nolock)
        where  ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
          and  (UserID = @ProjectManager or Email = @ProjectManager
                or LTRIM(RTRIM(ISNULL(FirstName,'''') + '' '' + ISNULL(LastName,''''))) = LTRIM(RTRIM(@ProjectManager)))
        if @PMKey is null
        begin
            set @PMKey = -1
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'',''NOT_FOUND'',''Project manager "'' + @ProjectManager + ''" not found; no projects matched that PM.'',''projectManager'')
        end
    end

    if @AccountManager is not null and LTRIM(RTRIM(@AccountManager)) <> ''''
    begin
        select @AMKey = MIN(UserKey) from tUser (nolock)
        where  ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
          and  (UserID = @AccountManager or Email = @AccountManager
                or LTRIM(RTRIM(ISNULL(FirstName,'''') + '' '' + ISNULL(LastName,''''))) = LTRIM(RTRIM(@AccountManager)))
        if @AMKey is null
        begin
            set @AMKey = -1
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'',''NOT_FOUND'',''Account manager "'' + @AccountManager + ''" not found; no projects matched that AM.'',''accountManager'')
        end
    end

    -- ------------------------------------------------------------------
    -- 3. Single-project mode: when @ProjectNumber was supplied, hard-gate
    --    access via spCheckAccess. This gives a clean -103 instead of a
    --    silently-empty result when the user can''t see the project.
    -- ------------------------------------------------------------------
    if @ProjectNumber is not null and LTRIM(RTRIM(@ProjectNumber)) <> ''''
    begin
        if @ProjectKey is null
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''NOT_FOUND'', ''Project not found for projectNumber: '' + @ProjectNumber, ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName

            drop table #errors
            return -101
        end

        exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey

        if @AccessOK <> 1
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')

            select errorType, errorCode, errorMessage, fieldName
            from   #errors order by errorType desc, fieldName

            drop table #errors
            return -103
        end
    end

    -- ------------------------------------------------------------------
    -- 4. Build #projectKeys: candidates that satisfy the filter set
    -- ------------------------------------------------------------------
    create table #projectKeys (ProjectKey int not null)

    if @Filter = ''over_budget''
    begin
        insert into #projectKeys (ProjectKey)
        select pr.ProjectKey
        from   tProject pr (nolock)
        left outer join tProjectRollup roll (nolock) on pr.ProjectKey = roll.ProjectKey
        where  pr.CompanyKey = @CompanyKey
          and  pr.Closed     = 0
          and  (@ProjectKey       is null or pr.ProjectKey       = @ProjectKey)
          and  (@ClientKey        is null or pr.ClientKey        = @ClientKey)
          and  (@ProjectTypeKey   is null or pr.ProjectTypeKey   = @ProjectTypeKey)
          and  (@ProjectStatusKey is null or pr.ProjectStatusKey = @ProjectStatusKey)
          and  (ISNULL(roll.LaborGross, 0)
                  + ISNULL(roll.MiscCostGross, 0)
                  + ISNULL(roll.ExpReceiptGross, 0)
                  + ISNULL(roll.VoucherOutsideCostsGross, 0))
              > (ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)
                  + ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0))
    end
    else if @Filter = ''behind_schedule''
    begin
        insert into #projectKeys (ProjectKey)
        select distinct pr.ProjectKey
        from   tProject pr (nolock)
        inner join tTask t (nolock) on pr.ProjectKey = t.ProjectKey
        where  pr.CompanyKey   = @CompanyKey
          and  pr.Closed       = 0
          and  t.ActComplete   is not null
          and  t.PlanComplete  < GETUTCDATE()
          and  (@ProjectKey       is null or pr.ProjectKey       = @ProjectKey)
          and  (@ClientKey        is null or pr.ClientKey        = @ClientKey)
          and  (@ProjectTypeKey   is null or pr.ProjectTypeKey   = @ProjectTypeKey)
          and  (@ProjectStatusKey is null or pr.ProjectStatusKey = @ProjectStatusKey)
    end
    else if @Filter = ''near_overbudget''
    begin
        insert into #projectKeys (ProjectKey)
        select pr.ProjectKey
        from   tProject pr (nolock)
        left outer join tProjectRollup roll (nolock) on pr.ProjectKey = roll.ProjectKey
        where  pr.CompanyKey = @CompanyKey
          and  pr.Closed     = 0
          and  (@ProjectKey       is null or pr.ProjectKey       = @ProjectKey)
          and  (@ClientKey        is null or pr.ClientKey        = @ClientKey)
          and  (@ProjectTypeKey   is null or pr.ProjectTypeKey   = @ProjectTypeKey)
          and  (@ProjectStatusKey is null or pr.ProjectStatusKey = @ProjectStatusKey)
          and  (ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)
                  + ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0)) > 0
          and  (ISNULL(roll.BilledAmount, 0)
                  - (ISNULL(roll.LaborNet, 0) + ISNULL(roll.MiscCostNet, 0)
                      + ISNULL(roll.ExpReceiptNet, 0) + ISNULL(roll.VoucherNet, 0)))
              / (ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)
                  + ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0)) < 0.10
    end
    else
    begin
        insert into #projectKeys (ProjectKey)
        select pr.ProjectKey
        from   tProject pr (nolock)
        where  pr.CompanyKey = @CompanyKey
          and  pr.Closed     = 0
          and  (@ProjectKey       is null or pr.ProjectKey       = @ProjectKey)
          and  (@ClientKey        is null or pr.ClientKey        = @ClientKey)
          and  (@ProjectTypeKey   is null or pr.ProjectTypeKey   = @ProjectTypeKey)
          and  (@ProjectStatusKey is null or pr.ProjectStatusKey = @ProjectStatusKey)
    end

    -- ------------------------------------------------------------------
    -- 5. List-mode set-based GL company + assignment filter
    --    (Single-project mode already passed spCheckAccess above.)
    -- ------------------------------------------------------------------
    if @ProjectKey is null
    begin
        if @RestrictToGLCompany = 1
            delete pk
            from   #projectKeys pk
            inner join tProject pr (nolock) on pk.ProjectKey = pr.ProjectKey
            where  pr.GLCompanyKey not in (
                       select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey
                   )

        set @CheckAssignment = 1
        if exists (
            select 1 from tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where  ra.EntityType = ''Security Group''
              and  ra.EntityKey  = @SecurityGroupKey
              and  r.RightID     = ''prjAccessAny''
        )
            set @CheckAssignment = 0

        if @CheckAssignment = 1
            delete from #projectKeys
            where  ProjectKey not in (select ProjectKey from tAssignment where UserKey = @UserKey)

        -- PM / AM scoping (list mode only; an explicit projectNumber is never filtered out)
        if @PMKey is not null
            delete pk from #projectKeys pk
            inner join tProject pr (nolock) on pk.ProjectKey = pr.ProjectKey
            where ISNULL(pr.ProjectManager, 0) <> @PMKey

        if @AMKey is not null
            delete pk from #projectKeys pk
            inner join tProject pr (nolock) on pk.ProjectKey = pr.ProjectKey
            where ISNULL(pr.AccountManager, 0) <> @AMKey
    end

    -- ------------------------------------------------------------------
    -- 6. Warnings (consistent shape)
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from   #errors where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 7. Project summary
    -- ------------------------------------------------------------------
    select
         pr.ProjectKey                                                     as ProjectKey
        ,pr.ProjectNumber                                                  as ProjectNumber
        ,ISNULL(pr.ProjectName, '''')                                        as ProjectName
        ,pr.ProjectNumber + '' '' + ISNULL(pr.ProjectName, '''')               as ProjectFullName
        ,ISNULL(pr.Description, '''')                                        as Description
        ,ISNULL(cl.CompanyName, '''')                                        as ClientName
        ,ISNULL(am.FirstName, '''') + '' '' + ISNULL(am.LastName, '''')          as AccountManager
        ,ISNULL(pm.FirstName, '''') + '' '' + ISNULL(pm.LastName, '''')          as ProjectManager
        ,ISNULL(bcu.FirstName, '''') + '' '' + ISNULL(bcu.LastName, '''')        as BillingContact
        ,ISNULL(ps.ProjectStatus, '''')                                      as ProjectStatus
        ,ISNULL(ps.ProjectStatusID, '''')                                    as ProjectStatusID
        ,ISNULL(pbs.ProjectBillingStatus, '''')                              as BillingStatus
        ,ISNULL(pr.StatusNotes, '''')                                        as StatusNotes
        ,ISNULL(pr.Closed, 0)                                              as Closed
        ,ISNULL(pr.NonBillable, 0)                                         as NonBillable
        ,case
            when ISNULL(pr.BillingMethod, 0) = 1 then ''Time and Materials''
            when ISNULL(pr.BillingMethod, 0) = 2 then ''Fixed Fee''
            when ISNULL(pr.BillingMethod, 0) = 3 then ''Retainer''
            else ''Time and Materials''
         end                                                                as BillingMethod
        ,ISNULL(pr.StartDate, '''')                                          as StartDate
        ,case when YEAR(pr.CompleteDate) <= 1900 then null else pr.CompleteDate end as DueDate
        ,ISNULL(pr.EstHours, 0) + ISNULL(pr.ApprovedCOHours, 0)            as BudgetHours
        ,ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)            as BudgetLaborGross
        ,ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0)       as BudgetExpenseGross
        ,ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)
           + ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0)   as BudgetTotal
        ,ISNULL(roll.Hours, 0)                                             as ActualHours
        ,ISNULL(roll.LaborGross, 0)                                        as ActualLaborGross
        ,ISNULL(roll.LaborNet, 0)                                          as ActualLaborCost
        ,ISNULL(roll.MiscCostGross, 0)
           + ISNULL(roll.ExpReceiptGross, 0)
           + ISNULL(roll.VoucherOutsideCostsGross, 0)                       as ActualExpenseGross
        ,ISNULL(roll.MiscCostNet, 0)
           + ISNULL(roll.ExpReceiptNet, 0)
           + ISNULL(roll.VoucherNet, 0)                                     as ActualExpenseCost
        ,ISNULL(roll.LaborGross, 0)
           + ISNULL(roll.MiscCostGross, 0)
           + ISNULL(roll.ExpReceiptGross, 0)
           + ISNULL(roll.VoucherOutsideCostsGross, 0)                       as ActualTotalGross
        ,ISNULL(roll.LaborNet, 0)
           + ISNULL(roll.MiscCostNet, 0)
           + ISNULL(roll.ExpReceiptNet, 0)
           + ISNULL(roll.VoucherNet, 0)                                     as ActualTotalCost
        ,ISNULL(roll.BilledAmount, 0)                                      as AmountBilled
        ,ISNULL(roll.LaborUnbilled, 0)
           + ISNULL(roll.MiscCostUnbilled, 0)
           + ISNULL(roll.ExpReceiptUnbilled, 0)
           + ISNULL(roll.VoucherUnbilled, 0)                                as UnbilledTotal
        ,ISNULL(roll.BilledAmount, 0)
           - (ISNULL(roll.LaborNet, 0)
                + ISNULL(roll.MiscCostNet, 0)
                + ISNULL(roll.ExpReceiptNet, 0)
                + ISNULL(roll.VoucherNet, 0))                               as Margin
        ,(ISNULL(pr.EstLabor, 0) + ISNULL(pr.ApprovedCOLabor, 0)
            + ISNULL(pr.EstExpenses, 0) + ISNULL(pr.ApprovedCOExpense, 0))
            - (ISNULL(roll.LaborGross, 0)
                + ISNULL(roll.MiscCostGross, 0)
                + ISNULL(roll.ExpReceiptGross, 0)
                + ISNULL(roll.VoucherOutsideCostsGross, 0))                 as BudgetRemaining
        ,pr.CustomFieldKey                                                 as CustomFieldKey
    from   tProject pr (nolock)
    inner join #projectKeys pk on pr.ProjectKey = pk.ProjectKey
    left outer join tProjectStatus ps (nolock)
        on pr.ProjectStatusKey = ps.ProjectStatusKey
    left outer join tProjectBillingStatus pbs (nolock)
        on pr.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
    left outer join tCompany cl (nolock)
        on pr.ClientKey = cl.CompanyKey
    left outer join tProjectType pt (nolock)
        on pr.ProjectTypeKey = pt.ProjectTypeKey
    left outer join tUser am (nolock)
        on pr.AccountManager = am.UserKey
    left outer join tUser pm (nolock)
        on pr.ProjectManager = pm.UserKey
    left outer join tUser bcu (nolock)
        on pr.BillingContact = bcu.UserKey
    left outer join tProjectRollup roll (nolock)
        on pr.ProjectKey = roll.ProjectKey

    drop table #projectKeys
    drop table #errors

    return 0



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vListing_Payment]'
GO
IF OBJECT_ID(N'[dbo].[vListing_Payment]', 'V') IS NOT NULL
EXEC sp_executesql N'
ALTER VIEW [dbo].[vListing_Payment]
AS

/*
|| When      Who Rel     What
|| 10/10/07  CRG 8.5     Added GLCompany
|| 02/14/07  GWG 8.6     Added the unapplied payment account
|| 04/23/09  GWG 10.023  Added Custom FieldKey
|| 05/21/09  MFT 10.026	 Unapplied Amount
|| 07/29/09  RLB 10.505  Added Opening Transactions
|| 03/09/10  RLB 10.520  Added account type on cash account 
|| 04/25/12  GHL 10.555  Added GLCompanyKey for map/restrict
|| 07/10/12  MFT 10.558  Added [Voided Payment]
|| 11/12/13  GHL 10.574  Added CurrencyID
|| 03/20/14  GHL 10.578  Added Exchange Rate
|| 07/28/16  WDF 10.606  (308500) Added [Pay To Name on Payment]
|| 04/19/18  AMP 18.5.0  (397451) Added [Vendor Phone]
|| 11/18/19  GHL 19.120  (455860) Added Cash Account Currency
|| 11/20/20  MFT 20.120  (537837) Add NEC to Type1099 enum
|| 12/20/21  MCM 21.01x  (581037) Added ACH Email and CC Email
|| 02/16/22  AMP 22.04.17 (586174) Added Payment Created Date
|| 10/03/22  AMP 22.11.20 (613940) Added Cash Amount
|| 04/21/23  AMP 23.05.14 (637959) Added ACH Enabled
|| 09/26/23  MCM 23.10.15 (628804) Added PaymentType
|| 07/21/26  AMP 26.08.16 (733336) Added [Vendor Active] and [Last Payment Date]
*/

SELECT
	 p.PaymentKey
	,p.CompanyKey
	,p.GLCompanyKey
	,p.VendorKey
	,c.CustomFieldKey
	,gl.AccountNumber as [Cash Account Number]
	,gl.AccountName as [Cash Account Name]
	,gl.AccountNumber + '' - '' + gl.AccountName as [Cash Account Full Name]
	,CASE gl.AccountType
		WHEN 10 THEN ''Bank''
		WHEN 11 THEN ''Accounts Receivable''
		WHEN 12 THEN ''Current Asset''
		WHEN 13 THEN ''Fixed Asset''
		WHEN 14 THEN ''Other Asset''
		WHEN 20 THEN ''Accounts Payable''
		WHEN 21 THEN ''Current Liability''
		WHEN 22 THEN ''Long Term Liability''
		WHEN 30 THEN ''Equity - Does Not Close''
		WHEN 31 THEN ''Equity - Closes''
		WHEN 32 THEN ''Retained Earnings''
		WHEN 40 THEN ''Income''
		WHEN 41 THEN ''Other Income''
		WHEN 50 THEN ''Cost of Goods Sold''
		WHEN 51 THEN ''Expense''
		WHEN 52 THEN ''Other Expense''
	END AS [Account Type]
	,p.PaymentAmount - 
	(Select ISNULL(Sum(Amount), 0) from tPaymentDetail (NOLOCK) Where PaymentKey = p.PaymentKey) AS [Unapplied Amount]
	,gl2.AccountNumber as [Unapplied Payment Account Number]
	,gl2.AccountName as [Unapplied Payment Account Name]
	,gl2.AccountNumber + '' - '' + gl2.AccountName as [Unapplied Payment Account Full Name]
	,p.PaymentDate as [Check Date]
	,p.CheckNumber as [Check Number]
	,c.VendorID as [Vendor ID]
	,c.CompanyName as [Vendor Name]
	,c.Phone as [Vendor Phone]
	,CASE c.Type1099 WHEN 1 THEN ''MISC'' WHEN 2 THEN ''INT'' WHEN 3 THEN ''NEC'' ELSE ''NONE'' END AS [Vendor 1099 Type]
	,c.EmailACHToAddress as [Email ACH to Address]
    ,c.EmailCCToAddress as [Email CC to Address]
	,cl.ClassID as [Class ID]
	,cl.ClassName as [Class Name]
	,ct.CompanyTypeName as [Company Type]
	,c.DBA as [Doing Business As]
	,CASE ISNULL(c.UseDBAForPayment, 0) WHEN 1 THEN c.DBA ELSE p.PayToName END AS [Pay To Name on Payment]
	,p.PayToName as [Pay To Name]
	,p.PayToAddress1 as [Pay To Address1]
	,p.PayToAddress2 as [Pay To Address2]
	,p.PayToAddress3 as [Pay To Address3]
	,p.PayToAddress4 as [Pay To Address4]
	,p.PayToAddress5 as [Pay To Address5]
	,p.PostingDate as [Posting Date]
	,p.Memo as [Check Memo]
	,p.PaymentAmount as [Check Amount]
	,case p.Posted when 1 then ''YES'' else ''NO'' end as Posted
	,case when p.CheckNumber is null then ''NO'' else ''YES'' end as Printed
	,(Select Count(*) from tTransaction (nolock) Where Entity = ''PAYMENT'' and EntityKey = p.PaymentKey) as [Posting Count]
	,Case (Select Distinct 1 from tTransaction tr(nolock) Where  p.PaymentKey = tr.EntityKey and tr.Entity = ''PAYMENT'' and tr.Cleared = 1) When 1 then ''YES'' else ''NO'' end as Cleared
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
  ,case ISNULL(p.OpeningTransaction, 0) when 0 then ''NO'' when 1 then ''YES'' end as [Opening Transaction]
  ,CASE ISNULL(VoidPaymentKey, 0) WHEN PaymentKey THEN ''YES'' ELSE ''NO'' END AS [Voided Payment]
  ,p.CurrencyID as [Currency]
  ,p.CashCurrencyID as [Cash Account Currency]
  ,p.ExchangeRate as [Exchange Rate]
  ,p.VCardBatchID as [VCard Batch ID]
  ,case ISNULL(p.VCardPublished, 0) when 0 then ''NO'' when 1 then ''YES'' end as [VCard Batch Published]
  ,p.CreatedDate as [Payment Created Date]
  ,p.CashAmount as [Cash Amount]
  ,CASE ISNULL(c.ACHEnabled, 0)
		WHEN 1 THEN ''YES''
		ELSE ''NO''
	END AS [ACH Enabled]
  , pt.PaymentTypeName as [Payment Type Name]
  ,CASE WHEN ISNULL(c.Vendor, 0) = 1 AND ISNULL(c.ActiveVendor, 0) = 1 THEN ''YES'' ELSE ''NO'' END AS [Vendor Active]
  ,(SELECT MAX(p2.PaymentDate) FROM tPayment p2 (nolock) WHERE p2.VendorKey = p.VendorKey AND p2.CompanyKey = p.CompanyKey) AS [Last Payment Date]
FROM
	tPayment p (nolock)
	INNER JOIN tCompany c (nolock) ON p.VendorKey = c.CompanyKey 
	left outer join tCompanyType ct (nolock) on c.CompanyTypeKey = ct.CompanyTypeKey
	left outer JOIN tGLAccount gl(nolock) ON p.CashAccountKey = gl.GLAccountKey
	left outer JOIN tGLAccount gl2 (nolock) ON p.UnappliedPaymentAccountKey = gl2.GLAccountKey
	left outer join tClass cl (nolock) on p.ClassKey = cl.ClassKey
	left outer join tGLCompany glc (nolock) on p.GLCompanyKey = glc.GLCompanyKey
	left outer join tPaymentType pt (nolock) on p.PaymentType = pt.PaymentType and p.CompanyKey = pt.CompanyKey
	--left outer join tTransaction tr (nolock) on p.PaymentKey = tr.EntityKey and tr.Entity = ''PAYMENT'' and tr.Cleared = 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPurchaseOrderGetAppList]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderGetAppList]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER procedure [dbo].[sptPurchaseOrderGetAppList]
	(
	@CompanyKey int
	,@POKind int
	,@UserKey int = null
	,@Search varchar(100) = NULL
	,@ProjectKey int = null
	)
as --Encrypt

/*
|| When      Who Rel      What
|| 11/16/15  GHL 10.598   Creation for the new APP dash
||                        Pull open orders entered by the user
|| 11/17/15  GHL 10.598   Upper Search to make it easy in development
|| 12/10/15  GHL 10.599   Added rejected records so that we can resubmit
|| 04/27/16  GHL 10.603   Added ProjectKey (after request on todo)
|| 09/17/18  GHL 18.910   (420246) Checking now project on PODs
|| 08/19/19  RLS 19.0.9   (471115) Added po.Description and po.DueDate
|| 01/28/20  AMP 20.0.2   (497753) Added Gross Amount for the PO/BO/IO sections of the Project 
|| 06/02/20  AMP 20.0.8.0 (516857) Removed the filter for only pulling open orders. A toggle switch was added to show open/closed orders on the PO/BO/IO screens.
|| 06/21/22  GAR 22.07.17 (603320) Added the Station ID and Name (Publication ID and Name) for the IO and BO card view in projects.
|| 07/20/26  AMP 26.08.16 (732631) Added the Station/Publication ID and Name (tCompanyMedia) to the @Search filter.
*/

	SET NOCOUNT ON

	select @Search =  upper(rtrim(ltrim(@Search)))

	if @Search = ''''
		select @Search = null

	select distinct po.PurchaseOrderKey
	      ,po.PurchaseOrderNumber
		  ,po.PODate
		  ,po.DueDate
	      ,po.PurchaseOrderTotal
		  ,po.Status
		  ,po.Description
		  ,p.ProjectNumber
		  ,p.ProjectName
		  ,isnull(p.ProjectNumber + '' - '', '''') + isnull(p.ProjectName, '''') as ProjectFullName
		  ,c.VendorID
		  ,c.CompanyName as VendorName
		  ,c.VendorID + '' - '' + c.CompanyName as VendorFullName
		  ,pod1.GrossAmount
		  ,po.Closed
		  ,isnull(cm.StationID + '' - '', '''') + isnull(cm.Name, '''') as StationFullName
	from tPurchaseOrder po (nolock)
		left outer join tProject p (nolock) on po.ProjectKey = p.ProjectKey 
		left outer join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		left outer join tPurchaseOrderDetail pod (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join (
			SELECT PurchaseOrderKey, SUM(GrossAmount) AS GrossAmount
			FROM tPurchaseOrderDetail (nolock)
			GROUP BY PurchaseOrderKey
		) pod1 on pod1.PurchaseOrderKey = po.PurchaseOrderKey
	where po.CompanyKey = @CompanyKey
	--and   po.Status in (1, 2, 3, 4) -- we show rejected orders also, remove them if needed	
	and   (@UserKey is null or po.CreatedByKey = @UserKey)
	and   po.POKind = @POKind
	and   (@Search is null
			or 
				(
				upper(po.PurchaseOrderNumber) like  ''%'' + @Search + ''%''
				or
				upper(p.ProjectNumber) like  ''%'' + @Search + ''%''
				or
				upper(p.ProjectName) like  ''%'' + @Search + ''%''
				or
				upper(c.VendorID) like  ''%'' + @Search + ''%''
				or
				upper(c.CompanyName) like  ''%'' + @Search + ''%''
				or
				upper(cm.StationID) like  ''%'' + @Search + ''%''
				or
				upper(cm.Name) like  ''%'' + @Search + ''%''
				)
		  )
	and (isnull(@ProjectKey,0) = 0 
		or po.ProjectKey = @ProjectKey
		or pod.ProjectKey = @ProjectKey
	)

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAITimeAddEntry]'
GO
IF OBJECT_ID(N'[dbo].[spApiAITimeAddEntry]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAITimeAddEntry]
    (
        @CompanyKey    int,
        @UserKey       int,
        @ProjectNumber varchar(50),
        @Hours         decimal(24,4),
        @WorkDate      smalldatetime  = null,
        @TaskID        nvarchar(30)   = null,
        @ServiceName   nvarchar(100)  = null,
        @Comments      nvarchar(2000) = null,
        @StartTime     varchar(20)    = null,
        @EndTime       varchar(20)    = null
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 03/10/26  QMD 26.03.15   Created for AI time tool
|| 07/10/25  AI  25.07.10   Replaced ad-hoc error returns with standard #errors pattern
|| 05/15/26  GRR 26.05.xx   Return taskID/serviceName instead of taskKey/serviceKey to match C# handler.
|| 05/28/26  AI  26.05.28   Added spCheckAccess (tProject) gate after project resolution.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billingusetimesheet.
*/

Declare @ProjectKey    int            = null
Declare @TaskKey       int            = 0
Declare @ServiceKey    int            = 0
Declare @TimeSheetKey  int            = null
Declare @WorkDateDT    smalldatetime
Declare @StartTimeDT   smalldatetime  = null
Declare @EndTimeDT     smalldatetime  = null
Declare @TimeKey       uniqueidentifier

    -- ------------------------------------------------------------------
    -- Gating security: billingusetimesheet
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billingusetimesheet''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billingusetimesheet).'' as errorMessage, ''general'' as fieldName
        return -103
    end

-- Create temp table for error/warning messages
select * into #errors from tAPIErrorTemplate where 1 = 2

-- Default work date to today (UTC date only, no time component)
If @WorkDate is null
    Set @WorkDateDT = CAST(CAST(GETUTCDATE() as date) as smalldatetime)
Else
    Set @WorkDateDT = CAST(CAST(@WorkDate as date) as smalldatetime)

-- Resolve project number -> project key
Select  @ProjectKey = ProjectKey
From    tProject (nolock)
Where   CompanyKey    = @CompanyKey
and     ProjectNumber = @ProjectNumber

If @ProjectKey is null
Begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Project not found: '' + @ProjectNumber, ''projectNumber'')

    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
End

-- Record-level access gate via spCheckAccess (tProject). Catches users trying
-- to log time against a project they can''t see (GL company / assignment).
Declare @AccessOK int
Exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey
If @AccessOK <> 1
Begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''You do not have access to this project.'', ''projectNumber'')

    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -103
End

-- Resolve task
If @TaskID is not null
Begin
    Select  @TaskKey = ISNULL(TaskKey, 0)
    From    tTask (nolock)
    Where   ProjectKey = @ProjectKey
    and     TaskID     = @TaskID

    If @TaskKey = 0
    Begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Task not found: '' + @TaskID, ''taskID'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    End
End
Else
Begin
    -- No task supplied - auto-detect using a 4-step fallback

    -- 1. User is assigned AND task dates bracket the work date
    Select  Top 1 @TaskKey = t.TaskKey
    From    tTask t (nolock)
    inner join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey
    Where   t.ProjectKey   = @ProjectKey
    and     tu.UserKey     = @UserKey
    and     t.PlanStart    <= @WorkDateDT
    and     t.PlanComplete >= @WorkDateDT
    Order by t.DisplayOrder

    -- 2. User is assigned on the project - any date
    If @TaskKey = 0
        Select  Top 1 @TaskKey = t.TaskKey
        From    tTask t (nolock)
        inner join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey
        Where   t.ProjectKey = @ProjectKey
        and     tu.UserKey   = @UserKey
        Order by t.DisplayOrder

    -- 3. Any task on the project whose dates bracket the work date
    If @TaskKey = 0
        Select  Top 1 @TaskKey = TaskKey
        From    tTask (nolock)
        Where   ProjectKey   = @ProjectKey
        and     PlanStart    <= @WorkDateDT
        and     PlanComplete >= @WorkDateDT
        Order by DisplayOrder

    -- 4. Nothing found - return an error
    If @TaskKey = 0
    Begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''No task could be determined for this project. Please provide a task ID.'', ''taskID'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    End
End

-- Resolve service
-- 1. Explicit service name supplied - match ServiceCode or Description
If @ServiceName is not null
Begin
    Select  Top 1 @ServiceKey = ISNULL(ServiceKey, 0)
    From    tService (nolock)
    Where   CompanyKey = @CompanyKey
    and     ISNULL(Active, 0) = 1
    and     (ServiceCode = @ServiceName or Description = @ServiceName)

    If @ServiceKey = 0
    Begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''NOT_FOUND'', ''Service not found: '' + @ServiceName + '' - Time entry will use the user''''s default service.'', ''serviceName'')
    End
End

-- 2. No explicit service (or service not found) - use the user default service
If @ServiceKey = 0
    Select  @ServiceKey = ISNULL(DefaultServiceKey, 0)
    From    tUser (nolock)
    Where   UserKey = @UserKey

-- Parse start/end time strings and combine with work date (HH:MM 24-hour)
If @StartTime is not null
    Set @StartTimeDT = TRY_CAST(CONVERT(varchar(10), @WorkDateDT, 101) + '' '' + @StartTime as smalldatetime)

If @EndTime is not null
    Set @EndTimeDT = TRY_CAST(CONVERT(varchar(10), @WorkDateDT, 101) + '' '' + @EndTime as smalldatetime)

-- Get or create the timesheet covering this work date
Exec sptTimeSheetGetByDate
    @CompanyKey         = @CompanyKey,
    @UserKey            = @UserKey,
    @Date               = @WorkDateDT,
    @TimeSheetKey       = @TimeSheetKey OUTPUT,
    @CreateNewTimeSheet = 1

If @TimeSheetKey is null
Begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Could not find or create a timesheet for the given date.'', ''workDate'')

    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
End

-- Insert the time entry via the standard procedure
Declare @InsertResult int
Exec @InsertResult = sptTimeInsert
    @TimeSheetKey = @TimeSheetKey,
    @UserKey      = @UserKey,
    @ProjectKey   = @ProjectKey,
    @TaskKey      = @TaskKey,
    @ServiceKey   = @ServiceKey,
    @WorkDate     = @WorkDateDT,
    @StartTime    = @StartTimeDT,
    @EndTime      = @EndTimeDT,
    @ActualHours  = @Hours,
    @PauseHours   = 0,
    @Comments     = @Comments,
    @RateLevel    = 1,
    @Source       = ''AI Assistant'',
    @TimeKey      = @TimeKey OUTPUT

If @InsertResult <> 1 or @TimeKey is null
Begin
    Declare @insertErrMsg nvarchar(200)
    Set @insertErrMsg =
        Case @InsertResult
            When -10  Then ''Work date is outside the timesheet period.''
            When -12  Then ''Work date is before the allowed date.''
            When -200 Then ''Start time is required.''
            When -201 Then ''End time is required.''
            When -202 Then ''Comments are required.''
            When -203 Then ''Task does not belong to the project.''
            When -625 Then ''No time entry allowed for this task.''
            Else ''Failed to add time entry. Error code: '' + Cast(@InsertResult as nvarchar(10))
        End

    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''INVALID_VALUE'', @insertErrMsg, ''general'')

    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -102
End

-- Return any warnings (e.g. service not found, fell back to default)
select errorType, errorCode, errorMessage, fieldName
from   #errors
where  errorType = ''warning''

-- Return success result
Select
     @TimeKey                               as timeKey
    ,CONVERT(varchar(10), @WorkDateDT, 101) as workDate
    ,@ProjectKey                            as projectKey
    ,t.TaskID                               as taskID
    ,s.Description                          as serviceName
    ,@Hours                                 as hours
From (Select 1 as n) dummy
left outer join tTask    t (nolock) on t.TaskKey    = @TaskKey
left outer join tService s (nolock) on s.ServiceKey = @ServiceKey

drop table #errors
return 1



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAITimeSubmitTimesheet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAITimeSubmitTimesheet]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAITimeSubmitTimesheet]
(
    @CompanyKey  int,
    @UserKey     int,
    @WorkDate    smalldatetime
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 03/10/26  QMD 26.03.15   Created for AI time tool
|| 05/25/26  AI  26.05.25   Added #errors / warnings scaffold; result-set shape is now
||                          [warnings, submitResult]. Caller submits their own timesheet only,
||                          so no record gate is needed (UserKey is implicit).
|| 05/28/26  AI  26.05.28   Added #errors / warnings result-set scaffold.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right billingusetimesheet.
*/

set nocount on

    -- ------------------------------------------------------------------
    -- Gating security: billingusetimesheet
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''billingusetimesheet''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (billingusetimesheet).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @TimeSheetKey   int       = null
    declare @CurrentStatus  smallint  = null
    declare @WorkDateDT     smalldatetime

    if @WorkDate is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''workDate is required.'', ''workDate'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -100
    end

    set @WorkDateDT = CAST(CAST(@WorkDate as date) as smalldatetime)

    exec sptTimeSheetGetByDate
         @CompanyKey         = @CompanyKey,
         @UserKey            = @UserKey,
         @Date               = @WorkDateDT,
         @TimeSheetKey       = @TimeSheetKey output,
         @CreateNewTimeSheet = 0

    -- Result set 1: warnings
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    -- Result set 2: submit outcome
    if @TimeSheetKey is null
    begin
        select 0 as submitted, ''No timesheet found for the given date.'' as message
        drop table #errors
        return 0
    end

    select @CurrentStatus = Status from tTimeSheet (nolock) where TimeSheetKey = @TimeSheetKey

    if @CurrentStatus >= 2
    begin
        select
             0 as submitted,
             case @CurrentStatus
                 when 2 then ''Timesheet is already submitted.''
                 when 4 then ''Timesheet is already approved.''
                 else ''Timesheet cannot be submitted in its current state.''
             end as message
        drop table #errors
        return 0
    end

    exec sptTimeSheetUpdateStatus
         @Approver       = @UserKey,
         @TimeSheetKey   = @TimeSheetKey,
         @Status         = 2,
         @SubmittedByKey = @UserKey

    select 1 as submitted, ''Timesheet submitted successfully.'' as message

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spImportBroadcastOrders]'
GO
IF OBJECT_ID(N'[dbo].[spImportBroadcastOrders]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spImportBroadcastOrders]
	@CompanyKey int,
	@PurchaseOrderTypeName varchar(200),
	@PurchaseOrderNumber varchar(30),
	@VendorID nvarchar(50),
	@StationID varchar(50),
	@MediaEstimateID varchar(50),
	@ProjectNumber varchar(100),
	@TaskID nvarchar(30),
	@ClassID varchar(50),
	@ItemID varchar(50),
	@Contact varchar(200),
	@Address1 varchar(100),
	@Address2 varchar(100),
	@Address3 varchar(100),
	@City varchar(100),
	@State varchar(50),
	@PostalCode varchar(20),
	@Country varchar(50),
	@DateCreated smalldatetime,
	@PODate smalldatetime,
	@OrderedBy varchar(200),
	@SpecialInstructions varchar(1000),
	@DeliveryInstructions varchar(1000),
	@Revision int,
	@ApprovedDate smalldatetime,
	@ApprovedByUserID varchar(100),
	@UserKey int,
	@oIdentity INT OUTPUT
AS --Encrypt

  /*
  || When     Who Rel          What
  || 07/24/09 GHL 10.5         Corrected addresses
  || 07/13/21 RLS 21.0.8.0     Changed @TaskID to nvarchar(30)
  || 11/12/21 RLS 21.12.19     (574346) Changed @VendorID to nvarchar(50)
  || 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
  */

	DECLARE	@PurchaseOrderTypeKey int,
			@VendorKey int,
			@ApprovedByKey int,
			@ItemKey int,
			@ClassKey int,
			@ProjectKey int,
			@TaskKey int,
			@CompanyMediaKey int,
			@MediaEstimateKey int
			
	SELECT	@oIdentity = 0
			
	IF EXISTS(SELECT 1 FROM tPurchaseOrder (nolock) 
		WHERE CompanyKey = @CompanyKey and PurchaseOrderNumber = @PurchaseOrderNumber and POKind = 2)
		Return -1

	if @PurchaseOrderTypeName is not null
	BEGIN
		SELECT	@PurchaseOrderTypeKey = PurchaseOrderTypeKey
		FROM	tPurchaseOrderType (nolock)
		WHERE	PurchaseOrderTypeName = @PurchaseOrderTypeName
		AND		CompanyKey = @CompanyKey
		if @PurchaseOrderTypeKey is null
			Return -3
	END
	ELSE
		Select @PurchaseOrderTypeKey = 0
		
	SELECT	@VendorKey = CompanyKey
	FROM	tCompany (nolock)
	WHERE	VendorID = @VendorID
	AND		OwnerCompanyKey = @CompanyKey
	
	IF @VendorKey IS NULL
		RETURN -2
		
	SELECT	@ApprovedByKey = UserKey
	FROM	tUser (nolock)
	WHERE	UserID = @ApprovedByUserID
	AND		CompanyKey = @CompanyKey
	
	IF @ApprovedByKey IS NULL
		SELECT	@ApprovedByKey = UserKey
		FROM	tUser (nolock)
		WHERE	SystemID = @ApprovedByUserID
		AND		CompanyKey = @CompanyKey
		
	Select @ProjectKey = ProjectKey 
	from tProject p (nolock) 
	inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	Where p.CompanyKey = @CompanyKey and ProjectNumber = @ProjectNumber and ps.ExpenseActive = 1
	if @ProjectKey is null
		return -4
		
	Select @TaskKey = TaskKey from tTask (nolock) Where ProjectKey = @ProjectKey and TaskID = @TaskID and MoneyTask = 1
	if @TaskKey is null
		return -5
		
	Select @ItemKey = ItemKey from tItem (nolock) Where CompanyKey = @ItemKey and ItemType = 2 and ItemID = @ItemID
	if @ItemKey is null and not @ItemID is null
		return -6
		
	Select @ClassKey = @ClassKey from tClass (nolock) Where CompanyKey = @CompanyKey and ClassID = @ClassID
	if @ClassKey is null and not @ClassID is null
		return -7
		
	Select @MediaEstimateKey = MediaEstimateKey from tMediaEstimate (nolock)
		Where CompanyKey = @CompanyKey and EstimateID = @MediaEstimateID
	if @MediaEstimateKey is null and not @MediaEstimateID is null
		return -8
		
	Select @CompanyMediaKey = CompanyMediaKey from tCompanyMedia (nolock) 
	Where CompanyKey = @CompanyKey and VendorKey = @VendorKey and MediaKind = 2 and StationID = @StationID
	if @CompanyMediaKey is null and not @StationID is null
		return -9
		
	IF @ApprovedByKey IS NULL
		SELECT	@ApprovedByKey = @UserKey
	
	if @DateCreated is null
		Select @DateCreated = GETDATE()
		
	if @Address1 is null
	BEGIN
	IF @CompanyMediaKey is null
		SELECT 
			@Address1 = case when pa.AddressKey is null then da.Address1 else pa.Address1 end ,
			@Address2 = case when pa.AddressKey is null then da.Address2  else pa.Address2 end ,
			@Address3 = case when pa.AddressKey is null then da.Address3  else pa.Address3 end ,
			@City = case when pa.AddressKey is null then da.City  else pa.City end ,
			@State = case when pa.AddressKey is null then da.State  else pa.State end , 
			@PostalCode = case when pa.AddressKey is null then da.PostalCode  else pa.PostalCode end ,
			@Country = case when pa.AddressKey is null then da.Country  else pa.Country end 
		FROM
			tCompany c (nolock)
		LEFT OUTER JOIN tAddress da (NOLOCK) ON c.DefaultAddressKey = da.AddressKey
		LEFT OUTER JOIN tAddress pa (NOLOCK) ON c.PaymentAddressKey = pa.AddressKey
		WHERE
			c.CompanyKey = @VendorKey
	ELSE
		SELECT 
			@Address1 = Address1,
			@Address2 = Address2,
			@Address3 = Address3,
			@City = City,
			@State = State, 
			@PostalCode = PostalCode,
			@Country = Country
		FROM
			tCompanyMedia (nolock)
		WHERE
			CompanyMediaKey = @CompanyMediaKey
	END
	
	
	INSERT tPurchaseOrder
		(
		CompanyKey,
		POKind,
		PurchaseOrderTypeKey,
		PurchaseOrderNumber,
		VendorKey,
		CompanyMediaKey,
		MediaEstimateKey,
		ProjectKey,
		TaskKey,
		ItemKey,
		ClassKey,
		Contact,
		Address1,
		Address2,
		Address3,
		City,
		State,
		PostalCode,
		Country,
		DateCreated,
		PODate,
		OrderedBy,
		SpecialInstructions,
		DeliveryInstructions,
		Revision,
		ApprovedDate,
		ApprovedByKey,
		Status,
		Closed,
		Downloaded,
		Printed
		)
	VALUES
		(
		@CompanyKey,
		1,
		@PurchaseOrderTypeKey,
		@PurchaseOrderNumber,
		@VendorKey,
		@CompanyMediaKey,
		@MediaEstimateKey,
		@ProjectKey,
		@TaskKey,
		@ItemKey,
		@ClassKey,
		@Contact,
		@Address1,
		@Address2,
		@Address3,
		@City,
		@State,
		@PostalCode,
		@Country,
		@DateCreated,
		@PODate,
		@OrderedBy,
		@SpecialInstructions,
		@DeliveryInstructions,
		ISNULL(@Revision, 0),
		@ApprovedDate,
		@ApprovedByKey,
		4,
		0,
		0,
		0
		)
	
	SELECT @oIdentity = @@IDENTITY


	RETURN 1
	



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesCreateClientInvoiceMassBilling]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCreateClientInvoiceMassBilling]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER procedure [dbo].[spFixedFeesCreateClientInvoiceMassBilling]
	(
	@CompanyKey int
	,@ClientKey int
	,@UserKey int
	,@InvoiceBy int -- 1 By Client, 2 By Client Parent
	,@EndDate smalldatetime -- for extra expenses
	,@InvoiceDate smalldatetime
	,@PostingDate smalldatetime
	,@CreateAsApproved int
	,@DefaultClassKey int
	,@AdvanceBilling int = 0 -- obsolete for 396483, part of the grid now
 
	-- for extra expenses
	,@OpenOrdersOnly int = 1
	,@Expense tinyint = 1-- Misc Costs, VDs and expenses on Credit Card Charges 
	,@ExpenseReport tinyint = 1 -- Expenses Reports/Receipts only 
	,@PO tinyint = 1
	,@IO tinyint = 1
	,@IOBeginDate datetime = null
	,@IOEndDate datetime = null
	,@BC tinyint = 1
	,@BCBeginDate datetime = null
	,@BCEndDate datetime = null

	,@OneLinePer varchar(20) = ''OneLine''-- OneLine, Item/Service
	,@NewInvoiceKey int = NULL OUTPUT
	)
as --Encrypt

 /*
  || When     Who Rel     What
  || 03/30/17 GHL 10.614  Creation to bill FF projects by client
  ||                      1 FF line per project, 1 TM line per project if ExpensesNotIncluded
  || 06/12/17 GHL 10.617  Added AdvanceBilling param (MN''s Todo)
  || 06/23/17 GHL 10.617  Do not include orders in extra expenses
  || 08/25/17 GHL 10.619 (360427) Do not create a FF line if BillAmount = 0 (could happen in mass billing FF
  ||                     if no budget with extra expenses, i.e. do not create a $0 budget amount line)
  || 10/02/17 GHL 10.621 (363756) Added default AR account from client
  || 11/22/17 GHL 10.622 (DEV1784 todo) Added checks before updating the billing schedule
  || 12/14/17 GHL 18.1.0 (DEV1784 Todo) Added flags to choose and pick which extra expenses should be included
  || 06/27/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
  || 10/03/18 GHL 18.920 (396483) Added logic for tBillingSchedule.AdvanceBill
  || 02/15/19 GHL 19.300 Similar to 446034 for Billing worksheets. Set correctly Entity/EntityKey
  || 01/27/20 GHL 20.030 (495024) Get the invoice template from the GL company if tPreference.LayoutFromGLCompany = 1
  || 07/14/21 GHL 21.080 (561725) Added line format Item/Service (in addition to 1 line) + cleanup the projects in the main temp table, prevents duplicates
  ||                     Also take in account the BillAs, and % Budget to claculate the bill amount for each item
  || 03/18/22 GHL 22.04.17 (590582) Added support for tProject.SetTaxableOnInvoice
  || 08/15/23 GAR 23.11.19 (DEV2605) Added InvoiceKey as an output parameter to pass back for Avalara tax calcs
  || 10/03/23 GAR 23.11.19 (652829) Moved the logging up into the project loop so each project would show up on the daily feed for the created invoice
  || 11/04/25 MCM 25.11.x (656423) Added Liability Account Key when calling sptInvoiceInsert
  || 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
  || 07/08/26 AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
 */

 /*
 The stored proc takes as inputs:
 - ClientKey
 - InvoiceBy -- 1 By Client, 2 By Client Parent
 - EndDate for extra expenses
 - The list of projects (in temp #projects) selected on the UI that contains:
    - ProjectKey
	- BillAmount
	- BillingScheduleKey
	- BillAs (% of Budget Total, % of Budget Remaining) for 561725
	- PercentBudget for 561725

  It will create 1 invoice per Client/Currency/GLCompany
  and 1 FF invoice line per project for FF amounts (1 line per project because we need the project on the line for future billing)
  and 1 TM invoice line per project for other expenses of projects where ExpensesNotIncluded = 1 (the project key will be on tInvoiceSummary and tInvoiceLine)

  for 561725:

  Old format -- 1 Line
  Project 1 FF
  Project 1 TM (for extras if Expenses Not included)
  Project 2 FF
  Project 2 TM 

  New format -- 1 Line per item/service
  Project 1
      Item 1 FF
	  Item 2 FF
  Project 1 TM
  Project 2
      Item 1 FF
	  Item 2 FF
  Project 2 TM

 */

	-- we use these vars and this temp if  OneLinePer is ''Item/Service''
	declare @DefaultDepartmentKey int

	-- copied from campaigns/billing/FixedFees.vb (used when expanding projects)
	-- this is an overkill but that will work for item/service line format
 	CREATE TABLE #line ( 
		Entity VARCHAR(50) NULL -- tItem, tService 
	   ,EntityKey INT NULL
	   ,EntityName VARCHAR(250) NULL
	   ,EntityDescription text null
	   ,BillAmt MONEY NULL
	   ,LineOrder INT NULL -- will not be used here
	   
	   ,EntityAccountKey int null
	   ,EntityDepartmentKey int null
	   ,EntityClassKey int null	
	   ,Taxable int null
	   ,Taxable2 int null
	  
	   ,InvoiceLineKey int null
	   ,Selected int null
	   ,LineKey int null -- will be used here
	   ,ParentLineKey int null
	   ,ProjectKey int null
	   ,LineType int null
	   ,GPFlag int null
		)

	-- vars for line info
	declare @ParentLineKey int
	declare @LineKey int
	declare @LineType int
	declare @LineEntity varchar(50)
	declare @LineEntityKey int
	declare @LineBillAmt money
	declare @LineOrder money
	declare @LineEntityName varchar(250)
	declare @LineAccountKey int 
	declare @LineDepartmentKey int
	declare @LineClassKey int 	
	declare @Taxable int
	declare @Taxable2 int
	-- end of vars used if  OneLinePer is ''Item/Service''

	-- Variables for logging 
	declare	@Action varchar(200),
		@ActionDate smalldatetime,
		@ActionBy varchar(500),
		@Comments varchar(4000),
		@Reference varchar(200),
		@SourceCompanyID varchar(100),
		@CampaignKey int 

	-- Variables for tPreference
	declare @ARAccountKey int
	declare @SalesAccountKey int
	declare @DefaultARAccountKey int
	declare @DefaultSalesAccountKey int
	declare @PostSalesUsingDetail int
	declare @BillMediaSeparately int
	declare @AdvBillAccountKey int
	declare @SetTaxableOnInvoice int
	declare @LayoutFromGLCompany int
	declare @GroupByBillingItem int
	declare @SecurityGroupKey int
	declare @LiabilityAccountKey int

	select @DefaultARAccountKey = DefaultARAccountKey
		  ,@DefaultSalesAccountKey = DefaultSalesAccountKey
		  ,@PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
		  ,@AdvBillAccountKey = AdvBillAccountKey
		  ,@SetTaxableOnInvoice = isnull(SetTaxableOnInvoice, 0)
		  ,@LayoutFromGLCompany = ISNULL(LayoutFromGLCompany,0)
	from   tPreference (nolock)
	where  CompanyKey = @CompanyKey

	select @BillMediaSeparately = Value
	from tAppSession (nolock) where Entity=''company'' and EntityKey = @CompanyKey and GroupID = ''massBilling'' and SessionID = ''BillMediaSeparately''
	select @BillMediaSeparately = isnull(@BillMediaSeparately, 0)
	select @BillMediaSeparately = 0 -- At this time, consider that it does not apply to FF projects

	select @SecurityGroupKey = SecurityGroupKey from tUser (nolock) where UserKey = @UserKey
	select @GroupByBillingItem = Value from tAppSession (nolock) where Entity = ''securitygroup'' and EntityKey = @SecurityGroupKey and GroupID = ''projectFFBilling'' and SessionID = ''GroupByBillingItem''
	if @@ROWCOUNT = 0
		select @GroupByBillingItem = Value from tAppSession (nolock) where Entity = ''company'' and EntityKey = @CompanyKey and GroupID = ''projectFFBilling'' and SessionID = ''GroupByBillingItem''
	
	IF @IOBeginDate is null
		select @IOBeginDate = ''1/1/1960''
	IF @BCBeginDate is null
		select @BCBeginDate = ''1/1/1960''
	IF @EndDate IS NULL
		SELECT @EndDate = ''01/01/2050''
	IF @IOEndDate is null
		select @IOEndDate = ''01/01/2050''
	IF @BCEndDate is null
		select @BCEndDate = ''01/01/2050''

	-- we need a ProjectID because we are going to process projecst by alpha number 
    create table #tProject (ProjectID int identity(1,1), ProjectKey int null, BillAmount money null, BillingScheduleKey int null,AdvanceBill int null, ExpensesNotIncluded int null
	, GLCompanyKey int null, CurrencyID varchar(10) null, CurrencyKey int null 
	, OfficeKey int null, ClassKey int null, ProjectName varchar(100) null
	, PercentBudget decimal(24,4) null, BillAs int null
	)
	
	IF @InvoiceBy = 1		
	-- for a particular client
	BEGIN	
		INSERT #tProject (ProjectKey, BillAmount, BillingScheduleKey, AdvanceBill, ExpensesNotIncluded, GLCompanyKey, CurrencyID, CurrencyKey, OfficeKey, ClassKey, ProjectName, PercentBudget, BillAs)  
		SELECT p.ProjectKey, isnull(b.BillAmount,0), isnull(b.BillingScheduleKey,0), isnull(b.AdvanceBill,0), ISNULL(p.ExpensesNotIncluded,0)
			,  ISNULL(p.GLCompanyKey, 0), p.CurrencyID, 0, p.OfficeKey, p.ClassKey, p.ProjectName, b.PercentBudget, b.BillAs
		FROM tProject p (NOLOCK) 
			inner join #projects b on p.ProjectKey = b.ProjectKey
		WHERE p.CompanyKey = @CompanyKey
		AND p.ClientKey = @ClientKey
		order by p.ProjectNumber
	END
	ELSE
	-- for a particular client parent
	BEGIN
		INSERT #tProject (ProjectKey, BillAmount, BillingScheduleKey, AdvanceBill, ExpensesNotIncluded, GLCompanyKey, CurrencyID, CurrencyKey, OfficeKey, ClassKey, ProjectName, PercentBudget, BillAs)  
		SELECT p.ProjectKey, isnull(b.BillAmount,0), isnull(b.BillingScheduleKey,0), isnull(b.AdvanceBill,0), ISNULL(p.ExpensesNotIncluded,0),  ISNULL(p.GLCompanyKey, 0), p.CurrencyID, 0, p.OfficeKey, p.ClassKey, p.ProjectName
			, b.PercentBudget, b.BillAs
		FROM tProject p (NOLOCK) 
			inner join #projects b on p.ProjectKey = b.ProjectKey
		WHERE p.CompanyKey = @CompanyKey
		AND ( p.ClientKey = @ClientKey
		      OR ClientKey IN (SELECT CompanyKey FROM tCompany (NOLOCK) 
		      WHERE ParentCompanyKey = @ClientKey
			  ))
		order by p.ProjectNumber
	END

	-- 561725 now delete the ones in the main/global temp table, there are not needed anymore, prevents duplicates
	delete #projects where ProjectKey in (select ProjectKey from #tProject)

	-- We must manufacture CurrencyKey to use in the loops
	-- CurrencyKey initialized at 0 -- Home Currency
	declare @CurrencyKey int
	declare @CurrencyID varchar(10)
	select @CurrencyID = ''''
	Select @CurrencyKey = 1
	while (1=1)
	begin
		select @CurrencyID = min(CurrencyID)
		from   #tProject
		where  CurrencyID is not null
		and    CurrencyID > @CurrencyID

		if @CurrencyID is null
			break

		update #tProject
		set    CurrencyKey = @CurrencyKey 
		where  CurrencyID = @CurrencyID

		select @CurrencyKey = @CurrencyKey + 1
	end

	-- get  client defaults  
	declare @BillingContact varchar(100)
	declare @PrimaryContactKey int 
	declare @SalesTaxKey int
	declare @SalesTax2Key int
	declare @PaymentTermsKey int
	declare @LayoutKey int
	declare @InvoiceTemplateKey int
	declare @ClientLayoutKey int
	declare @ClientInvoiceTemplateKey int
	declare @BillingAddressKey int
	declare @DueDays int
	declare @DueDate smalldatetime

	Select @ClientInvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
			, @SalesTaxKey = SalesTaxKey
			, @SalesTax2Key = SalesTax2Key
			, @ARAccountKey = ISNULL(DefaultARAccountKey, 0)
			, @SalesAccountKey = ISNULL(DefaultSalesAccountKey, 0)
			, @PaymentTermsKey = ISNULL(PaymentTermsKey, 0)
			, @ClientLayoutKey = LayoutKey
			, @BillingAddressKey = BillingAddressKey
			, @BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
			, @PrimaryContactKey = u.UserKey
		from tCompany cl (nolock) 
			left outer join tUser u (nolock) on cl.PrimaryContact = u.UserKey
		Where cl.CompanyKey = @ClientKey

	IF ISNULL(@PaymentTermsKey, 0) > 0
	BEGIN
		SELECT @DueDays = ISNULL(DueDays, 0)  
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @PaymentTermsKey
		 	
		SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate) 	
	END
	ELSE
		SELECT @DueDate = @InvoiceDate

	if isnull(@SalesAccountKey, 0) > 0
		select @DefaultSalesAccountKey = @SalesAccountKey

	if isnull(@ARAccountKey, 0) > 0
		select @DefaultARAccountKey = @ARAccountKey

	-- variables for invoice loop
	DECLARE @RetVal INT
			,@GLCompanyKey INT
			,@AdvanceBill INT
			,@ProjectID INT
			,@ProjectKey INT
			,@Error INT
			--,@NewInvoiceKey INT
			,@NewInvoiceLineKey INT
			,@ExpensesNotIncluded int
			,@NextTranNo varchar(100)
			,@InvoiceStatus int
			,@BillAmount money
			,@Entity varchar(50)
			,@EntityKey int
			,@ClassKey int
			,@OfficeKey int
			,@ProjectName varchar(100)
			,@PercentBudget decimal(24,4)
			,@BillAs int

	-- for extra expenses
	declare @ExpensesAmount money
		declare @MiscCostAmount money
		declare @ExpenseReceiptAmount money
		declare @VoucherAmount money
		declare @POAmount money
		declare @MediaAmount money
		declare @IOAmount money
		declare @BCAmount money

	SELECT @Error = 0
		   		
SELECT @AdvanceBill = -1
WHILE (1=1)
BEGIN
  SELECT @AdvanceBill = MIN(AdvanceBill) FROM #tProject
  WHERE AdvanceBill > @AdvanceBill
		 			
  IF @AdvanceBill is null
  BREAK
  								
	SELECT @GLCompanyKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @GLCompanyKey = MIN(GLCompanyKey) FROM #tProject
		WHERE GLCompanyKey > @GLCompanyKey
		AND   AdvanceBill = @AdvanceBill

		IF @GLCompanyKey IS NULL
			BREAK

		if @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
			select @LayoutKey = isnull(LayoutKey,0)
				  ,@InvoiceTemplateKey = isnull(InvoiceTemplateKey,0) 
			from   tGLCompany (nolock)
			where  GLCompanyKey = @GLCompanyKey 
		else
			select @LayoutKey = @ClientLayoutKey
				   ,@InvoiceTemplateKey = @ClientInvoiceTemplateKey
		
		SELECT @CurrencyKey = -1
		WHILE (1=1)
		BEGIN
			SELECT @CurrencyKey = MIN(CurrencyKey)
			FROM   #tProject 
			WHERE  GLCompanyKey   =  @GLCompanyKey
			AND    AdvanceBill    = @AdvanceBill	
			AND    CurrencyKey    >  @CurrencyKey
					
			IF @CurrencyKey IS NULL
				BREAK
					
			select @CurrencyID = CurrencyID
			from   #tProject
			where  GLCompanyKey = @GLCompanyKey
			and    CurrencyKey =  @CurrencyKey 
			AND    AdvanceBill    = @AdvanceBill

			--Set the AdvBillAcountKey
			SELECT 
				@AdvBillAccountKey = AdvBillAccountKey
			From
				tPreference (nolock)
			Where
				CompanyKey = @CompanyKey

			Set @LiabilityAccountKey = 
				Case 
					When @AdvanceBill = 1 Then @AdvBillAccountKey
					Else NULL
				End;


			/*		
			|| Create Invoice
			*/
				 
						exec @RetVal = sptInvoiceInsert
					@CompanyKey = @CompanyKey,
					@ClientKey = @ClientKey,
					@ContactName = @BillingContact,
					@PrimaryContactKey = @PrimaryContactKey,
					@AddressKey = @BillingAddressKey,
					@AdvanceBill = @AdvanceBill,
					@InvoiceNumber = null,
					@InvoiceDate = @InvoiceDate,
					@DueDate = @DueDate,
					@PostingDate = @PostingDate,
					@TermsKey = @PaymentTermsKey,
					@ARAccountKey = @DefaultARAccountKey,
					@ClassKey = @DefaultClassKey,
					@ProjectKey = @ProjectKey,
					@HeaderComment = null,
					@SalesTaxKey = @SalesTaxKey,
					@SalesTax2Key = @SalesTax2Key,
					@InvoiceTemplateKey = @InvoiceTemplateKey,
					@ApprovedByKey = @UserKey,
					@UserDefined1 = NULL,
					@UserDefined2 = NULL,
					@UserDefined3 = NULL,
					@UserDefined4 = NULL,
					@UserDefined5 = NULL,
					@UserDefined6 = NULL,
					@UserDefined7 = NULL,
					@UserDefined8 = NULL,
					@UserDefined9 = NULL,
					@UserDefined10 = NULL,
					@Downloaded = 0,
					@Printed = 0,
					@ParentInvoice = 0,
					@Emailed = 0,
					@CreatedByKey = @UserKey,
					@GLCompanyKey = @GLCompanyKey,
					@OfficeKey = null,
					@OpeningTransaction = 0,
					@LayoutKey = @LayoutKey,
					@CurrencyID = @CurrencyID,
					@ExchangeRate = 1,
					@RequestExchangeRate = 1, -- set exch rate
					@IsForRetainer = 0,
					@LiabilityAccountKey = @LiabilityAccountKey, -- **NEW PARAMETER ADDED**
					@oIdentity = @NewInvoiceKey OUTPUT -- Maps the output variable
				
					if @@ERROR <> 0 
						  begin
							return -1					  	
						  end
					if @RetVal <> 1 
						 begin
							return -1					   	
						  end
					
			If @CreateAsApproved = 1
			BEGIN
	
				--Check to see if the tInvoice Insert SP set the Invoice Number
				SELECT	@NextTranNo = InvoiceNumber
				FROM	tInvoice (nolock)
				WHERE	InvoiceKey = @NewInvoiceKey
	
				IF @NextTranNo IS NULL
				BEGIN
					--If the InvoiceNumber has not been set yet, get the next number
					DECLARE @TranType varchar(10) = CASE @AdvanceBilling WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

					EXEC spGetNextTranNo
						@CompanyKey,
						@TranType,
						@RetVal		      OUTPUT,
						@NextTranNo 	  OUTPUT	
		
					IF @RetVal <> 1
					BEGIN
						exec sptInvoiceDelete @NewInvoiceKey
						RETURN -1
					END
				END
	
				update tInvoice
				set	  ApprovedByKey = @UserKey
						,InvoiceStatus = 4 -- Approved
						,InvoiceNumber = @NextTranNo 
				where InvoiceKey = @NewInvoiceKey

				if @@ERROR <> 0 
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return -1					   	
				end
			END

			-- Now create one 1 FF invoice line per project
			-- We use ProjectID because I inserted projects by alpha order
			select @ProjectID = -1
			while (1=1)
			begin
				SELECT @ProjectID = MIN(ProjectID)
				FROM   #tProject 
				WHERE  GLCompanyKey   =  @GLCompanyKey	
				AND    CurrencyKey    =  @CurrencyKey
				AND    ProjectID      > @ProjectID

				IF @ProjectID is null
					break

				select @BillAmount = BillAmount
				      ,@ProjectKey = ProjectKey
					  ,@ExpensesNotIncluded = ExpensesNotIncluded
					  -- usual project defaults
					  ,@OfficeKey = OfficeKey
					  ,@ClassKey = ClassKey
					  ,@ProjectName = ProjectName
					  ,@PercentBudget = PercentBudget
					  ,@BillAs = isnull(BillAs,0)
				FROM   #tProject 
				WHERE  GLCompanyKey   =  @GLCompanyKey	
				AND    CurrencyKey    =  @CurrencyKey
				AND    ProjectID      =  @ProjectID
 

				if @ExpensesNotIncluded = 1
					-- Then this is labor, but we do not know which service 
					select @Entity = ''tService''   
						  ,@EntityKey = 0
					-- else they remain both NULL, we do not know if this is labor or expenses
				else
					select @Entity = null   
						  ,@EntityKey = null

				if @AdvanceBill = 1
					select @SalesAccountKey = @AdvBillAccountKey
				else
					select @SalesAccountKey = @DefaultSalesAccountKey
				
				/*
				 this is the old line format OneLinePer = ''One Line''
				*/

				-- projects with no budgets will have BillAmount = 0
				if @BillAmount != 0 and @OneLinePer != ''Item/Service''
				begin
					--create single invoice line for FF or budget amount
					exec @RetVal = sptInvoiceLineInsertMassBilling
								   @NewInvoiceKey				-- Invoice Key
								  ,@ProjectKey					-- ProjectKey
								  ,NULL							-- TaskKey
								  ,@ProjectName					-- Line Subject
								  ,null                 		-- Line description
								  ,1                    		-- Bill From 
								  ,1							-- Quantity
								  ,@BillAmount					-- Unit Amount
								  ,@BillAmount					-- Line Amount
								  ,2							-- line type = detail
								  ,0							-- parent line key
								  ,@SalesAccountKey				-- Default Sales AccountKey
								  ,@ClassKey                    -- Class Key
								  ,0							-- Taxable
								  ,0							-- Taxable2
								  ,NULL							-- Work TypeKey
								  ,0							-- PostInDetail
								  ,@Entity						-- Entity
								  ,@EntityKey					-- EntityKey
								  ,@OfficeKey
								  ,null  --@DepartmentKey
								  ,@NewInvoiceLineKey output
					if @RetVal <> 1 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1					   	
					  end
					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1					   	
					  end					  
				  end 

				/*
				-- this is the new line format OneLinePer = ''Item/Service'' 7/14/21
				*/

				-- If by Item/Service
				if @BillAmount != 0 and @OneLinePer = ''Item/Service''
				begin
					--create summary line for project
					exec @RetVal = sptInvoiceLineInsertMassBilling
								   @NewInvoiceKey				-- Invoice Key
								  ,@ProjectKey					-- ProjectKey
								  ,NULL							-- TaskKey
								  ,@ProjectName					-- Line Subject
								  ,null                 		-- Line description
								  ,1                    		-- Bill From 
								  ,0							-- Quantity
								  ,0					-- Unit Amount
								  ,0					-- Line Amount
								  ,1							-- line type = summary
								  ,0							-- parent line key
								  ,@SalesAccountKey				-- Default Sales AccountKey
								  ,@ClassKey                    -- Class Key
								  ,0							-- Taxable
								  ,0							-- Taxable2
								  ,NULL							-- Work TypeKey
								  ,0							-- PostInDetail
								  ,@Entity						-- Entity
								  ,@EntityKey					-- EntityKey
								  ,@OfficeKey
								  ,null  --@DepartmentKey
								  ,@NewInvoiceLineKey output
					if @RetVal <> 1 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1					   	
					  end
					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1					   	
					  end
					  
					  select @ParentLineKey = @NewInvoiceLineKey 
					   
					  truncate table #line 
					  exec spFixedFeesCreateInvoiceLinesBillAs 0, 0, @ProjectKey, @NewInvoiceLineKey, @BillAmount, @PercentBudget, @BillAs
	
					  -- if we did not create new lines, keep the old one and make it a detail line
					  if (select count(*) from #line) = 0
					  begin
							update tInvoiceLine 
							set TotalAmount = @BillAmount
								,LineType = 2 -- detail 
							where InvoiceLineKey = @ParentLineKey
					  end

					  -- get defaults
					  update #line
						set    #line.EntityName = i.ItemName
							  ,#line.EntityDescription = i.StandardDescription
							  ,#line.EntityAccountKey = i.SalesAccountKey
							  ,#line.EntityDepartmentKey = i.DepartmentKey
							  ,#line.EntityClassKey = i.ClassKey
							  ,#line.Taxable = i.Taxable	
							  ,#line.Taxable2 = i.Taxable2	
						from   tItem i (nolock)
						where  #line.EntityKey = i.ItemKey
						and    #line.Entity = ''tItem''
			
						update #line
						set    #line.EntityName = s.Description
							  ,#line.EntityDescription = s.InvoiceDescription
							  ,#line.EntityAccountKey = s.GLAccountKey
							  ,#line.EntityDepartmentKey = s.DepartmentKey
							  ,#line.EntityClassKey = s.ClassKey
							  ,#line.Taxable = s.Taxable	
							  ,#line.Taxable2 = s.Taxable2	
						from   tService s (nolock)
						where  #line.EntityKey = s.ServiceKey
						and    #line.Entity = ''tService''
			
						-- departments			
						update #line
						set    #line.EntityDepartmentKey = null
						where  #line.EntityDepartmentKey = 0

						update #line
						set    #line.EntityDepartmentKey = @DefaultDepartmentKey
						where  #line.EntityDepartmentKey is null
			
						-- classes
						update #line
						set    #line.EntityClassKey = null
						where  #line.EntityClassKey = 0
				
						update #line
						set    #line.EntityClassKey = @ClassKey -- will come from the project
						where  #line.EntityClassKey is null

						/*
						if @RequireClasses = 1 
						begin	
							if exists (select 1 from #line where EntityClassKey is null and isnull(LineType, 2) = 2)
								return -1	
						end
						*/

						-- sales account	
						update #line
						set    #line.EntityAccountKey = null
						where  #line.EntityAccountKey = 0

						if @AdvanceBill = 1
						begin
							if @AdvBillAccountKey is not null
								update #line
								set    #line.EntityAccountKey = @AdvBillAccountKey
				
							update #line
							set    #line.EntityAccountKey = @DefaultSalesAccountKey
							where  #line.EntityAccountKey = null
						end		
						else
						begin
							update #line
							set    #line.EntityAccountKey = @DefaultSalesAccountKey
							where  #line.EntityAccountKey = null
						end	

						update #line
						set    #line.EntityName = ''[No Item]''
							  ,#line.EntityDescription =''[No Item]''
						where  #line.Entity = ''tItem''
						and    #line.EntityKey = 0	   

						update #line
						set    #line.EntityName = ''[No Service]''
							  ,#line.EntityDescription =''[No Service]''
						where  #line.Entity = ''tService''
						and    #line.EntityKey = 0	   

						-- now create the lines
						select @LineKey = -1
						while (1=1)
						begin
							select @LineKey = min(LineKey)
							from   #line
							where  LineKey > @LineKey

							if @LineKey is null
								break
			
							select @LineEntity = Entity
									,@LineEntityKey = EntityKey
									,@LineEntityName = EntityName
									,@LineBillAmt = BillAmt	
									,@LineAccountKey = EntityAccountKey 
									,@LineDepartmentKey = EntityDepartmentKey
									,@LineClassKey = EntityClassKey
									,@Taxable = Taxable
									,@Taxable2 = Taxable2
							from   #line
							where  LineKey = @LineKey
				
							--create invoice line
							exec @RetVal = sptInvoiceLineInsertMassBilling
											@NewInvoiceKey				-- Invoice Key
											,@ProjectKey							-- ProjectKey
											,NULL							-- TaskKey
											,@LineEntityName				-- Line Subject
											,null                 		-- Line description
											,1                    		-- Bill From 
											,1							-- Quantity
											,@LineBillAmt					-- Unit Amount
											,@LineBillAmt					-- Line Amount
											,2							-- line type
											,@ParentLineKey					-- parent line key
											,@LineAccountKey				-- Default Sales AccountKey
											,@LineClassKey                -- Class Key
											,@Taxable						-- Taxable
											,@Taxable2					-- Taxable2
											,NULL							-- Work TypeKey -- will be updated by the grouping by bi
											,0							-- PostInDetail
											,@LineEntity					-- Entity
											,@LineEntityKey				-- EntityKey
											,@OfficeKey
											,@LineDepartmentKey
											,@NewInvoiceLineKey output
				
								if @RetVal <> 1 
								begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1
								end				
			
								update #line 
								set    InvoiceLineKey = @NewInvoiceLineKey
								where  LineKey = @LineKey
					
							end -- end loop on #line

							-- can only do it here because it is a text field
							update tInvoiceLine
							set    tInvoiceLine.LineDescription = #line.EntityDescription
							from   #line
							where  tInvoiceLine.InvoiceLineKey = #line.InvoiceLineKey  	
							and    tInvoiceLine.InvoiceKey = @NewInvoiceKey

							if @GroupByBillingItem = 1 and (select count(*) from #line) > 0
							begin
								exec sptInvoiceLineGroupFFByBillingItem @NewInvoiceKey, @ParentLineKey, 0 --CalcInvoiceOrder =  0 
							end

				  end -- if by Item/Service


				  -- Only Bill extras if this is not an advance bill
				  if @ExpensesNotIncluded = 1 And @AdvanceBill = 0
				  begin
					if @Expense = 1
					select @MiscCostAmount = ISNULL(SUM(mc.BillableCost), 0)
								FROM	tMiscCost mc (NOLOCK)
								WHERE	mc.ProjectKey = @ProjectKey
								AND     mc.InvoiceLineKey IS NULL
								AND     ISNULL(mc.WriteOff, 0) = 0
								AND     mc.ExpenseDate <= @EndDate
								AND		ISNULL(mc.OnHold, 0) = 0

					 if @ExpenseReport = 1
					 select @ExpenseReceiptAmount = ISNULL(SUM(er.BillableCost), 0)
								FROM	tExpenseReceipt er (NOLOCK), tExpenseEnvelope en (nolock)
								WHERE	er.ProjectKey = @ProjectKey
								AND		er.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
								AND		en.Status = 4
								AND     er.InvoiceLineKey IS NULL
								AND		ISNULL(er.WriteOff, 0) = 0
								AND     er.ExpenseDate <= @EndDate
								AND		ISNULL(er.OnHold, 0) = 0
								AND		er.VoucherDetailKey IS NULL
								/* projects with EBWS are excluded in spMassBillingGetFF
								AND		er.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tExpenseReceipt''  
												AND   b.ProjectKey = er.ProjectKey 
												AND   b.Status < 5				  											
												)
								*/

						if @Expense = 1
						SELECT @VoucherAmount = ISNULL(SUM(vd.BillableCost), 0)
								FROM	tVoucherDetail vd (NOLOCK) ,tVoucher v  (NOLOCK)
								WHERE	vd.VoucherKey   = v.VoucherKey
								AND		vd.ProjectKey = @ProjectKey
								AND     vd.InvoiceLineKey IS NULL
								AND		ISNULL(vd.WriteOff, 0) = 0
								AND		v.Status = 4
								AND     v.InvoiceDate <= @EndDate
								AND		ISNULL(vd.OnHold, 0) = 0

						if @PO = 1
						SELECT @POAmount = ISNULL(SUM(pod.BillableCost), 0)
								FROM	tPurchaseOrderDetail pod (NOLOCK)
										,tPurchaseOrder po (NOLOCK)
								WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
								AND		pod.ProjectKey = @ProjectKey
								AND		pod.InvoiceLineKey IS NULL
								AND		ISNULL(pod.AppliedCost, 0) = 0
								AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
								AND		ISNULL(pod.AmountBilled, 0) = 0
								AND		po.PODate <= @EndDate
								AND		po.Status = 4
								AND		po.POKind = 0
								AND		ISNULL(pod.OnHold, 0) = 0

						if @IO = 1
						SELECT @IOAmount =  isnull(SUM(Case ISNULL(po.BillAt, 0) 
									When 0 then isnull(BillableCost,0)
									When 1 then isnull(PTotalCost,isnull(TotalCost,0))
									When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ),0)
								FROM	tPurchaseOrderDetail pod (NOLOCK)
										,tPurchaseOrder po (NOLOCK)
								WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
								AND		pod.ProjectKey = @ProjectKey
								AND		pod.InvoiceLineKey IS NULL
								AND		ISNULL(pod.AppliedCost, 0) = 0
								AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
								AND		ISNULL(pod.AmountBilled, 0) = 0
								AND		pod.DetailOrderDate >= @IOBeginDate
								AND		pod.DetailOrderDate <= @IOEndDate
								AND		po.Status = 4
								AND		po.POKind = 1
								AND		ISNULL(pod.OnHold, 0) = 0
						
						if @BC = 1
						SELECT @BCAmount =  isnull(SUM(Case ISNULL(po.BillAt, 0) 
									When 0 then isnull(BillableCost,0)
									When 1 then isnull(PTotalCost,isnull(TotalCost,0))
									When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ),0)
								FROM	tPurchaseOrderDetail pod (NOLOCK)
										,tPurchaseOrder po (NOLOCK)
								WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
								AND		pod.ProjectKey = @ProjectKey
								AND		pod.InvoiceLineKey IS NULL
								AND		ISNULL(pod.AppliedCost, 0) = 0
								AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
								AND		ISNULL(pod.AmountBilled, 0) = 0
								AND		pod.DetailOrderDate >= @BCBeginDate
								AND		pod.DetailOrderDate <= @BCEndDate
								AND		po.Status = 4
								AND		po.POKind = 2
								AND		ISNULL(pod.OnHold, 0) = 0
						
					select @ExpensesAmount = isnull(@MiscCostAmount, 0) + isnull(@ExpenseReceiptAmount, 0) + isnull(@VoucherAmount, 0) + isnull(@POAmount, 0) + isnull(@IOAmount, 0) + isnull(@BCAmount, 0)

					if @ExpensesAmount != 0
					begin
							exec @RetVal = sptInvoiceLineInsertMassBilling
								   @NewInvoiceKey				-- Invoice Key
								  ,@ProjectKey					-- ProjectKey
								  ,null							-- TaskKey
								  ,@ProjectName 				-- Line Subject
								  ,''Other Expenses''             -- Line description
								  ,2                    		-- Bill From 
								  ,1							-- Quantity
								  ,@ExpensesAmount				-- Unit Amount
								  ,@ExpensesAmount				-- Line Amount
								  ,2							-- line type
								  ,0							-- parent line key
								  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
								  ,@DefaultClassKey                    -- Class Key
								  ,0							-- Taxable
								  ,0							-- Taxable2
								  ,NULL							-- Work TypeKey
								  ,@PostSalesUsingDetail							-- PostInDetail
								  ,NULL							-- Entity
								  ,NULL							-- EntityKey
								  ,@OfficeKey
								  ,null							--@DepartmentKey -- may need a department if department required
								  ,@NewInvoiceLineKey output

							if @NewInvoiceLineKey <= 0
							begin
								exec sptInvoiceDelete @NewInvoiceKey
								return -1
							end

							if @Expense = 1
							begin
								update tMiscCost
									set    InvoiceLineKey = @NewInvoiceLineKey
										,AmountBilled = BillableCost
									WHERE	ProjectKey = @ProjectKey
								AND     InvoiceLineKey IS NULL
								AND     ISNULL(WriteOff, 0) = 0
								AND     ExpenseDate <= @EndDate
								AND		ISNULL(OnHold, 0) = 0

								if @@ERROR <> 0 
									begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1				   	
									end
							end

							if @ExpenseReport = 1
							begin
								update tExpenseReceipt
									set    InvoiceLineKey = @NewInvoiceLineKey
										,AmountBilled = BillableCost
									FROM	tExpenseEnvelope en (nolock)
								WHERE	tExpenseReceipt.ProjectKey = @ProjectKey
								AND		tExpenseReceipt.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
								AND		en.Status = 4
								AND     tExpenseReceipt.InvoiceLineKey IS NULL
								AND		ISNULL(tExpenseReceipt.WriteOff, 0) = 0
								AND     tExpenseReceipt.ExpenseDate <= @EndDate
								AND		ISNULL(tExpenseReceipt.OnHold, 0) = 0
								AND		tExpenseReceipt.VoucherDetailKey IS NULL

								if @@ERROR <> 0 
									begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1				   	
									end
							end

							if @Expense = 1
							begin
								update tVoucherDetail
								set		InvoiceLineKey = @NewInvoiceLineKey 
										,AmountBilled = BillableCost
								FROM	tVoucher v  (NOLOCK)
								WHERE	tVoucherDetail.VoucherKey   = v.VoucherKey
								AND		tVoucherDetail.ProjectKey = @ProjectKey
								AND     tVoucherDetail.InvoiceLineKey IS NULL
								AND		ISNULL(tVoucherDetail.WriteOff, 0) = 0
								AND		v.Status = 4
								AND     v.InvoiceDate <= @EndDate
								AND		ISNULL(tVoucherDetail.OnHold, 0) = 0

								if @@ERROR <> 0 
									begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1				   	
									end
							end


							if @PO = 1
							begin
								update tPurchaseOrderDetail
								set		InvoiceLineKey = @NewInvoiceLineKey
										,tPurchaseOrderDetail.AccruedCost = 
										CASE 
											WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
											ELSE 0
										END
										,AmountBilled = isnull(BillableCost,0)
								FROM	tPurchaseOrder po (NOLOCK)
								WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
								AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
								AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
								AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
								AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
								AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
								AND		po.PODate <= @EndDate
								AND		po.Status = 4
								AND		po.POKind = 0
								AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0

								if @@ERROR <> 0 
									begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1				   	
									end
							end

							if @IO = 1
							begin
								update tPurchaseOrderDetail
								set		InvoiceLineKey = @NewInvoiceLineKey
										,tPurchaseOrderDetail.AccruedCost = 
										CASE 
											WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
											ELSE 0
										END
										,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
										When 0 then isnull(BillableCost,0)
										When 1 then isnull(PTotalCost,isnull(TotalCost,0))
										When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
								FROM	tPurchaseOrder po (NOLOCK)
								WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
								AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
								AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
								AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
								AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
								AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
								AND		tPurchaseOrderDetail.DetailOrderDate >= @IOBeginDate
								AND		tPurchaseOrderDetail.DetailOrderDate <= @IOEndDate
								AND		po.Status = 4
								AND		po.POKind = 1
								AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0

								if @@ERROR <> 0 
									begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1				   	
									end
							end

							if @BC = 1
							begin
								update tPurchaseOrderDetail
								set		InvoiceLineKey = @NewInvoiceLineKey
										,tPurchaseOrderDetail.AccruedCost = 
										CASE 
											WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
											ELSE 0
										END
										,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
										When 0 then isnull(BillableCost,0)
										When 1 then isnull(PTotalCost,isnull(TotalCost,0))
										When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
								FROM	tPurchaseOrder po (NOLOCK)
								WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
								AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
								AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
								AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
								AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
								AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
								AND		tPurchaseOrderDetail.DetailOrderDate >= @BCBeginDate
								AND		tPurchaseOrderDetail.DetailOrderDate <= @BCEndDate
								AND		po.Status = 4
								AND		po.POKind = 2
								AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0

								if @@ERROR <> 0 
									begin
									exec sptInvoiceDelete @NewInvoiceKey
									return -1				   	
									end
							end

					   end -- expenses amount <> 0


				  end -- end Expenses Not Included

				-- Now logging
				if @NewInvoiceLineKey > 0
				begin
					select @Entity = ''Client Invoice Line'',@EntityKey = @NewInvoiceLineKey,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

					select @Reference = i.InvoiceNumber
							,@SourceCompanyID = c.CustomerID
					from   tInvoiceLine il (nolock)
						left outer join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
						left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey						
					where  il.InvoiceLineKey = @NewInvoiceLineKey					

					select @Reference = isnull(@Reference,'''')
							,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
					-- the Invoice number may be missing if the user assign #s at approval time
					if len(@Reference) > 0
						select @Comments = ''Invoice '' + @Reference + '' was generated through fixed fee mass billing by client''
					else
						select @Comments = ''Invoice was generated through fixed fee mass billing  by client''

					select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

					exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey
				end -- end logging

			end -- end project loop			

			-- Now logging
			if @NewInvoiceKey >0
			begin
				select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

				select @Reference = i.InvoiceNumber
						,@SourceCompanyID = c.CustomerID
				from   tInvoice i (nolock)
					left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
				where  i.InvoiceKey = @NewInvoiceKey

				select @Reference = isnull(@Reference,'''')
						,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
				-- the Invoice number may be missing if the user assign #s at approval time
				if len(@Reference) > 0
					select @Comments = ''Invoice '' + @Reference + '' was generated through fixed fee mass billing by client''
				else
					select @Comments = ''Invoice was generated through fixed fee mass billing  by client''

				select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

				exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, 0, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey
			end -- end logging

			-- This will force the Taxable fields if the pref or the project requires them
			exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

			-- recalc the amounts in the header  
			exec sptInvoiceRecalcAmounts @NewInvoiceKey 
	
			-- Calculate the line order and position
			exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0

			-- now do rollups on projects
			 exec sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey, 1, 0

			 -- now mark the billing schedule as processed
			 --if @AdvanceBill = 0
			 --begin
				 update tBillingSchedule
				 set    tBillingSchedule.InvoiceKey = @NewInvoiceKey
				       ,tBillingSchedule.BilledComment = case when isnull(b.PercentBudget, 0) > 0
				                                              then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(b.PercentBudget, 0) * (
				                                                       case when isnull(b.ExpensesNotIncluded, 0) = 0
				                                                            then isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0) + isnull(p.EstExpenses, 0) + isnull(p.ApprovedCOExpense, 0)
				                                                            else isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0)
				                                                       end) / 100.00, 2), ''N2'')
				                                              else null end
				 from   #tProject b
				 join   tProject p (nolock) on p.ProjectKey = b.ProjectKey
				 where  tBillingSchedule.BillingScheduleKey = b.BillingScheduleKey
				 and	b.GLCompanyKey = @GLCompanyKey
				 and    b.CurrencyKey = @CurrencyKey
				 and    isnull(b.AdvanceBill,0) = @AdvanceBill

				 and    tBillingSchedule.BillingKey is null
				 and    tBillingSchedule.InvoiceKey is null

			 --end

		END -- end currency
	END --  end GL company
		
END -- Advance Bill loop
				
	return 1
	
					
					
														
	

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesCreateProjectInvoiceMassBilling]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCreateProjectInvoiceMassBilling]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spFixedFeesCreateProjectInvoiceMassBilling]
(
	@ProjectKey int
	,@CompanyKey int
	,@UserKey int
	,@PercentBudget decimal(24,4) -- if 40 %, or = 40 , Bill Amount = (Budget Amount * 40.00) / 100.00 
	,@InvoiceAmount money   -- this a % of the budget amount 
	,@EndDate smalldatetime -- End Date for extra expenses
	,@InvoiceDate smalldatetime
	,@PostingDate smalldatetime
	,@CreateAsApproved int
	,@DefaultClassKey int
	,@BillingScheduleKey int
	,@AdvanceBilling int = 0
	,@BillAs int = 0 -- 0 % of Remaining, 1 % of Total

	-- for extra expenses
	,@OpenOrdersOnly int = 1
	,@Expense tinyint = 1-- Misc Costs, VDs and expenses on Credit Card Charges 
	,@ExpenseReport tinyint = 1 -- Expenses Reports/Receipts only 
	,@PO tinyint = 1
	,@IO tinyint = 1
	,@IOBeginDate datetime = null
	,@IOEndDate datetime = null
	,@BC tinyint = 1
	,@BCBeginDate datetime = null
	,@BCEndDate datetime = null

	,@InvoiceBy varchar(20) = ''Item/Service'' -- OneLine, Task, Item/Service, BillingItem
	)
as --Encrypt

SET NOCOUNT ON

	/*
    || When     Who Rel    What
    || 03/10/16 GHL 10.602 Creation for wjapp FF mass billing
	||                     wrapper to spFixedFeesCreateProjectInvoice
	|| 07/21/16 GHL 10.606 Added action logging for MN''s ToDo 
	|| 10/19/16 GHL 10.609 Added patch when PercentBudget = 0
	|| 12/26/16 GHL 10.611 (325400) Added patch when PercentBudget = Bill Amount / Budget Amount < 0.0001 
	||                     (325380) Added logging in the case when expenses are included
	|| 01/04/17 GHL 10.611 Only take labor budget (entity = tService) if ExpensesNotIncluded (todo mass billing FF)
	|| 03/31/17 GHL 10.614 (334769) Do not submit for approval if the invoice is not created as approved
	|| 06/12/17 GHL 10.617 Added AdvanceBilling param (MN''s Todo)
	|| 10/30/17 GHL 10.621 (DEV1784 todo) Added logic for tBillingSchedule.DollarAmount (alternative to PercentBudget)
	||                     If there is a rounding error, add the penny to a line
	||                     Note: the 2 InvoiceBy values are ''Item/Service'' and ''OneLine''
	|| 11/22/17 GHL 10.622 (DEV1784 todo) Added checks before updating the billing schedule
	|| 12/14/17 GHL 18.1.0 (DEV1784 Todo) Added flags to choose and pick which extra expenses should be included
	|| 01/03/17 GHL 18.1.0 (378287) Added support for % of Total, % of Remaining
    ||                      This helps when we have multiple estimates (see design doc) 
	|| 06/26/18 GHL 18.7.0 (402606) Propagate tBillingSchedule.Comments to tInvoice.HeaderComments
	|| 06/27/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
	|| 07/27/18 GHL 18.800 (384542) Reuse the same settings than in FF project billing when creating the invoice
	|| 10/03/18 GHL 18.920 (396483) Now that we have a flag tBillingSchedule.AdvanceBill, update the tBillingSchedule
	||                     even if AdvanceBilling = 0
	|| 05/08/20 GHL 20.060 (467592) Added InvoiceBy parameter to support multiple line formats in addition to ''Item/Service''
	||                     Also added @UpdateLabor when calling the sp creating the invoice so that the lines will be flagged
	||                     as labor if @ExpensesNotIncluded
	|| 10/19/20 GHL 20.110 (533948) Increased size of EntityName to 500 from 250 to handle long task names
	|| 10/04/21 GHL 21.1100 (573215) If BillingScheduleKey passed, check if there is an invoice already to fight duplicate invoices
	|| 01/31/22 GHL 22.0200 (586090) Check for duplicate invoice for that project/day
	|| 03/18/22 GHL 22.04.17 (590582) Added support for tProject.SetTaxableOnInvoice
	|| 06/20/22 GHL 22.07.00 (603509) When checking for duplicate invoices, also check the status of the billing schedule
	|| 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
	|| 07/08/26 AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
	|| 07/07/26 MFT 26.08.01 (729267) Added BillExpensesByItem (Fixed Fee expenses billed one line per Item)
	|| 07/28/26 MFT 26.08.01 (729267) BillExpensesByItem: added a "Expenses" summary line
	*/

	declare @NewInvoiceKey int
	declare @NewInvoiceLineKey int
	declare @NextTranNo varchar(100)
	declare @InvoiceStatus int
	declare @ApprovedByKey int
	declare @RetVal int
	declare @GroupByBillingItem int
	declare @OfficeKey int
	declare @BudgetAmount money
	declare @PercentBudgetHiPrecision decimal(24,8) -- when we need more that 4 decimal points
	declare @ExpensesNotIncluded int
	declare @BillExpensesByItem int
	declare @AdvBillAccountKey int
	declare @DefaultSalesAccountKey int
	declare @PostSalesUsingDetail int
	declare @SalesAccountKey int
	declare @RoundingError money
	declare @SetTaxableOnInvoice int
		
	declare @EntityName	VARCHAR(250)
	declare @LineOrder int

	-- used when @BillExpensesByItem = 1 (extra expenses billed one line per Item)
	declare @CurItemKey int
	declare @CurEntityKey int
	declare @CurItemName VARCHAR(250)
	declare @CurAmount money
	declare @CurTaxable tinyint
	declare @CurTaxable2 tinyint
	declare @CurLineOrder int
	declare @ExpensesLineKey int   -- parent "Expenses" summary line that groups the per-Item lines

	-- fight duplicate invoices
	if isnull(@BillingScheduleKey, 0) > 0
	begin
		if exists (select 1 from tBillingSchedule -- no NOLOCK
		where BillingScheduleKey = @BillingScheduleKey
		and InvoiceKey > 0)
			return 1
	end

	declare @ClientKey int
	select @ClientKey = ClientKey from tProject (nolock) where ProjectKey = @ProjectKey
	
	--Issue 363995: Instead of using InvoiceDate for the comparison, use the DateCreated
	declare @DateCreated smalldatetime
	select @DateCreated = convert (varchar(10), getdate(), 101)

	-- Issue 603509: Check also the billing schedule status
	-- allow if the billing schedule is free (is that safe to prevent duplicates) 

	declare @CheckForDuplicates int 
	select @CheckForDuplicates = 1

	if exists (select 1 from tBillingSchedule (nolock)
		where  ProjectKey = @ProjectKey 
		and    InvoiceKey is null -- this means that the Billing Schedule step is free
		and    BillingKey is null
		and    NextBillDate <= @DateCreated
		and    BillingScheduleKey = @BillingScheduleKey
		)
		select @CheckForDuplicates = 0

	-- note: if there is no billing schedule, @CheckForDuplicates will be 1, we will check for duplicate invoices

	if  @CheckForDuplicates = 1 and exists (select 1 from tInvoice (nolock) 
		where ClientKey = @ClientKey 
		and ProjectKey = @ProjectKey
		and convert (varchar(10), DateCreated, 101) = @DateCreated 
		and AdvanceBill = 0
		)
		return 1

	if isnull(@InvoiceBy, '''') = ''''
		select @InvoiceBy = ''Item/Service''

	-- get company preferences
	Select @PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
			,@DefaultSalesAccountKey = DefaultSalesAccountKey
			,@AdvBillAccountKey = AdvBillAccountKey
			,@SetTaxableOnInvoice = isnull(SetTaxableOnInvoice, 0)
	From tPreference (nolock)
	Where CompanyKey = @CompanyKey

	if @AdvanceBilling = 1 and isnull(@AdvBillAccountKey, 0) = 0
		return -2

	if @AdvanceBilling = 1
		select @SalesAccountKey = @AdvBillAccountKey
	else
		select @SalesAccountKey = @DefaultSalesAccountKey

	select @PercentBudgetHiPrecision = @PercentBudget

	-- @ExpensesNotIncluded is an important flag, if expenses are not included
	-- the FF invoice lines will be flagged as Labor so that we can compare correctly to the labor budget
	select @ExpensesNotIncluded = isnull(ExpensesNotIncluded, 0)
		      ,@BillExpensesByItem = isnull(BillExpensesByItem, 0)
		      ,@OfficeKey = OfficeKey
	from tProject (nolock) where ProjectKey = @ProjectKey

	-- Variables for logging 
	declare	@Entity varchar(50),
		@EntityKey int,
		@Action varchar(200),
		@ActionDate smalldatetime,
		@ActionBy varchar(500),
		@Comments varchar(4000),
		@Reference varchar(200),
		@SourceCompanyID varchar(100),
		@CampaignKey int 


	CREATE TABLE #line ( Entity	VARCHAR(50) NULL,
		EntityKey			INT NULL, 
		EntityName			VARCHAR(500) NULL, -- will hold entity name and task name  
		BillAmt             MONEY NULL, 
		LineOrder           INT NULL, 
		Taxable             INT NULL, 
 		Taxable2            INT NULL, 
		WorkTypeKey         INT NULL, 
		TaskKey             INT NULL, 
		SummaryTaskKey      INT NULL, 
		InvoiceLineKey      INT NULL, 
		BudgetTaskType      INT NULL, 
		Selected            INT NULL, 
		GPFlag              INT NULL,

		BudgetAmount        MONEY NULL,
		BilledAmount        MONEY NULL,
		RemainingAmount     MONEY NULL
	)

/* 
* By Item/Service *****************************************************************************************
*/

if @InvoiceBy = ''Item/Service''
begin 
	if @BillAs = 1
	begin
		-- Bill as % Total
		-- we do not need to know the Billed Amount

		if @ExpensesNotIncluded = 0
			insert #line (Entity, EntityKey, BudgetAmount, Selected)
			select Entity, EntityKey, isnull(Gross, 0) + isnull(COGross, 0), 1
			from   tProjectEstByItem (nolock)
			where  ProjectKey = @ProjectKey
		else
			insert #line (Entity, EntityKey, BudgetAmount, Selected)
			select Entity, EntityKey, isnull(Gross, 0) + isnull(COGross, 0), 1
			from   tProjectEstByItem (nolock)
			where  ProjectKey = @ProjectKey
			and    Entity = ''tService''

		if exists (select 1 from #line) 
			select @InvoiceBy = ''Item/Service''
				  ,@GroupByBillingItem = 1
		else
			select @InvoiceBy = ''OneLine''
				  ,@GroupByBillingItem = 0

		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''
				  ,@GroupByBillingItem = 0

		-- patch for the UI not calculating % budget
		if @InvoiceBy = ''Item/Service''
		begin
			if @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			begin
				select @BudgetAmount = sum(BudgetAmount) from #line

				if isnull(@BudgetAmount,0) = 0
					select @InvoiceBy = ''OneLine''
						,@GroupByBillingItem = 0
				else
					select @PercentBudgetHiPrecision =  (@InvoiceAmount * 100.00 ) / @BudgetAmount
			end
		end

		-- if we still have a problem calculating the % budget, use a single line on the invoice
		if @InvoiceBy = ''Item/Service'' and @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			select @InvoiceBy = ''OneLine''
				  ,@GroupByBillingItem = 0
	 
		if @InvoiceBy = ''Item/Service''
		begin
			-- we need to establish a line order
			update #line
			set    #line.EntityName = s.Description
			from   tService s (nolock)
			where  #line.Entity = ''tService''
			and    #line.EntityKey = s.ServiceKey

			update #line
			set    #line.EntityName = i.ItemName
			from   tItem i (nolock)
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = i.ItemKey

			update #line
			set    #line.EntityName = ''[No Service]''
			where  #line.Entity = ''tService''
			and    #line.EntityKey = 0

			update #line
			set    #line.EntityName = ''[No Item]''
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = 0

			select @LineOrder = 1
			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tService''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tService''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tItem''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tItem''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			-- and calculate the BillAmount on each line
			update #line
			set    #line.BillAmt = round((isnull(BudgetAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)

			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- InvoiceBy = Item/Service

	end -- BillAs = 1 -- Bill as % Total

	--select * from #line
	--select @InvoiceBy, @InvoiceAmount
	--return  1

	if @BillAs = 0
	begin	
		-- Bill as % Remaining
		-- we need to know the Billed Amount

		-- Here, this is more complicated because BilledAmount could be for a single invoice line without service
		-- Or we could have Billed amount and no budget amount
		-- we cannot rely only on tProjectEstByItem
		if @ExpensesNotIncluded = 0
		begin
			insert #line (Entity, EntityKey, BudgetAmount, BilledAmount,Selected)
			-- Services
			SELECT ''tService'', s.ServiceKey
			,ISNULL((SELECT pe.Gross  
						FROM tProjectEstByItem pe (NOLOCK) 
						Where pe.ProjectKey = @ProjectKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			+ ISNULL((SELECT pe.COGross  
						FROM tProjectEstByItem pe (NOLOCK) 
						Where pe.ProjectKey = @ProjectKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   isum.Entity = ''tService''
						AND   ISNULL(isum.EntityKey, 0) = s.ServiceKey
						AND   inv.AdvanceBill = 0), 0)
			, 1
			FROM		
				(
				select ServiceKey
				from tService (nolock)
				where CompanyKey = @CompanyKey
				UNION
				select	0 AS ServiceKey
				) AS s    
    
			-- items
			insert #line (Entity, EntityKey, BudgetAmount, BilledAmount,Selected)
			SELECT ''tItem'', i.ItemKey
			,ISNULL((SELECT pe.Gross  
						FROM tProjectEstByItem pe (NOLOCK) 
						Where pe.ProjectKey = @ProjectKey   
						AND ISNULL(pe.EntityKey, 0) = i.ItemKey
						AND pe.Entity = ''tItem''  
						), 0) 

			+ ISNULL((SELECT pe.COGross  
						FROM tProjectEstByItem pe (NOLOCK) 
						Where pe.ProjectKey = @ProjectKey   
						AND ISNULL(pe.EntityKey, 0) = i.ItemKey
						AND pe.Entity = ''tItem''  
						), 0) 

			-- this should work because if expenses are included, there should not be extra expenses
			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   ISNULL(isum.Entity, '''') IN ('''',''tItem'')
						AND   ISNULL(isum.EntityKey, 0) = i.ItemKey
						AND   inv.AdvanceBill = 0), 0)
			, 1
			FROM		
				(
				select ItemKey
				from tItem (nolock)
				where CompanyKey = @CompanyKey
				UNION
				select	0 AS ItemKey
				) AS i    
	
		end
		else
		begin
			-- Expenses are not included
			-- Take labor budget only
			-- Take labor FF billed only

			INSERT #line (Entity, EntityKey, BudgetAmount, BilledAmount, Selected)

			-- Services
			SELECT ''tService'', s.ServiceKey
			,ISNULL((SELECT pe.Gross  
						FROM tProjectEstByItem pe (NOLOCK) 
						Where pe.ProjectKey = @ProjectKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			+ ISNULL((SELECT pe.COGross  
						FROM tProjectEstByItem pe (NOLOCK) 
						Where pe.ProjectKey = @ProjectKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   il.BillFrom = 1 -- Fixed Fee
						AND   isum.Entity = ''tService''
						AND   ISNULL(isum.EntityKey, 0) = s.ServiceKey
						AND   inv.AdvanceBill = 0), 0)
			,1
			FROM		
				(
				select ServiceKey
				from tService (nolock)
				where CompanyKey = @CompanyKey
				UNION
				select	0 AS ServiceKey
				) AS s    
    
		end

		update #line 
		set    RemainingAmount = isnull(BudgetAmount, 0) - isnull(BilledAmount, 0) 

		-- at this time, I accept negative numbers
		-- because users could bill by item/service then by 1 line, creating situations where budget - billed <0
		delete #line where RemainingAmount = 0 

		if exists (select 1 from #line) 
			select @InvoiceBy = ''Item/Service''
				  ,@GroupByBillingItem = 1
		else
			select @InvoiceBy = ''OneLine''
				  ,@GroupByBillingItem = 0

		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''
				  ,@GroupByBillingItem = 0

		if @InvoiceBy = ''Item/Service''
		begin
			-- we need to establish a line order
			update #line
			set    #line.EntityName = s.Description
			from   tService s (nolock)
			where  #line.Entity = ''tService''
			and    #line.EntityKey = s.ServiceKey

			update #line
			set    #line.EntityName = i.ItemName
			from   tItem i (nolock)
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = i.ItemKey

			update #line
			set    #line.EntityName = ''[No Service]''
			where  #line.Entity = ''tService''
			and    #line.EntityKey = 0

			update #line
			set    #line.EntityName = ''[No Item]''
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = 0

			select @LineOrder = 1
			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tService''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tService''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tItem''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tItem''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			-- and calculate the BillAmount on each line
			if @PercentBudgetHiPrecision <> 100
				update #line
				set    #line.BillAmt = round((isnull(RemainingAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)
			else
				update #line
				set    #line.BillAmt = round(isnull(RemainingAmount, 0), 2)
			
			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- InvoiceBy = Item/Service

	end -- BillAs = 0 -- Bill as % Remaining

end -- End ''Item/Service''

/* 
* By Task *********************************************************************************************
*/

if @InvoiceBy = ''Task''
begin
	select @GroupByBillingItem = 0 -- not applicable when by task

	-- Insert the no task row...TaskKey = -1
	INSERT #line ( Entity, EntityKey, BudgetAmount, LineOrder, Selected, TaskKey, SummaryTaskKey, BudgetTaskType) 
	Values ( null, null  , 0.0 , 1 , 1 , -1 , 0 , 2 )

	if @ExpensesNotIncluded = 1
		-- take labor only
		update #line
		set    BudgetAmount =
			ISNULL((Select Sum(Round(ISNULL(etl.Hours, 0) * ISNULL(etl.Rate, 0),2)) 
					from tEstimateTaskLabor etl  (nolock) inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
					Where e.ProjectKey = @ProjectKey   
					and e.EstType > 1 and e.Approved = 1 and isnull(etl.TaskKey, 0) = 0 
					), 0)
			+ ISNULL((Select Sum(et.EstLabor)
					from tEstimateTask et  (nolock) inner join vEstimateApproved e (nolock) on et.EstimateKey = e.EstimateKey
					Where e.ProjectKey = @ProjectKey 
					and e.EstType = 1 and e.Approved = 1 and isnull(et.TaskKey, 0) = 0 
					), 0)
		where  #line.TaskKey = -1
	else
		-- take labor and expenses
		update #line
		set    BudgetAmount =
			ISNULL((Select Sum(Round(ISNULL(etl.Hours, 0) * ISNULL(etl.Rate, 0),2)) 
					from tEstimateTaskLabor etl  (nolock) inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
					Where e.ProjectKey = @ProjectKey   
					and e.EstType > 1 and e.Approved = 1 and isnull(etl.TaskKey, 0) = 0 
					), 0)
			+ ISNULL((Select Sum(et.EstLabor)
					from tEstimateTask et  (nolock) inner join vEstimateApproved e (nolock) on et.EstimateKey = e.EstimateKey
					Where e.ProjectKey = @ProjectKey 
					and e.EstType = 1 and e.Approved = 1 and isnull(et.TaskKey, 0) = 0 
					), 0)
			+ ISNULL((
		            Select Sum(case 
					when e.ApprovedQty = 1 Then ete.BillableCost
					when e.ApprovedQty = 2 Then ete.BillableCost2
					when e.ApprovedQty = 3 Then ete.BillableCost3
					when e.ApprovedQty = 4 Then ete.BillableCost4
					when e.ApprovedQty = 5 Then ete.BillableCost5
					when e.ApprovedQty = 6 Then ete.BillableCost6											 
					end ) 
					from tEstimateTaskExpense ete  (nolock) inner join vEstimateApproved e (nolock) on ete.EstimateKey = e.EstimateKey
					Where e.ProjectKey = @ProjectKey   
					and e.EstType > 1 and e.Approved = 1 and isnull(ete.TaskKey, 0) = 0
					), 0)
					+ ISNULL((Select Sum(et.EstExpenses) 
					from tEstimateTask et  (nolock) inner join vEstimateApproved e (nolock) on et.EstimateKey = e.EstimateKey
					Where e.ProjectKey = @ProjectKey   
					and e.EstType = 1 and e.Approved = 1 and isnull(et.TaskKey, 0) = 0
					), 0)
		where  #line.TaskKey = -1

	-- And now the tasks on the project
	INSERT #line ( Entity, EntityKey, BudgetAmount, LineOrder, Selected, TaskKey, SummaryTaskKey, BudgetTaskType) 
	select null, null
	,case when @ExpensesNotIncluded = 1 then isnull(EstLabor,0) + isnull(ApprovedCOLabor,0)
	      else isnull(EstLabor,0) + isnull(ApprovedCOLabor,0) + isnull(EstExpenses,0) + isnull(ApprovedCOExpense,0)
		  end
	, ProjectOrder + 1, 1, TaskKey, SummaryTaskKey
	, case when TaskType = 1 and isnull(TrackBudget,0) = 0 then 1
	else 2 end
	from tTask  (nolock)
	where ProjectKey = @ProjectKey
	and   MoneyTask = 1 -- only budget tasks

	if @BillAs = 1
	begin
		-- Bill as % Total
		
		-- patch for the UI not calculating % budget
		if @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
		begin
			select @BudgetAmount = sum(BudgetAmount) from #line where BudgetTaskType = 2 -- detail line only

			if isnull(@BudgetAmount,0) = 0
				select @InvoiceBy = ''OneLine''
					,@GroupByBillingItem = 0
			else
				select @PercentBudgetHiPrecision =  (@InvoiceAmount * 100.00 ) / @BudgetAmount
		end
		
		if @InvoiceBy = ''Task'' 
		begin
			-- and calculate the BillAmount on each line
			update #line
			set    #line.BillAmt = round((isnull(BudgetAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)
			where BudgetTaskType = 2 -- detail line only

			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line where BudgetTaskType = 2
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line
		end

	 end

	 if @BillAs = 0
	 begin
		-- Bill as % of remaining
		-- we need the BilledAmount

		-- in tInvoiceSummary labor has Entity = ''tService''
		-- in tInvoiceSummary expenses have Entity = ''tItem'' or null

		if @ExpensesNotIncluded = 0
		begin
			-- expenses are included, take all
			update #line
			set    #line.BilledAmount =
			ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   ISNULL(isum.TaskKey, 0) = #line.TaskKey
						AND   inv.AdvanceBill = 0), 0)
			where #line.BudgetTaskType = 2
			and #line.TaskKey > 0 

			update #line
			set    #line.BilledAmount =
			ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   ISNULL(isum.TaskKey, 0) = 0 -- No Task in tInvoice Summary
						AND   inv.AdvanceBill = 0), 0)
			where #line.BudgetTaskType = 2
			and #line.TaskKey = -1 -- No Task here 
		end
		else
		begin
			-- expenses are NOT included, take labor only
			update #line
			set    #line.BilledAmount =
			ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   ISNULL(isum.TaskKey, 0) = #line.TaskKey
						AND   inv.AdvanceBill = 0
						AND   isum.Entity = ''tService''
						), 0)
			where #line.BudgetTaskType = 2
			and #line.TaskKey > 0 

			update #line
			set    #line.BilledAmount =
			ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE isum.ProjectKey = @ProjectKey
						AND   ISNULL(isum.TaskKey, 0) = 0 -- No Task in tInvoice Summary
						AND   inv.AdvanceBill = 0
						AND   isum.Entity = ''tService''
						), 0)
			where #line.BudgetTaskType = 2
			and #line.TaskKey = -1 -- No Task here 
		end

		 update #line 
		 set    RemainingAmount = isnull(BudgetAmount, 0) - isnull(BilledAmount, 0)
		 where #line.BudgetTaskType = 2

		 -- and calculate the BillAmount on each line
		if @PercentBudgetHiPrecision <> 100
			update #line
			set    #line.BillAmt = round((isnull(RemainingAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)
		else
			update #line
			set    #line.BillAmt = round(isnull(RemainingAmount, 0), 2)
			
		-- recalc InvoiceAmount because of rounding errors
		select @RoundingError = sum(BillAmt) from #line where #line.BudgetTaskType = 2
		select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

		if @RoundingError <> 0
			update #line
			set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
			where  LineOrder = 1 -- first line

	 end -- BillAs = 0

end -- InvoiceBy = Task

/*
* Billing Item ************************************************************************************
*/

if @InvoiceBy = ''BillingItem''
begin
	select @GroupByBillingItem = 0 -- not applicable when by BillingItem

	-- only pick the billing items that you need

	-- always select the No WorkType row
	insert #line (Entity, EntityKey, LineOrder, Selected)
	values (''tWorkType'', 0, 1, 1)

	-- process budget first !!!

	insert #line (Entity, EntityKey, LineOrder, Selected)
	select distinct ''tWorkType'', isnull(s.WorkTypeKey,0), 2, 1
	from   tProjectEstByItem pebi (nolock)
	inner join tService s (nolock) on pebi.Entity = ''tService'' and pebi.EntityKey = s.ServiceKey
	where  pebi.ProjectKey = @ProjectKey
	and    isnull(s.WorkTypeKey,0) > 0
	and    isnull(s.WorkTypeKey,0) not in (select EntityKey from #line)

	-- calculate the budget amount

	-- no matter what @ExpensesNotIncluded we take budget labor
	update #line
	set    #line.BudgetAmount = isnull(#line.BudgetAmount,0)  +  isnull((
		select sum(isnull(pe.Gross,0) + isnull(pe.COGross,0))  
		FROM tProjectEstByItem pe (NOLOCK) 
		inner join tService	s (nolock) on pe.EntityKey = s.ServiceKey	 
		Where pe.ProjectKey = @ProjectKey   
		AND pe.Entity = ''tService'' 
		AND #line.EntityKey = isnull(s.WorkTypeKey, 0) 
		),0)

	-- add the labor in tProjectEstByItem where EntityKey = 0 (no service i.e. no billing item) 
	update #line
	set    #line.BudgetAmount = isnull(#line.BudgetAmount,0)  +  isnull((
		select sum(isnull(pe.Gross,0) + isnull(pe.COGross,0))  
		FROM tProjectEstByItem pe (NOLOCK) 	 
		Where pe.ProjectKey = @ProjectKey   
		AND pe.Entity = ''tService''
		AND pe.EntityKey = 0 
		AND #line.EntityKey = 0 
		),0)

	-- then if expenses are included, take expense budget
	if @ExpensesNotIncluded = 0
	begin
		insert #line (Entity, EntityKey, LineOrder, Selected)
		select distinct ''tWorkType'', isnull(i.WorkTypeKey,0), 2, 1
		from   tProjectEstByItem pebi (nolock)
		inner join tItem i (nolock) on pebi.Entity = ''tItem'' and pebi.EntityKey = i.ItemKey
		where  pebi.ProjectKey = @ProjectKey
		and    isnull(i.WorkTypeKey,0) > 0
		and    isnull(i.WorkTypeKey,0) not in (select EntityKey from #line)

		update #line
		set    #line.BudgetAmount = isnull(#line.BudgetAmount,0)  +  isnull((
			select sum(isnull(pe.Gross,0) + isnull(pe.COGross,0))  
			FROM tProjectEstByItem pe (NOLOCK) 
			inner join tItem i (nolock) on pe.EntityKey = i.ItemKey	 
			Where pe.ProjectKey = @ProjectKey   
			AND pe.Entity = ''tItem'' 
			AND #line.EntityKey = isnull(i.WorkTypeKey, 0) 
		    ),0)

		-- add the expenses in tProjectEstByItem where EntityKey = 0 (no item i.e. no billing item) 
		update #line
		set    #line.BudgetAmount = isnull(#line.BudgetAmount,0)  +  isnull((
			select sum(isnull(pe.Gross,0) + isnull(pe.COGross,0))  
			FROM tProjectEstByItem pe (NOLOCK) 	 
			Where pe.ProjectKey = @ProjectKey   
			AND pe.Entity = ''tItem''
			AND pe.EntityKey = 0 
			AND #line.EntityKey = 0 
		    ),0)
	end

	if @BillAs = 1
	begin
		-- bill as % of total budget we do not need the billed amount
		-- so we do not need more billing items from the billing side

		delete #line where isnull(BudgetAmount,0) = 0

		if not exists (select 1 from #line) 
			select @InvoiceBy = ''OneLine''
		
		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''

		-- patch for the UI not calculating % budget
		if @InvoiceBy = ''BillingItem''
		begin
			if @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			begin
				select @BudgetAmount = sum(BudgetAmount) from #line

				if isnull(@BudgetAmount,0) = 0
					select @InvoiceBy = ''OneLine''
						,@GroupByBillingItem = 0
				else
					select @PercentBudgetHiPrecision =  (@InvoiceAmount * 100.00 ) / @BudgetAmount
			end
		end

		-- if we still have a problem calculating the % budget, use a single line on the invoice
		if @InvoiceBy = ''BillingItem'' and @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			select @InvoiceBy = ''OneLine''

		if @InvoiceBy = ''BillingItem'' 
		begin
			-- we need to establish a line order
			update #line
			set    #line.EntityName = w.WorkTypeName
			from   tWorkType w (nolock)
			where  #line.EntityKey = w.WorkTypeKey

			update #line
			set    #line.EntityName = ''[No Billing Item]''
			where  #line.EntityKey = 0
		
			select @LineOrder = 1
			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end
		
			-- and calculate the BillAmount on each line
			update #line
			set    #line.BillAmt = round((isnull(BudgetAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)

			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- @InvoiceBy = ''BillingItem''


	end -- if @BillAs = 1

	if @BillAs = 0
	begin
		-- Bill as % Remaining
		-- we need the billed amount 

		if @ExpensesNotIncluded = 0
		begin
			-- expenses are included, take all

			insert #line (Entity, EntityKey, LineOrder, Selected)
			select distinct ''tWorkType'', isnull(il.WorkTypeKey,0), 2, 1
			from tInvoiceSummary isum (NOLOCK)
				inner join tInvoice invc (NOLOCK) on isum.InvoiceKey = invc.InvoiceKey 
			inner join tInvoiceLine il (nolock) on invc.InvoiceKey = il.InvoiceKey
			Where il.ProjectKey = @ProjectKey 
			And   invc.AdvanceBill = 0
			And   il.BillFrom = 1				-- Fixed Fee Only
			and    isnull(il.WorkTypeKey,0) not in (select EntityKey from #line)

			insert #line (Entity, EntityKey, LineOrder, Selected)
			select distinct ''tWorkType'', isnull(s.WorkTypeKey,0), 2, 1
			from tInvoiceSummary isum (NOLOCK)
				inner join tInvoice invc (NOLOCK) on isum.InvoiceKey = invc.InvoiceKey
				inner join tService s (NOLOCK) ON isum.EntityKey = s.ServiceKey 
			inner join tInvoiceLine il (nolock) on invc.InvoiceKey = il.InvoiceKey
			Where il.ProjectKey = @ProjectKey 
			And   invc.AdvanceBill = 0
			And   il.BillFrom = 2				-- TM
			AND   isum.Entity = ''tService''
			and    isnull(s.WorkTypeKey,0) not in (select EntityKey from #line)

			insert #line (Entity, EntityKey, LineOrder, Selected)
			select distinct ''tWorkType'', isnull(i.WorkTypeKey,0), 2, 1
			from tInvoiceSummary isum (NOLOCK)
				inner join tInvoice invc (NOLOCK) on isum.InvoiceKey = invc.InvoiceKey
				inner join tItem i (NOLOCK) ON isum.EntityKey = i.ItemKey 
			inner join tInvoiceLine il (nolock) on invc.InvoiceKey = il.InvoiceKey
			Where il.ProjectKey = @ProjectKey 
			And   invc.AdvanceBill = 0
			And   il.BillFrom = 2				-- TM
			AND   isum.Entity = ''tItem''
			and    isnull(i.WorkTypeKey,0) not in (select EntityKey from #line)

			-- now pull the billed amount
			update #line
			set    #line.BilledAmount = isnull(#line.BilledAmount,0) + ISNULL((Select Sum(isum.Amount) 
			 from tInvoiceSummary isum (nolock) 
			 inner join tInvoice invc (nolock) on isum.InvoiceKey = invc.InvoiceKey
			 inner join tInvoiceLine il (nolock) on isum.InvoiceLineKey = il.InvoiceLineKey
			 Where isum.ProjectKey = @ProjectKey 
			 And   ISNULL(il.WorkTypeKey, 0) = #line.EntityKey 
			 And   invc.AdvanceBill = 0
			 And   il.BillFrom = 1				-- Fixed Fee Only
			 ), 0)
	     
			+ ISNULL((SELECT Sum(isum.Amount) 
			from tInvoiceSummary isum (NOLOCK)
			inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
			inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
			inner join tService s (NOLOCK) ON isum.EntityKey = s.ServiceKey
			WHERE isum.ProjectKey = @ProjectKey
			AND   inv.AdvanceBill = 0
			And   il.BillFrom = 2	-- TM
			AND   isum.Entity = ''tService''
			AND   ISNULL(s.WorkTypeKey, 0) = #line.EntityKey 
			), 0)
		 
			+ ISNULL((SELECT Sum(isum.Amount) 
			from tInvoiceSummary isum (NOLOCK)
			inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
			inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
			inner join tItem i (NOLOCK) ON isum.EntityKey = i.ItemKey
			WHERE isum.ProjectKey = @ProjectKey
			AND   inv.AdvanceBill = 0
			And   il.BillFrom = 2 -- TM
			AND   isum.Entity = ''tItem''
			AND   ISNULL(i.WorkTypeKey, 0) = #line.EntityKey 
			), 0)
			
			where  #line.EntityKey > 0 -- there is a billing item

			-- no billing item
			update #line 
			set    #line.BilledAmount = isnull(#line.BilledAmount,0) + ISNULL((Select Sum(isum.Amount) 
			 from tInvoiceSummary isum (nolock) 
			 inner join tInvoice invc (nolock) on isum.InvoiceKey = invc.InvoiceKey
			 inner join tInvoiceLine il (nolock) on isum.InvoiceLineKey = il.InvoiceLineKey
			 Where isum.ProjectKey = @ProjectKey 
			 And   ISNULL(il.WorkTypeKey, 0) = 0 
			 And   invc.AdvanceBill = 0
			 And   il.BillFrom = 1				-- Fixed Fee Only
			 ), 0)
	     
			+ ISNULL((SELECT Sum(isum.Amount) 
			from tInvoiceSummary isum (NOLOCK)
			inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
			inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
			left outer join tService s (NOLOCK) ON isum.EntityKey = s.ServiceKey
			WHERE isum.ProjectKey = @ProjectKey
			AND   inv.AdvanceBill = 0
			And   il.BillFrom = 2	-- TM
			AND   isum.Entity = ''tService''
			AND   ISNULL(s.WorkTypeKey, 0) = 0 
			), 0)
		 
			+ ISNULL((SELECT Sum(isum.Amount) 
			from tInvoiceSummary isum (NOLOCK)
			inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
			inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
			left outer join tItem i (NOLOCK) ON isum.EntityKey = i.ItemKey
			WHERE isum.ProjectKey = @ProjectKey
			AND   inv.AdvanceBill = 0
			And   il.BillFrom = 2 -- TM
			AND   ISNULL(isum.Entity, '''') in ('''', ''tItem'')
			AND   ISNULL(i.WorkTypeKey, 0) = 0 

			), 0)

			where  #line.EntityKey = 0 -- there is a no billing item

		end -- end @ExpensesNotIncluded = 0
		else
		begin
			-- expenses are NOT included, take labor only

			insert #line (Entity, EntityKey, LineOrder, Selected)
			select distinct ''tWorkType'', isnull(il.WorkTypeKey,0), 2, 1
			from tInvoiceSummary isum (NOLOCK)
				inner join tInvoice invc (NOLOCK) on isum.InvoiceKey = invc.InvoiceKey 
			inner join tInvoiceLine il (nolock) on invc.InvoiceKey = il.InvoiceKey
			Where il.ProjectKey = @ProjectKey 
			And   invc.AdvanceBill = 0
			And   il.BillFrom = 1				-- Fixed Fee Only
			And   il.Entity = ''tService''
			and    isnull(il.WorkTypeKey,0) not in (select EntityKey from #line)

			insert #line (Entity, EntityKey, LineOrder, Selected)
			select distinct ''tWorkType'', isnull(s.WorkTypeKey,0), 2, 1
			from tInvoiceSummary isum (NOLOCK)
				inner join tInvoice invc (NOLOCK) on isum.InvoiceKey = invc.InvoiceKey
				inner join tService s (NOLOCK) ON isum.EntityKey = s.ServiceKey 
			inner join tInvoiceLine il (nolock) on invc.InvoiceKey = il.InvoiceKey
			Where il.ProjectKey = @ProjectKey 
			And   invc.AdvanceBill = 0
			And   il.BillFrom = 2				-- TM
			AND   isum.Entity = ''tService''
			and    isnull(s.WorkTypeKey,0) not in (select EntityKey from #line)

			-- now pull the billed amount
			update #line
			set    #line.BilledAmount = isnull(#line.BilledAmount,0) + ISNULL((Select Sum(isum.Amount) 
			 from tInvoiceSummary isum (nolock) 
			 inner join tInvoice invc (nolock) on isum.InvoiceKey = invc.InvoiceKey
			 inner join tInvoiceLine il (nolock) on isum.InvoiceLineKey = il.InvoiceLineKey -- how can we restrict labor only
			 Where isum.ProjectKey = @ProjectKey 
			 And   ISNULL(il.WorkTypeKey, 0) = #line.EntityKey 
			 And   invc.AdvanceBill = 0
			 And   il.Entity = ''tService''
			 And   il.BillFrom = 1				-- Fixed Fee Only
			 ), 0)
	     
			+ ISNULL((SELECT Sum(isum.Amount) 
			from tInvoiceSummary isum (NOLOCK)
			inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
			inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
			inner join tService s (NOLOCK) ON isum.EntityKey = s.ServiceKey
			WHERE isum.ProjectKey = @ProjectKey
			AND   inv.AdvanceBill = 0
			And   il.BillFrom = 2	-- TM
			AND   isum.Entity = ''tService''
			AND   ISNULL(s.WorkTypeKey, 0) = #line.EntityKey 
			), 0)
			
			where  #line.EntityKey > 0 -- there is a billing item

			-- no billing item
			update #line 
			set    #line.BilledAmount = isnull(#line.BilledAmount,0) + ISNULL((Select Sum(isum.Amount) 
			 from tInvoiceSummary isum (nolock) 
			 inner join tInvoice invc (nolock) on isum.InvoiceKey = invc.InvoiceKey
			 inner join tInvoiceLine il (nolock) on isum.InvoiceLineKey = il.InvoiceLineKey -- how can we restrict labor only
			 Where isum.ProjectKey = @ProjectKey 
			 And   ISNULL(il.WorkTypeKey, 0) = 0 
			 And   invc.AdvanceBill = 0
			 And   il.BillFrom = 1				-- Fixed Fee Only
			 And   il.Entity = ''tService''
			 ), 0)
	     
			+ ISNULL((SELECT Sum(isum.Amount) 
			from tInvoiceSummary isum (NOLOCK)
			inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
			inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
			left outer join tService s (NOLOCK) ON isum.EntityKey = s.ServiceKey
			WHERE isum.ProjectKey = @ProjectKey
			AND   inv.AdvanceBill = 0
			And   il.BillFrom = 2	-- TM
			AND   isum.Entity = ''tService''
			AND   ISNULL(s.WorkTypeKey, 0) = 0 
			), 0)
		
			where  #line.EntityKey = 0 -- there is a no billing item

		end -- end @ExpensesNotIncluded = 1


		update #line 
		set    RemainingAmount = isnull(BudgetAmount, 0) - isnull(BilledAmount, 0) 

		-- at this time, I accept negative numbers
		-- because users could bill by item/service then by 1 line, creating situations where budget - billed <0
		delete #line where RemainingAmount = 0 

		if exists (select 1 from #line) 
			select @InvoiceBy = ''BillingItem''
		else
			select @InvoiceBy = ''OneLine''
				  
		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''
				  
		if @InvoiceBy = ''BillingItem'' 
		begin
			-- we need to establish a line order
			update #line
			set    #line.EntityName = w.WorkTypeName
			from   tWorkType w (nolock)
			where  #line.EntityKey = w.WorkTypeKey

			update #line
			set    #line.EntityName = ''[No Billing Item]''
			where  #line.EntityKey = 0
		
			select @LineOrder = 1
			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end
		
			-- and calculate the BillAmount on each line
			if @PercentBudgetHiPrecision <> 100
				update #line
				set    #line.BillAmt = round((isnull(RemainingAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)
			else
				update #line
				set    #line.BillAmt = round(isnull(RemainingAmount, 0), 2)

			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- @InvoiceBy = ''BillingItem''



	end -- end BillAs = 0

end -- end BillingItem case

--select * from #line
--select sum(BilledAmount) from #line
--return 1

/*
* Invoice Creation ************************************************************************************
*/

	-- Now extract some invoice settings from the FF Project billing section
	declare @AddProjectLine int
	declare @AllowZeroLines int
	declare @GroupByBillingItem2 int -- this is the flag in the session, I already have a variable of the same name
	declare @AddTaskDetails int
	declare @SecurityGroupKey int

	select @SecurityGroupKey = SecurityGroupKey from tUser (nolock) where UserKey = @UserKey

	select @AddProjectLine = Value from tAppSession (nolock) where Entity = ''securitygroup'' and EntityKey = @SecurityGroupKey and GroupID = ''projectFFBilling'' and SessionID = ''AddProjectLine''
	if @@ROWCOUNT = 0
		select @AddProjectLine = Value from tAppSession (nolock) where Entity = ''company'' and EntityKey = @CompanyKey and GroupID = ''projectFFBilling'' and SessionID = ''AddProjectLine''
	
	select @AllowZeroLines = Value from tAppSession (nolock) where Entity = ''securitygroup'' and EntityKey = @SecurityGroupKey and GroupID = ''projectFFBilling'' and SessionID = ''AllowZeroLines''
	if @@ROWCOUNT = 0
		select @AllowZeroLines = Value from tAppSession (nolock) where Entity = ''company'' and EntityKey = @CompanyKey and GroupID = ''projectFFBilling'' and SessionID = ''AllowZeroLines''
	
	select @GroupByBillingItem2 = Value from tAppSession (nolock) where Entity = ''securitygroup'' and EntityKey = @SecurityGroupKey and GroupID = ''projectFFBilling'' and SessionID = ''GroupByBillingItem''
	if @@ROWCOUNT = 0
		select @GroupByBillingItem2 = Value from tAppSession (nolock) where Entity = ''company'' and EntityKey = @CompanyKey and GroupID = ''projectFFBilling'' and SessionID = ''GroupByBillingItem''
	
	select @AddTaskDetails = Value from tAppSession (nolock) where Entity = ''securitygroup'' and EntityKey = @SecurityGroupKey and GroupID = ''projectFFBilling'' and SessionID = ''AddTaskDetails''
	if @@ROWCOUNT = 0
		select @AddTaskDetails = Value from tAppSession (nolock) where Entity = ''company'' and EntityKey = @CompanyKey and GroupID = ''projectFFBilling'' and SessionID = ''AddTaskDetails''

	select @AddProjectLine = isnull(@AddProjectLine, 0), @AllowZeroLines = isnull(@AllowZeroLines, 0), @GroupByBillingItem2 = isnull(@GroupByBillingItem2, 1), @AddTaskDetails = isnull(@AddTaskDetails, 0)
	
	-- if the users do not want to group by BI, reset this
	if @GroupByBillingItem2 = 0
		select @GroupByBillingItem = 0

	-- and create the invoice
	exec @NewInvoiceKey = spFixedFeesCreateProjectInvoice @ProjectKey=@ProjectKey,@InvoiceBy=@InvoiceBy,@UserKey=@UserKey,@InvoiceAmount=@InvoiceAmount,@AdvanceBilling=@AdvanceBilling
					,@DefaultClassKey=@DefaultClassKey,@EstimateKey=null,@DefaultDepartmentKey=null
					,@AddProjectLine=@AddProjectLine,@AllowZeroLines=@AllowZeroLines,@GroupByBillingItem=@GroupByBillingItem,@AddTaskDetails=@AddTaskDetails
					,@InvoiceDate=@InvoiceDate,@PostingDate=@PostingDate, @UpdateLabor = 1
	
	if @NewInvoiceKey <= 0
		return -1

	-- issue 402606 propagate tBillingSchedule.Comments to tInvoice.HeaderComment
	update tInvoice
	set    tInvoice.HeaderComment = bs.Comments
	from   tBillingSchedule bs (nolock)
	where  tInvoice.InvoiceKey = @NewInvoiceKey
	and    bs.BillingScheduleKey = @BillingScheduleKey

	-- now there is tBillingSchedule.AdvanceBill, so do not check AdvanceBilling
	--if @AdvanceBilling = 0
	--begin
		if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @NewInvoiceKey and ProjectKey = @ProjectKey) 
			update tBillingSchedule
			set    InvoiceKey = @NewInvoiceKey
			      ,BilledComment = (select case when isnull(PercentBudget, 0) > 0
			                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(PercentBudget, 0) * (
			                                             case when isnull(p.ExpensesNotIncluded, 0) = 0
			                                                  then isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0) + isnull(p.EstExpenses, 0) + isnull(p.ApprovedCOExpense, 0)
			                                                  else isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0)
			                                             end) / 100.00, 2), ''N2'')
			                                    else null end
			                         from  tProject p (nolock)
			                         where p.ProjectKey = @ProjectKey)
			where  BillingScheduleKey = @BillingScheduleKey
			and    BillingKey is null
			and    InvoiceKey is null
	--end

	If @CreateAsApproved = 1
		BEGIN
	
			--Check to see if the tInvoice Insert SP set the Invoice Number
			SELECT	@NextTranNo = InvoiceNumber
			FROM	tInvoice (nolock)
			WHERE	InvoiceKey = @NewInvoiceKey
	
			IF @NextTranNo IS NULL
			BEGIN
				--If the InvoiceNumber has not been set yet, get the next number
				DECLARE @TranType varchar(10) = CASE @AdvanceBilling WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

				EXEC spGetNextTranNo
					@CompanyKey,
					@TranType,
					@RetVal		      OUTPUT,
					@NextTranNo 	  OUTPUT	
		
				IF @RetVal <> 1
				BEGIN
					exec sptInvoiceDelete @NewInvoiceKey
					RETURN -1
				END
			END
	
			update tInvoice
			set	  ApprovedByKey = @UserKey
					,InvoiceStatus = 4 -- Approved
					,InvoiceNumber = @NextTranNo 
			where InvoiceKey = @NewInvoiceKey

		END
		/* Removed for issue 334769
		ELSE
		BEGIN
		
			select @InvoiceStatus = InvoiceStatus
					,@ApprovedByKey = ApprovedByKey
			from   tInvoice (nolock)
			where  InvoiceKey = @NewInvoiceKey

			-- only if not already approved and the approver is valid, submit
			if @InvoiceStatus <> 4 And isnull(@ApprovedByKey, 0) > 0
				update tInvoice
				set    InvoiceStatus = 2
				where InvoiceKey = @NewInvoiceKey
		END -- created as approved 
		*/

		-- Now check if we need an extra invoice line for the expenses not included in Fixed Fee
	
		-- However if AdvanceBilling = 1, we cannot include expenses on a Time And Material type of line
		if @AdvanceBilling = 1
			select @ExpensesNotIncluded = 0

		-- If expenses are not included, return now
		if isnull(@ExpensesNotIncluded, 0) = 0
		begin
			-- now do rollups on projects
			 exec sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey, 1, 0

			 -- and log the creation of the invoice
			select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

			select @Reference = i.InvoiceNumber
				  ,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @NewInvoiceKey

			select @Reference = isnull(@Reference,'''')
				  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through fixed fee mass billing''
			else
				select @Comments = ''Invoice was generated through fixed fee mass billing''

			-- log how we billed
			select @Comments = @Comments + '' ('' + cast(@PercentBudget as varchar(50))
			if @BillAs = 0 
				select @Comments = @Comments + ''% of Remaining)''
			else
				select @Comments = @Comments + ''% of Total)''

			select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

			return @NewInvoiceKey
		end

		-- Now process the case when expenses are not included
		IF @IOBeginDate is null
			select @IOBeginDate = ''1/1/1960''
		IF @BCBeginDate is null
			select @BCBeginDate = ''1/1/1960''
		IF @EndDate IS NULL
			SELECT @EndDate = ''01/01/2050''
		IF @IOEndDate is null
			select @IOEndDate = ''01/01/2050''
		IF @BCEndDate is null
			select @BCEndDate = ''01/01/2050''
	

		declare @ExpensesAmount money
		declare @MiscCostAmount money
		declare @ExpenseReceiptAmount money
		declare @VoucherAmount money
		declare @POAmount money
		declare @IOAmount money
		declare @BCAmount money
	
		-- projects should not be in the fixed fee list on the UI if they have a BWS, so do not check the presence on a BWS here
		IF @Expense = 1	
		select @MiscCostAmount = ISNULL(SUM(mc.BillableCost), 0)
					FROM	tMiscCost mc (NOLOCK)
					WHERE	mc.ProjectKey = @ProjectKey
					AND     mc.InvoiceLineKey IS NULL
					AND     ISNULL(mc.WriteOff, 0) = 0
					AND     mc.ExpenseDate <= @EndDate
					AND		ISNULL(mc.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		mc.MiscCostKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tMiscCost''  
												AND   b.ProjectKey = mc.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

	     IF @ExpenseReport = 1
		 select @ExpenseReceiptAmount = ISNULL(SUM(er.BillableCost), 0)
					FROM	tExpenseReceipt er (NOLOCK), tExpenseEnvelope en (nolock)
					WHERE	er.ProjectKey = @ProjectKey
					AND		er.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
					AND		en.Status = 4
					AND     er.InvoiceLineKey IS NULL
					AND		ISNULL(er.WriteOff, 0) = 0
					AND     er.ExpenseDate <= @EndDate
					AND		ISNULL(er.OnHold, 0) = 0
					AND		er.VoucherDetailKey IS NULL
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		er.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tExpenseReceipt''  
												AND   b.ProjectKey = er.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

			IF @Expense = 1
			SELECT @VoucherAmount = ISNULL(SUM(vd.BillableCost), 0)
					FROM	tVoucherDetail vd (NOLOCK) ,tVoucher v  (NOLOCK)
					WHERE	vd.VoucherKey   = v.VoucherKey
					AND		vd.ProjectKey = @ProjectKey
					AND     vd.InvoiceLineKey IS NULL
					AND		ISNULL(vd.WriteOff, 0) = 0
					AND		v.Status = 4
					AND     v.InvoiceDate <= @EndDate
					AND		ISNULL(vd.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		vd.VoucherDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tVoucherDetail'' 
												AND   b.ProjectKey = vd.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

			IF @PO = 1
			SELECT @POAmount = ISNULL(SUM(pod.BillableCost), 0)
					FROM	tPurchaseOrderDetail pod (NOLOCK)
							,tPurchaseOrder po (NOLOCK)
					WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = @ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		po.PODate <= @EndDate
					AND		po.Status = 4
					AND		po.POKind = 0
					AND		ISNULL(pod.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = pod.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

			IF @IO = 1
			SELECT @IOAmount =  isnull(SUM(Case ISNULL(po.BillAt, 0) 
						When 0 then isnull(BillableCost,0)
						When 1 then isnull(PTotalCost,isnull(TotalCost,0))
						When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ),0)
					FROM	tPurchaseOrderDetail pod (NOLOCK)
							,tPurchaseOrder po (NOLOCK)
					WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = @ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @IOBeginDate
					AND		pod.DetailOrderDate <= @IOEndDate
					AND		po.Status = 4
					AND		po.POKind = 1
					AND		ISNULL(pod.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = pod.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

				IF @BC = 1
				SELECT @BCAmount =  isnull(SUM(Case ISNULL(po.BillAt, 0) 
						When 0 then isnull(BillableCost,0)
						When 1 then isnull(PTotalCost,isnull(TotalCost,0))
						When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ),0)
					FROM	tPurchaseOrderDetail pod (NOLOCK)
							,tPurchaseOrder po (NOLOCK)
					WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = @ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @BCBeginDate
					AND		pod.DetailOrderDate <= @BCEndDate
					AND		po.Status = 4
					AND		po.POKind = 2
					AND		ISNULL(pod.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = pod.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

		declare @ParentLineKey  int
		select @ParentLineKey = 0
		
		-- if we added a top line, place this one under it   
		if @AddProjectLine = 1 and exists (select 1 from tInvoiceLine (nolock) 
			where InvoiceKey = @NewInvoiceKey and  LineType = 1  and InvoiceOrder = 1
		)
		begin
			select @ParentLineKey = InvoiceLineKey
			from tInvoiceLine (nolock) 
			where InvoiceKey = @NewInvoiceKey and  LineType = 1  and InvoiceOrder = 1
		end

		select @ExpensesAmount = isnull(@MiscCostAmount, 0) + isnull(@ExpenseReceiptAmount, 0) + isnull(@VoucherAmount, 0) + isnull(@POAmount, 0) + isnull(@IOAmount, 0) + isnull(@BCAmount, 0)

		if @ExpensesAmount != 0
		begin

			if isnull(@BillExpensesByItem, 0) = 0
			begin
				-- Default behavior: all extra expenses roll up into a single ''Other Expenses'' line
				exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,null							-- TaskKey
					  ,''Other Expenses''					-- Line Subject
					  ,null                 		-- Line description
					  ,2                    		-- Bill From 
					  ,1							-- Quantity
					  ,@ExpensesAmount				-- Unit Amount
					  ,@ExpensesAmount				-- Line Amount
					  ,2							-- line type
					  ,@ParentLineKey				-- parent line key
					  ,@SalesAccountKey				-- Default Sales AccountKey
					  ,@DefaultClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,NULL							-- Work TypeKey
					  ,@PostSalesUsingDetail							-- PostInDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,@OfficeKey
					  ,null							--@DepartmentKey -- may need a department if department required
					  ,@NewInvoiceLineKey output

				if @NewInvoiceLineKey <= 0
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return -1
				end

				 if @Expense = 1
				 begin
					 update tMiscCost
					 set    InvoiceLineKey = @NewInvoiceLineKey
							,AmountBilled = BillableCost
					 WHERE	ProjectKey = @ProjectKey
					AND     InvoiceLineKey IS NULL
					AND     ISNULL(WriteOff, 0) = 0
					AND     ExpenseDate <= @EndDate
					AND		ISNULL(OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		tMiscCost.MiscCostKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tMiscCost''  
													AND   b.ProjectKey = tMiscCost.ProjectKey 
													AND   b.Status < 5				  											
													)
					*/

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

                if @ExpenseReport = 1
				begin
					update tExpenseReceipt
					 set    InvoiceLineKey = @NewInvoiceLineKey
							,AmountBilled = BillableCost
					 FROM	tExpenseEnvelope en (nolock)
					WHERE	tExpenseReceipt.ProjectKey = @ProjectKey
					AND		tExpenseReceipt.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
					AND		en.Status = 4
					AND     tExpenseReceipt.InvoiceLineKey IS NULL
					AND		ISNULL(tExpenseReceipt.WriteOff, 0) = 0
					AND     tExpenseReceipt.ExpenseDate <= @EndDate
					AND		ISNULL(tExpenseReceipt.OnHold, 0) = 0
					AND		tExpenseReceipt.VoucherDetailKey IS NULL
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		tExpenseReceipt.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tExpenseReceipt''  
													AND   b.ProjectKey = tExpenseReceipt.ProjectKey 
													AND   b.Status < 5				  											
													)
					*/

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @Expense = 1
				begin
					update tVoucherDetail
					set		InvoiceLineKey = @NewInvoiceLineKey 
							,AmountBilled = BillableCost
					FROM	tVoucher v  (NOLOCK)
					WHERE	tVoucherDetail.VoucherKey   = v.VoucherKey
					AND		tVoucherDetail.ProjectKey = @ProjectKey
					AND     tVoucherDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tVoucherDetail.WriteOff, 0) = 0
					AND		v.Status = 4
					AND     v.InvoiceDate <= @EndDate
					AND		ISNULL(tVoucherDetail.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		tVoucherDetail.VoucherDetailKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tVoucherDetail'' 
													AND   b.ProjectKey = tVoucherDetail.ProjectKey 
													AND   b.Status < 5				  											
													)
					*/
					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @PO = 1
				begin
					update tPurchaseOrderDetail
					set		InvoiceLineKey = @NewInvoiceLineKey
							,tPurchaseOrderDetail.AccruedCost = 
							CASE 
								WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
								ELSE 0
							END
							,AmountBilled = isnull(BillableCost,0)
					FROM	tPurchaseOrder po (NOLOCK)
					WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
					AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
					AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
					AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
					AND		po.PODate <= @EndDate
					AND		po.Status = 4
					AND		po.POKind = 0
					AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @IO = 1
				begin
					update tPurchaseOrderDetail
					set		InvoiceLineKey = @NewInvoiceLineKey
							,tPurchaseOrderDetail.AccruedCost = 
							CASE 
								WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
								ELSE 0
							END
							,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
							When 0 then isnull(BillableCost,0)
							When 1 then isnull(PTotalCost,isnull(TotalCost,0))
							When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
					FROM	tPurchaseOrder po (NOLOCK)
					WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
					AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
					AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
					AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
					AND		tPurchaseOrderDetail.DetailOrderDate >= @IOBeginDate
					AND		tPurchaseOrderDetail.DetailOrderDate <= @IOEndDate
					AND		po.Status = 4
					AND		po.POKind = 1
					AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @BC = 1
				begin
					update tPurchaseOrderDetail
					set		InvoiceLineKey = @NewInvoiceLineKey
							,tPurchaseOrderDetail.AccruedCost = 
							CASE 
								WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
								ELSE 0
							END
							,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
							When 0 then isnull(BillableCost,0)
							When 1 then isnull(PTotalCost,isnull(TotalCost,0))
							When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
					FROM	tPurchaseOrder po (NOLOCK)
					WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
					AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
					AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
					AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
					AND		tPurchaseOrderDetail.DetailOrderDate >= @BCBeginDate
					AND		tPurchaseOrderDetail.DetailOrderDate <= @BCEndDate
					AND		po.Status = 4
					AND		po.POKind = 2
					AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
					/* because projects will EBWS are excluded in spMassBillingGetFF
					AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey 
												AND   b.Status < 5				  											
												)
					*/

					if @@ERROR <> 0
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1
					  end
				end

			end -- BillExpensesByItem = 0
			else
			begin
				-- Bill Expenses by Item: one invoice line per Item, instead of a single ''Other Expenses'' line

				CREATE TABLE #expenseByItem ( ItemKey int NULL, Amount money NULL )
				CREATE TABLE #expenseByItemTotal ( ItemKey int NULL, ItemName VARCHAR(250) NULL, Amount money NULL, LineOrder int NULL, InvoiceLineKey int NULL, Taxable tinyint NULL, Taxable2 tinyint NULL )

				if @Expense = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(ItemKey, 0), sum(BillableCost)
					FROM	tMiscCost (NOLOCK)
					WHERE	ProjectKey = @ProjectKey
					AND     InvoiceLineKey IS NULL
					AND     ISNULL(WriteOff, 0) = 0
					AND     ExpenseDate <= @EndDate
					AND		ISNULL(OnHold, 0) = 0
					group by isnull(ItemKey, 0)

				if @ExpenseReport = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(er.ItemKey, 0), sum(er.BillableCost)
					FROM	tExpenseReceipt er (NOLOCK), tExpenseEnvelope en (nolock)
					WHERE	er.ProjectKey = @ProjectKey
					AND		er.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
					AND		en.Status = 4
					AND     er.InvoiceLineKey IS NULL
					AND		ISNULL(er.WriteOff, 0) = 0
					AND     er.ExpenseDate <= @EndDate
					AND		ISNULL(er.OnHold, 0) = 0
					AND		er.VoucherDetailKey IS NULL
					group by isnull(er.ItemKey, 0)

				if @Expense = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(vd.ItemKey, 0), sum(vd.BillableCost)
					FROM	tVoucherDetail vd (NOLOCK) ,tVoucher v  (NOLOCK)
					WHERE	vd.VoucherKey   = v.VoucherKey
					AND		vd.ProjectKey = @ProjectKey
					AND     vd.InvoiceLineKey IS NULL
					AND		ISNULL(vd.WriteOff, 0) = 0
					AND		v.Status = 4
					AND     v.InvoiceDate <= @EndDate
					AND		ISNULL(vd.OnHold, 0) = 0
					group by isnull(vd.ItemKey, 0)

				if @PO = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(pod.ItemKey, 0), sum(pod.BillableCost)
					FROM	tPurchaseOrderDetail pod (NOLOCK), tPurchaseOrder po (NOLOCK)
					WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = @ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		po.PODate <= @EndDate
					AND		po.Status = 4
					AND		po.POKind = 0
					AND		ISNULL(pod.OnHold, 0) = 0
					group by isnull(pod.ItemKey, 0)

				if @IO = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(pod.ItemKey, 0), sum(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(pod.BillableCost,0)
								When 1 then isnull(pod.PTotalCost,isnull(pod.TotalCost,0))
								When 2 then isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,isnull(pod.TotalCost,0)) end )
					FROM	tPurchaseOrderDetail pod (NOLOCK), tPurchaseOrder po (NOLOCK)
					WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = @ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @IOBeginDate
					AND		pod.DetailOrderDate <= @IOEndDate
					AND		po.Status = 4
					AND		po.POKind = 1
					AND		ISNULL(pod.OnHold, 0) = 0
					group by isnull(pod.ItemKey, 0)

				if @BC = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(pod.ItemKey, 0), sum(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(pod.BillableCost,0)
								When 1 then isnull(pod.PTotalCost,isnull(pod.TotalCost,0))
								When 2 then isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,isnull(pod.TotalCost,0)) end )
					FROM	tPurchaseOrderDetail pod (NOLOCK), tPurchaseOrder po (NOLOCK)
					WHERE	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = @ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @BCBeginDate
					AND		pod.DetailOrderDate <= @BCEndDate
					AND		po.Status = 4
					AND		po.POKind = 2
					AND		ISNULL(pod.OnHold, 0) = 0
					group by isnull(pod.ItemKey, 0)

				insert #expenseByItemTotal (ItemKey, Amount)
				select ItemKey, sum(Amount)
				from   #expenseByItem
				group by ItemKey

				update #expenseByItemTotal
				set    ItemName = i.ItemName
					  ,Taxable = i.Taxable
					  ,Taxable2 = i.Taxable2
				from   tItem i (nolock)
				where  #expenseByItemTotal.ItemKey = i.ItemKey

				update #expenseByItemTotal
				set    ItemName = ''[No Item]''
				where  ItemKey = 0 or ItemName is null

				update #expenseByItemTotal
				set    Taxable = isnull(Taxable, 0)
					  ,Taxable2 = isnull(Taxable2, 0)

				-- establish a stable line order (alphabetical by item name, like the Item/Service fixed fee lines above)
				select @LineOrder = 1
				select @EntityName = ''''
				while (1=1)
				begin
					select @EntityName = min(ItemName)
					from   #expenseByItemTotal
					where  ItemName > @EntityName

					if @EntityName is null
						break

					update #expenseByItemTotal
					set    LineOrder = @LineOrder
					where  ItemName = @EntityName

					select @LineOrder = @LineOrder + 1
				end

				-- Add a parent "Expenses" summary line (amount 0) that will contain all per-Item lines.
				-- Amount stays 0 so the invoice total is not double-counted (sptInvoiceRecalcAmounts sums every line).
				exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,null							-- TaskKey
					  ,''Expenses''					-- Line Subject
					  ,null                 		-- Line description
					  ,2                    		-- Bill From
					  ,0							-- Quantity
					  ,0							-- Unit Amount
					  ,0							-- Line Amount (header only - children carry the amounts)
					  ,1							-- line type (1 = header/summary)
					  ,@ParentLineKey				-- parent line key
					  ,@SalesAccountKey				-- Default Sales AccountKey
					  ,@DefaultClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,NULL							-- Work TypeKey
					  ,@PostSalesUsingDetail							-- PostInDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,@OfficeKey
					  ,null							-- DepartmentKey
					  ,@ExpensesLineKey output

				if @ExpensesLineKey <= 0
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return -1
				end

				select @CurLineOrder = min(LineOrder) from #expenseByItemTotal

				while @CurLineOrder is not null
				begin
					select @CurItemKey = ItemKey, @CurItemName = ItemName, @CurAmount = isnull(Amount, 0)
						  ,@CurTaxable = isnull(Taxable, 0), @CurTaxable2 = isnull(Taxable2, 0)
					from   #expenseByItemTotal
					where  LineOrder = @CurLineOrder

					select @CurEntityKey = null
					if @CurItemKey > 0
						select @CurEntityKey = @CurItemKey

					exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,@ProjectKey					-- ProjectKey
						  ,null							-- TaskKey
						  ,@CurItemName					-- Line Subject
						  ,null                 		-- Line description
						  ,2                    		-- Bill From
						  ,1							-- Quantity
						  ,@CurAmount					-- Unit Amount
						  ,@CurAmount					-- Line Amount
						  ,2							-- line type
						  ,@ExpensesLineKey				-- parent line key (nested under the "Expenses" summary line)
						  ,@SalesAccountKey				-- Default Sales AccountKey
						  ,@DefaultClassKey             -- Class Key
						  ,@CurTaxable					-- Taxable
						  ,@CurTaxable2					-- Taxable2
						  ,NULL							-- Work TypeKey
						  ,@PostSalesUsingDetail							-- PostInDetail
						  ,''tItem''						-- Entity
						  ,@CurEntityKey				-- EntityKey
						  ,@OfficeKey
						  ,null							--@DepartmentKey -- may need a department if department required
						  ,@NewInvoiceLineKey output

					if @NewInvoiceLineKey <= 0
					begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1
					end

					if @Expense = 1
					begin
						update tMiscCost
						set    InvoiceLineKey = @NewInvoiceLineKey
							  ,AmountBilled = BillableCost
						WHERE	ProjectKey = @ProjectKey
						AND     InvoiceLineKey IS NULL
						AND     ISNULL(WriteOff, 0) = 0
						AND     ExpenseDate <= @EndDate
						AND		ISNULL(OnHold, 0) = 0
						AND     isnull(ItemKey, 0) = @CurItemKey

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @ExpenseReport = 1
					begin
						update tExpenseReceipt
						set    InvoiceLineKey = @NewInvoiceLineKey
							  ,AmountBilled = BillableCost
						FROM	tExpenseEnvelope en (nolock)
						WHERE	tExpenseReceipt.ProjectKey = @ProjectKey
						AND		tExpenseReceipt.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
						AND		en.Status = 4
						AND     tExpenseReceipt.InvoiceLineKey IS NULL
						AND		ISNULL(tExpenseReceipt.WriteOff, 0) = 0
						AND     tExpenseReceipt.ExpenseDate <= @EndDate
						AND		ISNULL(tExpenseReceipt.OnHold, 0) = 0
						AND		tExpenseReceipt.VoucherDetailKey IS NULL
						AND     isnull(tExpenseReceipt.ItemKey, 0) = @CurItemKey

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @Expense = 1
					begin
						update tVoucherDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,AmountBilled = BillableCost
						FROM	tVoucher v  (NOLOCK)
						WHERE	tVoucherDetail.VoucherKey   = v.VoucherKey
						AND		tVoucherDetail.ProjectKey = @ProjectKey
						AND     tVoucherDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tVoucherDetail.WriteOff, 0) = 0
						AND		v.Status = 4
						AND     v.InvoiceDate <= @EndDate
						AND		ISNULL(tVoucherDetail.OnHold, 0) = 0
						AND     isnull(tVoucherDetail.ItemKey, 0) = @CurItemKey

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @PO = 1
					begin
						update tPurchaseOrderDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,tPurchaseOrderDetail.AccruedCost =
								CASE
									WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
									ELSE 0
								END
								,AmountBilled = isnull(BillableCost,0)
						FROM	tPurchaseOrder po (NOLOCK)
						WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
						AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
						AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
						AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
						AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
						AND		po.PODate <= @EndDate
						AND		po.Status = 4
						AND		po.POKind = 0
						AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
						AND     isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @IO = 1
					begin
						update tPurchaseOrderDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,tPurchaseOrderDetail.AccruedCost =
								CASE
									WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
									ELSE 0
								END
								,AmountBilled = isnull(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(BillableCost,0)
								When 1 then isnull(PTotalCost,isnull(TotalCost,0))
								When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
						FROM	tPurchaseOrder po (NOLOCK)
						WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
						AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
						AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
						AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
						AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
						AND		tPurchaseOrderDetail.DetailOrderDate >= @IOBeginDate
						AND		tPurchaseOrderDetail.DetailOrderDate <= @IOEndDate
						AND		po.Status = 4
						AND		po.POKind = 1
						AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
						AND     isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @BC = 1
					begin
						update tPurchaseOrderDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,tPurchaseOrderDetail.AccruedCost =
								CASE
									WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
									ELSE 0
								END
								,AmountBilled = isnull(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(BillableCost,0)
								When 1 then isnull(PTotalCost,isnull(TotalCost,0))
								When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
						FROM	tPurchaseOrder po (NOLOCK)
						WHERE	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
						AND		tPurchaseOrderDetail.ProjectKey = @ProjectKey
						AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
						AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
						AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
						AND		tPurchaseOrderDetail.DetailOrderDate >= @BCBeginDate
						AND		tPurchaseOrderDetail.DetailOrderDate <= @BCEndDate
						AND		po.Status = 4
						AND		po.POKind = 2
						AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
						AND     isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					select @CurLineOrder = min(LineOrder) from #expenseByItemTotal where LineOrder > @CurLineOrder
				end
			end -- BillExpensesByItem = 1

				-- This will force the Taxable fields if the pref or the project requires them
				exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

				 -- before we leave, better to recalc the amounts in the header  
				exec sptInvoiceRecalcAmounts @NewInvoiceKey 
	
				-- Calculate the line order and position
				exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0


		end

		if @NewInvoiceKey >0
		begin
			select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

			select @Reference = i.InvoiceNumber
				  ,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @NewInvoiceKey

			select @Reference = isnull(@Reference,'''')
				  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through fixed fee mass billing''
			else
				select @Comments = ''Invoice was generated through fixed fee mass billing''

			-- log how we billed
			select @Comments = @Comments + '' ('' + cast(@PercentBudget as varchar(50))
			if @BillAs = 0 
				select @Comments = @Comments + ''% of Remaining)''
			else
				select @Comments = @Comments + ''% of Total)''
			
			select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey
		end


		-- now do rollups on projects
		 exec sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey, 1, 0

		return @NewInvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateSequence]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateSequence]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateSequence]
	@ActivityKey int,
	@Sequence int
AS

/*
|| When      Who Rel      What
|| 6/17/09   CRG 10.5.0.0 Created because when events are synced with CalDAV, their Sequence numbers may have already been defined.
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time
*/

	UPDATE	tActivity
	SET		Sequence = @Sequence
	WHERE	ActivityKey = @ActivityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectCopyEntity]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectCopyEntity]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptProjectCopyEntity]
 (
 @UserKey int,
 @ProjectName nvarchar(100),
 @ProjectNumber varchar(100),
 @CompanyKey int,
 @ProjectStatusKey int,
 @ProjectTypeKey int,
 @ClientDivisionKey int,
 @ClientProductKey int,
 @OfficeKey int,
 @GLCompanyKey int,
 @ClassKey int,
 @ClientKey int,
 @RequestKey int,
 @CopyProjectKey int,
 @CopyEstimate tinyint,
 @CopyFrom int, -- 0: from project,  1: from project type
 @EstimateInternalApprover int,
 @TeamKey int,
 @LeadKey int,
 @Entity varchar(50),  -- ''tLead'' for now
 @EntityKey int,       -- LeadKey
 @ProjectColor varchar(10),  
 @ModelYear varchar(10) = null,
 @CampaignKey int = null,
 @IsLegacy bit = 0, --To be deprecated
 @oIdentity INT OUTPUT
 )
AS --Encrypt

  /*
  || When     Who Rel      What
  || 03/22/10 GHL 10.520   Cloned sptProjectCopy for opportunity  
  || 04/02/10 GHL 10.521   Updating now tLead.ConvertEntity,tLead.ConvertEntityKey
  || 04/08/10 GHL 10.522   (78512) Checking existence of template project before executing sp
  ||                        if does not exist, bounce back to sptProjectCopy
  || 04/22/10 GHL 10.522   Moved patch of 04/08/10 to the VB section. Added LeadKey
  || 08/19/10 GHL 10.534   (87237 + 87571) Always copy of the estimates for the entity (not dependent on @CopyEstimate = 1)
  ||                       copying estimates from the copyProjectKey still depend on @CopyEstimate = 1 
  || 11/11/10 GHL 10.538   (94144) Added param UserKey when calling sptProjectCopyEstimates
  || 12/1/10  RLB 10.5.3.9 (94833) just adding Default User Service instead of all users services
  || 07/19/11 RLB 10.5.4.6 (116508) set project Billing Method from copied project
  || 09/09/11 RLB 10.5.4.8 (120913) Set Date Converted on Opportunity
  || 11/22/11 RLB 10.5.5.1 (124338) If client has a Default EstimateTemplate or layout set that on the Estimates
  || 02/12/13 GHL 10.5.6.5 (167857) Added ModelYear for a customization for Spark44
  || 06/18/13 GHL 10.5.6.9 (181721) Added campaign key for new project numbers by campaign
  || 08/26/13 RLB 10.5.7.1 (170225) Set BillingManagerKey from Client Default
  || 11/25/13 RLB 10.5.7.4 (197740) Adding some validation for client and selected gl company 
  || 11/05/14 RLB 10.5.8.6 Copy AnyoneChargeTime over to new project from template
  || 02/06/15 GHL 10.5.8.8 When copying defaults from the client, do not forget the title info
  || 09/25/15 GHL 10.5.9.6 Added call to sptProjectWebDavSafeFolders like in sptProjectCopy
  ||                       Added parameter template to project create stored proc
  || 10/30/15 WDF 10.5.9.7 (257042) Added customization for ''AVERA''
  || 03/13/17 MFT 10.6.1.4 (335024) Added @IsLegacy and logic. May be removed when this sp is no longer called from classic
  || 04/12/17 WDF 10.6.1.5 (341220) Passed @IsLegacy to exec of sptProjectCreate which was missed in Rel. 10.6.1.4 (335024)
  || 05/31/18 GHL 18.6.0.0  Added parameter @ValidateRetainer to sptProjectCreate
  || 10/12/20 CRG 20.1.0.0 (532716) Removed the Master Task check
  || 11/23/20 RLS 20.1.2.0 (535729) Changed @ProjectName to nvarchar
  || 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
  || 07/14/26 RLB 26.08.16 (731407) Copy DoNotPostWIP over to new project from template
  ||
 */

	DECLARE @RetVal INT
	       ,@ProjectKey INT
	       ,@SpecCustomFieldKey INT
 

declare @kCopyFromProject int		select @kCopyFromProject = 0
declare @kCopyFromProjectType int	select @kCopyFromProjectType = 1
  
declare @kByTaskOnly int            select @kByTaskOnly = 1
declare @kByTaskService int         select @kByTaskService = 2
declare @kByTaskPerson int          select @kByTaskPerson = 3
declare @kByServiceOnly int         select @kByServiceOnly = 4
declare @kBySegmentService int      select @kBySegmentService = 5  -- Unlikely here since it is only for campaigns 


  DECLARE @RequireMasterTask INT
  declare @Customizations varchar(1000)
  declare @SparkCustomization int
  declare @AveraCustomization int
  declare @RestrictToGLCompany int
 
  SELECT @RequireMasterTask = ISNULL(RequireMasterTask, 0)
        ,@Customizations = UPPER(ISNULL(Customizations, ''''))
		,@RestrictToGLCompany = isnull(RestrictToGLCompany, 0)
  FROM   tPreference (NOLOCK)
  WHERE  CompanyKey = @CompanyKey 
  
  IF @RestrictToGLCompany = 1
  BEGIN
	IF NOT EXISTS (SELECT 1
				   FROM  tGLCompanyAccess (NOLOCK)
				   WHERE CompanyKey = @CompanyKey
				    AND Entity = ''tCompany''
					AND EntityKey = @ClientKey
					AND GLCompanyKey = @GLCompanyKey)
					RETURN -15
  END

select @AveraCustomization = 0
if (charindex(''AVERA'',@Customizations) > 0) and (@CopyFrom = @kCopyFromProject)
begin
	if @CopyProjectKey > 0
	begin 
		if not exists(select ProjectNumber from tProject (nolock) where ProjectKey = @CopyProjectKey and Template = 1)
		begin
			select @AveraCustomization = 1
		end
	end
end

if charindex(''SPARK44'',@Customizations) > 0
begin
	select @SparkCustomization = 1

	if @ModelYear is null
	begin
		if @CopyProjectKey > 0
			select @ModelYear = ModelYear from tProject (nolock) where ProjectKey = @CopyProjectKey

		if @ModelYear is null
			select @ModelYear = DATEPART("YEAR",GETDATE()) - 2000

		if len(@ModelYear) = 1
			select @ModelYear = ''0'' + @ModelYear

	end

end
else
	select @SparkCustomization = 0

	        	
	-- First call sptProjectCreate
	EXEC @RetVal = sptProjectCreate
				@UserKey,
				@ProjectName,
				@ProjectNumber,
				@CompanyKey,
				@ProjectStatusKey,
				@ProjectTypeKey,
				@ClientDivisionKey,
				@ClientProductKey,
				@OfficeKey,
				@GLCompanyKey,
				@ClientKey,
				@CampaignKey,
				@ProjectColor,
				@SparkCustomization,
				@AveraCustomization,
				@CopyProjectKey,
				@ModelYear,
				0, --@Template
				1, --@ValidateRetainer
				@IsLegacy, 
				@ProjectKey OUTPUT
	
	IF @RetVal <> 1 
	BEGIN
		SELECT @oIdentity = 0
		RETURN @RetVal
	END
	 
	SELECT @oIdentity = @ProjectKey
	
	--Set the WebDav safe folder names
	EXEC sptProjectWebDavSafeFolders @ProjectKey, 0

	IF @RequestKey > 0
	begin
		
		Update	tProject
		Set		RequestKey = @RequestKey
		Where	ProjectKey = @ProjectKey
		
	end

	DECLARE @GetRateFrom SMALLINT
	       ,@GetMarkupFrom SMALLINT
	
	IF (ISNULL(@CopyProjectKey, 0) = 0) AND (@CopyFrom = @kCopyFromProject)
	BEGIN
		-- copy from project but there is no project to copy
		
		IF ISNULL(@ClientKey, 0) > 0
		BEGIN
			UPDATE	tProject 
			SET		tProject.GetRateFrom =
				CASE @IsLegacy
					WHEN 1 THEN ISNULL(cl.GetRateFrom, 2)
					ELSE
						CASE ISNULL(cl.GetRateFrom, 2)
							WHEN 1 THEN 2
							WHEN 6 THEN 4
							ELSE ISNULL(cl.GetRateFrom, 2)
						END
				END
				,tProject.TimeRateSheetKey = ISNULL(cl.TimeRateSheetKey, 0)
				,tProject.TitleRateSheetKey = ISNULL(cl.TitleRateSheetKey, 0)
				,tProject.HourlyRate = ISNULL(cl.HourlyRate, 0)
				,tProject.GetMarkupFrom = ISNULL(cl.GetMarkupFrom, 2)
				,tProject.ItemRateSheetKey = ISNULL(cl.ItemRateSheetKey, 0)
				,tProject.ItemMarkup = ISNULL(cl.ItemMarkup, 0)			  
			FROM	tCompany cl (NOLOCK)
			WHERE	cl.CompanyKey = @ClientKey
			AND		tProject.ProjectKey = @ProjectKey
		END
		
		-- If a team was specified, add the people in it
		IF ISNULL(@TeamKey, 0) > 0
			INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
			SELECT DISTINCT @ProjectKey  -- new ProjectKey
					,tTeamUser.UserKey, 0
			FROM	tTeamUser (NOLOCK)
			INNER JOIN tUser u (nolock) ON tTeamUser.UserKey = u.UserKey
			WHERE	tTeamUser.TeamKey = @TeamKey
			AND		u.Active = 1
			AND		tTeamUser.UserKey not in (Select UserKey from tAssignment (nolock) Where ProjectKey = @ProjectKey)

		UPDATE tAssignment 
		SET    tAssignment.HourlyRate = u.HourlyRate
		FROM   tUser u (NOLOCK)
		WHERE  tAssignment.UserKey = u.UserKey
		AND    tAssignment.ProjectKey = @ProjectKey
	END	
	ELSE
	BEGIN
		-- there could be a valid project to copy OR we copy from a project type 
		
		IF @CopyProjectKey > 0
		UPDATE
			tProject
		SET
			tProject.GetRateFrom =
				CASE @IsLegacy
					WHEN 1 THEN p2.GetRateFrom
					ELSE
						CASE p2.GetRateFrom
							WHEN 1 THEN 2
							WHEN 6 THEN 4
							ELSE p2.GetRateFrom
						END
				END,
			tProject.TimeRateSheetKey = p2.TimeRateSheetKey,
			tProject.TitleRateSheetKey = p2.TitleRateSheetKey,
			tProject.HourlyRate = p2.HourlyRate,
			tProject.GetMarkupFrom = p2.GetMarkupFrom,
			tProject.ItemRateSheetKey = p2.ItemRateSheetKey,
			tProject.ItemMarkup = p2.ItemMarkup,
			tProject.IOCommission = p2.IOCommission,
			tProject.BCCommission = p2.BCCommission,
			tProject.ScheduleDirection = p2.ScheduleDirection,
			tProject.ClassKey = ISNULL(p2.ClassKey, @ClassKey),
			tProject.BillingMethod = p2.BillingMethod,
			tProject.ExpensesNotIncluded = p2.ExpensesNotIncluded
		FROM tProject
			,tProject p2 (NOLOCK)
		WHERE
			tProject.ProjectKey = @ProjectKey 
		AND  
			p2.ProjectKey = @CopyProjectKey
			
		-- Check if we need to get defaults from the client
		If ISNULL(@ClientKey, 0) > 0
		BEGIN
			SELECT @GetRateFrom =
				CASE @IsLegacy
					WHEN 1 THEN GetRateFrom
					ELSE
						CASE GetRateFrom
							WHEN 1 THEN 2
							WHEN 6 THEN 4
							ELSE GetRateFrom
						END
				END
				,@GetMarkupFrom = GetMarkupFrom
			FROM   tProject (NOLOCK)
			WHERE  ProjectKey = @ProjectKey
			
			-- If Get Rate from Client
			IF @GetRateFrom = 1
			BEGIN
				UPDATE tProject 
				SET
					tProject.GetRateFrom =
						CASE @IsLegacy
							WHEN 1 THEN ISNULL(cl.GetRateFrom, 2)
							ELSE
								CASE ISNULL(cl.GetRateFrom, 2)
								WHEN 1 THEN 2
								WHEN 6 THEN 4
								ELSE ISNULL(cl.GetRateFrom, 2)
							END
					END
					,tProject.TimeRateSheetKey = ISNULL(cl.TimeRateSheetKey, 0)
					,tProject.TitleRateSheetKey = ISNULL(cl.TitleRateSheetKey, 0)
					,tProject.HourlyRate = ISNULL(cl.HourlyRate, 0)
				FROM   tCompany cl (NOLOCK)
				WHERE  cl.CompanyKey = @ClientKey
				AND    cl.GetRateFrom IS NOT NULL
				AND    tProject.ProjectKey = @ProjectKey
			END	

			-- If Get Markup  from Client
			IF @GetMarkupFrom = 1
			BEGIN
				UPDATE tProject 
				SET    tProject.GetMarkupFrom = ISNULL(cl.GetMarkupFrom, 2)
					  ,tProject.ItemRateSheetKey = ISNULL(cl.ItemRateSheetKey, 0)
					  ,tProject.ItemMarkup = ISNULL(cl.ItemMarkup, 0)
				FROM   tCompany cl (NOLOCK)
				WHERE  cl.CompanyKey = @ClientKey
				AND    cl.GetMarkupFrom IS NOT NULL
				AND  tProject.ProjectKey = @ProjectKey
			END	
		END
			
		-- Now copy detail from CopyProjectKey to ProjectKey
		IF @CopyProjectKey > 0
		BEGIN
		
			UPDATE
				tProject
			SET
				tProject.BillingContact = CASE 
					WHEN tProject.ClientKey = p2.ClientKey THEN p2.BillingContact
					ELSE NULL
					END,
				tProject.OverrideRate = p2.OverrideRate,
				tProject.NonBillable = p2.NonBillable,
				tProject.ScheduleDirection = p2.ScheduleDirection,
				tProject.AnyoneChargeTime = p2.AnyoneChargeTime,
				tProject.DoNotPostWIP = p2.DoNotPostWIP
			FROM tProject (NOLOCK)
				 ,tProject p2 (NOLOCK)
			WHERE
				tProject.ProjectKey = @ProjectKey 
			AND  
				p2.ProjectKey = @CopyProjectKey

			 -- sptProjectCreate assigns people with AutoAssign = 0 and the creator even if AutoAssign = 0
			 -- Copy now people from the old project
			INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
			SELECT DISTINCT @ProjectKey  -- new ProjectKey
					,tAssignment.UserKey, 0
			FROM	tAssignment (NOLOCK)
			INNER JOIN tUser u (nolock) ON tAssignment.UserKey = u.UserKey
			WHERE	ProjectKey = @CopyProjectKey 
			AND		u.Active = 1
			AND		tAssignment.UserKey not in (Select UserKey from tAssignment (nolock) Where ProjectKey = @ProjectKey)

		END
		
		-- If a team was specified, add the people in it
		IF ISNULL(@TeamKey, 0) > 0
			INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
			SELECT DISTINCT @ProjectKey  -- new ProjectKey
					,tTeamUser.UserKey, 0
			FROM	tTeamUser (NOLOCK)
			INNER JOIN tUser u (nolock) ON tTeamUser.UserKey = u.UserKey
			WHERE	tTeamUser.TeamKey = @TeamKey
			AND		u.Active = 1
			AND		tTeamUser.UserKey not in (Select UserKey from tAssignment (nolock) Where ProjectKey = @ProjectKey)

		UPDATE tAssignment 
		SET    tAssignment.HourlyRate = u.HourlyRate
		FROM   tUser u (NOLOCK)
		WHERE  tAssignment.UserKey = u.UserKey
		AND    tAssignment.ProjectKey = @ProjectKey
		
		if @CopyFrom = @kCopyFromProject
		BEGIN			
			-- cannot use sptProjectCopyTasks because it copies tasks from tTask
			--exec sptProjectCopyTasks @ProjectKey, @CopyProjectKey, @CopyEstimate, @UserKey

			-- copy tasks from tEstimateTaskTemp
			-- this will also copy estimates of type task only (1), task/service (2), task/user (3)
			exec sptProjectCopyTasksEntity @ProjectKey, @CopyProjectKey, @CopyEstimate, @Entity, @EntityKey, @UserKey
		END
		
		if @CopyFrom = @kCopyFromProjectType
		BEGIN
			
			Declare @MaxOrder int, @NewTaskKey int, @CurOrder int, @CurMTID varchar(100)
			Select @MaxOrder = Max(DisplayOrder), @CurOrder = 0 from tProjectTypeMasterTask (NOLOCK) Where ProjectTypeKey = @ProjectTypeKey
			
			While @CurOrder < @MaxOrder
			BEGIN
				Select @CurOrder = @CurOrder + 1
				Select @CurMTID = TaskID from tProjectTypeMasterTask (NOLOCK) 
					inner join tMasterTask (NOLOCK) on tProjectTypeMasterTask.MasterTaskKey = tMasterTask.MasterTaskKey
				Where ProjectTypeKey = @ProjectTypeKey and DisplayOrder = @CurOrder
				if @CurMTID is not null
				BEGIN
					exec sptTaskQuickInsert @ProjectKey, @CurMTID, NULL, 0, 1, @NewTaskKey OUTPUT
				END
			END
			
			exec sptTaskOrder @ProjectKey, 0, 0, 0
		END
		
		
		If isnull(@EstimateInternalApprover, 0) <> 0
			UPDATE tEstimate
			SET    InternalApprover = @EstimateInternalApprover
			WHERE  ProjectKey = @ProjectKey
			AND    InternalStatus = 1
			
	END
		
	-- this will copy estimates of type service only (4), segment/service (5), also copy the approval status
	exec sptProjectCopyEstimates @Entity, @EntityKey,@ProjectKey, 1, @UserKey

	-- Defaulting Layout, Estimate Template and Billing Manager from client onto Estimate
	DECLARE @DefaultLayoutKey int, @DefaultEstimateTemplateKey int, @DefaultBillingManagerKey int
	If ISNULL(@ClientKey, 0) > 0
		Select @DefaultLayoutKey = ISNULL(LayoutKey, 0), @DefaultEstimateTemplateKey = ISNULL(EstimateTemplateKey, 0) , @DefaultBillingManagerKey = ISNULL(BillingManagerKey, 0 ) from tCompany (NOLOCK) Where CompanyKey = @ClientKey

	if ISNULL(@DefaultEstimateTemplateKey, 0) <> 0
		UPDATE tEstimate
		SET EstimateTemplateKey = @DefaultEstimateTemplateKey
		WHERE ProjectKey = @ProjectKey

	if ISNULL(@DefaultLayoutKey, 0) <> 0
		UPDATE tEstimate
		SET LayoutKey = @DefaultLayoutKey
		WHERE ProjectKey = @ProjectKey

	if ISNULL(@DefaultBillingManagerKey, 0) <> 0
			UPDATE tProject
			SET BillingManagerKey = @DefaultBillingManagerKey
			WHERE ProjectKey = @ProjectKey
	
	Delete tProjectUserServices Where ProjectKey = @ProjectKey
	
	Insert tProjectUserServices (ProjectKey, UserKey, ServiceKey)
		Select DISTINCT @ProjectKey, u.UserKey, u.DefaultServiceKey
		from tUser u (nolock) 
		inner join tAssignment a (nolock) on u.UserKey = a.UserKey  
		Where ISNULL(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
		And   a.ProjectKey = @ProjectKey And u.DefaultServiceKey IS NOT NULL

	UPDATE	tProject
	SET		TeamKey = @TeamKey
	       ,ModelYear = @ModelYear
	WHERE	ProjectKey = @ProjectKey

	IF @Entity = ''tLead''
	BEGIN
		UPDATE	tProject
		SET		LeadKey = @EntityKey
		WHERE	ProjectKey = @ProjectKey
		
		UPDATE tLead
		SET    ConvertEntity = ''tProject''
		      ,ConvertEntityKey = @ProjectKey
		      ,ConvertedByKey = @UserKey
			  ,DateConverted = CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime)
		WHERE  LeadKey = @EntityKey
		      
	END
	ELSE
		UPDATE	tProject
		SET		LeadKey = @LeadKey
		WHERE	ProjectKey = @ProjectKey
			
			
  -- also since we copy now the approval status, rollup the estimates data
  exec sptEstimateRollupDetail @ProjectKey
  			
 /* set nocount on */
 return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIReassignTask]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIReassignTask]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIReassignTask]
(
    @CompanyKey     int,
    @UserKey        int,
    @ProjectNumber  varchar(100),
    @TaskID         nvarchar(30),
    @FromUser       varchar(100),
    @ToUser         varchar(100),
    @Comment        varchar(4000) = null,
    @Hours          decimal(24, 4) = null
)
AS --Encrypt

/*
|| When      Who Rel        What
|| 03/30/26  AI  26.03.30   Created - reassign a task user record from one user to another
|| 04/08/26  GG  26.04.08   Modified - supports name, userid, or email lookup
|| 04/10/26  CRG 26.05.17   Added Hours parm
|| 05/22/26  CRG 26.06.14   Modified parameter names to match the CS code
|| 05/25/26  AI  26.05.25   Replaced inline GL company + assignment checks with spCheckAccess (tProject).
||                          Bug fix: previous code REQUIRED prjAccessAny and would deny users who only
||                          had explicit project assignment. spCheckAccess correctly treats assignment
||                          as a valid path when prjAccessAny is absent. Feature-right check
||                          (schedEdit / prjEdit) is preserved separately.
|| 05/28/26  AI  26.05.28   spCheckAccess (tProject) replaces inline checks. Bug fix: old code denied users with only tAssignment access.
|| 06/15/26  GAR 26.06.14   (730907) Fixed an issue with rights - Claude was using prjEdit and schedEdit and there is no such thing - switched to prjedittasks
|| 07/10/26  GAR 26.07.19   Added gating security - requires right prjedittasks.
*/

set nocount on

    declare @ProjectKey         int
    declare @TaskKey            int
    declare @OldUserKey         int
    declare @NewUserKey         int
    declare @NewUserServiceKey  int
    declare @TaskUserKey        int
    declare @ErrorCount         int
    declare @SecurityGroupKey   int
    declare @IsAdministrator    bit
    declare @HasScheduleEditRight tinyint
    declare @AccessOK           int

    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 1. Required-field validation
    -- ------------------------------------------------------------------
    if @ProjectNumber is null or LTRIM(RTRIM(@ProjectNumber)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''ProjectNumber is required.'', ''projectNumber'')

    if @TaskID is null or LTRIM(RTRIM(@TaskID)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''TaskID is required.'', ''taskID'')

    if @FromUser is null or LTRIM(RTRIM(@FromUser)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''OldPerson is required.'', ''oldPerson'')

    if @ToUser is null or LTRIM(RTRIM(@ToUser)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''NewPerson is required.'', ''newPerson'')

    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -100
    end

    -- ------------------------------------------------------------------
    -- 2. Resolve users + project
    -- ------------------------------------------------------------------
    select @OldUserKey = MIN(UserKey) from tUser (nolock)
    where  CompanyKey = @CompanyKey
      and  (UPPER(Email) = UPPER(@FromUser)
            or UPPER(UserID) = UPPER(@FromUser)
            or UPPER(FirstName + '' '' + LastName) = UPPER(@FromUser))

    if @OldUserKey is null
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found for OldPerson: '' + @FromUser, ''oldPerson'')

    select @NewUserKey = MIN(UserKey) from tUser (nolock)
    where  CompanyKey = @CompanyKey
      and  (UPPER(Email) = UPPER(@ToUser)
            or UPPER(UserID) = UPPER(@ToUser)
            or UPPER(FirstName + '' '' + LastName) = UPPER(@ToUser))

    if @NewUserKey is null
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found for NewPerson: '' + @ToUser, ''newPerson'')

    select @ProjectKey = ProjectKey from tProject (nolock)
    where  CompanyKey = @CompanyKey and UPPER(ProjectNumber) = UPPER(@ProjectNumber)

    if @ProjectKey is null
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Project not found for ProjectNumber: '' + @ProjectNumber, ''projectNumber'')

    select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
    if @ErrorCount > 0
    begin
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Record-level access gate via spCheckAccess (tProject)
    --    Replaces the old inline GL company + prjAccessAny check.
    -- ------------------------------------------------------------------
    exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey

    if @AccessOK <> 1
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. Feature-right gate: must be able to edit project schedules
    -- ------------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey,
           @IsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    set @HasScheduleEditRight = 0
    if @IsAdministrator = 1
        set @HasScheduleEditRight = 1
    else if exists (
        select 1 from tRight r (nolock)
        inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
        where  ra.EntityType = ''Security Group''
          and  ra.EntityKey  = @SecurityGroupKey
          and  r.RightID in (''prjedittasks'')
    )
        set @HasScheduleEditRight = 1

    if @HasScheduleEditRight = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to edit project schedules.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 5. Resolve task + task-user assignment
    -- ------------------------------------------------------------------
    select @TaskKey = TaskKey from tTask (nolock)
    where  ProjectKey = @ProjectKey and UPPER(TaskID) = UPPER(@TaskID)

    if @TaskKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'',
                ''Task not found for TaskID: '' + @TaskID + '' in project: '' + @ProjectNumber, ''taskID'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    select @TaskUserKey = MIN(TaskUserKey) from tTaskUser (nolock)
    where  TaskKey = @TaskKey and UserKey = @OldUserKey

    if @TaskUserKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'',
                ''Task assignment not found for OldPerson: '' + @FromUser + '' on TaskID: '' + @TaskID, ''oldPerson'')
        select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 6. Perform the reassignment
    -- ------------------------------------------------------------------
    select @NewUserServiceKey = DefaultServiceKey from tUser (nolock) where UserKey = @NewUserKey

    if not exists (
        select 1 from tAssignment (nolock) where ProjectKey = @ProjectKey and UserKey = @NewUserKey
    )
        insert into tAssignment (ProjectKey, UserKey) values (@ProjectKey, @NewUserKey)

    if ISNULL(@Hours, 0) = 0
    begin
        update tTaskUser
        set    UserKey    = @NewUserKey,
               ServiceKey = @NewUserServiceKey,
               Comments   = ISNULL(@Comment, Comments)
        where  TaskUserKey = @TaskUserKey
    end
    else
    begin
        declare @OldHours decimal(24, 4)

        select @OldHours = Hours from tTaskUser (nolock) where TaskUserKey = @TaskUserKey

        if @Hours > @OldHours
            set @OldHours = 0
        else
            set @OldHours = @OldHours - @Hours

        update tTaskUser set Hours = @OldHours where TaskUserKey = @TaskUserKey

        insert tTaskUser (TaskKey, UserKey, ServiceKey, Hours)
        values (@TaskKey, @NewUserKey, @NewUserServiceKey, @Hours)
    end

    -- ------------------------------------------------------------------
    -- 7. Notification context + success result
    -- ------------------------------------------------------------------
    declare @OldUserName varchar(100), @NewUserName varchar(100),
            @OldEmail    varchar(100), @NewEmail    varchar(100),
            @UserEmail   varchar(100), @Culture     int

    select @OldUserName = UserName, @OldEmail = Email from vUserName where UserKey = @OldUserKey
    select @NewUserName = UserName, @NewEmail = Email from vUserName where UserKey = @NewUserKey

    select @UserEmail = Email,
           @Culture   = ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture))
    from   vUserName u
    left join tOffice o (nolock) on u.OfficeKey = o.OfficeKey
    left join tPreference p (nolock) on ISNULL(u.OwnerCompanyKey, u.CompanyKey) = p.CompanyKey
    where  u.UserKey = @UserKey

    -- Warnings result set (consistent shape)
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    select @TaskUserKey  as taskUserKey,
           @TaskKey      as taskKey,
           @TaskID       as taskID,
           @ProjectKey   as projectKey,
           @ProjectNumber as projectNumber,
           @OldUserKey   as fromUserKey,
           @OldUserName  as fromUserName,
           @OldEmail     as fromEmail,
           @NewUserKey   as toUserKey,
           @NewUserName  as toUserName,
           @NewEmail     as toEmail,
           @UserEmail    as userEmail,
           @Culture      as culture,
           ''reassigned''  as action

    drop table #errors
    return 0

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCF_GetFieldPrintData]'
GO
IF OBJECT_ID(N'[dbo].[spCF_GetFieldPrintData]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spCF_GetFieldPrintData]

AS --Encrypt
/*
|| When      Who Rel      What
|| 07/17/18  WDF 18.8.0   New.  Used in spCF_GetFieldData to remove print fields that should not display because either   
||                        they do not have FieldValues or they are dependant and do not meet the requirements.
|| 08/14/18  WDF 18.9.0   (415141) Put in ''DisplayType'' exclusion so those types will NOT be dropped and will be allowed to print
|| 08/24/18  WDF 18.9.0   (416610) Change ''DisplayWhenValue'' from varchar(50) to varchar(1000)
|| 11/01/18  RLB 18.9.3   (428652) trying display text separators even ones with Display when options
|| 08/28/19  RLB 19.0.9.0 (456639) change fieldvalue to varchar max
|| 11/01/19  WDF 19.1.1.0 (486124) Changed @FieldValue from varchar(8000) to (max)
|| 06/26/20  RLS 20.0.7  (518686) Converted @DisplayWhenValue and @FieldValue to nvarchar
*/

DECLARE @CompanyKey INT, @FieldDefKey INT, @DisplayWhenFieldDefKey int, @DisplayWhen int, @DisplayType int, @DisplayWhenValue nvarchar(1000), @FieldValue nvarchar(max)
DECLARE @Idx int, @RowNbr int, @LevelNbr int, @GroupNbr int, @MaxGroupNbr int, @RowCnt int

	CREATE TABLE #DisplayHierchy
	(Childkey int not null
	,ParentKey int not null)

	CREATE TABLE #CF_HIER
	(GroupNbr int not null
	,LevelNbr int not null
	,FieldDefKey int not null
	,DisplayWhen tinyint not null 
	,DisplayWhenFieldDefKey int null
	,DisplayWhenValue nvarchar(1000) null
	,FieldValue varchar(MAX) null
	,DisplayType int not null)

	INSERT INTO #DisplayHierchy
	SELECT  FieldDefKey
			,CASE ISNULL(DisplayWhen, 0)
				WHEN 0 THEN FieldDefKey
				ELSE ISNULL(DisplayWhenFieldDefKey, FieldDefKey)
			END
	 FROM #TempCF

	SELECT @FieldDefKey = -1
	SELECT @Idx = 0

	--
	-- #TempCF is generated in spCF_GetFieldData
	--
	-- This loop will set up a hierarchy of Parent and Child keys 
	-- The hierarchy is comprised of groups of Parent/Child keys which are identified by a GroupNbr.  
	-- Within each group is a Level identifier with the Parent at the 0 level and subsequent Parent/Children 
	-- at levels 1,2,3 etc depending at how nested they are.  A child can be a Parent but the Top Parent is the
	-- only one at Level 0.
	-- Example:   A is the parent; B is dependant on A; C is dependant on B; D is dependant on C
	--            The Hierarchey is as follows...
	--                
	--            Group    Level   FieldDefKey
	--              0         0        A
	--              0         1        B (Dependant on A)
	--              0         2        C (Dependant on B)
	--              0         3        D (Dependant on C)
	--               
	--    If B''s dependancy on A is not met, then we do not want C or D to display either.  So, the lower levels should
	--    not display if any of the higher levels do not meet their dependancy requirements.    
	--        
	--    Note there could be multiple fields at the same level if they are all dependant on the same  Parent/Child.
	--    
	--    We now pass in ''DisplayType'' to exclude certain types that should always be allowed to print.
	--
	WHILE (1=1)
	BEGIN
		SELECT @FieldDefKey = MIN(FieldDefKey)
		  FROM #TempCF
		 WHERE ISNULL(DisplayWhen, 0) = 0
		   AND DisplayType NOT IN (12)  -- Display Only
		   AND FieldDefKey > @FieldDefKey
	
		IF @FieldDefKey IS NULL
			BREAK
		
		UPDATE #DisplayHierchy SET ParentKey = 0 WHERE Childkey = @FieldDefKey;

		WITH CTE ([level], Childkey, ParentKey)
		AS (
			SELECT CAST(0 AS tinyint) AS [level], Childkey, ParentKey
				FROM #DisplayHierchy (nolock)
				WHERE Childkey = @FieldDefKey
				AND ParentKey = 0
			UNION ALL
			SELECT CAST(c.[level] + 1 AS tinyint) AS [level], a.Childkey, a.ParentKey
				FROM #DisplayHierchy a (nolock) INNER JOIN CTE c ON (a.ParentKey = c.Childkey)
			)

		INSERT INTO #CF_HIER
		SELECT  @Idx, [level], fd.FieldDefKey, ISNULL(fd.DisplayWhen, 0), fd.DisplayWhenFieldDefKey, fd.DisplayWhenValue, fd.FieldValue, fd.DisplayType
			FROM CTE c INNER JOIN #TempCF fd ON (c.Childkey = fd.FieldDefKey)
		ORDER BY fd.DisplayWhen, c.[level];

		SELECT @RowCnt = @@ROWCOUNT

		IF @RowCnt > 1
			SELECT @Idx = @Idx + 1

		UPDATE #DisplayHierchy SET ParentKey = @FieldDefKey where Childkey = @FieldDefKey
	END

	-- This adds a row number so we can loop through using that uniques identifier
	SELECT ROW_NUMBER() OVER(ORDER BY GroupNbr, LevelNbr) AS RowNbr, GroupNbr, LevelNbr, FieldDefKey, DisplayWhen, DisplayWhenFieldDefKey, DisplayWhenValue, FieldValue, DisplayType
	  INTO #CF_HIER_GRP
      FROM #CF_HIER ORDER BY GroupNbr, LevelNbr

	SELECT @GroupNbr = 0
	SELECT @MaxGroupNbr = MAX(GroupNbr) FROM #CF_HIER

	-- Loop through and remove those FieldDefs from the #TempCF that should not print if they either
	-- do not have a ''fieldvalue'', their dependancy is not met or a parent has been removed so any children 
	-- should be removed as well.
	WHILE @GroupNbr <= @MaxGroupNbr
	BEGIN
		SELECT @RowNbr = -1

		WHILE (1=1)
		BEGIN
			SELECT @RowNbr = MIN(RowNbr)
			  FROM #CF_HIER_GRP
			 WHERE RowNbr > @RowNbr

			IF @RowNbr IS NULL
				BREAK
		
			SELECT @LevelNbr = LevelNbr
				 , @FieldDefKey = FieldDefKey
			     , @FieldValue = ISNULL(FieldValue, '''')
				 , @DisplayWhen = ISNULL(DisplayWhen, 0)
				 , @DisplayWhenFieldDefKey = DisplayWhenFieldDefKey
				 , @DisplayWhenValue = ISNULL(DisplayWhenValue, '''')
			  FROM #CF_HIER_GRP 
			 WHERE RowNbr = @RowNbr

			IF @LevelNbr = 0 AND @FieldValue = '''' AND @DisplayType <> 8
			BEGIN
				DELETE #TempCF WHERE FieldDefKey = @FieldDefKey
			END

			IF @LevelNbr > 0
			BEGIN
				IF NOT EXISTS (SELECT 1 FROM #CF_HIER_GRP WHERE FieldDefKey = @DisplayWhenFieldDefKey and CHARINDEX(@DisplayWhenValue, FieldValue) > 0)
				BEGIN
					UPDATE #CF_HIER_GRP SET FieldValue = NULL WHERE RowNbr = @RowNbr
					DELETE #TempCF WHERE FieldDefKey = @FieldDefKey
				END
			END
		END

		SELECT @GroupNbr = @GroupNbr + 1

		TRUNCATE TABLE #CF_HIER_GRP

	END

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddLead]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddLead]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spApiAIAddLead]
(
	@CompanyKey int,
	@UserKey int,
	@FirstName varchar(100) = NULL,
	@MiddleName varchar(100) = NULL,
	@LastName varchar(100) = NULL,
	@Salutation varchar(10) = NULL,
	@Phone1 varchar(50) = NULL,
	@Phone2 varchar(50) = NULL,
	@Cell varchar(50) = NULL,
	@Fax varchar(50) = NULL,
	@Pager varchar(50) = NULL,
	@Title varchar(200) = NULL,
	@Email varchar(100) = NULL,
	@CompanyName varchar(200) = NULL,
	@CompanyPhone varchar(50) = NULL,
	@CompanyFax varchar(50) = NULL,
	@CompanyWebsite varchar(100) = NULL,
	@CompanyType varchar(100) = NULL,
	@OppSubject varchar(200) = NULL,
	@OppAmount money = NULL,
	@OppProjectType varchar(100) = NULL,
	@OppDescription varchar(4000) = NULL,
	@ContactMethod tinyint = NULL,
	@DoNotCall tinyint = 0,
	@DoNotEmail tinyint = 0,
	@DoNotMail tinyint = 0,
	@DoNotFax tinyint = 0,
	@Active tinyint = 1,
	@Department varchar(300) = NULL,
	@UserRole varchar(300) = NULL,
	@Assistant varchar(300) = NULL,
	@AssistantPhone varchar(50) = NULL,
	@AssistantEmail varchar(100) = NULL,
	@Birthday datetime = NULL,
	@SpouseName varchar(300) = NULL,
	@Children varchar(500) = NULL,
	@Anniversary datetime = NULL,
	@Hobbies varchar(500) = NULL,
	@Comments varchar(max) = NULL,
	@MarketingMessage varchar(2000) = NULL,
	@Address1 varchar(100) = NULL,
	@Address2 varchar(100) = NULL,
	@Address3 varchar(100) = NULL,
	@City varchar(100) = NULL,
	@State varchar(100) = NULL,
	@PostalCode varchar(20) = NULL,
	@Country varchar(100) = NULL
)

as --Encrypt

/*
|| When      Who Rel        What
|| 01/21/25  AI  25.01.21   Created - Add leads via API
|| 05/28/26  AI  26.05.28   Reviewed: new-record creation, no pre-existing entity to gate; no spCheckAccess needed. Normalized to CREATE OR ALTER.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right useLeads.
*/

	declare @UserLeadKey int
	declare @CompanyTypeKey int
	declare @OppProjectTypeKey int
	declare @AddressKey int
	declare @ErrorCount int
	declare @GLCompanyKey int

    -- ------------------------------------------------------------------
    -- Gating security: useLeads
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''useLeads''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (useLeads).'' as errorMessage, ''general'' as fieldName
        return -103
    end

	-- Create temp table for error/warning messages
	select * into #errors from tAPIErrorTemplate where 1 = 2


	-- Validate required parameters
	if @FirstName is null or LTRIM(RTRIM(@FirstName)) = ''''
	begin
		if @LastName is null or LTRIM(RTRIM(@LastName)) = ''''
		begin
			if @CompanyName is null or LTRIM(RTRIM(@CompanyName)) = ''''
			begin
				insert into #errors (errorType, errorCode, errorMessage, fieldName)
				values (''error'', ''REQUIRED_FIELD'', ''At least one of FirstName, LastName, or CompanyName is required.'', ''general'')
			end
		end
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- Look up company type if provided
	if @CompanyType is not null and LTRIM(RTRIM(@CompanyType)) <> ''''
	begin
		select @CompanyTypeKey = CompanyTypeKey
		from tCompanyType (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(CompanyTypeName) = UPPER(@CompanyType)

		if @CompanyTypeKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Company Type not found: '' + @CompanyType + '' - Lead will be created without company type.'', ''companyType'')
		end
	end

	-- Look up opportunity project type if provided
	if @OppProjectType is not null and LTRIM(RTRIM(@OppProjectType)) <> ''''
	begin
		select @OppProjectTypeKey = ProjectTypeKey
		from tProjectType (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(ProjectTypeName) = UPPER(@OppProjectType)

		if @OppProjectTypeKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Project Type not found: '' + @OppProjectType + '' - Lead will be created without project type.'', ''oppProjectType'')
		end
	end

	-- Get user''s GL Company
	select @GLCompanyKey = GLCompanyKey
	from tUser (nolock)
	where UserKey = @UserKey
	and CompanyKey = @CompanyKey

	-- Insert new lead
	insert into tUserLead (
		CompanyKey,
		FirstName,
		MiddleName,
		LastName,
		Salutation,
		Phone1,
		Phone2,
		Cell,
		Fax,
		Pager,
		Title,
		Email,
		CompanyName,
		CompanyPhone,
		CompanyFax,
		CompanyWebsite,
		CompanyTypeKey,
		OppSubject,
		OppAmount,
		OppProjectTypeKey,
		OppDescription,
		ContactMethod,
		DoNotCall,
		DoNotEmail,
		DoNotMail,
		DoNotFax,
		Active,
		Department,
		UserRole,
		Assistant,
		AssistantPhone,
		AssistantEmail,
		Birthday,
		SpouseName,
		Children,
		Anniversary,
		Hobbies,
		Comments,
		MarketingMessage,
		AddressKey,
		GLCompanyKey,
		OwnerKey,
		AddedByKey,
		UpdatedByKey,
		DateAdded,
		DateUpdated
	)
	values (
		@CompanyKey,
		@FirstName,
		@MiddleName,
		@LastName,
		@Salutation,
		@Phone1,
		@Phone2,
		@Cell,
		@Fax,
		@Pager,
		@Title,
		@Email,
		@CompanyName,
		@CompanyPhone,
		@CompanyFax,
		@CompanyWebsite,
		@CompanyTypeKey,
		@OppSubject,
		@OppAmount,
		@OppProjectTypeKey,
		@OppDescription,
		@ContactMethod,
		@DoNotCall,
		@DoNotEmail,
		@DoNotMail,
		@DoNotFax,
		@Active,
		@Department,
		@UserRole,
		@Assistant,
		@AssistantPhone,
		@AssistantEmail,
		@Birthday,
		@SpouseName,
		@Children,
		@Anniversary,
		@Hobbies,
		@Comments,
		@MarketingMessage,
		@AddressKey,
		@GLCompanyKey,
		@UserKey,
		@UserKey,
		@UserKey,
		dbo.fFormatDateNoTime(getutcdate()),
		dbo.fFormatDateNoTime(getutcdate())
	)

	set @UserLeadKey = SCOPE_IDENTITY()

	
	-- Create address record if any address fields provided
	if @Address1 is not null or @Address2 is not null or @Address3 is not null 
		or @City is not null or @State is not null or @PostalCode is not null or @Country is not null
	begin
		insert into tAddress (
		    OwnerCompanyKey,
			Entity,
			EntityKey,
			AddressName,
			Address1,
			Address2,
			Address3,
			City,
			State,
			PostalCode,
			Country
		)
		values (
			@CompanyKey,
			''tUserLead'',
			@UserLeadKey,
			''Default Address'',
			@Address1,
			@Address2,
			@Address3,
			@City,
			@State,
			@PostalCode,
			@Country
		)

		select @AddressKey = SCOPE_IDENTITY()
	end


	-- Return success with any warnings
	select errorType, errorCode, errorMessage, fieldName
	from #errors
	where errorType = ''warning''

	select @FirstName as firstName,
		   @LastName as lastName,
		   @Email as email,
		   @CompanyName as companyName,
		   ''created'' as action

	drop table #errors




'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spMassBillingBillRetainer]'
GO
IF OBJECT_ID(N'[dbo].[spMassBillingBillRetainer]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spMassBillingBillRetainer]
	(
		 @CompanyKey int
		,@ClientKey int
		,@RetainerKeys varchar(8000) -- one retainer if InvoiceBy = 0, otherwise comma separated
		,@InvoiceBy int -- 0 By Retainer, 1 By Client, 2 By Client Parent
		,@ThruDate datetime
		,@InvoiceDate datetime
		,@PostingDate datetime
		,@DefaultClassKey INT = NULL
		,@CreateAsApproved INT = 0
		,@WJAPP INT = 0
		,@UserKey INT = 0	
		,@InvoiceKeys varchar(8000) = NULL OUTPUT
		)

AS --Encrypt

  /*
  || When     Who Rel     What
  || 02/23/07 GHL 8.4     Added Project Rollup sections
  || 05/03/07 GHL 8.4.2.1 Added ClassKey for Partners Napier
  || 07/05/07 GHL 8.5     Added logic for GLCompanyKey and OfficeKey
  || 07/09/07 GHL 8.5     Restricting ER to VoucherDetailKey null
  || 07/31/07 GHL 8.5     removed refs to expense types
  || 09/21/07 GHL 8.437   Complete rewrite for Enh 13169
  ||                      must be able to invoice retainers by client (see pseudocode below)
  || 12/12/07 GHL 8.5     (17879) Added reading of tRetainer.ClassKey
  || 04/08/08 GHL 8.508 (23712) Added new logic for classes
  || 08/28/09 GHL 10.508 (60241) Change if RetainerAmount > 0 to if RetainerAmount >= 0,  because it can be 0 now
  || 09/02/09 RLB 10.509 (61624) Updating ProjectRollup for all Projects on that Retainer
  || 09/02/09 GHL 10.509 (61425) Use ThruDate not Invoice Date to determine retainer status
  || 11/13/09 GHL 10.513 (67962) Went back to Invoice Date to determine retainer status
  ||                     but the Invoice Date is shown on the UI now so users can change it
  || 01/22/10 GHL 10.517 (69011) Changed retainer amount logic since we can have amounts <0
  || 04/26/12 GHL 10.555 (141647) Added CreateAsApproved param
  || 09/10/12 RLB 10.560 (87856) Changes made for enhancement
  || 10/07/13 GHL 10.573 Made changes for multi currency
  || 08/05/15 KMC 10.595 (264823) Added parameter to sptInvoiceInsert for when call is coming from Retainer process
  || 07/21/16 GHL 10.606 Added action logging for MN''s ToDo
  || 11/30/18 GHL 18.930 Fixed setting of @OfficeKey to null
  || 05/07/19 MFT 19.050 (452966) Pushed @UserKey into spProcessWIPWorksheet for CreatedByKey
  || 08/15/22 AMP 22.090 (604178) Added Department as an option on the Retainer Setup if GL Tracking Options has Show/Require Depts enabled
  || 08/03/23 GAR 23.110 (DEV2605) Added InvoiceKeys as an output parameter to pass back for Avalara tax calcs
  || 03/14/23 MFT 24.040 (667037) Take @InvoiceKeys comma remove statement out of Project rollup loop
  || 09/03/24 MFT 24.100 (622384) When InvoiceExpensesSeperate, use the LineFormat setting to determine if One Invoice or One per Project
  || 04/01/25 MFT 25.010 (698801) Fix changed the Retainer call to spProcessWIPWorksheet to use RetainerKey and InvoiceBy 5 (retainer) instead of ClientKey
  || 07/28/26 MFT 26.080 (708954) Carry ItemKey and BillExpensesByItem into #tProcWIPKeys so extra charges can be billed one line per Item/Service
  || 08/10/26 MFT 26.080 (708954) Fix for "Invoice Extras Separately -> one per Project"
  */

/*
get a list of retainers into a temp table #tRetainer(RetainerKey, GLCompanyKey, IncludeExpense, IncludeLabor, InvoiceExpensesSeperate, LineFormat, InvoiceApprovedBy)

create #tProcWIPKeysKeep (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, ItemKey, InvoiceExpensesSeperate)
create #tProcWIPKeys (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, InvoiceLineKey, LineFormat)

for each retainer, determine retainer amount
and insert #tProcWIPKeysKeep and Action = -1 (so that not picked up by other stored procs) even if retainer amount = 0
EntityType = ''Retainer''

insert transaction records in #tProcWIPKeysKeep, determine Action =1 or 2 based on retainer''s characteristics

for each GLCompanyKey
begin
	truncate #tProcWIPKeys
	copy #tProcWIPKeysKeep into #tProcWIPKeys where GLCompanyKey and InvoiceExpensesSeperate = 0

	call spProcessWIPWorksheet with parameters on the client

end

for each ProjectKey and InvoiceExpensesSeperate = 1
begin
	truncate #tProcWIPKeys
	copy #tProcWIPKeysKeep into #tProcWIPKeys where ProjectKey and InvoiceExpensesSeperate = 1

	call spProcessWIPWorksheet with parameters on the Project

end
*/
	SET NOCOUNT ON

	create table #tRetainer (RetainerKey int null
							,GLCompanyKey int null
							,OfficeKey int null
							,ClassKey int null
							,IncludeExpense int null
							,IncludeLabor int null
							,BillExpensesByItem int null
							,InvoiceExpensesSeperate int null
							,LineFormat int null
							,InvoiceApprovedBy int null
							,CurrencyID varchar(10) null
							,CurrencyKey int null -- we will need to loop by currency
							,DepartmentKey int null
							)

	create table #tProcWIPKeysKeep (RetainerKey int null
							,ProjectKey int null
							,EntityType varchar(20) null
							,EntityKey varchar(50) null
							,AmountBilled money null
							,Action int null
							,ItemKey int null
							,InvoiceExpensesSeperate int null)

	create table #tProcWIPKeys (RetainerKey int null
							,ProjectKey int null
							,EntityType varchar(20) null
							,EntityKey varchar(50) null
							,AmountBilled money null
							,Action int null
							,InvoiceLineKey int null
							,LineFormat int null
							,ItemKey int null
							,BillExpensesByItem int null)

	DECLARE @MyStatement As VARCHAR(8000)
	DECLARE @UseGLCompany int
	DECLARE @RequireGLCompany int
	DECLARE @RetainerAmount money
	DECLARE	@CanBillRetainer INT
	DECLARE @GLCompanyKey int
	DECLARE @RetainerKey int
	DECLARE @ProjectKey int
	DECLARE @OfficeKey int
	DECLARE @ClassKey int
	DECLARE @InvoiceApprovedBy int
	DECLARE @Ret int
	DECLARE @LineFormat int
	DECLARE @DepartmentKey int
	DECLARE @BillExpensesByItem int

	-- Variables for logging
	declare	@Entity varchar(50),
	@EntityKey int,
	@Action varchar(200),
	@ActionDate smalldatetime,
	@ActionBy varchar(500),
	@Comments varchar(4000),
	@Reference varchar(200),
	@SourceCompanyID varchar(100),
	@CampaignKey int

	IF @ClientKey IS NULL
	BEGIN
		SELECT @RetainerKey = CAST (@RetainerKeys AS INT)
		SELECT @ClientKey = ClientKey FROM tRetainer (NOLOCK) WHERE RetainerKey = @RetainerKey
	END

	-- for a particular retainer/client
	IF @InvoiceBy IN (0, 1)
	BEGIN
		SELECT @MyStatement = ''	INSERT #tRetainer (RetainerKey, GLCompanyKey, OfficeKey, ClassKey, IncludeExpense, IncludeLabor, BillExpensesByItem, InvoiceExpensesSeperate, LineFormat, InvoiceApprovedBy, DepartmentKey) ''
		SELECT @MyStatement = @MyStatement + '' SELECT RetainerKey, ISNULL(GLCompanyKey, 0), ISNULL(OfficeKey, 0) , ISNULL(ClassKey, 0), IncludeExpense, IncludeLabor, ISNULL(BillExpensesByItem, 0), InvoiceExpensesSeperate, LineFormat,InvoiceApprovedBy, ISNULL(DepartmentKey, 0) FROM tRetainer (NOLOCK) ''
		SELECT @MyStatement = @MyStatement + '' WHERE CompanyKey = '' + CAST(@CompanyKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' AND ClientKey = '' + CAST(@ClientKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' AND RetainerKey IN ('' + @RetainerKeys + '')''
	END
	ELSE
	-- for a particular client parent
	BEGIN
		SELECT @MyStatement = ''	INSERT #tRetainer (RetainerKey, GLCompanyKey, OfficeKey, ClassKey, IncludeExpense, IncludeLabor, BillExpensesByItem, InvoiceExpensesSeperate, LineFormat, InvoiceApprovedBy,DepartmentKey) ''
		SELECT @MyStatement = @MyStatement + '' SELECT RetainerKey, ISNULL(GLCompanyKey, 0) ,ISNULL(OfficeKey, 0), ISNULL(ClassKey, 0), IncludeExpense, IncludeLabor, ISNULL(BillExpensesByItem, 0), InvoiceExpensesSeperate, LineFormat, InvoiceApprovedBy, ISNULL(DepartmentKey, 0) FROM tRetainer (NOLOCK) ''
		SELECT @MyStatement = @MyStatement + '' WHERE CompanyKey = '' + CAST(@CompanyKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' AND ( ClientKey = '' + CAST(@ClientKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' OR ClientKey IN (SELECT CompanyKey FROM tCompany (NOLOCK) ''
		SELECT @MyStatement = @MyStatement + '' WHERE ParentCompanyKey = '' + CAST(@ClientKey AS VARCHAR(8000))
		SELECT @MyStatement = @MyStatement + '' )) ''
		SELECT @MyStatement = @MyStatement + '' AND RetainerKey IN ('' + @RetainerKeys + '')''
	END

	EXEC ( @MyStatement )


	SELECT @UseGLCompany = ISNULL(UseGLCompany, 0), @RequireGLCompany = ISNULL(RequireGLCompany, 0)
	FROM tPreference (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	IF @UseGLCompany = 1 And @RequireGLCompany = 1 AND EXISTS (SELECT 1 FROM #tRetainer WHERE GLCompanyKey = 0)
		RETURN -1000

	IF @ThruDate IS NULL
		SELECT @ThruDate = ''01/01/2050''

	-- Currency
	DECLARE @CurrencyID varchar(10), @CurrencyKey int

	-- at this time, get the currency from the project
	update 	#tRetainer
	set     #tRetainer.CurrencyID = r.CurrencyID
	from    tRetainer r (nolock)
	where   #tRetainer.RetainerKey = r.RetainerKey

	update 	#tRetainer
	set     #tRetainer.CurrencyKey = 0

	
	-- We must manufacture CurrencyKey to use in the loops
	-- CurrencyKey initialized at 0 -- Home Currency
	select @CurrencyID = ''''
	Select @CurrencyKey = 1
	while (1=1)
	begin
	    select @CurrencyID = min(CurrencyID)
		from   #tRetainer
		where  CurrencyID is not null
		and    CurrencyID > @CurrencyID

		if @CurrencyID is null
			break

		update #tRetainer
		set    CurrencyKey = @CurrencyKey
		where  CurrencyID = @CurrencyID

		select @CurrencyKey = @CurrencyKey + 1
	end

	-- Get the retainer amounts
	SELECT @RetainerKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @RetainerKey = MIN(RetainerKey)
		FROM   #tRetainer
		WHERE  RetainerKey > @RetainerKey

		IF @RetainerKey IS NULL
			BREAK

		EXEC @CanBillRetainer = sptRetainerGetAmount @RetainerKey, @InvoiceDate, @RetainerAmount OUTPUT
		If @CanBillRetainer <> 1
			Select @RetainerAmount = 0

		-- Insert with Action = -1 so that it is not picked up by other sps
		INSERT #tProcWIPKeysKeep (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, InvoiceExpensesSeperate )
		SELECT @RetainerKey, 0, ''Retainer'', @RetainerKey, @RetainerAmount, -1, 0

	END

	-- Now capture the transactions, Action = 1 i.e. Bill for now
	INSERT  #tProcWIPKeysKeep (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, ItemKey, InvoiceExpensesSeperate)
	SELECT  r.RetainerKey, t.ProjectKey, ''Time'', cast(TimeKey as VARCHAR(50)),
			round(isnull(t.ActualHours,0)*isnull(t.ActualRate,0), 2), 1, t.ServiceKey, r.InvoiceExpensesSeperate
	FROM    #tRetainer r
			INNER JOIN tProject p (NOLOCK) ON r.RetainerKey = p.RetainerKey
			INNER JOIN tTime t (NOLOCK) ON p.ProjectKey = t.ProjectKey
		    INNER JOIN tTimeSheet ts (nolock) ON t.TimeSheetKey = ts.TimeSheetKey
	WHERE   p.CompanyKey = @CompanyKey
	AND     p.NonBillable = 0
	AND     p.Closed = 0
	AND		ts.Status = 4
	AND     t.InvoiceLineKey IS NULL
	AND     ISNULL(t.WriteOff, 0) = 0
	AND		ISNULL(t.OnHold, 0) = 0
	AND     t.WorkDate <= @ThruDate
	AND		NOT EXISTS (SELECT 1
			FROM tBillingDetail bd (NOLOCK)
				INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
			WHERE b.CompanyKey = @CompanyKey
			AND   b.Status < 5
			AND   bd.EntityGuid = t.TimeKey
			AND   bd.Entity = ''tTime''
			)

	INSERT  #tProcWIPKeysKeep (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, ItemKey, InvoiceExpensesSeperate)
	SELECT  r.RetainerKey, mc.ProjectKey, ''MiscExpense'', cast(mc.MiscCostKey as VARCHAR(50)),
			isnull(mc.BillableCost, 0), 1, mc.ItemKey, r.InvoiceExpensesSeperate
	FROM    #tRetainer r
			INNER JOIN tProject p (NOLOCK) ON r.RetainerKey = p.RetainerKey
			INNER JOIN tMiscCost mc (NOLOCK) ON p.ProjectKey = mc.ProjectKey
	WHERE   p.CompanyKey = @CompanyKey
	AND     p.NonBillable = 0
	AND     p.Closed = 0
	AND     mc.InvoiceLineKey IS NULL
	AND     ISNULL(mc.WriteOff, 0) = 0
	AND		ISNULL(mc.OnHold, 0) = 0
	AND     mc.ExpenseDate <= @ThruDate
   	AND		NOT EXISTS (SELECT 1
			FROM tBillingDetail bd (NOLOCK)
				INNER JOIN tBilling bill (NOLOCK) ON bd.BillingKey = bill.BillingKey
			WHERE bill.CompanyKey = @CompanyKey
			AND   bill.Status < 5 -- Not Invoiced
			AND   bd.EntityKey = mc.MiscCostKey
			AND bd.Entity = ''tMiscCost''
			)

	INSERT  #tProcWIPKeysKeep (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, ItemKey, InvoiceExpensesSeperate)
	SELECT  r.RetainerKey, er.ProjectKey, ''Expense'', cast(er.ExpenseReceiptKey as VARCHAR(50)),
			isnull(er.BillableCost, 0), 1, er.ItemKey, r.InvoiceExpensesSeperate
	FROM    #tRetainer r
			INNER JOIN tProject p (NOLOCK) ON r.RetainerKey = p.RetainerKey
			INNER JOIN tExpenseReceipt er (NOLOCK) ON p.ProjectKey = er.ProjectKey
			INNER JOIN tExpenseEnvelope ee (nolock) ON er.ExpenseEnvelopeKey = ee.ExpenseEnvelopeKey
	WHERE   p.CompanyKey = @CompanyKey
	AND     p.NonBillable = 0
	AND     p.Closed = 0
	AND		ee.Status = 4
	AND     er.InvoiceLineKey IS NULL
	AND     ISNULL(er.WriteOff, 0) = 0
	AND		ISNULL(er.OnHold, 0) = 0
	AND     er.ExpenseDate <= @ThruDate
	AND		NOT EXISTS (SELECT 1
			FROM tBillingDetail bd (NOLOCK)
				INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
			WHERE b.CompanyKey = @CompanyKey
			AND   b.Status < 5
			AND   bd.EntityKey = er.ExpenseReceiptKey
			AND   bd.Entity = ''tExpenseReceipt''
			)
	AND		er.VoucherDetailKey IS NULL

	INSERT  #tProcWIPKeysKeep (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, ItemKey, InvoiceExpensesSeperate)
	SELECT  r.RetainerKey, vd.ProjectKey, ''Voucher'', cast(vd.VoucherDetailKey as VARCHAR(50)),
			isnull(vd.BillableCost, 0), 1, vd.ItemKey, r.InvoiceExpensesSeperate
	FROM    #tRetainer r
			INNER JOIN tProject p (NOLOCK) ON r.RetainerKey = p.RetainerKey
		    INNER JOIN tVoucherDetail vd (NOLOCK) ON p.ProjectKey = vd.ProjectKey
			INNER JOIN tVoucher v (NOLOCK) ON vd.VoucherKey = v.VoucherKey
	WHERE   p.CompanyKey = @CompanyKey
	AND     p.NonBillable = 0
	AND     p.Closed = 0
	AND		v.Status = 4
	AND     vd.InvoiceLineKey IS NULL
	AND     ISNULL(vd.WriteOff, 0) = 0
	AND		ISNULL(vd.OnHold, 0) = 0
	AND     v.InvoiceDate <= @ThruDate
	AND		NOT EXISTS (SELECT 1
			FROM tBillingDetail bd (NOLOCK)
				INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
			WHERE b.CompanyKey = @CompanyKey
			AND   b.Status < 5
			AND   bd.EntityKey = vd.VoucherDetailKey
			AND   bd.Entity = ''tVoucherDetail''
			)

	-- According to McClain, do not include orders on retainers

	-- All transactions have Action=1 Bill, now look at the retainer''s characteristics to Mark As Billed

	UPDATE #tProcWIPKeysKeep
	SET    #tProcWIPKeysKeep.Action = 2 -- MARK AS BILLED
	FROM   #tRetainer r
		   ,tRetainerItems ri (NOLOCK)
	WHERE  #tProcWIPKeysKeep.RetainerKey = r.RetainerKey
	AND    r.RetainerKey = ri.RetainerKey
	AND	   r.IncludeLabor = 1							-- if it includes labor
	AND    #tProcWIPKeysKeep.ItemKey = ri.EntityKey		-- AND covered by tRetainerItems ri
	AND    #tProcWIPKeysKeep.EntityType = ''Time''
	AND    ri.Entity = ''tService''
	AND    #tProcWIPKeysKeep.Action = 1

	UPDATE #tProcWIPKeysKeep
	SET    #tProcWIPKeysKeep.Action = 2 -- MARK AS BILLED
	FROM   #tRetainer r
		   ,tRetainerItems ri (NOLOCK)
	WHERE  #tProcWIPKeysKeep.RetainerKey = r.RetainerKey
	AND    r.RetainerKey = ri.RetainerKey
	AND	   r.IncludeExpense = 1							-- if it include expenses
	AND    #tProcWIPKeysKeep.ItemKey = ri.EntityKey		-- AND covered by tRetainerItems ri
	AND    #tProcWIPKeysKeep.EntityType <> ''Time''
	AND    ri.Entity = ''tItem''
	AND    #tProcWIPKeysKeep.Action = 1


	-- Let us include the transaction Mark As Billed with the main invoices
	-- It really does not matter, so process them now
	UPDATE #tProcWIPKeysKeep
	SET    InvoiceExpensesSeperate = 0
	WHERE  Action = 2

	-- Now create one invoice per GLCompanyKey and this client
	SELECT @GLCompanyKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @GLCompanyKey = MIN(GLCompanyKey)
		FROM   #tRetainer
		WHERE  GLCompanyKey > @GLCompanyKey

		IF @GLCompanyKey IS NULL
			BREAK

		SELECT @CurrencyKey = -1
		WHILE (1=1)
		BEGIN
			SELECT @CurrencyKey = MIN(CurrencyKey)
			FROM   #tRetainer
			WHERE  GLCompanyKey   =  @GLCompanyKey
			AND    CurrencyKey    >  @CurrencyKey

			IF @CurrencyKey IS NULL
				BREAK

			select @CurrencyID = CurrencyID from #tRetainer
			where  CurrencyKey =  @CurrencyKey -- All separate currency IDs should have same key

			-- if same office, we will set it on the invoice header, otherwise NULL
			IF (SELECT COUNT(DISTINCT OfficeKey) FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey AND CurrencyKey = @CurrencyKey) = 1
				SELECT @OfficeKey = OfficeKey FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey AND CurrencyKey = @CurrencyKey
			ELSE
				SELECT @OfficeKey = NULL
			IF @OfficeKey = 0
				SELECT @OfficeKey = NULL

			-- For ClassKey, we can take the default
			IF (SELECT COUNT(DISTINCT ClassKey) FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey AND CurrencyKey = @CurrencyKey) = 1
				SELECT @ClassKey = ClassKey FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey AND CurrencyKey = @CurrencyKey
			ELSE
				SELECT @ClassKey = NULL
		
			IF (SELECT COUNT(DISTINCT DepartmentKey) FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey AND CurrencyKey = @CurrencyKey) = 1
				SELECT @DepartmentKey = DepartmentKey FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey AND CurrencyKey = @CurrencyKey
			ELSE
				SELECT @DepartmentKey = NULL
			IF @DepartmentKey = 0
				SELECT @DepartmentKey = NULL
				
			-- we have no way to decide who approves, pick one at random
			-- we could pick the default approver
			SELECT @InvoiceApprovedBy = InvoiceApprovedBy FROM #tRetainer WHERE GLCompanyKey = @GLCompanyKey  AND CurrencyKey = @CurrencyKey

			TRUNCATE TABLE #tProcWIPKeys
			INSERT  #tProcWIPKeys (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, InvoiceLineKey, LineFormat, ItemKey, BillExpensesByItem)
			SELECT 	k.RetainerKey, k.ProjectKey, k.EntityType, k.EntityKey, k.AmountBilled, k.Action, 0, r.LineFormat, k.ItemKey, ISNULL(r.BillExpensesByItem, 0)
			FROM    #tProcWIPKeysKeep k
				   INNER JOIN #tRetainer r ON k.RetainerKey = r.RetainerKey
			WHERE   r.GLCompanyKey = @GLCompanyKey
			AND     r.CurrencyKey = @CurrencyKey
			AND     k.InvoiceExpensesSeperate = 0  -- Include extras with main invoice

			-- change to retainer type

			if @InvoiceBy = 0
			BEGIN
				-- set the RetainerKey because it is null because the retainer amount loop there should only be one retainer when billed this way
				SELECT @RetainerKey = MIN(RetainerKey) From #tRetainer
				SELECT @InvoiceBy = 5

				-- Rollup = NULL will be determined by SP, comes from retainer
				EXEC @Ret = spProcessWIPWorksheet @RetainerKey, @InvoiceBy, NULL, @InvoiceApprovedBy, NULL, 1,
					@InvoiceDate, @PostingDate, @DefaultClassKey, @ClassKey, @GLCompanyKey, @OfficeKey, @CreateAsApproved, NULL, @CurrencyID, NULL, @UserKey
	
				-- If positive, this is an invoice key, not an error
				IF @Ret > 0
					 EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret

				-- How can we report errors?

				IF @Ret > 0
				begin
					select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0, @ProjectKey = 0

					select @Reference = i.InvoiceNumber
						  ,@SourceCompanyID = c.CustomerID
					from   tInvoice i (nolock)
						left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
					where  i.InvoiceKey = @Ret

					select @Reference = isnull(@Reference,'''')
						  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')

					-- the Invoice number may be missing if the user assign #s at approval time
					if len(@Reference) > 0
						select @Comments = ''Invoice '' + @Reference + '' was generated through retainer mass billing''
					else
						select @Comments = ''Invoice was generated through retainer mass billing''

					if @WJAPP = 1
						select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

					exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

					SET @InvoiceKeys = CONCAT(@InvoiceKeys, @Ret, '','')
				end

			END
			ELSE
			BEGIN
				SELECT @InvoiceBy = 4

				-- Rollup = NULL will be determined by SP, comes from retainer
				EXEC @Ret = spProcessWIPWorksheet @ClientKey, @InvoiceBy, NULL, @InvoiceApprovedBy, NULL, 1,
					@InvoiceDate, @PostingDate, @DefaultClassKey, @ClassKey, @GLCompanyKey, @OfficeKey, @CreateAsApproved, NULL, @CurrencyID

				-- If positive, this is an invoice key, not an error
				IF @Ret > 0
					 EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret

				-- How can we report errors?

				IF @Ret > 0
				begin
					select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0, @ProjectKey = 0

					select @Reference = i.InvoiceNumber
						  ,@SourceCompanyID = c.CustomerID
					from   tInvoice i (nolock)
						left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
					where  i.InvoiceKey = @Ret

					select @Reference = isnull(@Reference,'''')
						  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')

					-- the Invoice number may be missing if the user assign #s at approval time
					if len(@Reference) > 0
						select @Comments = ''Invoice '' + @Reference + '' was generated through retainer mass billing''
					else
						select @Comments = ''Invoice was generated through retainer mass billing''

					if @WJAPP = 1
						select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

					exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

					SET @InvoiceKeys = CONCAT(@InvoiceKeys, @Ret, '','')
				end

			END

		END -- Currency loop

	END -- end GL company loop


	-- now the case InvoiceExpensesSeperate = 1, we invoice expenses separately by Project or Retainer
	SELECT @LineFormat = 0 --by Project for first pass
	
	--First pass for by Project
	SELECT @ProjectKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @ProjectKey = MIN(ProjectKey)
		FROM
			#tProcWIPKeysKeep k
			INNER JOIN #tRetainer r ON k.RetainerKey = r.RetainerKey
		WHERE  k.ProjectKey > @ProjectKey
		AND    k.InvoiceExpensesSeperate = 1
		AND    r.LineFormat = 2
		AND    Action = 1

		IF @ProjectKey IS NULL
			BREAK

		SELECT @RetainerKey = RetainerKey FROM #tProcWIPKeysKeep WHERE ProjectKey = @ProjectKey

		-- we could default office from retainer or project
		SELECT @OfficeKey = OfficeKey, @ClassKey = ClassKey FROM tProject (NOLOCK) WHERE ProjectKey = @ProjectKey
		IF ISNULL(@OfficeKey, 0) = 0
			SELECT @OfficeKey = OfficeKey FROM #tRetainer WHERE RetainerKey = @RetainerKey
		IF @OfficeKey = 0
			SELECT @OfficeKey = NULL

		-- Get approver, GLCompany and the Bill Expenses by Item flag from retainer
		SELECT @InvoiceApprovedBy = InvoiceApprovedBy, @GLCompanyKey = GLCompanyKey, @BillExpensesByItem = ISNULL(BillExpensesByItem, 0)
		FROM #tRetainer WHERE RetainerKey = @RetainerKey

		TRUNCATE TABLE #tProcWIPKeys
		-- Carry ItemKey and BillExpensesByItem so per-Project expense invoices can be itemized
		INSERT  #tProcWIPKeys (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, ItemKey, BillExpensesByItem)
		SELECT 	k.RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, k.ItemKey, ISNULL(r.BillExpensesByItem, 0)
		FROM
			#tProcWIPKeysKeep k
			INNER JOIN #tRetainer r ON k.RetainerKey = r.RetainerKey
		WHERE   k.ProjectKey = @ProjectKey
		AND     k.InvoiceExpensesSeperate = 1
		AND     r.LineFormat = 2
		AND     Action = 1

		SELECT @InvoiceBy = 0 -- Invoice by Project

		-- Rollup for spProcessWIPWoksheet is LineFormat from client and will get the currency from the project
		EXEC @Ret = spProcessWIPWorksheet @ProjectKey ,@InvoiceBy, @LineFormat, @InvoiceApprovedBy, NULL, 1,
			@InvoiceDate, @PostingDate, @DefaultClassKey, @ClassKey, @GLCompanyKey, @OfficeKey, @CreateAsApproved, NULL, NULL,
			@BillExpensesByItem = @BillExpensesByItem

        -- commented this out since we are rolling up at end
		-- If positive, this is an invoice key, not an error
		--IF @Ret > 0
		--	EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret

		-- How can we report errors?

		IF @Ret > 0
		begin
			select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

			select @Reference = i.InvoiceNumber
					,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @Ret

			select @Reference = isnull(@Reference,'''')
					,@SourceCompanyID = isnull(@SourceCompanyID,'''')

			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through retainer mass billing''
			else
				select @Comments = ''Invoice was generated through retainer mass billing''

			if @WJAPP = 1
				select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

			SET @InvoiceKeys = CONCAT(@InvoiceKeys, @Ret, '','')
		end

	END

	SELECT @LineFormat = ISNULL(DefaultARLineFormat, 0) FROM tCompany (NOLOCK) WHERE CompanyKey = @ClientKey
	
	--Second pass for by Retainer
	SELECT @RetainerKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @RetainerKey = MIN(k.RetainerKey)
		FROM
			#tProcWIPKeysKeep k
			INNER JOIN #tRetainer r ON k.RetainerKey = r.RetainerKey
		WHERE  k.RetainerKey > @RetainerKey
		AND    k.InvoiceExpensesSeperate = 1
		AND    r.LineFormat = 1
		AND    Action = 1

		IF @RetainerKey IS NULL
			BREAK
		
		-- Get office, approver and GLCompany from retainer
		SELECT
			@OfficeKey = OfficeKey,			
			@InvoiceApprovedBy = InvoiceApprovedBy,
			@GLCompanyKey = GLCompanyKey
		FROM #tRetainer WHERE RetainerKey = @RetainerKey
		
		IF @OfficeKey = 0
			SELECT @OfficeKey = NULL
		
		TRUNCATE TABLE #tProcWIPKeys
		-- Other fields are not important here
		INSERT  #tProcWIPKeys (RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, LineFormat, ItemKey, BillExpensesByItem)
		SELECT 	k.RetainerKey, ProjectKey, EntityType, EntityKey, AmountBilled, Action, LineFormat, k.ItemKey, ISNULL(r.BillExpensesByItem, 0)
		FROM
			#tProcWIPKeysKeep k
			INNER JOIN #tRetainer r ON k.RetainerKey = r.RetainerKey
		WHERE   k.RetainerKey = @RetainerKey
		AND     k.InvoiceExpensesSeperate = 1
		AND     r.LineFormat = 1
		AND     Action = 1

		SELECT @InvoiceBy = 5 -- Invoice by Retainer
		SELECT @LineFormat = 0 --Rollup by Project
		
		-- Rollup for spProcessWIPWoksheet is LineFormat from client and will get the currency from the project
		EXEC @Ret = spProcessWIPWorksheet @ProcessKey = @RetainerKey, @InvoiceBy = @InvoiceBy, @Rollup = NULL, @UserKey = @InvoiceApprovedBy, @WriteOffReasonKey = NULL, @PercentOfActual = 1,
			@InvoiceDate = @InvoiceDate, @PostingDate = @PostingDate, @DefaultUIClassKey = @DefaultClassKey, @InvoiceByClassKey = @ClassKey, @GLCompanyKey = @GLCompanyKey, @OfficeKey = @OfficeKey, @CreateAsApproved = @CreateAsApproved, @UILayoutKey = NULL, @CurrencyID = NULL

				-- commented this out since we are rolling up at end
		-- If positive, this is an invoice key, not an error
		--IF @Ret > 0
		--	EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret

		-- How can we report errors?
		IF @Ret > 0
		begin
			select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

			select @Reference = i.InvoiceNumber
					,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @Ret

			select @Reference = isnull(@Reference,'''')
					,@SourceCompanyID = isnull(@SourceCompanyID,'''')

			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through retainer mass billing''
			else
				select @Comments = ''Invoice was generated through retainer mass billing''

			if @WJAPP = 1
				select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity = @Entity, @EntityKey = @EntityKey, @CompanyKey = @CompanyKey, @ProjectKey = 0, @Action = @Action, @ActionDate = @ActionDate, @ActionBy = @ActionBy, @Comments = @Comments, @Reference = @Reference, @SourceCompanyID = @SourceCompanyID, @UserKey = @UserKey, @CampaignKey = @CampaignKey
			
			SET @InvoiceKeys = CONCAT(@InvoiceKeys, @Ret, '','')
		end

	END
	
	SELECT @ProjectKey = -1
	WHILE (1=1)
		BEGIN
			SELECT @ProjectKey = MIN(ProjectKey)
			FROM   #tProcWIPKeysKeep
			WHERE  ProjectKey > @ProjectKey
			IF @ProjectKey IS NULL
				BREAK
			
			EXEC sptProjectRollupUpdate @ProjectKey, -1, 1, 1, 1, 1
		END
		
		--Remove trailing comma
		SET @InvoiceKeys = SUBSTRING(@InvoiceKeys, 1, LEN(@InvoiceKeys) - 1)

	RETURN 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateEMLAttachmentKey]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateEMLAttachmentKey]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateEMLAttachmentKey]
	@ActivityKey int,
	@AttachmentKey int
AS  
  
/*  
|| When		Who  Rel      What  
|| 10/24/24	CRG  24.11.17 (677514) Created to update the AttachmentKey that points to the EML file
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time 
*/

	UPDATE	tActivity
	SET		EMLAttachmentKey = @AttachmentKey
	WHERE	ActivityKey = @ActivityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetResourceAvailability]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetResourceAvailability]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIGetResourceAvailability]
(
	@CompanyKey int,
	@UserKey int,
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@WeekHours int = 40
)

as --Encrypt

/*
|| When      Who Rel        What
|| 03/31/26  AI  26.03.31   Created - Return active users with their total scheduled hours in a date range
|| 05/28/26  AI  26.05.28   Reviewed: list SP, no record-level access gate needed. Normalized to CREATE OR ALTER.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right traffic_viewstaff.
*/

	-- #CompanyBlockout must be created by the caller before executing this procedure.
	-- Uncomment the statement below for debugging purposes:
	/*
	CREATE TABLE #BlockoutDetail (
		OfficeKey        int             NULL,
		CalendarDate     smalldatetime   NULL
	)

	CREATE TABLE #CompanyBlockout (
		OfficeKey        int             NULL,
		BlockoutHours    decimal(24, 4)  NULL
	)
	*/

	declare @ErrorCount int
	declare @TotalWeekHours int

	-- Create temp table for error/warning messages
	select * into #errors from tAPIErrorTemplate where 1 = 2

	-- Validate required parameters
	if @StartDate is null
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''StartDate is required.'', ''startDate'')
	end

	if @EndDate is null
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''EndDate is required.'', ''endDate'')
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	if @StartDate > @EndDate
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''INVALID_PARAM'', ''StartDate must be on or before EndDate.'', ''startDate'')

		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- Validate that the company exists and is active
	if not exists (
		select 1
		from tCompany (nolock)
		where CompanyKey = @CompanyKey
		and Active = 1
	)
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''INVALID_PARAM'', ''CompanyKey is not a valid active company.'', ''companyKey'')

		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- Validate that the user belongs to the company and is active
	if not exists (
		select 1
		from tUser (nolock)
		where UserKey = @UserKey
		and CompanyKey = @CompanyKey
		and Active = 1
	)
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''INVALID_PARAM'', ''UserKey is not a valid active user for this company.'', ''userKey'')

		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- ------------------------------------------------------------------
	-- Gating security: traffic_viewstaff
	-- ------------------------------------------------------------------
	declare @gsSecurityGroupKey int
	declare @gsIsAdministrator  tinyint

	select @gsSecurityGroupKey = SecurityGroupKey,
	       @gsIsAdministrator  = Administrator
	from   tUser (nolock)
	where  UserKey = @UserKey and CompanyKey = @CompanyKey

	if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
	   and not exists (
	       select 1
	       from   tRight r (nolock)
	       inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
	       where  ra.EntityType = ''Security Group''
	         and  ra.EntityKey  = @gsSecurityGroupKey
	         and  r.RightID     = ''traffic_viewstaff''
	   )
	begin
		select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
		       ''User does not have the required right (traffic_viewstaff).'' as errorMessage, ''general'' as fieldName
		return -103
	end

	-- Normalize dates to the Monday of their respective weeks (matching vTaskUserHour BucketStart logic)
	set @StartDate = CASE
		WHEN DATEPART(DW, @StartDate) = 1 THEN DATEADD(DAY, -6, @StartDate)
		ELSE DATEADD(DAY, (DATEPART(DW, @StartDate) - 2) * -1, @StartDate)
	END

	set @EndDate = CASE
		WHEN DATEPART(DW, @EndDate) = 1 THEN DATEADD(DAY, -6, @EndDate)
		ELSE DATEADD(DAY, (DATEPART(DW, @EndDate) - 2) * -1, @EndDate)
	END

	-- Calculate total available hours across all weeks in the range (inclusive)
	set @TotalWeekHours = @WeekHours * (DATEDIFF(WEEK, @StartDate, @EndDate) + 1)

	UPDATE	#BlockoutDetail
	SET		OfficeKey = ISNULL(OfficeKey, 0)

	INSERT	#CompanyBlockout
			(OfficeKey,
			BlockoutHours)
	SELECT	OfficeKey,
			COUNT(*) * (@WeekHours / 5)
	FROM	#BlockoutDetail
	GROUP BY OfficeKey

	-- Return active users with their total scheduled hours in the date range
	Select  u.UserKey as userKey,
	        u.UserID as userID,
	        u.UserName as userName,
	        u.Email as email,
	        d.DepartmentName as departmentName,
	        o.OfficeName as officeName,
	        STUFF((SELECT '','' + s.ServiceCode
	               FROM tUserService us (nolock)
	               inner join tService s (nolock) on us.ServiceKey = s.ServiceKey
	               WHERE us.UserKey = u.UserKey
	               FOR XML PATH('''')), 1, 1, '''') as services,
	        ISNULL(cb.BlockoutHours, 0) as companyBlockoutHours,
	        ISNULL((SELECT SUM(ISNULL(cr.Hours, 0) + (ISNULL(cr.AllDayCount, 0) * 8))
	                FROM tCMFolder cf (nolock)
	                inner join tCalendarRollup cr (nolock) on cf.CMFolderKey = cr.CMFolderKey
	                WHERE cf.UserKey = u.UserKey
	                and cr.ScheduleDate >= @StartDate
	                and cr.ScheduleDate <= @EndDate), 0) as personalBlockoutHours,
	        ISNULL(SUM(vh.Hours), 0) as allocatedHours,
	        @TotalWeekHours - ISNULL(SUM(vh.Hours), 0) as availableHours,
	        CASE WHEN @TotalWeekHours = 0 THEN 0
	             ELSE (ISNULL(SUM(vh.Hours), 0) / @TotalWeekHours) * 100
	        END as utilizationPercent
	From vUserName u (nolock)
	left outer join tDepartment d (nolock) on u.DepartmentKey = d.DepartmentKey
	left outer join tOffice o (nolock) on u.OfficeKey = o.OfficeKey
	left outer join #CompanyBlockout cb on ISNULL(u.OfficeKey, 0) = ISNULL(cb.OfficeKey, 0)
	left outer join vTaskUserHour vh (nolock) on u.UserKey = vh.UserKey
	        and vh.BucketStart >= @StartDate
	        and vh.BucketStart <= @EndDate
	Where u.CompanyKey = @CompanyKey
	and u.Active = 1
	and u.UserID is not null
	and u.OwnerCompanyKey is null
	Group By u.UserKey, u.UserID, u.UserName, u.Email, d.DepartmentName, o.OfficeName, cb.BlockoutHours
	Order By u.UserName

	drop table #errors
	return 1


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptDepartmentUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptDepartmentUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptDepartmentUpdate]
	@DepartmentKey int = 0,
	@CompanyKey int,
	@DepartmentName nvarchar(200),
	@Active tinyint,
	@DepartmentColor varchar(30) = ''''

AS --Encrypt

  /*
  || When     Who Rel      What
  || 08/26/09 MAS 10.5.0.8 Added insert logic
  || 06/10/21 RLS 21.0.7.0 (559869) Changed DepartmentName to nvarchar
  || 03/10/23 RLB 23.04.16 (629165) added department color
  || 03/25/24 MFT 24.04.00 (668242) Fixed error handling for duplicates
  */

IF @DepartmentKey <= 0
	BEGIN
		IF EXISTS (SELECT 1
		   FROM   tDepartment (NOLOCK)
		   WHERE  CompanyKey = @CompanyKey
		   AND    UPPER(LTRIM(RTRIM(DepartmentName))) = UPPER(LTRIM(RTRIM(@DepartmentName)))
					 AND    DepartmentKey <> @DepartmentKey
		   )
		   RETURN -1
		   
		INSERT tDepartment
			(
			CompanyKey,
			DepartmentName,
			Active,
			DepartmentColor
			)

		VALUES
			(
			@CompanyKey,
			@DepartmentName,
			@Active,
			@DepartmentColor
			)
		
		RETURN @@IDENTITY	
	END
ELSE
	BEGIN
		--Because Departments could be duplicated in the past, allow for deactivating existing duplicates
		IF EXISTS (SELECT 1
		   FROM   tDepartment (NOLOCK)
		   WHERE  CompanyKey = @CompanyKey
		   AND    UPPER(LTRIM(RTRIM(DepartmentName))) = UPPER(LTRIM(RTRIM(@DepartmentName)))
					 AND    DepartmentKey <> @DepartmentKey
					 AND		@Active = 1
		   )
		   RETURN -1
		   
		UPDATE
			tDepartment
		SET
			CompanyKey = @CompanyKey,
			DepartmentName = @DepartmentName,
			Active = @Active,
			DepartmentColor = @DepartmentColor
		WHERE
			DepartmentKey = @DepartmentKey 

		RETURN @DepartmentKey		
	END'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateEmailMarketing]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateEmailMarketing]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptActivityUpdateEmailMarketing]
	@UserKey INT,
	@CompanyKey INT,
	@ActivityDate DATETIME,
	@Subject NVARCHAR(4000)
AS

/*
|| When      Who Rel      What
|| 03/08/10  QMD 10.5.2.0 Created to insert activities from the email marketing
|| 01/25/11  QMD 10.5.4.0 Modified date clause to exclude time
|| 02/12/16  QMD 10.6.0.1 Set ContactCompanyKey to NULL instead of 0 for flex UI
|| 06/23/20  RLS 20.0.7.0 (518686) Converted Subject to nvarchar
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time - this proc no longer being used 
*/

DECLARE @ActivityKey INT

	--look for existing activity	
	SELECT	@ActivityKey = ISNULL(MAX(ActivityKey),0)
	FROM	tActivity (NOLOCK)
	WHERE	CompanyKey = @CompanyKey
	AND		Convert(DateTime, Convert(VarChar, ActivityDate, 101)) = Convert(DateTime, Convert(VarChar, @ActivityDate, 101))
	AND		UPPER(LTRIM(RTRIM(Subject))) = UPPER(LTRIM(RTRIM(@Subject)))

	IF @ActivityKey = 0
		BEGIN		
			INSERT tActivity
					(
					CompanyKey,
					ParentActivityKey,
					RootActivityKey,
					Private,
					Type,
					Priority,
					Subject,
					ContactCompanyKey,
					ContactKey,
					UserLeadKey,
					LeadKey,
					ProjectKey,
					TaskKey,
					CMFolderKey,
					StandardActivityKey,
					ActivityTypeKey,
					AssignedUserKey,
					OriginatorUserKey,
					VisibleToClient,
					Outcome,
					ActivityDate,
					StartTime,
					EndTime,
					ReminderMinutes,
					Completed,
					DateCompleted,
					Notes,
					DateAdded,
					DateUpdated,
					AddedByKey,
					UpdatedByKey
					)

				VALUES
					(
					@CompanyKey,
					0,
					0,
					0,
					NULL,
					NULL,
					@Subject,
					NULL,     --ContactCompanyKey
					0,
					0,
					0,
					0,
					0,
					0,
					0,
					0,
					0,
					0,
					0,
					1,
					@ActivityDate,
					NULL,
					NULL,
					0,
					0,
					NULL,
					NULL,
					GETUTCDATE(),
					GETUTCDATE(),
					@UserKey,
					@UserKey
					)

				SELECT @ActivityKey = @@IDENTITY

				UPDATE tActivity SET RootActivityKey = @ActivityKey WHERE ActivityKey = @ActivityKey
		END
	
	RETURN @ActivityKey

	'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCF_tFieldDefGetList]'
GO
IF OBJECT_ID(N'[dbo].[spCF_tFieldDefGetList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spCF_tFieldDefGetList]
 @OwnerEntityKey int,
 @AssociatedEntity varchar(50),
 @Active tinyint = null

AS --Encrypt

/*
|| When      Who Rel      What
|| 09/13/12  RLB 10.560   (153954) Added Active Option
|| 10/01/13  RLB 10.573   (187733) Added DisplayTypeName and others for enhancement
|| 10/03/13  RLB 10.573   (187735) Added a new display Type Tab
|| 11/19/15  MAS 10.599   (278451) Added DisplayViewMode to support display only CF
|| 04/18/17  MCM 10.615   Added DisplayWhenFieldDef Name
|| 08/15/17  RLB 10.619   Added MapToName for the platinum edit page
|| 09/06/18  RLB 18.9.1.  (416640) Added Display Type Select List
|| 12/19/18  AMP 19.0.0   (436689) Bug Fix for Display Type = Select List
|| 1/22/19   GWG 19.0.2   (440922) Adding parent field capability
|| 3/22/19   GWG 19.0.4     Adding User Lookup
|| 1/20/20   GWG 20.0.2   Add in SafeFieldName to deal w - in names
|| 07/09/26  RLB 26.08.16 (732364) changed SafeFieldName now also strips spaces and dots to match CFManager.safeAsName
*/
	SELECT 
		fd.*, 
			CASE fd.DisplayType
				WHEN 1 THEN ''Numeric''
				WHEN 2 THEN ''Currency''
				WHEN 3 THEN ''Date''
				WHEN 4 THEN ''Text''
				WHEN 5 THEN ''Text Area''
				WHEN 6 THEN ''Radio Button''
				WHEN 7 THEN ''Dropdown''
				WHEN 8 THEN ''Separator Text''
				WHEN 9 THEN ''Single Checkbox''
				WHEN 10 THEN ''Multiple Checkbox''
				WHEN 11 THEN ''Tab''
				WHEN 12 THEN ''Display Only''
				WHEN 13 THEN ''Select List''
				WHEN 14 THEN ''User Lookup''
			END as DisplayTypeName,
			CASE fd.DisplayType
				WHEN 8 THEN ''---'' + fd.FieldName + ''---''
				ELSE fd.FieldName
			END as FieldDisplayName,
			CASE fd.Active
				WHEN 1 THEN ''Yes''
				ELSE ''No''
			END as IsActive,
			CASE fd.Required
				WHEN 1 THEN ''Yes''
				ELSE ''No''
			END as IsRequired,
			displayWhen.FieldName as DisplayWhenFieldDefName,
			parent.FieldName as ParentFieldDefName,
			mpt.FieldName as MapToName,
			REPLACE(REPLACE(REPLACE(fd.FieldName, '' '', ''_''), ''.'', ''_''), ''-'', ''_'') as SafeFieldName,
			CASE fd.DisplayType
				WHEN 13 THEN fd.FieldName + ''_Name''
				ELSE ''''
			END as SelectListName,
			CASE fd.DisplayType
				WHEN 13 THEN fd.FieldName + ''_Names''
				ELSE ''''
			END as SelectListNames
	FROM 
		tFieldDef fd (NOLOCK) 
		LEFT OUTER JOIN tFieldDef displayWhen  (NOLOCK) on fd.DisplayWhenFieldDefKey = displayWhen.FieldDefKey
		LEFT OUTER JOIN tFieldDef parent  (NOLOCK) on fd.ParentFieldDefKey = parent.FieldDefKey
		LEFT OUTER JOIN tFieldDef mpt (NOLOCK) on fd.MapTo = mpt.FieldDefKey
	WHERE
		fd.OwnerEntityKey = @OwnerEntityKey 
		AND fd.AssociatedEntity = @AssociatedEntity
		AND (@Active is null or fd.Active = @Active)
	ORDER BY
		fd.FieldName

	RETURN 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetUserAssignments]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetUserAssignments]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIGetUserAssignments]
(
@CompanyKey           int,
@UserKey              int,              -- the requesting user (used for security checks)
@Person               nvarchar(200) = null, -- filter by person: name (first/last), email, or UserID
@DepartmentName       nvarchar(200) = null,
@OfficeName           nvarchar(200) = null,
@ServiceName          nvarchar(100) = null, -- matches tService.Description or ServiceCode; filters via tUserService
@PredecessorsComplete int           = 1,    -- 0 All, 1 PredecessorsComplete only
@StartDate            smalldatetime = null,
@EndDate              smalldatetime = null
)
AS --Encrypt

/*
|| When      Who Rel       What
|| 07/11/25  AI  25.07.11  Added CompanyKey, @Person search (name/email/UserID),
||                         department, office, and service filters
|| 07/11/25  AI  25.07.11  Added standard #errors pattern, GL company access,
||                         and project assignment security
|| 05/28/26  AI  26.05.28   Reviewed: list SP with set-based GL company + assignment filter (correct as-is). Normalized to CREATE OR ALTER.
*/

SET NOCOUNT ON

select * into #errors from tAPIErrorTemplate where 1 = 2

-- Apply date defaults if not supplied
IF @StartDate IS NULL SET @StartDate = CAST(GETDATE() AS smalldatetime)
IF @EndDate   IS NULL SET @EndDate   = DATEADD(YEAR, 1, @StartDate)

-- -----------------------------------------------------------------------
-- Requesting user security profile
-- -----------------------------------------------------------------------
DECLARE @SecurityGroupKey    int
DECLARE @IsAdministrator     bit
DECLARE @RestrictToGLCompany tinyint
DECLARE @HasAccessAny        tinyint

SELECT @SecurityGroupKey = SecurityGroupKey,
       @IsAdministrator  = Administrator
FROM   tUser (nolock)
WHERE  UserKey    = @UserKey
AND    CompanyKey = @CompanyKey

-- GL company restriction preference
SELECT @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
FROM   tPreference (nolock)
WHERE  CompanyKey = @CompanyKey

-- Does the requesting user have the "access any project" right?
SET @HasAccessAny = 0
IF @IsAdministrator = 1
    SET @HasAccessAny = 1
ELSE IF EXISTS (
    SELECT 1
    FROM   tRight r (nolock)
    INNER JOIN tRightAssigned ra (nolock) ON r.RightKey = ra.RightKey
    WHERE  ra.EntityType = ''Security Group''
    AND    ra.EntityKey  = @SecurityGroupKey
    AND    r.RightID     = ''prjAccessAny''
)
    SET @HasAccessAny = 1

-- -----------------------------------------------------------------------
-- Resolve @Person  a single UserKey (error if not found)
-- -----------------------------------------------------------------------
DECLARE @ResolvedUserKey int = 0

IF @Person IS NOT NULL AND LTRIM(RTRIM(@Person)) <> ''''
BEGIN
SELECT TOP 1 @ResolvedUserKey = UserKey
FROM   tUser (nolock)
WHERE  CompanyKey = @CompanyKey
AND    Active     = 1
AND    (
FirstName + '' '' + LastName LIKE ''%'' + @Person + ''%''
OR Email  = @Person
OR UserID = @Person
)

IF @ResolvedUserKey = 0
BEGIN
INSERT INTO #errors (errorType, errorCode, errorMessage, fieldName)
VALUES (''error'', ''NOT_FOUND'', ''No user found matching: '' + @Person, ''person'')

SELECT errorType, errorCode, errorMessage, fieldName FROM #errors
DROP TABLE #errors
RETURN -101
END
END

-- -----------------------------------------------------------------------
-- Resolve DepartmentKey from name (warning if not found)
-- -----------------------------------------------------------------------
DECLARE @DepartmentKey int = null
IF @DepartmentName IS NOT NULL AND LTRIM(RTRIM(@DepartmentName)) <> ''''
BEGIN
SELECT TOP 1 @DepartmentKey = DepartmentKey
FROM   tDepartment (nolock)
WHERE  CompanyKey      = @CompanyKey
AND    DepartmentName LIKE ''%'' + @DepartmentName + ''%''

IF @DepartmentKey IS NULL
BEGIN
INSERT INTO #errors (errorType, errorCode, errorMessage, fieldName)
VALUES (''warning'', ''NOT_FOUND'', ''No department found matching: '' + @DepartmentName + '' - filter ignored.'', ''departmentName'')
END
END

-- -----------------------------------------------------------------------
-- Resolve OfficeKey from name (warning if not found)
-- -----------------------------------------------------------------------
DECLARE @OfficeKey int = null
IF @OfficeName IS NOT NULL AND LTRIM(RTRIM(@OfficeName)) <> ''''
BEGIN
SELECT TOP 1 @OfficeKey = OfficeKey
FROM   tOffice (nolock)
WHERE  CompanyKey  = @CompanyKey
AND    OfficeName LIKE ''%'' + @OfficeName + ''%''

IF @OfficeKey IS NULL
BEGIN
INSERT INTO #errors (errorType, errorCode, errorMessage, fieldName)
VALUES (''warning'', ''NOT_FOUND'', ''No office found matching: '' + @OfficeName + '' - filter ignored.'', ''officeName'')
END
END

-- -----------------------------------------------------------------------
-- Resolve ServiceKey from name or code (warning if not found)
-- -----------------------------------------------------------------------
DECLARE @ServiceKey int = null
IF @ServiceName IS NOT NULL AND LTRIM(RTRIM(@ServiceName)) <> ''''
BEGIN
SELECT TOP 1 @ServiceKey = ServiceKey
FROM   tService (nolock)
WHERE  CompanyKey = @CompanyKey
AND    (Description LIKE ''%'' + @ServiceName + ''%''
     OR ServiceCode LIKE ''%'' + @ServiceName + ''%'')

IF @ServiceKey IS NULL
BEGIN
INSERT INTO #errors (errorType, errorCode, errorMessage, fieldName)
VALUES (''warning'', ''NOT_FOUND'', ''No service found matching: '' + @ServiceName + '' - filter ignored.'', ''serviceName'')
END
END

-- -----------------------------------------------------------------------
-- Collect matching users based on filters
-- -----------------------------------------------------------------------
CREATE TABLE #tMatchedUsers (UserKey INT NOT NULL)

IF @ResolvedUserKey > 0
BEGIN
INSERT INTO #tMatchedUsers (UserKey) VALUES (@ResolvedUserKey)
END
ELSE
BEGIN
INSERT INTO #tMatchedUsers (UserKey)
SELECT DISTINCT u.UserKey
FROM   tUser u (nolock)
WHERE  u.CompanyKey = @CompanyKey
AND    u.Active     = 1
AND    (@DepartmentKey IS NULL OR u.DepartmentKey = @DepartmentKey)
AND    (@OfficeKey     IS NULL OR u.OfficeKey     = @OfficeKey)
AND    (@ServiceKey    IS NULL OR EXISTS (
SELECT 1 FROM tUserService us (nolock)
WHERE  us.UserKey    = u.UserKey
AND    us.ServiceKey = @ServiceKey
))
END

-- -----------------------------------------------------------------------
-- Collect task assignments for matched users within date range
-- -----------------------------------------------------------------------
CREATE TABLE #tTaskUser (TaskUserKey INT NOT NULL)

INSERT INTO #tTaskUser (TaskUserKey)
SELECT tu.TaskUserKey
FROM   #tMatchedUsers mu (nolock)
INNER JOIN tTaskUser tu (nolock) ON tu.UserKey  = mu.UserKey
INNER JOIN tTask t (nolock)     ON t.TaskKey    = tu.TaskKey
WHERE  t.PredecessorsComplete >= @PredecessorsComplete
AND    t.PlanComplete         >= @StartDate
AND    t.PlanComplete         <= @EndDate

-- -----------------------------------------------------------------------
-- Return warnings (non-fatal) then results
-- -----------------------------------------------------------------------
SELECT errorType, errorCode, errorMessage, fieldName
FROM   #errors
WHERE  errorType = ''warning''

SELECT
p.ProjectKey
,p.ProjectNumber
,p.ProjectName
,u.UserKey
,u.FirstName
,u.LastName
,u.Email
,tu.TaskUserKey
,t.TaskName
,t.TaskID
,t.PlanComplete
,t.PlanStart
,tu.Hours
,tu.ADescription AS Comments
,t.Description
,s.Description   AS ServiceDescription

FROM   #tTaskUser ta (nolock)
INNER JOIN tTaskUser tu (nolock) ON tu.TaskUserKey = ta.TaskUserKey
INNER JOIN tUser u (nolock)      ON u.UserKey      = tu.UserKey
LEFT  JOIN tService s (nolock)   ON s.ServiceKey   = tu.ServiceKey
INNER JOIN tTask t (nolock)      ON t.TaskKey      = tu.TaskKey
INNER JOIN tProject p (nolock)   ON p.ProjectKey   = t.ProjectKey
WHERE  p.Active       = 1
AND    p.CompanyKey   = @CompanyKey
AND    tu.PercComp    < 100
-- GL company restriction: requesting user must have access to the project''s GL company
AND    (@IsAdministrator = 1 OR @RestrictToGLCompany = 0 OR EXISTS (
SELECT 1 FROM tUserGLCompanyAccess ga (nolock)
WHERE  ga.UserKey      = @UserKey
AND    ga.GLCompanyKey = p.GLCompanyKey
))
-- Project assignment restriction: if no prjAccessAny right, limit to assigned projects
AND    (@HasAccessAny = 1 OR EXISTS (
SELECT 1 FROM tAssignment a (nolock)
WHERE  a.ProjectKey = p.ProjectKey
AND    a.UserKey    = @UserKey
))

ORDER BY u.LastName, u.FirstName, p.ProjectNumber, t.ProjectOrder

DROP TABLE #errors
RETURN 0

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityDelete]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityDelete]
	(
	@ActivityKey int
	)
	
AS

/*
|| When     Who Rel      What
|| 6/9/09   CRG 10.5.0.0 Added tCalendarReminder
|| 10/20/14 RLB 10.5.8.5 delete any children activities
|| 03/15/18 GWG 18.4     Add protection for deleting a 0 Key
|| 06/08/18 RLB 18.6.0.0 remove activity if it is on a review comment
|| 07/31/25 AMP 25.07.20 (705762/705766)Added webhook deleting by ActivityEntity
*/
if ISNULL(@ActivityKey , 0) = 0
	return -1


Declare @CustomFieldKey int,
        @CompanyKey int,
		@ActivityEntity varchar(50),
		@aKeys varchar(max)


Select @CustomFieldKey = ISNULL(CustomFieldKey, 0),
       @CompanyKey =  ISNULL(CompanyKey, 0),
	   @ActivityEntity = ActivityEntity
FROM tActivity (NOLOCK) 
WHERE
	ActivityKey = @ActivityKey 
	
if @CustomFieldKey > 0 
	exec spCF_tObjectFieldSetDelete @CustomFieldKey

-- delete any children of the activity getting deleted
Delete tActivityLink where ActivityKey in (select ActivityKey from tActivity (nolock) where ParentActivityKey = @ActivityKey)
Delete tActivityEmail where ActivityKey in (select ActivityKey from tActivity (nolock) where ParentActivityKey = @ActivityKey)
Delete tActivity Where ParentActivityKey =  @ActivityKey

update tReviewComment set ActivityKey = null, FixThis = null where ActivityKey = @ActivityKey



Delete tActivityLink Where ActivityKey = @ActivityKey
Delete tActivityEmail Where ActivityKey = @ActivityKey
DELETE tCalendarReminder WHERE Entity = ''tActivity'' AND EntityKey = @ActivityKey
Delete tActivity Where ActivityKey = @ActivityKey


--Created new for Webhooks - Delete will return the key that was deleted
--Insert into tApiQueue only when the record exists in tApiHook    	
SELECT @aKeys =  ISNULL(CONVERT(VARCHAR(100),@ActivityKey), '''')
exec spApiWebHookQueueInsert @CompanyKey, @ActivityEntity, @aKeys, ''D''
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetCalendarEvents]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetCalendarEvents]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spApiAIGetCalendarEvents]
(
	@CompanyKey int,
	@UserKey int,
	@StartDate datetime,
	@EndDate datetime,
	@UTCOffsetHours	int      = 0,
	@UserName varchar(200)   = NULL
)

as

/*
|| When      Who Rel        What
|| 05/01/26  GRR 26.05.xx   Created
|| 05/04/26  GRR 26.05.xx   Added user name to search on.
|| 05/15/26  GRR 26.05.xx   Fixed date range filter to use overlap check so events ending after midnight are returned.
|| 05/28/26  AI  26.05.28   Reviewed: only feature-right (admineditusercalendar) check; no record-level entity gate applies. Normalized to CREATE OR ALTER.
|| 06/18/26  GAR 26.07.xx   Also allow access when caller''s security group has CanView or CanAdd in tCMFolderSecurity for the target user''s calendar folder.
|| 06/29/26  GAR 26.07.xx   Initialize @IsAdministrator = 0 so a failed tUser lookup never silently bypasses the security check.
|| 06/29/26  GAR 26.07.xx   Per-folder security: admins/admineditusercalendar get all events; others get only events from folders
||                           they have explicit tCMFolderSecurity access to. Upfront check now only errors when caller has NO
||                           folder access at all rather than acting as an all-or-nothing gate.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right calUseCalendar.
*/

Declare @SecurityGroupKey int
Declare @IsAdministrator bit = 0
Declare @HasAdminRight bit = 0
Declare @TargetUserKey int

    -- ------------------------------------------------------------------
    -- Gating security: calUseCalendar
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''calUseCalendar''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (calUseCalendar).'' as errorMessage, ''general'' as fieldName
        return -103
    end

Select * into #errors From tAPIErrorTemplate Where 1 = 2

-- If a user name was provided, resolve it to a UserKey
If @UserName Is Not Null And LTRIM(RTRIM(@UserName)) <> ''''
Begin
	Select Top 1 @TargetUserKey = UserKey
	From tUser (nolock)
	Where CompanyKey = @CompanyKey
	And ISNULL(Active,0) = 1
	And (FirstName + '' '' + LastName LIKE ''%'' + @UserName + ''%''
			Or UserID Like ''%'' + @UserName + ''%''
			Or Email Like ''%'' + @UserName + ''%''
		)
	Order By UserKey

	If @TargetUserKey Is Null
	Begin
		Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
		Values (''error'', ''NOT_FOUND'', ''User not found: '' + @UserName + ''.'', ''userName'')

		Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
		Drop Table #errors
		Return -101
	End

	-- Security only applies when viewing a different user''s calendar
	If @TargetUserKey <> @UserKey
	Begin
		Select @SecurityGroupKey = SecurityGroupKey,
			@IsAdministrator = ISNULL(Administrator, 0)
		From tUser (nolock)
		Where UserKey = @UserKey
			And CompanyKey = @CompanyKey

		If @IsAdministrator = 0
		Begin
			-- Check for the broad ''admineditusercalendar'' feature right (grants access to all folders)
			If Exists (
				Select 1 From tRight r (nolock)
				Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
				Where ra.EntityType = ''SecurityGroup''
				And ra.EntityKey = @SecurityGroupKey
				And r.RightID = ''admineditusercalendar''
			)
				Set @HasAdminRight = 1

			-- Without the broad right, caller must have per-folder access to at least one of
			-- the target user''s calendar folders.  If none exist, return ACCESS_DENIED now
			-- so we give a meaningful error rather than silently returning zero rows.
			If @HasAdminRight = 0
			Begin
				If Not Exists (
					Select 1 From tCMFolder f (nolock)
					Inner Join tCMFolderSecurity fsec (nolock) On f.CMFolderKey = fsec.CMFolderKey
					Where f.UserKey = @TargetUserKey
					And f.Entity = ''tCalendar''
					And (fsec.CanView = 1 Or fsec.CanAdd = 1)
					And (   (fsec.Entity = ''tUser''          And fsec.EntityKey = @UserKey)
					     Or (fsec.Entity = ''tSecurityGroup'' And fsec.EntityKey = @SecurityGroupKey)
					    )
				)
				Begin
					Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
					Values (''error'', ''ACCESS_DENIED'', ''You do not have permissions to view other users'''' calendar entries.'', ''userName'')

					Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
					Drop Table #errors
					Return -103
				End
			End
		End
	End

End
Else
	Set @TargetUserKey = @UserKey

Drop Table #errors

-- First leg: non-recurring events and first occurrence of recurring events (stored in tCalendar)
Select cal.Subject, cal.Description, cal.Location, p.ProjectNumber, p.ProjectName, t.TaskID, u.FirstName + '' '' + u.LastName as ContactName, c.CompanyName,
	cal.Recurring, cal.RecurringCount, cal.RecurringEndDate, cal.RecurringSettings, cal.UID, cal.OriginalUID, cal.EventStart as EventStart, cal.EventEnd as EventEnd, cal.Pattern, cal.Su, cal.Mo, cal.Tu, cal.We, cal.Th, cal.Fr, cal.Sa,
	f.FolderName as FolderName
From tCalendar cal (nolock)
inner join tCalendarAttendee ca (nolock) on ca.CalendarKey = cal.CalendarKey
inner join tCMFolder f (nolock) on f.CMFolderKey = ca.CMFolderKey
left outer join tProject p (nolock) on p.ProjectKey = cal.ProjectKey
left outer join tTask t (nolock) on t.TaskKey = cal.TaskKey
left outer join tUser u (nolock) on u.UserKey = cal.ContactUserKey
left outer join tCompany c (nolock) on c.CompanyKey = cal.ContactCompanyKey

Where f.UserKey = @TargetUserKey
And cal.EventStart < DATEADD(day, 1, @EndDate)
And cal.EventEnd > @StartDate
And (
	@TargetUserKey = @UserKey		-- own calendar: no restriction
	Or @IsAdministrator = 1			-- system admin: no restriction
	Or @HasAdminRight = 1			-- admineditusercalendar right: no restriction
	Or Exists (						-- per-folder grant: only folders caller can see
		Select 1 From tCMFolderSecurity fsec (nolock)
		Where fsec.CMFolderKey = f.CMFolderKey
		And (fsec.CanView = 1 Or fsec.CanAdd = 1)
		And (   (fsec.Entity = ''tUser''          And fsec.EntityKey = @UserKey)
		     Or (fsec.Entity = ''tSecurityGroup'' And fsec.EntityKey = @SecurityGroupKey)
		    )
	)
)

Union All

-- Second leg: subsequent occurrences of recurring events (stored in tCalendarCache)
Select cal.Subject, cal.Description, cal.Location, p.ProjectNumber, p.ProjectName, t.TaskID, u.FirstName + '' '' + u.LastName as ContactName, c.CompanyName,
	cal.Recurring, cal.RecurringCount, cal.RecurringEndDate, cal.RecurringSettings, cal.UID, cal.OriginalUID, cal.EventStart as EventStart, cal.EventEnd as EventEnd, cal.Pattern, cal.Su, cal.Mo, cal.Tu, cal.We, cal.Th, cal.Fr, cal.Sa,
	f.FolderName as FolderName
From tCalendar cal (nolock)
inner join tCalendarCache cc (nolock) on cc.CalendarKey = cal.CalendarKey
inner join tCalendarAttendee ca (nolock) on ca.CalendarKey = cal.CalendarKey
inner join tCMFolder f (nolock) on f.CMFolderKey = ca.CMFolderKey
left outer join tProject p (nolock) on p.ProjectKey = cal.ProjectKey
left outer join tTask t (nolock) on t.TaskKey = cal.TaskKey
left outer join tUser u (nolock) on u.UserKey = cal.ContactUserKey
left outer join tCompany c (nolock) on c.CompanyKey = cal.ContactCompanyKey

Where f.UserKey = @TargetUserKey
And cc.EventStart < DATEADD(day, 1, @EndDate)
And cc.EventEnd > @StartDate
And (
	@TargetUserKey = @UserKey		-- own calendar: no restriction
	Or @IsAdministrator = 1			-- system admin: no restriction
	Or @HasAdminRight = 1			-- admineditusercalendar right: no restriction
	Or Exists (						-- per-folder grant: only folders caller can see
		Select 1 From tCMFolderSecurity fsec (nolock)
		Where fsec.CMFolderKey = f.CMFolderKey
		And (fsec.CanView = 1 Or fsec.CanAdd = 1)
		And (   (fsec.Entity = ''tUser''          And fsec.EntityKey = @UserKey)
		     Or (fsec.Entity = ''tSecurityGroup'' And fsec.EntityKey = @SecurityGroupKey)
		    )
	)
)


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCF_tFieldDefUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spCF_tFieldDefUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spCF_tFieldDefUpdate]
 @FieldDefKey int,
 @OwnerEntityKey int,
 @AssociatedEntity varchar(50),
 @FieldName varchar(75),
 @Description varchar(300),
 @DisplayType smallint,
 @Caption varchar(1000),
 @Hint varchar(1000),
 @Size int,
 @MinSize int,
 @MaxSize int,
 @TextRows int,
 @ValueList text,
 @Required tinyint,
 @Active tinyint,
 @OnlyAuthorEdit tinyint,
 @MapTo int,
 @DisplayViewMode tinyint,
 @DisplayWhen tinyint,
 @DisplayWhenFieldDefKey int,
 @DisplayWhenValue nvarchar(1000),
 @DefaultValue nvarchar(max) = NULL,
 @DoNotCopy tinyint = 0,
 @DisplayWhenMatchType tinyint = 0,
 @ParentFieldDefKey int = NULL,
 @DecimalPlaces int = 0,
 @Color varchar(20) = NULL
 
AS --Encrypt

/*
|| When      Who Rel     What
|| 06/22/11  GHL 10.545  (114355) Changed @ValueList from varchar(4000) to text
|| 11/15/13  RLB 10.574  (190288) increaded Hint to varchar(300)
|| 11/19/15  MAS 10.599  (278451) Added DisplayViewMode to support display only CF
|| 02/25/15  MAS 10.601  (278448) Added DisplayWhen, DisplayWhenFieldDefKey & @DisplayWhenValue to support conditional CFs
|| 05/18/16  MCM 10.606  (295808) Increased size of Caption and Hint to 1000 Characters
|| 01/10/17  GWG 18.2	 Added default value and do not copy
|| 08/24/18  WDF 18.9.0  (416610) Change ''DisplayWhenValue'' from varchar(50) to varchar(1000)
|| 12/18/18  WDF 19.02.0 (416610) Added ''DisplayWhenMatchType''
|| 1/22/19   GWG 19.0.2  (440922) Adding parent field capability
|| 2/20/19   GWG 19.0.3  Adding Decimal Places for input fields and converted to work like the new sp (combine insert and update)
|| 6/11/19   GWG 19.0.7  Adding color for date fields on deliverables
|| 06/26/20  RLS 20.0.7  (518686) Converted DisplayWhenValue and DefaultValue to nvarchar
*/

 IF EXISTS(SELECT 1 FROM tFieldDef (NOLOCK)
  WHERE FieldName = @FieldName AND OwnerEntityKey = @OwnerEntityKey AND FieldDefKey <> @FieldDefKey AND AssociatedEntity = @AssociatedEntity and FieldDefKey > 0)
	Return -1


if @FieldDefKey <= 0
BEGIN

INSERT tFieldDef
  (
  OwnerEntityKey,
  AssociatedEntity,
  FieldName,
  Description,
  DisplayType,
  Caption,
  Hint,
  Size,
  MinSize,
  MaxSize,
  TextRows,
  ValueList,
  Required,
  Active,
  OnlyAuthorEdit,
  MapTo,
  DisplayViewMode,
  DisplayWhen,
  DisplayWhenFieldDefKey,
  DisplayWhenValue,
  DefaultValue,
  DoNotCopy,
  DisplayWhenMatchType,
  ParentFieldDefKey,
  DecimalPlaces,
  Color
  )
 VALUES
  (
  @OwnerEntityKey,
  @AssociatedEntity,
  @FieldName,
  @Description,
  @DisplayType,
  @Caption,
  @Hint,
  @Size,
  @MinSize,
  @MaxSize,
  @TextRows,
  @ValueList,
  @Required,
  @Active,
  @OnlyAuthorEdit,
  @MapTo,
  @DisplayViewMode,
  @DisplayWhen,
  @DisplayWhenFieldDefKey,
  @DisplayWhenValue,
  @DefaultValue,
  @DoNotCopy,
  @DisplayWhenMatchType,
  @ParentFieldDefKey,
  @DecimalPlaces,
  @Color
  )
 
SELECT @FieldDefKey = @@IDENTITY
END

ELSE
BEGIN
  UPDATE
   tFieldDef
  SET
   OwnerEntityKey = @OwnerEntityKey,
   FieldName = @FieldName,
   Description = @Description,
   DisplayType = @DisplayType,
   Caption = @Caption,
   Hint = @Hint,
   Size = @Size,
   MinSize = @MinSize,
   MaxSize = @MaxSize,
   TextRows = @TextRows,
   ValueList = @ValueList,
   Required = @Required,
   Active = @Active,
   OnlyAuthorEdit = @OnlyAuthorEdit,
   MapTo = @MapTo,
   DisplayViewMode = @DisplayViewMode,
   DisplayWhen = @DisplayWhen,
   DisplayWhenFieldDefKey = @DisplayWhenFieldDefKey,
   DisplayWhenValue = @DisplayWhenValue,
   DefaultValue = @DefaultValue,
   DoNotCopy = @DoNotCopy,
   DisplayWhenMatchType = @DisplayWhenMatchType,
   ParentFieldDefKey = @ParentFieldDefKey,
   DecimalPlaces = @DecimalPlaces,
   Color = @Color
  WHERE
   FieldDefKey = @FieldDefKey 

END


  return @FieldDefKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spProcessWIPWorksheetOneLinePerItem]'
GO
IF OBJECT_ID(N'[dbo].[spProcessWIPWorksheetOneLinePerItem]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spProcessWIPWorksheetOneLinePerItem]
	(
		@NewInvoiceKey INT
		,@ProjectKey INT
		,@DefaultSalesAccountKey INT
		,@DefaultClassKey INT
		,@WorkTypeKey INT
		,@PostSalesUsingDetail INT
		,@CampaignKey INT = null
	)
AS -- Encrypt

  /*
  || When     Who Rel     What
  || 07/17/26 MFT 26.08.01 (729267) Created to support BillExpensesByItem (extra expenses billed one line per Item)
  || 07/28/26 MFT 26.08.01 (729267) Added a parent "Expenses" summary line containing the per-Item lines
  */

	SET NOCOUNT ON

declare @RetVal int
declare @NewInvoiceLineKey int
declare @CompanyKey int
declare @LineOrder int
declare @EntityName varchar(250)
declare @CurLineOrder int
declare @CurItemKey int
declare @CurItemName varchar(250)
declare @CurAmount money
declare @CurTaxable tinyint
declare @CurTaxable2 tinyint
declare @CurEntityKey int
declare @ExpensesLineKey int   -- parent "Expenses" summary line that groups the per-Item lines

if isnull(@ProjectKey, 0) > 0
	select @CompanyKey = CompanyKey from tProject (nolock) where ProjectKey = @ProjectKey
else if isnull(@CampaignKey, 0) > 0
	select @CompanyKey = CompanyKey from tCampaign (nolock) where CampaignKey = @CampaignKey

CREATE TABLE #expenseByItem ( ItemKey int NULL, Amount money NULL )
CREATE TABLE #expenseByItemTotal ( ItemKey int NULL, ItemName VARCHAR(250) NULL, Amount money NULL, LineOrder int NULL, Taxable tinyint NULL, Taxable2 tinyint NULL )

-- expense receipts
insert #expenseByItem (ItemKey, Amount)
select isnull(t.ItemKey, 0), sum(isnull(t.BillableCost,0))
from   tExpenseReceipt t (nolock), #tProcWIPKeys w
where  w.EntityType = ''Expense''
and    t.ExpenseReceiptKey = cast(w.EntityKey as integer)
group by isnull(t.ItemKey, 0)

-- misc expenses
insert #expenseByItem (ItemKey, Amount)
select isnull(t.ItemKey, 0), sum(isnull(t.BillableCost,0))
from   tMiscCost t (nolock), #tProcWIPKeys w
where  w.EntityType = ''MiscExpense''
and    t.MiscCostKey = cast(w.EntityKey as integer)
group by isnull(t.ItemKey, 0)

-- vouchers
insert #expenseByItem (ItemKey, Amount)
select isnull(t.ItemKey, 0), sum(isnull(t.BillableCost,0))
from   tVoucherDetail t (nolock), #tProcWIPKeys w
where  w.EntityType = ''Voucher''
and    t.VoucherDetailKey = cast(w.EntityKey as integer)
group by isnull(t.ItemKey, 0)

-- po''s
insert #expenseByItem (ItemKey, Amount)
select isnull(pod.ItemKey, 0), sum(Case ISNULL(po.BillAt, 0)
			When 0 then isnull(pod.BillableCost,0)
			When 1 then isnull(pod.PTotalCost,isnull(pod.TotalCost,0))
			When 2 then isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,isnull(pod.TotalCost,0)) end )
from   tPurchaseOrderDetail pod (nolock)
inner join tPurchaseOrder po (nolock) on po.PurchaseOrderKey = pod.PurchaseOrderKey
inner join #tProcWIPKeys w on pod.PurchaseOrderDetailKey = cast(w.EntityKey as integer)
where  w.EntityType = ''Order''
group by isnull(pod.ItemKey, 0)

insert #expenseByItemTotal (ItemKey, Amount)
select ItemKey, sum(Amount)
from   #expenseByItem
group by ItemKey

update #expenseByItemTotal
set    ItemName = i.ItemName
	  ,Taxable = i.Taxable
	  ,Taxable2 = i.Taxable2
from   tItem i (nolock)
where  #expenseByItemTotal.ItemKey = i.ItemKey
and    i.CompanyKey = @CompanyKey

update #expenseByItemTotal
set    ItemName = ''[No Item]''
where  ItemKey = 0 or ItemName is null

update #expenseByItemTotal
set    Taxable = isnull(Taxable, 0)
	  ,Taxable2 = isnull(Taxable2, 0)

-- establish a stable line order (alphabetical by item name)
select @LineOrder = 1
select @EntityName = ''''
while (1=1)
begin
	select @EntityName = min(ItemName)
	from   #expenseByItemTotal
	where  ItemName > @EntityName

	if @EntityName is null
		break

	update #expenseByItemTotal
	set    LineOrder = @LineOrder
	where  ItemName = @EntityName

	select @LineOrder = @LineOrder + 1
end

-- Add a parent "Expenses" summary line (amount 0) that will contain all per-Item lines.
-- Amount stays 0 so the invoice total is not double-counted (sptInvoiceRecalcAmounts sums every line).
if exists (select 1 from #expenseByItemTotal)
begin
	exec @RetVal = sptInvoiceLineInsertMassBilling
			@NewInvoiceKey				-- Invoice Key
			,@ProjectKey				-- ProjectKey
			,NULL						-- TaskKey
			,''Expenses''					-- Line Subject
			,null						-- Line description
			,2							-- Bill From
			,0							-- Quantity
			,0							-- Unit Amount
			,0							-- Line Amount (header only - children carry the amounts)
			,1							-- line type (1 = header/summary)
			,0							-- parent line key
			,@DefaultSalesAccountKey	-- Default Sales AccountKey
			,@DefaultClassKey			-- Class Key
			,0							-- Taxable
			,0							-- Taxable2
			,@WorkTypeKey				-- Work TypeKey
			,@PostSalesUsingDetail
			,NULL						-- Entity
			,NULL						-- EntityKey
			,NULL						-- OfficeKey
			,NULL						-- DepartmentKey
			,@ExpensesLineKey output

	if @RetVal <> 1
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -6
	  end
	if @@ERROR <> 0
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -6
	  end
end

select @CurLineOrder = min(LineOrder) from #expenseByItemTotal

while @CurLineOrder is not null
begin
	select @CurItemKey = ItemKey, @CurItemName = ItemName, @CurAmount = isnull(Amount, 0)
		  ,@CurTaxable = isnull(Taxable, 0), @CurTaxable2 = isnull(Taxable2, 0)
	from   #expenseByItemTotal
	where  LineOrder = @CurLineOrder

	select @CurEntityKey = null
	if @CurItemKey > 0
		select @CurEntityKey = @CurItemKey

	exec @RetVal = sptInvoiceLineInsertMassBilling
			@NewInvoiceKey				-- Invoice Key
			,@ProjectKey				-- ProjectKey
			,NULL						-- TaskKey
			,@CurItemName				-- Line Subject
			,null						-- Line description
			,2							-- Bill From
			,0							-- Quantity
			,0							-- Unit Amount
			,@CurAmount					-- Line Amount
			,2							-- line type
			,@ExpensesLineKey			-- parent line key (nested under the "Expenses" summary line)
			,@DefaultSalesAccountKey	-- Default Sales AccountKey
			,@DefaultClassKey			-- Class Key
			,@CurTaxable				-- Taxable
			,@CurTaxable2				-- Taxable2
			,@WorkTypeKey				-- Work TypeKey
			,@PostSalesUsingDetail
			,''tItem''					-- Entity
			,@CurEntityKey				-- EntityKey
			,NULL						-- OfficeKey
			,NULL						-- DepartmentKey
			,@NewInvoiceLineKey output

	if @RetVal <> 1
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -6
	  end
	if @@ERROR <> 0
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -6
	  end

	-- expenses
	update tExpenseReceipt
	   set InvoiceLineKey = @NewInvoiceLineKey
		  ,AmountBilled = BillableCost
	  from #tProcWIPKeys
	 where #tProcWIPKeys.EntityType = ''Expense''
	   and tExpenseReceipt.ExpenseReceiptKey = cast(#tProcWIPKeys.EntityKey as integer)
	   and isnull(tExpenseReceipt.ItemKey, 0) = @CurItemKey
	if @@ERROR <> 0
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -8
	  end

	-- misc expenses
	update tMiscCost
	   set InvoiceLineKey = @NewInvoiceLineKey
		  ,AmountBilled = BillableCost
	  from #tProcWIPKeys
	 where #tProcWIPKeys.EntityType = ''MiscExpense''
	   and tMiscCost.MiscCostKey = cast(#tProcWIPKeys.EntityKey as integer)
	   and isnull(tMiscCost.ItemKey, 0) = @CurItemKey
	if @@ERROR <> 0
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -9
	  end

	-- voucher
	update tVoucherDetail
	   set InvoiceLineKey = @NewInvoiceLineKey
		  ,AmountBilled = BillableCost
	  from #tProcWIPKeys
	 where #tProcWIPKeys.EntityType = ''Voucher''
	   and tVoucherDetail.VoucherDetailKey = cast(#tProcWIPKeys.EntityKey as integer)
	   and isnull(tVoucherDetail.ItemKey, 0) = @CurItemKey
	if @@ERROR <> 0
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -10
	  end

	-- po
	update tPurchaseOrderDetail
	   set InvoiceLineKey = @NewInvoiceLineKey
		,tPurchaseOrderDetail.AccruedCost =
					CASE
						WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
						ELSE 0
					END
		  ,AmountBilled = isnull(Case ISNULL(po.BillAt, 0)
			When 0 then isnull(BillableCost,0)
			When 1 then isnull(PTotalCost,isnull(TotalCost,0))
			When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
	  from #tProcWIPKeys, tPurchaseOrder po (nolock)
	 where #tProcWIPKeys.EntityType = ''Order''
	   and po.PurchaseOrderKey = tPurchaseOrderDetail.PurchaseOrderKey
	   and tPurchaseOrderDetail.PurchaseOrderDetailKey = cast(#tProcWIPKeys.EntityKey as integer)
	   and isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey
	if @@ERROR <> 0
	  begin
		exec sptInvoiceDelete @NewInvoiceKey
		return -10
	  end

	select @CurLineOrder = min(LineOrder) from #expenseByItemTotal where LineOrder > @CurLineOrder
end

exec sptInvoiceRecalcAmounts @NewInvoiceKey

RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesTransactionsAddExtras]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesTransactionsAddExtras]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spFixedFeesTransactionsAddExtras]
	(
	@InvoiceKey int
	,@ProjectKey int
	,@CampaignKey int = null
	)
	AS --Encrypt

/*
|| When     Who Rel     What
|| 04/12/16 GHL 10.603  Creation for the new wjapp FF billing screens
||                      when creating a FF invoice, add extra transactions if there are not included in the fixed fee setup
|| 04/13/16 GHL 10.603  Added rollup in tInvoiceSummary
|| 06/27/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
|| 10/19/20 GHL 20.110 (533381) Changes for Campaign FF billing, now ProjectKey can be null
|| 03/18/22 GHL 22.04.17 (590582) Added support for tProject.SetTaxableOnInvoice 
|| 04/17/24 MCM 24.05.xx (670036) Added support for the Credit Card Charges
|| 07/17/26 MFT 26.08.01 (729267) Added BillExpensesByItem (extra expenses billed one line per Item)
*/

if isnull(@InvoiceKey, 0) = 0
	return 1

if not exists (select 1 from #tProcWIPKeys )
	return 1

declare @ExpensesNotIncluded int
declare @CompanyKey int
declare @BillExpensesByItem int

if isnull(@ProjectKey,0) = 0 and isnull(@CampaignKey,0) = 0
	return 1

if isnull(@ProjectKey,0) > 0
	select @ExpensesNotIncluded = ExpensesNotIncluded
		  ,@CompanyKey = CompanyKey
		  ,@BillExpensesByItem = isnull(BillExpensesByItem, 0)
	from tProject (nolock) where ProjectKey = @ProjectKey

if isnull(@CampaignKey,0) > 0
	select @ExpensesNotIncluded = ExpensesNotIncluded
		  ,@CompanyKey = CompanyKey
		  ,@BillExpensesByItem = isnull(BillExpensesByItem, 0)
	from tCampaign (nolock) where CampaignKey = @CampaignKey

if isnull(@ExpensesNotIncluded, 0) = 0
	return 1 -- expenses are included

-- Types in vProjectCosts
	declare @kTypeLabor varchar(20)						select @kTypeLabor = ''LABOR''
	declare @kTypeExpenseReport varchar(20)				select @kTypeExpenseReport = ''EXPRPT''
	declare @kTypeMiscCost varchar(20)					select @kTypeMiscCost = ''MISCCOST''
	declare @kTypeVoucher varchar(20)					select @kTypeVoucher = ''VOUCHER''
	declare @kTypeOrder varchar(20)						select @kTypeOrder = ''ORDER''
	declare @kTypeCCCharge varchar(20)					select @kTypeCCCharge = ''CREDIT CARD CHARGE''
	
	-- Types in proc wip 
	declare @kWIPLabor varchar(20)						select @kWIPLabor = ''Time''
	declare @kWIPExpenseReport varchar(20)				select @kWIPExpenseReport = ''Expense''
	declare @kWIPMiscCost varchar(20)					select @kWIPMiscCost = ''MiscExpense''
	declare @kWIPVoucher varchar(20)					select @kWIPVoucher = ''Voucher''
	declare @kWIPOrder varchar(20)						select @kWIPOrder = ''Order''
	declare @kWIPCCCharge varchar(20)					select @kWIPCCCharge = ''Voucher'' --''CreditCardCharge''
	
	-- Then change vProjectCosts types to the WIP types
	update #tProcWIPKeys
	set    EntityType = 
		case 
			when EntityType = @kTypeLabor then @kWIPLabor 
			when EntityType = @kTypeExpenseReport then @kWIPExpenseReport
			when EntityType = @kTypeMiscCost then @kWIPMiscCost
			when EntityType = @kTypeVoucher then @kWIPVoucher
			when EntityType = @kTypeOrder then @kWIPOrder
			when EntityType = @kTypeCCCharge then @kWIPCCCharge
			end
	/*		
	|| Validations
	*/	
	-- no labor
	delete #tProcWIPKeys where EntityType = @kWIPLabor 

	-- check if already invoiced
	update #tProcWIPKeys  
	set    #tProcWIPKeys.InvoiceLineKey = b.InvoiceLineKey
	      ,#tProcWIPKeys.WriteOff = b.WriteOff
	from  tMiscCost b (NOLOCK) 
	where b.MiscCostKey = cast(#tProcWIPKeys.EntityKey as integer)
	and #tProcWIPKeys.EntityType = @kWIPMiscCost
	
	update #tProcWIPKeys  
	set    #tProcWIPKeys.InvoiceLineKey = b.InvoiceLineKey
			,#tProcWIPKeys.WriteOff = b.WriteOff
	from  tExpenseReceipt b (NOLOCK) 
	where b.ExpenseReceiptKey = cast(#tProcWIPKeys.EntityKey as integer)
	and #tProcWIPKeys.EntityType = @kWIPExpenseReport

	update #tProcWIPKeys  
	set    #tProcWIPKeys.InvoiceLineKey = b.InvoiceLineKey
			,#tProcWIPKeys.WriteOff = b.WriteOff
	from  tVoucherDetail b (NOLOCK) 
	where b.VoucherDetailKey = cast(#tProcWIPKeys.EntityKey as integer)
	and #tProcWIPKeys.EntityType = @kWIPVoucher

	update #tProcWIPKeys  
	set    #tProcWIPKeys.InvoiceLineKey = b.InvoiceLineKey
	from  tPurchaseOrderDetail b (NOLOCK) 
	where b.PurchaseOrderDetailKey = cast(#tProcWIPKeys.EntityKey as integer)
	and #tProcWIPKeys.EntityType = @kWIPOrder

	-- check billing worksheets
	update #tProcWIPKeys  
	set    #tProcWIPKeys.BillingID = b.BillingID
	from  tBillingDetail bd (NOLOCK) 
		  ,tBilling b (nolock)
	where bd.EntityKey = cast(#tProcWIPKeys.EntityKey as integer)
	AND   bd.Entity = ''tMiscCost''
	AND   b.CompanyKey = @CompanyKey
	AND   b.Status < 5
	and   b.BillingKey = bd.BillingKey
	and #tProcWIPKeys.EntityType = @kWIPMiscCost
	
	update #tProcWIPKeys  
	set    #tProcWIPKeys.BillingID = b.BillingID
	from  tBillingDetail bd (NOLOCK) 
		  ,tBilling b (nolock)
	where bd.EntityKey = cast(#tProcWIPKeys.EntityKey as integer)
	AND   bd.Entity = ''tExpenseReceipt''
	AND   b.CompanyKey = @CompanyKey
	AND   b.Status < 5
	and   b.BillingKey = bd.BillingKey
	and #tProcWIPKeys.EntityType = @kWIPExpenseReport

	update #tProcWIPKeys  
	set    #tProcWIPKeys.BillingID = b.BillingID
	from  tBillingDetail bd (NOLOCK) 
		  ,tBilling b (nolock)
	where bd.EntityKey = cast(#tProcWIPKeys.EntityKey as integer)
	AND   bd.Entity = ''tVoucherDetail''
	AND   b.CompanyKey = @CompanyKey
	AND   b.Status < 5
	and   b.BillingKey = bd.BillingKey
	and #tProcWIPKeys.EntityType = @kWIPVoucher

	update #tProcWIPKeys  
	set    #tProcWIPKeys.BillingID = b.BillingID
	from  tBillingDetail bd (NOLOCK) 
		  ,tBilling b (nolock)
	where bd.EntityKey = cast(#tProcWIPKeys.EntityKey as integer)
	AND   bd.Entity = ''tPurchaseOrderDetail''
	AND   b.CompanyKey = @CompanyKey
	AND   b.Status < 5
	and   b.BillingKey = bd.BillingKey
	and #tProcWIPKeys.EntityType = @kWIPOrder

	-- do not process if billed or in the process of being billed
	delete #tProcWIPKeys where InvoiceLineKey is not null or BillingID is not null or WriteOff  = 1

	if not exists (select 1 from #tProcWIPKeys)
		return 1

-- Now create invoice line for the transactions

declare @RetVal int
declare @DefaultSalesAccountKey int
declare @HeaderClassKey int
declare @DefaultClassKey int
declare @WorkTypeKey int
declare @PostSalesUsingDetail int
declare @RequireClasses int
declare @SetTaxableOnInvoice int

Select @PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
			,@WorkTypeKey         = AdvBillItemKey
			,@RequireClasses      = ISNULL(RequireClasses, 0)
			,@DefaultClassKey     = DefaultClassKey
			,@DefaultSalesAccountKey = DefaultSalesAccountKey
			,@SetTaxableOnInvoice = isnull(SetTaxableOnInvoice, 0)
	From tPreference (nolock)
		Where CompanyKey = @CompanyKey
			
select @HeaderClassKey = ClassKey from tInvoice (nolock) where InvoiceKey = @InvoiceKey
if @RequireClasses = 1 and isnull(@HeaderClassKey, 0) = 0
	select @HeaderClassKey = @DefaultClassKey

if isnull(@BillExpensesByItem, 0) = 0
begin
	-- Default behavior: all extra expenses roll up into a single ''Expenses'' line
	exec @RetVal = spProcessWIPWorksheetOneLine @InvoiceKey ,@ProjectKey ,''Expenses''
				,@DefaultSalesAccountKey, @HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail
end
else
begin
	-- Bill Expenses by Item: one invoice line per Item, instead of a single ''Expenses'' line
	exec @RetVal = spProcessWIPWorksheetOneLinePerItem @InvoiceKey ,@ProjectKey
				,@DefaultSalesAccountKey, @HeaderClassKey, @WorkTypeKey ,@PostSalesUsingDetail, @CampaignKey
end

-- This will force the Taxable fields if the pref or the project requires them
exec sptInvoiceSetTaxable @InvoiceKey, @SetTaxableOnInvoice

-- before we leave, better to recalc the amounts in the header  
exec sptInvoiceRecalcAmounts @InvoiceKey 

-- recalc invoice order from the root
exec sptInvoiceOrder @InvoiceKey, 0, 0, 0

-- and update the invoice summary table
exec sptInvoiceSummary @InvoiceKey

if @RetVal <0
	return -1

return 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetOpportunities]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetOpportunities]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIGetOpportunities]
(
    @CompanyKey   int,
    @UserKey      int,
    @Stage        varchar(300) = null,
    @Status       varchar(300) = null,
    @Owner        varchar(300) = null,
    @ProjectType  varchar(300) = null,
    @StartDate    date         = null,
    @EndDate      date         = null
)
AS --Encrypt

/*
|| When      Who Rel        What
|| --        --  --         Created - opportunities list with set-based GL filter
|| 05/25/26  AI  26.05.25   Added #errors / warnings scaffold; result-set shape is now
||                          [warnings, opportunities] - handler updated to match.
|| 05/28/26  AI  26.05.28   Added #errors / warnings result-set; handler updated to read [warnings, opportunities].
|| 07/10/26  GAR 26.07.19   Added gating security - requires useOpp; cm_viewothermanagers gates opportunities not assigned to the caller.
*/

set nocount on

    -- ------------------------------------------------------------------
    -- Gating security: useOpp
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint
    declare @gsCanViewOthers    tinyint = 0

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''useOpp''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (useOpp).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    -- cm_viewothermanagers: without it (and not admin), restrict to opportunities
    -- where the caller is the account manager.
    if @gsIsAdministrator = 1
        set @gsCanViewOthers = 1
    else if exists (
            select 1
            from   tRight r (nolock)
            inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
            where  ra.EntityType = ''Security Group''
              and  ra.EntityKey  = @gsSecurityGroupKey
              and  r.RightID     = ''cm_viewothermanagers''
        )
        set @gsCanViewOthers = 1

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @RestrictToGLCompany int

    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    from   tPreference (nolock) where CompanyKey = @CompanyKey

    -- Result set 1: warnings
    select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''

    -- Result set 2: opportunities
    select
        l.LeadID            as leadID,
        l.Subject           as subject,
        ls.LeadStageName    as stageName,
        lst.LeadStatusName  as status,
        u.UserFullName      as accountManagerName,
        u.Email             as accountManagerEmail,
        l.CurrentStatus     as currentStatus,
        l.OutcomeComment    as outcomeComment,
        l.DateAdded         as dateAdded,
        l.SaleAmount        as saleAmount,
        l.Probability       as probability,
        l.SubAmount         as subAmount,
        l.Margin            as margin,
        l.OutsideCostsGross as outsideCostsGross,
        l.MediaGross        as mediaGross,
        l.MediaPerc         as mediaPerc,
        l.AGI               as agi,
        l.Labor             as laborAmount,
        l.Months            as months,
        l.BidDate           as bidDate,
        l.EstCloseDate      as estCloseDate,
        l.ActualCloseDate   as actualCloseDate,
        l.DateUpdated       as dateUpdated,
        l.Comments          as description
    from   tLead l (nolock)
    left join tLeadStage ls (nolock) on l.LeadStageKey = ls.LeadStageKey
    left join tLeadStatus lst (nolock) on l.LeadStatusKey = lst.LeadStatusKey
    left join vUserName u (nolock) on l.AccountManagerKey = u.UserKey
    left join tProjectType pt (nolock) on l.ProjectTypeKey = pt.ProjectTypeKey
    where  l.CompanyKey = @CompanyKey
      and  (@Stage       is null or ls.LeadStageName    in (select value from STRING_SPLIT(@Stage, '','')))
      and  (@Status      is null or lst.LeadStatusName  in (select value from STRING_SPLIT(@Status, '','')))
      and  (@Owner       is null or u.UserName          in (select value from STRING_SPLIT(@Owner, '','')))
      and  (@ProjectType is null or pt.ProjectTypeName  in (select value from STRING_SPLIT(@ProjectType, '','')))
      and  (@StartDate   is null or l.DateAdded         >= @StartDate)
      and  (@EndDate     is null or l.DateAdded         <= @EndDate)
      and  (@RestrictToGLCompany = 0
            or l.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey))
      and  (@gsCanViewOthers = 1 or l.AccountManagerKey = @UserKey)

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptAttachmentValidatePermission]'
GO
IF OBJECT_ID(N'[dbo].[sptAttachmentValidatePermission]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptAttachmentValidatePermission]
    (
        @CompanyKey         int,
        @UserKey            int,
        @AssociatedEntity   varchar(50),
        @EntityKey          int
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/12/26  GRR 26.05.xx   Created — generic permission check for tAttachment inserts.
||                          Dispatches per @AssociatedEntity. Each branch does
||                          its own existence + ownership + state + GL + right
||                          checks and emits a single result row the caller can act on.
||
|| Result row columns:
||   CanAttach     tinyint         1 = attach allowed, 0 = blocked
||   ErrorMessage  nvarchar    NULL on success, reason on failure
||   EntityExists  tinyint         1 if the row was found in this company
||   UserOwns      tinyint         1 if the user is the record''s owner (else they''re using an override right)
||   EntityState   varchar     Human-readable state of the entity (where applicable)
||
|| Adding a new entity:
||   1. Add a new ELSE IF @AssociatedEntity = ''YourEntity'' branch below
||   2. Apply checks: existence + CompanyKey, ownership/override, state, GL, right
||   3. Set @CanAttach=1 + clear @ErrorMessage on success
||   4. Document the entity in mcp-dev skill OPERATIONS.md
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        tinyint
    Declare @RestrictToGLCompany    int

    Declare @CanAttach              tinyint             = 0
    Declare @ErrorMessage           nvarchar(500)   = NULL
    Declare @EntityExists           tinyint             = 0
    Declare @UserOwns               tinyint             = 0
    Declare @EntityState            nvarchar(50)    = NULL

    -- ============================================================================
    -- Load caller''s security context
    -- ============================================================================
    Select  @SecurityGroupKey = SecurityGroupKey,
            @IsAdministrator  = ISNULL(Administrator, 0)
      From  tUser (nolock)
     Where  UserKey = @UserKey
       And  CompanyKey = @CompanyKey

    If @SecurityGroupKey Is Null
    Begin
        Set @ErrorMessage = ''Calling user not found in this company.''
        Goto Done
    End

    Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
      From  tPreference (nolock)
     Where  CompanyKey = @CompanyKey

    -- ============================================================================
    -- Dispatch on entity type
    -- ============================================================================

    If @AssociatedEntity = ''ExpenseReceipt''
    Begin
        Declare @EnvUserKey         int
        Declare @EnvStatus          smallint
        Declare @EnvGLCompanyKey    int

        Select  @EntityExists       = 1,
                @EnvUserKey         = ee.UserKey,
                @EnvStatus          = ee.Status,
                @EnvGLCompanyKey    = p.GLCompanyKey,
                @EntityState        = Case ee.Status
                                          When 1 Then ''Unsubmitted''
                                          When 2 Then ''Submitted''
                                          When 3 Then ''Rejected''
                                          When 4 Then ''Approved''
                                          Else        ''Unknown''
                                      End
          From  tExpenseReceipt  er (nolock)
    Inner Join  tExpenseEnvelope ee (nolock) On ee.ExpenseEnvelopeKey = er.ExpenseEnvelopeKey
    Left outer join tProject p (nolock) On p.ProjectKey = er.ProjectKey
         Where  er.ExpenseReceiptKey = @EntityKey
           And  ee.CompanyKey        = @CompanyKey

        If @EntityExists = 0
        Begin
            Set @ErrorMessage = ''Expense receipt not found in this company.''
            Goto Done
        End

        -- Ownership / override-right check
        If @EnvUserKey = @UserKey
        Begin
            Set @UserOwns = 1
        End
        Else If @IsAdministrator = 0
        Begin
            If Not Exists (
                Select  1
                  From  tRight r (nolock)
            Inner Join  tRightAssigned ra (nolock) On ra.RightKey = r.RightKey
                 Where  ra.EntityType = ''Security Group''
                   And  ra.EntityKey  = @SecurityGroupKey
                   And  r.RightID     = ''billingviewallexpense''
            )
            Begin
                Set @ErrorMessage = ''You do not have permission to modify another user''''s expense receipt.''
                Goto Done
            End

            -- GL company access (only enforced when company preference is set)
            If @RestrictToGLCompany = 1 And @EnvGLCompanyKey Is Not Null
            Begin
                If Not Exists (
                    Select  1
                      From  tUserGLCompanyAccess (nolock)
                     Where  UserKey      = @UserKey
                       And  GLCompanyKey = @EnvGLCompanyKey
                )
                Begin
                    Set @ErrorMessage = ''You do not have GL company access for this expense envelope.''
                    Goto Done
                End
            End
        End

        -- State check: only Unsubmitted (1) or Rejected (3) accept attachments
        If @EnvStatus Not In (1, 3)
        Begin
            Set @ErrorMessage = ''Cannot attach to a receipt whose envelope is '' + ISNULL(@EntityState, ''Unknown'') + ''. Only Unsubmitted or Rejected envelopes accept new attachments.''
            Goto Done
        End

        Set @CanAttach = 1
        Goto Done
    End

    -- ----------------------------------------------------------------------------
    Else If @AssociatedEntity = ''tVoucher'' Or @AssociatedEntity = ''Voucher''
    Begin
        Declare @VoucherCreatedBy   int
        Declare @VoucherStatus      smallint
        Declare @VoucherGLCompany   int
        Declare @VoucherPosted      tinyint
        Declare @VoucherCreditCard  tinyint

        Select  @EntityExists       = 1,
                @VoucherCreatedBy   = CreatedByKey,
                @VoucherStatus      = Status,
                @VoucherGLCompany   = GLCompanyKey,
                @VoucherPosted      = ISNULL(Posted, 0),
                @VoucherCreditCard  = ISNULL(CreditCard, 0),
                @EntityState        = Case Status
                                          When 1 Then ''Draft''
                                          When 2 Then ''Submitted''
                                          When 3 Then ''Rejected''
                                          When 4 Then ''Approved''
                                          Else        ''Unknown''
                                      End
          From  tVoucher (nolock)
         Where  VoucherKey = @EntityKey
           And  CompanyKey = @CompanyKey

        If @EntityExists = 0
        Begin
            Set @ErrorMessage = ''Voucher not found in this company.''
            Goto Done
        End

        -- Voucher edit right is the floor — needed even to touch your own voucher.
        -- (purch_editvoucher = "Add and Edit Vendor Invoices")
        If @IsAdministrator = 0
        Begin
            If Not Exists (
                Select  1
                  From  tRight r (nolock)
            Inner Join  tRightAssigned ra (nolock) On ra.RightKey = r.RightKey
                 Where  ra.EntityType = ''Security Group''
                   And  ra.EntityKey  = @SecurityGroupKey
                   And  r.RightID     = ''purch_editvoucher''
            )
            Begin
                Set @ErrorMessage = ''You do not have permission to edit vouchers (requires purch_editvoucher).''
                Goto Done
            End
        End

        -- Ownership check
        If @VoucherCreatedBy = @UserKey
        Begin
            Set @UserOwns = 1
        End
        -- For non-owners, purch_editvoucher (already verified above) is sufficient
        -- since voucher editing is gated at the right level, not per-record ownership.
        Else
        Begin
            Set @UserOwns = 0
        End

        -- GL company access
        If @IsAdministrator = 0 And @RestrictToGLCompany = 1 And @VoucherGLCompany Is Not Null
        Begin
            If Not Exists (
                Select  1
                  From  tUserGLCompanyAccess (nolock)
                 Where  UserKey      = @UserKey
                   And  GLCompanyKey = @VoucherGLCompany
            )
            Begin
                Set @ErrorMessage = ''You do not have GL company access for this voucher.''
                Goto Done
            End
        End

        -- State check: posted vouchers are audit-frozen, refuse new attachments.
        -- Allowed states: Draft (1), Submitted (2), Rejected (3). Approved/Posted (4) is locked.
        If @VoucherPosted = 1 Or @VoucherStatus = 4
        Begin
            Set @ErrorMessage = ''Cannot attach to a posted voucher.''
            Goto Done
        End

        Set @CanAttach = 1
        Goto Done
    End

    -- ----------------------------------------------------------------------------
    -- Unknown entity
    Else
    Begin
        Set @ErrorMessage = ''Attachments are not supported for entity type '''''' + ISNULL(@AssociatedEntity, ''(null)'') + ''''''. Supported types: ExpenseReceipt, Voucher.''
        Goto Done
    End

    Done:

    Select  ISNULL(@CanAttach, 0)   As CanAttach,
            @ErrorMessage           As ErrorMessage,
            ISNULL(@EntityExists, 0) As EntityExists,
            ISNULL(@UserOwns, 0)    As UserOwns,
            @EntityState            As EntityState
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetScheduleDetails]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetScheduleDetails]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIGetScheduleDetails]
(
    @CompanyKey     int,
    @UserKey        int,
    @ProjectNumber  varchar(300),
    @UserID         varchar(300) = null
)
AS --Encrypt

/*
|| When      Who Rel        What
|| --        --  --         Created - AI schedule details (project + tasks + assignments)
|| 05/25/26  AI  26.05.25   Added #errors standard error logging + spCheckAccess gate (tProject).
||                          Replaces the inline GL company + project-assignment check that returned
||                          empty rows on denial; now returns -103 with an explicit ACCESS_DENIED.
|| 05/28/26  AI  26.05.28   Full rewrite: #errors / warnings + spCheckAccess (tProject). Result-set shape now [warnings, project, tasks, assignments].
|| 06/11/26  GAR 26.07.19   (730680) Assignments result set now includes actHours (sum of tTime.ActualHours per user per task).
|| 06/18/26  GAR 26.07.19   (730520) Adding baseline start and baseline complete to the tasks
|| 07/10/26  GAR 26.07.19   Added gating security - requires right prjviewtasks.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @ProjectKey     int
    declare @FilterUserKey  int = null
    declare @AccessOK       int

    -- ------------------------------------------------------------------
    -- 1. Validate user
    -- ------------------------------------------------------------------
    if not exists (
        select 1 from tUser (nolock)
        where  UserKey = @UserKey and CompanyKey = @CompanyKey
    )
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- Gating security: prjviewtasks
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''prjviewtasks''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (prjviewtasks).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    -- ------------------------------------------------------------------
    -- 2. Resolve project
    -- ------------------------------------------------------------------
    if @ProjectNumber is null or LTRIM(RTRIM(@ProjectNumber)) = ''''
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''projectNumber is required.'', ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -100
    end

    select @ProjectKey = ProjectKey
    from   tProject (nolock)
    where  CompanyKey    = @CompanyKey
      and  ProjectNumber = @ProjectNumber

    if @ProjectKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Project not found for projectNumber: '' + @ProjectNumber, ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Access gate (spCheckAccess: tProject)
    -- ------------------------------------------------------------------
    exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey

    if @AccessOK <> 1
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. Optional @UserID filter (resolve to UserKey)
    -- ------------------------------------------------------------------
    if @UserID is not null and @UserID <> ''''
    begin
        select @FilterUserKey = UserKey
        from   tUser (nolock)
        where  ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
          and  (   UserID like ''%'' + @UserID + ''%''
                or Email + ''|'' + FirstName + '' '' + LastName like ''%'' + @UserID + ''%'' )

        if @FilterUserKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'',
                    ''User not found for userID: '' + @UserID + '' - returning unfiltered schedule.'',
                    ''userID'')
    end

    -- ------------------------------------------------------------------
    -- 5. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from   #errors where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 6. Result set 2: project header
    -- ------------------------------------------------------------------
    select
        p.ProjectNumber  as projectNumber,
        p.ProjectName    as projectName,
        p.Description    as description,
        p.StartDate      as planStart,
        p.CompleteDate   as planComplete,
        c.CustomerID     as clientID,
        c.CompanyName    as clientName
    from   tProject p (nolock)
    inner join tCompany c (nolock) on c.CompanyKey = p.ClientKey
    where  p.ProjectKey = @ProjectKey

    -- ------------------------------------------------------------------
    -- 7. Result set 3: tasks (with predecessors / successors as JSON)
    -- ------------------------------------------------------------------
    select
        t.TaskKey               as taskKey,
        t.TaskID                as taskID,
        t.TaskName              as taskName,
        t.Description           as description,
        t.PlanStart             as planStart,
        t.PlanComplete          as planComplete,
        t.ActStart              as actStart,
        t.ActComplete           as actComplete,
        t.BaseStart             as baseStart,
        t.BaseComplete          as baseComplete,
        t.EstHours              as estHours,
        t.TotalActualHours      as actHours,
        t.PercComp              as percentComplete,
        t.PredecessorsComplete  as predecessorsComplete,
        t.SummaryTaskKey        as parentTaskKey,
        t.ProjectOrder          as displayOrder,
        (
            select pt.TaskID as taskID,
                   pt.TaskName as task,
                   p.Lag  as lagDays,
                   p.Type as lagType
            from   tTaskPredecessor p (nolock)
            inner join tTask pt (nolock) on pt.TaskKey = p.PredecessorKey
            where  p.TaskKey = t.TaskKey
            for json path
        ) as predecessors,
        (
            select st.TaskID as taskID,
                   st.TaskName as task,
                   p.Lag  as lagDays,
                   p.Type as lagType
            from   tTaskPredecessor p (nolock)
            inner join tTask st (nolock) on st.TaskKey = p.PredecessorKey
            where  p.PredecessorKey = t.TaskKey
            for json path
        ) as successors
    from   tTask t (nolock)
    where  t.ProjectKey = @ProjectKey
      and  (@FilterUserKey is null or exists (
                select 1 from tTaskUser tu (nolock)
                where  tu.TaskKey = t.TaskKey and tu.UserKey = @FilterUserKey
            ))
    order by t.ProjectOrder

    -- ------------------------------------------------------------------
    -- 8. Result set 4: task assignments (with actual hours per user per task)
    -- ------------------------------------------------------------------
    ;with cteActuals as (
        select TaskKey, UserKey, SUM(ActualHours) as actHours
        from   tTime (nolock)
        where  ProjectKey = @ProjectKey
        group by TaskKey, UserKey
    )
    select
        t.TaskKey                                 as taskKey,
        s.ServiceCode                             as serviceCode,
        s.Description                             as service,
        u.FirstName                               as firstName,
        u.LastName                                as lastName,
        tu.Hours                                  as allocatedHours,
        ISNULL(a.actHours, 0)                     as actHours,
        ISNULL(tu.APlanStart, t.PlanStart)        as assignmentPlanStart,
        ISNULL(tu.APlanComplete, t.PlanComplete)  as assignmentPlanComplete,
        tu.PercComp                               as assignmentPercentComplete
    from   tTaskUser tu (nolock)
    inner join tTask t (nolock) on t.TaskKey = tu.TaskKey
    left outer join tUser u (nolock) on u.UserKey = tu.UserKey
    left outer join tService s (nolock) on s.ServiceKey = tu.ServiceKey
    left outer join cteActuals a on a.TaskKey = tu.TaskKey and a.UserKey = tu.UserKey
    where  t.ProjectKey = @ProjectKey
      and  (@FilterUserKey is null or tu.UserKey = @FilterUserKey)

    drop table #errors
    return 0



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIgetProjectFiles]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIgetProjectFiles]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIgetProjectFiles]
(
    @CompanyKey     int,
    @UserKey        int,
    @ProjectNumber  varchar(300)
)
AS --Encrypt

/*
|| When      Who Rel        What
|| --        --  --         Created - AI project file browser
|| 05/25/26  AI  26.05.25   Added #errors standard error logging + spCheckAccess gate (tProject).
||                          File-level security (tWebDavSecurity path precedence) is preserved
||                          downstream - spCheckAccess only enforces project-level access.
|| 05/28/26  AI  26.05.28   Full rewrite: #errors / warnings + spCheckAccess (tProject). Preserved webdav file-level security.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right fileAccess.
*/

set nocount on

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @ProjectKey         int
    declare @SecurityGroupKey   int
    declare @IsAdministrator    bit
    declare @SuspendAdmin       bit
    declare @AccessOK           int

    -- ------------------------------------------------------------------
    -- 1. Validate user + load security context
    -- ------------------------------------------------------------------
    select @SecurityGroupKey = SecurityGroupKey,
           @IsAdministrator  = Administrator,
           @SuspendAdmin     = ISNULL(SuspendAdmin, 0)
    from   tUser (nolock)
    where  UserKey    = @UserKey
      and  CompanyKey = @CompanyKey

    if @SecurityGroupKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''User not found or invalid UserKey.'', ''general'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- Gating security: fileAccess
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID     = ''fileAccess''
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (fileAccess).'' as errorMessage, ''general'' as fieldName
        return -103
    end

    if @SuspendAdmin = 1
        set @IsAdministrator = 0

    -- ------------------------------------------------------------------
    -- 2. Resolve project
    -- ------------------------------------------------------------------
    if @ProjectNumber is null or LTRIM(RTRIM(@ProjectNumber)) = ''''
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''projectNumber is required.'', ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -100
    end

    select @ProjectKey = ProjectKey
    from   tProject (nolock)
    where  CompanyKey = @CompanyKey
      and  UPPER(ProjectNumber) = UPPER(@ProjectNumber)

    if @ProjectKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Project not found for projectNumber: '' + @ProjectNumber, ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Project-level access gate (spCheckAccess: tProject)
    -- ------------------------------------------------------------------
    exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey

    if @AccessOK <> 1
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')

        select errorType, errorCode, errorMessage, fieldName
        from   #errors order by errorType desc, fieldName

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. Warnings result set
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from   #errors where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 5. Files - admins see everything in the project
    -- ------------------------------------------------------------------
    if @IsAdministrator = 1
    begin
        select  f.FileName     as fileName,
                f.Path         as path,
                f.LastModified as lastModified,
                f.Description  as description,
                u.UserName     as lastModifiedName,
                @ProjectKey    as projectKey
        from    tWebDavFile f (nolock)
        left join vUserName u (nolock) on f.LastModifiedBy = u.UserKey
        where   f.ProjectKey = @ProjectKey
        order by f.Path, f.LastModified desc, f.FileKey desc

        drop table #errors
        return 0
    end

    -- ------------------------------------------------------------------
    -- 6. Non-admin: file-level path security via tWebDavSecurity precedence
    -- ------------------------------------------------------------------
    declare @ApplicableSecurity table (
        ProjectKey int,
        Path       varchar(500),
        PathUpper  varchar(500),
        ViewFolder bit,
        Precedence int    -- 1 = path-specific, 2 = project-level, 3 = company-wide
    )

    insert into @ApplicableSecurity (ProjectKey, Path, PathUpper, ViewFolder, Precedence)
    select distinct
        s.ProjectKey,
        ISNULL(s.Path, '''')              as Path,
        UPPER(ISNULL(s.Path, ''''))       as PathUpper,
        s.ViewFolder,
        case
            when s.ProjectKey = @ProjectKey and s.Path <> '''' then 1
            when s.ProjectKey = @ProjectKey and s.Path = ''''  then 2
            when s.ProjectKey = 0                            then 3
            else 4
        end                              as Precedence
    from   tWebDavSecurity s (nolock)
    where  s.CompanyKey = @CompanyKey
      and  (s.ProjectKey = 0 or s.ProjectKey = @ProjectKey)
      and  (
                (s.Entity = ''tUser''          and s.EntityKey = @UserKey)
             or (s.Entity = ''tSecurityGroup'' and s.EntityKey = @SecurityGroupKey)
           )

    select  f.FileName     as fileName,
            f.Path         as path,
            f.LastModified as lastModified,
            f.Description  as description,
            u.UserName     as lastModifiedName,
            @ProjectKey    as projectKey
    from    tWebDavFile f (nolock)
    left join vUserName u (nolock) on f.LastModifiedBy = u.UserKey
    where   f.ProjectKey = @ProjectKey
      and   exists (
                select top 1 1
                from   @ApplicableSecurity sec
                where
                    (
                        (sec.Precedence = 1
                            and (   UPPER(ISNULL(f.Path, '''')) = sec.PathUpper
                                 or UPPER(ISNULL(f.Path, '''')) like sec.PathUpper + ''/%''))
                     or (sec.Precedence = 2
                            and not exists (
                                select 1 from @ApplicableSecurity sec2
                                where sec2.Precedence = 1
                                  and (   UPPER(ISNULL(f.Path, '''')) = sec2.PathUpper
                                       or UPPER(ISNULL(f.Path, '''')) like sec2.PathUpper + ''/%'')
                            ))
                     or (sec.Precedence = 3
                            and not exists (
                                select 1 from @ApplicableSecurity sec2
                                where sec2.Precedence in (1, 2)
                                  and (   sec2.Precedence = 2
                                       or (   UPPER(ISNULL(f.Path, '''')) = sec2.PathUpper
                                           or UPPER(ISNULL(f.Path, '''')) like sec2.PathUpper + ''/%''))
                            ))
                    )
                    and sec.ViewFolder = 1
                order by sec.Precedence asc
            )
    order by f.Path, f.LastModified desc, f.FileKey desc

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddTask]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddTask]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIAddTask]
(
	@CompanyKey int,
	@UserKey int,
	@ProjectNumber varchar(100),
	@TaskID nvarchar(30) = null,
	@TaskName nvarchar(500),
	@Description nvarchar(max) = null,
	@ParentTaskID nvarchar(30) = null,
	@InsertBelowTaskID nvarchar(30) = null, -- Optional TaskID to specify where to insert new task under the parent (if not provided, will be added as last child of ParentTaskID)
	@PlanStart smalldatetime = null,
	@PlanComplete smalldatetime = null,
	@PlanDuration int = null,
	@EstHours decimal(24,4) = 0,
	@AssignedTo varchar(max) = null,
	@PredecessorTaskIDs varchar(max) = null,
	@Comments varchar(4000) = null,
	@TrackBudget tinyint = null
)

as --Encrypt

/*
|| When      Who Rel        What
|| 04/01/26  AI  26.05.17   Created - Add/Update tasks via API with assignments and predecessors
|| 04/22/26  CRG 26.05.17   Updated - Add InsertBelowTaskID parameter to specify where to insert new task under the parent
|| 05/18/26  CRG 26.05.17   Fixed the DisplayOrder and ParentTaskKeys so that the TaskID will be set correctly
|| 05/28/26  AI  26.05.28   spCheckAccess (tProject) replaces inline GL company + assignment checks.
|| 06/15/26  GAR 26.06.14   (730907) Fixed an issue with rights - Claude was using prjEdit and schedEdit and there is no such thing - switched to prjedittasks
|| 06/22/26  CRG 26.07.19   Added @TrackBudget parameter; wired into INSERT and UPDATE.
|| 06/22/26  CRG 26.05.19   Added TrackBudget validation and MoneyTask/BudgetTaskKey cascade logic.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right prjedittasks.
*/

	declare @ProjectKey int
	declare @TaskKey int
	declare @ParentTaskKey int
	declare @InsertBelowTaskKey int
	declare @ServiceKey int
	declare @WorkTypeKey int
	declare @TaskExists tinyint
	declare @TaskStatus smallint
	declare @ErrorCount int
	declare @CheckParentKey int
	declare @ResetCheckResult int
	declare @CurrentTaskConstraint int

	-- Create temp table for error/warning messages
	select * into #errors from tAPIErrorTemplate where 1 = 2

	-- Validate required parameters
	if @TaskName is null or LTRIM(RTRIM(@TaskName)) = ''''
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''TaskName is required.'', ''taskName'')
	end

	if @ProjectNumber is null or LTRIM(RTRIM(@ProjectNumber)) = ''''
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''ProjectNumber is required.'', ''projectNumber'')
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- Get the project key for the requested project
	select @ProjectKey = ProjectKey
	from tProject (nolock)
	where CompanyKey = @CompanyKey
	and UPPER(ProjectNumber) = UPPER(@ProjectNumber)

	if @ProjectKey is null
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''NOT_FOUND'', ''Project not found for ProjectNumber: '' + @ProjectNumber, ''projectNumber'')
	end

	-- Security checks: Get user''s security group and administrator status
	declare @SecurityGroupKey int
	declare @IsAdministrator bit
	declare @RestrictToGLCompany tinyint
	declare @CheckAssignment tinyint
	declare @HasScheduleEditRight tinyint
	declare @ProjectGLCompanyKey int

	select @SecurityGroupKey = SecurityGroupKey,
		   @IsAdministrator = Administrator
	from tUser (nolock)
	where UserKey = @UserKey
	and CompanyKey = @CompanyKey

	-- Record-level access gate via spCheckAccess (tProject). Replaces the
	-- inline GL company + assignment checks. spCheckAccess handles admin
	-- bypass and the prjAccessAny / tAssignment fallback.
	if @ProjectKey is not null
	begin
		declare @AccessOK int
		exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey
		if @AccessOK <> 1
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')
	end

	-- Administrators bypass the remaining feature-right checks
	if @IsAdministrator = 0 or @IsAdministrator is null
	begin

		-- Check if user has schedule edit rights
		set @HasScheduleEditRight = 0

		if exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID in (''prjedittasks'')
		)
		begin
			set @HasScheduleEditRight = 1
		end

		if @HasScheduleEditRight = 0
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have permission to edit project schedules.'', ''general'')
		end
	end

	-- Return errors if security checks failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -103
	end

	-- Check if task already exists by TaskID
	set @TaskExists = 0
	if @TaskID is not null and @TaskID <> ''''
	begin
		select @TaskKey = TaskKey
		from tTask (nolock)
		where ProjectKey = @ProjectKey
		and UPPER(TaskID) = UPPER(@TaskID)

		if @TaskKey is not null
			set @TaskExists = 1
	end

	-- Find parent task key if ParentTaskID is provided
	if @ParentTaskID is not null and @ParentTaskID <> ''''
	begin
		select @ParentTaskKey = TaskKey
		from tTask (nolock)
		where ProjectKey = @ProjectKey
		and UPPER(TaskID) = UPPER(@ParentTaskID)

		if @ParentTaskKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''NOT_FOUND'', ''Parent task not found or not a summary task for ParentTaskID: '' + @ParentTaskID, ''parentTaskID'')
		end
	end

	-- Find insert below task key if ParentTaskID is provided
	if @InsertBelowTaskID is not null and @InsertBelowTaskID <> ''''
	begin
		select @InsertBelowTaskKey = TaskKey
		from tTask (nolock)
		where ProjectKey = @ProjectKey
		and UPPER(TaskID) = UPPER(@InsertBelowTaskID)

		if @InsertBelowTaskKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''NOT_FOUND'', ''Insert Below task not found'', ''insertBelowTaskID'')
		end

		if @ParentTaskKey is not null
		begin
			--Make sure the Insert Below Task is a child of the Parent Task
			if not exists(
					select 1
					from tTask (nolock)
					where TaskKey = @InsertBelowTaskKey
					and SummaryTaskKey = @ParentTaskKey)
			begin
				insert into #errors (errorType, errorCode, errorMessage, fieldName)
				values (''warning'', ''PREVIOUS_NOT_VALID'', ''Insert Below task not a child of the ParentTaskID: '' + @ParentTaskID, ''insertBelowTaskID'')

				set @InsertBelowTaskKey = null -- Ignore the Insert Below Task if it''s not a child of the Parent Task
			end
		end
		else
		begin
			--Set the Parent Task to the Summary Task of the Insert Below Task if Parent Task is not provided
			select @ParentTaskKey = SummaryTaskKey
			from tTask (nolock)
			where ProjectKey = @ProjectKey
			and TaskKey = @InsertBelowTaskKey
		end
	end

	-- Return errors if any lookups failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -101
	end

	-- Calculate plan dates if needed
	if @PlanStart is null
		set @PlanStart = GETDATE()

	if @PlanComplete is null
	begin
		if @PlanDuration is not null and @PlanDuration > 0
			set @PlanComplete = DATEADD(DAY, @PlanDuration + ((@PlanDuration + DATEPART(WEEKDAY, @PlanStart) - 1) / 5) * 2, @PlanStart)
		else
			set @PlanComplete = DATEADD(DAY, 1 + ((1 + DATEPART(WEEKDAY, @PlanStart) - 1) / 5) * 2, @PlanStart)
	end
	else
	begin
		if @PlanDuration is null
			set @PlanDuration = dbo.fDateDiffNoWeekend(@PlanStart, @PlanComplete)
	end

	if @PlanDuration is null
		set @PlanDuration = 0

	-- -----------------------------------------------------------------------
	-- TrackBudget validation
	-- -----------------------------------------------------------------------
	if @TrackBudget is not null
	begin
		-- Determine the effective parent key to begin ancestor traversal.
		-- For existing tasks: read the stored SummaryTaskKey (unless caller supplied a new parent).
		-- For new tasks: use @ParentTaskKey directly (null = top-level, no ancestors).
		if @TaskExists = 1
		begin
			select @CheckParentKey = NULLIF(SummaryTaskKey, 0) from tTask (nolock) where TaskKey = @TaskKey
			if @ParentTaskKey is not null
				set @CheckParentKey = @ParentTaskKey
		end
		else
			set @CheckParentKey = @ParentTaskKey

		if @TrackBudget = 1
		begin
			-- Check that no ancestor has TrackBudget = 1
			if @CheckParentKey is not null
			begin
				;with AncestorCTE as (
					select TaskKey, SummaryTaskKey, TrackBudget
					from tTask (nolock) where TaskKey = @CheckParentKey
					union all
					select t.TaskKey, t.SummaryTaskKey, t.TrackBudget
					from tTask t (nolock)
					inner join AncestorCTE a on t.TaskKey = a.SummaryTaskKey
					where a.SummaryTaskKey > 0
				)
				select @ErrorCount = COUNT(*) from AncestorCTE where TrackBudget = 1

				if @ErrorCount > 0
					insert into #errors (errorType, errorCode, errorMessage, fieldName)
					values (''error'', ''TRACK_BUDGET_CONFLICT'', ''TrackBudget cannot be set to 1 because a parent task is already tracking budget and expenses.'', ''trackBudget'')
			end

			-- For an existing task, check that no descendant has TrackBudget = 1.
			-- NOTE: CTE must be immediately followed by a DML statement; result is captured
			-- in @ErrorCount before branching with IF.
			if @TaskExists = 1
			begin
				;with DescendantCTE as (
					select TaskKey from tTask (nolock) where SummaryTaskKey = @TaskKey
					union all
					select t.TaskKey from tTask t (nolock)
					inner join DescendantCTE d on t.SummaryTaskKey = d.TaskKey
				)
				select @ErrorCount = COUNT(*)
				from tTask (nolock) t
				inner join DescendantCTE d on t.TaskKey = d.TaskKey
				where t.TrackBudget = 1

				if @ErrorCount > 0
					insert into #errors (errorType, errorCode, errorMessage, fieldName)
					values (''error'', ''TRACK_BUDGET_CONFLICT'', ''TrackBudget cannot be set to 1 because a child task is already tracking budget and expenses.'', ''trackBudget'')
			end
		end
		else if @TrackBudget = 0 and @TaskExists = 1
		begin
			-- New tasks with TrackBudget = 0 pass through; only existing tasks need the reset check.
			exec @ResetCheckResult = sptTaskCheckResetTrackBudget @TaskKey

			if @ResetCheckResult < 0
				insert into #errors (errorType, errorCode, errorMessage, fieldName)
				values (''error'', ''TRACK_BUDGET_HAS_TRANSACTIONS'', ''TrackBudget cannot be set to 0 because transactions are already tied to this task.'', ''trackBudget'')
			else if @ResetCheckResult > 0
			begin
				-- Even with no transaction block, Duration of Project constraint requires TrackBudget.
				select @CurrentTaskConstraint = TaskConstraint from tTask (nolock) where TaskKey = @TaskKey
				if @CurrentTaskConstraint = 7  -- Enum.ProjectScheduleConstraintTypes.DURATION_OF_PROJECT
					insert into #errors (errorType, errorCode, errorMessage, fieldName)
					values (''error'', ''TASK_CONSTRAINT'', ''TrackBudget cannot be set to 0 because the scheduling constraint requires tracking budget and expenses.'', ''trackBudget'')
			end
		end

		select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
		if @ErrorCount > 0
		begin
			select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
			drop table #errors
			return -104
		end
	end

	-- Insert or Update the task
	if @TaskExists = 0
	begin
		-- Calculate display order for new task
		Update tTask Set TaskType = 1 Where TaskKey = @ParentTaskKey -- Ensure parent is marked as summary task

		declare @DisplayOrder int,
				@ProjectOrder int

		--print ''InsertBelowTaskKey: '' + ISNULL(CAST(@InsertBelowTaskKey as varchar), ''null'')

		if @InsertBelowTaskKey is not null
		begin
			--Get the display order of the task to insert below + 1 and increment
			--display order of all tasks below it
			select	@DisplayOrder = ISNULL(MAX(DisplayOrder), 0) + 1
			from	tTask (nolock)
			where	ProjectKey = @ProjectKey
			and		TaskKey = @InsertBelowTaskKey

			update  tTask
			set		DisplayOrder = DisplayOrder + 1
			where	ProjectKey = @ProjectKey
			and		SummaryTaskKey = @ParentTaskKey
			and		DisplayOrder >= @DisplayOrder
		end
		else
		begin
			select	@DisplayOrder = ISNULL(MAX(DisplayOrder), 0) + 1
			from	tTask (nolock)
			where	ProjectKey = @ProjectKey
			and		SummaryTaskKey = ISNULL(@ParentTaskKey, 0)
		end

		--print ''DisplayOrder: '' + ISNULL(CAST(@DisplayOrder as varchar), ''null'')

		--print ''ParentTaskKey: '' + ISNULL(CAST(@ParentTaskKey as varchar), ''null'')

		if @DisplayOrder = 1 --This will be inserted directly below the parent
			if @ParentTaskKey is not null
				select	@ProjectOrder = ISNULL(ProjectOrder, 0) + 1
				from	tTask (nolock)
				where	TaskKey = @ParentTaskKey
			else
				select	@ProjectOrder = ISNULL(MAX(ProjectOrder), 0) + 1
				from	tTask (nolock)
				where	ProjectKey = @ProjectKey
				and		ISNULL(SummaryTaskKey, 0) = 0
		else
			select	@ProjectOrder = ISNULL(MAX(ProjectOrder), 0) + 1
			from	tTask (nolock)
			where	ProjectKey = @ProjectKey
			and		SummaryTaskKey = ISNULL(@ParentTaskKey, 0)
			and		DisplayOrder = @DisplayOrder - 1

		--print ''ProjectOrder: '' + ISNULL(CAST(@ProjectOrder as varchar), ''null'')

		if isnull(@ProjectOrder, 0) = 0
			set @ProjectOrder = 1

		update	tTask
		set		ProjectOrder = ProjectOrder + 1
		where	ProjectKey = @ProjectKey
		and		ProjectOrder > @ProjectOrder

		-- Insert new task
		insert into tTask
		(
			ProjectKey,
			TaskID,
			TaskName,
			Description,
			TaskType,
			SummaryTaskKey,
			DisplayOrder,
			ProjectOrder,
			ServiceKey,
			WorkTypeKey,
			PlanStart,
			PlanComplete,
			PlanDuration,
			TaskStatus,
			Comments,
			ScheduleTask,
			MoneyTask,
			TaskConstraint,
			TrackBudget,
			DateUpdated
		)
		values
		(
			@ProjectKey,
			@TaskID,
			@TaskName,
			@Description,
			2,
			ISNULL(@ParentTaskKey, 0),
			@DisplayOrder,
			@ProjectOrder,
			@ServiceKey,
			@WorkTypeKey,
			@PlanStart,
			@PlanComplete,
			@PlanDuration,
			@TaskStatus,
			@Comments,
			1,
			1,
			0,
			@TrackBudget,
			GETUTCDATE()
		)

		set @TaskKey = SCOPE_IDENTITY()

		-- Reorder tasks in project
		exec sptTaskOrder @ProjectKey, 0, 0, 0
	end
	else
	begin
		-- Update existing task
		update tTask
		set TaskName = @TaskName,
			Description = ISNULL(@Description, Description),
			SummaryTaskKey = ISNULL(@ParentTaskKey, SummaryTaskKey),
			ServiceKey = ISNULL(@ServiceKey, ServiceKey),
			WorkTypeKey = ISNULL(@WorkTypeKey, WorkTypeKey),
			PlanStart = ISNULL(@PlanStart, PlanStart),
			PlanComplete = ISNULL(@PlanComplete, PlanComplete),
			PlanDuration = ISNULL(@PlanDuration, PlanDuration),
			Comments = ISNULL(@Comments, Comments),
			EstHours = ISNULL(@EstHours, EstHours),
			TrackBudget = ISNULL(@TrackBudget, TrackBudget),
			DateUpdated = GETUTCDATE()
		where TaskKey = @TaskKey
	end

	-- -----------------------------------------------------------------------
	-- TrackBudget cascades (MoneyTask and BudgetTaskKey)
	-- -----------------------------------------------------------------------
	if @TrackBudget = 1
	begin
		-- Set MoneyTask = 1 and BudgetTaskKey = self on the task
		update tTask set MoneyTask = 1, BudgetTaskKey = @TaskKey where TaskKey = @TaskKey

		-- Propagate MoneyTask = 1 up to all ancestors
		;with AncestorCTE as (
			select TaskKey, SummaryTaskKey
			from tTask (nolock)
			where TaskKey = (select NULLIF(SummaryTaskKey, 0) from tTask (nolock) where TaskKey = @TaskKey)
			union all
			select t.TaskKey, t.SummaryTaskKey from tTask t (nolock)
			inner join AncestorCTE a on t.TaskKey = a.SummaryTaskKey
			where a.SummaryTaskKey > 0
		)
		update tTask set MoneyTask = 1 from tTask t inner join AncestorCTE a on t.TaskKey = a.TaskKey

		-- Set BudgetTaskKey = @TaskKey down through all descendants
		;with DescendantCTE as (
			select TaskKey from tTask (nolock) where SummaryTaskKey = @TaskKey
			union all
			select t.TaskKey from tTask t (nolock)
			inner join DescendantCTE d on t.SummaryTaskKey = d.TaskKey
		)
		update tTask set BudgetTaskKey = @TaskKey from tTask t inner join DescendantCTE d on t.TaskKey = d.TaskKey
	end
	else if @TrackBudget = 0 and @TaskExists = 1
	begin
		-- Clear MoneyTask and BudgetTaskKey on the task itself
		update tTask set MoneyTask = 0, BudgetTaskKey = 0 where TaskKey = @TaskKey

		-- Propagate MoneyTask = 0 up to all ancestors
		;with AncestorCTE as (
			select TaskKey, SummaryTaskKey
			from tTask (nolock)
			where TaskKey = (select NULLIF(SummaryTaskKey, 0) from tTask (nolock) where TaskKey = @TaskKey)
			union all
			select t.TaskKey, t.SummaryTaskKey from tTask t (nolock)
			inner join AncestorCTE a on t.TaskKey = a.SummaryTaskKey
			where a.SummaryTaskKey > 0
		)
		update tTask set MoneyTask = 0 from tTask t inner join AncestorCTE a on t.TaskKey = a.TaskKey

		-- Clear BudgetTaskKey down through all descendants
		;with DescendantCTE as (
			select TaskKey from tTask (nolock) where SummaryTaskKey = @TaskKey
			union all
			select t.TaskKey from tTask t (nolock)
			inner join DescendantCTE d on t.SummaryTaskKey = d.TaskKey
		)
		update tTask set BudgetTaskKey = 0 from tTask t inner join DescendantCTE d on t.TaskKey = d.TaskKey
	end

	-- Create temp table to store user keys and service keys
	create table #users (UserKey int, DefaultServiceKey int)

	-- Process assignments if provided
	if @AssignedTo is not null and @AssignedTo <> ''''
	begin
		-- Split comma-separated values and look up users
		declare @UserIdentifier varchar(200)
		declare @Pos int
		declare @AssignedToCopy varchar(max)
		declare @FoundUserKey int
		declare @DefaultServiceKey int

		set @AssignedToCopy = @AssignedTo + '',''
		set @Pos = CHARINDEX('','', @AssignedToCopy)

		while @Pos > 0
		begin
			set @UserIdentifier = LTRIM(RTRIM(SUBSTRING(@AssignedToCopy, 1, @Pos - 1)))
			set @AssignedToCopy = SUBSTRING(@AssignedToCopy, @Pos + 1, LEN(@AssignedToCopy))
			set @Pos = CHARINDEX('','', @AssignedToCopy)

			if @UserIdentifier <> ''''
			begin
				-- Look up user by UserID or Name (partial match) and get DefaultServiceKey
				set @FoundUserKey = null
				set @DefaultServiceKey = null

				select top 1 @FoundUserKey = UserKey,
							 @DefaultServiceKey = DefaultServiceKey
				from tUser (nolock)
				where CompanyKey = @CompanyKey
				and (
					UPPER(UserID) = UPPER(@UserIdentifier)
					or UPPER(FirstName + '' '' + LastName) like ''%'' + UPPER(@UserIdentifier) + ''%''
					or UPPER(LastName + '', '' + FirstName) like ''%'' + UPPER(@UserIdentifier) + ''%''
				)

				if @FoundUserKey is not null
				begin
					insert into #users (UserKey, DefaultServiceKey)
					values (@FoundUserKey, @DefaultServiceKey)
				end
				else
				begin
					-- User not found - add warning
					insert into #errors (errorType, errorCode, errorMessage, fieldName)
					values (''warning'', ''USER_NOT_FOUND'', ''User not found: '' + @UserIdentifier, ''assignedTo'')
				end
			end
		end

		-- Add users to project assignment if not already assigned
		insert into tAssignment (ProjectKey, UserKey, SubscribeDiary, SubscribeToDo, DeliverableReviewer, DeliverableNotify, SubscribeFileUpload)
		select distinct @ProjectKey,
			   u.UserKey, SubscribeDiary, SubscribeToDo, DeliverableReviewer, DeliverableNotify, SubscribeFileUpload
		from #users u
			inner join tUser (nolock) on u.UserKey = tUser.UserKey
		where not exists (
			select 1
			from tAssignment a (nolock)
			where a.ProjectKey = @ProjectKey
			and a.UserKey = u.UserKey
		)

		declare @userCount int
		select	@userCount = count(*)
		from	#users

		-- Users can be duplicated on an assignment, so always insert them
		insert into tTaskUser(TaskKey, UserKey, ServiceKey, Hours)
		select @TaskKey, UserKey, DefaultServiceKey,
				case
					when @userCount > 0 then @EstHours / @userCount
					else 0
				end
		from #users
	end

	-- Process predecessor task IDs if provided
	if @PredecessorTaskIDs is not null and @PredecessorTaskIDs <> ''''
	begin
		-- Create temp table to store predecessor task keys
		create table #predecessors (PredecessorKey int)

		-- Split comma-separated task IDs and look up task keys
		declare @PredTaskID nvarchar(30)
		declare @PredKey int
		set @Pos = null

		declare @PredecessorsCopy varchar(2000)
		set @PredecessorsCopy = @PredecessorTaskIDs + '',''
		set @Pos = CHARINDEX('','', @PredecessorsCopy)

		while @Pos > 0
		begin
			set @PredTaskID = LTRIM(RTRIM(SUBSTRING(@PredecessorsCopy, 1, @Pos - 1)))
			set @PredecessorsCopy = SUBSTRING(@PredecessorsCopy, @Pos + 1, LEN(@PredecessorsCopy))
			set @Pos = CHARINDEX('','', @PredecessorsCopy)

			if @PredTaskID <> ''''
			begin
				-- Look up task key by TaskID in same project
				set @PredKey = null

				select @PredKey = TaskKey
				from tTask (nolock)
				where ProjectKey = @ProjectKey
				and UPPER(TaskID) = UPPER(@PredTaskID)

				if @PredKey is not null
				begin
					insert into #predecessors (PredecessorKey)
					values (@PredKey)
				end
				else
				begin
					-- Predecessor task not found - add warning
					insert into #errors (errorType, errorCode, errorMessage, fieldName)
					values (''warning'', ''TASK_NOT_FOUND'', ''Predecessor task not found: '' + @PredTaskID, ''predecessorTaskIDs'')
				end
			end
		end

		-- Delete existing predecessors for this task (we''ll re-add them)
		delete from tTaskPredecessor
		where TaskKey = @TaskKey

		-- Add predecessors to tTaskPredecessor
		insert into tTaskPredecessor (TaskKey, PredecessorKey, Type, Lag, InWeeks)
		select @TaskKey, p.PredecessorKey, ''FS'', 0, 0
		from #predecessors p
		where not exists (
			select 1
			from tTaskPredecessor tp (nolock)
			where tp.TaskKey = @TaskKey
			and tp.PredecessorKey = p.PredecessorKey
		)

		drop table #predecessors
	end

	declare @AutoTaskID tinyint
	Select @AutoTaskID = ISNULL(AutoIDTask, 1) from tProject Where ProjectKey = @ProjectKey

	exec sptTaskOrder @ProjectKey, 0, 0, 0, @AutoTaskID -- AutoIDTask = 1 to reset TaskIDs based on TaskKey to ensure uniqueness

	-- Check for any errors that should prevent success
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''

	if @ErrorCount > 0
	begin
		-- Return only errors
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		where errorType = ''error''
		order by fieldName

		drop table #errors
		return -102
	end
	else
	begin
		declare	@UserEmail varchar(100),
				@Culture int

		select	@UserEmail = Email,
				@Culture = ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture))
		from	vUserName u
		left join tOffice o (nolock) on u.OfficeKey = o.OfficeKey
		left join tPreference p (nolock) on ISNULL(u.OwnerCompanyKey, u.CompanyKey) = p.CompanyKey
		where	u.UserKey = @UserKey

		-- Return success result with any warnings
		select @TaskKey as taskKey,
			   @TaskID as taskID,
			   @TaskName as taskName,
			   @ProjectKey as projectKey,
			   @ProjectNumber as projectNumber,
			   @UserEmail as userEmail,
			   @Culture as culture,
			   case when @TaskExists = 1 then ''updated'' else ''created'' end as action

		-- Return warnings if any exist
		if exists (select 1 from #errors where errorType = ''warning'')
		begin
			select errorType, errorCode, errorMessage, fieldName
			from #errors
			where errorType = ''warning''
			order by fieldName
		end

		-- Return the users who were assigned
		select	*
		from	#users

		drop table #users
		drop table #errors
		return 1
	end

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddActivity]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddActivity]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spApiAIAddActivity]
(
	@CompanyKey int,
	@UserKey int,
	@ProjectNumber varchar(300) = null,
	@TaskID varchar(300) = null,
	@OpportunityID varchar(300) = null,
	@CompanyName varchar(500) = null,
	@ContactName varchar(500) = null,
	@Subject varchar(1000),
	@Body varchar(max) = null,
	@ActivityDate smalldatetime = null,
	@EmailTo varchar(max) = null,
	@AssignedTo varchar(500) = null
)

as --Encrypt

/*
|| When      Who Rel        What
|| 01/20/25  AI  25.01.20   Created - Add activity via API with email recipients
|| 01/21/25  AI  25.01.21   Updated - Added support for opportunities, companies, contacts; made project optional
|| 07/10/25  AI  25.07.10   Added @AssignedTo parameter to look up assigned user by name, email, or UserID
|| 05/28/26  AI  26.05.28   spCheckAccess (tProject) replaces inline GL company + project assignment checks.
|| 07/10/26  GAR 26.07.19   Added gating security - requires right prjnotes OR useActivities.
*/

	declare @ProjectKey int
	declare @TaskKey int
	declare @LeadKey int
	declare @ClientCompanyKey int
	declare @ContactKey int
	declare @ActivityKey int
	declare @ErrorCount int
	declare @SecurityGroupKey int
	declare @IsAdministrator bit
	declare @RestrictToGLCompany tinyint
	declare @CheckAssignment tinyint
	declare @ProjectGLCompanyKey int
	declare @RootActivityKey int
	declare @ProjectName varchar(500)
	declare @EntityCount int
	declare @Entity varchar(100)
	declare @AssignedUserKey int

    -- ------------------------------------------------------------------
    -- Gating security: prjnotes OR useActivities
    -- ------------------------------------------------------------------
    declare @gsSecurityGroupKey int
    declare @gsIsAdministrator  tinyint

    select @gsSecurityGroupKey = SecurityGroupKey,
           @gsIsAdministrator  = Administrator
    from   tUser (nolock)
    where  UserKey = @UserKey and CompanyKey = @CompanyKey

    if (@gsIsAdministrator = 0 or @gsIsAdministrator is null)
       and not exists (
           select 1
           from   tRight r (nolock)
           inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
           where  ra.EntityType = ''Security Group''
             and  ra.EntityKey  = @gsSecurityGroupKey
             and  r.RightID in (''prjnotes'', ''useActivities'')
       )
    begin
        select ''error'' as errorType, ''ACCESS_DENIED'' as errorCode,
               ''User does not have the required right (prjnotes or useActivities).'' as errorMessage, ''general'' as fieldName
        return -103
    end

	-- Create temp table for error/warning messages
	select * into #errors from tAPIErrorTemplate where 1 = 2


	-- Validate required parameters
	-- Validate that either Subject or Body is provided
	if (@Subject is null or LTRIM(RTRIM(@Subject)) = '''') 
	   and (@Body is null or LTRIM(RTRIM(@Body)) = '''')
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''Either Subject or Body must be provided.'', ''subject'')
	end

	-- If only Body is provided, set Subject to first 40 characters
	if (@Subject is null or LTRIM(RTRIM(@Subject)) = '''') 
	   and @Body is not null and LTRIM(RTRIM(@Body)) <> ''''
	begin
		set @Subject = LEFT(LTRIM(RTRIM(@Body)), 40)
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- Look up project if ProjectNumber is provided
	if @ProjectNumber is not null and LTRIM(RTRIM(@ProjectNumber)) <> ''''
	begin
		select @ProjectKey = ProjectKey, @ProjectName = ProjectName
		from tProject (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(ProjectNumber) = UPPER(@ProjectNumber)

		if @ProjectKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Project not found for ProjectNumber: '' + @ProjectNumber + '' - Activity will be created without project link.'', ''projectNumber'')
		end
	end

	-- Look up opportunity if OpportunityID is provided
	if @OpportunityID is not null and LTRIM(RTRIM(@OpportunityID)) <> ''''
	begin
		select @LeadKey = LeadKey
		from tLead (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadID) = UPPER(@OpportunityID)

		if @LeadKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Opportunity not found for OpportunityID: '' + @OpportunityID + '' - Activity will be created without opportunity link.'', ''opportunityID'')
		end
	end

	-- Look up company if CompanyName is provided
	if @CompanyName is not null and LTRIM(RTRIM(@CompanyName)) <> ''''
	begin
		select @ClientCompanyKey = CompanyKey
		from tCompany (nolock)
		where OwnerCompanyKey = @CompanyKey
		and (UPPER(CompanyName) = UPPER(@CompanyName) or UPPER(CustomerID) = UPPER(@CompanyName))

		if @ClientCompanyKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Company not found for CompanyName: '' + @CompanyName + '' - Activity will be created without company link.'', ''companyName'')
		end
	end

	if @ClientCompanyKey is null and @ProjectKey is not null
		Select @ClientCompanyKey = ClientKey from tProject (nolock) Where ProjectKey = @ProjectKey

	-- Look up contact if ContactName is provided
	if @ContactName is not null and LTRIM(RTRIM(@ContactName)) <> ''''
	begin
		select top 1 @ContactKey = UserKey
		from tUser (nolock)
		where ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
		and (UPPER(FirstName + '' '' + LastName) LIKE ''%'' + UPPER(@ContactName) + ''%''
			or UPPER(Email) = UPPER(@ContactName))

		if @ContactKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Contact not found for ContactName: '' + @ContactName + '' - Activity will be created without contact link.'', ''contactName'')
		end
	end

	-- Validate that at least one entity was found
	set @EntityCount = 0
	if @ProjectKey is not null set @EntityCount = @EntityCount + 1
	if @LeadKey is not null set @EntityCount = @EntityCount + 1
	if @ClientCompanyKey is not null set @EntityCount = @EntityCount + 1
	if @ContactKey is not null set @EntityCount = @EntityCount + 1

	if @EntityCount = 0
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''At least one valid entity (project, opportunity, company, or contact) must be provided.'', ''general'')
	end

	-- Get task key if TaskID is provided (only valid with a project)
	if @TaskID is not null and LTRIM(RTRIM(@TaskID)) <> '''' and @ProjectKey is not null
	begin
		select @TaskKey = TaskKey
		from tTask (nolock)
		where ProjectKey = @ProjectKey
		and UPPER(TaskID) = UPPER(@TaskID)

		if @TaskKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Task not found for TaskID: '' + @TaskID + '' - Activity will be created without task link.'', ''taskID'')
		end
	end

	-- Security checks: Get user''s security group and administrator status
	select @SecurityGroupKey = SecurityGroupKey,
		   @IsAdministrator = Administrator
	from tUser (nolock)
	where UserKey = @UserKey
	and CompanyKey = @CompanyKey

	-- Record-level access gate via spCheckAccess (tProject). Replaces the
	-- inline GL company + assignment checks. spCheckAccess handles admin
	-- bypass and the prjAccessAny / tAssignment fallback.
	if @ProjectKey is not null
	begin
		declare @AccessOK int
		exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tProject'', @ProjectKey
		if @AccessOK <> 1
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project.'', ''projectNumber'')
	end

	if not exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID in (''prjnotes'', ''useActivities'')
		)
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
				values (''error'', ''ACCESS_DENIED'', ''User does not have rights to this feature.'', ''projectNumber'')
		end

	-- Return errors if security checks or validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -103
	end

	-- Create temp table for email recipients
	create table #emailRecipients (
		UserKey int
	)

	if @ContactKey > 0
		insert into #emailRecipients (UserKey) values (@ContactKey)

	-- Parse @EmailTo string if provided
	if @EmailTo is not null and LTRIM(RTRIM(@EmailTo)) <> ''''
	begin
		-- Replace semicolons with commas for uniform splitting
		set @EmailTo = REPLACE(@EmailTo, '';'', '','')

		-- Parse comma-separated values and match to tUser
		declare @RecipientValue varchar(500)
		declare @Position int

		while CHARINDEX('','', @EmailTo) > 0
		begin
			set @Position = CHARINDEX('','', @EmailTo)
			set @RecipientValue = LTRIM(RTRIM(SUBSTRING(@EmailTo, 1, @Position - 1)))
			set @EmailTo = SUBSTRING(@EmailTo, @Position + 1, LEN(@EmailTo))

			if @RecipientValue <> ''''
			begin
				-- Try to match by Email, UserID, or FullName
				insert into #emailRecipients (UserKey)
				select distinct TOP 1 UserKey
				from tUser (nolock)
				where ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
				and Active = 1
				and (
					UPPER(Email) = UPPER(@RecipientValue)
					or UPPER(UserID) = UPPER(@RecipientValue)
					or UPPER(FirstName + '' '' + LastName) LIKE ''%'' + UPPER(@RecipientValue) + ''%''
				)
				and UserKey not in (select UserKey from #emailRecipients where UserKey is not null)
			end
		end

		-- Process the last value (or only value if no commas)
		set @RecipientValue = LTRIM(RTRIM(@EmailTo))
		if @RecipientValue <> ''''
		begin
			insert into #emailRecipients (UserKey)
			select distinct TOP 1 UserKey
			from tUser (nolock)
			where CompanyKey = @CompanyKey
			and Active = 1
			and (
				UPPER(Email) = UPPER(@RecipientValue)
				or UPPER(UserID) = UPPER(@RecipientValue)
				or UPPER(ISNULL(FirstName, '''') + '' '' + ISNULL(LastName, '''')) = UPPER(@RecipientValue)
			)
			and UserKey not in (select UserKey from #emailRecipients where UserKey is not null)
		end
	end
	if @ProjectKey is null
		Select @Entity = ''Activity''
	else
		Select @Entity = ''Diary''

	-- Resolve assigned user: look up by name, email, or UserID if @AssignedTo is provided
	set @AssignedUserKey = @UserKey

	if @AssignedTo is not null and LTRIM(RTRIM(@AssignedTo)) <> ''''
	begin
		select top 1 @AssignedUserKey = UserKey
		from tUser (nolock)
		where CompanyKey = @CompanyKey
		and Active = 1
		and (
			UPPER(FirstName + '' '' + LastName) = UPPER(LTRIM(RTRIM(@AssignedTo)))
			or UPPER(Email) = UPPER(LTRIM(RTRIM(@AssignedTo)))
			or UPPER(UserID) = UPPER(LTRIM(RTRIM(@AssignedTo)))
		)

		if @AssignedUserKey is null
		begin
			set @AssignedUserKey = @UserKey
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Assigned user not found for AssignedTo: '' + @AssignedTo + '' - Activity will be assigned to the requesting user.'', ''assignedTo'')
		end
	end
		

	-- Insert the activity
	insert into tActivity (
		CompanyKey,
		ParentActivityKey,
		RootActivityKey,
		Type,
		Subject,
		ProjectKey,
		TaskKey,
		ContactCompanyKey,
		ContactKey,
		LeadKey,
		AssignedUserKey,
		OriginatorUserKey,
		ActivityDate,
		Notes,
		DateAdded,
		DateUpdated,
		AddedByKey,
		UpdatedByKey,
		GLCompanyKey,
		SendNotification,
		ActivityEntity,
		VisibleToClient,
		UID
	)
	values (
		@CompanyKey,
		0,
		0,
		''Email'',
		@Subject,
		@ProjectKey,
		@TaskKey,
		@ClientCompanyKey,
		@ContactKey,
		@LeadKey,
		@AssignedUserKey,
		@UserKey,
		@ActivityDate,
		@Body,
		getutcdate(),
		getutcdate(),
		@UserKey,
		@UserKey,
		@ProjectGLCompanyKey,
		1,
		@Entity,
		0,
		NEWID()
	)

	set @ActivityKey = SCOPE_IDENTITY()

	-- Set RootActivityKey to itself (common pattern for root activities)
	set @RootActivityKey = @ActivityKey

	update tActivity
	set RootActivityKey = @RootActivityKey
	where ActivityKey = @ActivityKey

	-- Insert email recipients into tActivityEmail
	if exists (select 1 from #emailRecipients where UserKey is not null)
	begin
		insert into tActivityEmail (ActivityKey, UserKey, OriginalUser)
		select @ActivityKey, UserKey, 1
		from #emailRecipients
		where UserKey is not null
	end

	-- Link activity to entities in tActivityLink

	-- Link to project
	if @ProjectKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tProject'', @ProjectKey)
	end

	-- Link to task (if task exists)
	if @TaskKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tTask'', @TaskKey)
	end

	-- Link to opportunity
	if @LeadKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tLead'', @LeadKey)
	end

	-- Link to company
	if @ClientCompanyKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tCompany'', @ClientCompanyKey)
	end

	-- Link to contact
	if @ContactKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tContact'', @ContactKey)
	end

	-- Return success with ActivityKey and any warnings
	select errorType, errorCode, errorMessage, fieldName
	from #errors
	where errorType = ''warning''

	select @ProjectName as projectName,
			@ActivityKey as activityKey,
			@ProjectKey as projectKey,
			@ProjectName as projectName,
			@TaskKey as taskKey,
			@LeadKey as leadKey,
			@ContactKey as contactKey,
		   (select COUNT(*) from #emailRecipients where UserKey is not null) as recipientCount

	drop table #errors
	drop table #emailRecipients
	


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddUpdateOpportunity]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddUpdateOpportunity]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIAddUpdateOpportunity]
(
	@CompanyKey int,
	@UserKey int,
	@OpportunityID varchar(50) = NULL,
	@Subject varchar(200) = NULL,
	@CompanyName varchar(300) = NULL,
	@ContactName varchar(300) = NULL,
	@ProjectType varchar(100) = NULL,
	@Status varchar(50) = NULL,
	@Stage varchar(50) = NULL, 
	@CurrentStatus varchar(300) = NULL,
	@Probability int = 100,
	@SaleAmount decimal(18,2) = 0,
	@StartDate datetime = NULL,
	@EstCloseDate datetime = NULL,
	@Description varchar(max) = NULL
)

as --Encrypt

/*
|| When      Who Rel        What
|| 01/21/25  AI  25.01.21   Created - Add/Update opportunities via API
|| 05/28/26  AI  26.05.28   spCheckAccess (tLead) on update path replaces inline GL company check.
*/

	declare @LeadKey int
	declare @ClientCompanyKey int
	declare @ContactKey int
	declare @ProjectTypeKey int
	declare @LeadStatusKey int
	declare @LeadStageKey int
	declare @ErrorCount int
	declare @SecurityGroupKey int
	declare @IsAdministrator bit
	declare @RestrictToGLCompany tinyint
	declare @GLCompanyKey int
	declare @HasAddRight tinyint
	declare @HasEditRight tinyint
	declare @IsUpdate tinyint
	declare @Action varchar(20)

	-- Variables to hold current values for update
	declare @CurrentSubject varchar(200)
	declare @CurrentClientCompanyKey int
	declare @CurrentContactKey int
	declare @CurrentProjectTypeKey int
	declare @CurrentLeadStatusKey int
	declare @CurrentLeadStageKey int
	declare @CurrentProbability int
	declare @CurrentSaleAmount decimal(18,2)
	declare @CurrentStartDate datetime
	declare @CurrentEstCloseDate datetime
	declare @CurrentDescription varchar(max)
	declare @CurrentCurrentStatus varchar(300)

	-- Create temp table for error/warning messages
	select * into #errors from tAPIErrorTemplate where 1 = 2


	-- Determine if this is an insert or update
	set @IsUpdate = 0
	if @OpportunityID is not null and LTRIM(RTRIM(@OpportunityID)) <> ''''
	begin
		-- Check if opportunity exists
		select @LeadKey = LeadKey,
			   @CurrentSubject = Subject,
			   @CurrentClientCompanyKey = CompanyKey,
			   @CurrentContactKey = ContactKey,
			   @CurrentProjectTypeKey = ProjectTypeKey,
			   @CurrentLeadStatusKey = LeadStatusKey,
			   @CurrentLeadStageKey = LeadStageKey,
			   @CurrentCurrentStatus = CurrentStatus,
			   @CurrentProbability = Probability,
			   @CurrentSaleAmount = SaleAmount,
			   @CurrentStartDate = StartDate,
			   @CurrentEstCloseDate = EstCloseDate,
			   @CurrentDescription = Comments,
			   @GLCompanyKey = GLCompanyKey
		from tLead (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadID) = UPPER(@OpportunityID)

		if @LeadKey is not null
			set @IsUpdate = 1
		else
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''NOT_FOUND'', ''Opportunity not found for OpportunityID: '' + @OpportunityID, ''opportunityID'')
		end
	end

	-- Validate required parameters for insert
	if @IsUpdate = 0
	begin
		if @Subject is null or LTRIM(RTRIM(@Subject)) = ''''
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''REQUIRED_FIELD'', ''Subject is required for new opportunities.'', ''subject'')
		end
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- For update, merge current values with provided values (NULL means keep current)
	if @IsUpdate = 1
	begin
		set @Subject = ISNULL(@Subject, @CurrentSubject)
		set @Probability = ISNULL(@Probability, @CurrentProbability)
		set @SaleAmount = ISNULL(@SaleAmount, @CurrentSaleAmount)
		set @StartDate = ISNULL(@StartDate, @CurrentStartDate)
		set @EstCloseDate = ISNULL(@EstCloseDate, @CurrentEstCloseDate)
		set @Description = ISNULL(@Description, @CurrentDescription)
		set @CurrentStatus = ISNULL(@CurrentStatus, @CurrentCurrentStatus)

		-- For company/contact, only update if explicitly provided
		if @CompanyName is not null
			set @CurrentClientCompanyKey = NULL  -- Force lookup
		if @ContactName is not null
			set @CurrentContactKey = NULL  -- Force lookup
		if @ProjectType is not null
			set @CurrentProjectTypeKey = NULL  -- Force lookup
		-- For status/stage, only update if explicitly provided
		if @Status is null
			set @LeadStatusKey = @CurrentLeadStatusKey
		if @Stage is null
			set @LeadStageKey = @CurrentLeadStageKey
	end

	-- Look up client company if CompanyName is provided
	if @CompanyName is not null and LTRIM(RTRIM(@CompanyName)) <> ''''
	begin
		select @ClientCompanyKey = CompanyKey
		from tCompany (nolock)
		where OwnerCompanyKey = @CompanyKey
		and (UPPER(CompanyName) = UPPER(@CompanyName) or UPPER(CustomerID) = UPPER(@CompanyName))

		if @ClientCompanyKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''NOT_FOUND'', ''Company not found: '' + @CompanyName + '' - A Company is required for an opportunity.'', ''companyName'')
		end
	end
	else if @IsUpdate = 1
	begin
		set @ClientCompanyKey = @CurrentClientCompanyKey
	end

	-- Look up contact if ContactName is provided
	if @ContactName is not null and LTRIM(RTRIM(@ContactName)) <> ''''
	begin
		select top 1 @ContactKey = ContactKey
		from tContact (nolock)
		where OwnerCompanyKey = @CompanyKey
		and (UPPER(FirstName + '' '' + LastName) = UPPER(@ContactName) 
			or UPPER(LastName + '', '' + FirstName) = UPPER(@ContactName)
			or UPPER(Email) = UPPER(@ContactName))
		and (@ClientCompanyKey is null or CompanyKey = @ClientCompanyKey)

		if @ContactKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Contact not found: '' + @ContactName + '' - Opportunity will be created without contact link.'', ''contactName'')
		end
	end
	else if @IsUpdate = 1
	begin
		set @ContactKey = @CurrentContactKey
	end

	-- Look up project type if provided
	if @ProjectType is not null and LTRIM(RTRIM(@ProjectType)) <> ''''
	begin
		select @ProjectTypeKey = ProjectTypeKey
		from tProjectType (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(ProjectTypeName) = UPPER(@ProjectType)

		if @ProjectTypeKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Project Type not found: '' + @ProjectType + '' - Opportunity will be created without project type.'', ''projectType'')
		end
	end
	else if @IsUpdate = 1
	begin
		set @ProjectTypeKey = @CurrentProjectTypeKey
	end

	-- Look up status key if provided
	if @Status is not null and LTRIM(RTRIM(@Status)) <> ''''
	begin
		select @LeadStatusKey = LeadStatusKey
		from tLeadStatus (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadStatusName) = UPPER(@Status)

		if @LeadStatusKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Status not found: '' + @Status + '' - Default status will be used.'', ''status'')
		end
	end
	else
	begin
		select @LeadStatusKey = LeadStatusKey
		from tLeadStatus (nolock)
		where CompanyKey = @CompanyKey and DisplayOrder = 1
	end

	-- Look up stage key if provided
	if @Stage is not null and LTRIM(RTRIM(@Stage)) <> ''''
	begin
		select @LeadStageKey = LeadStageKey
		from tLeadStage (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadStageName) = UPPER(@Stage)

		if @LeadStageKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Stage not found: '' + @Stage + '' - Default stage will be used.'', ''stage'')
		end
	end
	else
	begin
		select @LeadStageKey = LeadStageKey
		from tLeadStage (nolock)
		where CompanyKey = @CompanyKey and DisplayOrder = 1
	end

	-- Get user''s security group and administrator status
	select @SecurityGroupKey = SecurityGroupKey,
		   @IsAdministrator = Administrator,
		   @GLCompanyKey = CASE WHEN @IsUpdate = 0 THEN GLCompanyKey ELSE @GLCompanyKey END
	from tUser (nolock)
	where UserKey = @UserKey
	and CompanyKey = @CompanyKey

	-- Administrators bypass all security checks
	if @IsAdministrator = 0 or @IsAdministrator is null
	begin
		-- Check if user has rights to add or edit opportunities
		set @HasAddRight = 0
		set @HasEditRight = 0

		if exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID = ''addOpp''
		)
		begin
			set @HasAddRight = 1
		end

		if exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID = ''useOpp''
		)
		begin
			set @HasEditRight = 1
		end

		if @IsUpdate = 0 and @HasAddRight = 0
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have permission to add opportunities.'', ''general'')
		end

		if @IsUpdate = 1 and @HasEditRight = 0
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have permission to edit opportunities.'', ''general'')
		end

		-- Record-level access gate for updates via spCheckAccess (tLead) —
		-- opportunities live in tLead. Replaces the inline GL company check.
		if @IsUpdate = 1 and @LeadKey is not null
		begin
			declare @AccessOK int
			exec @AccessOK = spCheckAccess @UserKey, @CompanyKey, ''tLead'', @LeadKey
			if @AccessOK <> 1
				insert into #errors (errorType, errorCode, errorMessage, fieldName)
				values (''error'', ''ACCESS_DENIED'', ''User does not have access to this opportunity.'', ''opportunityID'')
		end
	end

	-- Return errors if security checks failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -103
	end

	-- Insert or Update
	if @IsUpdate = 0
	begin
		-- Insert new opportunity
		insert into tLead (
			CompanyKey,
			ContactCompanyKey,
			ContactKey,
			ProjectTypeKey,
			LeadStatusKey,
			LeadStageKey,
			Subject,
			CurrentStatus,
			Probability,
			SaleAmount,
			StartDate,
			EstCloseDate,
			Comments,
			AccountManagerKey,
			GLCompanyKey,
			AddedByKey,
			UpdatedByKey,
			DateAdded,
			DateUpdated
		)
		values (
			@CompanyKey,
			@ClientCompanyKey,
			@ContactKey,
			@ProjectTypeKey,
			@LeadStatusKey,
			@LeadStageKey,
			@Subject,
			@CurrentStatus,
			@Probability,
			@SaleAmount,
			@StartDate,
			@EstCloseDate,
			@Description,
			@UserKey,
			@GLCompanyKey,
			@UserKey,
			@UserKey,
			dbo.fFormatDateNoTime(getutcdate()),
			dbo.fFormatDateNoTime(getutcdate())
		)

		set @LeadKey = SCOPE_IDENTITY()

		-- Generate OpportunityID 
		Select @OpportunityID = ISNULL(Max(LeadID), 0) + 1 from tLead (nolock) 
		Where CompanyKey = @CompanyKey

		update tLead
		set LeadID = @OpportunityID
		where LeadKey = @LeadKey

		set @Action = ''created''
	end
	else
	begin
		-- Update existing opportunity
		update tLead
		set CompanyKey = @ClientCompanyKey,
			ContactKey = @ContactKey,
			ProjectTypeKey = @ProjectTypeKey,
			LeadStatusKey = @LeadStatusKey,
			LeadStageKey = @LeadStageKey,
			Subject = @Subject,
			CurrentStatus = @CurrentStatus,
			Probability = @Probability,
			SaleAmount = @SaleAmount,
			StartDate = @StartDate,
			EstCloseDate = @EstCloseDate,
			Comments = @Description,
			DateUpdated = dbo.fFormatDateNoTime(getutcdate()),
			UpdatedByKey = @UserKey
		where LeadKey = @LeadKey

		-- Track stage change history if stage has changed
		if @CurrentLeadStageKey is not null 
			and @LeadStageKey is not null 
			and @CurrentLeadStageKey <> @LeadStageKey
		begin
			insert into tLeadStageHistory (
				LeadKey,
				LeadStageKey,
				HistoryDate,
				Comment,
				Probability,
				SaleAmount,
				EstCloseDate
			)
			values (
				@LeadKey,
				@LeadStageKey,
				dbo.fFormatDateNoTime(getutcdate()),
				@CurrentStatus,
				@Probability,
				@SaleAmount,
				@EstCloseDate
			)
		end

		set @Action = ''updated''
	end

	-- Return success with OpportunityID and any warnings
	select errorType, errorCode, errorMessage, fieldName
	from #errors
	where errorType = ''warning''

	select @OpportunityID as opportunityID,
		   @Subject as subject,
		   @Action as action

	drop table #errors
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesCreateCampaignInvoiceMassBilling]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCreateCampaignInvoiceMassBilling]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spFixedFeesCreateCampaignInvoiceMassBilling]
(
	@CampaignKey int
	,@CompanyKey int
	,@UserKey int
	,@PercentBudget decimal(24,4) -- if 40 %, or = 40 , Bill Amount = (Budget Amount * 40.00) / 100.00 
	,@InvoiceAmount money   -- this a % of the budget amount 
	,@EndDate smalldatetime -- End Date for extra expenses
	,@InvoiceDate smalldatetime
	,@PostingDate smalldatetime
	,@CreateAsApproved int
	,@DefaultClassKey int
	,@BillingScheduleKey int
	,@AdvanceBilling int = 0
	,@BillAs int = 0 -- 0 % of Remaining, 1 % of Total

	-- for extra expenses
	,@OpenOrdersOnly int = 1
	,@Expense tinyint = 1-- Misc Costs, VDs and expenses on Credit Card Charges 
	,@ExpenseReport tinyint = 1 -- Expenses Reports/Receipts only 
	,@PO tinyint = 1
	,@IO tinyint = 1
	,@IOBeginDate datetime = null
	,@IOEndDate datetime = null
	,@BC tinyint = 1
	,@BCBeginDate datetime = null
	,@BCEndDate datetime = null

	,@InvoiceBy varchar(20) = ''Item/Service'' -- OneLine, Segment, Item/Service
	,@AddTopLine tinyint = 0 
	)
as --Encrypt

SET NOCOUNT ON

	/*
    || When     Who Rel    What
    || 10/08/20 GHL 20.110 (529464) Creation for wjapp campaign FF mass billing
	||                     Clone of spFixedFeesCreateProjectInvoiceMassBilling
	|| 10/21/20 GHL 20.110 (533381) when calling spFixedFeesCreateInvoice, do not update the billing schedule, it will be done here
	|| 04/16/21 GHL 21.05.16 (555337) Setting now CampaignKey in tActionLog
	|| 04/26/21 GHL 21.05.16 (556225) When reading tCampaignEstByItem, summarize by campaign because the table has a row per camp, segment, item 
	|| 05/27/21 GHL 21.06.20 (560012) Added the ability of a top line for the campaign, this allow users to enter by service/items for taxes
    ||                       and rollup to top line 
	|| 06/09/21 GHL 21.06.20 (560163) Make sure that we update the billing schedule when creating the invoice
	|| 09/15/21 GHL 21.10.70 (568295) Setting now InvoiceDate and PostingDate
	|| 07/27/23 MCM 23.08.xx (647251) Setting the Due Date based on client payment terms
	|| 07/28/23 MCM 23.08.xx (647370) Fixed issue where there was bad ELSE which caused the CreateAsApproved logic to be skippe.
	|| 05/30/24 MCM 24.07.xx (651173) Added OfficeKey so it''s passed to the invoice creation
	|| 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
	|| 07/08/26 MFT 26.08.01 (729267) Added BillExpensesByItem (Fixed Fee expenses billed one line per Item)
	|| 07/14/26 AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
	|| 07/28/26 MFT 26.08.01 (729267) BillExpensesByItem: added a "Expenses" summary line
	*/

	/*
	No support for InvoiceBy = Project because in that situation, the budget comes from the projects not the campaign
	and the choice of the line type would need to be done first, before creating the invoices

	One invoice per campaign only (not per client)

	support for tCampaign.ExpensesNotIncluded

	must have 
	tCampaign.BillBy = 2 (bill by campaign)
	tCampaign.UseCampaignBudget = 1
	*/

	declare @NewInvoiceKey int
	declare @NewInvoiceLineKey int
	declare @NextTranNo varchar(100)
	declare @InvoiceStatus int
	declare @ApprovedByKey int
	declare @RetVal int
	declare @OfficeKey int
	declare @BudgetAmount money
	declare @PercentBudgetHiPrecision decimal(24,8) -- when we need more that 4 decimal points
	declare @ExpensesNotIncluded int
	declare @BillExpensesByItem int
	declare @AdvBillAccountKey int
	declare @DefaultSalesAccountKey int
	declare @PostSalesUsingDetail int
	declare @SalesAccountKey int
	declare @RoundingError money
	declare @SetTaxableOnInvoice int
	declare @ProjectKey int
	declare @EntityName	VARCHAR(500)
	declare @LineOrder int
	declare @ClientKey int
	declare @DueDate smalldatetime
	declare @PaymentTermsKey int
	declare @DefaultPaymentTerms int
	declare @TodaysDate smalldatetime
	declare @DueDays int
	declare @CurItemKey int
	declare @CurEntityKey int
	declare @CurItemName VARCHAR(250)
	declare @CurAmount money
	declare @CurTaxable tinyint
	declare @CurTaxable2 tinyint
	declare @CurLineOrder int

	if isnull(@InvoiceBy, '''') = ''''
		select @InvoiceBy = ''Item/Service''

	-- get company preferences
	Select @PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
			,@DefaultSalesAccountKey = DefaultSalesAccountKey
			,@AdvBillAccountKey = AdvBillAccountKey
			,@SetTaxableOnInvoice = isnull(SetTaxableOnInvoice, 0)
			,@DefaultPaymentTerms = isnull(PaymentTermsKey, 0)
	From tPreference (nolock)
	Where CompanyKey = @CompanyKey

	if @AdvanceBilling = 1 and isnull(@AdvBillAccountKey, 0) = 0
		return -2

	if @AdvanceBilling = 1
		select @SalesAccountKey = @AdvBillAccountKey
	else
		select @SalesAccountKey = @DefaultSalesAccountKey

	select @PercentBudgetHiPrecision = @PercentBudget

	-- @ExpensesNotIncluded is an important flag, if expenses are not included
	-- the FF invoice lines will be flagged as Labor so that we can compare correctly to the labor budget
	select @ExpensesNotIncluded = isnull(ExpensesNotIncluded, 0)
			, @ClientKey = ClientKey
			, @OfficeKey = OfficeKey
			, @BillExpensesByItem = isnull(BillExpensesByItem, 0)
	from tCampaign (nolock) where CampaignKey = @CampaignKey

	select @PaymentTermsKey = ISNULL(PaymentTermsKey, @DefaultPaymentTerms)
		from tCompany c (nolock) 
		where c.CompanyKey = @ClientKey

	-- Variables for logging 
	declare	@Entity varchar(50),
		@EntityKey int,
		@Action varchar(200),
		@ActionDate smalldatetime,
		@ActionBy varchar(500),
		@Comments varchar(4000),
		@Reference varchar(200),
		@SourceCompanyID varchar(100)


	CREATE TABLE #line ( 	Entity			    VARCHAR(50) NULL, 
			EntityKey			INT NULL, 
			EntityName			VARCHAR(250) NULL, 
			EntityDescription	TEXT NULL, 
			BillAmt             MONEY NULL, 
			LineOrder           INT NULL, 
			EntityAccountKey	INT NULL, 
			EntityDepartmentKey	INT NULL, 
			EntityClassKey	    INT NULL, 
			Taxable             INT NULL, 
			Taxable2            INT NULL, 
			InvoiceLineKey      INT NULL, 
			Selected            INT NULL, 
			LineKey             INT NULL, 
			ParentLineKey		INT NULL, 
			ProjectKey   		INT NULL, 
			LineType   	        INT NULL, 
			GPFlag              INT NULL,
			
			DisplayOrder        INT identity(1,1), -- we need to make sure that it is unique
			BudgetAmount        MONEY NULL,
			BilledAmount        MONEY NULL,
			RemainingAmount     MONEY NULL 
			 )

/* 
* By Item/Service *****************************************************************************************
*/
if @InvoiceBy = ''Item/Service''
begin 
	if @BillAs = 1
	begin
		-- Bill as % Total
		-- we do not need to know the Billed Amount

		if @ExpensesNotIncluded = 0
			insert #line (Entity, EntityKey, BudgetAmount, Selected)
			select Entity, EntityKey, sum(isnull(Gross, 0) + isnull(COGross, 0)), 1
			from   tCampaignEstByItem (nolock)
			where  CampaignKey = @CampaignKey
			group by Entity, EntityKey
		else
			insert #line (Entity, EntityKey, BudgetAmount, Selected)
			select Entity, EntityKey, sum(isnull(Gross, 0) + isnull(COGross, 0)), 1
			from   tCampaignEstByItem (nolock)
			where  CampaignKey = @CampaignKey
			and    Entity = ''tService''
			group by Entity, EntityKey

		-- patch for the UI not calculating % budget
		if @InvoiceBy = ''Item/Service''
		begin
			if @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			begin
				select @BudgetAmount = sum(BudgetAmount) from #line

				if isnull(@BudgetAmount,0) = 0
					select @InvoiceBy = ''OneLine''
				else
					select @PercentBudgetHiPrecision =  (@InvoiceAmount * 100.00 ) / @BudgetAmount
			end
		end

		-- if we still have a problem calculating the % budget, use a single line on the invoice
		if @InvoiceBy = ''Item/Service'' and @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			select @InvoiceBy = ''OneLine''
	 
		if @InvoiceBy = ''Item/Service''
		begin
			-- we need to establish a line order
			update #line
			set    #line.EntityName = s.Description
			from   tService s (nolock)
			where  #line.Entity = ''tService''
			and    #line.EntityKey = s.ServiceKey

			update #line
			set    #line.EntityName = i.ItemName
			from   tItem i (nolock)
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = i.ItemKey

			update #line
			set    #line.EntityName = ''[No Service]''
			where  #line.Entity = ''tService''
			and    #line.EntityKey = 0

			update #line
			set    #line.EntityName = ''[No Item]''
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = 0

			select @LineOrder = 1
			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tService''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tService''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tItem''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tItem''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			-- and calculate the BillAmount on each line
			update #line
			set    #line.BillAmt = round((isnull(BudgetAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)

			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- InvoiceBy = Item/Service

	end -- BillAs = 1 -- Bill as % Total
	--select * from #line
	--select @InvoiceBy, @InvoiceAmount
	--return  1

	if @BillAs = 0
	begin	
		-- Bill as % Remaining
		-- we need to know the Billed Amount

		-- Here, this is more complicated because BilledAmount could be for a single invoice line without service
		-- Or we could have Billed amount and no budget amount
		-- we cannot rely only on tProjectEstByItem
		if @ExpensesNotIncluded = 0 -- Expenses are included
		begin
			insert #line (Entity, EntityKey, BudgetAmount, BilledAmount,Selected)
			-- Services
			SELECT ''tService'', s.ServiceKey
			,ISNULL((SELECT sum(pe.Gross)  
						FROM tCampaignEstByItem pe (NOLOCK) 
						Where pe.CampaignKey = @CampaignKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''
						), 0) 

			+ ISNULL((SELECT SUM(pe.COGross)  
						FROM tCampaignEstByItem pe (NOLOCK) 
						Where pe.CampaignKey = @CampaignKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE inv.CampaignKey = @CampaignKey
						AND   isum.Entity = ''tService''
						AND   ISNULL(isum.EntityKey, 0) = s.ServiceKey
						AND   inv.AdvanceBill = 0), 0)
			, 1
			FROM		
				(
				select ServiceKey
				from tService (nolock)
				where CompanyKey = @CompanyKey
				UNION
				select	0 AS ServiceKey
				) AS s    
    
			-- items
			insert #line (Entity, EntityKey, BudgetAmount, BilledAmount,Selected)
			SELECT ''tItem'', i.ItemKey
			,ISNULL((SELECT sum(pe.Gross)  
						FROM tCampaignEstByItem pe (NOLOCK) 
						Where pe.CampaignKey = @CampaignKey   
						AND ISNULL(pe.EntityKey, 0) = i.ItemKey
						AND pe.Entity = ''tItem''  
						), 0) 

			+ ISNULL((SELECT sum(pe.COGross)  
						FROM tCampaignEstByItem pe (NOLOCK) 
						Where pe.CampaignKey = @CampaignKey   
						AND ISNULL(pe.EntityKey, 0) = i.ItemKey
						AND pe.Entity = ''tItem''  
						), 0) 

			-- this should work because if expenses are included, there should not be extra expenses
			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						WHERE inv.CampaignKey = @CampaignKey
						AND   ISNULL(isum.Entity, '''') IN ('''',''tItem'')
						AND   ISNULL(isum.EntityKey, 0) = i.ItemKey
						AND   inv.AdvanceBill = 0), 0)
			, 1
			FROM		
				(
				select ItemKey
				from tItem (nolock)
				where CompanyKey = @CompanyKey
				UNION
				select	0 AS ItemKey
				) AS i    
	
		end
		else
		begin
			-- Expenses are not included
			-- Take labor budget only
			-- Take labor FF billed only

			INSERT #line (Entity, EntityKey, BudgetAmount, BilledAmount, Selected)

			-- Services
			SELECT ''tService'', s.ServiceKey
			,ISNULL((SELECT sum(pe.Gross)  
						FROM tCampaignEstByItem pe (NOLOCK) 
						Where pe.CampaignKey = @CampaignKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			+ ISNULL((SELECT sum(pe.COGross)  
						FROM tCampaignEstByItem pe (NOLOCK) 
						Where pe.CampaignKey = @CampaignKey   
						AND ISNULL(pe.EntityKey, 0) = s.ServiceKey
						AND pe.Entity = ''tService''  
						), 0) 

			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
						WHERE inv.CampaignKey = @CampaignKey
						AND   il.BillFrom = 1 -- Fixed Fee
						AND   isum.Entity = ''tService''
						AND   ISNULL(isum.EntityKey, 0) = s.ServiceKey
						AND   inv.AdvanceBill = 0), 0)
			,1
			FROM		
				(
				select ServiceKey
				from tService (nolock)
				where CompanyKey = @CompanyKey
				UNION
				select	0 AS ServiceKey
				) AS s    
    
		end

		update #line 
		set    RemainingAmount = isnull(BudgetAmount, 0) - isnull(BilledAmount, 0) 

		-- at this time, I accept negative numbers
		-- because users could bill by item/service then by 1 line, creating situations where budget - billed <0
		delete #line where RemainingAmount = 0 

		if exists (select 1 from #line) 
			select @InvoiceBy = ''Item/Service''
		else
			select @InvoiceBy = ''OneLine''

		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''

		if @InvoiceBy = ''Item/Service''
		begin
			-- we need to establish a line order
			update #line
			set    #line.EntityName = s.Description
			from   tService s (nolock)
			where  #line.Entity = ''tService''
			and    #line.EntityKey = s.ServiceKey

			update #line
			set    #line.EntityName = i.ItemName
			from   tItem i (nolock)
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = i.ItemKey

			update #line
			set    #line.EntityName = ''[No Service]''
			where  #line.Entity = ''tService''
			and    #line.EntityKey = 0

			update #line
			set    #line.EntityName = ''[No Item]''
			where  #line.Entity = ''tItem''
			and    #line.EntityKey = 0

			select @LineOrder = 1
			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tService''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tService''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			select @EntityName = ''''
			while (1=1)
			begin
				select @EntityName = min(EntityName)
				from   #line
				where  Entity = ''tItem''
				and    EntityName > @EntityName

				if @EntityName is null
					break

				update #line
				set    #line.LineOrder = @LineOrder
				where  Entity = ''tItem''
				and    EntityName = @EntityName

				select @LineOrder = @LineOrder + 1
			end

			-- and calculate the BillAmount on each line
			if @PercentBudgetHiPrecision <> 100
				update #line
				set    #line.BillAmt = round((isnull(RemainingAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)
			else
				update #line
				set    #line.BillAmt = round(isnull(RemainingAmount, 0), 2)
			
			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			--select * from #line

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- InvoiceBy = Item/Service

	end -- BillAs = 0 -- Bill as % Remaining

end -- End ''Item/Service''

--select * from #line
--select sum(BillAmt) from #line where BillAmt > 0 
--return

/* 
* By Segment *********************************************************************************************
*/

if @InvoiceBy = ''Segment''
begin 
	if @BillAs = 1
	begin
		-- Bill as % Total
		-- we do not need to know the Billed Amount

		-- the budget comes from estimates by campaign segment/service
		-- so group by segment, the next stored proc will do the expansion by item

		if @ExpensesNotIncluded = 0
			insert #line (Entity, EntityKey, EntityName, BudgetAmount, Selected)
			select ''tCampaignSegment'', cebi.CampaignSegmentKey, cs.SegmentName,sum(isnull(cebi.Gross, 0) + isnull(cebi.COGross, 0)), 1
			from   tCampaignEstByItem  cebi (nolock)
				inner join tCampaignSegment cs (nolock) on cebi.CampaignSegmentKey = cs.CampaignSegmentKey
			where  cebi.CampaignKey = @CampaignKey
			group by cebi.CampaignSegmentKey, cs.DisplayOrder, cs.SegmentName
			order by cs.DisplayOrder
		else
			insert #line (Entity, EntityKey, EntityName, BudgetAmount, Selected)
			select ''tCampaignSegment'', cebi.CampaignSegmentKey, cs.SegmentName, sum(isnull(cebi.Gross, 0) + isnull(cebi.COGross, 0)), 1
			from   tCampaignEstByItem  cebi (nolock)
				inner join tCampaignSegment cs (nolock) on cebi.CampaignSegmentKey = cs.CampaignSegmentKey
			where  cebi.CampaignKey = @CampaignKey
			and    cebi.Entity = ''tService''
			group by cebi.CampaignSegmentKey, cs.DisplayOrder, cs.SegmentName
			order by cs.DisplayOrder

		if exists (select 1 from #line) 
			select @InvoiceBy = ''Segment''
		else
			select @InvoiceBy = ''OneLine''

		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''

		-- patch for the UI not calculating % budget
		if @InvoiceBy = ''Segment''
		begin
			-- we need to establish a line order
			-- some display orders start at 0, others start at 1, since it is an identity it should be unique now and start at 1
			update #line
			set    LineOrder = DisplayOrder

			if @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			begin
				select @BudgetAmount = sum(BudgetAmount) from #line

				if isnull(@BudgetAmount,0) = 0
					select @InvoiceBy = ''OneLine''
				else
					select @PercentBudgetHiPrecision =  (@InvoiceAmount * 100.00 ) / @BudgetAmount
			end
		end

		-- if we still have a problem calculating the % budget, use a single line on the invoice
		if @InvoiceBy = ''Segment'' and @PercentBudgetHiPrecision = 0 and @InvoiceAmount != 0
			select @InvoiceBy = ''OneLine''
	 
		if @InvoiceBy = ''Segment''
		begin
			-- and calculate the BillAmount on each line
			update #line
			set    #line.BillAmt = round((isnull(BudgetAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)

			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- InvoiceBy = Item/Service

	end -- BillAs = 1 -- Bill as % Total

	--select * from #line
	--select @InvoiceBy, @InvoiceAmount
	--return  1

	if @BillAs = 0
	begin	
		-- Bill as % Remaining
		-- we need to know the Billed Amount

		-- Here, this is more complicated because BilledAmount could be for a single invoice line without segment
		-- Or we could have Billed amount and no budget amount
		-- we cannot rely only on tCampaignEstByItem
		if @ExpensesNotIncluded = 0 -- Expenses are included
		begin
			insert #line (Entity, EntityKey, EntityName, BudgetAmount, BilledAmount,Selected)
			SELECT ''tCampaignSegment'', s.CampaignSegmentKey, s.SegmentName
			,ISNULL((SELECT sum(cebi.Gross)  
						FROM tCampaignEstByItem cebi (NOLOCK) 
						Where cebi.CampaignKey = @CampaignKey   
						AND ISNULL(cebi.CampaignSegmentKey, 0) = s.CampaignSegmentKey
						), 0) 

			+ ISNULL((SELECT sum(cebi.COGross)  
						FROM tCampaignEstByItem cebi (NOLOCK) 
						Where cebi.CampaignKey = @CampaignKey   
						AND ISNULL(cebi.CampaignSegmentKey, 0) = s.CampaignSegmentKey
						), 0) 

			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
						WHERE inv.CampaignKey = @CampaignKey
						AND   il.CampaignSegmentKey = s.CampaignSegmentKey
						AND   inv.AdvanceBill = 0), 0)
			, 1
			FROM		
				(
				select CampaignSegmentKey, DisplayOrder, SegmentName
				from tCampaignSegment (nolock)
				where CampaignKey = @CampaignKey
				
				-- do we allow for a 0 segment?
				--UNION
				--select	0 AS ServiceKey
				) AS s    
    
			order by s.DisplayOrder

		end
		else
		begin
			-- Expenses are not included
			-- Take labor budget only
			-- Take labor FF billed only

			insert #line (Entity, EntityKey, EntityName, BudgetAmount, BilledAmount,Selected)
			SELECT ''tCampaignSegment'', s.CampaignSegmentKey , s.SegmentName
			,ISNULL((SELECT sum(cebi.Gross)  
						FROM tCampaignEstByItem cebi (NOLOCK) 
						Where cebi.CampaignKey = @CampaignKey   
						AND ISNULL(cebi.CampaignSegmentKey, 0) = s.CampaignSegmentKey
						AND cebi.Entity = ''tService''  -- labor
						), 0) 

			+ ISNULL((SELECT sum(cebi.COGross)  
						FROM tCampaignEstByItem cebi (NOLOCK) 
						Where cebi.CampaignKey = @CampaignKey   
						AND ISNULL(cebi.CampaignSegmentKey, 0) = s.CampaignSegmentKey
						AND cebi.Entity = ''tService''  -- labor
						), 0) 

			,ISNULL((SELECT Sum(isum.Amount) 
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice inv (NOLOCK) on isum.InvoiceKey = inv.InvoiceKey
						inner join tInvoiceLine il (NOLOCK) on isum.InvoiceLineKey = il.InvoiceLineKey
						WHERE inv.CampaignKey = @CampaignKey
						AND   il.CampaignSegmentKey = s.CampaignSegmentKey
						AND   inv.AdvanceBill = 0
						AND   il.BillFrom = 1 -- Fixed Fee
						AND   isum.Entity = ''tService''
						), 0)
			, 1
			FROM		
				(
				select CampaignSegmentKey, DisplayOrder, SegmentName
				from tCampaignSegment (nolock)
				where CampaignKey = @CampaignKey
				
				-- do we allow for a 0 segment?
				--UNION
				--select	0 AS ServiceKey
				) AS s    
    
			order by s.DisplayOrder

		end

		update #line 
		set    RemainingAmount = isnull(BudgetAmount, 0) - isnull(BilledAmount, 0) 

		-- at this time, I accept negative numbers
		-- because users could bill by item/service then by 1 line, creating situations where budget - billed <0
		delete #line where RemainingAmount = 0 

		if exists (select 1 from #line) 
			select @InvoiceBy = ''Segment''
		else
			select @InvoiceBy = ''OneLine''

		if @InvoiceAmount = 0
			select @InvoiceBy = ''OneLine''

		if @InvoiceBy = ''Segment''
		begin
			-- some display orders start at 0, others start at 1, since it is an identity it should be unique now and start at 1
			update #line
			set    LineOrder = DisplayOrder

			-- and calculate the BillAmount on each line
			if @PercentBudgetHiPrecision <> 100
				update #line
				set    #line.BillAmt = round((isnull(RemainingAmount, 0) * @PercentBudgetHiPrecision) / 100.00, 2)
			else
				update #line
				set    #line.BillAmt = round(isnull(RemainingAmount, 0), 2)
			
			-- recalc InvoiceAmount because of rounding errors
			select @RoundingError = sum(BillAmt) from #line
			select @RoundingError = isnull(@InvoiceAmount,0) - isnull(@RoundingError, 0)

			if @RoundingError <> 0
				update #line
				set    BillAmt = isnull(BillAmt,0) + isnull(@RoundingError, 0)
				where  LineOrder = 1 -- first line

		end -- InvoiceBy = Item/Service

	end -- BillAs = 0 -- Bill as % Remaining

end -- End ''Segment''


--select * from #line
--select sum(BilledAmount) from #line
--return 1

/*
* Invoice Creation ************************************************************************************
*/
	-- and create the invoice	
	exec @NewInvoiceKey =  spFixedFeesCreateInvoice @Entity=''tCampaign'',@EntityKey=@CampaignKey,@InvoiceBy=@InvoiceBy,@UserKey=@UserKey
		,@InvoiceAmount=@InvoiceAmount,@AdvanceBilling=@AdvanceBilling,@DefaultClassKey=@DefaultClassKey,@EstimateKey=0,@DefaultDepartmentKey=0
		,@AddProjectDescription=0, @UpdateSchedule = 1, @AddTopLine = @AddTopLine
	if @NewInvoiceKey <= 0
		return -1

	-- issue 402606 propagate tBillingSchedule.Comments to tInvoice.HeaderComment
	update tInvoice
	set    tInvoice.HeaderComment = bs.Comments
	from   tBillingSchedule bs (nolock)
	where  tInvoice.InvoiceKey = @NewInvoiceKey
	and    bs.BillingScheduleKey = @BillingScheduleKey

	-- also if 1 line and Expenses not included, mark the line as labor
	-- this should be probably done in spFixedFeesCreateInvoice (we could do it when we deploy the changes for tCampaign.ExpensesNotIncluded)
	if @InvoiceBy = ''OneLine'' and isnull(@ExpensesNotIncluded,0) = 1
	begin
		update tInvoiceLine
		set    Entity = ''tService''
		      ,EntityKey = 0
		where InvoiceKey = @NewInvoiceKey
	end


	-- now there is tBillingSchedule.AdvanceBill, so do not check AdvanceBilling
	--if @AdvanceBilling = 0
	--begin
		if not exists (select 1 from tBillingSchedule (nolock) where InvoiceKey = @NewInvoiceKey and CampaignKey = @CampaignKey) 
			update tBillingSchedule
			set    InvoiceKey = @NewInvoiceKey
			      ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
			                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
			                                             case when isnull(c.ExpensesNotIncluded, 0) = 0
			                                                  then isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0) + isnull(c.EstExpenses, 0) + isnull(c.ApprovedCOExpense, 0)
			                                                  else isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0)
			                                             end) / 100.00, 2), ''N2'')
			                                    else null end
			                         from  tBillingSchedule bs (nolock)
			                         join  tCampaign c (nolock) on c.CampaignKey = bs.CampaignKey
			                         where bs.BillingScheduleKey = @BillingScheduleKey)
			where  BillingScheduleKey = @BillingScheduleKey
			and    BillingKey is null
			and    InvoiceKey is null
	--end

	--Set the Due Date
	select @TodaysDate = cast(cast(DATEPART(m,getdate()) as varchar(5))+''/''+cast(DATEPART(d,getdate()) as varchar(5))+''/''+cast(DATEPART(yy,getdate())as varchar(5)) as smalldatetime)
	IF ISNULL(@PaymentTermsKey, 0) > 0
	BEGIN
		SELECT @DueDays = ISNULL(DueDays, 30)
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @PaymentTermsKey

		if @DueDays is null 
		begin
			SELECT @DueDays = ISNULL(DueDays, 30)
			FROM   tPaymentTerms (NOLOCK)
			WHERE  PaymentTermsKey = @DefaultPaymentTerms
			if @DueDays is null 
			begin
				set @DueDays = 30
			end
		end

		SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate) 	
	END

	If @CreateAsApproved = 1
		BEGIN	
			--Check to see if the tInvoice Insert SP set the Invoice Number
			SELECT	@NextTranNo = InvoiceNumber			        
			FROM	tInvoice (nolock)
			WHERE	InvoiceKey = @NewInvoiceKey
	
			IF @NextTranNo IS NULL
			BEGIN
				--If the InvoiceNumber has not been set yet, get the next number
				DECLARE @TranType varchar(10) = CASE @AdvanceBilling WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

				EXEC spGetNextTranNo
					@CompanyKey,
					@TranType,
					@RetVal		      OUTPUT,
					@NextTranNo 	  OUTPUT				
		
				IF @RetVal <> 1
					BEGIN
						EXEC sptInvoiceDelete @NewInvoiceKey
						RETURN -1
					END
			END
	
			update tInvoice
			set	  ApprovedByKey = @UserKey
					,InvoiceStatus = 4 -- Approved
					,InvoiceNumber = @NextTranNo 	
					,InvoiceDate = @InvoiceDate
				    ,PostingDate = @PostingDate
					,DueDate = @DueDate
			where InvoiceKey = @NewInvoiceKey

		END
		/* Removed for issue 334769
		ELSE
		BEGIN
		
			select @InvoiceStatus = InvoiceStatus
					,@ApprovedByKey = ApprovedByKey
			from   tInvoice (nolock)
			where  InvoiceKey = @NewInvoiceKey

			-- only if not already approved and the approver is valid, submit
			if @InvoiceStatus <> 4 And isnull(@ApprovedByKey, 0) > 0
				update tInvoice
				set    InvoiceStatus = 2
				where InvoiceKey = @NewInvoiceKey
		END -- created as approved 
		*/
		ELSE
		BEGIN
			update tInvoice
			set    tInvoice.InvoiceDate = @InvoiceDate
				   ,tInvoice.PostingDate = @PostingDate
				   ,tInvoice.DueDate = @DueDate
			where  tInvoice.InvoiceKey = @NewInvoiceKey
		END

		-- Now check if we need an extra invoice line for the expenses not included in Fixed Fee
	
		-- However if AdvanceBilling = 1, we cannot include expenses on a Time And Material type of line
		if @AdvanceBilling = 1
			select @ExpensesNotIncluded = 0

		-- If expenses are not included, return now
		if isnull(@ExpensesNotIncluded, 0) = 0
		begin
			-- now do rollups on projects
			 exec sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey, 1, 0

			 -- and log the creation of the invoice
			select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @ProjectKey = null

			select @Reference = i.InvoiceNumber
				  ,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @NewInvoiceKey

			select @Reference = isnull(@Reference,'''')
				  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through fixed fee mass billing (campaign)''
			else
				select @Comments = ''Invoice was generated through fixed fee mass billing (campaign)''

			-- log how we billed
			select @Comments = @Comments + '' ('' + cast(@PercentBudget as varchar(50))
			if @BillAs = 0 
				select @Comments = @Comments + ''% of Remaining)''
			else
				select @Comments = @Comments + ''% of Total)''

			select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

			return @NewInvoiceKey
		end

		-- Now process the case when expenses are not included
		IF @IOBeginDate is null
			select @IOBeginDate = ''1/1/1960''
		IF @BCBeginDate is null
			select @BCBeginDate = ''1/1/1960''
		IF @EndDate IS NULL
			SELECT @EndDate = ''01/01/2050''
		IF @IOEndDate is null
			select @IOEndDate = ''01/01/2050''
		IF @BCEndDate is null
			select @BCEndDate = ''01/01/2050''
	

		declare @ExpensesAmount money
		declare @MiscCostAmount money
		declare @ExpenseReceiptAmount money
		declare @VoucherAmount money
		declare @POAmount money
		declare @IOAmount money
		declare @BCAmount money
	
		-- projects should not be in the fixed fee list on the UI if they have a BWS, so do not check the presence on a BWS here
		IF @Expense = 1	
		select @MiscCostAmount = ISNULL(SUM(mc.BillableCost), 0)
					FROM	tMiscCost mc (NOLOCK)
						INNER JOIN tProject p (nolock) on mc.ProjectKey = p.ProjectKey
					WHERE	p.CampaignKey = @CampaignKey
					AND     mc.InvoiceLineKey IS NULL
					AND     ISNULL(mc.WriteOff, 0) = 0
					AND     mc.ExpenseDate <= @EndDate
					AND		ISNULL(mc.OnHold, 0) = 0
					AND		mc.MiscCostKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tMiscCost''  
												AND   b.ProjectKey = mc.ProjectKey 
												AND   b.Status < 5				  											
												)
					

	     IF @ExpenseReport = 1
		 select @ExpenseReceiptAmount = ISNULL(SUM(er.BillableCost), 0)
					FROM	tExpenseReceipt er (NOLOCK), tExpenseEnvelope en (nolock), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					and     er.ProjectKey = p.ProjectKey
					AND		er.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
					AND		en.Status = 4
					AND     er.InvoiceLineKey IS NULL
					AND		ISNULL(er.WriteOff, 0) = 0
					AND     er.ExpenseDate <= @EndDate
					AND		ISNULL(er.OnHold, 0) = 0
					AND		er.VoucherDetailKey IS NULL
					AND		er.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tExpenseReceipt''  
												AND   b.ProjectKey = er.ProjectKey 
												AND   b.Status < 5				  											
												)
					

			IF @Expense = 1
			SELECT @VoucherAmount = ISNULL(SUM(vd.BillableCost), 0)
					FROM	tVoucherDetail vd (NOLOCK) ,tVoucher v  (NOLOCK), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					and     vd.VoucherKey   = v.VoucherKey
					AND		vd.ProjectKey = p.ProjectKey
					AND     vd.InvoiceLineKey IS NULL
					AND		ISNULL(vd.WriteOff, 0) = 0
					AND		v.Status = 4
					AND     v.InvoiceDate <= @EndDate
					AND		ISNULL(vd.OnHold, 0) = 0
					AND		vd.VoucherDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tVoucherDetail'' 
												AND   b.ProjectKey = vd.ProjectKey 
												AND   b.Status < 5				  											
												)
					

			IF @PO = 1
			SELECT @POAmount = ISNULL(SUM(pod.BillableCost), 0)
					FROM	tPurchaseOrderDetail pod (NOLOCK)
							,tPurchaseOrder po (NOLOCK)
							, tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND     pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = p.ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		po.PODate <= @EndDate
					AND		po.Status = 4
					AND		po.POKind = 0
					AND		ISNULL(pod.OnHold, 0) = 0
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = pod.ProjectKey 
												AND   b.Status < 5				  											
												)
					

			IF @IO = 1
			SELECT @IOAmount =  isnull(SUM(Case ISNULL(po.BillAt, 0) 
						When 0 then isnull(BillableCost,0)
						When 1 then isnull(PTotalCost,isnull(TotalCost,0))
						When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ),0)
					FROM	tPurchaseOrderDetail pod (NOLOCK)
							,tPurchaseOrder po (NOLOCK)
							, tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND  	pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = p.ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @IOBeginDate
					AND		pod.DetailOrderDate <= @IOEndDate
					AND		po.Status = 4
					AND		po.POKind = 1
					AND		ISNULL(pod.OnHold, 0) = 0
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = pod.ProjectKey 
												AND   b.Status < 5				  											
												)
					

				IF @BC = 1
				SELECT @BCAmount =  isnull(SUM(Case ISNULL(po.BillAt, 0) 
						When 0 then isnull(BillableCost,0)
						When 1 then isnull(PTotalCost,isnull(TotalCost,0))
						When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ),0)
					FROM	tPurchaseOrderDetail pod (NOLOCK)
							,tPurchaseOrder po (NOLOCK)
							, tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND     pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = p.ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @BCBeginDate
					AND		pod.DetailOrderDate <= @BCEndDate
					AND		po.Status = 4
					AND		po.POKind = 2
					AND		ISNULL(pod.OnHold, 0) = 0
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = pod.ProjectKey 
												AND   b.Status < 5				  											
												)
				
		-- place the line at under the root
		declare @ParentLineKey  int
		select @ParentLineKey = 0

		-- key of the ''Expenses'' summary line, when BillExpensesByItem = 1 (set just before the per-item loop below)
		declare @ExpensesLineKey int
		select @ExpensesLineKey = 0

		select @ExpensesAmount = isnull(@MiscCostAmount, 0) + isnull(@ExpenseReceiptAmount, 0) + isnull(@VoucherAmount, 0) + isnull(@POAmount, 0) + isnull(@IOAmount, 0) + isnull(@BCAmount, 0)
				PRINT ''@ExpensesAmount''
				PRINT @ExpensesAmount
		if @ExpensesAmount != 0
		begin
				PRINT ''CAlling''
				PRINT @OfficeKey

			if isnull(@BillExpensesByItem, 0) = 0
			begin
				-- Default behavior: all extra expenses roll up into a single ''Other Expenses'' line
				exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,null							-- TaskKey
					  ,''Other Expenses''					-- Line Subject
					  ,null                 		-- Line description
					  ,2                    		-- Bill From 
					  ,1							-- Quantity
					  ,@ExpensesAmount				-- Unit Amount
					  ,@ExpensesAmount				-- Line Amount
					  ,2							-- line type
					  ,@ParentLineKey				-- parent line key
					  ,@SalesAccountKey				-- Default Sales AccountKey
					  ,@DefaultClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,NULL							-- Work TypeKey
					  ,@PostSalesUsingDetail							-- PostInDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,@OfficeKey
					  ,null							--@DepartmentKey -- may need a department if department required
					  ,@NewInvoiceLineKey output

				if @NewInvoiceLineKey <= 0
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return -1
				end

				 if @Expense = 1
				 begin
					 update tMiscCost
					 set    InvoiceLineKey = @NewInvoiceLineKey
							,AmountBilled = BillableCost
					 FROM   tMiscCost (nolock)
					 inner join  tProject p (nolock) on tMiscCost.ProjectKey = p.ProjectKey
					 WHERE	p.CampaignKey = @CampaignKey
					AND     InvoiceLineKey IS NULL
					AND     ISNULL(WriteOff, 0) = 0
					AND     ExpenseDate <= @EndDate
					AND		ISNULL(OnHold, 0) = 0
					AND		tMiscCost.MiscCostKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
														INNER JOIN tProject p (nolock) on b.ProjectKey = p.ProjectKey  
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tMiscCost''  
													AND   b.ProjectKey = tMiscCost.ProjectKey 
													AND   b.Status < 5				  											
													)
					

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

                if @ExpenseReport = 1
				begin
					update tExpenseReceipt
					 set    InvoiceLineKey = @NewInvoiceLineKey
							,AmountBilled = BillableCost
					 FROM	tExpenseEnvelope en (nolock)
							,tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND     tExpenseReceipt.ProjectKey = p.ProjectKey
					AND		tExpenseReceipt.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
					AND		en.Status = 4
					AND     tExpenseReceipt.InvoiceLineKey IS NULL
					AND		ISNULL(tExpenseReceipt.WriteOff, 0) = 0
					AND     tExpenseReceipt.ExpenseDate <= @EndDate
					AND		ISNULL(tExpenseReceipt.OnHold, 0) = 0
					AND		tExpenseReceipt.VoucherDetailKey IS NULL
					AND		tExpenseReceipt.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tExpenseReceipt''  
													AND   b.ProjectKey = tExpenseReceipt.ProjectKey 
													AND   b.Status < 5				  											
													)
					

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @Expense = 1
				begin
					update tVoucherDetail
					set		InvoiceLineKey = @NewInvoiceLineKey 
							,AmountBilled = BillableCost
					FROM	tVoucher v  (NOLOCK)
							,tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND     tVoucherDetail.VoucherKey   = v.VoucherKey
					AND		tVoucherDetail.ProjectKey = p.ProjectKey
					AND     tVoucherDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tVoucherDetail.WriteOff, 0) = 0
					AND		v.Status = 4
					AND     v.InvoiceDate <= @EndDate
					AND		ISNULL(tVoucherDetail.OnHold, 0) = 0
					AND		tVoucherDetail.VoucherDetailKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tVoucherDetail'' 
													AND   b.ProjectKey = tVoucherDetail.ProjectKey 
													AND   b.Status < 5				  											
													)
					
					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @PO = 1
				begin
					update tPurchaseOrderDetail
					set		InvoiceLineKey = @NewInvoiceLineKey
							,tPurchaseOrderDetail.AccruedCost = 
							CASE 
								WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
								ELSE 0
							END
							,AmountBilled = isnull(BillableCost,0)
					FROM	tPurchaseOrder po (NOLOCK)
							,tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND     tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
					AND		tPurchaseOrderDetail.ProjectKey = p.ProjectKey
					AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
					AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
					AND		po.PODate <= @EndDate
					AND		po.Status = 4
					AND		po.POKind = 0
					AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
					AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey 
												AND   b.Status < 5				  											
												)
				

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @IO = 1
				begin
					update tPurchaseOrderDetail
					set		InvoiceLineKey = @NewInvoiceLineKey
							,tPurchaseOrderDetail.AccruedCost = 
							CASE 
								WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
								ELSE 0
							END
							,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
							When 0 then isnull(BillableCost,0)
							When 1 then isnull(PTotalCost,isnull(TotalCost,0))
							When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
					FROM	tPurchaseOrder po (NOLOCK)
							,tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey	
					AND     tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
					AND		tPurchaseOrderDetail.ProjectKey = p.ProjectKey
					AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
					AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
					AND		tPurchaseOrderDetail.DetailOrderDate >= @IOBeginDate
					AND		tPurchaseOrderDetail.DetailOrderDate <= @IOEndDate
					AND		po.Status = 4
					AND		po.POKind = 1
					AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
					AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey 
												AND   b.Status < 5				  											
												)

					if @@ERROR <> 0 
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1				   	
					  end
				end

				if @BC = 1
				begin
					update tPurchaseOrderDetail
					set		InvoiceLineKey = @NewInvoiceLineKey
							,tPurchaseOrderDetail.AccruedCost = 
							CASE 
								WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
								ELSE 0
							END
							,AmountBilled = isnull(Case ISNULL(po.BillAt, 0) 
							When 0 then isnull(BillableCost,0)
							When 1 then isnull(PTotalCost,isnull(TotalCost,0))
							When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
					FROM	tPurchaseOrder po (NOLOCK)
							,tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey	
					AND   	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
					AND		tPurchaseOrderDetail.ProjectKey = p.ProjectKey
					AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
					AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
					AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
					AND		tPurchaseOrderDetail.DetailOrderDate >= @BCBeginDate
					AND		tPurchaseOrderDetail.DetailOrderDate <= @BCEndDate
					AND		po.Status = 4
					AND		po.POKind = 2
					AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
					AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''  
												AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey 
												AND   b.Status < 5				  											
												)
					

					if @@ERROR <> 0
					  begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1
					  end
				end
			end -- BillExpensesByItem = 0
			else
			begin
				-- Bill Expenses by Item: one invoice line per Item, instead of a single ''Other Expenses'' line
				CREATE TABLE #expenseByItem ( ItemKey int NULL, Amount money NULL )
				CREATE TABLE #expenseByItemTotal ( ItemKey int NULL, ItemName VARCHAR(250) NULL, Amount money NULL, LineOrder int NULL, InvoiceLineKey int NULL, Taxable tinyint NULL, Taxable2 tinyint NULL )

				if @Expense = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(mc.ItemKey, 0), sum(mc.BillableCost)
					FROM	tMiscCost mc (NOLOCK)
						INNER JOIN tProject p (nolock) on mc.ProjectKey = p.ProjectKey
					WHERE	p.CampaignKey = @CampaignKey
					AND     mc.InvoiceLineKey IS NULL
					AND     ISNULL(mc.WriteOff, 0) = 0
					AND     mc.ExpenseDate <= @EndDate
					AND		ISNULL(mc.OnHold, 0) = 0
					AND		mc.MiscCostKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tMiscCost''
												AND   b.ProjectKey = mc.ProjectKey
												AND   b.Status < 5
												)
					group by isnull(mc.ItemKey, 0)

				if @ExpenseReport = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(er.ItemKey, 0), sum(er.BillableCost)
					FROM	tExpenseReceipt er (NOLOCK), tExpenseEnvelope en (nolock), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					and     er.ProjectKey = p.ProjectKey
					AND		er.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
					AND		en.Status = 4
					AND     er.InvoiceLineKey IS NULL
					AND		ISNULL(er.WriteOff, 0) = 0
					AND     er.ExpenseDate <= @EndDate
					AND		ISNULL(er.OnHold, 0) = 0
					AND		er.VoucherDetailKey IS NULL
					AND		er.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tExpenseReceipt''
												AND   b.ProjectKey = er.ProjectKey
												AND   b.Status < 5
												)
					group by isnull(er.ItemKey, 0)

				if @Expense = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(vd.ItemKey, 0), sum(vd.BillableCost)
					FROM	tVoucherDetail vd (NOLOCK), tVoucher v (NOLOCK), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					and     vd.VoucherKey   = v.VoucherKey
					AND		vd.ProjectKey = p.ProjectKey
					AND     vd.InvoiceLineKey IS NULL
					AND		ISNULL(vd.WriteOff, 0) = 0
					AND		v.Status = 4
					AND     v.InvoiceDate <= @EndDate
					AND		ISNULL(vd.OnHold, 0) = 0
					AND		vd.VoucherDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tVoucherDetail''
												AND   b.ProjectKey = vd.ProjectKey
												AND   b.Status < 5
												)
					group by isnull(vd.ItemKey, 0)

				if @PO = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(pod.ItemKey, 0), sum(pod.BillableCost)
					FROM	tPurchaseOrderDetail pod (NOLOCK), tPurchaseOrder po (NOLOCK), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND     pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = p.ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		po.PODate <= @EndDate
					AND		po.Status = 4
					AND		po.POKind = 0
					AND		ISNULL(pod.OnHold, 0) = 0
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''
												AND   b.ProjectKey = pod.ProjectKey
												AND   b.Status < 5
												)
					group by isnull(pod.ItemKey, 0)

				if @IO = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(pod.ItemKey, 0), sum(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(pod.BillableCost,0)
								When 1 then isnull(pod.PTotalCost,isnull(pod.TotalCost,0))
								When 2 then isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,isnull(pod.TotalCost,0)) end )
					FROM	tPurchaseOrderDetail pod (NOLOCK), tPurchaseOrder po (NOLOCK), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND		pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = p.ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @IOBeginDate
					AND		pod.DetailOrderDate <= @IOEndDate
					AND		po.Status = 4
					AND		po.POKind = 1
					AND		ISNULL(pod.OnHold, 0) = 0
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''
												AND   b.ProjectKey = pod.ProjectKey
												AND   b.Status < 5
												)
					group by isnull(pod.ItemKey, 0)

				if @BC = 1
					insert #expenseByItem (ItemKey, Amount)
					select isnull(pod.ItemKey, 0), sum(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(pod.BillableCost,0)
								When 1 then isnull(pod.PTotalCost,isnull(pod.TotalCost,0))
								When 2 then isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,isnull(pod.TotalCost,0)) end )
					FROM	tPurchaseOrderDetail pod (NOLOCK), tPurchaseOrder po (NOLOCK), tProject p (nolock)
					WHERE	p.CampaignKey = @CampaignKey
					AND		pod.PurchaseOrderKey = po.PurchaseOrderKey
					AND		pod.ProjectKey = p.ProjectKey
					AND		pod.InvoiceLineKey IS NULL
					AND		ISNULL(pod.AppliedCost, 0) = 0
					AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
					AND		ISNULL(pod.AmountBilled, 0) = 0
					AND		pod.DetailOrderDate >= @BCBeginDate
					AND		pod.DetailOrderDate <= @BCEndDate
					AND		po.Status = 4
					AND		po.POKind = 2
					AND		ISNULL(pod.OnHold, 0) = 0
					AND		pod.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
												FROM tBillingDetail bd (NOLOCK)
													INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
												WHERE b.CompanyKey = @CompanyKey
												AND   bd.Entity = ''tPurchaseOrderDetail''
												AND   b.ProjectKey = pod.ProjectKey
												AND   b.Status < 5
												)
					group by isnull(pod.ItemKey, 0)

				insert #expenseByItemTotal (ItemKey, Amount)
				select ItemKey, sum(Amount)
				from   #expenseByItem
				group by ItemKey

				update #expenseByItemTotal
				set    ItemName = i.ItemName
					  ,Taxable = i.Taxable
					  ,Taxable2 = i.Taxable2
				from   tItem i (nolock)
				where  #expenseByItemTotal.ItemKey = i.ItemKey

				update #expenseByItemTotal
				set    ItemName = ''[No Item]''
				where  ItemKey = 0 or ItemName is null

				update #expenseByItemTotal
				set    Taxable = isnull(Taxable, 0)
					  ,Taxable2 = isnull(Taxable2, 0)

				-- establish a stable line order (alphabetical by item name)
				select @LineOrder = 1
				select @EntityName = ''''
				while (1=1)
				begin
					select @EntityName = min(ItemName)
					from   #expenseByItemTotal
					where  ItemName > @EntityName

					if @EntityName is null
						break

					update #expenseByItemTotal
					set    LineOrder = @LineOrder
					where  ItemName = @EntityName

					select @LineOrder = @LineOrder + 1
				end

				-- add an ''Expenses'' summary line (zero-dollar header) so the per-item lines below have
				-- something to roll up under, instead of sitting loose at the root
				exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,@ProjectKey					-- ProjectKey
					  ,null							-- TaskKey
					  ,''Expenses''					-- Line Subject
					  ,null                 		-- Line description
					  ,2                    		-- Bill From
					  ,0							-- Quantity
					  ,0							-- Unit Amount
					  ,0							-- Line Amount
					  ,1							-- line type (1 = Summary)
					  ,@ParentLineKey				-- parent line key (root)
					  ,@SalesAccountKey				-- Default Sales AccountKey
					  ,@DefaultClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,NULL							-- Work TypeKey
					  ,@PostSalesUsingDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,@OfficeKey
					  ,null							--@DepartmentKey
					  ,@ExpensesLineKey output

				if isnull(@ExpensesLineKey, 0) <= 0
					select @ExpensesLineKey = @ParentLineKey -- fall back to root if the summary line failed to insert

				select @CurLineOrder = min(LineOrder) from #expenseByItemTotal

				while @CurLineOrder is not null
				begin
					select @CurItemKey = ItemKey, @CurItemName = ItemName, @CurAmount = isnull(Amount, 0)
						  ,@CurTaxable = isnull(Taxable, 0), @CurTaxable2 = isnull(Taxable2, 0)
					from   #expenseByItemTotal
					where  LineOrder = @CurLineOrder

					select @CurEntityKey = null
					if @CurItemKey > 0
						select @CurEntityKey = @CurItemKey

					exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,@ProjectKey					-- ProjectKey
						  ,null							-- TaskKey
						  ,@CurItemName					-- Line Subject
						  ,null                 		-- Line description
						  ,2                    		-- Bill From
						  ,1							-- Quantity
						  ,@CurAmount					-- Unit Amount
						  ,@CurAmount					-- Line Amount
						  ,2							-- line type
						  ,@ExpensesLineKey				-- parent line key (under the ''Expenses'' summary line)
						  ,@SalesAccountKey				-- Default Sales AccountKey
						  ,@DefaultClassKey             -- Class Key
						  ,@CurTaxable					-- Taxable
						  ,@CurTaxable2					-- Taxable2
						  ,NULL							-- Work TypeKey
						  ,@PostSalesUsingDetail							-- PostInDetail
						  ,''tItem''						-- Entity
						  ,@CurEntityKey				-- EntityKey
						  ,@OfficeKey
						  ,null							--@DepartmentKey -- may need a department if department required
						  ,@NewInvoiceLineKey output

					if @NewInvoiceLineKey <= 0
					begin
						exec sptInvoiceDelete @NewInvoiceKey
						return -1
					end

					if @Expense = 1
					begin
						update tMiscCost
						set    InvoiceLineKey = @NewInvoiceLineKey
							  ,AmountBilled = BillableCost
						FROM   tMiscCost (nolock)
						inner join  tProject p (nolock) on tMiscCost.ProjectKey = p.ProjectKey
						WHERE	p.CampaignKey = @CampaignKey
						AND     InvoiceLineKey IS NULL
						AND     ISNULL(WriteOff, 0) = 0
						AND     ExpenseDate <= @EndDate
						AND		ISNULL(OnHold, 0) = 0
						AND     isnull(tMiscCost.ItemKey, 0) = @CurItemKey
						AND		tMiscCost.MiscCostKey NOT IN (SELECT bd.EntityKey
														FROM tBillingDetail bd (NOLOCK)
															INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
															INNER JOIN tProject p (nolock) on b.ProjectKey = p.ProjectKey
														WHERE b.CompanyKey = @CompanyKey
														AND   bd.Entity = ''tMiscCost''
														AND   b.ProjectKey = tMiscCost.ProjectKey
														AND   b.Status < 5
														)

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @ExpenseReport = 1
					begin
						update tExpenseReceipt
						 set    InvoiceLineKey = @NewInvoiceLineKey
								,AmountBilled = BillableCost
						 FROM	tExpenseEnvelope en (nolock)
								,tProject p (nolock)
						WHERE	p.CampaignKey = @CampaignKey
						AND     tExpenseReceipt.ProjectKey = p.ProjectKey
						AND		tExpenseReceipt.ExpenseEnvelopeKey = en.ExpenseEnvelopeKey
						AND		en.Status = 4
						AND     tExpenseReceipt.InvoiceLineKey IS NULL
						AND		ISNULL(tExpenseReceipt.WriteOff, 0) = 0
						AND     tExpenseReceipt.ExpenseDate <= @EndDate
						AND		ISNULL(tExpenseReceipt.OnHold, 0) = 0
						AND		tExpenseReceipt.VoucherDetailKey IS NULL
						AND     isnull(tExpenseReceipt.ItemKey, 0) = @CurItemKey
						AND		tExpenseReceipt.ExpenseReceiptKey NOT IN (SELECT bd.EntityKey
														FROM tBillingDetail bd (NOLOCK)
															INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
														WHERE b.CompanyKey = @CompanyKey
														AND   bd.Entity = ''tExpenseReceipt''
														AND   b.ProjectKey = tExpenseReceipt.ProjectKey
														AND   b.Status < 5
														)

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @Expense = 1
					begin
						update tVoucherDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,AmountBilled = BillableCost
						FROM	tVoucher v  (NOLOCK)
								,tProject p (nolock)
						WHERE	p.CampaignKey = @CampaignKey
						AND     tVoucherDetail.VoucherKey   = v.VoucherKey
						AND		tVoucherDetail.ProjectKey = p.ProjectKey
						AND     tVoucherDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tVoucherDetail.WriteOff, 0) = 0
						AND		v.Status = 4
						AND     v.InvoiceDate <= @EndDate
						AND		ISNULL(tVoucherDetail.OnHold, 0) = 0
						AND     isnull(tVoucherDetail.ItemKey, 0) = @CurItemKey
						AND		tVoucherDetail.VoucherDetailKey NOT IN (SELECT bd.EntityKey
														FROM tBillingDetail bd (NOLOCK)
															INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
														WHERE b.CompanyKey = @CompanyKey
														AND   bd.Entity = ''tVoucherDetail''
														AND   b.ProjectKey = tVoucherDetail.ProjectKey
														AND   b.Status < 5
														)

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @PO = 1
					begin
						update tPurchaseOrderDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,tPurchaseOrderDetail.AccruedCost =
								CASE
									WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
									ELSE 0
								END
								,AmountBilled = isnull(BillableCost,0)
						FROM	tPurchaseOrder po (NOLOCK)
								,tProject p (nolock)
						WHERE	p.CampaignKey = @CampaignKey
						AND     tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
						AND		tPurchaseOrderDetail.ProjectKey = p.ProjectKey
						AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
						AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
						AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
						AND		po.PODate <= @EndDate
						AND		po.Status = 4
						AND		po.POKind = 0
						AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
						AND     isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey
						AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tPurchaseOrderDetail''
													AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey
													AND   b.Status < 5
													)

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @IO = 1
					begin
						update tPurchaseOrderDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,tPurchaseOrderDetail.AccruedCost =
								CASE
									WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
									ELSE 0
								END
								,AmountBilled = isnull(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(BillableCost,0)
								When 1 then isnull(PTotalCost,isnull(TotalCost,0))
								When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
						FROM	tPurchaseOrder po (NOLOCK)
								,tProject p (nolock)
						WHERE	p.CampaignKey = @CampaignKey
						AND     tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
						AND		tPurchaseOrderDetail.ProjectKey = p.ProjectKey
						AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
						AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
						AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
						AND		tPurchaseOrderDetail.DetailOrderDate >= @IOBeginDate
						AND		tPurchaseOrderDetail.DetailOrderDate <= @IOEndDate
						AND		po.Status = 4
						AND		po.POKind = 1
						AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
						AND     isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey
						AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tPurchaseOrderDetail''
													AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey
													AND   b.Status < 5
													)

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					if @BC = 1
					begin
						update tPurchaseOrderDetail
						set		InvoiceLineKey = @NewInvoiceLineKey
								,tPurchaseOrderDetail.AccruedCost =
								CASE
									WHEN po.BillAt < 2 THEN ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate, 1), 2)
									ELSE 0
								END
								,AmountBilled = isnull(Case ISNULL(po.BillAt, 0)
								When 0 then isnull(BillableCost,0)
								When 1 then isnull(PTotalCost,isnull(TotalCost,0))
								When 2 then isnull(BillableCost,0) - isnull(PTotalCost,isnull(TotalCost,0)) end ,0)
						FROM	tPurchaseOrder po (NOLOCK)
								,tProject p (nolock)
						WHERE	p.CampaignKey = @CampaignKey
						AND   	tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey
						AND		tPurchaseOrderDetail.ProjectKey = p.ProjectKey
						AND		tPurchaseOrderDetail.InvoiceLineKey IS NULL
						AND		ISNULL(tPurchaseOrderDetail.AppliedCost, 0) = 0
						AND		(@OpenOrdersOnly = 0 OR tPurchaseOrderDetail.Closed = 0)
						AND		ISNULL(tPurchaseOrderDetail.AmountBilled, 0) = 0
						AND		tPurchaseOrderDetail.DetailOrderDate >= @BCBeginDate
						AND		tPurchaseOrderDetail.DetailOrderDate <= @BCEndDate
						AND		po.Status = 4
						AND		po.POKind = 2
						AND		ISNULL(tPurchaseOrderDetail.OnHold, 0) = 0
						AND     isnull(tPurchaseOrderDetail.ItemKey, 0) = @CurItemKey
						AND		tPurchaseOrderDetail.PurchaseOrderDetailKey NOT IN (SELECT bd.EntityKey
													FROM tBillingDetail bd (NOLOCK)
														INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
													WHERE b.CompanyKey = @CompanyKey
													AND   bd.Entity = ''tPurchaseOrderDetail''
													AND   b.ProjectKey = tPurchaseOrderDetail.ProjectKey
													AND   b.Status < 5
													)

						if @@ERROR <> 0
						begin
							exec sptInvoiceDelete @NewInvoiceKey
							return -1
						end
					end

					select @CurLineOrder = min(LineOrder) from #expenseByItemTotal where LineOrder > @CurLineOrder
				end
			end -- BillExpensesByItem = 1

				-- set taxable on lines
				if @SetTaxableOnInvoice = 1
					update tInvoiceLine
					set    Taxable =1, Taxable2 = 1
					where  InvoiceKey = @NewInvoiceKey
					and    LineType = 2 -- Details only

				 -- before we leave, better to recalc the amounts in the header  
				exec sptInvoiceRecalcAmounts @NewInvoiceKey 
	
				-- Calculate the line order and position
				exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0


		end

		if @NewInvoiceKey >0
		begin
			select @Entity = ''Client Invoice'',@EntityKey = @NewInvoiceKey,@Action = ''Generated'', @ActionDate = getutcdate(), @ProjectKey = null

			select @Reference = i.InvoiceNumber
				  ,@SourceCompanyID = c.CustomerID
			from   tInvoice i (nolock)
				left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
			where  i.InvoiceKey = @NewInvoiceKey

			select @Reference = isnull(@Reference,'''')
				  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
			-- the Invoice number may be missing if the user assign #s at approval time
			if len(@Reference) > 0
				select @Comments = ''Invoice '' + @Reference + '' was generated through fixed fee mass billing (campaign)''
			else
				select @Comments = ''Invoice was generated through fixed fee mass billing (campaign)''

			-- log how we billed
			select @Comments = @Comments + '' ('' + cast(@PercentBudget as varchar(50))
			if @BillAs = 0 
				select @Comments = @Comments + ''% of Remaining)''
			else
				select @Comments = @Comments + ''% of Total)''
			
			select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

			exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey
		end


		-- now do rollups on projects
		 exec sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey, 1, 0

		return @NewInvoiceKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spBillingInvoiceBillLayout]'
GO
IF OBJECT_ID(N'[dbo].[spBillingInvoiceBillLayout]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spBillingInvoiceBillLayout]
	(
	@TopBillingKey INT
	,@UserKey INT
	,@BillingStatusKey INT
	,@InvoiceDate smalldatetime = Null 
	,@PostingDate smalldatetime = Null
	,@CreateAsApproved INT 
	)
AS

  /*
  || When     Who Rel   What
  || 06/29/06 GHL 8.35  Removed ProjectKey on extra summary lines. Was showing  
  ||                    on grids and users expected Project # and name on invoice
  ||                    when template was set to show project # and name and
  ||                    By Top Lines (Bug 5850 Ervin and Smith)
  || 07/28/06 GHL 8.4   Added TrackBudget in task temp tables
  || 09/05/06 CRG 8.35	Removed the check for SetInvoiceNumberOnApproval when auto-approving the invoice.
  ||					(Bug 6437)
  || 09/27/06 GHL 8.4   Added support of fixed fee billing by billing item  
  || 10/11/06 CRG 8.35  Added Emailed column.
  || 02/22/07 GHL 8.4   Added Project Rollup section
  || 07/09/07 GHL 8.5   Added logic for company/office
  || 07/27/07 GHL 8.43  (Bug 9987) Taking in account now tPrefs settings for Invoice Approver
  || 08/07/07 GHL 8.5   Added Invoice Rollup
  || 08/09/07 GHL 8.5   Added Office/Department for extra project line
  || 09/26/07 GHL 8.5   Removed invoice summary since it is done in invoice recalc amounts
  || 03/27/08 GHL 8.507 (21598) Changing the billing status only if > 0 (i.e. not if null, or 0)
  || 04/08/08 GHL 8.508 (23712) New logic for classes, remove reading of FixedFeeBillingClassDetail  
  || 06/18/08 GHL 8.513 Added OpeningBalance
  || 07/14/08 GHL 8.515 (30094) Added call to sptInvoiceOrder
  || 08/12/08 GHL 10.006 (32051) Moved invoice recalc amounts before creation of advance bills
  ||                     because InvoiceTotalAmount was not set yet
  || 08/13/08 GHL 10.008 (32232) Using now sptInvoiceLineInsertMassBilling when creating invoice lines for projects
  ||                     This sp bypasses validations and recalcs not necessary here
  || 10/08/08 GHL 10.010 (36927) Taking now default line format for Fixed Fee as One line instead of Service/item
  ||                     This is a problem if FixedFeeDisplay is null (sptBillingInsert has been fixed though)
  || 10/13/08 GHL 10.010 (37465) If tTask.ShowDescOnEst = 1 bring over task description
  || 03/18/09 GHL 10.021 Added generation of invoices per billing item then item
  || 06/01/09 GHL 10.026 (52904) Moved position of BI/Item call inside the Ws/Project loop (was outside) 
  || 07/09/09 GHL 10.503 (56803) Using now the class from individual WS rather than from the master WS
  ||                     The class on the master WS goes to the invoice header
  ||                     The class on the individual WSs go to the invoice lines
  || 07/29/09 GHL 10.505 (57778) Do not prevent the users from creating an invoice with 0 amount  
  || 08/14/09 GHL 10.507 (60305) Prevent the users from creating an invoice if there are no billing detail records
  || 08/24/09 GHL 10.507 (60195) For Fixed Fee projects, check if tBillingFixedFee.Amount > 0 before creating invoice 
  || 08/25/09 GHL 10.508 (60144) Account for retainer projects when deciding on creating the invoice
  || 09/10/09 GHL 10.509 (62127) Changed BillingCount definition to = COUNT(*) from #tBilling where BillingCount <> 0 
  ||                      Instead of = SUM(BillingCount) from #tBilling
  ||                      because we need an exact count of projects with anything to bill
  || 09/11/09 GHL 10.509  Get only child billing worksheets which have not been invoiced yet
  || 01/22/10 GHL 10.517 (69011) Changed retainer amount logic since we can have amounts <0  
  || 03/24/10 GHL 10.521 Added LayoutKey
  || 03/31/10 GHL 10.522 Cloned spBillingInvoiceBill to handle new types of rollup based on Layout
  || 04/12/10 GHL 10.521 (75825) Line description is now a text field, cannot be held in a variable  
  || 04/16/10 GHL 10.521 Setting now DisplayOption in the case of task rollup
  || 04/23/10 GHL 10.521 Added ProjectKey on Project summary lines for custom fields
  || 06/10/10 GHL 10.530 (82735) For AdvBill overwrite the SalesAccountKey on the lines to the Adv Bill Account 
  ||                     that has already been set on the Billing WS
  || 06/14/10 GHL 10.531 Fixed setting of @kDisplayOptionTransactions
  || 10/13/10 GHL 10.536 Setting now BillingKey = TopBillingKey in single project mode
  || 12/10/10 GHL 10.539 Setting now campaign segment on lines when TopEntity = Campaign and Rollup=By Project/Task
  ||                     At KN''s request
  || 05/21/12 GHL 10.556 Added reading of ShowTransactionsOnInvoices (customization for Etna)
  ||                     Most of the projects will be No Details
  ||                     Expense project will be Transactions 
  || 05/23/12 GHL 10.556 (144563) If we group by campaign but there was only one project (i.e. no masters)
  ||                     we must also set the campaign key on the invoice
  || 08/07/12 GHL 10.558 (151083) If the line format = @kByProjectBillingItem (obsolete)
  ||                      change it to @kByProjectBillingItemItem
  || 08/10/12 GHL 10.558 (150858) If the new invoice is completely covered by an advance bill, set Printed = 1
  || 09/27/12 GHL 10.560 Added update of billing group on invoice for HMI request
  || 10/15/12 GHL 10.561 (156926) Added FixedFeeRollup 
  ||                     Initially we only had one Rollup (For Fixed Fee the TM trans were rolled up into 1 line)
  ||                     But Enlighten wants to control the TM rollup on FF projects
  ||                     Decided to have 2 rollups (one TM and one FF)
  ||                     Note: The TM rollup for FF projects can only be changed on master BWS 
  || 02/26/13 GHL 10.565 (167798) When applying advance bills, add taxes to the applied amount.
  ||                     The original amount does not include taxes and users have to manually add taxes
  || 04/04/13 GHL 10.566 (173907) Added checking of ProjectName not null before inserting line for project in case of multi projects
  || 10/01/13 GHL 10.573 Added multi currency logic
  || 01/03/14 WDF 10.576 (188500) Pass UserKey to sptInvoiceInsert
  || 10/10/14 GHL 10.584 (232654) Setting now tInvoice.BillingKey to better detect duplicate invoices
  || 11/12/14 GHL 10.586 Added support of titles for Abelson Tayor
  || 12/02/14 GHL 10.587 Renamed spBillingInvoiceOneLinePerServiceItem to spBillingInvoiceOneLinePerServiceItemFF 
  ||                     Added support for line format rollup: By Service OR Item
  || 12/02/14 GHL 10.587 (239399) Added call sptInvoiceLineApplyTaskOptions when billing by project/task and there is a master worksheet
  || 03/19/15 GHL 10.591 Added setting of Hours on invoice lines for abelson taylor
  || 06/15/15 GHL 10.593 (260071) If the rollup is by billing item and item, and there are some FF projects, change to by project then billing item and item
  || 08/12/15 GHL 10.594 Added IsRetainer = 0 when creating an invoice
  || 08/18/15 GHL 10.595 Only set the campaign segment if we group by campaign
  || 04/14/17 GHL 10.614 (341368) Put back the switch from Project/Service to Project/Billing Item/Item because I had removed it
  ||                     for issue 23117 which was resolved in a different manner by creating a new format (Project / Service/Item)
  || 08/14/17 GHL 10.619 (341875) customization for Owens Harkey..get taxes from vendor
  || 10/02/17 GHL 10.621 (363756) Added AR account info
  || 11/03/17 GHL 10.621 (366171) For the ''one line'' rollup, set the Display Option from the tProject row in tLayoutBilling
  || 03/06/18 GHL 18.400 (388967) For fixed fee projects, we may have fixed fee (FF) and time and material (TM) data. process FF first
  || 06/26/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
  || 10/04/18 GHL 18.920 (424266) Added logic to fight duplicates invoices per billing worksheet
  || 10/30/18 MFT 18.920 (428311) Fixed bug that did not generate a line when line format Billing Item and Item with a Layout
  || 11/01/18 GHL 18.920 (428664) Added a check of tInvoice.BillingKey at the end also, to fight duplicate invoices 
  || 01/09/19 GHL 19.100 (437259) For the case ''Single Project Mode'' process the fixed fee recs before the time and approval recs
  || 05/10/19 GHL 19.600 (459199) Link the invoice to the billing schedule for FF projects
  || 01/27/20 GHL 20.030 (495024) Get the invoice template from the GL company if tPreference.LayoutFromGLCompany = 1
  || 02/18/20 MCM 21.030 (544541) Updated check to be <> 0 instead of > 0 on the BillingFixedFeeKey count
  || 03/24/21 GHL 21.04.16 (455922) Added line format by project for FF campaign mode 
  || 05/17/21 GHL 21.06.20 (558991) Added logic for ''Add Project Line'' for FF projects
  || 06/10/21 GHL 21.07.20 (560163) Updating tBillingSchedule for campaigns
  || 06/15/21 GHL 21.070 (561987) Added same logic of FixedFeeAddProjectLine for campaigns
  || 10/18/21 MCM 21.11X (570762) Updated so the project is the top row for @kByProjectTask, @kByProjectService and @kByProjectServiceOrItem
  || 11/05/21 GHL 21.120 (574541) Changed the logic for advance bills. Now child BWS can be applied to Advance Bills
  ||                              Used to be only for top billing key (the master BWS)
  || 03/18/22 GHL 22.040 (590582) Added support for tProject.SetTaxableOnInvoice
  || 11/03/22 MFT 22.110 (618076) Added support for making InvoiceApprover PM from Project
  || 11/16/22 MFT 22.120 (618633) Respect DisplayOption in Layout for Project Service/Item rollup
  || 12/16/22 MFT 23.010 (624039) Allow Invoice generation when there is no Default Sales Acct, even if GL Acct is required if Post Sales From Detail is on
  || 02/20/23 GAR 23.030 (622546) Have Fixed Fee Campaign mass billing observe the default approver settings from trans pref / client invoice / default approver
  || 03/13/23 MFT 23.040 (629602) Respect the Layout Billing Item / Item values for Segments
  || 06/06/23 MFT 23.060 (642167) For ByProjectServiceOrItem, put Quantity and Unit Amount on the line to match Mass Billing
  || 08/14/23 MFT 23.090 (648611) Increase InvoiceComment max
  || 03/12/24 MFT 24.040 (666923) Fix DisplayOption at Campaign/Project/Segement level
  || 04/17/24 MFT 24.040 (669961) Fix DisplayOption at BillingItem level (broken by previous update)
  || 05/03/24 MFT 24.050 (671639) Fix extra top line Project add when Fixed Fee and grouped by Billing Item
  || 05/10/24 MFT 24.060 (666923) Fix top line Project when no detail lines below (line type 2)
  || 12/16/24 MFT 25.010 (686350) Use TimeRateSheet InvoiceLabel if exists
  || 12/18/24 MFT 25.010 (690378) Put hours/rate on the Invoice line when invoicing by Task
  || 12/19/24 MFT 25.010 (690879) Restored the Project and Service rollup (was always available for non-Layout Invoices)
  || 01/07/25 MFT 25.010 (691740) Fixed extra top line Project add when Fixed Fee (all grouping cases)
  || 04/03/25 MCM 25.04x (698988) Fixed error return codes -1 to -104 and -1 to -106
  || 07/21/25 MFT 25.080 (706297) Use SP to apply AB, or short circuit with Avalara
  || 08/27/25 MFT 25.090 (709533) Use DisplayOrder of Child BWS
  || 09/12/25 MFT 25.100 (711284) Prevent blank Invoice Approver when set to use PM
  || 11/04/25 MCM 25.110 (656423) Added Liability Account Key when calling sptInvoiceInsert
  || 04/21/26 AMP 26.050 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
  || 05/14/26 RLS 26.060 (725399) Added  @DefaultARApprover = 5
  || 05/19/26 MFT 26.060 (728635) Added ProjectKey to Service/Item lines when only one Project to match Mass Billing
  || 07/08/26 AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
  || 07/14/26 AMP 26.07.19 (729259) Added BilledComment population for campaign billing schedule rows (FF and T&M paths)
  */

	SET NOCOUNT ON

-- Layout display options
DECLARE @kDisplayOptionNoDetail INT			SELECT @kDisplayOptionNoDetail = 1
DECLARE @kDisplayOptionSubItemDetail INT	SELECT @kDisplayOptionSubItemDetail = 2
DECLARE @kDisplayOptionTransactions INT		SELECT @kDisplayOptionTransactions = 3

-- Line Format/Rollup option
DECLARE @kByOneLine INT                     SELECT @kByOneLine = 0
DECLARE @kByBillingItemItem INT             SELECT @kByBillingItemItem = 9
DECLARE @kByProjectTask INT                 SELECT @kByProjectTask = 1
DECLARE @kByProjectBillingItemItem INT      SELECT @kByProjectBillingItemItem = 8 -- New
DECLARE @kByProjectService INT              SELECT @kByProjectService = 2 -- Obsolete
DECLARE @kByProjectBillingItem INT          SELECT @kByProjectBillingItem = 3 -- Legacy also, Obsolete
DECLARE @kByProjectServiceOrItem INT        SELECT @kByProjectServiceOrItem = 14 

DECLARE @kByRetainer INT                    SELECT @kByRetainer = 4
DECLARE @kFFByTask INT                      SELECT @kFFByTask = 5
DECLARE @kFFByServiceItem INT               SELECT @kFFByServiceItem = 6
DECLARE @kFFByProject INT					SELECT @kFFByProject = 7

-- Added for Abelson Taylor
DECLARE @kByProjectTitle INT				SELECT @kByProjectTitle = 11
DECLARE @kByProjectTitleService INT			SELECT @kByProjectTitleService = 12
DECLARE @kByProjectServiceTitle INT			SELECT @kByProjectServiceTitle = 13

-- Billing Methods
DECLARE @kTMBillingMethod int				SELECT @kTMBillingMethod = 1
DECLARE @kFFBillingMethod int				SELECT @kFFBillingMethod = 2
DECLARE @kRetainerBillingMethod int			SELECT @kRetainerBillingMethod = 3


-- Variables to capture tBilling record
	DECLARE @BillingCount INT
			,@BillingMethod INT
			,@FixedFeeDisplay INT
			,@BillingKey INT
			,@DisplayOrder INT
			,@Status INT
			,@BillingApprover INT -- This is the Approver on the Billing WS (defaulted from AE on Project)		
			,@InvoiceApprover INT -- Final approver on Invoice, will depend on transaction preferences
			,@NewInvoiceKey INT
			,@ParentInvoiceLineKey INT
			,@AdvanceBill INT
			,@RetVal INT
			,@FixedFeeAddProjectLine INT -- straight from tBilling
			,@ShowExtraProjectLine INT -- final flag to decide if we add an extra line
			,@ProjectLineAdded INT -- to avoid creating the project line twice
			,@PrimaryContactKey INT
			,@AddressKey INT
			,@GLCompanyKey INT
			,@OfficeKey INT
			,@CurrencyID VARCHAR(10)

-- Clone variables from spProcessWIPWorksheet	
declare @CompanyKey int
declare @ClientKey int
declare @ProjectKey int
declare @EstimateKey int	
declare @Rollup int
declare @FixedFeeRollup int
declare @BillingContact varchar(100) 
declare @DefaultSalesAccountKey int
declare @SalesAccountKey int 
declare @RequireGLAccounts tinyint
declare @TodaysDate smalldatetime
declare @DueDate smalldatetime
declare @DueDays int
declare @InvoiceComment varchar(max)
declare @ProjectName varchar(500)
declare @WorkTypeKey int
declare @ARAccountKey int
declare @DefaultARAccountKey int
declare @DefaultARApprover int
declare @DefaultARApproverKey int
declare @PostSalesUsingDetail tinyint
declare @InvoiceTemplateKey int
declare @SalesTaxKey int, @SalesTax2Key int, @PaymentTermsKey int
declare @RequireClasses tinyint
declare @TopBillingClassKey int
declare @BillingClassKey int
declare @DefaultClassKey int
declare @LayoutKey int
declare @TaskShowTransactions int
declare @LayoutProjectDisplayOption int
declare @UseBillingTitles int -- this will indicate the Abelson Taylor company
declare @SetInvoiceNumberOnApproval tinyint
declare @NextTranNo varchar(100)
declare @UseMediaTaxes int -- this will indicate to pull the taxes from the vendor 
declare @Customizations varchar(2000)
declare @SetTaxableOnInvoice int
declare @OldInvoiceKey int
declare @OldStatus int
declare @LayoutFromGLCompany int
declare @AdvBillAccountKey int
declare @LiabilityAccountKey int

-- Segment logic
declare @TopRollup int
declare @TopEntity varchar(50)
declare @TopEntityKey int
declare @TopGroupEntity varchar(50)
declare @TopGroupEntityKey int
declare @CampaignSegmentKey int
declare @SegmentDisplayOrder int
declare @SegmentParentInvoiceLineKey int 
declare @SegmentName varchar(500)
declare @SingleProjectMode int
declare @ShowTransactionsOnInvoices int -- Etna
declare @IsFFCampaign int --Is this a FF campaign? if yes we can add a '' Expenses'' mention to projects (single line format)

select @OldInvoiceKey = isnull(InvoiceKey, 0) 
	  ,@OldStatus = Status
from tBilling (nolock) where BillingKey = @TopBillingKey

-- Is it a valid invoice?
if not exists (select 1 from tInvoice (nolock) where InvoiceKey = @OldInvoiceKey)
	select @OldInvoiceKey = 0

-- If already invoiced, abort
if @OldInvoiceKey > 0 
	return -1001
if @OldStatus = 5
	return -1001
-- this way to check for duplicates should be stronger because tInvoice is set earlier
if exists (select 1 from tInvoice (nolock) where BillingKey = @TopBillingKey)
    return -1001 


	/*		
	|| Inits
	*/
	If @PostingDate IS NOT NULL
		select @TodaysDate = cast(cast(DATEPART(m,@PostingDate) as varchar(5))+''/''+cast(DATEPART(d,@PostingDate) as varchar(5))+''/''+cast(DATEPART(yy,@PostingDate)as varchar(5)) as smalldatetime)
	ELSE
	BEGIN
		select @TodaysDate = cast(cast(DATEPART(m,getdate()) as varchar(5))+''/''+cast(DATEPART(d,getdate()) as varchar(5))+''/''+cast(DATEPART(yy,getdate())as varchar(5)) as smalldatetime)
		Select @PostingDate = @TodaysDate
	END
	if @InvoiceDate is null
		Select @InvoiceDate = @TodaysDate
	
	-- Reset error
	update tBilling 
	set ErrorMsg = NULL 
	where BillingKey = @TopBillingKey 
					
	/*				
	|| Prep temp tables
	|| temp table created in .NET
	|| CREATE TABLE #tBilling(BillingKey INT NULL, DisplayOrder INT NULL, BillingCount INT NULL, CampaignSegmentKey INT NULL, SegmentDisplayOrder INT NULL, ProjectKey INT NULL, CampaignKey INT NULL)
	*/
	CREATE TABLE #tCampaignSegment(CampaignSegmentKey INT NULL, SegmentDisplayOrder INT NULL )
			
	IF (SELECT ParentWorksheet FROM tBilling (NOLOCK) WHERE BillingKey = @TopBillingKey) = 0
	BEGIN
		INSERT #tBilling (BillingKey) VALUES (@TopBillingKey)
	
		SELECT @SingleProjectMode = 1
	END
	ELSE
	BEGIN
		INSERT #tBilling (BillingKey, DisplayOrder, ProjectKey, CampaignKey) 
		SELECT BillingKey, DisplayOrder, ProjectKey, CampaignKey
		FROM   tBilling (NOLOCK) 
		WHERE  ParentWorksheetKey = @TopBillingKey
		AND    Status <> 5 -- do not take if already invoiced during approval
		ORDER BY DisplayOrder
		
		SELECT @SingleProjectMode = 0
	END
	
	-- do we have some T&M to bill?
	UPDATE #tBilling
	SET    #tBilling.BillingCount = ISNULL((
		SELECT COUNT (bd.BillingDetailKey) FROM tBillingDetail bd (NOLOCK) 
		WHERE bd.BillingKey = #tBilling.BillingKey AND bd.Action = 1
		-- even if Amount = 0, we have to create a $0 invoice 
	),0)

	-- do we have some FF to bill?
	UPDATE #tBilling
	SET    #tBilling.BillingCount = ISNULL(#tBilling.BillingCount, 0) + ISNULL((
		SELECT COUNT (bff.BillingFixedFeeKey) FROM tBillingFixedFee bff (NOLOCK) 
		WHERE bff.BillingKey = #tBilling.BillingKey 
		AND bff.Amount <> 0 -- Added this because one tBillingFixedFee rec is created automatically with Amount = 0  
	),0)
		
	-- do we have retainer amounts to bill?
	UPDATE #tBilling
	SET    #tBilling.BillingCount = ISNULL(#tBilling.BillingCount, 0) + 1
	FROM   tBilling b (NOLOCK)
	WHERE  #tBilling.BillingKey = b.BillingKey
	--AND    ISNULL(b.RetainerAmount, 0) > 0
	AND    b.Entity = ''Retainer'' -- because now b.RetainerAmount can be <0, =0, >0
		
	-- Do not bill if no count
	SELECT @BillingCount = COUNT(*) FROM #tBilling WHERE ISNULL(BillingCount, 0) <> 0 
	
	-- No Amount to bill, mark BWS as Invoiced 	
	IF @BillingCount = 0
	BEGIN
		UPDATE 	tBilling 
		SET     tBilling.Status = 5
		FROM    #tBilling b
		WHERE   tBilling.BillingKey = b.BillingKey
		
		UPDATE 	tBilling 
		SET tBilling.Status = 5
		WHERE   tBilling.BillingKey = @TopBillingKey
			
		RETURN 1
	END
	
	-- Do not trust tBilling.DisplayOrder, setup our own
	SELECT @DisplayOrder = 1
	UPDATE #tBilling 
	SET    #tBilling.DisplayOrder = @DisplayOrder
	      ,@DisplayOrder = @DisplayOrder + 1
	WHERE DisplayOrder IS NULL
	
	-- set the flag that says that we have a FF campaign
	If exists (select 1 from tBilling bill (nolock) 
				inner join #tBilling b on bill.BillingKey = b.BillingKey
				where  bill.CampaignKey > 0 and bill.BillingMethod = 2)
		select @IsFFCampaign = 1
	else
		select @IsFFCampaign = 0
		
	SELECT  bd.* 
	INTO    #tBillingDetail
	FROM	tBillingDetail bd (NOLOCK)
		INNER JOIN #tBilling b ON bd.BillingKey = b.BillingKey
	WHERE   bd.Action = 1 -- Only trans to bill, others are handled on ws approval

				
	--create temp tables needed for task management
	create table #tInvcTask(
         TaskKey int null
        ,SummaryTaskKey int null
        ,TaskType smallint null
        ,DisplayOrder int null
        ,Taxable tinyint null 
        ,Taxable2 tinyint null 
        ,WorkTypeKey int null 
        ,TrackBudget int null
        ,TaskName varchar(500) null
        ,Description varchar(6000) null
		)
				
	create table #tInvcRootTask (
		TaskKey int null
		,SummaryTaskKey int null
        ,TaskType smallint null
        ,DisplayOrder int null
        ,Taxable tinyint null 
        ,Taxable2 tinyint null 
        ,WorkTypeKey int null               
        ,TrackBudget int null
        ,TaskName varchar(500) null
        ,Description varchar(6000) null
        )                
	
	--create temp tables needed for some other groupings
	 CREATE TABLE #tran(
		Entity varchar(20) null,		-- like in tBillingDetail, tMiscCost, tTime, etc.... 
		EntityKey varchar(50) null,     -- transaction key
		EntityGuid uniqueidentifier null,
		
		BilledAmount money null,
		Quantity decimal(24,4) null,
		RateLevel int null,
		Rate money null,
		BilledComment varchar(2000),
		
		LayoutEntityKey int null,       -- ItemKey or ServiceKey depending on LayoutEntity

		-- All fields above should be set before this SP 
			
		LayoutEntity varchar(50) null,   -- like in tLayoutBilling, tItem, tService
		LayoutOrder int null,	
		WorkTypeLayoutOrder int null,
			
		WorkTypeKey int null,
		WorkTypeName varchar(200) null, 
		ItemName varchar(200) null,     -- will come from item or service
		
		-- Use this vars for a simpler grouping (like Service/Item)
		GroupEntity varchar(25) null,
		GroupEntityKey int null,
		GroupName varchar(250) null,

		InvoiceLineKey int null,
		LineID int null,
		
		UpdateFlag int null
		)
		
	CREATE TABLE #line(
		LineID int identity(1,1),
		ParentLineID int null,
		InvoiceLineKey int null,
		ParentLineKey int null,
		
		BilledAmount money null,
		Quantity decimal(24,4) null,
		UnitCost money null,
		
		Subject VARCHAR(200) null,
		Description text null,
		Taxable int null,
		Taxable2 int null,
		ClassKey int null,
		SalesAccountKey int null,
		
		WorkTypeKey int null,
		ItemKey int null, 
		ServiceKey int null,
		
		LayoutOrder int null, -- just for initial pull
		
		DisplayOption int null,
		
		UpdateFlag int null
		)

	-- we need some valid display orders for billing items and items and services in the case when LayoutKey = 0
	-- (maybe not needed now with new requirement that without a layout, we call the old sp)
	-- also we will need the names and descriptions
	-- so my strategy was to get them upfront
	create table #allitems (Entity varchar(20) null, EntityKey int, WorkTypeKey int
	    , EntityName varchar(200) null, Description text null
	    , StdEntityName varchar(200) null, StdDescription text null
	    , DisplayOrder int null, SalesAccountKey int null,ClassKey int null, Taxable int null, Taxable2 int null
		)
	
	/*				
	|| Get defaults from top billing worksheet or Pref or client
	*/
	SELECT @CompanyKey = b.CompanyKey
		   ,@ClientKey = b.ClientKey
		   ,@ProjectKey = b.ProjectKey
		   ,@TopBillingClassKey = ISNULL(b.ClassKey, 0)
		   ,@SalesTaxKey = b.SalesTaxKey
		   ,@SalesTax2Key = b.SalesTax2Key
		   ,@PaymentTermsKey = ISNULL(b.TermsKey, 0) 
		   ,@DefaultSalesAccountKey = ISNULL(b.DefaultSalesAccountKey, 0) -- It is NULL or 0 in table tBilling
		   ,@BillingApprover = ISNULL(b.Approver, @UserKey)	
     	   ,@InvoiceComment = b.InvoiceComment
		   ,@Status = b.Status
		   ,@AdvanceBill = ISNULL(b.AdvanceBill, 0) -- only FF and will be on their own ws	
		   ,@PrimaryContactKey = b.PrimaryContactKey -- NULL is fine
		   ,@AddressKey = b.AddressKey -- NULL is fine
		   ,@GLCompanyKey = b.GLCompanyKey
		   ,@OfficeKey = b.OfficeKey	
		   ,@CurrencyID = b.CurrencyID

		   ,@TopRollup = ISNULL(b.DefaultARLineFormat, 0) -- Default is 1 line per Project 
	       ,@TopEntity = b.Entity							-- Will indicate Campaign
	       ,@TopEntityKey = b.EntityKey
		   ,@TopGroupEntity = b.GroupEntity				-- Will indicate Campaign on single projects
	       ,@TopGroupEntityKey = b.GroupEntityKey
	       ,@LayoutKey = isnull(b.LayoutKey, 0)
	       ,@TaskShowTransactions = ISNULL(l.TaskShowTransactions, 0)
	FROM
		tBilling b (NOLOCK)
		LEFT JOIN tLayout l (nolock) ON b.LayoutKey = l.LayoutKey
	WHERE  BillingKey = @TopBillingKey

	if @TopRollup = @kByProjectService
		select @TopRollup = @kByProjectBillingItemItem

	if @TopRollup = @kByProjectBillingItem
		select @TopRollup = @kByProjectBillingItemItem

	--Set the AdvBillAcountKey
	Select 
		@AdvBillAccountKey = AdvBillAccountKey
	From
		tPreference (nolock)
	Where
		CompanyKey = @CompanyKey
		
	Set @LiabilityAccountKey = 
		Case 
			When @AdvanceBill = 1 Then @AdvBillAccountKey
			Else NULL
	End;

	-- for top rollup = 9 -- By Billing Item/Item...this works only for TM projects
	-- because we are trying to combine all transactions on TM billing worksheets and organize them by BI/Item, regardless of projects 
	-- if there are some FF projects, this does not work well, change to By Project then Billing Item/Item 
	if @TopRollup = @kByBillingItemItem
	begin
		if exists (select 1 
					from #tBilling b
					inner join tBilling bill (nolock) on b.BillingKey = bill.BillingKey
					where  bill.BillingMethod > 1
					)
			BEGIN
				select @TopRollup = @kByProjectBillingItemItem
				IF @BillingCount = 1 SELECT @Rollup = @TopRollup
			END
	end

	-- Already invoiced
	IF @Status = 5
	BEGIN
		update tBilling set ErrorMsg = ''The billing worksheet was already invoiced''
		where BillingKey = @TopBillingKey 
			
		RETURN -1
	END

	SELECT @LayoutProjectDisplayOption = DisplayOption
	FROM   tLayoutBilling (nolock)
	WHERE  LayoutKey = @LayoutKey
	AND    Entity = ''tProject''
	AND    EntityKey = 0
		
	-- Make sure that no vendor invoice have been applied against POs
	IF EXISTS (SELECT 1
				FROM  tPurchaseOrderDetail pod (NOLOCK)
				INNER JOIN tPurchaseOrder po (NOLOCK) ON po.PurchaseOrderKey = pod.PurchaseOrderKey
				INNER JOIN #tBillingDetail bd (NOLOCK) ON pod.PurchaseOrderDetailKey = bd.EntityKey
														AND bd.Entity = ''tPurchaseOrderDetail''
				WHERE po.CompanyKey = @CompanyKey
				AND	ISNULL(pod.AppliedCost, 0) > 0
				)
	BEGIN
		update tBilling set ErrorMsg = ''Vendor Invoices have been applied to POs involved on this billing worksheet''
		where BillingKey = @TopBillingKey 
		
		RETURN -1			
	END
	
	
	-- Campaign/Segment logic
	
	-- Note: Could be debatable here and we could only do this if we have a campaign 
	-- Only set the segments if we group by campaign
	if @TopEntity = ''Campaign''
	begin
		update #tBilling
		set    #tBilling.CampaignSegmentKey = p.CampaignSegmentKey
		      ,#tBilling.SegmentDisplayOrder = s.DisplayOrder
		from   tProject p (nolock)
		   inner join tCampaignSegment s (nolock) on p.CampaignSegmentKey = s.CampaignSegmentKey  
		where  #tBilling.ProjectKey = p.ProjectKey
	end
	
	update #tBilling
	set    CampaignSegmentKey = isnull(CampaignSegmentKey, 0)
		   ,SegmentDisplayOrder = isnull(SegmentDisplayOrder, 1)
	
	insert #tCampaignSegment(CampaignSegmentKey, SegmentDisplayOrder)
	select  distinct CampaignSegmentKey, SegmentDisplayOrder
	from    #tBilling
	where   CampaignSegmentKey > 0
	order   by SegmentDisplayOrder
	
	-- Do not trust #tCampaignSegment.DisplayOrder, setup our own
	SELECT @SegmentDisplayOrder = 1
	UPDATE #tCampaignSegment 
	SET    #tCampaignSegment.SegmentDisplayOrder = @SegmentDisplayOrder
	      ,@SegmentDisplayOrder = @SegmentDisplayOrder + 1
	
	IF @PrimaryContactKey IS NOT NULL
		select @BillingContact = Left(FirstName + '' '' + LastName, 100)
		from   tUser (nolock) 
		Where  UserKey = @PrimaryContactKey
		
	-- get other client defaults  
	Select @InvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
		  ,@ARAccountKey = ISNULL(DefaultARAccountKey, 0)
	from tCompany (nolock)
	Where CompanyKey = @ClientKey
	
	Select @LayoutFromGLCompany  = ISNULL(LayoutFromGLCompany,0)
	From tPreference (nolock)
	Where CompanyKey = @CompanyKey
		
	IF @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
		select @InvoiceTemplateKey = InvoiceTemplateKey from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey
			
	if @PaymentTermsKey = 0
		Select @PaymentTermsKey = PaymentTermsKey
		From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	Select @PostSalesUsingDetail  = ISNULL(PostSalesUsingDetail, 0)
			,@DefaultARAccountKey = DefaultARAccountKey
			,@WorkTypeKey         = AdvBillItemKey
			,@RequireClasses      = ISNULL(RequireClasses, 0)
			,@RequireGLAccounts   = ISNULL(RequireGLAccounts, 0)
			,@SetInvoiceNumberOnApproval = ISNULL(SetInvoiceNumberOnApproval,0)
			,@DefaultARApprover   = ISNULL(DefaultARApprover, 0)
			,@DefaultARApproverKey = ISNULL(DefaultARApproverKey, 0)			
			,@DefaultClassKey      = DefaultClassKey
			,@UseBillingTitles	   = ISNULL(UseBillingTitles, 0)
			,@Customizations = LOWER(ISNULL(Customizations, ''''))
			,@SetTaxableOnInvoice  = ISNULL(SetTaxableOnInvoice,0) -- this overrides the Taxable on tasks/items/services/BI and also used for 1-line invoice
	From tPreference (nolock)
	Where CompanyKey = @CompanyKey
	
	if ISNULL(@ARAccountKey, 0) > 0
		select @DefaultARAccountKey = @ARAccountKey

	-- customization for Owens Harkey, use taxes from the vendor, vouchers, orders
	if charindex(''mediataxes'', @Customizations) > 0
		select @UseMediaTaxes = 1
	else
		select @UseMediaTaxes = 0
				
	-- validation of classes
	if @RequireClasses = 1 AND ISNULL(@TopBillingClassKey, 0) = 0 AND ISNULL(@DefaultClassKey, 0) = 0
	BEGIN
		update tBilling set ErrorMsg = ''There is no class for this worksheet, but your company requires classes on transactions''
		where BillingKey = @TopBillingKey 
		
		RETURN -106			
	END
	
	if @RequireClasses = 1 AND ISNULL(@TopBillingClassKey, 0) = 0
		SELECT @TopBillingClassKey = @DefaultClassKey
	
	-- validation of GL accounts
	if @DefaultSalesAccountKey = 0
		Select @DefaultSalesAccountKey = ISNULL(DefaultSalesAccountKey, 0)
		From tPreference (nolock)
		Where CompanyKey = @CompanyKey
	
	if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @DefaultSalesAccountKey )
		Select @DefaultSalesAccountKey = 0
		
	if @RequireGLAccounts = 1 AND @DefaultSalesAccountKey = 0 AND @PostSalesUsingDetail = 0
	BEGIN
		update tBilling set ErrorMsg = ''There is no Default Sales Account for this worksheet and for your company''
		where BillingKey = @TopBillingKey 
		
		RETURN -104			
	END
	
	IF ISNULL(@PaymentTermsKey, 0) > 0
	BEGIN
		SELECT @DueDays = ISNULL(DueDays, 0)
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @PaymentTermsKey
		 	
		SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate) 	
	END
	ELSE
		SELECT @DueDate = @TodaysDate

-- DefaultARApprover 
-- 0 Person Entering the Invoice
-- 1 AE From project
-- 2 Automatically approved ==> set invoice # when SetInvoiceNumberOnApproval = 1
-- 3 Default Approver in tPrefs
-- 4 PM From Project
-- 5 Billing Manager From Project

IF @DefaultARApprover = 0
	SELECT @InvoiceApprover = @UserKey
-- If AE From project, it was already copied to the WS, so take it from WS	
IF @DefaultARApprover = 1
	SELECT @InvoiceApprover = @BillingApprover
-- Automatically approved, set to current user
IF @DefaultARApprover = 2
	SELECT @InvoiceApprover = @UserKey 
-- If default approver from tPrefs
IF @DefaultARApprover = 3
BEGIN
	IF @DefaultARApproverKey > 0 
		SELECT @InvoiceApprover = @DefaultARApproverKey
	ELSE
		SELECT @InvoiceApprover = @UserKey
END
IF @DefaultARApprover = 4
	BEGIN
		SELECT @InvoiceApprover = ProjectManager
		FROM tProject (nolock)
		WHERE ProjectKey = @ProjectKey
		
		--If this is a multi-project BWS, prevent the approver from being blank
		IF ISNULL(@InvoiceApprover, 0) = 0
			SELECT @InvoiceApprover = @UserKey
	END
IF @DefaultARApprover = 5
	BEGIN
		SELECT @InvoiceApprover = BillingManagerKey
		FROM tProject (nolock)
		WHERE ProjectKey = @ProjectKey
		
		--If this is a multi-project BWS, prevent the approver from being blank
		IF ISNULL(@InvoiceApprover, 0) = 0
			SELECT @InvoiceApprover = @UserKey
	END
	/*				
	|| Create an invoice
	*/
	exec @RetVal = sptInvoiceInsert
			@CompanyKey = @CompanyKey,
			@ClientKey = @ClientKey,
			@ContactName = @BillingContact,
			@PrimaryContactKey = @PrimaryContactKey,
			@AddressKey = @AddressKey,
			@AdvanceBill = @AdvanceBill,
			@InvoiceNumber = null,
			@InvoiceDate = @InvoiceDate,
			@DueDate = @DueDate,
			@PostingDate = @PostingDate,
			@TermsKey = @PaymentTermsKey,
			@ARAccountKey = @DefaultARAccountKey,
			@ClassKey = @TopBillingClassKey,
			@ProjectKey = @ProjectKey,
			@HeaderComment = @InvoiceComment,
			@SalesTaxKey = @SalesTaxKey,
			@SalesTax2Key = @SalesTax2Key,
			@InvoiceTemplateKey = @InvoiceTemplateKey,
			@ApprovedByKey = @InvoiceApprover,
			@UserDefined1 = NULL,
			@UserDefined2 = NULL,
			@UserDefined3 = NULL,
			@UserDefined4 = NULL,
			@UserDefined5 = NULL,
			@UserDefined6 = NULL,
			@UserDefined7 = NULL,
			@UserDefined8 = NULL,
			@UserDefined9 = NULL,
			@UserDefined10 = NULL,
			@Downloaded = 0,
			@Printed = 0,
			@ParentInvoice = 0,
			@Emailed = 0,
			@CreatedByKey = @UserKey,
			@GLCompanyKey = @GLCompanyKey,
			@OfficeKey = @OfficeKey,
			@OpeningTransaction = 0,
			@LayoutKey = @LayoutKey,
			@CurrencyID = @CurrencyID,
			@ExchangeRate = 1,
			@RequestExchangeRate = 1,
			@IsForRetainer = 0,
			@LiabilityAccountKey = @LiabilityAccountKey, -- **NEW PARAMETER ADDED HERE**
			@oIdentity = @NewInvoiceKey OUTPUT -- Maps the output variable

	if @@ERROR <> 0 
	  begin
		update tBilling set ErrorMsg = ''An error occurred when creating the invoice'' 
		where BillingKey = @TopBillingKey 
		
		return -5					   	
	  end
	if @RetVal <> 1 
	 begin
		update tBilling set ErrorMsg = ''An error occurred when creating the invoice'' 
		where BillingKey = @TopBillingKey 
		
		return -5					   	
	  end
	 
	 -- used in search for duplicates at the top of the sp spBillingInvoiceBill
	update tInvoice set BillingKey = @TopBillingKey where InvoiceKey = @NewInvoiceKey

	-- (622546 ) Update the approver based on the selection in trans pref / client invoices / default approver
	-- We only care about 4 because the others are handled in sptInvoiceInsert from above
	Declare @PM int -- Project Manager

	if @TopEntity = ''Campaign''
	begin
		update tInvoice
		set    CampaignKey = @TopEntityKey
		where  InvoiceKey = @NewInvoiceKey

		-- If PM From campaign
		if @DefaultARApprover = 4
		begin
			Select @InvoiceApprover = ISNULL(PMKey, @UserKey) from tCampaign (nolock) Where CampaignKey = @TopEntityKey
			if @InvoiceApprover = 0
				Select @InvoiceApprover = @UserKey
		end
	end
	else
	begin
		-- If there is only 1 project for the campaign, there will be no master
		-- so get campaign from the group info on the single billing WS instead
		if @TopGroupEntity = ''Campaign''
		begin
			update tInvoice
			set    CampaignKey = @TopGroupEntityKey
			where  InvoiceKey = @NewInvoiceKey
		end

		-- If PM From campaign
		if @DefaultARApprover = 4
		begin
			Select @InvoiceApprover = ISNULL(PMKey, @UserKey) from tCampaign (nolock) Where CampaignKey = @TopGroupEntityKey
			if @InvoiceApprover = 0
				Select @InvoiceApprover = @UserKey
		end
	end

	if @TopEntity = ''BillingGroup''
	begin
		update tInvoice
		set    BillingGroupKey = @TopEntityKey
		where  InvoiceKey = @NewInvoiceKey
	end
	else
	begin
		-- If there is only 1 project for the campaign, there will be no master
		-- so get campaign from the group info on the single billing WS instead
		if @TopGroupEntity = ''BillingGroup''
		begin
			update tInvoice
			set    BillingGroupKey = @TopGroupEntityKey
			where  InvoiceKey = @NewInvoiceKey
		end
	end

	--update AR account key
	--also bypass normal approval process since it went thru billing ws approval process
	If @CreateAsApproved = 1
	BEGIN
	
		--Check to see if the tInvoice Insert SP set the Invoice Number
		SELECT	@NextTranNo = InvoiceNumber
		FROM	tInvoice (nolock)
		WHERE	InvoiceKey = @NewInvoiceKey
	
		IF @NextTranNo IS NULL
		BEGIN
			--If the InvoiceNumber has not been set yet, get the next number
			DECLARE @TranType varchar(10) = CASE @AdvanceBill WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

			EXEC spGetNextTranNo
				@CompanyKey,
				@TranType,
				@RetVal		      OUTPUT,
				@NextTranNo 	  OUTPUT
				IF @RetVal <> 1
					RETURN -5
		END
	
		update tInvoice
		set ARAccountKey = @DefaultARAccountKey
			,ApprovedByKey = @InvoiceApprover
			,InvoiceStatus = 4 -- Approved
			,InvoiceNumber = @NextTranNo 
		where InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0 
		begin
			update tBilling set ErrorMsg = ''An error occurred when updating the invoice'' 
			where BillingKey = @TopBillingKey 
			exec sptInvoiceDelete @NewInvoiceKey

			return -5					   	
		end
	END
	ELSE
	BEGIN
		update tInvoice
		set ARAccountKey = @DefaultARAccountKey
			,ApprovedByKey = @InvoiceApprover
		where InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0 
		begin
			update tBilling set ErrorMsg = ''An error occurred when updating the invoice'' 
			where BillingKey = @TopBillingKey 
			exec sptInvoiceDelete @NewInvoiceKey

			return -5					   	
		end
	END
		
	/*				
	|| Add child billing worksheets
	*/
  		 	
 /*
 get TopRollup, LayoutKey
 
 TopRollup = 0 - 1 line
           = 1 - By Project/Task
           = 8 - By Project/Billing Item/Item
           = 9 - By Billing Item
 
call spBillingLinesGetItems 

create invoice with LayoutKey
 
// TopRollup = 9 then we should not have FF or retainer, should all be TM projects  
//This is the particular case where all projects are grouped by segments only==> different loop
if TopRollup = 9
begin
	if (count of valid segments) > 0       
	begin
		for each segment	    
			@ParentInvoiceLineKey = 0

			update tWorkTypeCust (segment)
			
			enter a new line for the segment
			get @ParentInvoiceLineKey 
			
			truncate #tran
			for each billing WS/project for the segment
				insert in #tran (spBillingLinesGetTrans)					
			end for
			spBillingLinesGetFromLayout
			spBillingLinesInsert for @ParentInvoiceLineKey
		end for
	end    

	-- project without segment or single project case
	@ParentInvoiceLineKey = 0
	
	update tWorkTypeCust (campaign)
			
	truncate #tran
	for each billing WS/project without segment
		insert in #tran (spBillingLinesGetTrans)					
	end for
	spBillingLinesGetFromLayout
	spBillingLinesInsert for @ParentInvoiceLineKey

end
           
if TopRollup <> 9 and Single Project
begin
	@ParentInvoiceLineKey = 0
	
	get Rollup from BillingMethod
	 
	if Rollup = 8 // Project then BI then Item
	begin
		enter a new line for the project
		get @ParentInvoiceLineKey 

		update tWorkTypeCust (project)
	
		truncate #tran
		for each billing WS/project without segment
			insert in #tran (spBillingLinesGetTrans)					
		end for
		spBillingLinesGetFromLayout
		spBillingLinesInsert for @ParentInvoiceLineKey
	
	end
	
	if Rollup = 1 (task), 4, 5, 6 do as usual
	
end
           

if TopRollup <> 9 and Multiple project
begin
	if (count of valid segments) > 0       
	begin
		for each segment	    
			
			update tWorkTypeCust (segment)
			
			enter a new line for the segment
			get @SegmentParentInvoiceLineKey 
			
			for each billing WS/project for the segment
				enter a line for the project starting at @SegmentParentInvoiceLineKey
				get @ParentInvoiceLineKey
				
				get Rollup
			
				if Rollup = 8
					truncate #tran
					insert in #tran (spBillingLinesGetTrans)					
					spBillingLinesGetFromLayout
					spBillingLinesInsert for @ParentInvoiceLineKey
				end if
				
				if Rollup = 1, 4, 5, 6 do as usual
			
			end for
			
		end for
	end    

	for each billing WS/project without a segment
		enter a line for the project starting at 0
		get @ParentInvoiceLineKey
		
		get Rollup
	
		if Rollup = 8
			truncate #tran
			insert in #tran (spBillingLinesGetTrans)					
			spBillingLinesGetFromLayout
			spBillingLinesInsert for @ParentInvoiceLineKey
		end if
		
		if Rollup = 1, 4, 5, 6 do as usual
	
	end for

end
           
 */ 		 	
  	
 
 exec spBillingLinesGetItems @CompanyKey, null, 0 

 if @TopRollup = @kByBillingItemItem  -- Do not process by project, but by segment only
 begin
	select @SegmentDisplayOrder = -1
	while (1=1)
	begin
		select @SegmentDisplayOrder = Min(SegmentDisplayOrder)
		from   #tCampaignSegment
		where  SegmentDisplayOrder > @SegmentDisplayOrder
		
		if @SegmentDisplayOrder is null
			break
			
		select @CampaignSegmentKey = CampaignSegmentKey
		from   #tCampaignSegment
		where  SegmentDisplayOrder = @SegmentDisplayOrder
			
		exec spBillingLinesUpdateItems ''tCampaignSegment'', @CampaignSegmentKey
		
		-- Create summary line for segment
		select @SegmentName = SegmentName
		from   tCampaignSegment (nolock)
		where  CampaignSegmentKey = @CampaignSegmentKey

		Select @BillingClassKey = 0
		Select @SalesAccountKey = @DefaultSalesAccountKey 
			
		--create single invoice line
		exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,NULL							-- ProjectKey 
					  ,NULL							-- TaskKey
					  ,@SegmentName					-- Line Subject
					  ,NULL                 		-- Line description
					  ,0		      				-- Bill From 
					  ,0							-- Quantity
					  ,0							-- Unit Amount
					  ,0							-- Line Amount
					  ,1							-- line type = Summary
					  ,0							-- parent line key
					  ,NULL --@SalesAccountKey				-- Default Sales AccountKey (displayed on screen)
					  ,@BillingClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,null							-- Work TypeKey
					  ,@PostSalesUsingDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,NULL							-- OfficeKey
					  ,NULL							-- DepartmentKey
					  ,@SegmentParentInvoiceLineKey output

		if @@ERROR <> 0 
		  begin

			update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			exec sptInvoiceDelete @NewInvoiceKey
			return -17					 	
		  end			   		     		 
		if @RetVal <> 1 
		  begin
			update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			exec sptInvoiceDelete @NewInvoiceKey
			return -17					 	
		  end
	
		-- since segments are not in tLayoutBilling, set them to SubItemDetail
		update tInvoiceLine 
		set    DisplayOption = @kDisplayOptionSubItemDetail
		       ,CampaignSegmentKey = @CampaignSegmentKey
		where  InvoiceLineKey = @SegmentParentInvoiceLineKey
		
		truncate table #tran
		
		select @DisplayOrder = -1
		while (1=1)
		begin
			select @DisplayOrder = Min(DisplayOrder)
			from   #tBilling
			where  CampaignSegmentKey = @CampaignSegmentKey
			and    DisplayOrder > @DisplayOrder
			
			if @DisplayOrder is null
				break
				
			select @BillingKey = BillingKey		      
			from   #tBilling
			where  DisplayOrder = @DisplayOrder
			
			exec spBillingLinesGetTrans @BillingKey	  
		end 

		-- we do not have any defaults for the segments
		Select @BillingClassKey = 0
		Select @SalesAccountKey = @DefaultSalesAccountKey 

		if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
			SELECT @BillingClassKey = @DefaultClassKey
		
		exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tCampaignSegment'', @CampaignSegmentKey
			,@DefaultSalesAccountKey,@BillingClassKey,@DefaultClassKey, 0 --@GetItemInfo
		
		--Set Subjetct to TimeRateSheet.InvoiceLabel if exists
		EXEC spBillingLinesUpdateFromRateSheet @ProjectKey
		
		-- project key null here
		exec @RetVal = spBillingLinesInsert @CompanyKey,@NewInvoiceKey,null ,@DefaultSalesAccountKey ,@DefaultClassKey
			,@SegmentParentInvoiceLineKey,@PostSalesUsingDetail, @CampaignSegmentKey
		
		IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	

	end -- segment loop
 

	-- now process the billing  records without a segment
	
	if @TopEntity = ''Campaign''
		exec spBillingLinesUpdateItems ''tCampaign'', @TopEntityKey
	
	truncate table #tran

	select @DisplayOrder = -1
	while (1=1)
	begin
		select @DisplayOrder = Min(DisplayOrder)
		from   #tBilling
		where  CampaignSegmentKey = 0
		and    DisplayOrder > @DisplayOrder
		
		if @DisplayOrder is null
			break
			
		select @BillingKey = BillingKey		      
		from   #tBilling
		where  DisplayOrder = @DisplayOrder
		
		exec spBillingLinesGetTrans @BillingKey	  
	end 

	-- we do not have any defaults 
	Select @BillingClassKey = 0
	Select @SalesAccountKey = @DefaultSalesAccountKey 

	if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
		SELECT @BillingClassKey = @DefaultClassKey
	
	if @TopEntity = ''Campaign''
		exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tCampaign'', @TopEntityKey
			,@DefaultSalesAccountKey,@BillingClassKey,@DefaultClassKey, 0 --@GetItemInfo 
	else
		exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, null, 0
			,@DefaultSalesAccountKey,@BillingClassKey,@DefaultClassKey, 0 --@GetItemInfo
	
	--Set Subjetct to TimeRateSheet.InvoiceLabel if exists
	EXEC spBillingLinesUpdateFromRateSheet @ProjectKey
	
	-- the lines will be under the root
	select @ParentInvoiceLineKey = 0
	
	-- project key null here
	EXEC @RetVal = spBillingLinesInsert @CompanyKey, @NewInvoiceKey, @ProjectKey, @DefaultSalesAccountKey, @DefaultClassKey
		,@ParentInvoiceLineKey,@PostSalesUsingDetail

	IF @RetVal < 0
		BEGIN
			update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			EXEC sptInvoiceDelete @NewInvoiceKey
			RETURN @RetVal
		END	

	IF ISNULL(@BillingStatusKey, 0) > 0
	BEGIN
		UPDATE tProject
		SET    tProject.ProjectBillingStatusKey = @BillingStatusKey
		FROM   #tBilling 
		WHERE  tProject.ProjectKey = #tBilling.ProjectKey
	END

 
 end -- @TopRollup = @kByBillingItemItem 		 	
  		 	
 -- Single project 		 	
 if @TopRollup <> @kByBillingItemItem and @SingleProjectMode = 1
 begin
		SELECT @ProjectLineAdded = 0

		SELECT @ParentInvoiceLineKey = 0
		SELECT @ProjectKey = b.ProjectKey
			   ,@Rollup = CASE ISNULL(b.DefaultARLineFormat, 0) WHEN 9 THEN @TopRollup ELSE ISNULL(b.DefaultARLineFormat, 0) END -- Default is 1 line per Project 
	    	   ,@BillingMethod = b.BillingMethod
			   ,@ProjectName = ISNULL(p.ProjectName, c.CampaignName)
			   ,@ShowTransactionsOnInvoices = isnull(p.ShowTransactionsOnInvoices, 0) -- for Etna customization
			   ,@FixedFeeDisplay = ISNULL(b.FixedFeeDisplay, 1) -- Default is ONE invoice line
			   ,@SalesAccountKey = ISNULL(b.DefaultSalesAccountKey, 0) -- Can be null or 0	
			   ,@EstimateKey = b.EstimateKey -- For FF
		       ,@BillingClassKey = ISNULL(b.ClassKey, 0)
			   ,@FixedFeeAddProjectLine = ISNULL(b.FixedFeeAddProjectLine,0)
		FROM   tBilling b (NOLOCK)
			LEFT OUTER JOIN tProject p (NOLOCK) ON b.ProjectKey = p.ProjectKey
			LEFT OUTER JOIN tCampaign c (nolock) ON b.CampaignKey = c.CampaignKey
		WHERE  b.BillingKey = @TopBillingKey

		-- in single project mode, billing key is the top one
		select @BillingKey = @TopBillingKey

		if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
			Select @SalesAccountKey = @DefaultSalesAccountKey 

		if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
			SELECT @BillingClassKey = @DefaultClassKey

		-- If retainer, ignore line format/rollup and set up a dummy rollup
		IF @BillingMethod = 3
			SELECT @Rollup = 4
		
		-- If FF, it will depend on FixedFeeDisplay	
		IF @BillingMethod = 2
		BEGIN
			IF @FixedFeeDisplay = 1
				SELECT @FixedFeeRollup = @kByOneLine 	-- There is just a line in tBillingFixedFee for Entity = ''tEstimate''  
			ELSE IF @FixedFeeDisplay = 2 
				SELECT @FixedFeeRollup = @kFFByTask 	-- By Task
			ELSE IF @FixedFeeDisplay = 3
				SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Service Item or by Billing Item
			ELSE IF @FixedFeeDisplay = 4
				SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Billing Item
			ELSE IF @FixedFeeDisplay = 5
				SELECT @FixedFeeRollup = @kFFByProject		-- By Project
			ELSE
				SELECT @FixedFeeRollup = @kFFByServiceItem 
						
		END	

		-- This is obsolete (removed for 237117, readded for 341368 because we created a new format by service / item for 237117)
		--if @Rollup = @kByProjectService
		--	Select @Rollup = @kByProjectBillingItemItem
		--Except: the option was never removed from BWS and it is still respected for non-Layout Invoices; made no sense to take away for only Layouts
		
		if @Rollup = @kByProjectBillingItem
			Select @Rollup = @kByProjectBillingItemItem
		
		-- For issue 437259 process the Fixed Fee recs first

		/*--
		|| Fixed Fee by Task
		*/--		
		if @BillingMethod = @kFFBillingMethod And @FixedFeeRollup = @kFFByTask 
		begin
				if (@BillingMethod = @kFFBillingMethod and @FixedFeeAddProjectLine = 1)
				begin
					--create single invoice line
					exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
															-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
															-- (GHL 4/23/10 put it back for custom fields)
							  ,@ProjectKey					-- ProjectKey 
							  ,NULL							-- TaskKey
							  ,@ProjectName					-- Line Subject
							  ,NULL                 		-- Line description
							  ,0		      				-- Bill From 
							  ,0							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type = Summary
							  ,0							-- parent line key
							  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
							  ,@BillingClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,@WorkTypeKey					-- Work TypeKey
							  ,@PostSalesUsingDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DepartmentKey
							  ,@ParentInvoiceLineKey output

				if @@ERROR <> 0 
				  begin

					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end			   		     		 
				if @RetVal <> 1 
				  begin
					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end
		
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey
			end

			exec @RetVal = spBillingInvoiceOneLinePerTaskFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@ProjectKey, @SalesAccountKey , @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey
				,@EstimateKey
				
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		/*--
		|| Fixed Fee by Service/Item
		*/--		
		if @BillingMethod = @kFFBillingMethod And @FixedFeeRollup = @kFFByServiceItem 
		begin
			-- 561987 should work for campaign also
			--if isnull(@ProjectKey,0) > 0 and @FixedFeeAddProjectLine = 1
			if @FixedFeeAddProjectLine = 1
			begin
				-- Create summary line for project
				exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
															-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
															-- (GHL 4/23/10 put it back for custom fields)
							  ,@ProjectKey					-- ProjectKey 
							  ,NULL							-- TaskKey
							  ,@ProjectName					-- Line Subject
							  ,NULL                 		-- Line description
							  ,0		      				-- Bill From 
							  ,0							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type = Summary
							  ,0							-- parent line key
							  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
							  ,@BillingClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,@WorkTypeKey					-- Work TypeKey
							  ,@PostSalesUsingDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DepartmentKey
							  ,@ParentInvoiceLineKey output

				if @@ERROR <> 0 
				  begin

					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end			   		     		 
				if @RetVal <> 1 
				  begin
					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end

				  -- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey

				 select @ProjectLineAdded = 1

			end

			exec @RetVal = spBillingInvoiceOneLinePerServiceItemFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@ProjectKey, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey, @EstimateKey
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	
		  		

	    /*
		|| Fixed Fee by Project
		*/		
		if @BillingMethod = @kFFBillingMethod And @FixedFeeRollup = @kFFByProject
		begin
			exec @RetVal = spBillingInvoiceOneLinePerProjectFF @CompanyKey, @NewInvoiceKey ,@BillingKey , @ParentInvoiceLineKey 
				, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per project for a fixed fee campaign worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end		

		/*--
		|| Fixed Fee One Line
		*/--				
		IF @BillingMethod = @kFFBillingMethod And @FixedFeeRollup = @kByOneLine						
		BEGIN
			-- Pass 2 as @BillingMethod to indicate tBillingFixedFee records
			EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 2, @ProjectKey 
			,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail	
			,@EstimateKey

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	
		END
		
		if @Rollup = @kByProjectBillingItemItem
		begin
			if (@BillingMethod = @kTMBillingMethod and @ProjectLineAdded = 0) OR (@BillingMethod = @kFFBillingMethod and @FixedFeeAddProjectLine = 1 and @ProjectLineAdded = 0)
			begin
				-- Create summary line for project
				--create single invoice line
				exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
															-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
															-- (GHL 4/23/10 put it back for custom fields)
							  ,@ProjectKey					-- ProjectKey 
							  ,NULL							-- TaskKey
							  ,@ProjectName					-- Line Subject
							  ,NULL                 		-- Line description
							  ,0		      				-- Bill From 
							  ,0							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type = Summary
							  ,0							-- parent line key
							  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
							  ,@BillingClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,@WorkTypeKey					-- Work TypeKey
							  ,@PostSalesUsingDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DepartmentKey
							  ,@ParentInvoiceLineKey output

				if @@ERROR <> 0 
				  begin

					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end			   		     		 
				if @RetVal <> 1 
				  begin
					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end
		
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey
			end

			-- Billing Item desc
			exec spBillingLinesUpdateItems ''tProject'', @ProjectKey
			
			truncate table #tran
			exec spBillingLinesGetTrans @TopBillingKey	  
			 
			if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
				Select @SalesAccountKey = @DefaultSalesAccountKey 

			if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
				SELECT @BillingClassKey = @DefaultClassKey
	
			exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tProject'', @ProjectKey
				,@DefaultSalesAccountKey,@BillingClassKey,@DefaultClassKey, 0 --@GetItemInfo
				
			--Set Subjetct to TimeRateSheet.InvoiceLabel if exists
			EXEC spBillingLinesUpdateFromRateSheet @ProjectKey
			
			exec @RetVal = spBillingLinesInsert @CompanyKey,@NewInvoiceKey,@ProjectKey ,@DefaultSalesAccountKey ,@DefaultClassKey
				,@ParentInvoiceLineKey,@PostSalesUsingDetail

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	

		end -- Rollup @kByProjectBillingItemItem 


		/*	--
		|| Handle single invoice line
		*/ --	
		IF @Rollup <= @kByOneLine					
		BEGIN
			-- Pass 1 instead of @BillingMethod to indicate tBillingDetail records
			EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 1, @ProjectKey 
			,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail
			,@EstimateKey	

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	

			IF @RetVal > 0 
			begin
				 -- Customization for Etna
				 if @ShowTransactionsOnInvoices = 1
					begin
						update tInvoiceLine
						set    DisplayOption = @kDisplayOptionTransactions
						where  InvoiceLineKey = @RetVal
					end
				else
				begin
					-- for the others, set the 1 line display option as the project option (issue 366171)
					-- we could also limit this if we have a project only (i.e. not a retainer line)
					update tInvoiceLine
					set    DisplayOption = @LayoutProjectDisplayOption 
					where  InvoiceLineKey = @RetVal
				end

			end
			
		END	
		
		/* --
		|| Handle invoice lines by Task
		*/ --		
		if @Rollup = @kByProjectTask 
		begin
			if (@BillingMethod = @kTMBillingMethod and @ProjectLineAdded = 0) OR (@BillingMethod = @kFFBillingMethod and @FixedFeeAddProjectLine = 1 and @ProjectLineAdded = 0)
			begin
				-- Create summary line for project
			
				--create single invoice line
				exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
															-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
															-- (GHL 4/23/10 put it back for custom fields)
							  ,@ProjectKey					-- ProjectKey 
							  ,NULL							-- TaskKey
							  ,@ProjectName					-- Line Subject
							  ,NULL                 		-- Line description
							  ,0		      				-- Bill From 
							  ,0							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type = Summary
							  ,0							-- parent line key
							  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
							  ,@BillingClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,@WorkTypeKey					-- Work TypeKey
							  ,@PostSalesUsingDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DepartmentKey
							  ,@ParentInvoiceLineKey output

				if @@ERROR <> 0 
				  begin

					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end			   		     		 
				if @RetVal <> 1 
				  begin
					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end
		
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey
			end

			exec @RetVal = spBillingInvoiceOneLinePerTask @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
				
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
			
			exec @RetVal = sptInvoiceLineApplyTaskOptions @NewInvoiceKey
			--put hours & rate on Invoice lines
			EXEC sptInvoiceLineSetHours @NewInvoiceKey
		end

		/*
		|| Handle invoice lines by Service (One line for expenses)
		*/		
		if @Rollup = @kByProjectService
		begin
			if (@BillingMethod = @kTMBillingMethod and @ProjectLineAdded = 0) OR (@BillingMethod = @kFFBillingMethod and @FixedFeeAddProjectLine = 1 and @ProjectLineAdded = 0)
			begin
				-- Create summary line for project
			
				--create single invoice line
				exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
															-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
															-- (GHL 4/23/10 put it back for custom fields)
							  ,@ProjectKey					-- ProjectKey 
							  ,NULL							-- TaskKey
							  ,@ProjectName					-- Line Subject
							  ,NULL                 		-- Line description
							  ,0		      				-- Bill From 
							  ,0							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type = Summary
							  ,0							-- parent line key
							  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
							  ,@BillingClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,@WorkTypeKey					-- Work TypeKey
							  ,@PostSalesUsingDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DepartmentKey
							  ,@ParentInvoiceLineKey output

				if @@ERROR <> 0 
				  begin

					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end			   		     		 
				if @RetVal <> 1 
				  begin
					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end
		
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey
			end

			exec @RetVal = spBillingInvoiceOneLinePerService @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end
		 	
		/*
		|| Handle invoice lines by Service/Item (One line per item for expenses) 
		*/
		if @Rollup = @kByProjectServiceOrItem
		begin
			if (@BillingMethod = @kTMBillingMethod and @ProjectLineAdded = 0) OR (@BillingMethod = @kFFBillingMethod and @FixedFeeAddProjectLine = 1 and @ProjectLineAdded = 0)
			begin
				-- Create summary line for project
				--create single invoice line
				exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
															-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
															-- (GHL 4/23/10 put it back for custom fields)
							  ,@ProjectKey					-- ProjectKey 
							  ,NULL							-- TaskKey
							  ,@ProjectName					-- Line Subject
							  ,NULL                 		-- Line description
							  ,0		      				-- Bill From 
							  ,0							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type = Summary
							  ,0							-- parent line key
							  ,null -- @SalesAccountKey				-- Default Sales AccountKey (because displayed on screen)
							  ,@BillingClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,@WorkTypeKey					-- Work TypeKey
							  ,@PostSalesUsingDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DepartmentKey
							  ,@ParentInvoiceLineKey output

				if @@ERROR <> 0 
				  begin

					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end			   		     		 
				if @RetVal <> 1 
				  begin
					update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					exec sptInvoiceDelete @NewInvoiceKey
					return -17					 	
				  end
		
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey
			end

			exec @RetVal = spBillingInvoiceOneLinePerServiceItem @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
				
			EXEC sptInvoiceLineSetHours @NewInvoiceKey
			EXEC sptInvoiceLineSetExpenses @NewInvoiceKey
		end

		/*--
		|| Handle invoice line for the retainer amount
		*/--		
		if @Rollup = @kByRetainer 
		begin
			exec @RetVal = spBillingInvoiceRetainer @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@SalesAccountKey , @BillingClassKey, @WorkTypeKey, @InvoiceDate
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a retainer'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		IF ISNULL(@BillingStatusKey, 0) > 0
		BEGIN
			UPDATE tProject
			SET    ProjectBillingStatusKey = @BillingStatusKey
			WHERE  ProjectKey = @ProjectKey
		END


		/*	--
		|| Handle invoice lines per title for Abelson Taylor
		*/ --	
		IF @Rollup in ( @kByProjectTitle, @kByProjectTitleService, @kByProjectServiceTitle)					
		BEGIN

			EXEC @RetVal = spBillingInvoiceOneLinePerTitle @NewInvoiceKey, @BillingKey, @Rollup, @ProjectKey 
			,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @PostSalesUsingDetail, @ParentInvoiceLineKey

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per title for a worksheet''  
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	

		END	


 end -- Single Project case		 	
 
 -- Multiple Project mode
 if @TopRollup <> @kByBillingItemItem  and @SingleProjectMode = 0
 begin
	-- If there is a FF Campaign, place it at the top of the invoice
	if @IsFFCampaign = 1
	begin
		SELECT @BillingKey = b.BillingKey
		FROM   #tBilling b (NOLOCK)
		where  CampaignKey > 0

		SELECT @ProjectKey = b.ProjectKey
				,@Rollup = ISNULL(b.DefaultARLineFormat, 0) -- Default is 1 line per Project 
				,@BillingMethod = b.BillingMethod
				,@ProjectName = isnull(p.ProjectName, c.CampaignName)
				,@ShowTransactionsOnInvoices = isnull(p.ShowTransactionsOnInvoices, 0) -- Customization for Etna
				,@FixedFeeDisplay = ISNULL(b.FixedFeeDisplay, 1) -- Default is ONE invoice line
				,@SalesAccountKey = ISNULL(b.DefaultSalesAccountKey, 0) -- Can be null or 0	
				,@EstimateKey = b.EstimateKey -- For FF
				,@BillingClassKey = ISNULL(b.ClassKey, 0)
		FROM   tBilling b (NOLOCK)
			LEFT OUTER JOIN tProject p (NOLOCK) ON b.ProjectKey = p.ProjectKey
			LEFT OUTER JOIN tCampaign c (NOLOCK) ON b.CampaignKey = c.CampaignKey
		WHERE  b.BillingKey = @BillingKey

		if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
			Select @SalesAccountKey = @DefaultSalesAccountKey 

		if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
			SELECT @BillingClassKey = @DefaultClassKey

		-- overwrite Rollup from the master WS--it may be changed later based on FF or retainer
		select @Rollup = @TopRollup

		-- If retainer, ignore line format/rollup and set up a dummy rollup
		IF @BillingMethod = 3
			SELECT @Rollup = 4
			
		-- If FF, it will depend on FixedFeeDisplay	
		IF @BillingMethod = 2
		BEGIN
			IF @FixedFeeDisplay = 1
				SELECT @FixedFeeRollup = @kByOneLine 	-- There is just a line in tBillingFixedFee for Entity = ''tEstimate''  
			ELSE IF @FixedFeeDisplay = 2 
				SELECT @FixedFeeRollup = @kFFByTask 	-- By Task
			ELSE IF @FixedFeeDisplay = 3
				SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Service Item or by Billing Item
			ELSE IF @FixedFeeDisplay = 4
				SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Billing Item
			ELSE IF @FixedFeeDisplay = 5
				SELECT @FixedFeeRollup = @kFFByProject 	-- By Project
			ELSE
				SELECT @FixedFeeRollup = @kFFByServiceItem 
							
		END	

		-- This is obsolete (re-enabled for 237117)
		--if @Rollup = @kByProjectService
		--	Select @Rollup = @kByProjectBillingItemItem

		if @Rollup = @kByProjectBillingItem
			Select @Rollup = @kByProjectBillingItemItem

		-- Create summary line for project
		select @ShowExtraProjectLine = 0
		if  @Rollup > @kByOneLine -- only if we do not have a one line 
			select @ShowExtraProjectLine =1
		if @BillingMethod = 2 and @FixedFeeRollup > @kByOneLine
			select @ShowExtraProjectLine =1

		if  @ShowExtraProjectLine =1 And @ProjectName is not null
		begin
				
			--create single invoice line
			exec @RetVal = sptInvoiceLineInsertMassBilling
						@NewInvoiceKey				-- Invoice Key
													-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
													-- (GHL 4/23/10 put it back for custom fields)
						,@ProjectKey					-- ProjectKey 
						,NULL							-- TaskKey
						,@ProjectName					-- Line Subject
						,NULL                 		-- Line description
						,0		      				-- Bill From 
						,0							-- Quantity
						,0							-- Unit Amount
						,0							-- Line Amount
						,1							-- line type = Summary
						,0							-- parent line key, important here must be under the root
						,null -- @SalesAccountKey				-- Default Sales AccountKey (displayed on screen)
						,@BillingClassKey             -- Class Key
						,0							-- Taxable
						,0							-- Taxable2
						,@WorkTypeKey					-- Work TypeKey
						,@PostSalesUsingDetail
						,NULL							-- Entity
						,NULL							-- EntityKey
						,NULL							-- OfficeKey
						,NULL							-- DepartmentKey
						,@ParentInvoiceLineKey output

		if @@ERROR <> 0 
			begin

			update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			exec sptInvoiceDelete @NewInvoiceKey
			return -17					 	
			end			   		     		 
		if @RetVal <> 1 
			begin
			update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			exec sptInvoiceDelete @NewInvoiceKey
			return -17					 	
			end
		
			-- DisplayOption from tLayoutBilling must be set for the project
			update tInvoiceLine 
			set    DisplayOption = @LayoutProjectDisplayOption
					,CampaignSegmentKey = @CampaignSegmentKey	
			where  InvoiceLineKey = @ParentInvoiceLineKey
			  
		end -- project summary line 
		else
		begin
			select @ParentInvoiceLineKey = 0
		end
			
		/*--
		|| Fixed Fee by Task
		*/--		
		if @BillingMethod =2 and @FixedFeeRollup = @kFFByTask 
		begin
			exec @RetVal = spBillingInvoiceOneLinePerTaskFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@ProjectKey, @SalesAccountKey , @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey
				,@EstimateKey
					
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		/*--
		|| Fixed Fee by Service/Item
		*/--		
		if @BillingMethod =2 and @FixedFeeRollup = @kFFByServiceItem 
		begin
			exec @RetVal = spBillingInvoiceOneLinePerServiceItemFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@ProjectKey, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey, @EstimateKey
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	
			  
		/*
		|| Fixed Fee by Project
		*/		
		if @BillingMethod = 2 And @FixedFeeRollup = @kFFByProject
		begin
			exec @RetVal = spBillingInvoiceOneLinePerProjectFF @CompanyKey, @NewInvoiceKey ,@BillingKey , @ParentInvoiceLineKey 
				, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per project for a fixed fee campaign worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end		

		/*--
		|| Fixed Fee on one invoice line
		*/--	
		if @BillingMethod =2 and @FixedFeeRollup =	@kByOneLine					
		BEGIN
			-- Pass 2 to indicate tBillingFixedFee records
			EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 2, @ProjectKey 
			,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail	
			,@EstimateKey

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	
		END	


	end -- END FF Campaign


	select @SegmentDisplayOrder = -1
	while (1=1)
	begin
		select @SegmentDisplayOrder = Min(SegmentDisplayOrder)
		from   #tCampaignSegment
		where  SegmentDisplayOrder > @SegmentDisplayOrder
		
		if @SegmentDisplayOrder is null
			break
			
		select @CampaignSegmentKey = CampaignSegmentKey
		from   #tCampaignSegment
		where  SegmentDisplayOrder = @SegmentDisplayOrder
			
		exec spBillingLinesUpdateItems ''tCampaignSegment'', @CampaignSegmentKey
		
		-- Create summary line for segment
		select @SegmentName = SegmentName
		from   tCampaignSegment (nolock)
		where  CampaignSegmentKey = @CampaignSegmentKey
			
		Select @BillingClassKey = 0
		Select @SalesAccountKey = @DefaultSalesAccountKey 
			
		--create single invoice line
		exec @RetVal = sptInvoiceLineInsertMassBilling
					   @NewInvoiceKey				-- Invoice Key
					  ,NULL							-- ProjectKey 
					  ,NULL							-- TaskKey
					  ,@SegmentName					-- Line Subject
					  ,NULL                 		-- Line description
					  ,0		      				-- Bill From 
					  ,0							-- Quantity
					  ,0							-- Unit Amount
					  ,0							-- Line Amount
					  ,1							-- line type = Summary
					  ,0							-- parent line key
					  ,null --@SalesAccountKey				-- Default Sales AccountKey (displayed on screen)
					  ,@BillingClassKey             -- Class Key
					  ,0							-- Taxable
					  ,0							-- Taxable2
					  ,null							-- Work TypeKey
					  ,@PostSalesUsingDetail
					  ,NULL							-- Entity
					  ,NULL							-- EntityKey
					  ,NULL							-- OfficeKey
					  ,NULL							-- DepartmentKey
					  ,@SegmentParentInvoiceLineKey output

		if @@ERROR <> 0 
		  begin

			update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			exec sptInvoiceDelete @NewInvoiceKey
			return -17					 	
		  end			   		     		 
		if @RetVal <> 1 
		  begin
			update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
			where BillingKey = @TopBillingKey 

			exec sptInvoiceDelete @NewInvoiceKey
			return -17					 	
		  end
				
		--Segments treated the same as Campaign/Project
		update tInvoiceLine 
		set    DisplayOption = @LayoutProjectDisplayOption
		      ,CampaignSegmentKey = @CampaignSegmentKey
		where  InvoiceLineKey = @SegmentParentInvoiceLineKey
				
		select @DisplayOrder = -1
		while (1=1)
		begin
			select @DisplayOrder = Min(DisplayOrder)
			from   #tBilling
			where  CampaignSegmentKey = @CampaignSegmentKey
			and    DisplayOrder > @DisplayOrder
			
			if @DisplayOrder is null
				break
			
			SELECT @BillingKey = BillingKey
			FROM   #tBilling (NOLOCK)
			WHERE  DisplayOrder = @DisplayOrder
	
			SELECT @ProjectKey = b.ProjectKey
				   ,@Rollup = ISNULL(b.DefaultARLineFormat, 0) -- Default is 1 line per Project 
				   ,@BillingMethod = b.BillingMethod
				   ,@ProjectName = isnull(p.ProjectName, c.CampaignName)
				   ,@ShowTransactionsOnInvoices = isnull(p.ShowTransactionsOnInvoices, 0) -- Customization for Etna
				   ,@FixedFeeDisplay = ISNULL(b.FixedFeeDisplay, 1) -- Default is ONE invoice line
				   ,@SalesAccountKey = ISNULL(b.DefaultSalesAccountKey, 0) -- Can be null or 0	
				   ,@EstimateKey = b.EstimateKey -- For FF
				   ,@BillingClassKey = ISNULL(b.ClassKey, 0)
				   ,@FixedFeeAddProjectLine = ISNULL(b.FixedFeeAddProjectLine,0)
			FROM   tBilling b (NOLOCK)
				LEFT OUTER JOIN tProject p (NOLOCK) ON b.ProjectKey = p.ProjectKey
				LEFT OUTER JOIN tCampaign c (NOLOCK) ON b.CampaignKey = c.CampaignKey
			WHERE  b.BillingKey = @BillingKey

			if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
				Select @SalesAccountKey = @DefaultSalesAccountKey 

			if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
				SELECT @BillingClassKey = @DefaultClassKey

			-- overwrite Rollup from the master WS--it may be changed later based on FF or retainer
			select @Rollup = @TopRollup

			-- If retainer, ignore line format/rollup and set up a dummy rollup
			IF @BillingMethod = 3
				SELECT @Rollup = 4
			
			-- If FF, it will depend on FixedFeeDisplay	
			IF @BillingMethod = 2
			BEGIN
				IF @FixedFeeDisplay = 1
					SELECT @FixedFeeRollup = @kByOneLine 	-- There is just a line in tBillingFixedFee for Entity = ''tEstimate''  
				ELSE IF @FixedFeeDisplay = 2 
					SELECT @FixedFeeRollup = @kFFByTask 	-- By Task
				ELSE IF @FixedFeeDisplay = 3
					SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Service Item or by Billing Item
				ELSE IF @FixedFeeDisplay = 4
					SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Billing Item
				ELSE IF @FixedFeeDisplay = 5
					SELECT @FixedFeeRollup = @kFFByProject 	-- By Project
				ELSE
					SELECT @FixedFeeRollup = @kFFByServiceItem 
							
			END	

			-- This is obsolete (re-enabled for 237117)
			--if @Rollup = @kByProjectService
			--	Select @Rollup = @kByProjectBillingItemItem

			if @Rollup = @kByProjectBillingItem
				Select @Rollup = @kByProjectBillingItemItem

			-- Create summary line for project
			select @ShowExtraProjectLine = 0
			if  @Rollup > @kByOneLine -- only if we do not have a one line 
				select @ShowExtraProjectLine =1
			if @BillingMethod = 2 and @FixedFeeRollup > @kByOneLine
				select @ShowExtraProjectLine =1

			-- If the user asked for an extra project line
			-- 561987 should work for campaigns also
			--if @BillingMethod = 2 and @FixedFeeRollup = @kFFByServiceItem and @ProjectKey > 0 and @FixedFeeAddProjectLine = 1
			if @BillingMethod = 2 and @FixedFeeRollup = @kFFByServiceItem and @FixedFeeAddProjectLine = 1
				select @ShowExtraProjectLine =1

			if  @ShowExtraProjectLine =1 And @ProjectName is not null
			begin
				
			--create single invoice line
			exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
														-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
														-- (GHL 4/23/10 put it back for custom fields)
						  ,@ProjectKey					-- ProjectKey 
						  ,NULL							-- TaskKey
						  ,@ProjectName					-- Line Subject
						  ,NULL                 		-- Line description
						  ,0		      				-- Bill From 
						  ,0							-- Quantity
						  ,0							-- Unit Amount
						  ,0							-- Line Amount
						  ,1							-- line type = Summary
						  ,@SegmentParentInvoiceLineKey	-- parent line key, important here must be under segment
						  ,null -- @SalesAccountKey				-- Default Sales AccountKey (displayed on screen)
						  ,@BillingClassKey             -- Class Key
						  ,0							-- Taxable
						  ,0							-- Taxable2
						  ,@WorkTypeKey					-- Work TypeKey
						  ,@PostSalesUsingDetail
						  ,NULL							-- Entity
						  ,NULL							-- EntityKey
						  ,NULL							-- OfficeKey
						  ,NULL							-- DepartmentKey
						  ,@ParentInvoiceLineKey output

			if @@ERROR <> 0 
			  begin

				update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				exec sptInvoiceDelete @NewInvoiceKey
				return -17					 	
			  end			   		     		 
			if @RetVal <> 1 
			  begin
				update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				exec sptInvoiceDelete @NewInvoiceKey
				return -17					 	
			  end
		
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
					   ,CampaignSegmentKey = @CampaignSegmentKey	
				where  InvoiceLineKey = @ParentInvoiceLineKey
			  
			end -- project summary line 
			else
			begin
				select @ParentInvoiceLineKey = @SegmentParentInvoiceLineKey
			end
			
			/*--
			|| Fixed Fee by Task
			*/--		
			if @BillingMethod =2 and @FixedFeeRollup = @kFFByTask 
			begin
				exec @RetVal = spBillingInvoiceOneLinePerTaskFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
					,@ProjectKey, @SalesAccountKey , @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey
					,@EstimateKey
					
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a fixed fee worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end			  	

			/*--
			|| Fixed Fee by Service/Item
			*/--		
			if @BillingMethod =2 and @FixedFeeRollup = @kFFByServiceItem 
			begin
				exec @RetVal = spBillingInvoiceOneLinePerServiceItemFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
					,@ProjectKey, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey, @EstimateKey
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a fixed fee worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end			  	
			  
			 /*
			|| Fixed Fee by Project
			*/		
			if @BillingMethod = 2 And @FixedFeeRollup = @kFFByProject
			begin
				exec @RetVal = spBillingInvoiceOneLinePerProjectFF @CompanyKey, @NewInvoiceKey ,@BillingKey , @ParentInvoiceLineKey 
					, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per project for a fixed fee campaign worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end		

			/*--
			|| Fixed Fee on one invoice line
			*/--	
			if @BillingMethod =2 and @FixedFeeRollup =	@kByOneLine					
			BEGIN
				-- Pass 2 to indicate tBillingFixedFee records
				EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 2, @ProjectKey 
				,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail	
				,@EstimateKey

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a fixed fee worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	
			END	

			if @Rollup = @kByProjectBillingItemItem
			begin
				exec spBillingLinesUpdateItems ''tProject'', @ProjectKey
				
				truncate table #tran
				exec spBillingLinesGetTrans @BillingKey	  
				 
				if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
					Select @SalesAccountKey = @DefaultSalesAccountKey 

				if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
					SELECT @BillingClassKey = @DefaultClassKey
		
				exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tCampaignSegment'', @CampaignSegmentKey
					,@DefaultSalesAccountKey,@BillingClassKey,@DefaultClassKey, 0 --@GetItemInfo
				
				--Set Subjetct to TimeRateSheet.InvoiceLabel if exists
				EXEC spBillingLinesUpdateFromRateSheet @ProjectKey
				
				exec @RetVal = spBillingLinesInsert @CompanyKey,@NewInvoiceKey,@ProjectKey ,@DefaultSalesAccountKey ,@DefaultClassKey
					,@ParentInvoiceLineKey,@PostSalesUsingDetail, @CampaignSegmentKey

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	

			end -- Rollup @kByProjectBillingItemItem 


			/*	--
			|| Handle single invoice line
			*/ --	
			IF @Rollup <= @kByOneLine						
			BEGIN
				-- if there is a FF campaign, specify expenses for projects
				If @IsFFCampaign = 1 and isnull(@ProjectKey,0) > 0
					select @ProjectName = @ProjectName + '' Expenses''

				EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 1, @ProjectKey 
				,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail
				,@EstimateKey	

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	

				IF @RetVal > 0 
				begin
					-- Customization for Etna
					if @ShowTransactionsOnInvoices = 1
					begin
						update tInvoiceLine
						set    DisplayOption = @kDisplayOptionTransactions
						where  InvoiceLineKey = @RetVal
					end
					else
					begin
						-- for the others, set the 1 line display option as the project option (issue 366171)
						update tInvoiceLine
						set    DisplayOption = @LayoutProjectDisplayOption 
						where  InvoiceLineKey = @RetVal
					end
				end

			END	
			
			/* --
			|| Handle invoice lines by Task
			*/ --		
			if @Rollup = @kByProjectTask 
			begin
				exec @RetVal = spBillingInvoiceOneLinePerTask @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
					,@SalesAccountKey , @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
					
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
				
				exec @RetVal = sptInvoiceLineApplyTaskOptions @NewInvoiceKey
				--put hours & rate on Invoice lines
				EXEC sptInvoiceLineSetHours @NewInvoiceKey
			end


			/*
			|| Handle invoice lines by Service (One line for expenses)
			*/		
			if @Rollup = @kByProjectService
			begin
				exec @RetVal = spBillingInvoiceOneLinePerService @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
					,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end
			  	
			/*
			|| Handle invoice lines by Service/Item (One line per item for expenses) 
			*/		
			if @Rollup = @kByProjectServiceOrItem
			begin
				exec @RetVal = spBillingInvoiceOneLinePerServiceItem @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
					,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey  -- many not necessary because it may be deleted by prev sp
					return @RetVal
				end
				
				EXEC sptInvoiceLineSetHours @NewInvoiceKey
				EXEC sptInvoiceLineSetExpenses @NewInvoiceKey
			end

			/*--
			|| Handle invoice line for the retainer amount
			*/--		
			if @Rollup = @kByRetainer 
			begin
				exec @RetVal = spBillingInvoiceRetainer @NewInvoiceKey ,@BillingKey, @BillingMethod 
					,@SalesAccountKey , @BillingClassKey, @WorkTypeKey, @InvoiceDate
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a retainer'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end			  	

			/*	--
			|| Handle invoice lines per title for Abelson Taylor
			*/ --	
			IF @Rollup in ( @kByProjectTitle, @kByProjectTitleService, @kByProjectServiceTitle)					
			BEGIN

				EXEC @RetVal = spBillingInvoiceOneLinePerTitle @NewInvoiceKey, @BillingKey, @Rollup, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @PostSalesUsingDetail, @ParentInvoiceLineKey

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per title for a worksheet''  
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	

			END	


		end -- billing rec/project per segment
		
	end -- segment loop
 

	-- now process the billing  records without a segment
	
	if @TopEntity = ''Campaign''
		exec spBillingLinesUpdateItems ''tCampaign'', @TopEntityKey
	
	select @DisplayOrder = -1
		while (1=1)
		begin
			select @DisplayOrder = Min(DisplayOrder)
			from   #tBilling
			where  CampaignSegmentKey = 0
			and    isnull(CampaignKey, 0) = 0 -- it was already processed at the top
			and    DisplayOrder > @DisplayOrder
			
			if @DisplayOrder is null
				break
			
			SELECT @BillingKey = BillingKey
			FROM   #tBilling (NOLOCK)
			WHERE  DisplayOrder = @DisplayOrder
	
			SELECT @ProjectKey = b.ProjectKey
				   ,@Rollup = ISNULL(b.DefaultARLineFormat, 0) -- Default is 1 line per Project 
	    		   ,@BillingMethod = b.BillingMethod
				   ,@ProjectName = isnull(p.ProjectName, c.CampaignName)
				   ,@ShowTransactionsOnInvoices = isnull(ShowTransactionsOnInvoices, 0) -- Customizatiom for Etna
				   ,@FixedFeeDisplay = ISNULL(b.FixedFeeDisplay, 1) -- Default is ONE invoice line
				   ,@SalesAccountKey = ISNULL(b.DefaultSalesAccountKey, 0) -- Can be null or 0	
				   ,@EstimateKey = b.EstimateKey -- For FF
				   ,@BillingClassKey = ISNULL(b.ClassKey, 0)
				   ,@FixedFeeAddProjectLine = ISNULL(FixedFeeAddProjectLine,0)
			FROM   tBilling b (NOLOCK)
				LEFT OUTER JOIN tProject p (NOLOCK) ON b.ProjectKey = p.ProjectKey
				LEFT OUTER JOIN tCampaign c (NOLOCK) ON b.CampaignKey = c.CampaignKey

			WHERE  b.BillingKey = @BillingKey

			if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
				Select @SalesAccountKey = @DefaultSalesAccountKey 

			if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
				SELECT @BillingClassKey = @DefaultClassKey

			-- overwrite Rollup from the master WS--it may be changed later based on FF or retainer
			select @Rollup = @TopRollup

			-- If retainer, ignore line format/rollup and set up a dummy rollup
			IF @BillingMethod = 3
				SELECT @Rollup = @kByRetainer 
			
			-- If FF, it will depend on FixedFeeDisplay	
			IF @BillingMethod = 2
			BEGIN
				IF @FixedFeeDisplay = 1
					SELECT @FixedFeeRollup = @kByOneLine 	-- There is just a line in tBillingFixedFee for Entity = ''tEstimate''  
				ELSE IF @FixedFeeDisplay = 2 
					SELECT @FixedFeeRollup = @kFFByTask 	-- By Task
				ELSE IF @FixedFeeDisplay = 3
					SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Service Item or by Billing Item
				ELSE IF @FixedFeeDisplay = 4
					SELECT @FixedFeeRollup = @kFFByServiceItem 	-- By Billing Item
				ELSE IF @FixedFeeDisplay = 5
					SELECT @FixedFeeRollup = @kFFByProject 					-- By Project
				ELSE
					SELECT @FixedFeeRollup = @kFFByServiceItem 
							
			END	

			-- Create summary line for project
			select @ShowExtraProjectLine = 0
			if  @Rollup > @kByOneLine -- only if we do not have a one line 
				select @ShowExtraProjectLine =1
			if @BillingMethod = 2 and @FixedFeeRollup > @kByOneLine
				select @ShowExtraProjectLine =1
			
			-- 561987 should work for campaign also
			--if @BillingMethod = 2 and @FixedFeeRollup = @kFFByServiceItem and @ProjectKey > 0 and @FixedFeeAddProjectLine = 1
			if @BillingMethod = 2 and @FixedFeeRollup = @kFFByServiceItem and @FixedFeeAddProjectLine = 1
				select @ShowExtraProjectLine =1
			
			if @ShowExtraProjectLine =1 and @ProjectName is not null
			begin
			
			--create single invoice line
			exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
														-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
														-- (GHL 4/23/10 put it back for custom fields)
						  ,@ProjectKey					-- ProjectKey 
						  ,NULL							-- TaskKey
						  ,@ProjectName					-- Line Subject
						  ,NULL                 		-- Line description
						  ,0		      				-- Bill From 
						  ,0							-- Quantity
						  ,0							-- Unit Amount
						  ,0							-- Line Amount
						  ,1							-- line type = Summary
						  ,0							-- parent line key, important here must be under root
						  ,null -- @SalesAccountKey				-- Default Sales AccountKey
						  ,@BillingClassKey             -- Class Key
						  ,0							-- Taxable
						  ,0							-- Taxable2
						  ,@WorkTypeKey					-- Work TypeKey
						  ,@PostSalesUsingDetail
						  ,NULL							-- Entity
						  ,NULL							-- EntityKey
						  ,NULL							-- OfficeKey
						  ,NULL							-- DepartmentKey
						  ,@ParentInvoiceLineKey output

			if @@ERROR <> 0 
			  begin

				update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				exec sptInvoiceDelete @NewInvoiceKey
				return -17					 	
			  end			   		     		 
			if @RetVal <> 1 
			  begin
				update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				exec sptInvoiceDelete @NewInvoiceKey
				return -17					 	
			  end
			
				-- DisplayOption from tLayoutBilling must be set for the project
				update tInvoiceLine 
				set    DisplayOption = @LayoutProjectDisplayOption
				where  InvoiceLineKey = @ParentInvoiceLineKey
			
			end -- Rollup>0
			else
			begin
				select @ParentInvoiceLineKey = 0
			end

			/*--
			|| Fixed Fee by Task
			*/--		
			if @BillingMethod = 2 and @FixedFeeRollup = @kFFByTask 
			begin
				exec @RetVal = spBillingInvoiceOneLinePerTaskFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
					,@ProjectKey, @SalesAccountKey , @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey
					,@EstimateKey
					
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a fixed fee worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end			  	

			/*--
			|| Fixed Fee by Service/Item
			*/--		
			if @BillingMethod = @kFFBillingMethod and @FixedFeeRollup = @kFFByServiceItem 
			begin
				exec @RetVal = spBillingInvoiceOneLinePerServiceItemFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
					,@ProjectKey, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey, @EstimateKey
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a fixed fee worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end			  	
			  		
			/*
			|| Fixed Fee by Project
			*/		
			if @BillingMethod = @kFFBillingMethod And @FixedFeeRollup = @kFFByProject
			begin
				exec @RetVal = spBillingInvoiceOneLinePerProjectFF @CompanyKey, @NewInvoiceKey ,@BillingKey , @ParentInvoiceLineKey 
					, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per project for a fixed fee campaign worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end	

			/*--
			|| Fixed Fee on one invoice line
			*/--	
			if @BillingMethod = @kFFBillingMethod and @FixedFeeRollup = @kByOneLine
			BEGIN
				-- Pass 2 instead of @BillingMethod to indicate tBillingFixedFee records
				EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 2, @ProjectKey 
				,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail	
				,@EstimateKey

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a fixed fee worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	
			END	
			
			if @Rollup = @kByProjectBillingItemItem 
			begin
				exec spBillingLinesUpdateItems ''tProject'', @ProjectKey
				
				truncate table #tran
				exec spBillingLinesGetTrans @BillingKey	  
				 
				if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
					Select @SalesAccountKey = @DefaultSalesAccountKey 

				if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
					SELECT @BillingClassKey = @DefaultClassKey
		
				exec spBillingLinesGetFromLayout @CompanyKey,@LayoutKey, ''tProject'', @ProjectKey
					,@DefaultSalesAccountKey,@BillingClassKey,@DefaultClassKey, 0 --@GetItemInfo
				
				--Set Subjetct to TimeRateSheet.InvoiceLabel if exists
				EXEC spBillingLinesUpdateFromRateSheet @ProjectKey
				
				exec @RetVal = spBillingLinesInsert @CompanyKey,@NewInvoiceKey,@ProjectKey ,@DefaultSalesAccountKey ,@DefaultClassKey
					,@ParentInvoiceLineKey,@PostSalesUsingDetail

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	

			end -- Rollup @kByProjectBillingItemItem 


			/*	--
			|| Handle single invoice line
			*/ --	
			IF @Rollup <= @kByOneLine						
			BEGIN
				-- if there is a FF campaign, specify expenses for projects
				If @IsFFCampaign = 1 and isnull(@ProjectKey,0) > 0
					select @ProjectName = @ProjectName + '' Expenses''

				-- pass 1 as Billing Method to indicate tBillingDetail
				EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 1, @ProjectKey 
				,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail
				,@EstimateKey	

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	

				-- Customization for Etna
				IF @RetVal > 0 and @ShowTransactionsOnInvoices = 1
				begin
					update tInvoiceLine
					set    DisplayOption = @kDisplayOptionTransactions
					where  InvoiceLineKey = @RetVal
				end


			END	
			
			/* --
			|| Handle invoice lines by Task
			*/ --		
			if @Rollup = @kByProjectTask 
			begin
				exec @RetVal = spBillingInvoiceOneLinePerTask @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
					,@SalesAccountKey , @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
					
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end

				exec @RetVal = sptInvoiceLineApplyTaskOptions @NewInvoiceKey
				--put hours & rate on Invoice lines
				EXEC sptInvoiceLineSetHours @NewInvoiceKey
			end

			/*
			|| Handle invoice lines by Service (One line for expenses)
			*/		
			if @Rollup = @kByProjectService
			begin
				exec @RetVal = spBillingInvoiceOneLinePerService @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
					,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end
			  	
			/*
			|| Handle invoice lines by Service/Item (One line per item for expenses) 
			*/		
			if @Rollup = @kByProjectServiceOrItem
			begin
				exec @RetVal = spBillingInvoiceOneLinePerServiceItem @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
					,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a worksheet'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
				
				EXEC sptInvoiceLineSetHours @NewInvoiceKey
				EXEC sptInvoiceLineSetExpenses @NewInvoiceKey				
			end

			/*--
			|| Handle invoice line for the retainer amount
			*/--		
			if @Rollup = @kByRetainer 
			begin
				exec @RetVal = spBillingInvoiceRetainer @NewInvoiceKey ,@BillingKey, @BillingMethod 
					,@SalesAccountKey , @BillingClassKey, @WorkTypeKey, @InvoiceDate
	  			if @RetVal < 0
				begin
					update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a retainer'' 
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					return @RetVal
				end
			end			  	

			/*	--
			|| Handle invoice lines per title for Abelson Taylor
			*/ --	
			IF @Rollup in ( @kByProjectTitle, @kByProjectTitleService, @kByProjectServiceTitle)					
			BEGIN

				EXEC @RetVal = spBillingInvoiceOneLinePerTitle @NewInvoiceKey, @BillingKey, @Rollup, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @PostSalesUsingDetail, @ParentInvoiceLineKey

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per title for a worksheet''  
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	

			END	

		end -- billing rec/project NO segment

	
	IF ISNULL(@BillingStatusKey, 0) > 0
	BEGIN
		UPDATE tProject
		SET    tProject.ProjectBillingStatusKey = @BillingStatusKey
		FROM   #tBilling 
		WHERE  tProject.ProjectKey = #tBilling.ProjectKey
	END
 
 end -- @TopRollup <> 9 Multiple project

select @OldInvoiceKey = isnull(InvoiceKey, 0) 
	  ,@OldStatus = Status
from tBilling (nolock) where BillingKey = @TopBillingKey

-- If already invoiced, abort
if @OldInvoiceKey > 0 Or @OldStatus = 5 
begin
	EXEC sptInvoiceDelete @NewInvoiceKey
	return -1001
end		
if exists (select 1 from tInvoice (nolock) where BillingKey = @TopBillingKey and InvoiceKey <> @NewInvoiceKey)
begin
	EXEC sptInvoiceDelete @NewInvoiceKey
	return -1001
end		

	-- Patch to set campaign segment on lines at KN''s request
	if @TopEntity = ''Campaign'' and @TopRollup = @kByProjectTask 
	begin
		update tInvoiceLine
		set    tInvoiceLine.CampaignSegmentKey = p.CampaignSegmentKey
		from   tProject p (nolock)
		where  tInvoiceLine.InvoiceKey = @NewInvoiceKey
		and    tInvoiceLine.ProjectKey = p.ProjectKey 		
	end

	exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0 -- added because we do not do it in sptInvoiceLineInsertMassBilling

	-- This will force the Taxable fields if the pref or the project requires them
	exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

	exec sptInvoiceRecalcAmounts @NewInvoiceKey

	-- the media taxes will be placed in the other taxes, tax1 and tax2 must be calculated first
	if @UseMediaTaxes = 1
		-- customization: pull taxes from the vendor instead of the client
		exec sptInvoiceGetVendorTaxes @NewInvoiceKey

	-- by default
	-- I apply the SubItemDetail disp option to summary tasks
	-- I apply the NoDetail disp option to detail tasks
	
  IF @Rollup = @kByProjectServiceOrItem
  	BEGIN
			update tInvoiceLine
			set    DisplayOption = 2 --@kDisplayOptionSubItemDetail
			where  InvoiceKey = @NewInvoiceKey
			and    LineType = 1 -- @kLineTypeSummary
			
			UPDATE tInvoiceLine
			SET DisplayOption = @LayoutProjectDisplayOption
			WHERE
				InvoiceKey = @NewInvoiceKey AND
				ISNULL(WorkTypeKey, 0) = 0 AND --Is not a Billing Item
				LineType = 1 AND
				ParentLineKey = 0

			UPDATE tInvoiceLine
			SET DisplayOption = lb.DisplayOption
			FROM
				tInvoiceLine il (nolock)
				INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
				INNER JOIN tLayoutBilling lb (nolock) ON il.Entity = lb.Entity AND il.EntityKey = lb.EntityKey AND lb.LayoutKey = i.LayoutKey
			WHERE il.InvoiceKey = @NewInvoiceKey
  	END
  ELSE
  	BEGIN
			update tInvoiceLine
			set    DisplayOption = 2 --@kDisplayOptionSubItemDetail
			where  InvoiceKey = @NewInvoiceKey
			and    LineType = 1 -- @kLineTypeSummary
			and    isnull(DisplayOption, 0) = 0

			UPDATE tInvoiceLine
			SET DisplayOption = @LayoutProjectDisplayOption
			WHERE
				InvoiceKey = @NewInvoiceKey AND
				ISNULL(WorkTypeKey, 0) = 0 AND --Is not a Billing Item
				(
					(
						LineType = 1 AND
						ParentLineKey = 0
					) OR
					Entity = ''tProject''
				)
				
			update tInvoiceLine
			set    DisplayOption = CASE WHEN @TaskShowTransactions = 1 THEN @kDisplayOptionTransactions ELSE @kDisplayOptionNoDetail END
			where  InvoiceKey = @NewInvoiceKey
			and    LineType = 2 -- @kLineTypeDetail
			and    isnull(DisplayOption, 0) = 0
		END
	
	-- If the user wanted an advance bill, tBilling.DefaultSalesAccountKey should already be set to the AdvBill account so set it now on the lines
	IF @AdvanceBill = 1
		UPDATE tInvoiceLine SET SalesAccountKey = @DefaultSalesAccountKey WHERE InvoiceKey = @NewInvoiceKey AND LineType = 2 

	-- This processing below involves the master as well
	-- Make sure that the master is in there too
	IF (SELECT COUNT(*) FROM #tBilling WHERE BillingKey = @TopBillingKey) = 0 		
		INSERT #tBilling (BillingKey) VALUES (@TopBillingKey) 

	-- Handle Advance Payments
	DECLARE @AvalaraEnabled tinyint
	SELECT @AvalaraEnabled = ISNULL(AvalaraEnabled, 0) FROM tPreference (nolock) WHERE CompanyKey = @CompanyKey
	
	IF @AvalaraEnabled = 0 --If using Avalara, the taxes will be overwritten after the spBillingInvoiceBill SP completes; run this SP after the Avalara call
		EXEC spBillingApplyAdvanceBill @TopBillingKey, @NewInvoiceKey

	-- If the invoice is completely paid by the advance bills, set Printed = 1 
	declare @InvoiceOpenAmount money
	declare @InvoiceTotalAmount money
	select @InvoiceOpenAmount = isnull(InvoiceTotalAmount, 0) - isnull(RetainerAmount, 0)  
	     ,@InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0)
	from tInvoice (nolock)
	where InvoiceKey = @NewInvoiceKey

	if @InvoiceOpenAmount = 0 and @InvoiceTotalAmount <> 0
		update tInvoice
		set    Printed = 1
		where  InvoiceKey = @NewInvoiceKey

	-- This processing below involves the master as well
	-- Make sure that the master is in there too
	IF (SELECT COUNT(*) FROM #tBilling WHERE BillingKey = @TopBillingKey) = 0 		
		INSERT #tBilling (BillingKey) VALUES (@TopBillingKey) 

			
	UPDATE tBilling 
	SET    tBilling.InvoiceKey = @NewInvoiceKey 
		  ,tBilling.Status = 5
	FROM #tBilling
	WHERE  tBilling.BillingKey = #tBilling.BillingKey	
	IF @@ERROR <> 0
	BEGIN
		update tBilling set ErrorMsg = ''An error occurred when changing the status of the billing worksheet to invoiced'' 
		where BillingKey = @TopBillingKey 

		EXEC sptInvoiceDelete @NewInvoiceKey
		RETURN -1000
	END
		
	EXEC sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey	
		
	-- This is an attempt to reconnect with a billing schedule on a FF project if missing
	SELECT @BillingKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @BillingKey = MIN(tb.BillingKey)
		FROM   #tBilling tb
			INNER JOIN tBilling b (nolock) ON tb.BillingKey = b.BillingKey
		WHERE  tb.BillingKey > @BillingKey
		AND    b.ProjectKey > 0
		AND    b.BillingKey > @BillingKey
		AND    b.BillingMethod = 2 -- FF

		IF @BillingKey is null
			break

		SELECT @ProjectKey = ProjectKey  from tBilling (nolock) where BillingKey = @BillingKey

		-- if missing, place the invoice on a billing schedule
		IF NOT EXISTS (SELECT 1 FROM tBillingSchedule (nolock) WHERE ProjectKey = @ProjectKey and BillingKey = @BillingKey)
			EXEC spFixedFeesUpdateBillingSchedule @NewInvoiceKey, @ProjectKey
		ELSE
		UPDATE tBillingSchedule
		SET    InvoiceKey = @NewInvoiceKey
		      ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
		                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
		                                             case when isnull(p.ExpensesNotIncluded, 0) = 0
		                                                  then isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0) + isnull(p.EstExpenses, 0) + isnull(p.ApprovedCOExpense, 0)
		                                                  else isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0)
		                                             end) / 100.00, 2), ''N2'')
		                                    else null end
		                            from tBillingSchedule bs (nolock)
		                                inner join tProject p (nolock) on bs.ProjectKey = p.ProjectKey
		                            where bs.ProjectKey = @ProjectKey and bs.BillingKey = @BillingKey)
		WHERE  ProjectKey = @ProjectKey and BillingKey = @BillingKey
	END

	-- Link campaign billing schedules to the invoice (all billing methods — worksheet rows have BillingKey set)
	declare @CampaignKey int
	SELECT @BillingKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @BillingKey = MIN(tb.BillingKey)
		FROM   #tBilling tb
			INNER JOIN tBilling b (nolock) ON tb.BillingKey = b.BillingKey
		WHERE  tb.BillingKey > @BillingKey
		AND    b.CampaignKey > 0
		AND    b.BillingKey > @BillingKey

		IF @BillingKey is null
			break

		SELECT @CampaignKey = CampaignKey  from tBilling (nolock) where BillingKey = @BillingKey

		UPDATE tBillingSchedule
			SET    InvoiceKey = @NewInvoiceKey
			      ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
			                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
			                                             case when isnull(c.ExpensesNotIncluded, 0) = 0
			                                                  then isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0) + isnull(c.EstExpenses, 0) + isnull(c.ApprovedCOExpense, 0)
			                                                  else isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0)
			                                             end) / 100.00, 2), ''N2'')
			                                    else null end
			                         from  tBillingSchedule bs (nolock)
			                         join  tCampaign c (nolock) on c.CampaignKey = bs.CampaignKey
			                         where bs.CampaignKey = @CampaignKey and bs.BillingKey = @BillingKey)
			WHERE  CampaignKey = @CampaignKey and BillingKey = @BillingKey
	END


	-- Link T&M project billing schedules to the invoice (BilledComment populated by spFixedFeesUpdateBillingSchedule)
	SELECT @BillingKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @BillingKey = MIN(tb.BillingKey)
		FROM   #tBilling tb
			INNER JOIN tBilling b (nolock) ON tb.BillingKey = b.BillingKey
		WHERE  tb.BillingKey > @BillingKey
		AND    b.ProjectKey > 0
		AND    b.BillingKey > @BillingKey
		AND    b.BillingMethod = 1 -- T&M

		IF @BillingKey is null break

		SELECT @ProjectKey = ProjectKey from tBilling (nolock) where BillingKey = @BillingKey

		EXEC spFixedFeesUpdateBillingSchedule @NewInvoiceKey, @ProjectKey
	END

	RETURN @NewInvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectUpdateSetup]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectUpdateSetup]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptProjectUpdateSetup]
	@ProjectKey int,
	@CompanyKey int,
	@ProjectName nvarchar(100),
	@ProjectNumber varchar(100),
	@ProjectTypeKey int,
	@ClientDivisionKey int,
	@ClientProductKey int,
	@ClientKey int,
	@CampaignKey int,
	@ClientProjectNumber varchar(200),
	@RequestKey int,
	@BillingContact int, 
	@CustomFieldKey int,
	@OfficeKey int,
	@GLCompanyKey int,
	@GLCompanySource smallint,
	@ClassKey int,
	@AccountManager int,
	@Closed tinyint,
	@ProjectStatusKey int,
	@ProjectBillingStatusKey int,
	@StatusNotes nvarchar(max),
	@DetailedNotes nvarchar(4000),
	@ClientNotes nvarchar(4000),
	@Description nvarchar(max),
	@ImageFolderKey int,
	@KeyPeople1 int,
	@KeyPeople2 int,
	@KeyPeople3 int,
	@KeyPeople4 int,
	@KeyPeople5 int,
	@KeyPeople6 int,
	@StartDate smalldatetime,
	@CompleteDate smalldatetime,
	@WorkMon tinyint,
	@WorkTue tinyint,
	@WorkWed tinyint,
	@WorkThur tinyint,
	@WorkFri tinyint,
	@WorkSat tinyint,
	@WorkSun tinyint,
	@ScheduleDirection smallint,
	@FlightStartDate smalldatetime,
	@FlightEndDate smalldatetime,
	@FlightInterval tinyint,
	@ProjectColor varchar(10),
	@CampaignBudgetKey int,
	@TeamKey int,
	@LeadKey int,
	@LayoutKey int,
	@CampaignSegmentKey int,
	
	@GetRateFrom smallint,
	@HourlyRate money,
	@TimeRateSheetKey int,
	@TitleRateSheetKey int,
	@OverrideRate tinyint,
	@NonBillable tinyint,
	@UtilizationType varchar(50),
	@GetMarkupFrom smallint,
	@ItemRateSheetKey int,
	@ItemMarkup decimal(24,4),
	@IOCommission decimal(24,4),
	@BCCommission decimal(24,4),
	@Template tinyint,
	@RetainerKey int,
	@BillingMethod smallint,
	@ExpensesNotIncluded tinyint,
	@AutoIDTask smallint = -1, --smallint so we can default to -1
	@SimpleSchedule smallint = -1, --smallint so we can default to -1

	@ClientBHours tinyint = 1,
	@ClientBLabor tinyint = 1,
	@ClientBCO tinyint = 1,
	@ClientBExpenses tinyint = 1,
	@ClientAHours tinyint = 1,
	@ClientALabor tinyint = 1,
	@ClientAPO tinyint = 1,
	@ClientAExpenses tinyint = 1,

	@ShowTransactionsOnInvoices tinyint = 0,
	@DoNotPostWIP tinyint = 0,
	@BillingGroupKey int = null,
	@ModelYear varchar(10) = null,
	@BillingManagerKey int = null,
	@CurrencyID varchar(10) = null,
	@AnyoneChargeTime tinyint = 0,
	@PlanningBillOption smallint = null,
	@PlanningProjectMultipleTasks tinyint = null,
	@PlanningProjectKey int = -1,
	@ProjectManager int = null,
	@PlanningProjectAutoRollover tinyint = null,
	@ForecastForceToFF tinyint = 0,
	@PlanningProjectAllowPeople tinyint = null,
	@SetTaxableOnInvoice tinyint = 0,
	
	@AvalaraOverrideTaxCodes tinyint = 0,
	@AvalaraTaxCodeKey int = NULL,

	@LimitProjectServices tinyint = 0,
	@UserKey int = NULL,
	@UpdateProjectStatus tinyint = 0,
	@OverrideScheduleOptions tinyint = null,
	@AutoScheduleProjects tinyint = null,
	@AutoScheduleTaskEndDate tinyint = null,
	@ActualDateUpdatesPlan tinyint = null,
	@WeekendBucket tinyint = null,
	@ExcludeFromRM tinyint = null,
	@OverrideExcludeFromRM tinyint = null,
	@SlackChannelID nvarchar(20) = null,
	@RequireCommentsOnTimePj tinyint = 0,
	@BucketPerWeek tinyint = null,
	@BillExpensesByItem tinyint = null

AS --Encrypt

  /*
  || When     Who Rel      What
  || 10/13/06 GHL 8.4      Limited validation of Start/Complete dates against Scheduled tasks only  
  || 12/13/06 GHL 8.4      Removed validation of Start/Complete dates at user''s request
  || 04/18/07 QMD 8.4.2    Added Project Color
  || 05/22/07 CRG 8.4.3    Added CampaignBudgetKey  
  || 07/05/07 GHL 8.5      Added check of tRetainer.GLCompanyKey       
  || 11/16/07 GHL 8.5      Added checking of client in tTransaction       
  || 12/10/07 GWG 8.5      Changed locking logic on office and company to be more selective based on the show options. 
  || 12/29/08 CRG 10.0.1.5 (39387) Added TeamKey parameter.
  || 01/10/09 GWG 10.0.1.6 Commented out the update to custom field key, should never be updated except by custom field routines.
  || 01/27/09 MFT 10.0.1.8 (45458) Trim leading and trailing spaces from ProjectNumber; Replace same strings from ProjectNumber as in sptProjectCreate
  || 01/29/09 MFT 10.0.1.8 (45145) (45415) Added RETURN -6 to trap for missing ProjectStatusKey record
  || 03/16/09 QMD 10.5	   Remove User Defined Fields
  || 07/14/09 GHL 10.505   (56909) Allowing now change of client even if there are some posted transactions
  ||                        Also updating now CASH basis GL transactions
  || 12/20/09 GWG 10.5.1.5 Added Segment and layout keys (cmp updated as well with hidden fields) Also Merged the update acct routine to make one call and sperate from cmp
  || 3/2/10   CRG 10.5.1.9  Added @AutoIDTask and @SimpleSchedule
  || 5/13/10  CRG 10.5.2.2  (80503) Now returning an error if the campaign client is not the same as the project client and the campaign''s BillBy is not set to Project.
  || 8/19/10  GHL 10.5.3.4  If we changed the campaign, make sure that the project is not on an approved campaign estimate
  || 12/7/10  RLB 10.5.3.9  (96122) IF Campaign was removed update any Campaign Estimates by Project to reflect that the project was removed
  || 1/17/11  RLB 10.5.4.0  (100586) Added some validation on project status when closing a project
  || 09/21/11 RLB 10.5.4.8  (119193) Added for this enhancement
  || 10/13/11 GHL 10.4.5.9 Added new entity CREDITCARD 
  || 10/27/11 GWG 10.5.4.9  Added flags for setting columns in client budget grid
  || 04/02/11 GWG 10.5.5.4  Added GLCompanySource
  || 05/02/12 RLB 10.5.5.5  (125332) Added check for any unbilled PO''s that are not closed when closing a project
  || 05/21/12 GHL 10.5.5.6  Added @ShowTransactionsOnInvoices for a customization at Etna
  || 05/23/12 GWG 10.5.5.6  Added more error return codes on closing so people can tell why it will not close
  || 05/29/12 RLB 10.5.5.6  (143337) Fixed to only null the project close date if the project closed was unchecked
  || 07/05/12 RLB 10.5.5.7  (148224) if there was a projectclosedate it was not getting  set on the update
  || 07/17/12 GHL 10.5.5.8  Added DoNotPostWIP and BillingGroupCode for customizations for HMI
  || 09/26/12 GHL 10.5.6.0  Changed BillingGroupCode to BillingGroupKey (new table tBillingGroup)
  || 02/12/13 GHL 10.5.6.5  (167857) Added ModelYear for a customization for Spark44
  || 06/15/13 GWG 10.5.6.9  Added code to remap offices if it is different
  || 08/26/13 RLB 10.5.7.1  (170225) Adding BillingManagerKey update
  || 09/12/13 GHL 10.5.7.2  Added currency ID
  || 02/13/14 PLC 10.5.7.7  Added TransferOutDate is null to open items logic
  || 09/24/14 MAS 10.5.8.4  Added TitleRateSheetKey for Abelson & Taylor
  || 11/05/14 RLB 10.5.8.6  Added AnyoneChargeTime for Abelson & Taylor
  || 02/02/15 GHL 10.5.8.8  Added validation of change of division/product for Abelson & Taylor
  || 02/27/15 GHL 10.5.8.9  For Abelson, do not consider transferred transactions when setting the lock of divisions
  || 10/08/15 GHL 10.5.9.7  (273223) Added checking of existing transactions when changing currency 
  || 10/13/15 RLB 10.5.9.8  added check for campainid matching any project numbers which can not be because of Plat changes
  || 10/27/15 GHL 10.5.9.8  Templates may not have a project status, so do not validate status and active for those
  || 11/16/16 WDF 10.6.1.0  (318451) Added DateUpdated
  || 01/01/18 GHL 18.1.0    (378816) When we close a project, do  a final project rollup
  || 06/01/18 RLB 18.6.0.0  changed for reports...what change?
  || 08/23/18 GHL 18.9.0.0  (417377) Added protection against 0 or null billing method
  || 01/19/19 GWG 19.0.2    removed duplicate updates of office key to tTransaction
  || 02/05/19 CRG 19.0.3.0  (421239) Added PlanningBillOption
  || 02/08/19 CRG 19.0.3.0  (421239) Added PlanningProjectMultipleTasks
  || 02/28/19 CRG 19.0.3.0  (421239) Added PlanningProjectKey
  || 06/06/19 RLB 19.0.7.0  (446229) Adding Project Manager
  || 01/10/20 GHL 20.0.2.0  (496078) For templates do not check active/status because the project status is not on the UI
  || 08/10/20 MCM 20.0.9.0  (522660) When importing a template, if the IsActive on the status is null, then set active = 1
  || 11/23/20 RLS 20.1.2.0  (535729) Changed @ProjectName to nvarchar
  || 12/17/20 RLS 21.0.1.0  (535729) Changed @Description to nvarchar
  || 02/08/21 CRG 21.03.14  (521442) Added PlanningProjectAutoRollover
  || 03/29/21 WDF 21.0.4.0  (553365) Description size changed from nvarchar(4000) to nvarchar(max)
  || 04/05/21 GHL 21.05.16.0000 (553170) Added parameter ForecastForceToFF to process TM projects as Fixed Fee on forecasts
  || 11/09/21 GHL 21.12.19  (573376) Do not close a project if it has an open BWS
  || 12/13/21 CRG 22.01.16  (578510) Added @PlanningProjectAllowPeople
  || 03/18/22 GHL 22.04.17  (590582) Added handling of SetTaxableOnInvoice for Fingerpaint enh
  || 06/24/22 GWG 22.07.10  add update to hourly rate on tTaskUser if the setup is changed.
  || 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
  || 09/22/22 GAR 22.10.16 (DEV2605) Added AvalaraTaxCodeKey
  || 10/12/22 RLB 22.11.20 (610106) added LimitProjectServices for customization
  || 10/24/22 RLS 22.11.20 (614999) Check that the project is not currently in a status that is Locked (tProjectStatus.Locked) before updating
  || 01/04/23 GAR 23.02.19 (626391) Change the security check to call spUserHasRight - Admin should be able to update a locked status
  || 05/31/23 CRG 23.07.16 (639524) Added OverrideScheduleOptions, AutoScheduleProjects, AutoScheduleTaskEndDate, and ActualDateUpdatesPlan
  || 09/25/23 CRG 23.10.15 (651709) Added check to make sure you can''t set a day to a non-working day if a ConstraintDayOfTheWeek is set to that day
  || 10/11/23 RLS 23.11.19 (651185) Changed StatusNotes to nvarchar(max)
  || 11/28/23 CRG 23.12.17 (649537) Added WeekendBucket
  || 01/10/24 RLS 24.02.18 (653569)  Changed DetailedNotes to nvarchar
  || 04/02/24 RLS 24.04.14 (661674)  Changed ClientNotes to nvarchar
  || 05/14/24 RLB 24.06.16 (659813) Adding ExcludeFromRM option
  || 11/20/24 CRG 24.12.15 (688517) Added OverrideExcludeFromRM
  || 12/20/24 MCM 25.01.x  (689316) Updated the check on the billingGroupGLCompanyKey to allow for -1, which is all glCopmanies
  || 01/22/25 GAR 25.02.x  (692485) Added SlackChannelID to update
  || 03/26/25 RLB 25.04.20 (697032) added RequireCommentsOnTimePj for customization WoodruffRequireComments
  || 08/13/25 GAR 25.09.14 (705884) Added AvalaraOverrideTaxCodes for overriding lower level tax codes in Avalara 
  || 01/21/26 CRG 26.02.15 (717807) Added BucketPerWeek
  || 07/07/26 MFT 26.08.01 (729267) Added BillExpensesByItem (Fixed Fee expenses billed one line per Item)
  */
  
Declare @Active tinyint
Declare @AllowTime tinyint
Declare @AllowExpense tinyint
Declare @CurClosed tinyint
Declare @RetainerGLCompanyKey int
Declare @RetainerCurrencyID varchar(10)
Declare @CampaignCurrencyID varchar(10)
Declare @BillingGroupGLCompanyKey int
Declare @OldClientKey int, @OldOfficeKey int
Declare @OldClientDivisionKey int, @OldClientProductKey int

DECLARE	@CurAutoIDTask tinyint,
		@CurSimpleSchedule tinyint,
		@CurCampaignKey int,
		@CurCurrencyID varchar(10),
		@ProjectCloseDate smalldatetime,
		@PlanningProject tinyint,
		@CurPlanningBillOption smallint,
		@CurPlanningProjectMultipleTasks tinyint,
		@CurPlanningProjectKey int,
		@CurPlanningProjectAutoRollover tinyint,
		@CurPlanningProjectAllowPeople tinyint,
		@CurGetRateFrom tinyint,
		@Locked tinyint,
		@EditLocked tinyint = 0,
		@CurOverrideScheduleOptions tinyint,
		@CurAutoScheduleProjects tinyint,
		@CurAutoScheduleTaskEndDate tinyint,
		@CurActualDateUpdatesPlan tinyint,
		@CurWeekendBucket tinyint,
		@CurExcludeFromRM tinyint,
		@CurOverrideExcludeFromRM tinyint,
		@CurBucketPerWeek tinyint,
		@CurBillExpensesByItem tinyint

Declare @LockCompany int, @UseGLCompany tinyint, @UseOffice tinyint, @MultiCurrency int, @LockDivisionProduct int
DECLARE @IOClientLink int, @BCClientLink int
	
IF EXISTS(
	SELECT 1 FROM tProject (NOLOCK) 
	WHERE
		ProjectNumber = @ProjectNumber AND
		CompanyKey = @CompanyKey AND
		ProjectKey <> @ProjectKey AND
		Deleted = 0
		)
	RETURN -1

	IF EXISTS(
			SELECT 1 FROM tCampaign (NOLOCK) 
			WHERE
				CampaignID = @ProjectNumber AND
				CompanyKey = @CompanyKey			
				)
			RETURN -15

	SELECT @Active = IsActive, @AllowTime = TimeActive, @AllowExpense = ExpenseActive
	FROM tProjectStatus (NOLOCK) 
	WHERE ProjectStatusKey = @ProjectStatusKey
	
	-- All these checks should not apply to templates, there is a new TemplateActive flag now
	if isnull(@Template,0) = 0
	begin
		IF @Active IS NULL --and isnull(@Template,0) = 0
			RETURN -6

		IF @Closed = 1 and @Active = 1 
			return -2

		if @Closed = 1 and @Active = 0 and (@AllowTime = 1 OR @AllowExpense = 1)
			return -9
	end

	Select @CurClosed = Closed
		  ,@OldClientKey = ClientKey
		  ,@OldOfficeKey = ISNULL(OfficeKey, 0)
		  ,@CurAutoIDTask = AutoIDTask
		  ,@CurSimpleSchedule = SimpleSchedule
		  ,@CurCampaignKey = CampaignKey
		  ,@CurCurrencyID = CurrencyID
		  ,@ProjectCloseDate = ProjectCloseDate
		  ,@OldClientProductKey = ClientProductKey
		  ,@OldClientDivisionKey = ClientDivisionKey
		  ,@PlanningProject = PlanningProject
		  ,@CurPlanningBillOption = PlanningBillOption
		  ,@CurPlanningProjectMultipleTasks = PlanningProjectMultipleTasks
		  ,@CurPlanningProjectKey = PlanningProjectKey
		  ,@CurPlanningProjectAutoRollover = PlanningProjectAutoRollover
		  ,@CurPlanningProjectAllowPeople = PlanningProjectAllowPeople
		  ,@CurGetRateFrom = GetRateFrom
		  ,@CurOverrideScheduleOptions = OverrideScheduleOptions
		  ,@CurAutoScheduleProjects = AutoScheduleProjects
		  ,@CurAutoScheduleTaskEndDate = AutoScheduleTaskEndDate
		  ,@CurActualDateUpdatesPlan = ActualDateUpdatesPlan
		  ,@CurWeekendBucket = WeekendBucket
		  ,@CurExcludeFromRM = ExcludeFromRM
		  ,@CurOverrideExcludeFromRM = OverrideExcludeFromRM
		  ,@CurBucketPerWeek = BucketPerWeek
		  ,@CurBillExpensesByItem = BillExpensesByItem
	from tProject (nolock)
	Where ProjectKey = @ProjectKey

	IF @PlanningBillOption IS NULL
		SELECT @PlanningBillOption = @CurPlanningBillOption

	IF @PlanningProjectMultipleTasks IS NULL
		SELECT @PlanningProjectMultipleTasks = @CurPlanningProjectMultipleTasks

	IF @PlanningProjectAutoRollover IS NULL
		SELECT @PlanningProjectAutoRollover = @CurPlanningProjectAutoRollover

	IF @PlanningProjectAllowPeople IS NULL
		SELECT @PlanningProjectAllowPeople = @CurPlanningProjectAllowPeople

	IF @PlanningProjectKey = -1
		SELECT	@PlanningProjectKey = @CurPlanningProjectKey

	IF @PlanningProject = 1 AND @PlanningProjectMultipleTasks = 0
	BEGIN
		--Make sure that the planning project doesn''t already have multiple tasks
		DECLARE	@TaskCount int

		SELECT	@TaskCount = COUNT(*)
		FROM	tTask (nolock)
		WHERE	ProjectKey = @ProjectKey
		
		IF @TaskCount > 1
			RETURN -501
	END

	IF @PlanningProject = 1 AND @PlanningProjectAllowPeople = 0
	BEGIN
		--Make sure that the planning project doesn''t already have people assigned
		IF EXISTS(
				SELECT	NULL 
				FROM	tTaskUser tu (nolock)
				INNER JOIN tTask t (nolock) ON tu.TaskKey = t.TaskKey
				WHERE	t.ProjectKey = @ProjectKey
				AND		tu.UserKey IS NOT NULL)
			RETURN -510
	END

	IF @AutoIDTask = -1
		SELECT @AutoIDTask = @CurAutoIDTask
		
	IF @SimpleSchedule = -1
		SELECT @SimpleSchedule = @CurSimpleSchedule
	
	if @Closed = 1 and @CurClosed = 0
	BEGIN
		If Exists(Select 1 from tTime (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey is null and WriteOff = 0 and TransferOutDate is null)
			return -301
		If Exists(Select 1 from tExpenseReceipt (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey is null and WriteOff = 0 and VoucherDetailKey is null  and TransferOutDate is null)
			return -302
		If Exists(Select 1 from tMiscCost (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey is null and WriteOff = 0 and TransferOutDate is null)
			return -303
		If Exists(Select 1 from tVoucherDetail (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey is null and WriteOff = 0 and TransferOutDate is null)
			return -304
		If Exists(Select 1 from tPurchaseOrderDetail (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey is null and Closed = 0 and TransferOutDate is null)
			return -305
		If Exists(Select 1 from tBilling (nolock) Where ProjectKey = @ProjectKey and Status < 5)
			return -310 -- because 306 to 309 is in use in VB
	END

	IF @OverrideScheduleOptions IS NULL
		SELECT @OverrideScheduleOptions = @CurOverrideScheduleOptions

	IF @AutoScheduleProjects IS NULL
		SELECT @AutoScheduleProjects = @CurAutoScheduleProjects

	IF @AutoScheduleTaskEndDate IS NULL
		SELECT @AutoScheduleTaskEndDate = @CurAutoScheduleTaskEndDate

	IF @ActualDateUpdatesPlan IS NULL
		SELECT	@ActualDateUpdatesPlan = @CurActualDateUpdatesPlan

	IF @WeekendBucket IS NULL
		SELECT @WeekendBucket = @CurWeekendBucket
			
	IF @ExcludeFromRM IS NULL
		SELECT @ExcludeFromRM = @CurExcludeFromRM

	IF @OverrideExcludeFromRM IS NULL
		SELECT @OverrideExcludeFromRM = @CurOverrideExcludeFromRM

	IF @BucketPerWeek IS NULL
		SELECT	@BucketPerWeek = @CurBucketPerWeek

	IF @BillExpensesByItem IS NULL
		SELECT	@BillExpensesByItem = @CurBillExpensesByItem

	-- Bill Expenses by Item only applies to Fixed Fee projects where expenses are billed outside the fixed fee (ExpensesNotIncluded)
	IF ISNULL(@BillingMethod, 0) <> 2 OR ISNULL(@ExpensesNotIncluded, 0) <> 1
		SELECT @BillExpensesByItem = 0

	IF ISNULL(@OverrideScheduleOptions, 0) = 0
	BEGIN
		SELECT	@AutoScheduleProjects = NULL,
				@AutoScheduleTaskEndDate = NULL,
				@ActualDateUpdatesPlan = NULL,
				@WeekendBucket = NULL
	END

	/*	
	IF @ScheduleDirection = 1
	BEGIN	
		If Exists (Select 1 From tTask (NOLOCK) 
					Where ProjectKey = @ProjectKey
					And   (ConstraintDate < @StartDate Or ActStart < @StartDate	
						   Or ActComplete < @StartDate
						   )
					And   ScheduleTask = 1
					)
			return -4	
	END
	ELSE
	BEGIN
		If Exists (Select 1 From tTask (NOLOCK) 
					Where ProjectKey = @ProjectKey
					And   (ConstraintDate > @CompleteDate Or ActStart > @CompleteDate
						   Or ActComplete > @CompleteDate
						   )
					And   ScheduleTask = 1
					)
			return -4
			
	END		
	*/

Select @UseGLCompany = ISNULL(UseGLCompany, 0)
      ,@UseOffice = ISNULL(UseOffice, 0) 
	  ,@IOClientLink = ISNULL(IOClientLink, 1)
	  ,@BCClientLink = ISNULL(BCClientLink, 1)
	  ,@MultiCurrency = ISNULL(MultiCurrency, 0)
from tPreference (nolock) 
Where CompanyKey = @CompanyKey

Select @LockCompany = 0
Select @LockDivisionProduct = 0

	if exists(Select 1 from tInvoiceLine (nolock) Where ProjectKey = @ProjectKey)
		Select @LockCompany = 1
	
	if @LockCompany = 0 And exists(Select 1 from tVoucherDetail (nolock) Where ProjectKey = @ProjectKey)
		Select @LockCompany = 1
			
	if exists(Select 1 from tBilling (nolock) Where ProjectKey = @ProjectKey)
		Select @LockCompany = 1
			  ,@LockDivisionProduct = 1

	if @LockDivisionProduct = 0 And exists(Select 1 from tMiscCost (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey > 0 or WIPPostingInKey > 0 or WIPPostingOutKey > 0))
		Select @LockCompany = 1
		      ,@LockDivisionProduct = 1

	if @LockDivisionProduct = 0 And exists(Select 1 from tExpenseReceipt (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey > 0 or WIPPostingInKey > 0 or WIPPostingOutKey > 0))
		Select @LockCompany = 1
		      ,@LockDivisionProduct = 1

	if @LockDivisionProduct = 0 And exists(Select 1 from tVoucherDetail (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey > 0 or WIPPostingInKey > 0 or WIPPostingOutKey > 0))
		Select @LockCompany = 1
		      ,@LockDivisionProduct = 1

	if @LockDivisionProduct = 0 And exists(Select 1 from tPurchaseOrderDetail (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey > 0)
		Select @LockCompany = 1
		      ,@LockDivisionProduct = 1

	if @LockDivisionProduct = 0 And exists(Select 1 from tTime (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey > 0 or WIPPostingInKey > 0 or WIPPostingOutKey > 0))
		Select @LockCompany = 1
			,@LockDivisionProduct = 1

	if @LockCompany = 1
	BEGIN
		if @UseGLCompany = 1
			Select @GLCompanyKey = GLCompanyKey, @GLCompanySource = GLCompanySource from tProject (nolock) Where ProjectKey = @ProjectKey
		--if @UseOffice = 1
			--Select @OfficeKey = OfficeKey from tProject (nolock) Where ProjectKey = @ProjectKey
	END
	

	if exists (select 1 from tPreference pref (nolock)
			inner join tProject p (nolock) on pref.CompanyKey = p.CompanyKey 
            where p.ProjectKey = @ProjectKey
			and   lower(pref.Customizations) like ''%abelson%'' 
		  )
	begin
		-- if allready locked, no need to check further, so only do this if @LockDivisionProduct = 0 
		if @LockDivisionProduct = 0
		begin
			-- we have already checked if transactions were billed or in WIP
			-- we need to check now if transactions where marked as billed or written off  
			if exists (Select 1 from tMiscCost (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey = 0 or WriteOff = 1))
				Select @LockDivisionProduct = 1

			if @LockDivisionProduct = 0 and exists(Select 1 from tExpenseReceipt (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey = 0 or WriteOff = 1)
				and TransferToKey is null)
				Select @LockDivisionProduct = 1

			if @LockDivisionProduct = 0 and exists(Select 1 from tVoucherDetail (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey = 0 or WriteOff = 1)
				and TransferToKey is null)
				Select @LockDivisionProduct = 1

			if @LockDivisionProduct = 0 and exists(Select 1 from tPurchaseOrderDetail (nolock) Where ProjectKey = @ProjectKey and InvoiceLineKey >= 0
				and TransferToKey is null)
				Select @LockDivisionProduct = 1

			if @LockDivisionProduct = 0 and exists(Select 1 from tTime (nolock) Where ProjectKey = @ProjectKey and (InvoiceLineKey = 0 or WriteOff = 1)
				and TransferToKey is null)
				Select @LockDivisionProduct = 1

		end

		if @LockDivisionProduct = 1 and isnull(@ClientDivisionKey, 0) <> isnull(@OldClientDivisionKey, 0)
			select @ClientDivisionKey = @OldClientDivisionKey

		if @LockDivisionProduct = 1 and isnull(@ClientProductKey, 0) <> isnull(@OldClientProductKey, 0)
			select @ClientProductKey = @OldClientProductKey

	end


	IF ISNULL(@OldClientKey, 0) > 0 AND ISNULL(@OldClientKey, 0) <> ISNULL(@ClientKey, 0)
	BEGIN 	
		If EXISTS (SELECT 1 FROM tTransaction (NOLOCK) 
					WHERE CompanyKey = @CompanyKey
					AND   Entity NOT IN (''VOUCHER'', ''CREDITCARD'')       -- do not include vouchers
					AND   ProjectKey = @ProjectKey
					AND   ClientKey = @OldClientKey
					)
					Return -4
	END	
	
	/*
	438696  Mike wanted this reversed
	IF ISNULL(@OldOfficeKey, 0) <> ISNULL(@OfficeKey, 0)
	BEGIN 	
		Update tTransaction Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tCashTransaction Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tCashTransactionLine Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tVoucher Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tVoucherDetail Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tInvoice Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tInvoiceLine Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tInvoiceSummary Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tJournalEntryDetail Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tQuoteDetail Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tPurchaseOrderDetail Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tProject Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
		Update tTransaction Set OfficeKey = @OfficeKey Where ProjectKey = @ProjectKey
	END		
	*/

	if isnull(@BillingMethod,0) = 0
		select @BillingMethod = 1 -- TM

	if @BillingMethod != 1
		select @ForecastForceToFF = 0

	-- if billing by retainer
	If @BillingMethod = 3
	Begin
		Select @RetainerGLCompanyKey = GLCompanyKey
		      ,@RetainerCurrencyID = CurrencyID
		From tRetainer (NOLOCK) 
		Where RetainerKey = @RetainerKey
		
		If isnull(@RetainerGLCompanyKey, 0) <> isnull(@GLCompanyKey, 0)
			Return -5

		if @MultiCurrency = 1 And isnull(@RetainerCurrencyID, '''')  <> isnull(@CurrencyID, '''') 
			Return -11
	End

	-- if billing by Billing Group 
	If isnull(@BillingGroupKey, 0) > 0
	Begin
		Select @BillingGroupGLCompanyKey = GLCompanyKey
		From tBillingGroup (NOLOCK) 
		Where BillingGroupKey = @BillingGroupKey
		
		--BillingGroupGLCompanyKey = -1 means all GL Companies
		If isnull(@BillingGroupGLCompanyKey, 0) >=0 AND  isnull(@BillingGroupGLCompanyKey, 0) <> isnull(@GLCompanyKey, 0)
			Return -10
	End
	 
	-- if billing by campaign, unfortunately, the campaigns initially had no GLCompanyKey, so it is difficult to validate GL comps
	IF ISNULL(@CampaignKey, 0) > 0
	BEGIN
		DECLARE @CampaignClientKey int,
				@BillBy smallint
		
		SELECT	@CampaignClientKey = ClientKey,
				@BillBy = BillBy,
				@CampaignCurrencyID = CurrencyID 
		FROM	tCampaign (nolock)
		WHERE	CampaignKey = @CampaignKey
		
		IF @ClientKey <> @CampaignClientKey AND @BillBy <> 1
			RETURN -7 --The campaign must be for the same client, unless the campaign''s BillBy is set to "Project" (1)
	
		if @MultiCurrency = 1 And isnull(@CampaignCurrencyID, '''')  <> isnull(@CurrencyID, '''') 
			Return -12
	END	
	
	If @MultiCurrency = 1 And isnull(@CurCurrencyID, '''') <> isnull(@CurrencyID, '''')
	begin
		-- A currency must be as tight as a company
		-- so if the company is locked and the currency is changed, return an error
		if @LockCompany = 1
			 RETURN -13

		-- if there are some purchase order or voucher details, we cannot change the currency
		-- because when we apply PO to VI the project currency has to match
		if exists (select 1 from tPurchaseOrderDetail (nolock) where ProjectKey = @ProjectKey)
			RETURN -13
		
		if exists (select 1 from tVoucherDetail (nolock) where ProjectKey = @ProjectKey)
			RETURN -13
			
		if exists (select 1 from tTime (nolock) where ProjectKey = @ProjectKey)
			RETURN -13		 
	end 
	 
	-- If we changed the campaign, make sure that the project is not on an approved campaign estimate 
	IF ISNULL(@CurCampaignKey, 0) > 0 And ISNULL(@CampaignKey, 0) <> ISNULL(@CurCampaignKey, 0)
	BEGIN
		declare @SalesTax1Amount MONEY, @SalesTax2Amount MONEY

		declare @EstimateTotal money
		declare @LaborGross money
		declare @ExpenseGross money
		declare @TaxableTotal money
		declare @ContingencyTotal money
		declare @LaborNet money
		declare @ExpenseNet money
		declare @Hours decimal(24,4)
		declare @CampaignEstimateKey int

		if exists (select 1 
					from tEstimate e (nolock)
					inner join tEstimateProject ep (nolock) on  e.EstimateKey = ep.EstimateKey
					where e.CompanyKey = @CompanyKey
					and   e.InternalStatus = 4
					and   ep.ProjectKey = @ProjectKey)
			RETURN -8
			
			-- Added to update any Campaign Estimates by project this project was on
			select @CampaignEstimateKey = -1
			while (1=1)
				begin
					select @CampaignEstimateKey = min(e.EstimateKey) 
					from   tEstimate e (nolock)
					inner join tEstimateProject ep (nolock) on e.EstimateKey = ep.EstimateKey
					where  e.CampaignKey = @CurCampaignKey
					and    ep.ProjectKey = @ProjectKey
					and    e.EstimateKey > @CampaignEstimateKey 

						if @CampaignEstimateKey is null
						break
							DELETE tEstimateProject 
							WHERE  ProjectKey = @ProjectKey
							and    EstimateKey = @CampaignEstimateKey
							 
							select @EstimateTotal = sum(e.EstimateTotal)
								  ,@LaborGross = sum(e.LaborGross)
								  ,@ExpenseGross = sum(e.ExpenseGross)
								  ,@SalesTax1Amount = sum(e.SalesTaxAmount)
								  ,@SalesTax2Amount = sum(e.SalesTax2Amount)
								  ,@TaxableTotal = sum(e.TaxableTotal)
								  ,@ContingencyTotal = sum(e.ContingencyTotal)
								  ,@LaborNet = sum(e.LaborNet)
								  ,@ExpenseNet = sum(e.ExpenseNet)
								  ,@Hours = sum(e.Hours)

							from  tEstimateProject ep (nolock)
								inner join tEstimate e (nolock) on ep.ProjectEstimateKey = e.EstimateKey 
							where ep.EstimateKey = @CampaignEstimateKey
	
							UPDATE tEstimate
								SET    EstimateTotal	= ISNULL(@EstimateTotal, 0) 
									  ,LaborGross		= ISNULL(@LaborGross, 0)
									  ,ExpenseGross		= ISNULL(@ExpenseGross, 0)
									  ,SalesTaxAmount   = ISNULL(@SalesTax1Amount, 0)
									  ,SalesTax2Amount  = ISNULL(@SalesTax2Amount, 0)
									  ,TaxableTotal		= ISNULL(@TaxableTotal, 0)
									  ,ContingencyTotal	= ISNULL(@ContingencyTotal, 0)
									  ,LaborNet			= ISNULL(@LaborNet, 0)
									  ,ExpenseNet		= ISNULL(@ExpenseNet, 0)	
									  ,Hours			= ISNULL(@Hours, 0)	
								WHERE EstimateKey		= @CampaignEstimateKey
				end
	END

	--Just in case get rate from or rate sheet changes, roll rates onto assignments
	exec sptProjectRollupSetAssignmentRates @ProjectKey

	if @Closed = 1 and @CurClosed = 0
	
		Select @ProjectCloseDate = GETUTCDATE()
	
	if @Closed = 0 and @CurClosed = 1
		Select @ProjectCloseDate = NULL


	if @UpdateProjectStatus = 1
	BEGIN

		-- If the project is in a locked status, check that the user can update locked 
		select @Locked = ISNULL(ps.Locked, 0) 
					FROM tProject p (NOLOCK)
					INNER JOIN tProjectStatus ps on p.ProjectStatusKey = ps.ProjectStatusKey
					WHERE ProjectKey = @ProjectKey

		EXEC @EditLocked = sptUserHasRight @UserKey, ''prjEditLocked''
		
			if (@Locked = 1 AND @EditLocked = 0)
				return -511

	END --if @UpdateProjectStatus = 1

	--Validate Work Days don''t violate any Constraint Day of the Week settings on the schedule

	SELECT DISTINCT ConstraintDayOfTheWeek
	INTO	#ConstraintDayOfTheWeek
	FROM	tTask (nolock)
	WHERE	ProjectKey = @ProjectKey
	AND		ConstraintDayOfTheWeek > 0

	IF @WorkSun = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 1)
			RETURN -600
	IF @WorkMon = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 2)
			RETURN -600
	IF @WorkTue = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 3)
			RETURN -600
	IF @WorkWed = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 4)
			RETURN -600
	IF @WorkThur = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 5)
			RETURN -600
	IF @WorkFri = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 6)
			RETURN -600
	IF @WorkSat = 0
		IF EXISTS (SELECT NULL FROM #ConstraintDayOfTheWeek WHERE ConstraintDayOfTheWeek = 7)
			RETURN -600

	BEGIN TRAN
	
	UPDATE
		tProject
	SET
		ClientKey = @ClientKey,
		CampaignKey = @CampaignKey,
		ProjectName = @ProjectName,
		ProjectNumber = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(@ProjectNumber, ''&'', ''''), '','', ''''), ''"'', ''''), '''''''', ''''))),
		ProjectTypeKey = @ProjectTypeKey,
		ClientDivisionKey = @ClientDivisionKey,
		ClientProductKey = @ClientProductKey,
		ClientProjectNumber = @ClientProjectNumber,
		RequestKey = @RequestKey,
		BillingContact = @BillingContact,
		--CustomFieldKey = @CustomFieldKey,
		OfficeKey = @OfficeKey,
		GLCompanyKey = @GLCompanyKey,
		GLCompanySource = @GLCompanySource,
		ClassKey = @ClassKey,
		AccountManager = @AccountManager,
		Closed = @Closed,
		ProjectCloseDate = @ProjectCloseDate,
		ProjectStatusKey = @ProjectStatusKey,
		ProjectBillingStatusKey = @ProjectBillingStatusKey,
		ImageFolderKey = @ImageFolderKey,
		Active = ISNULL(@Active, 1),
		KeyPeople1 = @KeyPeople1,
		KeyPeople2 = @KeyPeople2,
		KeyPeople3 = @KeyPeople3,
		KeyPeople4 = @KeyPeople4,
		KeyPeople5 = @KeyPeople5,
		KeyPeople6 = @KeyPeople6,
		StatusNotes = @StatusNotes,
		DetailedNotes = @DetailedNotes,
		ClientNotes = @ClientNotes,
		Description = @Description,
		StartDate = @StartDate,
		CompleteDate = @CompleteDate,
		WorkMon = @WorkMon,
		WorkTue = @WorkTue,
		WorkWed = @WorkWed,
		WorkThur = @WorkThur,
		WorkFri = @WorkFri,
		WorkSat = @WorkSat,
		WorkSun = @WorkSun,
		ScheduleDirection = @ScheduleDirection,
		FlightStartDate = @FlightStartDate,
		FlightEndDate = @FlightEndDate,
		FlightInterval = @FlightInterval,
		ProjectColor = @ProjectColor,
		CampaignBudgetKey = @CampaignBudgetKey,
		TeamKey = @TeamKey,
		LeadKey = @LeadKey,
		LayoutKey = @LayoutKey,
		CampaignSegmentKey = @CampaignSegmentKey,
		
		GetRateFrom = @GetRateFrom,
		HourlyRate = @HourlyRate,
		TimeRateSheetKey = @TimeRateSheetKey,
		TitleRateSheetKey = @TitleRateSheetKey,
		OverrideRate = @OverrideRate,
		NonBillable = @NonBillable,
		UtilizationType = @UtilizationType,
		GetMarkupFrom = @GetMarkupFrom,
		ItemRateSheetKey = @ItemRateSheetKey,
		ItemMarkup = @ItemMarkup,
		IOCommission = @IOCommission,
		BCCommission = @BCCommission,
		Template = @Template,
		RetainerKey = CASE WHEN @BillingMethod = 3 THEN @RetainerKey ELSE NULL END,
		BillingMethod = @BillingMethod,
		ExpensesNotIncluded = @ExpensesNotIncluded,
		AutoIDTask = @AutoIDTask,
		SimpleSchedule = @SimpleSchedule,

		ClientBHours = @ClientBHours,
		ClientBLabor = @ClientBLabor,
		ClientBCO = @ClientBCO,
		ClientBExpenses = @ClientBExpenses,
		ClientAHours = @ClientAHours,
		ClientALabor = @ClientALabor,
		ClientAPO = @ClientAPO,
		ClientAExpenses = @ClientAExpenses,

		ShowTransactionsOnInvoices = @ShowTransactionsOnInvoices,
		DoNotPostWIP = @DoNotPostWIP,
		BillingGroupKey = @BillingGroupKey,
		ModelYear = @ModelYear,
		BillingManagerKey = @BillingManagerKey,
		CurrencyID = @CurrencyID,
		AnyoneChargeTime = @AnyoneChargeTime,

		PlanningBillOption = @PlanningBillOption,
		PlanningProjectMultipleTasks = @PlanningProjectMultipleTasks,
		PlanningProjectKey = @PlanningProjectKey,
		ProjectManager = @ProjectManager,
		PlanningProjectAutoRollover = @PlanningProjectAutoRollover,
		PlanningProjectAllowPeople = @PlanningProjectAllowPeople,
		
		DateUpdated = GETUTCDATE(),
		ForecastForceToFF = isnull(@ForecastForceToFF, 0),
		SetTaxableOnInvoice = isnull(@SetTaxableOnInvoice, 0),

		AvalaraOverrideTaxCodes = @AvalaraOverrideTaxCodes,
		AvalaraTaxCodeKey = @AvalaraTaxCodeKey,

		LimitProjectServices = @LimitProjectServices,

		OverrideScheduleOptions = @OverrideScheduleOptions,
		AutoScheduleProjects = @AutoScheduleProjects,
		AutoScheduleTaskEndDate = @AutoScheduleTaskEndDate,
		ActualDateUpdatesPlan = @ActualDateUpdatesPlan,
		WeekendBucket = @WeekendBucket,
		ExcludeFromRM = @ExcludeFromRM,
		OverrideExcludeFromRM = @OverrideExcludeFromRM,
		SlackChannelID = @SlackChannelID,
		RequireCommentsOnTimePj = @RequireCommentsOnTimePj,
		BucketPerWeek = @BucketPerWeek,
		BillExpensesByItem = @BillExpensesByItem
	WHERE
		ProjectKey = @ProjectKey 
		
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -100
	END
	
	IF @ProjectKey > 0  AND ISNULL(@OldClientKey, 0) <> ISNULL(@ClientKey, 0)
	BEGIN 	
		UPDATE tVoucherDetail
		SET    ClientKey = @ClientKey
		WHERE  ProjectKey = @ProjectKey	 
		--AND    ClientKey = @OldClientKey
		AND    isnull(ItemKey, 0) = 0

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
	
		UPDATE tVoucherDetail
		SET    tVoucherDetail.ClientKey = @ClientKey
		FROM   tItem i (nolock)  
		WHERE  tVoucherDetail.ProjectKey = @ProjectKey	 
		--AND    tVoucherDetail.ClientKey = @OldClientKey
		AND    tVoucherDetail.ItemKey = i.ItemKey
        AND    i.ItemType IN (0, 3)

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
       
        IF @IOClientLink = 1  
		BEGIN
			UPDATE tVoucherDetail
			SET    tVoucherDetail.ClientKey = @ClientKey
			FROM   tItem i (nolock)  
			WHERE  tVoucherDetail.ProjectKey = @ProjectKey	 
			--AND    tVoucherDetail.ClientKey = @OldClientKey
			AND    tVoucherDetail.ItemKey = i.ItemKey
			AND    i.ItemType = 1 -- IO
        
			IF @@ERROR <> 0
			BEGIN
				ROLLBACK TRAN
				RETURN -100
			END
	       
        END
        
		IF @BCClientLink = 1  
		BEGIN
			UPDATE tVoucherDetail
			SET    tVoucherDetail.ClientKey = @ClientKey
			FROM   tItem i (nolock)  
			WHERE  tVoucherDetail.ProjectKey = @ProjectKey	 
			--AND    tVoucherDetail.ClientKey = @OldClientKey
			AND    tVoucherDetail.ItemKey = i.ItemKey
			AND    i.ItemType = 2 -- BC

			IF @@ERROR <> 0
			BEGIN
				ROLLBACK TRAN
				RETURN -100
			END
        
        END

		-- update ACCRUAL GL Transactions where the section is not ''LINE''        
		UPDATE tTransaction
		SET    ClientKey = @ClientKey
		WHERE  CompanyKey = @CompanyKey
		AND    Entity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    ProjectKey = @ProjectKey	 
		--AND    ClientKey = @OldClientKey
		AND    Section <> 2

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
		
		UPDATE tCashTransactionLine
		SET    ClientKey = @ClientKey
		WHERE  CompanyKey = @CompanyKey
		AND    Entity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    ProjectKey = @ProjectKey	 
		--AND    ClientKey = @OldClientKey
		AND    Section <> 2

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
		
		-- update ACCRUAL GL Transactions where the section is ''LINE''        
		-- must join with voucher detail
		UPDATE tTransaction
		SET    tTransaction.ClientKey = vd.ClientKey
		FROM   tVoucherDetail vd (nolock)
		WHERE  tTransaction.CompanyKey = @CompanyKey
		AND    tTransaction.Entity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    tTransaction.ProjectKey = @ProjectKey	 
		--AND    tTransaction.ClientKey = @OldClientKey
		AND    tTransaction.Section = 2
		AND    tTransaction.DetailLineKey = vd.VoucherDetailKey
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END

		UPDATE tCashTransactionLine
		SET    tCashTransactionLine.ClientKey = vd.ClientKey
		FROM   tVoucherDetail vd (nolock)
		WHERE  tCashTransactionLine.CompanyKey = @CompanyKey
		AND    tCashTransactionLine.Entity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    tCashTransactionLine.ProjectKey = @ProjectKey	 
		--AND    tCashTransactionLine.ClientKey = @OldClientKey
		AND    tCashTransactionLine.Section = 2
		AND    tCashTransactionLine.DetailLineKey = vd.VoucherDetailKey
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END

		-- update CASH GL Transactions
		
		UPDATE tCashTransaction
		SET    tCashTransaction.ClientKey = @ClientKey
		WHERE  tCashTransaction.CompanyKey = @CompanyKey
		AND    tCashTransaction.Entity = ''PAYMENT''	 
		AND    tCashTransaction.AEntity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    tCashTransaction.ProjectKey = @ProjectKey	 
		--AND    tCashTransaction.ClientKey = @OldClientKey
		AND    tCashTransaction.Section <> 2
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
		
		UPDATE tCashTransaction
		SET    tCashTransaction.ClientKey = vd.ClientKey
		FROM   tVoucherDetail vd (nolock)
		WHERE  tCashTransaction.CompanyKey = @CompanyKey
		AND    tCashTransaction.Entity = ''PAYMENT''	 
		AND    tCashTransaction.AEntity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    tCashTransaction.ProjectKey = @ProjectKey	 
		--AND    tCashTransaction.ClientKey = @OldClientKey
		AND    tCashTransaction.Section = 2
		AND    tCashTransaction.DetailLineKey = vd.VoucherDetailKey

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
		
		UPDATE tCashTransaction
		SET    tCashTransaction.ClientKey = @ClientKey
		WHERE  tCashTransaction.CompanyKey = @CompanyKey
		AND    tCashTransaction.Entity IN (''VOUCHER'',''CREDITCARD'')	 
		AND    tCashTransaction.ProjectKey = @ProjectKey	 
		--AND    tCashTransaction.ClientKey = @OldClientKey
		AND    tCashTransaction.Section <> 2
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
		
		UPDATE tCashTransaction
		SET    tCashTransaction.ClientKey = vd.ClientKey
		FROM   tVoucherDetail vd (nolock)
		WHERE  tCashTransaction.CompanyKey = @CompanyKey
		AND    tCashTransaction.Entity IN (''VOUCHER'',''CREDITCARD'') 
		AND    tCashTransaction.ProjectKey = @ProjectKey	 
		--AND    tCashTransaction.ClientKey = @OldClientKey
		AND    tCashTransaction.Section = 2
		AND    tCashTransaction.DetailLineKey = vd.VoucherDetailKey

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -100
		END
		
	END
		
	COMMIT TRAN
		 
	-- if we close a project, do a final rollup 
	-- this does not have to be done in a SQL transaction
	if @Closed = 1 and @CurClosed = 0
		exec sptProjectRollupUpdate @ProjectKey, -1, 1, 1, 1, 1

 RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptMediaPlanBottomLineInvoiceGetDetails]'
GO
IF OBJECT_ID(N'[dbo].[sptMediaPlanBottomLineInvoiceGetDetails]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptMediaPlanBottomLineInvoiceGetDetails]
     @CompanyKey int
	,@MediaPlanKey int
	,@VendorKey int
	,@LinkID varchar(50) -- LinkID of the Invoice header, can be used to generate a linkID on the detail 
	,@POLinkID varchar(50)  -- Order Link ID on the MPVDs
	,@InvoiceTotal decimal(24,6)
	
as --Encrypt

/*
|| When         Who Rel         What
|| 07/1/20      GHL 20.070      New For Bottom Line Invoicing in Media Plans
||                              Get a list of MPVD details 
|| 05/30/2024   MAS 24.06.16    (673092) Added primary key to #detail
|| 08/07/2026   MAS 26.08.16    (734579) Negative (credit) bottom line invoices now apply correctly.
||                              The old code split into three branches (capacity greater than, equal to,
||                              or less than the invoice total) that only worked for positive amounts.
||                              Replaced with one loop that handles positive invoices and credits the
||                              same way. Positive-invoice behavior is unchanged; a credit lands on the
||                              earliest line, matching how Strata applies bottom line credits.
*/

declare @MediaPlanDetailKey int
declare @MediaPlanDetailID int -- so that we can have a sort other than the key
declare @Apply money
declare @RemainingToApply money

	create table #detail(MediaPlanDetailID int identity primary key, MediaPlanDetailKey int null
	, LinkID varchar(100) null, SpotLinkID varchar(50) null
	, Cost money null, Applied money null, AmountToApply money null
	, LastVoucher int null, UpdateFlag int null)

	insert #detail (MediaPlanDetailKey, SpotLinkID, Cost, Applied, AmountToApply, LastVoucher)
	select mpd.MediaPlanDetailKey, mpd.SpotLinkID, mpd.Cost, 0, 0, 0
	from   tMediaPlanDetail mpd (nolock)
	inner join tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey 
	inner join tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey 
	where  mp.CompanyKey = @CompanyKey
	and    mp.MediaPlanKey = @MediaPlanKey 
	and    upper(mpd.OrderLinkID) = upper(@POLinkID) -- we need a PO link ID otherwise the list could be very long
	and    mpv.VendorKey = @VendorKey 

	-- control the sort here
	order by mpd.StartDate

	update #detail
	set    #detail.Applied = (select sum(mpvd.Cost) from tMediaPlanVoucherDetail mpvd (nolock) 
	where mpvd.MediaPlanDetailKey = #detail.MediaPlanDetailKey
	) 

	update #detail
	set    AmountToApply = isnull(Cost, 0) - isnull(Applied, 0)  

	-- delete if fully applied
	delete #detail
	where AmountToApply = 0 

	-- Spread the invoice total across the order''s buy lines that still have an open
	-- balance, oldest first (by start date). Each line takes up to its open balance
	-- until the whole invoice total is used up; anything left over goes on the last
	-- line used. Works for a normal invoice (positive) and a credit (negative) alike;
	-- a credit lands on the earliest line, the same way Strata applies bottom-line credits.
	select @RemainingToApply = @InvoiceTotal
	select @MediaPlanDetailID = -1
	while (1=1)
	begin
		select @MediaPlanDetailID = min(MediaPlanDetailID)
		from   #detail
		where  MediaPlanDetailID > @MediaPlanDetailID

		if @MediaPlanDetailID is null
			break

		select @Apply = AmountToApply from #detail
		where MediaPlanDetailID = @MediaPlanDetailID

		-- only take what''s still left of the invoice (a credit lands in full on this line)
		if sign(@Apply) <> sign(@RemainingToApply) or abs(@Apply) > abs(@RemainingToApply)
			select @Apply = @RemainingToApply

		select @RemainingToApply = @RemainingToApply - @Apply

		-- mark the detail as being selected
		update #detail set AmountToApply = @Apply, UpdateFlag = 1
		where MediaPlanDetailID = @MediaPlanDetailID

		if @RemainingToApply = 0
			break
	end -- distribution loop

	-- if anything is still left, add it to the last line so the pieces total the invoice
	if @RemainingToApply <> 0
	begin
		select @MediaPlanDetailID = max(MediaPlanDetailID) from #detail where UpdateFlag = 1
		update #detail set AmountToApply = isnull(AmountToApply, 0) + @RemainingToApply
		where MediaPlanDetailID = @MediaPlanDetailID
	end

	-- delete the ones we do not want to apply
	delete #detail where isnull(UpdateFlag, 0) = 0

	/*
	create table #detail(MediaPlanDetailID int identity, MediaPlanDetailKey int null
	, LinkID varchar(100) null, SpotLinkID varchar(50) null
	, Cost money null, Applied money null, AmountToApply money null
	, LastVoucher int null, UpdateFlag int null)
	*/

	select MediaPlanDetailKey
		, LinkID	-- null for now but could be created based on the linkID of the header 
		, SpotLinkID
		, AmountToApply as Cost
		, LastVoucher  
	     , -1 * MediaPlanDetailID as MediaPlanVoucherDetailKey -- negative will cause an Add
	from #detail

	return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserLeadConvert]'
GO
IF OBJECT_ID(N'[dbo].[sptUserLeadConvert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptUserLeadConvert]
	(
	@OwnerKey INT,
	@UserKey INT,
	@UserLeadKey INT,
	@UserCompanyKey INT,
	@CompanyKey INT,
	@CreateContact INT,
	@FirstName NVARCHAR(50),
	@LastName NVARCHAR(50),
	@ContactFolderKey INT,
	@CreateCompany INT,
	@CompanyName NVARCHAR(150),
	@CompanyFolderKey INT,
	@CreateOpportunity INT,
	@OppSubject NVARCHAR(200),
	@OppDescription NVARCHAR(4000),
	@OppStageKey INT,
	@OppFolderKey INT,
	@OppStatusKey INT,
	@CreateActivity INT,
	@ActivitySubject VARCHAR(75),
	@ActivityNote TEXT,
	@ActivityDate smalldatetime,
	@ActivityStartTime smalldatetime,
	@ActivityEndTime smalldatetime,
	@ActivityCompleted TINYINT,
	@ActivityFolderKey INT,
	@ActivityTypeKey int,
	@AddToEmail int,
	@ActivityAssignedUserKey int,
	@ActivityReminderMinutes int,
	@ActivityPriority varchar(20),
	@OppProjectTypeKey int,
	@OppAmount money,
	@oContactIdentity INT OUTPUT,
	@oCompanyIdentity INT OUTPUT,
	@oOpportunityIdentity INT OUTPUT,
	@oActivityIdentity INT OUTPUT,
	@oExistingActivityIdentity INT OUTPUT
	)
AS --Encrypt

/*
|| When      Who Rel      What
|| 08/13/08  QMD 10.5.0.0 Created to convert a lead into a contact, lead, or opportunity
|| 01/30/09  RTC 10.5.0.0 Added existing activity logic and corrected the new activity logic
|| 03/06/09  QMD 10.5.0.0 Added in Opportunity Custom Fields
|| 4/29/09   CRG 10.5.0.0 Added ActivityAssignedUserKey, ActivityReminderMinutes, ActivityPriority
|| 5/19/09   CRG 10.5.0.0 Added ActivityStartTime and ActivityEndTime
|| 5/19/09   MAS 10.5.0.0 Added tUser DateLeadCreated = DateAdded
|| 5/29/09   MFT 10.5.0.0 tUserLead Comments to tUser only if no company created
|| 6/01/09   MFT 10.5.0.0 Made tUser.UserCompanyName = tCompany.CompanyName if linked
|| 6/24/09   MAS 10.5.0.0 (55679) Added a input param, @UserCompanyKey.  It''s used if the user wants
						  to convert a lead and use an existing Company.  Moved the History copy so that
						  it''s used for both new and exsisting companies
|| 08/03/09  GWG 10.5.0.6 Fixed level history if stage is null
|| 10/29/09  GHL 10.5.1.3 (66978) The Activity should not be threaded, i.e. leave
||                        ParentActivityKey = 0
|| 2/20/10   GWG 10.5.1.9 Changed the save of comments so they are saved to the company and the contact.
|| 02/26/10  QMD 10.5.1.9 Add Insert into tUserLeadUpdateLog
|| 3/01/10   RLB 10.5.1.9 Added ActivityTypeKey on converted Leads to contacts
|| 05/18/10  RLB 10.5.2.3 (80993)Default Client Vendor Login to 1 when converting to contact
|| 06/22/10  MFT 10.5.3.1 (83691) Set labor and expense defaults on tCompany (from tPreference)
|| 10/11/10  RLB 10.5.3.6 Added Email to for an enhancement
|| 01/12/11  QMD 10.5.4.0 Added Exec sptMarketingListListDeleteLogInsert 
|| 02/16/11  GHL 10.5.4.1 Added created user, company, opportunity, activity to the log in order to help us with the report 
|| 07/25/12  GHL 10.5.5.8 Added propagation of the GL company if we restrict to GL company
|| 10/22/15  GWG 10.5.9.7 Added lead ID
|| 02/03/17  RLB 10.6.1.1 setting Opp description on convert
|| 02/12/21  RLS 21.0.3.0 (546075) Changed @CompanyName to NVARCHAR
|| 02/17/21  RLS 21.0.3.0 (546075) Changed @FirstName and @LastName to NVARCHAR
|| 04/30/21  RLS 21.0.7.0 (556492) Changed @OppSubject NVARCHAR(200). Was varchar(75); underlying table is 200
|| 04/30/21  RLS 21.0.7.0 (556492) Changed @OppDescriptiont NVARCHAR(4000). Was TEXT; underlying table is NVARCHAR(4000) - was VARCHAR(4000)
|| 05/02/22  RLS 22.0.5.0 (596066) Add parameters @OppProjectTypeKey and @OppAmount and use them if populated
|| 06/03/23  RLB 23.07.16 (643147) set labor and AGI since sales amount if an Opp is created like the edit page would do if entered
|| 09/18/23  RLB 23.10.15 (651457) added check for add contact or company because one is required or the lead just get deleted
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time, this proc is for converting to a new Lead
*/
	
	IF @CreateCompany = 0 AND @CreateContact = 0
		Return -3

	Declare @ConvertDate smalldatetime
	Select @ConvertDate = Cast(Cast(Month(GETDATE()) as varchar) + ''/'' + Cast(Day(GETDATE()) as varchar) + ''/'' + Cast(Year(GETDATE()) as varchar) as smalldatetime)
	
	select @oExistingActivityIdentity = min(ActivityKey)
	from tActivity (nolock)
	where UserLeadKey = @UserLeadKey
	
	IF EXISTS(SELECT 1 FROM tUserLead WHERE UserLeadKey = @UserLeadKey)
	  BEGIN
	  	DECLARE
				@GetRateFrom smallint,
				@HourlyRate money,
				@TimeRateSheetKey int,
				@GetMarkupFrom smallint,
				@ItemMarkup decimal,
				@IOCommission decimal,
				@BCCommission decimal,
				@ItemRateSheetKey int,
				@GLCompanyKey int,
				@RestrictToGLCompany int
			
			SELECT @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0) from tPreference (NOLOCK) WHERE CompanyKey = @CompanyKey
			-- leave GLCompanyKey null
			SELECT @GLCompanyKey = GLCompanyKey FROM tUserLead (NOLOCK) WHERE UserLeadKey = @UserLeadKey

			IF @CreateCompany = 1
			  BEGIN
			  SELECT
			  		@GetRateFrom = GetRateFrom,
						@HourlyRate = HourlyRate,
						@TimeRateSheetKey = TimeRateSheetKey,
						@GetMarkupFrom = GetMarkupFrom,
						@ItemMarkup = ItemMarkup,
						@IOCommission = IOCommission,
						@BCCommission = BCCommission,
						@ItemRateSheetKey = ItemRateSheetKey
			  FROM
			  	tPreference (NOLOCK)
			  WHERE
			  	CompanyKey = @CompanyKey
			  
				INSERT INTO tCompany
						(
						CompanyName,
						Phone,
						Fax,
						WebSite, 
						Active,
						AccountManagerKey,
						OwnerCompanyKey,					
						ContactOwnerKey,
						CompanyTypeKey,
						DateAdded,
						DateUpdated,
						CreatedBy,
						ModifiedBy,
						CMFolderKey,
						CustomFieldKey, 
						Comments,
						SalesPersonKey,
						SourceKey,
						DateConverted,
						GetRateFrom,
						HourlyRate,
						TimeRateSheetKey,
						GetMarkupFrom,
						ItemMarkup,
						IOCommission,
						BCCommission,
						ItemRateSheetKey
						)
				
				SELECT	CASE ISNULL(@CompanyName,'''') WHEN '''' THEN CompanyName ELSE @CompanyName END,
						CompanyPhone,
						CompanyFax,
						CompanyWebsite,		
						1,			
						CASE WHEN @OwnerKey > 0 THEN @OwnerKey ELSE OwnerKey END,
						CompanyKey,
						CASE WHEN @OwnerKey > 0 THEN @OwnerKey ELSE OwnerKey END,
						CompanyTypeKey,			
						GETUTCDATE(),
						GETUTCDATE(),
						@UserKey,
						@UserKey,
						CASE ISNULL(@CompanyFolderKey, 0) WHEN 0 THEN NULL ELSE @CompanyFolderKey END,
						CompanyCustomFieldKey,
						Comments, 
						CASE WHEN @OwnerKey > 0 THEN @OwnerKey ELSE OwnerKey END,
						CompanySourceKey,
						@ConvertDate,
						@GetRateFrom,
						@HourlyRate,
						@TimeRateSheetKey,
						@GetMarkupFrom,
						@ItemMarkup,
						@IOCommission,
						@BCCommission,
						@ItemRateSheetKey
				FROM	tUserLead (nolock)
				WHERE	UserLeadKey = @UserLeadKey
				
				SELECT @oCompanyIdentity = @@Identity		
				
				if @RestrictToGLCompany = 1 and isnull(@GLCompanyKey, 0) > 0
					-- use sptGLCompanyAccessInsert because it checks if record exists before inserting
					exec sptGLCompanyAccessInsert ''tCompany'', @oCompanyIdentity, @GLCompanyKey
		
			  END
			ELSE
			  BEGIN			
				-- Set @oCompanyIdentity if we''re not creating a new company 
				If ISNULL(@oCompanyIdentity,0) = 0
					Set @oCompanyIdentity = @UserCompanyKey

				-- If we are using an existing company, give right access to it
				if @RestrictToGLCompany = 1 And isnull(@UserCompanyKey, 0) > 0 and isnull(@GLCompanyKey, 0) > 0
					-- use sptGLCompanyAccessInsert because it checks if record exists before inserting
					exec sptGLCompanyAccessInsert ''tCompany'', @UserCompanyKey, @GLCompanyKey

			  END

			-- Copy the Activity records regardless of whether it''s a new company or not
			UPDATE	tActivity
			SET		ContactCompanyKey = @oCompanyIdentity
			WHERE	UserLeadKey = @UserLeadKey

			INSERT	tActivityLink (ActivityKey, Entity, EntityKey)
			SELECT	ActivityKey, ''tCompany'', @oCompanyIdentity
			FROM	tActivity (NOLOCK)
			WHERE	UserLeadKey = @UserLeadKey


			IF @CreateContact = 1
			  BEGIN
				
			  	SELECT
			  		@CompanyName = CompanyName
			  	FROM
			  		tCompany (nolock)
			  	WHERE
			  		CompanyKey = @oCompanyIdentity
			  	
				INSERT INTO tUser 
						(
						CompanyKey,
						FirstName, 
						MiddleName, 
						LastName, 
						Salutation, 
						Phone1, 
						Phone2, 							
						Cell, 
						Fax, 
						Pager, 
						Title, 
						Email, 
						ContactMethod, 
						DoNotCall, 
						DoNotEmail, 							
						DoNotMail, 
						DoNotFax, 
						AddedByKey, 
						TimeZoneIndex, 
						OwnerKey, 							
						Department, 
						UserRole, 
						Assistant, 
						AssistantPhone, 							
						AssistantEmail, 
						Birthday, 
						SpouseName, 
						Children, 
						Anniversary, 
						Hobbies, 
						Comments, 								
						UserCompanyName,
						CMFolderKey,
						DateAdded,
						Active,
						OwnerCompanyKey,
						CustomFieldKey,
						DateConverted,
						DateLeadCreated,
						ClientVendorLogin
						)
				SELECT	@oCompanyIdentity,  
						@FirstName, 
						MiddleName, 
						@LastName, 					
						Salutation, 
						Phone1, 
						Phone2, 
						Cell, 
						Fax, 
						Pager, 
						Title, 
						Email, 					
						ContactMethod, 
						DoNotCall, 
						DoNotEmail, 
						DoNotMail, 
						DoNotFax, 
						AddedByKey, 
						TimeZoneIndex, 
						CASE WHEN @OwnerKey > 0 THEN @OwnerKey ELSE OwnerKey END, 					
						Department, 
						UserRole, 
						Assistant, 
						AssistantPhone, 
						AssistantEmail,					
						Birthday, 
						SpouseName, 
						Children, 
						Anniversary, 
						Hobbies, 
						Comments, 
						CASE ISNULL(@CompanyName,'''') WHEN '''' THEN CompanyName ELSE @CompanyName END,
						CASE ISNULL(@ContactFolderKey, 0) WHEN 0 THEN NULL ELSE @ContactFolderKey END,
						GETDATE(),
						1,
						@CompanyKey,
						UserCustomFieldKey,
						@ConvertDate,
						DateAdded,
						1	
				FROM	tUserLead (NOLOCK)
				WHERE	UserLeadKey = @UserLeadKey	

				SET @oContactIdentity = @@IDENTITY			   

				if @RestrictToGLCompany = 1 and isnull(@GLCompanyKey, 0) > 0
					-- use sptGLCompanyAccessInsert because it checks if record exists before inserting
					exec sptGLCompanyAccessInsert ''tUser'', @oContactIdentity, @GLCompanyKey

				UPDATE	tActivity
				SET		ContactKey = @oContactIdentity
				WHERE	UserLeadKey = @UserLeadKey
			
				INSERT  tActivityLink (ActivityKey, Entity, EntityKey)
				SELECT	ActivityKey, ''tUser'', @oContactIdentity
				FROM	tActivity (NOLOCK)
				WHERE	UserLeadKey = @UserLeadKey

				-- Log Change MarketingListKey
				IF EXISTS(SELECT * FROM tMarketingListList (NOLOCK) WHERE Entity = ''tUserLead'' AND EntityKey = @UserLeadKey)
				  BEGIN
					DECLARE @pList VARCHAR(50)
					SELECT @pList = ''@UserLeadKey = '' + CONVERT(VARCHAR(10),@UserLeadKey)
					EXEC sptMarketingListListDeleteLogInsert @UserKey, @UserLeadKey, ''tUserLead'', ''sptUserLeadConvert'', @pList, ''UI''
				  END
				  
				UPDATE	tMarketingListList
				SET		Entity = ''tUser'', EntityKey = @oContactIdentity
				WHERE	EntityKey = @UserLeadKey 
						AND Entity = ''tUserLead''				

				IF @CreateCompany = 1
				  BEGIN
					UPDATE	tCompany
					SET		PrimaryContact = @oContactIdentity
					WHERE	CompanyKey = @oCompanyIdentity

				  END
			  END
			  
			-- Update addresses based on what was created
			Declare @BKey int, @HKey int, @OKey int
			 
			Select @BKey = AddressKey, @HKey = HomeAddressKey, @OKey = OtherAddressKey from tUserLead (nolock) Where UserLeadKey = @UserLeadKey
			 
			if @CreateContact = 0 and @CreateCompany = 1
			BEGIN
					-- move all the addresses over
				UPDATE	tAddress
				SET		CompanyKey = @oCompanyIdentity, Entity = NULL, EntityKey = NULL
				WHERE	Entity = ''tUserLead''
						AND EntityKey = @UserLeadKey
				
				Update tCompany Set DefaultAddressKey = @BKey Where CompanyKey = @oCompanyIdentity
			END

			if @CreateContact = 1 and @CreateCompany = 1
			BEGIN
					-- Just update the company address
				UPDATE	tAddress
				SET		CompanyKey = @oCompanyIdentity, Entity = NULL, EntityKey = NULL
				WHERE	AddressKey = @BKey
				
				Update tCompany Set DefaultAddressKey = @BKey Where CompanyKey = @oCompanyIdentity
					-- move the rest to the user
				UPDATE	tAddress
				SET		CompanyKey = 0, Entity = ''tUser'', EntityKey = @oContactIdentity
				WHERE	Entity = ''tUserLead''
						AND EntityKey = @UserLeadKey
				
				Update tUser Set HomeAddressKey = @HKey, OtherAddressKey = @OKey Where UserKey = @oContactIdentity
				
			END
			if @CreateContact = 1 and @CreateCompany = 0
			BEGIN
					-- move the rest to the user
				UPDATE	tAddress
				SET		CompanyKey = 0, Entity = ''tUser'', EntityKey = @oContactIdentity
				WHERE	Entity = ''tUserLead''
						AND EntityKey = @UserLeadKey
				
				Update tUser Set AddressKey = @BKey, HomeAddressKey = @HKey, OtherAddressKey = @OKey Where UserKey = @oContactIdentity
				
			END

			IF @CreateOpportunity = 1
			  BEGIN

				DECLARE @Probability INT, @LeadID int, @Labor money = null, @AGI money = null
				Select @LeadID = ISNULL(Max(LeadID), 0) + 1 from tLead (nolock) 
				Where CompanyKey = @CompanyKey 

				if ISNULL(@OppAmount, 0) > 0
					select @Labor = @OppAmount, @AGI = @OppAmount
				
				SELECT @Probability = DefaultProbability FROM tLeadStage (NOLOCK) WHERE LeadStageKey = @OppStageKey
		
				INSERT INTO tLead
						(
						CompanyKey,
						[Subject],
						Comments,
						ContactCompanyKey,
						ContactKey,
						AccountManagerKey,
						ProjectTypeKey,
						LeadStageKey,
						WWPCurrentLevel,
						SaleAmount,
						Labor,
						AGI,
						AddedByKey,
						UpdatedByKey,
						DateAdded,
						DateUpdated,
						LeadStatusKey,
						CMFolderKey,
						Probability,
						CustomFieldKey,
						DateConverted,
						GLCompanyKey, 
						LeadID
						)
				SELECT	@CompanyKey,
						@OppSubject,
						@OppDescription,
						@oCompanyIdentity,
						@oContactIdentity,
						OwnerKey,
						CASE ISNULL(@OppProjectTypeKey, 0) WHEN 0 THEN OppProjectTypeKey ELSE @OppProjectTypeKey END,
						@OppStageKey,
						1,
						CASE ISNULL(@OppAmount, 0) WHEN 0 THEN OppAmount ELSE @OppAmount END,
						@Labor,
						@AGI,
						@UserKey,
						@UserKey,
						GETUTCDATE(),
						GETUTCDATE(),
						@OppStatusKey,
						CASE ISNULL(@OppFolderKey, 0) WHEN 0 THEN NULL ELSE @OppFolderKey END,
						@Probability,
						OppCustomFieldKey,
						@ConvertDate,
						@GLCompanyKey,
						@LeadID
				FROM	tUserLead (NOLOCK)
				WHERE	UserLeadKey = @UserLeadKey
					
				SET @oOpportunityIdentity = @@IDENTITY			   
				
				IF ISNULL(@oContactIdentity,0) > 0
				  BEGIN
					INSERT INTO tLeadUser (LeadKey, UserKey, [Role])
					SELECT @oOpportunityIdentity, @oContactIdentity, UserRole FROM tUserLead (NOLOCK) WHERE UserLeadKey = @UserLeadKey

				  END 

				if @OppStageKey is not null
					INSERT INTO tLeadStageHistory (LeadKey, LeadStageKey, HistoryDate, Comment)
					VALUES (@oOpportunityIdentity, @OppStageKey, GETDATE(), ''Opportunity Created'')

				INSERT INTO tLevelHistory (Entity, EntityKey, [Level], LevelDate)
				VALUES (''tLead'', @oOpportunityIdentity, 1, GETUTCDATE())
				

				UPDATE	tActivity
				SET		LeadKey = @oOpportunityIdentity
				WHERE	UserLeadKey = @UserLeadKey
		

				INSERT INTO tActivityLink (ActivityKey, Entity, EntityKey)
				SELECT	ActivityKey, ''tLead'', @oOpportunityIdentity
				FROM	tActivity (NOLOCK)
				WHERE	UserLeadKey = @UserLeadKey


			  END

			IF @CreateActivity = 1
			  BEGIN
		
				INSERT INTO tActivity
						(
						[Subject],
						ActivityDate,
						Completed,
						Priority,
						CompanyKey,
						ContactCompanyKey,
						ContactKey,
						OriginatorUserKey,
						LeadKey,
						AddedByKey,
						UpdatedByKey,
						DateAdded,
						DateUpdated,
						ActivityTypeKey,
						AssignedUserKey,
						Notes,
						CMFolderKey,
						ReminderMinutes,
						StartTime,
						EndTime,
						GLCompanyKey,
						ActivityEntity
						)
				SELECT 
						@ActivitySubject,
						@ActivityDate,
						@ActivityCompleted,
						@ActivityPriority,
						@CompanyKey,
						@oCompanyIdentity,
						@oContactIdentity,
						@UserKey,
						@oOpportunityIdentity,
						@UserKey,
						@UserKey,
						GETUTCDATE(),
						GETUTCDATE(),
						@ActivityTypeKey,
						@ActivityAssignedUserKey,
						@ActivityNote,
						CASE ISNULL(@ActivityFolderKey, 0) WHEN 0 THEN NULL ELSE @ActivityFolderKey END,
						@ActivityReminderMinutes,
						@ActivityStartTime,
						@ActivityEndTime,
						@GLCompanyKey,
						''Activity''
				FROM	tUserLead (NOLOCK)
				WHERE	UserLeadKey = @UserLeadKey
				
				SET @oActivityIdentity = @@IDENTITY			   

				--need to update newly inserted activity with the new key
				update tActivity set RootActivityKey = @oActivityIdentity
				where ActivityKey = @oActivityIdentity
				
				
				IF ISNULL(@oCompanyIdentity,0) > 0
				  BEGIN
					INSERT INTO tActivityLink (ActivityKey, Entity, EntityKey)
					VALUES (@oActivityIdentity, ''tCompany'', @oCompanyIdentity)

				  END

				IF ISNULL(@oContactIdentity,0) > 0
				  BEGIN
					INSERT INTO tActivityLink (ActivityKey, Entity, EntityKey)
					VALUES (@oActivityIdentity, ''tUser'', @oContactIdentity)

				  END

				IF ISNULL(@oOpportunityIdentity,0) > 0
				  BEGIN
					INSERT INTO tActivityLink (ActivityKey, Entity, EntityKey)
					VALUES (@oActivityIdentity, ''tLead'', @oOpportunityIdentity)

				  END
				IF ISNULL(@AddToEmail, 0) > 0
					BEGIN
						EXEC sptActivityEmailUpdate @oActivityIdentity, @oContactIdentity, @UserKey, ''insert''
					
					END
			
			  END



		   -- clean up activity table by getting rid of the UserLeadKey
		   UPDATE tActivity
		   SET    UserLeadKey = NULL
		   WHERE  UserLeadKey = @UserLeadKey


		   -- clean up ActivityLink table
		   DELETE tActivityLink
		   WHERE  Entity = ''tUserLead'' 
				  AND EntityKey = @UserLeadKey		
									
		  -- Log Deletes
		   select @CreateCompany = isnull(@CreateCompany, 0)
		   select @CreateContact = isnull(@CreateContact, 0)
           select @CreateOpportunity = isnull(@CreateOpportunity, 0) 
           select @CreateActivity = isnull(@CreateActivity, 0)

		   select @oCompanyIdentity = isnull(@oCompanyIdentity, 0)
		   select @oContactIdentity = isnull(@oContactIdentity, 0)
           select @oOpportunityIdentity = isnull(@oOpportunityIdentity, 0) 
           select @oActivityIdentity = isnull(@oActivityIdentity, 0)

		   DECLARE @parmList VARCHAR(1500)
           SELECT @parmList = ''@UserLeadKey='' + CONVERT(VARCHAR(15),@UserLeadKey)
		   SELECT @parmList = @parmList + '',@CreateCompany='' + CONVERT(VARCHAR(10),@CreateCompany)
		   SELECT @parmList = @parmList + '',@CreateContact='' + CONVERT(VARCHAR(10),@CreateContact)
		   SELECT @parmList = @parmList + '',@CreateOpportunity='' + CONVERT(VARCHAR(10),@CreateOpportunity)
		   SELECT @parmList = @parmList + '',@CreateActivity='' + CONVERT(VARCHAR(10),@CreateActivity)

		   SELECT @parmList = @parmList + '',@oCompanyIdentity='' + CONVERT(VARCHAR(15),@oCompanyIdentity)
		   SELECT @parmList = @parmList + '',@oContactIdentity='' + CONVERT(VARCHAR(15),@oContactIdentity)
		   SELECT @parmList = @parmList + '',@oOpportunityIdentity='' + CONVERT(VARCHAR(15),@oOpportunityIdentity)
		   SELECT @parmList = @parmList + '',@oActivityIdentity='' + CONVERT(VARCHAR(15),@oActivityIdentity)

		   EXEC sptUserLeadUpdateLogInsert @UserLeadKey, @UserKey, ''D'', ''sptUserLeadConvert'', @parmList, ''UI''					
		
		  -- delete lead
		   Delete tUserLead
		   WHERE  UserLeadKey = @UserLeadKey
	  END
	ELSE 
	  RETURN -2'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectNoteInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectNoteInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptProjectNoteInsert]
	@CompanyKey int,
	@Entity varchar(50),
	@EntityKey int,
	@ProjectKey int,
	@ParentActivityKey int,
	@AddedByKey int,
	@Subject varchar(2000),
	@Note text,
	@VisibleToClient tinyint,
	@AddedByEmail varchar(300),
	@oIdentity INT OUTPUT
AS --Encrypt

/*
|| When      Who Rel      What
|| 01/09/09  GHL 10.5.0.0 Inserting now in tActivity instead of tProjectNote
|| 07/10/09  QMD 10.5.0.4 Removed TimeZoneIndex
|| 12/21/10  GHL 10.5.3.9 Added ActivityEntity
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time - this proc no longer being used 
*/

	SELECT @AddedByKey = ISNULL(@AddedByKey, 0)
	
	IF @AddedByKey = 0 AND @AddedByEmail IS NOT NULL
	BEGIN
		SELECT @AddedByKey = UserKey 
		FROM   tUser (NOLOCK)
		WHERE  Email = @AddedByEmail
		AND    (CompanyKey = @CompanyKey OR OwnerCompanyKey = @CompanyKey)
		
		SELECT @AddedByKey = ISNULL(@AddedByKey, 0)	
	END  
	
	DECLARE @ClientKey INT
	DECLARE @DateAdded DATETIME
	DECLARE @RootActivityKey INT
	DECLARE @ActivityEntity varchar(50)

	SELECT @ClientKey = ClientKey FROM tProject (NOLOCK) WHERE ProjectKey = @ProjectKey 
	SELECT @DateAdded = CONVERT(VARCHAR(10), GETDATE(), 101)
	
	IF ISNULL(@ProjectKey, 0) > 0
		SELECT @ActivityEntity = ''Diary''
	ELSE
		SELECT @ActivityEntity = ''Activity''
	
	INSERT tActivity
		(
		CompanyKey,
		ParentActivityKey,
		RootActivityKey,
		Private,
		Type,
		--Priority,
		Subject,
		ContactCompanyKey,
		ContactKey,
		UserLeadKey,
		LeadKey,
		ProjectKey,
		StandardActivityKey,
		AssignedUserKey,
		OriginatorUserKey,
		CustomFieldKey,
		VisibleToClient,
		Outcome,
		ActivityDate,
		StartTime,
		EndTime,
		ReminderMinutes,
		ActivityTime,
		Completed,
		DateCompleted,
		Notes,
		AddedByKey,
		UpdatedByKey,
		DateAdded,
		DateUpdated,
		ActivityEntity
		)
		
		Select 
		@CompanyKey, --CompanyKey,
		@ParentActivityKey, --ParentActivityKey,
		0, --RootActivityKey,
		0, --Private,
		NULL, --Type,
		--NULL, --Priority,
		@Subject, --Subject,
		@ClientKey, --ContactCompanyKey,
		NULL, --ContactKey,
		NULL, --UserLeadKey,
		NULL, --LeadKey,
		@ProjectKey, --ProjectKey,
		NULL, --StandardActivityKey,
		@AddedByKey, --AssignedUserKey,
		@AddedByKey, --OriginatorUserKey,
		NULL, --CustomFieldKey,
		@VisibleToClient, --VisibleToClient,
		NULL, --Outcome,
		@DateAdded, --ActivityDate,
		NULL, --StartTime,
		NULL, --EndTime,
		0, --ReminderMinutes,
		NULL, --ActivityTime,
		1, --Completed,
		@DateAdded, --DateCompleted,
		@Note, --Notes,
		@AddedByKey, --AddedByKey,
		@AddedByKey, --UpdatedByKey,
		GETUTCDATE(), --DateAdded,
		GETUTCDATE(), --DateUpdated
	    @ActivityEntity

	SELECT @oIdentity = @@IDENTITY
	
	IF ISNULL(@ParentActivityKey, 0) = 0
		-- if you do not have a parent, then you must be a root
		SELECT @RootActivityKey = @oIdentity
	ELSE
		-- if you have a parent, get the root from it, all share the same root
		SELECT @RootActivityKey = RootActivityKey FROM tActivity (NOLOCK) WHERE ActivityKey = @ParentActivityKey
	
	Update tActivity Set RootActivityKey = @RootActivityKey Where ActivityKey = @oIdentity

	-- now add a link for the client
	IF ISNULL(@ClientKey, 0) > 0
		INSERT tActivityLink (ActivityKey, Entity, EntityKey)
		VALUES (@oIdentity, ''tCompany'', @ClientKey)
	
	-- and add a link for the project
	IF ISNULL(@ProjectKey, 0) > 0
		INSERT tActivityLink (ActivityKey, Entity, EntityKey)
		VALUES (@oIdentity, ''tProject'', @ProjectKey)
	
	/*	
	INSERT tProjectNote
		(
		CompanyKey,
		Entity,
		EntityKey,
		ProjectKey,
		ParentNoteKey,
		AddedByKey,
		DateAdded,
		Note,
		VisibleToClient,
		AddedByEmail
		)

	VALUES
		(
		@CompanyKey,
		@Entity,
		@EntityKey,
		@ProjectKey,
		@ParentNoteKey,
		@AddedByKey,
		GETDATE(),
		@Note,
		@VisibleToClient,
		@AddedByEmail
		)
	*/
	
	RETURN 1
	

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spBillingInvoiceBill]'
GO
IF OBJECT_ID(N'[dbo].[spBillingInvoiceBill]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[spBillingInvoiceBill]
	(
	@TopBillingKey INT
	,@UserKey INT
	,@BillingStatusKey INT
	,@InvoiceDate smalldatetime = Null 
	,@PostingDate smalldatetime = Null
	,@CreateAsApproved INT 
	)
AS

  /*
  || When     Who Rel   What
  || 06/29/06 GHL 8.35  Removed ProjectKey on extra summary lines. Was showing  
  ||                    on grids and users expected Project # and name on invoice
  ||                    when template was set to show project # and name and
  ||                    By Top Lines (Bug 5850 Ervin and Smith)
  || 07/28/06 GHL 8.4   Added TrackBudget in task temp tables
  || 09/05/06 CRG 8.35	Removed the check for SetInvoiceNumberOnApproval when auto-approving the invoice.
  ||					(Bug 6437)
  || 09/27/06 GHL 8.4   Added support of fixed fee billing by billing item  
  || 10/11/06 CRG 8.35  Added Emailed column.
  || 02/22/07 GHL 8.4   Added Project Rollup section
  || 07/09/07 GHL 8.5   Added logic for company/office
  || 07/27/07 GHL 8.43  (Bug 9987) Taking in account now tPrefs settings for Invoice Approver
  || 08/07/07 GHL 8.5   Added Invoice Rollup
  || 08/09/07 GHL 8.5   Added Office/Department for extra project line
  || 09/26/07 GHL 8.5   Removed invoice summary since it is done in invoice recalc amounts
  || 03/27/08 GHL 8.507 (21598) Changing the billing status only if > 0 (i.e. not if null, or 0)
  || 04/08/08 GHL 8.508 (23712) New logic for classes, remove reading of FixedFeeBillingClassDetail  
  || 06/18/08 GHL 8.513 Added OpeningBalance
  || 07/14/08 GHL 8.515 (30094) Added call to sptInvoiceOrder
  || 08/12/08 GHL 10.006 (32051) Moved invoice recalc amounts before creation of advance bills
  ||                     because InvoiceTotalAmount was not set yet
  || 08/13/08 GHL 10.008 (32232) Using now sptInvoiceLineInsertMassBilling when creating invoice lines for projects
  ||                     This sp bypasses validations and recalcs not necessary here
  || 10/08/08 GHL 10.010 (36927) Taking now default line format for Fixed Fee as One line instead of Service/item
  ||                     This is a problem if FixedFeeDisplay is null (sptBillingInsert has been fixed though)
  || 10/13/08 GHL 10.010 (37465) If tTask.ShowDescOnEst = 1 bring over task description
  || 03/18/09 GHL 10.021 Added generation of invoices per billing item then item
  || 06/01/09 GHL 10.026 (52904) Moved position of BI/Item call inside the Ws/Project loop (was outside) 
  || 07/09/09 GHL 10.503 (56803) Using now the class from individual WS rather than from the master WS
  ||                     The class on the master WS goes to the invoice header
  ||                     The class on the individual WSs go to the invoice lines
  || 07/29/09 GHL 10.505 (57778) Do not prevent the users from creating an invoice with 0 amount  
  || 08/14/09 GHL 10.507 (60305) Prevent the users from creating an invoice if there are no billing detail records
  || 08/24/09 GHL 10.507 (60195) For Fixed Fee projects, check if tBillingFixedFee.Amount > 0 before creating invoice 
  || 08/25/09 GHL 10.508 (60144) Account for retainer projects when deciding on creating the invoice
  || 09/10/09 GHL 10.509 (62127) Changed BillingCount definition to = COUNT(*) from #tBilling where BillingCount <> 0 
  ||                      Instead of = SUM(BillingCount) from #tBilling
  ||                      because we need an exact count of projects with anything to bill
  || 09/11/09 GHL 10.509  Get only child billing worksheets which have not been invoiced yet
  || 01/22/10 GHL 10.517 (69011) Changed retainer amount logic since we can have amounts <0  
  || 03/24/10 GHL 10.521 Added LayoutKey
  || 04/23/10 GHL 10.521 Added ProjectKey on Project summary lines for custom fields
  || 06/10/10 GHL 10.530 (82735) For AdvBill overwrite the SalesAccountKey on the lines to the Adv Bill Account 
  ||                     that has already been set on the Billing WS
  || 12/22/10 GHL 10.539  Added seeding of DisplayOption
  || 05/18/11 GHL 10.544  (111527) Only add an extra line for FF projects if this is more than a single FF line 
  || 01/03/12 GHL 10.551  (130049) Recovering now when Rollup/LineFormat = 9 by Billing Item/Item 
  ||                      (only in spBillingInvoiceBillLayout) set Rollup = 0, 1 line per project
  || 05/21/12 GHL 10.556 Added reading of ShowTransactionsOnInvoices (customization for Etna)
  ||                     Most of the projects will be No Details
  ||                     Expense project will be Transactions
  || 05/23/12 GHL 10.556 (144563) If we group by campaign but there was only one project (i.e. no masters)
  ||                     we must also set the campaign key on the invoice
  || 08/10/12 GHL 10.558 (150858) If the new invoice is completely covered by an advance bill, set Printed = 1
  || 09/27/12 GHL 10.560 Added update of billing group on invoice for HMI request
  || 10/15/12 GHL 10.561 (156926) Added FixedFeeRollup 
  ||                     Initially we only had one Rollup (For Fixed Fee the TM trans were rolled up into 1 line)
  ||                     But Enlighten wants to control the TM rollup on FF projects
  ||                     Decided to have 2 rollups (one TM and one FF)
  ||                     Note: The TM rollup for FF projects can only be changed on master BWS 
  || 02/26/13 GHL 10.565 (167798) When applying advance bills, add taxes to the applied amount.
  ||                     The original amount does not include taxes and users have to manually add taxes
  || 04/04/13 GHL 10.566 (173907) Added checking of ProjectName not null before inserting line for project in case of multi projects
  || 10/01/13 GHL 10.573 Added multi currency logic
  || 01/03/14 WDF 10.576 (188500) Pass UserKey to sptInvoiceInsert
  || 08/07/14 GHL 10.583 (225414) Do not create an invoice if there is an invoice on the billing WS already or Status = 5
  || 10/10/14 GHL 10.584 (232654) Rather than using tBilling.InvoiceKey from being used to detect duplicates,
  ||                     use tInvoice.BillingKey because I noticed that duplicates had lines intertwined.
  ||                     Better to set tInvoice.BillingKey at the beginning of the process, than tBilling.InvoiceKey at the
  ||                     end of the process  
  || 11/12/14 GHL 10.586 Added support of titles for Abelson Tayor
  || 12/02/14 GHL 10.587 Renamed spBillingInvoiceOneLinePerServiceItem to spBillingInvoiceOneLinePerServiceItemFF 
  ||                     Added support for line format rollup: By Service OR Item
  || 03/20/15 GHL 10.591 Added setting of hours on Time lines
  || 08/13/15 GHL 10.595 Added param IsRetainer when calling sptInvoiceInsert
  || 08/14/17 GHL 10.619 (341875) customization for Owens Harkey..get taxes from vendor
  || 10/02/17 GHL 10.621 (363756) Added AR account info
  || 03/06/18 GHL 18.400 (388967) For fixed fee projects, we may have fixed fee (FF) and time and material (TM) data. process FF first
  || 06/26/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
  || 11/01/18 GHL 18.920 (428664) Added a check of tInvoice.BillingKey at the end also, to fight duplicate invoices 
  || 11/30/18 GHL 18.930 (433642) Pull the invoice template from retainer and set them on the invoice 
  || 05/10/19 GHL 19.600 (459199) Link the invoice to the billing schedule for FF projects
  || 01/27/20 GHL 20.030 (495024) Get the invoice template from the GL company if tPreference.LayoutFromGLCompany = 1
  || 04/17/20 AMP 20.050 (510663) Changed the InvoiceComment to varch(max) to prevent them from being cutoff. 
  || 04/17/20 MFT 20.050 (512169) Changed the fallback for @Rollup = 9 when no Layout from 0 to 8
  || 01/15/21 GHL 21.010 (540479) Creation to cleanup deleted time entries on billing worksheets
  ||                     If deleted time entries are kept on the BWS, there will be a discrepancy with invoices 
  || 02/18/20 MCM 21.030 (544541) Updated check to be <> 0 instead of > 0 on the BillingFixedFeeKey count
  || 03/11/21 MFT 21.010 (455922) Added tCampaign table & CampaignName to query to support Fixed Fee Campaign billing
  || 04/12/21 GHL 21.050 (455922) Added line format by project for FF campaign mode 
  || 05/17/21 GHL 21.06.20 (558991) Added logic for ''Add Project Line'' for FF projects
  || 06/10/21 GHL 21.07.20 (560163) Updating tBillingSchedule for campaigns
  || 06/15/21 GHL 21.070 (561987) Added same logic of FixedFeeAddProjectLine for campaigns
  || 11/05/21 GHL 21.120 (574541) Changed the logic for advance bills. Now child BWS can be applied to Advance Bills
  ||                              Used to be only for top billing key (the master BWS)
  || 01/12/22 GHL 22.020 (579936) Added support for Rollup = 9 (Billing Item and Item) regardless of projects
  ||                              In that case, call spBillingInvoiceBillLayout
  || 03/18/22 GHL 22.040 (590582) Added support for tProject.SetTaxableOnInvoice
  || 11/03/22 MFT 22.110 (618076) Added support for making InvoiceApprover PM from Project
  || 12/16/22 MFT 23.010 (624039) Allow Invoice generation when there is no Default Sales Acct, even if GL Acct is required if Post Sales From Detail is on
  || 02/20/23 GAR 23.030 (622546) Have Fixed Fee Campaign mass billing observe the default approver settings from trans pref / client invoice / default approver
  || 06/06/23 MFT 23.060 (642167) For ByProjectServiceOrItem, put Quantity and Unit Amount on the line to match Mass Billing
  || 01/03/25 MCM 25.02x (674742) Added @OfficeKey when creating the invoice line
  || 04/03/25 MCM 25.04x (698988) Fixed error return codes -1 to -104 and -1 to -106
  || 06/24/25 AMP (704696) Corrected the column sizes for TaskName and Description in #tInvcTask,and #tInvcRootTask to match table definition tTask
  || 07/21/25 MFT 25.090 (706297) Use SP to apply AB, or short circuit with Avalara
  || 08/27/25 MFT 25.090 (709533) Use DisplayOrder of Child BWS
  || 09/12/25 MFT 25.100 (711284) Prevent blank Invoice Approver when set to use PM
  || 11/04/25 MCM 25.11.x (656423) Added Liability Account Key when calling sptInvoiceInsert
  || 02/11/26 AMP 26.030 (721828) For Time and Materials and no layout being used the line format drives whether we show a top project line on the UI template,
  ||                              and the generated invoice
  || 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
  || 05/13/26 RLS 26.06.14 (725399) Added IF @DefaultARApprover = 5
  || 07/08/26 AMP 26.07.19 (729259) Populate BilledComment with the scheduled dollar amount (PercentBudget * Budget) at time of billing for percentage rows
  || 07/14/26 AMP 26.07.19 (729259) Added BilledComment population for campaign billing schedule rows (FF and T&M paths)
 */

	SET NOCOUNT ON

-- Variables to capture tBilling record
	DECLARE @BillingCount INT
			,@BillingMethod INT
			,@FixedFeeDisplay INT
			,@BillingKey INT
			,@DisplayOrder INT
			,@Status INT
			,@BillingApprover INT -- This is the Approver on the Billing WS (defaulted from AE on Project)		
			,@InvoiceApprover INT -- Final approver on Invoice, will depend on transaction preferences
			,@NewInvoiceKey INT
			,@ParentInvoiceLineKey INT
			,@AdvanceBill INT
			,@RetVal INT
			,@FixedFeeAddProjectLine INT -- straight from tBilling
			,@ShowExtraProjectLine INT -- final flag to decide if we add an extra line
			,@PrimaryContactKey INT
			,@AddressKey INT
			,@GLCompanyKey INT
			,@OfficeKey INT
			,@CurrencyID VARCHAR(10)
			

-- Clone variables from spProcessWIPWorksheet	
declare @CompanyKey int
declare @ClientKey int
declare @ProjectKey int
declare @EstimateKey int	
declare @Rollup int
declare @FixedFeeRollup int
declare @BillingContact varchar(100) 
declare @DefaultSalesAccountKey int
declare @SalesAccountKey int 
declare @RequireGLAccounts tinyint
declare @TodaysDate smalldatetime
declare @DueDate smalldatetime
declare @DueDays int
declare @InvoiceComment varchar(max)
declare @ProjectName varchar(500)
declare @WorkTypeKey int
declare @ARAccountKey int
declare @DefaultARAccountKey int
declare @DefaultARApprover int
declare @DefaultARApproverKey int
declare @PostSalesUsingDetail tinyint
declare @InvoiceTemplateKey int
declare @SalesTaxKey int, @SalesTax2Key int, @PaymentTermsKey int
declare @RequireClasses tinyint
declare @TopBillingClassKey int
declare @BillingClassKey int
declare @DefaultClassKey int
declare @LayoutKey int
declare @ShowTransactionsOnInvoices int -- Etna
declare @SetInvoiceNumberOnApproval tinyint
declare	@NextTranNo varchar(100)
declare @OldInvoiceKey int
declare @OldStatus int
declare @UseBillingTitles int -- this will indicate the Abelson Taylor company
declare @UseMediaTaxes int -- this will indicate to pull the taxes from the vendor 
declare @Customizations varchar(2000)
declare @SetTaxableOnInvoice int
declare @LayoutFromGLCompany int
declare @AdvBillAccountKey int
declare @LiabilityAccountKey int = null

declare @TopEntity varchar(50)
declare @TopEntityKey int
declare @TopGroupEntity varchar(50)
declare @TopGroupEntityKey int
declare @IsFFCampaign int -- Is this a FF campaign? if yes we can add a '' Expenses'' mention to projects
declare @TopRollup int

-- this is a patch to remove the time details which have been deleted
exec sptBillingCleanupDeletedDetails @TopBillingKey

select @LayoutKey = isnull(LayoutKey, 0)
      ,@OldInvoiceKey = isnull(InvoiceKey, 0) 
	  ,@OldStatus = Status
	  ,@TopRollup = ISNULL(DefaultARLineFormat, 0) -- Default is 1 line per Project
from tBilling (nolock) where BillingKey = @TopBillingKey

-- Is it a valid invoice?
if not exists (select 1 from tInvoice (nolock) where InvoiceKey = @OldInvoiceKey)
	select @OldInvoiceKey = 0

-- If already invoiced, abort
if @OldInvoiceKey > 0 
	return -1001
if @OldStatus = 5
	return -1001
-- this way to check for duplicates should be stronger because tInvoice is set earlier
if exists (select 1 from tInvoice (nolock) where BillingKey = @TopBillingKey)
    return -1001 

if @LayoutKey > 0
begin 
	exec @NewInvoiceKey = spBillingInvoiceBillLayout @TopBillingKey,@UserKey,@BillingStatusKey,@InvoiceDate,@PostingDate,@CreateAsApproved
	return @NewInvoiceKey
end

-- for top rollup = 9 -- By Billing Item/Item...this works only for TM projects
-- because we are trying to combine all transactions on TM billing worksheets and organize them by BI/Item, regardless of projects 
-- if there are some FF projects, this does not work well, change to By Project then Billing Item/Item 
if @TopRollup = 9
begin
	if exists (select 1 
				from  tBilling b
				where b.ParentWorksheetKey = @TopBillingKey 
				and   b.BillingMethod > 1
				)
		select @TopRollup = 8
end

if @TopRollup = 9 -- By Billing Item and Item regardless of projects, even if there is no layout, that should work
begin 
	exec @NewInvoiceKey = spBillingInvoiceBillLayout @TopBillingKey,@UserKey,@BillingStatusKey,@InvoiceDate,@PostingDate,@CreateAsApproved
	return @NewInvoiceKey
end

	/*		
	|| Inits
	*/
	If @PostingDate IS NOT NULL
		select @TodaysDate = cast(cast(DATEPART(m,@PostingDate) as varchar(5))+''/''+cast(DATEPART(d,@PostingDate) as varchar(5))+''/''+cast(DATEPART(yy,@PostingDate)as varchar(5)) as smalldatetime)
	ELSE
	BEGIN
		select @TodaysDate = cast(cast(DATEPART(m,getdate()) as varchar(5))+''/''+cast(DATEPART(d,getdate()) as varchar(5))+''/''+cast(DATEPART(yy,getdate())as varchar(5)) as smalldatetime)
		Select @PostingDate = @TodaysDate
	END
	if @InvoiceDate is null
		Select @InvoiceDate = @TodaysDate

	-- Reset error
	update tBilling 
	set ErrorMsg = NULL 
	where BillingKey = @TopBillingKey 

	/*				
	|| temp table created in .NET
	|| CREATE TABLE #tBilling(BillingKey INT NULL, DisplayOrder INT NULL, BillingCount INT NULL, CampaignSegmentKey INT NULL, SegmentDisplayOrder INT NULL, ProjectKey INT NULL, CampaignKey INT NULL)
	*/
	
	IF (SELECT ParentWorksheet FROM tBilling (NOLOCK) WHERE BillingKey = @TopBillingKey) = 0
		INSERT #tBilling (BillingKey) VALUES (@TopBillingKey)
	ELSE
		INSERT #tBilling (BillingKey, DisplayOrder)
		SELECT BillingKey, DisplayOrder
		FROM   tBilling (NOLOCK) 
		WHERE  ParentWorksheetKey = @TopBillingKey
		AND    Status <> 5 -- do not take if already invoiced during approval
		ORDER BY DisplayOrder

	-- do we have some T&M to bill?
	UPDATE #tBilling
	SET    #tBilling.BillingCount = ISNULL((
		SELECT COUNT (bd.BillingDetailKey) FROM tBillingDetail bd (NOLOCK) 
		WHERE bd.BillingKey = #tBilling.BillingKey AND bd.Action = 1
		-- even if Amount = 0, we have to create a $0 invoice 
	),0)

	-- do we have some FF to bill?
	UPDATE #tBilling
	SET    #tBilling.BillingCount = ISNULL(#tBilling.BillingCount, 0) + ISNULL((
		SELECT COUNT (bff.BillingFixedFeeKey) FROM tBillingFixedFee bff (NOLOCK) 
		WHERE bff.BillingKey = #tBilling.BillingKey 
		AND bff.Amount <> 0 -- Added this because one tBillingFixedFee rec is created automatically with Amount = 0  
	),0)

	-- do we have retainer amounts to bill?
	UPDATE #tBilling
	SET    #tBilling.BillingCount = ISNULL(#tBilling.BillingCount, 0) + 1
	FROM   tBilling b (NOLOCK)
	WHERE  #tBilling.BillingKey = b.BillingKey
	--AND    ISNULL(b.RetainerAmount, 0) > 0
	AND    b.Entity = ''Retainer'' -- because now b.RetainerAmount can be <0, =0, >0

	-- Do not bill if no count
	SELECT @BillingCount = COUNT(*) FROM #tBilling WHERE ISNULL(BillingCount, 0) <> 0 

	-- No Amount to bill, mark BWS as Invoiced 	
	IF @BillingCount = 0
	BEGIN
		UPDATE 	tBilling 
		SET     tBilling.Status = 5
		FROM    #tBilling b
		WHERE   tBilling.BillingKey = b.BillingKey

		UPDATE 	tBilling 
		SET tBilling.Status = 5
		WHERE   tBilling.BillingKey = @TopBillingKey

		RETURN 1
	END

	-- Do not trust tBilling.DisplayOrder, setup our own
	SELECT @DisplayOrder = 1
	UPDATE #tBilling 
	SET    #tBilling.DisplayOrder = @DisplayOrder
	      ,@DisplayOrder = @DisplayOrder + 1
	WHERE DisplayOrder IS NULL

    -- set the flag that says that we have a FF campaign
	If exists (select 1 from tBilling bill (nolock) 
				inner join #tBilling b on bill.BillingKey = b.BillingKey
				where  bill.CampaignKey > 0 and bill.BillingMethod = 2)
		select @IsFFCampaign = 1
	else
		select @IsFFCampaign = 0

	SELECT  bd.* 
	INTO    #tBillingDetail
	FROM	tBillingDetail bd (NOLOCK)
		INNER JOIN #tBilling b ON bd.BillingKey = b.BillingKey
	WHERE   bd.Action = 1 -- Only trans to bill, others are handled on ws approval


	--create temp tables needed for task management
	create table #tInvcTask
                (
                 TaskKey int null
                ,SummaryTaskKey int null
                ,TaskType smallint null
                ,DisplayOrder int null
                ,Taxable tinyint null 
                ,Taxable2 tinyint null 
                ,WorkTypeKey int null 
                ,TrackBudget int null
                ,TaskName nvarchar(500) null
                ,Description nvarchar(max) null
      )	
	create table #tInvcRootTask
     (
				TaskKey int null
				,SummaryTaskKey int null
                ,TaskType smallint null
                ,DisplayOrder int null
                ,Taxable tinyint null 
                ,Taxable2 tinyint null 
                ,WorkTypeKey int null               
                ,TrackBudget int null
                ,TaskName nvarchar(500) null
                ,Description nvarchar(max) null
                )                

	--create temp tables needed for some other groupings	
	 CREATE TABLE #tran(
		Entity varchar(20) null,		-- like in tBillingDetail, tMiscCost, tTime, etc.... 
		EntityKey varchar(50) null,     -- transaction key
		EntityGuid uniqueidentifier null,

		BilledAmount money null,
		Quantity decimal(24,4) null,
		RateLevel int null,
		Rate money null,
		BilledComment varchar(2000),

		LayoutEntityKey int null,       -- ItemKey or ServiceKey depending on LayoutEntity

		-- All fields above should be set before this SP 

		LayoutEntity varchar(50) null,   -- like in tLayoutBilling, tItem, tService
		LayoutOrder int null,	
		WorkTypeLayoutOrder int null,

		WorkTypeKey int null,
		WorkTypeName varchar(200) null, 
		ItemName varchar(200) null,     -- will come from item or service

		-- Use this vars for a simpler grouping (like Service/Item)
		GroupEntity varchar(25) null,
		GroupEntityKey int null,
		GroupName varchar(250) null,

		InvoiceLineKey int null,
		LineID int null,

		UpdateFlag int null
		)

	/*				
	|| Get defaults from top billing worksheet or Pref or client
	*/
	SELECT @CompanyKey = CompanyKey
		   ,@ClientKey = ClientKey
		   ,@ProjectKey = ProjectKey
		   ,@TopBillingClassKey = ISNULL(ClassKey, 0)
		   ,@SalesTaxKey = SalesTaxKey
		   ,@SalesTax2Key = SalesTax2Key
		   ,@PaymentTermsKey = ISNULL(TermsKey, 0) 
		   ,@DefaultSalesAccountKey = ISNULL(DefaultSalesAccountKey, 0) -- It is NULL or 0 in table tBilling
		   ,@BillingApprover = ISNULL(Approver, @UserKey)	
		   ,@InvoiceComment = InvoiceComment
		   ,@Status = Status
		   ,@AdvanceBill = ISNULL(AdvanceBill, 0) -- only FF and will be on their own ws	
		   ,@PrimaryContactKey = PrimaryContactKey -- NULL is fine
		   ,@AddressKey = AddressKey -- NULL is fine
		   ,@GLCompanyKey = GLCompanyKey
		   ,@OfficeKey = OfficeKey	
		   ,@CurrencyID = CurrencyID

		   ,@TopEntity = Entity							-- Will indicate Campaign
	       ,@TopEntityKey = EntityKey
		   ,@TopGroupEntity = GroupEntity				-- Will indicate Campaign on single projects
	       ,@TopGroupEntityKey = GroupEntityKey

	FROM   tBilling (NOLOCK)
	WHERE  BillingKey = @TopBillingKey

	--Set the AdvBillAcountKey
	SELECT 
		@AdvBillAccountKey = AdvBillAccountKey
	From
		tPreference (nolock)
	Where
		CompanyKey = @CompanyKey
	
	Set @LiabilityAccountKey = 
		Case 
			When @AdvanceBill = 1 Then @AdvBillAccountKey
			Else NULL
		End;


	-- Already invoiced
	IF @Status = 5
	BEGIN
		update tBilling set ErrorMsg = ''The billing worksheet was already invoiced''
		where BillingKey = @TopBillingKey 
		RETURN -1
	END

	-- Make sure that no vendor invoice have been applied against POs
	IF EXISTS (SELECT 1
				FROM  tPurchaseOrderDetail pod (NOLOCK)
				INNER JOIN tPurchaseOrder po (NOLOCK) ON po.PurchaseOrderKey = pod.PurchaseOrderKey
				INNER JOIN #tBillingDetail bd (NOLOCK) ON pod.PurchaseOrderDetailKey = bd.EntityKey
														AND bd.Entity = ''tPurchaseOrderDetail''
				WHERE po.CompanyKey = @CompanyKey
				AND	ISNULL(pod.AppliedCost, 0) > 0
				)
	BEGIN
		update tBilling set ErrorMsg = ''Vendor Invoices have been applied to POs involved on this billing worksheet''
		where BillingKey = @TopBillingKey 

		RETURN -1		
	END

	IF @PrimaryContactKey IS NOT NULL
		select @BillingContact = Left(FirstName + '' '' + LastName, 100)
		from   tUser (nolock) 
		Where  UserKey = @PrimaryContactKey

	-- get other client defaults  
	Select @InvoiceTemplateKey = ISNULL(InvoiceTemplateKey, 0)
	      ,@ARAccountKey = ISNULL(DefaultARAccountKey, 0)
	from tCompany (nolock)
	Where CompanyKey = @ClientKey

	Select @LayoutFromGLCompany  = ISNULL(LayoutFromGLCompany,0)
	From tPreference (nolock)
	Where CompanyKey = @CompanyKey

	IF @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
		select @InvoiceTemplateKey = InvoiceTemplateKey from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey

	if @PaymentTermsKey = 0
		Select @PaymentTermsKey = PaymentTermsKey
		From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	declare @RetainerInvoiceTemplateKey int
	if @TopEntity in (''RetainerMaster'', ''Retainer'')
		select @RetainerInvoiceTemplateKey = InvoiceTemplateKey
		from tRetainer (nolock)
		where RetainerKey = @TopEntityKey

	if isnull(@RetainerInvoiceTemplateKey, 0) > 0
		Select @InvoiceTemplateKey = @RetainerInvoiceTemplateKey

	Select @PostSalesUsingDetail   = ISNULL(PostSalesUsingDetail, 0)
			,@DefaultARAccountKey  = DefaultARAccountKey
			,@WorkTypeKey          = AdvBillItemKey
			,@RequireClasses       = ISNULL(RequireClasses, 0)
			,@RequireGLAccounts    = ISNULL(RequireGLAccounts, 0)
			,@SetInvoiceNumberOnApproval = ISNULL(SetInvoiceNumberOnApproval,0)
			,@DefaultARApprover    = ISNULL(DefaultARApprover, 0)
			,@DefaultARApproverKey = ISNULL(DefaultARApproverKey, 0)			
			,@DefaultClassKey      = DefaultClassKey
			,@UseBillingTitles	   = ISNULL(UseBillingTitles, 0)
			,@Customizations       = LOWER(ISNULL(Customizations, ''''))
			,@SetTaxableOnInvoice  = ISNULL(SetTaxableOnInvoice,0) -- this overrides the Taxable on tasks/items/services/BI and also used for 1-line invoice
	From tPreference (nolock)
	Where CompanyKey = @CompanyKey

	if ISNULL(@ARAccountKey, 0) > 0
		select @DefaultARAccountKey = @ARAccountKey

	-- customization for Owens Harkey, use taxes from the vendor, vouchers, orders
	if charindex(''mediataxes'', @Customizations) > 0
		select @UseMediaTaxes = 1
	else
		select @UseMediaTaxes = 0

	-- validation of classes
	if @RequireClasses = 1 AND ISNULL(@TopBillingClassKey, 0) = 0 AND ISNULL(@DefaultClassKey, 0) = 0
	BEGIN
		update tBilling set ErrorMsg = ''There is no class for this worksheet, but your company requires classes on transactions''
		where BillingKey = @TopBillingKey 

		RETURN -106
	END

	if @RequireClasses = 1 AND ISNULL(@TopBillingClassKey, 0) = 0
		SELECT @TopBillingClassKey = @DefaultClassKey

	-- validation of GL accounts
	if @DefaultSalesAccountKey = 0
		Select @DefaultSalesAccountKey = ISNULL(DefaultSalesAccountKey, 0)
		From tPreference (nolock)
		Where CompanyKey = @CompanyKey

	if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @DefaultSalesAccountKey )
		Select @DefaultSalesAccountKey = 0

	if @RequireGLAccounts = 1 AND @DefaultSalesAccountKey = 0 AND @PostSalesUsingDetail = 0
	BEGIN
		update tBilling set ErrorMsg = ''There is no Default Sales Account for this worksheet and for your company''
		where BillingKey = @TopBillingKey 

		RETURN -104			
	END

	IF ISNULL(@PaymentTermsKey, 0) > 0
	BEGIN
		SELECT @DueDays = ISNULL(DueDays, 0)
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @PaymentTermsKey

		SELECT @DueDate = DATEADD(d, @DueDays, @InvoiceDate) 	
	END
	ELSE
		SELECT @DueDate = @TodaysDate

-- DefaultARApprover 
-- 0 Person Entering the Invoice
-- 1 AE From project
-- 2 Automatically approved ==> set invoice # when SetInvoiceNumberOnApproval = 1
-- 3 Default Approver in tPrefs
-- 4 PM From Project
-- 5 Billing Manager From Project


IF @DefaultARApprover = 0
	SELECT @InvoiceApprover = @UserKey
-- If AE From project, it was already copied to the WS, so take it from WS, otherwise it''s the Biller
IF @DefaultARApprover = 1
	SELECT @InvoiceApprover = @BillingApprover
-- Automatically approved, set to current user
IF @DefaultARApprover = 2
	SELECT @InvoiceApprover = @UserKey 
-- If default approver from tPrefs
IF @DefaultARApprover = 3
BEGIN
	IF @DefaultARApproverKey > 0 
		SELECT @InvoiceApprover = @DefaultARApproverKey
	ELSE
		SELECT @InvoiceApprover = @UserKey
END
IF @DefaultARApprover = 4
	BEGIN
		SELECT @InvoiceApprover = ProjectManager
		FROM tProject (nolock)
		WHERE ProjectKey = @ProjectKey
		
		--If this is a multi-project BWS, prevent the approver from being blank
		IF ISNULL(@InvoiceApprover, 0) = 0
			SELECT @InvoiceApprover = @UserKey
	END
IF @DefaultARApprover = 5
	BEGIN
		SELECT @InvoiceApprover = BillingManagerKey
		FROM tProject (nolock)
		WHERE ProjectKey = @ProjectKey
		
		--If this is a multi-project BWS, prevent the approver from being blank
		IF ISNULL(@InvoiceApprover, 0) = 0
			SELECT @InvoiceApprover = @UserKey
	END

	/*				
	|| Create an invoice
	*/
	exec @RetVal = sptInvoiceInsert
			@CompanyKey = @CompanyKey,
			@ClientKey = @ClientKey,
			@ContactName = @BillingContact,
			@PrimaryContactKey = @PrimaryContactKey,
			@AddressKey = @AddressKey,
			@AdvanceBill = @AdvanceBill,
			@InvoiceNumber = null,
			@InvoiceDate = @InvoiceDate,
			@DueDate = @DueDate,
			@PostingDate = @PostingDate,
			@TermsKey = @PaymentTermsKey,
			@ARAccountKey = @DefaultARAccountKey,
			@ClassKey = @TopBillingClassKey,
			@ProjectKey = @ProjectKey,
			@HeaderComment = @InvoiceComment,
			@SalesTaxKey = @SalesTaxKey,
			@SalesTax2Key = @SalesTax2Key,
			@InvoiceTemplateKey = @InvoiceTemplateKey,
			@ApprovedByKey = @InvoiceApprover,
			@UserDefined1 = NULL,
			@UserDefined2 = NULL,
			@UserDefined3 = NULL,
			@UserDefined4 = NULL,
			@UserDefined5 = NULL,
			@UserDefined6 = NULL,
			@UserDefined7 = NULL,
			@UserDefined8 = NULL,
			@UserDefined9 = NULL,
			@UserDefined10 = NULL,
			@Downloaded = 0,
			@Printed = 0,
			@ParentInvoice = 0,
			@Emailed = 0,
			@CreatedByKey = @UserKey,
			@GLCompanyKey = @GLCompanyKey,
			@OfficeKey = @OfficeKey,
			@OpeningTransaction = 0,
			@LayoutKey = @LayoutKey,
			@CurrencyID = @CurrencyID,
			@ExchangeRate = 1,
			@RequestExchangeRate = 1,
			@IsForRetainer = 0,
			@LiabilityAccountKey = @LiabilityAccountKey , -- **New Parameter**
			@oIdentity = @NewInvoiceKey OUTPUT

	if @@ERROR <> 0 
	  begin
		update tBilling set ErrorMsg = ''An error occurred when creating the invoice'' 
		where BillingKey = @TopBillingKey 

		return -5					   	
	  end
	if @RetVal <> 1 
	 begin
		update tBilling set ErrorMsg = ''An error occurred when creating the invoice'' 
		where BillingKey = @TopBillingKey 

		return -5					   	
	  end

	-- used in search for duplicates at the top of the sp
	update tInvoice set BillingKey = @TopBillingKey where InvoiceKey = @NewInvoiceKey

	-- (622546 ) Update the approver based on the selection in trans pref / client invoices / default approver
	-- We only care about 4 because the others are handled in sptInvoiceInsert from above
	Declare @PM int -- Project Manager

	if @TopEntity = ''Campaign''
	begin
		update tInvoice
		set    CampaignKey = @TopEntityKey
		where  InvoiceKey = @NewInvoiceKey
		
		-- If PM From campaign
		if @DefaultARApprover = 4
		begin
			Select @InvoiceApprover = ISNULL(PMKey, 0) from tCampaign (nolock) Where CampaignKey = @TopEntityKey
			if @InvoiceApprover = 0
				Select @InvoiceApprover = @UserKey
		end
	end
	else
	begin
		-- If there is only 1 project for the campaign, there will be no master
		-- so get campaign from the group info on the single billing WS instead
		if @TopGroupEntity = ''Campaign''
		begin
			update tInvoice
			set    CampaignKey = @TopGroupEntityKey
			where  InvoiceKey = @NewInvoiceKey

			-- If PM From campaign
			if @DefaultARApprover = 4
			begin
				Select @InvoiceApprover = ISNULL(PMKey, 0) from tCampaign (nolock) Where CampaignKey = @TopGroupEntityKey
				if @InvoiceApprover = 0
					Select @InvoiceApprover = @UserKey
			end
		end
	end

	if @TopEntity = ''BillingGroup''
	begin
		update tInvoice
		set    BillingGroupKey = @TopEntityKey
		where  InvoiceKey = @NewInvoiceKey
	end
	else
	begin
		-- If there is only 1 project for the campaign, there will be no master
		-- so get campaign from the group info on the single billing WS instead
		if @TopGroupEntity = ''BillingGroup''
		begin
			update tInvoice
			set    BillingGroupKey = @TopGroupEntityKey
			where  InvoiceKey = @NewInvoiceKey
		end
	end

	--update AR account key
	--also bypass normal approval process since it went thru billing ws approval process
	If @CreateAsApproved = 1
	BEGIN

		--Check to see if the tInvoice Insert SP set the Invoice Number
		SELECT	@NextTranNo = InvoiceNumber
		FROM	tInvoice (nolock)
		WHERE	InvoiceKey = @NewInvoiceKey

		IF @NextTranNo IS NULL
		BEGIN
			--If the InvoiceNumber has not been set yet, get the next number
			DECLARE @TranType varchar(10) = CASE @AdvanceBill WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END

			EXEC spGetNextTranNo
				@CompanyKey,
				@TranType,
				@RetVal		  OUTPUT,
				@NextTranNo   OUTPUT

			IF @RetVal <> 1
				RETURN -5
		END

		update tInvoice
		set ARAccountKey = @DefaultARAccountKey
			,ApprovedByKey = @InvoiceApprover
			,InvoiceStatus = 4 -- Approved
			,InvoiceNumber = @NextTranNo 
		where InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0 
		begin
			update tBilling set ErrorMsg = ''An error occurred when updating the invoice'' 
			where BillingKey = @TopBillingKey 
			exec sptInvoiceDelete @NewInvoiceKey

			return -5					   	
		end
	END
	ELSE
	BEGIN
		update tInvoice
		set ARAccountKey = @DefaultARAccountKey
			,ApprovedByKey = @InvoiceApprover
		where InvoiceKey = @NewInvoiceKey

		if @@ERROR <> 0 
		begin
			update tBilling set ErrorMsg = ''An error occurred when updating the invoice'' 
			where BillingKey = @TopBillingKey 
			exec sptInvoiceDelete @NewInvoiceKey

			return -5					   	
		end
	END

	/*				
	|| Add child billing worksheets
	*/

	SELECT @DisplayOrder = -1
	WHILE (1=1)
	BEGIN
		SELECT @DisplayOrder = MIN(DisplayOrder)
		FROM   #tBilling WHERE DisplayOrder > @DisplayOrder

		IF @DisplayOrder IS NULL
			BREAK

		SELECT @BillingKey = BillingKey
		FROM   #tBilling (NOLOCK)
		WHERE  DisplayOrder = @DisplayOrder

		SELECT @ParentInvoiceLineKey = 0

		SELECT @ProjectKey = b.ProjectKey
			   ,@Rollup = ISNULL(b.DefaultARLineFormat, 0) -- Default is 1 line per Project 
	    	   ,@BillingMethod = b.BillingMethod
			   ,@ProjectName = ISNULL(p.ProjectName, c.CampaignName)
			   ,@ShowTransactionsOnInvoices = isnull(p.ShowTransactionsOnInvoices, 0) -- for Etna customization
			   ,@FixedFeeDisplay = ISNULL(b.FixedFeeDisplay, 1) -- Default is ONE invoice line
			   ,@SalesAccountKey = ISNULL(b.DefaultSalesAccountKey, 0) -- Can be null or 0	
			   ,@EstimateKey = b.EstimateKey -- For FF
		       ,@BillingClassKey = ISNULL(b.ClassKey, 0)
			   ,@FixedFeeAddProjectLine = ISNULL(b.FixedFeeAddProjectLine,0)
			   ,@OfficeKey = ISNULL(p.OfficeKey, c.OfficeKey)
		FROM
			tBilling b (nolock)
			LEFT JOIN tProject p (nolock) ON b.ProjectKey = p.ProjectKey
			LEFT JOIN tCampaign c (nolock) ON b.CampaignKey = c.CampaignKey
		WHERE  b.BillingKey = @BillingKey

		if not exists (select 1 from tGLAccount (NOLOCK) where CompanyKey = @CompanyKey and GLAccountKey = @SalesAccountKey )
			Select @SalesAccountKey = @DefaultSalesAccountKey 

		if @RequireClasses = 1 AND @BillingClassKey = 0 AND ISNULL(@DefaultClassKey, 0) > 0 
			SELECT @BillingClassKey = @DefaultClassKey

		-- If retainer, ignore line format/rollup and set up a dummy rollup
		IF @BillingMethod = 3
			SELECT @Rollup = 4

		-- If FF, it will depend on FixedFeeDisplay	
		IF @BillingMethod = 2
		BEGIN
			IF @FixedFeeDisplay = 1
				SELECT @FixedFeeRollup = 0	-- There is just a line in tBillingFixedFee for Entity = ''tEstimate''  
			ELSE IF @FixedFeeDisplay = 2 
				SELECT @FixedFeeRollup = 5	-- By Task
			ELSE IF @FixedFeeDisplay = 3
				SELECT @FixedFeeRollup = 6	-- By Service Item or by Billing Item
			ELSE IF @FixedFeeDisplay = 4
				SELECT @FixedFeeRollup = 6	-- By Billing Item
			ELSE IF @FixedFeeDisplay = 5
				SELECT @FixedFeeRollup = 7	-- By Project
			ELSE
				SELECT @FixedFeeRollup = 6

		END	

 		-- Rollup possible values: 
		-- If by Project			If by Client or other
		-- 0 1 Line					0 =1 line per project
		-- 1 Task					1 =1 line per project and Task
		-- 2 Service				2 =1 line per project and Service
		-- 3 Billing Item			3 =1 line per project and Billing Item 
		-- 8 Billing Item the Item  8 =1 line per project and Billing Item and Item

		-- For Abelson and Taylor only
		-- 11 Title
		-- 12 Title and Service
		-- 13 Service and Title

		-- New billing method
		-- 14 Service/Item ( not Service and Item, but Service or Item)

		-- Additional values
		-- 4 Retainer
		-- 5 FF By Task
		-- 6 FF By Service/Item or Billing Item
		-- 7 FF By Project

		/* This is how it should display when we have several projects

		Project 1
			Task 1		100
			Task 2		200
			Task 3		100
		Project 2
			BI 1		200
			BI 2		100
			BI 3		100
		Project 3
			S 1			10
			S 2			100
			S 3			100
			Exp			200
		Project 4		8000
		Retainer		1000

		If we only have one project, display normally

		Task 1
		Task 2
		Task 3

		i.e. without project line

		*/
	
		SELECT @ShowExtraProjectLine = 0
		--PRINT ''@BillingCount = '' + CONVERT(VARCHAR(10), @BillingCount)
		IF @BillingCount > 1
			BEGIN
				IF @BillingMethod = 1 -- TM
					IF @Rollup IN (1, 2, 3, 8, 9, 11, 12, 13, 14) -- 11, 12, 13 by title, for Abelson Taylor only
						SELECT @ShowExtraProjectLine = 1
					
				IF @BillingMethod = 2 -- FF, will display lines by Estimate (FFDisplay=1), Tasks (=2) or Service/Items (=3)
					IF @FixedFeeRollup > 0 -- if not one line per project
						SELECT @ShowExtraProjectLine = 1
			END	
			-- Not necessary for Retainers

		ELSE --Only One Project being billed
			BEGIN
			--print str(@Rollup)
				IF @Rollup = 8		
					SELECT @ShowExtraProjectLine = 1
			END	

	-- Rollup 9 is only valid in spBillingInvoiceLayout
		-- recover by selecting One Line Per Project
		if @Rollup = 9
			select @Rollup = 8


		-- Also if the user wants it for FF projects
		-- that can allow them to bill by service/items and then they can rollup to the top project line on the printout
		--if @BillingMethod = 2 and @FixedFeeAddProjectLine = 1 and isnull(@ProjectKey, 0) >= 0 and @FixedFeeRollup = 6 -- Item/service or Billing Item
		-- 561987 works for campaign also
		if @BillingMethod = 2 and @FixedFeeAddProjectLine = 1 and @FixedFeeRollup = 6 -- Item/service or Billing Item
			SELECT @ShowExtraProjectLine = 1

select @ShowExtraProjectLine as ShowExtraProjectLine 

		--select @FixedFeeDisplay as FixedFeeDisplay, @FixedFeeRollup as FixedFeeRollup,@Rollup as Rollup, @ProjectName as ProjectName
		--, @ShowExtraProjectLine as ShowExtraProjectLine,@ProjectName as ProjectName

		IF @ShowExtraProjectLine = 1 And @ProjectName is not null
		BEGIN
			-- Create summary line for project

			--create single invoice line
			exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
														-- (GHL 6/29/06, set to NULL instead of @ProjectKey)
														-- (GHL 4/23/10, set it back to @ProjectKey)
						  ,@ProjectKey					-- ProjectKey 
						  ,NULL							-- TaskKey
						  ,@ProjectName					-- Line Subject
						  ,NULL                 		-- Line description
						  ,0		      				-- Bill From 
						  ,0							-- Quantity
						  ,0							-- Unit Amount
						  ,0							-- Line Amount
						 ,1							-- line type = Summary
						  ,0							-- parent line key
						  ,NULL --@SalesAccountKey				-- Default Sales AccountKey -- displayed on screen
						  ,@BillingClassKey             -- Class Key
						  ,0							-- Taxable
						  ,0							-- Taxable2
						  ,@WorkTypeKey					-- Work TypeKey
						  ,@PostSalesUsingDetail
						  ,NULL							-- Entity
						  ,NULL							-- EntityKey
						  ,@OfficeKey					-- OfficeKey
						  ,NULL							-- DepartmentKey
						  ,@ParentInvoiceLineKey output

			if @@ERROR <> 0 
			  begin

				update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				exec sptInvoiceDelete @NewInvoiceKey
				return -17					 	
			  end			   		     		 
			if @RetVal <> 1 
			  begin
				update tBilling set ErrorMsg = ''An error occurred when inserting an invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				exec sptInvoiceDelete @NewInvoiceKey
				return -17					 	
			  end
		END


		/*
		|| Fixed Fee by Task
		*/		
		if @BillingMethod = 2 and @FixedFeeRollup = 5
		begin
			exec @RetVal = spBillingInvoiceOneLinePerTaskFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@ProjectKey, @SalesAccountKey , @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey
				,@EstimateKey

	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		/*
		|| Fixed Fee by Service/Item
		*/		
		if @BillingMethod = 2 And @FixedFeeRollup = 6
		begin
			exec @RetVal = spBillingInvoiceOneLinePerServiceItemFF @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@ProjectKey, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey, @ParentInvoiceLineKey, @EstimateKey
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	


		/*
		|| Fixed Fee by Project
		*/		
		if @BillingMethod = 2 And @FixedFeeRollup = 7
		begin
			exec @RetVal = spBillingInvoiceOneLinePerProjectFF @CompanyKey, @NewInvoiceKey ,@BillingKey , @ParentInvoiceLineKey 
				, @SalesAccountKey , @DefaultClassKey, @BillingClassKey, @WorkTypeKey
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per project for a fixed fee campaign worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		/*
		|| FF on one invoice line
		*/	

		IF @BillingMethod = 2 And @FixedFeeRollup = 0						
		BEGIN
			-- Pass 2 instead of @BillingMethod to indicate tBillingFixedFee records
			EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 2, @ProjectKey 
			,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail	
			,@EstimateKey

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a fixed fee worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	
		END	

		/*
		|| Handle single invoice line
		*/	
		IF @Rollup <= 0						
		BEGIN
			-- if there is a FF campaign, specify expenses for projects
			If @IsFFCampaign = 1 and isnull(@ProjectKey,0) > 0
				select @ProjectName = @ProjectName + '' Expenses''

			-- pass 1 as BillingMethod to indicate tBillingDetail
			EXEC @RetVal = spBillingInvoiceOneLine @NewInvoiceKey, @BillingKey, 1, @ProjectKey 
			,@ProjectName ,@SalesAccountKey, @BillingClassKey, @WorkTypeKey , @ParentInvoiceLineKey, @PostSalesUsingDetail
			,@EstimateKey	

			IF @RetVal < 0
			BEGIN
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				RETURN @RetVal
			END	

			-- Customization for Etna
			IF @RetVal > 0 and @ShowTransactionsOnInvoices = 1
			begin
				update tInvoiceLine
				set    DisplayOption = 3-- @kDisplayOptionTransactions
				where  InvoiceLineKey = @RetVal
			end

		END	

		/*
		|| Handle invoice lines by Task
		*/		
		if @Rollup = 1
		begin
			exec @RetVal = spBillingInvoiceOneLinePerTask @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 

	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per task for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end


		/*
		|| Handle invoice lines by Service (One line for expenses)
		*/		
		if @Rollup = 2
		begin
			exec @RetVal = spBillingInvoiceOneLinePerService @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end

		/*
		|| Handle invoice lines by Service/Item (One line per item for expenses) 
		*/		
		if @Rollup = 14
		begin
			exec @RetVal = spBillingInvoiceOneLinePerServiceItem @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per service/item for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
				
			EXEC sptInvoiceLineSetHours @NewInvoiceKey
			EXEC sptInvoiceLineSetExpenses @NewInvoiceKey
		end

		/*
		|| Handle invoice lines by Billing Item
		*/		
		if @Rollup = 3
		begin
			exec @RetVal = spBillingInvoiceOneLinePerBillingItem @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per billing item for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		/*
		|| Handle invoice line for the retainer amount
		*/		
		if @Rollup = 4
		begin
			exec @RetVal = spBillingInvoiceRetainer @NewInvoiceKey ,@BillingKey, @BillingMethod 
				,@SalesAccountKey , @BillingClassKey, @WorkTypeKey, @InvoiceDate
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting the invoice line for a retainer'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	


		/*
		|| Handle invoice lines by Billing Item AND Item
		*/		
		if @Rollup = 8
		begin
			exec @RetVal = spBillingInvoiceOneLinePerBillingItemItem @CompanyKey, @NewInvoiceKey ,@BillingKey, @BillingMethod, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @ParentInvoiceLineKey, @PostSalesUsingDetail 
	  		if @RetVal < 0
			begin
				update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per billing item and Item for a worksheet'' 
				where BillingKey = @TopBillingKey 

				EXEC sptInvoiceDelete @NewInvoiceKey
				return @RetVal
			end
		end			  	

		/*
		|| Handle invoice lines by Title for Abelson Taylor
		*/		
		if @Rollup in ( 11, 12, 13)
		begin
			EXEC @RetVal = spBillingInvoiceOneLinePerTitle @NewInvoiceKey, @BillingKey, @Rollup, @ProjectKey 
				,@SalesAccountKey , @DefaultClassKey, @BillingClassKey, @PostSalesUsingDetail, @ParentInvoiceLineKey

				IF @RetVal < 0
				BEGIN
					update tBilling set ErrorMsg = ''An error occurred when inserting invoice lines per title for a worksheet''  
					where BillingKey = @TopBillingKey 

					EXEC sptInvoiceDelete @NewInvoiceKey
					RETURN @RetVal
				END	
		end			  	

		IF ISNULL(@BillingStatusKey, 0) > 0
		BEGIN
			UPDATE tProject
			SET    ProjectBillingStatusKey = @BillingStatusKey
			WHERE  ProjectKey = @ProjectKey
		END

	END -- DisplayOrder or BillingKey


select @OldInvoiceKey = isnull(InvoiceKey, 0) 
	  ,@OldStatus = Status
from tBilling (nolock) where BillingKey = @TopBillingKey

-- If already invoiced, abort
if @OldInvoiceKey > 0 Or @OldStatus = 5 
begin
	EXEC sptInvoiceDelete @NewInvoiceKey
	return -1001
end		
if exists (select 1 from tInvoice (nolock) where BillingKey = @TopBillingKey and InvoiceKey <> @NewInvoiceKey)
begin
	EXEC sptInvoiceDelete @NewInvoiceKey
	return -1001
end		

	-- if summary line, display option = Sub Item Details
	-- if detail line, display option = No detail
	update tInvoiceLine
	set    DisplayOption = case when LineType =1 then 2 else 1 end
	where  InvoiceKey = @NewInvoiceKey
	and    DisplayOption is null

	exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0 -- added because we do not do it in sptInvoiceLineInsertMassBilling

	-- This will force the Taxable fields if the pref or the project requires them
	exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

	-- and recalc the taxes
	exec sptInvoiceRecalcAmounts @NewInvoiceKey

	-- the media taxes will be placed in the other taxes, tax1 and tax2 must be calculated first
	if @UseMediaTaxes = 1
		-- customization: pull taxes from the vendor instead of the client
		exec sptInvoiceGetVendorTaxes @NewInvoiceKey

	-- this is for Abelson Taylor, rollup hours on invoicelines
	exec  sptInvoiceLineSetHours @NewInvoiceKey

	-- If the user wanted an advance bill, tBilling.DefaultSalesAccountKey should already be set to the AdvBill account so set it now on the lines
	IF @AdvanceBill = 1
		UPDATE tInvoiceLine SET SalesAccountKey = @DefaultSalesAccountKey WHERE InvoiceKey = @NewInvoiceKey AND LineType = 2 

	-- This processing below involves the master as well
	-- Make sure that the master is in there too
	IF (SELECT COUNT(*) FROM #tBilling WHERE BillingKey = @TopBillingKey) = 0 		
		INSERT #tBilling (BillingKey) VALUES (@TopBillingKey) 

	-- Handle Advance Payments
	DECLARE @AvalaraEnabled tinyint
	SELECT @AvalaraEnabled = ISNULL(AvalaraEnabled, 0) FROM tPreference (nolock) WHERE CompanyKey = @CompanyKey
	
	IF @AvalaraEnabled = 0 --If using Avalara, the taxes will be overwritten after the spBillingInvoiceBill SP completes; run this SP after the Avalara call
		EXEC spBillingApplyAdvanceBill @TopBillingKey, @NewInvoiceKey

	-- If the invoice is completely paid by the advance bills, set Printed = 1 
	declare @InvoiceOpenAmount money
	declare @InvoiceTotalAmount money
	select @InvoiceOpenAmount = isnull(InvoiceTotalAmount, 0) - isnull(RetainerAmount, 0)  
	     ,@InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0)
	from tInvoice (nolock)
	where InvoiceKey = @NewInvoiceKey

	if @InvoiceOpenAmount = 0 and @InvoiceTotalAmount <> 0
		update tInvoice
		set    Printed = 1
		where  InvoiceKey = @NewInvoiceKey

	-- This processing below involves the master as well
	-- Make sure that the master is in there too
	IF (SELECT COUNT(*) FROM #tBilling WHERE BillingKey = @TopBillingKey) = 0 		
		INSERT #tBilling (BillingKey) VALUES (@TopBillingKey) 


	UPDATE tBilling 
	SET    tBilling.InvoiceKey = @NewInvoiceKey 
		  ,tBilling.Status = 5
	FROM #tBilling
	WHERE  tBilling.BillingKey = #tBilling.BillingKey	
	IF @@ERROR <> 0
	BEGIN
		update tBilling set ErrorMsg = ''An error occurred when changing the status of the billing worksheet to invoiced'' 
		where BillingKey = @TopBillingKey 

		EXEC sptInvoiceDelete @NewInvoiceKey
		RETURN -1000
	END

	EXEC sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey	

	-- This is an attempt to reconnect with a billing schedule on a FF project if missing
	SELECT @BillingKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @BillingKey = MIN(tb.BillingKey)
		FROM   #tBilling tb
			INNER JOIN tBilling b (nolock) ON tb.BillingKey = b.BillingKey
		WHERE  tb.BillingKey > @BillingKey
		AND    b.ProjectKey > 0
		AND    b.BillingKey > @BillingKey
		AND    b.BillingMethod = 2 -- FF

		IF @BillingKey is null
			break

		SELECT @ProjectKey = ProjectKey from tBilling (nolock) where BillingKey = @BillingKey

		-- if missing, place the invoice on a billing schedule
		IF NOT EXISTS (SELECT 1 FROM tBillingSchedule (nolock) WHERE ProjectKey = @ProjectKey and BillingKey = @BillingKey)
			EXEC spFixedFeesUpdateBillingSchedule @NewInvoiceKey, @ProjectKey
		ELSE
			UPDATE tBillingSchedule
			SET    InvoiceKey = @NewInvoiceKey
			      ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
			                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
			                                             case when isnull(p.ExpensesNotIncluded, 0) = 0
			                                                  then isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0) + isnull(p.EstExpenses, 0) + isnull(p.ApprovedCOExpense, 0)
			                                                  else isnull(p.EstLabor, 0) + isnull(p.ApprovedCOLabor, 0)
			                                             end) / 100.00, 2), ''N2'')
			                                    else null end
			                         from  tBillingSchedule bs (nolock)
			                         join  tProject p (nolock) on p.ProjectKey = bs.ProjectKey
			                         where bs.ProjectKey = @ProjectKey and bs.BillingKey = @BillingKey)
			WHERE  ProjectKey = @ProjectKey and BillingKey = @BillingKey

	END

	-- Link T&M project billing schedules to the invoice (BilledComment populated by spFixedFeesUpdateBillingSchedule)
	SELECT @BillingKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @BillingKey = MIN(tb.BillingKey)
		FROM   #tBilling tb
			INNER JOIN tBilling b (nolock) ON tb.BillingKey = b.BillingKey
		WHERE  tb.BillingKey > @BillingKey
		AND    b.ProjectKey > 0
		AND    b.BillingKey > @BillingKey
		AND    b.BillingMethod = 1 -- T&M

		IF @BillingKey is null
			break

		SELECT @ProjectKey = ProjectKey from tBilling (nolock) where BillingKey = @BillingKey

		EXEC spFixedFeesUpdateBillingSchedule @NewInvoiceKey, @ProjectKey

	END

	-- Link campaign billing schedules to the invoice (all billing methods — worksheet rows have BillingKey set)
	declare @CampaignKey int
	SELECT @BillingKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @BillingKey = MIN(tb.BillingKey)
		FROM   #tBilling tb
			INNER JOIN tBilling b (nolock) ON tb.BillingKey = b.BillingKey
		WHERE  tb.BillingKey > @BillingKey
		AND    b.CampaignKey > 0
		AND    b.BillingKey > @BillingKey

		IF @BillingKey is null
			break

		SELECT @CampaignKey = CampaignKey from tBilling (nolock) where BillingKey = @BillingKey

		UPDATE tBillingSchedule
			SET    InvoiceKey = @NewInvoiceKey
			      ,BilledComment = (select case when isnull(bs.PercentBudget, 0) > 0
			                                    then ''Scheduled Amount: '' + FORMAT(ROUND(isnull(bs.PercentBudget, 0) * (
			                                             case when isnull(c.ExpensesNotIncluded, 0) = 0
			                                                  then isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0) + isnull(c.EstExpenses, 0) + isnull(c.ApprovedCOExpense, 0)
			                                                  else isnull(c.EstLabor, 0) + isnull(c.ApprovedCOLabor, 0)
			                                             end) / 100.00, 2), ''N2'')
			                                    else null end
			                         from  tBillingSchedule bs (nolock)
			                         join  tCampaign c (nolock) on c.CampaignKey = bs.CampaignKey
			                         where bs.CampaignKey = @CampaignKey and bs.BillingKey = @BillingKey)
			WHERE  CampaignKey = @CampaignKey and BillingKey = @BillingKey
	END

	RETURN @NewInvoiceKey


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptBillingScheduleUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptBillingScheduleUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptBillingScheduleUpdate]
	@BillingScheduleKey int,
	@ProjectKey int = NULL,
	@NextBillDate smalldatetime,
	@TaskKey int,
	@Comments varchar(4000),
	@Action varchar(10) = ''update'',
	@PercentBudget decimal(24,4) = null,
	@DollarAmount decimal(24,4) = null,
	@AdvanceBill tinyint = 0,
	@CampaignKey int = NULL

AS --Encrypt

  /*
  || When     Who Rel    What
  || 08/25/09 GHL 10.508 (58125) Rewrote using new standard Action param 
  || 01/25/13 GHL 10.564 (166323) Could not generate FF billing worksheet because NextBillDate and TaskKey is null
  ||                      Deleting now records if both fields are null      
  || 07/15/13 GHL 10.570 (182036) Added PercentBudget     
  || 11/17/14 GHL 10.586 (236560) Added update of forecast so that the user can regenerate the forecast project detail                        
  || 10/24/17 MCM 10.621 (ToDo 312844) Adding the DollarAmount field
  || 01/08/18 GHL 18.100 Make sure that NextBillDate is unique (this was done to help MN with testing)
  || 03/09/18 GHL 18.300 (389314) Only check for unique NextBillDate if TaskKey = null, because tasks could end on the same day
  ||                     Possible scenarios:
  ||                     Task 1 2/13/18
  ||                     Task 2 2/13/18 (2 different tasks could have the same dates, issue 389314)
  ||                     Task 2 3/13/18 (same tasks, diff dates, unlikely because mass billing sets NextBillingDate to ActComplete)
  ||                     Blank  2/13/18
  ||                     Blank  2/13/18 (NOT ALLOWED) 
  || 10/03/18 GHL 18.920 (396483) Added Advance Bill parameter to specify that the invoice to create is an advance bill
  ||                     Only visible on the UI for FF projects, it is assumed that billing schedule for TM projects are always adv bill
  || 04/12/21 MFT 21.050 (455922) Added @CampaignKey
  || 07/08/26 AMP 26.07.19 (729259) Prevent editing billed rows; only allow Comments to be updated when InvoiceKey is set
  */

if @NextBillDate is null and isnull(@TaskKey, 0) = 0
	select @Action = ''delete''

if isnull(@PercentBudget, 0) <= 0
	select @PercentBudget = null

if isnull(@PercentBudget, 0) > 100
	select @PercentBudget = 100

if isnull(@PercentBudget, 0) > 0
	select @PercentBudget = round(@PercentBudget, 2)
	
if isnull(@DollarAmount, 0) <= 0
	select @DollarAmount = null

-- if there is a conflict, the % budget wins
if isnull(@PercentBudget, 0) > 0 And isnull(@DollarAmount, 0) > 0
	select @DollarAmount = null

select @AdvanceBill = isnull(@AdvanceBill, 0)

-- if this is an update/insert, make sure that NextBillDate/TaskKey are unique 
if @Action != ''delete''
begin
		-- only perform these checks if we have no tasks
		If isnull(@TaskKey, 0) = 0 and @NextBillDate is not null
		begin 
			IF @BillingScheduleKey <= 0 
			begin
				-- this is insert
				If exists (select  1 from tBillingSchedule (nolock)
					where ProjectKey = @ProjectKey
					and NextBillDate = @NextBillDate
					and isnull(TaskKey, 0) = 0
					) return -1
			end
			else
			begin
				If exists (select  1 from tBillingSchedule (nolock)
					where ProjectKey = @ProjectKey
					and NextBillDate = @NextBillDate
					and isnull(TaskKey, 0) = isnull(@TaskKey, 0) 
					and BillingScheduleKey != @BillingScheduleKey  
					) return -1
			end
		end
end


update tForecastDetail
set    tForecastDetail.RegenerateNeeded = 1
where  Entity in (''tProject-Approved'', ''tProject-Potential'')
and    EntityKey = @ProjectKey

if @Action = ''delete''
BEGIN
						
	DELETE
	FROM  tBillingSchedule
	WHERE BillingScheduleKey = @BillingScheduleKey 
	
	Return 0
END
ELSE
BEGIN

	-- if the row is already billed, only allow Comments to be updated
	if @BillingScheduleKey > 0
	begin
		declare @ExistingInvoiceKey int
		select @ExistingInvoiceKey = InvoiceKey from tBillingSchedule (nolock) where BillingScheduleKey = @BillingScheduleKey
		if isnull(@ExistingInvoiceKey, 0) > 0
		begin
			update tBillingSchedule set Comments = @Comments where BillingScheduleKey = @BillingScheduleKey
			return @BillingScheduleKey
		end
	end

	IF @BillingScheduleKey <= 0
	BEGIN
		INSERT tBillingSchedule
			(
			ProjectKey,
			NextBillDate,
			TaskKey,
			Comments,
			PercentBudget,
			DollarAmount,
			AdvanceBill,
			CampaignKey
			)

		VALUES
			(
			@ProjectKey,
			@NextBillDate,
			@TaskKey,
			@Comments,
			@PercentBudget,
			@DollarAmount,
			@AdvanceBill,
			@CampaignKey
			)
		
		return @@IDENTITY
	END
	ELSE
	BEGIN
	
		UPDATE
			tBillingSchedule
		SET
			ProjectKey = @ProjectKey,
			NextBillDate = @NextBillDate,
			TaskKey = @TaskKey,
			Comments = @Comments,
			PercentBudget = @PercentBudget,
			DollarAmount = @DollarAmount,
			AdvanceBill = @AdvanceBill,
			CampaignKey = @CampaignKey
		WHERE
			BillingScheduleKey = @BillingScheduleKey 
		
		return @BillingScheduleKey
	
	END
	
END

	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptApprovalStepNotifyDefInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptApprovalStepNotifyDefInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[sptApprovalStepNotifyDefInsert]
	@ApprovalStepDefKey int,
	@AssignedUserKey int,
	@DisplayOrder int,
	@Entity varchar(100) = Null
AS --Encrypt

 /*
  || When		Who Rel			What
  || 02/07/19   RLS 19.0.3.0    (441481) Created for enhancement
  || 03/15/22   RLB 22.04.17    (591764) user happened to have the same key as key person so match entity as well
  */

	if not exists (select 1 from tApprovalStepNotifyDef (nolock) where ApprovalStepDefKey = @ApprovalStepDefKey and AssignedUserKey = @AssignedUserKey and Entity = @Entity)

	INSERT tApprovalStepNotifyDef
		(
		ApprovalStepDefKey,
		AssignedUserKey,
		DisplayOrder,
		Entity
		)

	VALUES
		(
		@ApprovalStepDefKey,
		@AssignedUserKey,
		@DisplayOrder,
		@Entity
		)

	RETURN 1
	

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIUserLookupGet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIUserLookupGet]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAIUserLookupGet]
    (
        @CompanyKey int,
        @UserKey int
    )
AS --Encrypt

/*
|| When      Who Rel      What
|| 07/16/26  GAR 26.08.16 (733142)  Created. Rights-scoped replacement for the spInitLoad ''tUser'' branch used by
||                        the MCP get_lookup_list tool. Returns an explicit allow-list of tUser columns.
||                        Column groups mirror the rights that gate the tabs on the Employee admin page:
||                          admineditlogin        -> Security Controls fields (login, security group, SSO, lock state)
||                          user_billing          -> Accounting fields (rates, costs, limits, approvers, GL/vendor)
||                          employee_project_time -> Projects & Time fields (assignment defaults, subscriptions)
||                        Users without a group''s right receive NULL for that group''s columns.
||                        Credentials and tokens (Password, 2FA codes, OAuth/API tokens, Uid) are never returned.
||                        Result sets: 1) right flags  2) user rows. On access denial returns the standard
||                        #errors result set and -103.
*/

set nocount on

declare @SecurityGroupKey int
declare @Administrator int
declare @RestrictToGLCompany int

declare @HasAdminEmployee int = 0
declare @HasLogin int = 0        -- admineditlogin
declare @HasBilling int = 0      -- user_billing
declare @HasProjectTime int = 0  -- employee_project_time
declare @HasService int = 0      -- user_billing OR employee_project_time (default service fields)

select * into #errors from tAPIErrorTemplate where 1 = 2

select  @SecurityGroupKey = SecurityGroupKey,
        @Administrator = ISNULL(Administrator, 0)
from    tUser (nolock)
where   UserKey = @UserKey
and     (CompanyKey = @CompanyKey or OwnerCompanyKey = @CompanyKey)

if @Administrator is null
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''Calling user was not found in this company.'', ''general'')

    select errorType, errorCode, errorMessage, fieldName from #errors
    drop table #errors
    return -103
end

if @Administrator = 1
begin
    select @HasAdminEmployee = 1, @HasLogin = 1, @HasBilling = 1, @HasProjectTime = 1
end
else
begin
    select  @HasAdminEmployee = ISNULL(max(case when r.RightID = ''adminemployee''         then 1 else 0 end), 0),
            @HasLogin         = ISNULL(max(case when r.RightID = ''admineditlogin''        then 1 else 0 end), 0),
            @HasBilling       = ISNULL(max(case when r.RightID = ''user_billing''          then 1 else 0 end), 0),
            @HasProjectTime   = ISNULL(max(case when r.RightID = ''employee_project_time'' then 1 else 0 end), 0)
    from    tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where   ra.EntityType = ''Security Group''
    and     ra.EntityKey = @SecurityGroupKey
    and     r.RightID in (''adminemployee'', ''admineditlogin'', ''user_billing'', ''employee_project_time'')
end

if @HasAdminEmployee = 0
begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''Retrieving the User list requires the adminemployee right or administrator access.'', ''general'')

    select errorType, errorCode, errorMessage, fieldName from #errors
    drop table #errors
    return -103
end

if @HasBilling = 1 or @HasProjectTime = 1
    select @HasService = 1

select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0) from tPreference (nolock) where CompanyKey = @CompanyKey

-- Result set 1: which optional column groups are populated (the API layer
-- uses this to drop the ungranted groups from the response entirely)
select  @HasLogin as hasLoginFields,
        @HasBilling as hasBillingFields,
        @HasProjectTime as hasProjectTimeFields,
        @HasService as hasServiceFields

-- Result set 2: the user rows. Explicit allow-list only — never u.*.
-- Gated groups return NULL when the caller lacks the corresponding right.
select
        -- Base group: visible with adminemployee (Employee Details tab)
        u.UserKey as userKey,
        u.CompanyKey as companyKey,
        u.FirstName as firstName,
        u.MiddleName as middleName,
        u.LastName as lastName,
        u.Salutation as salutation,
        u.Title as title,
        u.Email as email,
        u.Phone1 as phone1,
        u.Phone2 as phone2,
        u.Cell as cell,
        u.Fax as fax,
        u.DepartmentKey as departmentKey,
        dep.DepartmentName as departmentName,
        u.OfficeKey as officeKey,
        o.OfficeName as officeName,
        u.Active as active,
        u.ClientVendorLogin as clientVendorLogin,
        u.Supervisor as supervisor,
        u.SupervisorKey as supervisorKey,
        u.ReportsToKey as reportsToKey,
        u.UserRole as userRole,
        u.TimeZoneIndex as timeZoneIndex,
        u.LanguageID as languageID,
        u.UserCulture as userCulture,
        u.InOutStatus as inOutStatus,
        u.InOutNotes as inOutNotes,
        u.DateAdded as dateAdded,
        u.DateHired as dateHired,
        u.LastModified as lastModified,
        u.CustomFieldKey as customFieldKey,
        LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, ''''))) as userName,
        LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, ''''))) as formattedName,
        case
            when u.MiddleName is null then LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, '''')))
            else LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + SUBSTRING(u.MiddleName, 1, 1) + '' '' + ISNULL(u.LastName, '''')))
        end as userFullName,
        SUBSTRING(ISNULL(u.FirstName, ''''), 1, 1) + SUBSTRING(ISNULL(u.MiddleName, ''''), 1, 1) + SUBSTRING(ISNULL(u.LastName, ''''), 1, 1) as initials,

        -- Login group: requires admineditlogin (Security Controls tab)
        case when @HasLogin = 1 then u.UserID else null end as userID,
        case when @HasLogin = 1 then u.SecurityGroupKey else null end as securityGroupKey,
        case when @HasLogin = 1 then u.Administrator else null end as administrator,
        case when @HasLogin = 1 then u.Locked else null end as locked,
        case when @HasLogin = 1 then u.RightLevel else null end as rightLevel,
        case when @HasLogin = 1 then u.SystemID else null end as systemID,
        case when @HasLogin = 1 then u.LastLogin else null end as lastLogin,
        case when @HasLogin = 1 then u.LastPwdChange else null end as lastPwdChange,
        case when @HasLogin = 1 then u.NumberOfAttempts else null end as numberOfAttempts,
        case when @HasLogin = 1 then u.ForcePwdChangeOnNextLogin else null end as forcePwdChangeOnNextLogin,
        case when @HasLogin = 1 then u.SSOAutoUpdateOff else null end as ssoAutoUpdateOff,
        case when @HasLogin = 1 then u.SSOAuthenticationOff else null end as ssoAuthenticationOff,
        case when @HasLogin = 1 then u.EnableAPIMCPUse else null end as enableAPIMCPUse,
        case when @HasLogin = 1 then u.SuspendAdmin else null end as suspendAdmin,
        case when @HasLogin = 1 then u.LoggedOut else null end as loggedOut,
        case when @HasLogin = 1 then u.LastLoggedOutDate else null end as lastLoggedOutDate,

        -- Billing group: requires user_billing (Accounting tab)
        case when @HasBilling = 1 then u.HourlyRate else null end as hourlyRate,
        case when @HasBilling = 1 then u.HourlyCost else null end as hourlyCost,
        case when @HasBilling = 1 then u.HourlyCost2 else null end as hourlyCost2,
        case when @HasBilling = 1 then u.MonthlyCost else null end as monthlyCost,
        case when @HasBilling = 1 then u.OvertimeCost else null end as overtimeCost,
        case when @HasBilling = 1 then u.VendorCost else null end as vendorCost,
        case when @HasBilling = 1 then u.OvertimeVendorCost else null end as overtimeVendorCost,
        case when @HasBilling = 1 then u.RateLevel else null end as rateLevel,
        case when @HasBilling = 1 then u.POLimit else null end as poLimit,
        case when @HasBilling = 1 then u.IOLimit else null end as ioLimit,
        case when @HasBilling = 1 then u.BCLimit else null end as bcLimit,
        case when @HasBilling = 1 then u.TimeApprover else null end as timeApproverKey,
        case when @HasBilling = 1 then u.ExpenseApprover else null end as expenseApproverKey,
        case when @HasBilling = 1 then u.CreditCardApprover else null end as creditCardApproverKey,
        case when @HasBilling = 1 then u.CalendarApprover else null end as calendarApproverKey,
        case when @HasBilling = 1 then u.BackupApprover else null end as backupApproverKey,
        case when @HasBilling = 1 then u.GLCompanyKey else null end as glCompanyKey,
        case when @HasBilling = 1 then glc.GLCompanyID else null end as glCompanyID,
        case when @HasBilling = 1 then glc.GLCompanyName else null end as glCompanyName,
        case when @HasBilling = 1 then u.ClassKey else null end as classKey,
        case when @HasBilling = 1 then u.VendorKey else null end as vendorKey,
        case when @HasBilling = 1 then u.TitleKey else null end as titleKey,
        case when @HasBilling = 1 then u.Contractor else null end as contractor,

        -- Projects & Time group: requires employee_project_time (Projects & Time tab)
        case when @HasProjectTime = 1 then u.AutoAssign else null end as autoAssign,
        case when @HasProjectTime = 1 then u.NoUnassign else null end as noUnassign,
        case when @HasProjectTime = 1 then u.SubscribeDiary else null end as subscribeDiary,
        case when @HasProjectTime = 1 then u.SubscribeDiaryPA else null end as subscribeDiaryPA,
        case when @HasProjectTime = 1 then u.SubscribeToDo else null end as subscribeToDo,
        case when @HasProjectTime = 1 then u.SubscribeToDoPA else null end as subscribeToDoPA,
        case when @HasProjectTime = 1 then u.SubscribeFileUpload else null end as subscribeFileUpload,
        case when @HasProjectTime = 1 then u.DeliverableReviewer else null end as deliverableReviewer,
        case when @HasProjectTime = 1 then u.DeliverableNotify else null end as deliverableNotify,
        case when @HasProjectTime = 1 then u.RequireUserTimeDetails else null end as requireUserTimeDetails,

        -- Service group: requires user_billing OR employee_project_time
        case when @HasService = 1 then u.DefaultServiceKey else null end as defaultServiceKey,
        case when @HasService = 1 then s.Description else null end as serviceDescription,
        case when @HasService = 1 then s.ServiceCode else null end as serviceCode

from    tUser u (nolock)
left join tService s (nolock) on u.DefaultServiceKey = s.ServiceKey
left join tOffice o (nolock) on u.OfficeKey = o.OfficeKey
left join tDepartment dep (nolock) on u.DepartmentKey = dep.DepartmentKey
left join tGLCompany glc (nolock) on u.GLCompanyKey = glc.GLCompanyKey
where   (
        u.CompanyKey = @CompanyKey
        or (u.OwnerCompanyKey = @CompanyKey and u.ClientVendorLogin = 0 and u.UserID is not null and u.Active = 1)
        )
and     (@RestrictToGLCompany = 0
        or u.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
        )
order by u.FirstName, u.LastName

drop table #errors
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIVendorUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIVendorUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE    PROCEDURE [dbo].[spApiAIVendorUpdate]
	@CompanyKey int = 0,
	@CompanyName nvarchar(200) = NULL,
	@OwnerCompanyKey int,
	@UserKey int,

	@VendorID nvarchar(50) = NULL,
	@Vendor tinyint = NULL,
	@Active tinyint = NULL,
	@ActiveVendor tinyint = NULL,
	@OverheadVendor tinyint = NULL,
	@OnHold tinyint = NULL,
	@VendorDownloaded tinyint = NULL,
	@WebSite varchar(100) = NULL,
	@Phone varchar(50) = NULL,
	@Fax varchar(50) = NULL,
	@EINNumber varchar(100) = NULL,
	@DBA varchar(200) = NULL,
	@UseDBAForPayment tinyint = NULL,
	@UseDBAForPayment1099 tinyint = NULL,
	@UseAltAddress tinyint = NULL,
	@CurrencyID varchar(10) = NULL,

	@AddressName varchar(200) = NULL,
	@Address1 varchar(100) = NULL,
	@Address2 varchar(100) = NULL,
	@Address3 varchar(100) = NULL,
	@City varchar(100) = NULL,
	@State varchar(50) = NULL,
	@PostalCode varchar(20) = NULL,
	@Country varchar(50) = NULL,
	@PaymentAddressKey int = NULL,

	@ContactOwnerName varchar(300) = NULL,
	@DefaultAPApproverName varchar(300) = NULL,

	@DefaultExpenseAccountKey int = NULL,
	@DefaultAPAccountKey int = NULL,
	@VendorSalesTaxKey int = NULL,
	@VendorSalesTax2Key int = NULL,
	@DefaultMemo nvarchar(500) = NULL,
	@TermsDays int = NULL,
	@TermsPercent decimal(24,4) = NULL,
	@TermsNet int = NULL,
	@Type1099 smallint = NULL,
	@Box1099 varchar(10) = NULL,
	@FATCAFilingRequirement tinyint = NULL,
	@AvalaraTaxCodeKey int = NULL,
	@POHeaderStandardTextKey int = NULL,
	@POFooterStandardTextKey int = NULL,

	@CCAccepted tinyint = NULL,
	@CCAccountKey int = NULL,
	@EmailCCToAddress varchar(200) = NULL,
	@VCardAccepted tinyint = NULL,
	@OnePaymentPerVoucher tinyint = NULL,
	@CCPayeeName varchar(50) = NULL

AS --Encrypt

/*
|| When      Who Rel        What
|| 07/09/26  GAR 26.08.16   (731183) Created -- AI/MCP-facing vendor-specific update, mirroring
||                                   spApiAIClientUpdate but for the Vendor side of tCompany. Separate from
||                                   spApiAICompanyUpdate (general company add/update) and
||                                   spApiAICompanyConvertToVendor (initial conversion to Vendor status).
||                                   Requires the target to already be an existing company (does not insert --
||                                   use add_update_company to create a company and convert_company_to_vendor
||                                   to make it a Vendor first). Wraps sptCompanyUpdateVendor with AI-friendly
||                                   name-based resolution, partial-update-safe defaults (seeded from the
||                                   current row so an update that only touches one field doesn''t blank out
||                                   the rest -- sptCompanyUpdateVendor itself does a full-row overwrite with
||                                   no ISNULL preservation), and the standard #errors validation/security
||                                   pattern. Deliberately does not replicate every side effect of the UI''s
||                                   Modules.Purchasing.Vendor.updateData (custom field writes, new-vendor
||                                   notification email, EIN/bank-change audit log entries) -- only the core
||                                   field update plus the GL-company-access default-row insert so the
||                                   editing user isn''t locked out under RestrictToGLCompany.
||                                   Does NOT accept banking/wire fields (BankAccountNumber, BankRoutingNumber,
||                                   BankAccountName, BankAccountTypeKey, BIC, IBAN, CountryCode, ACHEnabled,
||                                   ABAEnabled, PAINEnabled, EmailACHToAddress) by design -- an AI-driven tool
||                                   should not be able to redirect where a vendor gets paid. Those fields are
||                                   always passed through unchanged from the current row and remain UI-only.
|| 07/10/26  GAR 26.08.16   Added spCheckAccess (tCompany) record-level gate after the cm_editacctinfo right /
||                                   GL company checks -- mirrors spApiAIVoucherDetailUpdate / spApiAICompanyCustomFieldSave.
*/

  -- Set up error table
  select * into #errors from tAPIErrorTemplate where 1 = 2

  if @OwnerCompanyKey is null or @OwnerCompanyKey = 0
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''Owner Company is required.'', ''ownerCompanyKey'')

  if (@CompanyKey is null or @CompanyKey = 0) and (@CompanyName is null or LTRIM(RTRIM(@CompanyName)) = '''')
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''REQUIRED_FIELD'', ''companyKey or companyName is required.'', ''companyName'')

  declare @ErrorCount int
  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -100
  end

  -- Resolve CompanyKey by name if not supplied directly. This tool only updates an EXISTING
  -- company -- it never inserts a new tCompany row.
  if isnull(@CompanyKey, 0) = 0
  begin
    select @CompanyKey = CompanyKey
    from tCompany (nolock)
    where OwnerCompanyKey = @OwnerCompanyKey
      and CompanyName = @CompanyName
  end

  if not exists (select 1 from tCompany (nolock) where CompanyKey = @CompanyKey and OwnerCompanyKey = @OwnerCompanyKey)
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''NOT_FOUND'', ''Company not found: '' + isnull(@CompanyName, CAST(isnull(@CompanyKey,0) as varchar(20))) + ''. update_vendor only updates an existing company -- use add_update_company to create one first.'', ''companyName'')
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Rights: Administrator, or ''cm_editacctinfo'' -- mirrors Modules.Purchasing.Vendor.updateData''s
  -- update branch (WJAPP/purchasing/vendors/Vendor.vb). This tool never inserts, so the
  -- ''addCompanies'' branch used for brand-new vendors does not apply here.
  declare @IsAdministrator tinyint, @SecurityGroupKey int
  select @IsAdministrator = Administrator, @SecurityGroupKey = SecurityGroupKey
  from tUser (nolock)
  where UserKey = @UserKey

  if isnull(@IsAdministrator, 0) <> 1
  begin
    declare @HasEditAcctInfo bit = 0

    select @HasEditAcctInfo = 1
    from tRight r (nolock)
    inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
    where ra.EntityType = ''Security Group''
      and ra.EntityKey = @SecurityGroupKey
      and r.RightID = ''cm_editacctinfo''

    if @HasEditAcctInfo = 0
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You do not have the ''''Edit Account Info'''' right required to update this vendor.'', ''general'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -103
    end
  end

  -- GL company restriction: same record-level check used by spApiAICompanyUpdate / spApiAIClientUpdate
  declare @RestrictToGLCompany int, @CompanyGLCompanyKey int
  select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
  from tPreference (nolock)
  where CompanyKey = @OwnerCompanyKey

  if @IsAdministrator <> 1 and @RestrictToGLCompany = 1
  begin
    select @CompanyGLCompanyKey = GLCompanyKey from tCompany (nolock) where CompanyKey = @CompanyKey

    if not exists (select 1 from tUserGLCompanyAccess (nolock) where UserKey = @UserKey and GLCompanyKey = @CompanyGLCompanyKey)
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''ACCESS_DENIED'', ''You do not have access to this company based on your GL company restrictions.'', ''companyKey'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -103
    end
  end

  -- Record-level access gate via spCheckAccess (tCompany) -- catches folder security and any
  -- other record-level restrictions beyond the cm_editacctinfo right / GL company checks above.
  declare @AccessOK int
  exec @AccessOK = spCheckAccess @UserKey, @OwnerCompanyKey, ''tCompany'', @CompanyKey
  if @AccessOK <> 1
  begin
    insert into #errors (errorType, errorCode, errorMessage, fieldName)
    values (''error'', ''ACCESS_DENIED'', ''You do not have access to modify this vendor.'', ''companyKey'')
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -103
  end

  -- Name-based resolution for staff references. Each is seeded from the current row when the
  -- caller doesn''t supply a name, so an update that only touches unrelated fields leaves these
  -- assignments unchanged.
  declare @ContactOwnerKey int, @DefaultAPApproverKey int

  select @ContactOwnerKey = isnull(ContactOwnerKey, 0),
         @DefaultAPApproverKey = isnull(DefaultAPApproverKey, 0)
  from tCompany (nolock)
  where CompanyKey = @CompanyKey

  if @ContactOwnerName is not null and LTRIM(RTRIM(@ContactOwnerName)) <> ''''
  begin
    select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @ContactOwnerName order by UserKey
    if @ContactOwnerKey = 0
      select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @ContactOwnerName order by UserKey
    if @ContactOwnerKey = 0
      select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @ContactOwnerName order by UserKey
    if @ContactOwnerKey = 0
      select top 1 @ContactOwnerKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @ContactOwnerName + ''%'' order by UserKey
    if @ContactOwnerKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for companyOwner: '' + @ContactOwnerName, ''companyOwner'')
  end

  if @DefaultAPApproverName is not null and LTRIM(RTRIM(@DefaultAPApproverName)) <> ''''
  begin
    select top 1 @DefaultAPApproverKey = UserKey from tUser (nolock)
      where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName = @DefaultAPApproverName order by UserKey
    if @DefaultAPApproverKey = 0
      select top 1 @DefaultAPApproverKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and Email = @DefaultAPApproverName order by UserKey
    if @DefaultAPApproverKey = 0
      select top 1 @DefaultAPApproverKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and UserID = @DefaultAPApproverName order by UserKey
    if @DefaultAPApproverKey = 0
      select top 1 @DefaultAPApproverKey = UserKey from tUser (nolock)
        where CompanyKey = @OwnerCompanyKey and Active = 1 and FirstName + '' '' + LastName like ''%'' + @DefaultAPApproverName + ''%'' order by UserKey
    if @DefaultAPApproverKey = 0
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''NOT_FOUND'', ''User not found for defaultAPApprover: '' + @DefaultAPApproverName, ''defaultAPApprover'')
  end

  select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
  if @ErrorCount > 0
  begin
    select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
    drop table #errors
    return -101
  end

  -- Partial-update-safe defaults: seed every remaining optional param from the current row so a
  -- caller that only supplies e.g. termsNet doesn''t blank out everything else --
  -- sptCompanyUpdateVendor itself does a full-row overwrite with no ISNULL preservation.
  -- Banking/wire fields (Bank*, BIC, IBAN, CountryCode, ACHEnabled, ABAEnabled, PAINEnabled,
  -- EmailACHToAddress) are excluded from this tool''s surface by design -- always seeded from the
  -- current row so they pass through to sptCompanyUpdateVendor completely unchanged.
  declare
    @BankAccountNumber varchar(500), @BankRoutingNumber varchar(500), @BankAccountName varchar(100),
    @BankAccountTypeKey int, @PAINEnabled tinyint, @BIC varchar(20), @IBAN varchar(34),
    @CountryCode char(2), @ACHEnabled tinyint, @ABAEnabled tinyint, @EmailACHToAddress varchar(200)

  select
    @VendorID = isnull(@VendorID, VendorID),
    @Vendor = isnull(@Vendor, isnull(Vendor, 0)),
    @Active = isnull(@Active, isnull(Active, 1)),
    @ActiveVendor = isnull(@ActiveVendor, isnull(ActiveVendor, 1)),
    @OverheadVendor = isnull(@OverheadVendor, isnull(OverheadVendor, 0)),
    @OnHold = isnull(@OnHold, isnull(OnHold, 0)),
    @VendorDownloaded = isnull(@VendorDownloaded, isnull(VendorDownloaded, 0)),
    @WebSite = isnull(@WebSite, WebSite),
    @Phone = isnull(@Phone, Phone),
    @Fax = isnull(@Fax, Fax),
    @EINNumber = isnull(@EINNumber, EINNumber),
    @DBA = isnull(@DBA, DBA),
    @UseDBAForPayment = isnull(@UseDBAForPayment, isnull(UseDBAForPayment, 0)),
    @UseDBAForPayment1099 = isnull(@UseDBAForPayment1099, isnull(UseDBAForPayment1099, 0)),
    @UseAltAddress = isnull(@UseAltAddress, isnull(UseAltAddress, 0)),
    @CurrencyID = isnull(@CurrencyID, CurrencyID),
    @PaymentAddressKey = isnull(@PaymentAddressKey, isnull(PaymentAddressKey, 0)),
    @DefaultExpenseAccountKey = isnull(@DefaultExpenseAccountKey, isnull(DefaultExpenseAccountKey, 0)),
    @DefaultAPAccountKey = isnull(@DefaultAPAccountKey, isnull(DefaultAPAccountKey, 0)),
    @VendorSalesTaxKey = isnull(@VendorSalesTaxKey, isnull(VendorSalesTaxKey, 0)),
    @VendorSalesTax2Key = isnull(@VendorSalesTax2Key, isnull(VendorSalesTax2Key, 0)),
    @DefaultMemo = isnull(@DefaultMemo, DefaultMemo),
    @TermsDays = isnull(@TermsDays, isnull(TermsDays, 0)),
    @TermsPercent = isnull(@TermsPercent, isnull(TermsPercent, 0)),
    @TermsNet = isnull(@TermsNet, isnull(TermsNet, 30)),
    @Type1099 = isnull(@Type1099, isnull(Type1099, 0)),
    @Box1099 = isnull(@Box1099, Box1099),
    @FATCAFilingRequirement = isnull(@FATCAFilingRequirement, isnull(FATCAFilingRequirement, 0)),
    @AvalaraTaxCodeKey = isnull(@AvalaraTaxCodeKey, AvalaraTaxCodeKey),
    @POHeaderStandardTextKey = isnull(@POHeaderStandardTextKey, isnull(POHeaderStandardTextKey, 0)),
    @POFooterStandardTextKey = isnull(@POFooterStandardTextKey, isnull(POFooterStandardTextKey, 0)),
    @CCAccepted = isnull(@CCAccepted, isnull(CCAccepted, 0)),
    @CCAccountKey = isnull(@CCAccountKey, isnull(CCAccountKey, 0)),
    @EmailCCToAddress = isnull(@EmailCCToAddress, EmailCCToAddress),
    @VCardAccepted = isnull(@VCardAccepted, isnull(VCardAccepted, 0)),
    @OnePaymentPerVoucher = isnull(@OnePaymentPerVoucher, isnull(OnePaymentPerVoucher, 0)),
    @CCPayeeName = isnull(@CCPayeeName, CCPayeeName),
    -- Banking/wire fields: always the current row''s value -- never caller-writable on this tool.
    @BankAccountNumber = BankAccountNumber,
    @BankRoutingNumber = BankRoutingNumber,
    @BankAccountName = BankAccountName,
    @BankAccountTypeKey = BankAccountTypeKey,
    @PAINEnabled = isnull(PAINEnabled, 0),
    @BIC = BIC,
    @IBAN = IBAN,
    @CountryCode = CountryCode,
    @ACHEnabled = isnull(ACHEnabled, 0),
    @ABAEnabled = isnull(ABAEnabled, 0),
    @EmailACHToAddress = EmailACHToAddress
  from tCompany (nolock)
  where CompanyKey = @CompanyKey

  -- Address merge: only when the caller is touching the address (AddressName supplied).
  -- NOTE: sptCompanyUpdateVendor always INSERTS a new tAddress row when @AddressName is supplied
  -- (unlike sptCompanyUpdateClient, it has no "update existing address in place" branch) -- this
  -- matches the UI''s own Vendor.vb behavior exactly. To avoid blanking fields within that new
  -- row, omitted fields are still filled in from the vendor''s current default address.
  if @AddressName is not null
  begin
    declare @CurrentAddressKey int
    select @CurrentAddressKey = isnull(DefaultAddressKey, 0) from tCompany (nolock) where CompanyKey = @CompanyKey

    if @CurrentAddressKey > 0
    begin
      select
        @Address1 = isnull(@Address1, Address1),
        @Address2 = isnull(@Address2, Address2),
        @Address3 = isnull(@Address3, Address3),
        @City = isnull(@City, City),
        @State = isnull(@State, State),
        @PostalCode = isnull(@PostalCode, PostalCode),
        @Country = isnull(@Country, Country)
      from tAddress (nolock)
      where AddressKey = @CurrentAddressKey
    end
  end

  begin try

    exec @CompanyKey = sptCompanyUpdateVendor
      @CompanyKey = @CompanyKey,
      @OwnerCompanyKey = @OwnerCompanyKey,
      @CompanyName = @CompanyName,
      @VendorID = @VendorID,
      @Vendor = @Vendor,
      @OverheadVendor = @OverheadVendor,
      @OnHold = @OnHold,
      @VendorDownloaded = @VendorDownloaded,
      @WebSite = @WebSite,
      @Phone = @Phone,
      @Fax = @Fax,
      @Active = @Active,
      @DefaultExpenseAccountKey = @DefaultExpenseAccountKey,
      @DefaultAPAccountKey = @DefaultAPAccountKey,
      @VendorSalesTaxKey = @VendorSalesTaxKey,
      @VendorSalesTax2Key = @VendorSalesTax2Key,
      @DefaultAPApproverKey = @DefaultAPApproverKey,
      @DefaultMemo = @DefaultMemo,
      @TermsDays = @TermsDays,
      @TermsPercent = @TermsPercent,
      @TermsNet = @TermsNet,
      @Type1099 = @Type1099,
      @Box1099 = @Box1099,
      @FATCAFilingRequirement = @FATCAFilingRequirement,
      @DBA = @DBA,
      @UseDBAForPayment = @UseDBAForPayment,
      @EINNumber = @EINNumber,
      @CCAccepted = @CCAccepted,
      @CCAccountKey = @CCAccountKey,
      @EmailCCToAddress = @EmailCCToAddress,
      @EmailACHToAddress = @EmailACHToAddress,
      @VCardAccepted = @VCardAccepted,
      @OnePaymentPerVoucher = @OnePaymentPerVoucher,
      @CCPayeeName = @CCPayeeName,
      @BankAccountNumber = @BankAccountNumber,
      @BankRoutingNumber = @BankRoutingNumber,
      @BankAccountName = @BankAccountName,
      @BankAccountTypeKey = @BankAccountTypeKey,
      @PaymentAddressKey = @PaymentAddressKey,
      @Address1 = @Address1,
      @Address2 = @Address2,
      @Address3 = @Address3,
      @City = @City,
      @State = @State,
      @PostalCode = @PostalCode,
      @Country = @Country,
      @AddressName = @AddressName,
      @PAINEnabled = @PAINEnabled,
      @BIC = @BIC,
      @IBAN = @IBAN,
      @CountryCode = @CountryCode,
      @CurrencyID = @CurrencyID,
      @ACHEnabled = @ACHEnabled,
      @POHeaderStandardTextKey = @POHeaderStandardTextKey,
      @POFooterStandardTextKey = @POFooterStandardTextKey,
      @ContactOwnerKey = @ContactOwnerKey,
      @ABAEnabled = @ABAEnabled,
      @UserKey = @UserKey,
      @ActiveVendor = @ActiveVendor,
      @UseDBAForPayment1099 = @UseDBAForPayment1099,
      @AvalaraTaxCodeKey = @AvalaraTaxCodeKey,
      @UseAltAddress = @UseAltAddress

    if @CompanyKey = -500
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''DUPLICATE'', ''This Vendor ID has already been assigned to another Vendor.'', ''vendorID'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -102
    end
    if isnull(@CompanyKey, 0) <= 0
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', ''Vendor update failed (code '' + CAST(isnull(@CompanyKey,0) as varchar(20)) + '').'', ''general'')
      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
      return -100
    end

    -- Make sure the editing user isn''t locked out of this record if RestrictToGLCompany is on
    exec sptGLCompanyAccessInsertDefaults
        @Entity              = ''tCompany'',
        @EntityKey           = @CompanyKey,
        @UserKey             = @UserKey,
        @CompanyKey          = @OwnerCompanyKey,
        @CheckForExistingRow = 1

    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    select c.CompanyKey     as companyKey,
           c.CompanyName    as companyName,
           c.VendorID       as vendorId,
           c.Vendor         as vendor,
           c.ActiveVendor   as activeVendor
    from tCompany c (nolock)
    where c.CompanyKey = @CompanyKey

    drop table #errors

    RETURN @CompanyKey

  end try
  begin catch

    declare @ErrMsg nvarchar(4000) = ERROR_MESSAGE()
    declare @ErrSeverity int = ERROR_SEVERITY()

    if object_id(''tempdb..#errors'') is not null
    begin
      insert into #errors (errorType, errorCode, errorMessage, fieldName)
      values (''error'', ''EXCEPTION'', @ErrMsg, ''general'')

      select errorType, errorCode, errorMessage, fieldName from #errors order by errorType desc, fieldName
      drop table #errors
    end

    RAISERROR(@ErrMsg, @ErrSeverity, 1)
    return -100

  end catch

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceVoid]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceVoid]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptInvoiceVoid]
(
	@CompanyKey int,
	@InvoiceKey int,
	@VoidDate smalldatetime,
	@CreatedByKey int
)

AS --Encrypt

	SET NOCOUNT ON 

  /*
  || When     Who Rel      What
  || 09/23/13 GHL 10.572   (181928) Creation for voiding of invoices 
  || 09/30/13 GHL 10.572   Applying voided invoice to original as credit 
  || 10/16/13 GHL 10.573   Added new PO and VI fields (GrossAmount, Commission)
  || 11/01/13 GHL 10.573   (194937) Limiting now InvoiceNumber to 35 (vs 50)
  ||                       because on Server at Concentric it raises an error
  ||                       Also had to rtrim
  || 01/03/14 WDF 10.576   (188500) Added CreatedByKey, DateCreated to Insert tInvoice
  || 10/15/14 GHL 10.585   (233113) Updating now TransferComment because users are surprised to see negative time entries
  || 10/29/14 GAR 10.585   (234245) Changed the approver for a void to be the person that voided the invoice instead of the
  ||					   user that created the invoice.
  || 12/02/14 GHL 10.586   (235493) Do not void if there are some prebilled orders
  || 03/10/15 GHL 10.590   Added update of tTime.DepartmentKey for Abelson
  || 05/21/15 GHL 10.592   Added update of tTime.TitleKey for Abelson
  || 10/06/17 GHL 10.620   (366684) When copying expense receipts, set VoucherDetailKey = null because this is a 1 to 1 relationship
  || 08/03/20 GHL 20.090   (451878) Added fields for GL companies different currency
  || 02/02/22 GHL 22.020   (586608) Do not copy the voucher, because some users are surprised by the number of negative time entries
  || 07/26/22 GHL 22.080   (604153) Copy the Overtime on labor
  || 04/10/25 QMD 25.05.18 (697040) Adding CompanyKey to tTime
  || 07/29/26 MFT 26.07.29 (732430) Clear the voided invoice reference (InvoiceKey) from tBillingSchedule on completion of the void
  */

/* Issue= 181928

Please review the specs I''ve written before I send this to the client:

Hi Vickie and Hector,

Per our conversation about adding the void client invoice feature, below are the specifications and pricing for the customization request:

1. Add a new Void function on client invoices.  This will create duplicate transactions but negative to create the credit memo defaulting 
with today''s date as the invoice date and posting date.  

This will also create new duplicate transactions that can be billed on the project so that it can be later dispositioned (ie. billed, 
written-off, transferred, etc.)

There will be locking rules to prevent duplicate positive entries like not allowing the original invoice to be deleted if the void is present. 
 Any mistaken voids would require the user to first deleted the void before they can delete the original invoice.

Voids cannot be done for client invoices that contain prebilled orders since this presents accrual issues for prebilled orders.

$2,200.

Please reply with your approval and PO Number so we can schedule the development as soon as possible.  We will bill you 50% of 
the price to start the development and the remaining upon delivery of the customization.  Typically, the ETA is around 8 to 10 weeks but 
our engineers can provide a more definite timeframe once we receive your approval.

Please let me know if you have any questions.
Mike


9/23/13 meeting with Greg
On tVoucherDetails, PrebillAmount = 0
On tPurchaseOrderDetails, AccruedCost > 0 

9/30/13 talk with Greg
insert tInvoiceCredit rec
*/

Declare @kErrClosedDate	int			select @kErrClosedDate = -1
Declare @kErrInvoiceNumber	int		select @kErrInvoiceNumber = -2
Declare @kErrSplitBilling int		select @kErrSplitBilling = -3
Declare @kErrMediaSynch int			select @kErrMediaSynch = -4
Declare @kErrNoInvoiceNumber int	select @kErrNoInvoiceNumber = -5
Declare @kErrVoided int				select @kErrVoided = -6
Declare @kErrPO int					select @kErrPO = -7

Declare @kErrUnexpected int			select @kErrUnexpected = -99

Declare @VoidInvoiceKey int
Declare @CurKey int
Declare @GLClosedDate smalldatetime
Declare @UseMultiCompanyGLCloseDate tinyint
Declare @RetVal int
Declare @Error int
Declare @InvoiceNumber varchar(35)
Declare @OrigInvoiceNumber varchar(35)
Declare @ClientKey int
Declare @GLCompanyKey int
Declare @ParentInvoice int
Declare @ParentInvoiceKey int

Declare @InvoiceLineKey int
Declare @VoidInvoiceLineKey int
Declare @ParentLineKey int
Declare @VoidParentLineKey int
Declare @VoucherDetailKey int
Declare @VoidVoucherDetailKey int
Declare @NewVoucherDetailKey int 
Declare @InvoiceTotalAmount money

Select @GLClosedDate = GLClosedDate
	,@UseMultiCompanyGLCloseDate = ISNULL(MultiCompanyClosingDate, 0)
From
	tPreference (nolock)
Where
	CompanyKey = @CompanyKey

Select @OrigInvoiceNumber = InvoiceNumber
	  ,@InvoiceNumber = InvoiceNumber
      ,@ClientKey = ClientKey
      ,@GLCompanyKey = GLCompanyKey
	  ,@ParentInvoice = isnull(ParentInvoice, 0)
	  ,@ParentInvoiceKey = isnull(ParentInvoiceKey, 0) 
	  ,@InvoiceTotalAmount = isnull(InvoiceTotalAmount, 0)
	  ,@VoidInvoiceKey = VoidInvoiceKey
from  tInvoice (nolock) 
Where InvoiceKey = @InvoiceKey

if isnull(@VoidInvoiceKey, 0) >0
	return @kErrVoided

if @ParentInvoice >0 Or @ParentInvoiceKey >0
	return @kErrSplitBilling

if isnull(@InvoiceNumber, '''') = ''''
	return @kErrNoInvoiceNumber

-- check GL closed date
if @UseMultiCompanyGLCloseDate = 1 And ISNULL(@GLCompanyKey, 0) > 0
	BEGIN
		Select 
			@GLClosedDate = GLCloseDate
		From 
			tGLCompany (nolock)
		Where
			GLCompanyKey = @GLCompanyKey			
	END

if @GLClosedDate > @VoidDate
	return @kErrClosedDate

-- See if there is a invoice with this number
Select @InvoiceNumber = RTRIM(@InvoiceNumber) + '' VOID''
if exists(Select 1 from tInvoice (nolock) Where InvoiceNumber = @InvoiceNumber 
	and CompanyKey = @CompanyKey)
	return @kErrInvoiceNumber

if exists (select 1 from 
			tInvoiceLine il (nolock)
				inner join tPurchaseOrderDetail pod (nolock) on il.InvoiceLineKey = pod.InvoiceLineKey 
			where il.InvoiceKey = @InvoiceKey
			)
			return @kErrPO

-- check if media is linked 	
if exists (select 1 from 
			tInvoiceLine il (nolock)
				inner join tVoucherDetail vd (nolock) on il.InvoiceLineKey = vd.InvoiceLineKey 
				inner join tVoucher v (nolock) on vd.VoucherKey = v.VoucherKey 
			where il.InvoiceKey = @InvoiceKey
			and   (vd.LinkID is not null Or v.LinkID is not null) 
			)
			return @kErrMediaSynch

create table #lines (MyKey int identity(1,1) not null
		, InvoiceLineKey int null
		, VoidInvoiceLineKey int null
		, ParentLineKey int null
		) 

-- insert the lines by Invoice Order
insert #lines (InvoiceLineKey, ParentLineKey)
select InvoiceLineKey, ParentLineKey
from   tInvoiceLine (nolock)
where  InvoiceKey = @InvoiceKey 
order  by InvoiceOrder

-- we will need info on time and voucher details 
create table #transactions (InvoiceLineKey int null
	, VoidInvoiceLineKey int null
	, Entity varchar(20) null
	, EntityKey int null
	, EntityGuid uniqueidentifier null
	, VoidEntityGuid uniqueidentifier null -- this is for the Void invoice
	, NewEntityGuid uniqueidentifier null -- this is for the new transactions
	)

insert #transactions (InvoiceLineKey, Entity, EntityGuid)
select  il.InvoiceLineKey, ''tTime'', t.TimeKey
from    tInvoiceLine il (nolock)
	inner join tTime t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey 
where   il.InvoiceKey = @InvoiceKey

insert #transactions (InvoiceLineKey, Entity, EntityKey)
select  il.InvoiceLineKey, ''tVoucherDetail'', vd.VoucherDetailKey
from    tInvoiceLine il (nolock)
	inner join tVoucherDetail vd (nolock) on il.InvoiceLineKey = vd.InvoiceLineKey 
where   il.InvoiceKey = @InvoiceKey

	-- create UIDs
	update #transactions
	set    VoidEntityGuid = newid()
	where  Entity = ''tTime''	 

	update #transactions
	set    NewEntityGuid = newid()
	where  Entity = ''tTime''	

begin transaction

/*
Create the Invoice header
*/

INSERT tInvoice
           (CompanyKey
           ,ClientKey
           ,LinkID
           ,ParentInvoice
           ,ParentInvoiceKey
           ,PercentageSplit
           ,ContactName
           ,BillingContactKey
           ,AdvanceBill
           ,InvoiceNumber
           ,InvoiceDate
           ,DueDate
           ,PostingDate
           ,RecurringParentKey
           ,TermsKey
           ,ARAccountKey
           ,ClassKey
           ,ProjectKey
           ,RetainerAmount
           ,WriteoffAmount
           ,DiscountAmount
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,TotalNonTaxAmount
           ,InvoiceTotalAmount
           ,AmountReceived
           ,HeaderComment
           ,SalesTaxKey
           ,SalesTax2Key
           ,InvoiceStatus
           ,ApprovedDate
           ,ApprovedByKey
           ,ApprovalComments
           ,Posted
           ,Downloaded
           ,Printed
           ,InvoiceTemplateKey
           ,UserDefined1
           ,UserDefined2
           ,UserDefined3
           ,UserDefined4
           ,UserDefined5
           ,UserDefined6
           ,UserDefined7
           ,UserDefined8
           ,UserDefined9
           ,UserDefined10
           ,EstimateKey
           ,RetainerKey
           ,PrimaryContactKey
           ,AddressKey
           ,Emailed
           ,GLCompanyKey
           ,OfficeKey
           ,OpeningTransaction
           ,LayoutKey
           ,CampaignKey
           ,MediaEstimateKey
           ,AlternatePayerKey
           ,BillingGroupKey
           ,CurrencyID
           ,ExchangeRate
		   ,GLCCurrencyID
           ,GLCExchangeRate
           ,VoidInvoiceKey
           ,CreatedByKey
		   ,DateCreated)
     select
           CompanyKey
           ,ClientKey
           ,LinkID
           ,ParentInvoice
           ,ParentInvoiceKey
           ,PercentageSplit
           ,ContactName
           ,BillingContactKey
           ,AdvanceBill
           ,@InvoiceNumber -- VOID
           ,@VoidDate --InvoiceDate
           ,DueDate
           ,@VoidDate--PostingDate
           ,RecurringParentKey
           ,TermsKey
           ,ARAccountKey
           ,ClassKey
           ,ProjectKey
           ,0 --RetainerAmount
           ,0 --WriteoffAmount
           ,-1 * DiscountAmount
           ,-1 * SalesTaxAmount
           ,-1 * SalesTax1Amount
           ,-1 * SalesTax2Amount
           ,-1 * TotalNonTaxAmount
           ,-1 * InvoiceTotalAmount
           ,0 --AmountReceived
           ,HeaderComment
           ,SalesTaxKey
           ,SalesTax2Key
           ,1 --InvoiceStatus
           ,ApprovedDate
           ,@CreatedByKey --ApprovedByKey (234245)
           ,ApprovalComments
           ,0 --Posted
           ,0 --Downloaded
           ,0 --Printed
           ,InvoiceTemplateKey
           ,UserDefined1
           ,UserDefined2
           ,UserDefined3
           ,UserDefined4
           ,UserDefined5
           ,UserDefined6
           ,UserDefined7
           ,UserDefined8
           ,UserDefined9
           ,UserDefined10
           ,EstimateKey
           ,RetainerKey
           ,PrimaryContactKey
           ,AddressKey
           ,0 --Emailed
           ,GLCompanyKey
           ,OfficeKey
           ,OpeningTransaction
           ,LayoutKey
           ,CampaignKey
           ,MediaEstimateKey
           ,AlternatePayerKey
           ,BillingGroupKey
           ,CurrencyID
           ,ExchangeRate
		   ,GLCCurrencyID
           ,GLCExchangeRate
           ,null --VoidInvoiceKey
		   ,@CreatedByKey
		   ,GETDATE()

	from tInvoice (nolock)
	where InvoiceKey = @InvoiceKey

	select @Error = @@ERROR, @VoidInvoiceKey = @@IDENTITY

	if @Error > 0 
	begin
		rollback transaction 
		return @kErrUnexpected
	end

	-- Set the void keys to signify that this transaction has been voided and create a link
	Update tInvoice Set VoidInvoiceKey = @InvoiceKey Where InvoiceKey in (@InvoiceKey, @VoidInvoiceKey)
	if @@ERROR > 0 
	begin
		rollback transaction 
		return @kErrUnexpected
	end

/*
Create the Invoice lines
They should already be organized by InvoiceOrder, i.e. parent lines before child lines
*/

Select @CurKey = -1
while (1=1)
begin
	select @CurKey = min(MyKey)
	from   #lines
	where  MyKey > @CurKey

	if @CurKey is null
		break

	select @InvoiceLineKey = InvoiceLineKey
	      ,@ParentLineKey = ParentLineKey
	from  #lines
	where MyKey = @CurKey

	-- if there is a parent it should already have been created first
	if isnull(@ParentLineKey, 0) > 0
		select @VoidParentLineKey = VoidInvoiceLineKey
		from   #lines
		where  InvoiceLineKey = @ParentLineKey   
	else
		select @VoidParentLineKey = 0

	select @VoidParentLineKey = isnull(@VoidParentLineKey, 0)

	INSERT tInvoiceLine
           (InvoiceKey
           ,LinkID
           ,ProjectKey
           ,TaskKey
           ,LineType
           ,ParentLineKey
           ,LineSubject
           ,LineDescription
           ,BillFrom
           ,BilledTimeAmount
           ,BilledExpenseAmount
           ,Quantity
           ,UnitAmount
           ,TotalAmount
           ,PostSalesUsingDetail
           ,SalesAccountKey
           ,ClassKey
           ,DisplayOrder
           ,Taxable
           ,Taxable2
           ,WorkTypeKey
           ,InvoiceOrder
           ,LineLevel
           ,Entity
           ,EntityKey
           ,RetainerKey
           ,EstimateKey
           ,OfficeKey
           ,DepartmentKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,DisplayOption
           ,CampaignSegmentKey
           ,TargetGLCompanyKey
		   ,GLCExchangeRate
		   )
     select
           @VoidInvoiceKey
           ,LinkID
           ,ProjectKey
           ,TaskKey
           ,LineType
           ,@VoidParentLineKey
           ,LineSubject
           ,LineDescription
           ,BillFrom
           ,-1 * BilledTimeAmount
           ,-1 * BilledExpenseAmount
           ,Quantity
           ,-1 * UnitAmount
           ,-1 * TotalAmount
           ,PostSalesUsingDetail
           ,SalesAccountKey
           ,ClassKey
           ,DisplayOrder
           ,Taxable
           ,Taxable2
           ,WorkTypeKey
           ,InvoiceOrder
           ,LineLevel
           ,Entity
           ,EntityKey
           ,RetainerKey
           ,EstimateKey
           ,OfficeKey
           ,DepartmentKey
           ,-1 * SalesTaxAmount
           ,-1 * SalesTax1Amount
           ,-1 * SalesTax2Amount
           ,DisplayOption
           ,CampaignSegmentKey
           ,TargetGLCompanyKey
		   ,GLCExchangeRate
		from tInvoiceLine (nolock)
		where InvoiceLineKey = @InvoiceLineKey

		select @Error = @@ERROR, @VoidInvoiceLineKey = @@IDENTITY

		if @Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

		update #lines
		set    VoidInvoiceLineKey = @VoidInvoiceLineKey
		where  InvoiceLineKey = @InvoiceLineKey

end

	-- not absolutely necessary, but this way we only use 1 table
	update #transactions
	set    VoidInvoiceLineKey = l.VoidInvoiceLineKey
	from   #lines l
	where  #transactions.InvoiceLineKey = l.InvoiceLineKey	 


/*
Taxes
*/

insert tInvoiceTax (InvoiceKey, InvoiceLineKey, SalesTaxKey, SalesTaxAmount, Type)
select @VoidInvoiceKey, l.VoidInvoiceLineKey, it.SalesTaxKey, -1 * it.SalesTaxAmount, it.Type
from   tInvoiceTax it (nolock)
inner join #lines l on it.InvoiceLineKey = l.InvoiceLineKey
where  it.InvoiceKey = @InvoiceKey

if @@Error > 0 
begin
	rollback transaction 
	return @kErrUnexpected
end

insert tInvoiceLineTax (InvoiceLineKey, SalesTaxKey, SalesTaxAmount)
select l.VoidInvoiceLineKey, ilt.SalesTaxKey, -1 * ilt.SalesTaxAmount
from   tInvoiceLineTax ilt (nolock)
inner join #lines l on ilt.InvoiceLineKey = l.InvoiceLineKey

if @@Error > 0 
begin
	rollback transaction 
	return @kErrUnexpected
end

-- Enter credit app
insert tInvoiceCredit (InvoiceKey, CreditInvoiceKey, Description, Amount)
values (@InvoiceKey, @VoidInvoiceKey, ''Credit applied after voiding invoice'', @InvoiceTotalAmount)

if @@Error > 0 
begin
	rollback transaction 
	return @kErrUnexpected
end

/*
Now insert transactions, time entry last to reduce the duration of the SQL tran on tTime
*/

	-- Misc Cost

	insert tMiscCost (ProjectKey
           ,TaskKey
           ,ExpenseDate
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,ClassKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,UnitRate
           ,Markup
           ,Billable
           ,BillableCost
           ,AmountBilled
           ,EnteredByKey
           ,DateEntered
           ,InvoiceLineKey
           ,WriteOff
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DateBilled
           ,JournalEntryKey
           ,OnHold
           ,BilledComment
           ,DepartmentKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,OldWIPAmount
           ,BilledItem
           ,ExchangeRate
           ,CurrencyID)
     select ProjectKey
           ,TaskKey
           ,ExpenseDate
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,ClassKey
           ,-1 * Quantity -- reverse
           ,UnitCost 
           ,UnitDescription
           ,-1 * TotalCost -- reverse
           ,UnitRate 
           ,Markup
           ,Billable
           ,-1 * BillableCost -- reverse
           ,-1 * AmountBilled -- reverse
           ,EnteredByKey
           ,DateEntered
           ,l.VoidInvoiceLineKey -- New il
           ,WriteOff
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''')  --TransferComment
           ,WriteOffReasonKey
           ,@VoidDate -- DateBilled
           ,JournalEntryKey
           ,OnHold
           ,BilledComment
           ,DepartmentKey
           ,null -- TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,0 --OldWIPAmount
           ,BilledItem
           ,ExchangeRate
           ,CurrencyID
	from tMiscCost mc (nolock)
		inner join #lines l (nolock) on mc.InvoiceLineKey = l.InvoiceLineKey

	if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

	insert tMiscCost (ProjectKey
           ,TaskKey
           ,ExpenseDate
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,ClassKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,UnitRate
           ,Markup
           ,Billable
           ,BillableCost
           ,AmountBilled
           ,EnteredByKey
           ,DateEntered
           ,InvoiceLineKey
           ,WriteOff
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DateBilled
           ,JournalEntryKey
           ,OnHold
           ,BilledComment
           ,DepartmentKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,OldWIPAmount
           ,BilledItem
           ,ExchangeRate
           ,CurrencyID)
     select ProjectKey
           ,TaskKey
           ,ExpenseDate
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,ClassKey
           ,Quantity
           ,UnitCost 
           ,UnitDescription
           ,TotalCost 
           ,UnitRate 
           ,Markup
           ,Billable
           ,BillableCost
           ,0 --AmountBilled -- unbilled
           ,EnteredByKey
           ,DateEntered
           ,null -- InvoiceLineKey -- unbilled
           ,WriteOff
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,null -- DateBilled
           ,JournalEntryKey
           ,OnHold
           ,null --BilledComment
           ,DepartmentKey
           ,null -- TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,0 --OldWIPAmount
           ,BilledItem
           ,ExchangeRate
           ,CurrencyID
	from tMiscCost mc (nolock)
		inner join #lines l (nolock) on mc.InvoiceLineKey = l.InvoiceLineKey

	if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

	-- Expense receipts

	INSERT tExpenseReceipt
           (ExpenseEnvelopeKey
           ,UserKey
           ,ExpenseDate
           ,ExpenseType
           ,ProjectKey
           ,TaskKey
           ,PaperReceipt
           ,ActualQty
           ,ActualUnitCost
           ,ActualCost
           ,Billable
           ,Markup
           ,BillableCost
           ,Description
           ,Comments
           ,AmountBilled
           ,InvoiceLineKey
           ,WriteOff
           ,Downloaded
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DateBilled
           ,OnHold
           ,BilledComment
           ,UnitRate
           ,VoucherDetailKey
           ,ItemKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,Taxable
           ,Taxable2
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost)
     select ExpenseEnvelopeKey
           ,UserKey
           ,ExpenseDate
           ,ExpenseType
           ,ProjectKey
           ,TaskKey
           ,PaperReceipt
           ,-1 * ActualQty
           ,ActualUnitCost 
           ,-1 * ActualCost -- reverse
           ,Billable
           ,Markup
           ,-1 * BillableCost -- reverse
           ,Description
           ,Comments
           ,-1 * AmountBilled
           ,l.VoidInvoiceLineKey -- new line
           ,WriteOff
           ,Downloaded
           ,0 --WIPPostingInKey
           ,0--WIPPostingOutKey
           ,0--WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,@VoidDate --DateBilled
           ,OnHold
           ,BilledComment
           ,UnitRate 
           ,null --- VoucherDetailKey
           ,ItemKey
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,Taxable
           ,Taxable2
           ,-1 * SalesTaxAmount
           ,-1 * SalesTax1Amount
           ,-1 * SalesTax2Amount
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,-1 * PTotalCost
		from tExpenseReceipt er (nolock)
		inner join #lines l (nolock) on er.InvoiceLineKey = l.InvoiceLineKey

		if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

		INSERT tExpenseReceipt
           (ExpenseEnvelopeKey
           ,UserKey
           ,ExpenseDate
           ,ExpenseType
           ,ProjectKey
           ,TaskKey
           ,PaperReceipt
           ,ActualQty
           ,ActualUnitCost
           ,ActualCost
           ,Billable
           ,Markup
           ,BillableCost
           ,Description
           ,Comments
           ,AmountBilled
           ,InvoiceLineKey
           ,WriteOff
           ,Downloaded
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DateBilled
           ,OnHold
           ,BilledComment
           ,UnitRate
           ,VoucherDetailKey
           ,ItemKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,Taxable
           ,Taxable2
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost)
     select ExpenseEnvelopeKey
           ,UserKey
           ,ExpenseDate
           ,ExpenseType
           ,ProjectKey
           ,TaskKey
           ,PaperReceipt
           ,ActualQty
           ,ActualUnitCost 
           ,ActualCost
           ,Billable
           ,Markup
           ,BillableCost
           ,Description
           ,Comments
           ,0 --AmountBilled
           ,null --InvoiceLineKey
           ,WriteOff
           ,0 -- Downloaded
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,null --DateBilled
           ,OnHold
           ,null -- BilledComment
           ,UnitRate
           ,null -- VoucherDetailKey
           ,ItemKey
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,Taxable
           ,Taxable2
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
		from tExpenseReceipt er (nolock)
		inner join #lines l (nolock) on er.InvoiceLineKey = l.InvoiceLineKey

		if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

/*
POs
*/

/* No orders now
insert tPurchaseOrderDetail
           (PurchaseOrderKey
           ,LineNumber
           ,LinkID
           ,ProjectKey
           ,TaskKey
           ,ClassKey
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,Billable
           ,Markup
           ,BillableCost
           ,AppliedCost
           ,MakeGoodKey
           ,CustomFieldKey
           ,QuoteReplyDetailKey
           ,InvoiceLineKey
           ,AmountBilled
           ,AccruedCost
           ,DateBilled
           ,Closed
           ,DetailOrderDate
           ,DetailOrderEndDate
           ,UserDate1
           ,UserDate2
           ,UserDate3
           ,UserDate4
           ,UserDate5
           ,UserDate6
           ,OrderDays
           ,OrderTime
           ,OrderLength
           ,OnHold
           ,Taxable
           ,Taxable2
           ,BilledComment
           ,TransferComment
           ,AdjustmentNumber
           ,MediaRevisionReasonKey
           ,UnitRate
           ,AutoAdjustment
           ,DateClosed
           ,OfficeKey
           ,DepartmentKey
           ,AccruedExpenseInAccountKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,BilledItem
           ,CostToClient
           ,LineType
           ,Columns
           ,Inches
           ,Commission
           ,MediaPremiumKey
           ,PremiumAmountType
           ,PremiumPct
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
           ,PAppliedCost
           ,Quantity1
           ,Quantity2
           ,GrossAmount

		   ,OldDetailOrderDate
		   ,OldShortDescription
		   ,OldMediaPrintSpaceKey
		   ,OldMediaPrintPositionKey
		   ,OldCompanyMediaPrintContractKey
		   ,OldMediaPrintSpaceID
		   ,CommissionablePremium
		   )
     select
           PurchaseOrderKey
           ,LineNumber
           ,LinkID
           ,ProjectKey
           ,TaskKey
           ,ClassKey
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,case when Quantity = 0 then -1 else -1 * Quantity end
           ,UnitCost
           ,UnitDescription
           ,-1 * TotalCost
           ,Billable
           ,Markup
           ,-1 * BillableCost
           ,0 -- AppliedCost 
           ,MakeGoodKey
           ,0 --CustomFieldKey -- necessary to recreate?
           ,null -- QuoteReplyDetailKey
           ,l.VoidInvoiceLineKey
           ,-1 * AmountBilled
           ,-1 * AccruedCost
           ,@VoidDate --DateBilled
           ,Closed
           ,DetailOrderDate
           ,DetailOrderEndDate
           ,UserDate1
           ,UserDate2
           ,UserDate3
           ,UserDate4
           ,UserDate5
           ,UserDate6
           ,OrderDays
           ,OrderTime
           ,OrderLength
           ,OnHold
           ,Taxable
           ,Taxable2
           ,BilledComment
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,AdjustmentNumber
           ,MediaRevisionReasonKey
           ,UnitRate
           ,AutoAdjustment
           ,DateClosed
           ,OfficeKey
           ,DepartmentKey
           ,AccruedExpenseInAccountKey
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,-1 * SalesTaxAmount
           ,-1 * SalesTax1Amount
           ,-1 * SalesTax2Amount
           ,BilledItem
           ,CostToClient
           ,LineType
           ,Columns
           ,Inches
           ,Commission
           ,MediaPremiumKey
           ,PremiumAmountType
           ,PremiumPct
           ,PCurrencyID
           ,PExchangeRate
           ,-1 * PTotalCost
           ,0 --PAppliedCost
           ,-1 * Quantity1
           ,-1 * Quantity2
           ,-1 * GrossAmount
		   ,OldDetailOrderDate
		   ,OldShortDescription
		   ,OldMediaPrintSpaceKey
		   ,OldMediaPrintPositionKey
		   ,OldCompanyMediaPrintContractKey
		   ,OldMediaPrintSpaceID
		   ,CommissionablePremium

	from tPurchaseOrderDetail pod (nolock)
		inner join #lines l (nolock) on pod.InvoiceLineKey = l.InvoiceLineKey

		if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end


	insert tPurchaseOrderDetail
           (PurchaseOrderKey
           ,LineNumber
           ,LinkID
           ,ProjectKey
           ,TaskKey
           ,ClassKey
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,Billable
           ,Markup
           ,BillableCost
           ,AppliedCost
           ,MakeGoodKey
           ,CustomFieldKey
           ,QuoteReplyDetailKey
           ,InvoiceLineKey
           ,AmountBilled
           ,AccruedCost
           ,DateBilled
           ,Closed
           ,DetailOrderDate
           ,DetailOrderEndDate
           ,UserDate1
           ,UserDate2
           ,UserDate3
           ,UserDate4
           ,UserDate5
           ,UserDate6
           ,OrderDays
           ,OrderTime
           ,OrderLength
           ,OnHold
           ,Taxable
           ,Taxable2
           ,BilledComment
           ,TransferComment
           ,AdjustmentNumber
           ,MediaRevisionReasonKey
           ,UnitRate
           ,AutoAdjustment
           ,DateClosed
           ,OfficeKey
           ,DepartmentKey
           ,AccruedExpenseInAccountKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,BilledItem
           ,CostToClient
           ,LineType
           ,Columns
           ,Inches
           ,Commission
           ,MediaPremiumKey
           ,PremiumAmountType
           ,PremiumPct
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
           ,PAppliedCost
           ,Quantity1
           ,Quantity2
           ,GrossAmount
		   ,OldDetailOrderDate
		   ,OldShortDescription
		   ,OldMediaPrintSpaceKey
		   ,OldMediaPrintPositionKey
		   ,OldCompanyMediaPrintContractKey
		   ,OldMediaPrintSpaceID
		   ,CommissionablePremium
		   )
     select
           PurchaseOrderKey
           ,LineNumber
           ,LinkID
           ,ProjectKey
           ,TaskKey
           ,ClassKey
           ,ShortDescription
           ,LongDescription
           ,ItemKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,Billable
           ,Markup
           ,BillableCost
           ,0 --AppliedCost
           ,MakeGoodKey
           ,0 --CustomFieldKey
           ,null --QuoteReplyDetailKey
           ,null --InvoiceLineKey
           ,0 --AmountBilled
           ,null --AccruedCost -- since unbilled, nothing is accrued
           ,null --DateBilled
           ,Closed
           ,DetailOrderDate
           ,DetailOrderEndDate
           ,UserDate1
           ,UserDate2
           ,UserDate3
           ,UserDate4
           ,UserDate5
           ,UserDate6
           ,OrderDays
           ,OrderTime
           ,OrderLength
           ,OnHold
           ,Taxable
           ,Taxable2
           ,null -- BilledComment
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,AdjustmentNumber
           ,MediaRevisionReasonKey
           ,UnitRate
           ,AutoAdjustment
           ,DateClosed
           ,OfficeKey
           ,DepartmentKey
           ,AccruedExpenseInAccountKey
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,BilledItem
           ,CostToClient
           ,LineType
           ,Columns
           ,Inches
           ,Commission
           ,MediaPremiumKey
           ,PremiumAmountType
           ,PremiumPct
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
           ,0 --PAppliedCost
           ,Quantity1
           ,Quantity2
           ,GrossAmount
		   ,OldDetailOrderDate
		   ,OldShortDescription
		   ,OldMediaPrintSpaceKey
		   ,OldMediaPrintPositionKey
		   ,OldCompanyMediaPrintContractKey
		   ,OldMediaPrintSpaceID
		   ,CommissionablePremium
	from tPurchaseOrderDetail pod (nolock)
		inner join #lines l (nolock) on pod.InvoiceLineKey = l.InvoiceLineKey

		if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end
*/

	-- VoucherDetails, do it in a loop because of possible taxes in tVoucherDetailTax

select @VoucherDetailKey = -1
while (1=1)
begin
	select @VoucherDetailKey = min(EntityKey)
	from   #transactions
	where  Entity = ''tVoucherDetail''
	and    EntityKey > @VoucherDetailKey

	if @VoucherDetailKey is null
		break

	select @InvoiceLineKey = InvoiceLineKey
	      ,@VoidInvoiceLineKey = VoidInvoiceLineKey
	from   #transactions
	where  Entity = ''tVoucherDetail''
	and    EntityKey = @VoucherDetailKey

	INSERT tVoucherDetail
           (VoucherKey
           ,LinkID
           ,LineNumber
           ,PurchaseOrderDetailKey
           ,ClientKey
           ,ProjectKey
           ,TaskKey
           ,ShortDescription
           ,ItemKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,Billable
           ,Markup
           ,BillableCost
           ,AmountBilled
           ,InvoiceLineKey
           ,WriteOff
           ,PrebillAmount
           ,ExpenseAccountKey
           ,ClassKey
           ,QuantityBilled
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DatePaidByClient
           ,DateBilled
           ,Taxable
           ,Taxable2
           ,OnHold
           ,FinalForPO
           ,BilledComment
           ,LastVoucher
           ,UnitRate
           ,OfficeKey
           ,DepartmentKey
           ,OldExpenseAccountKey
           ,AccruedExpenseOutAccountKey
           ,SourceDate
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,OldWIPAmount
           ,TargetGLCompanyKey
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
		   ,Commission
		   ,GrossAmount
		   )
     select VoucherKey
           ,LinkID
           ,LineNumber
           ,PurchaseOrderDetailKey
           ,ClientKey
           ,ProjectKey
           ,TaskKey
           ,ShortDescription
           ,ItemKey
           ,-1 * Quantity
           ,UnitCost
           ,UnitDescription
           ,-1 * TotalCost
           ,Billable
           ,Markup
           ,-1 * BillableCost
           ,-1 * AmountBilled
           ,@VoidInvoiceLineKey
           ,WriteOff
           ,0 --PrebillAmount -- important so that we will not unaccrue
           ,ExpenseAccountKey
           ,ClassKey
           ,QuantityBilled
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,null --DatePaidByClient 
           ,@VoidDate -- DateBilled
           ,Taxable
           ,Taxable2
           ,OnHold
           ,FinalForPO
           ,BilledComment
           ,LastVoucher
           ,UnitRate
           ,OfficeKey
           ,DepartmentKey
           ,OldExpenseAccountKey
           ,AccruedExpenseOutAccountKey
           ,SourceDate
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,-1 * SalesTaxAmount
           ,-1 * SalesTax1Amount
           ,-1 * SalesTax2Amount
           ,0 --OldWIPAmount
           ,TargetGLCompanyKey
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,-1 * PTotalCost
		   ,Commission
		   ,-1 * GrossAmount
		from tVoucherDetail vd (nolock)
		where vd.VoucherDetailKey = @VoucherDetailKey

		select @Error = @@ERROR, @VoidVoucherDetailKey = @@IDENTITY

		if @Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end


		INSERT tVoucherDetail
           (VoucherKey
           ,LinkID
           ,LineNumber
           ,PurchaseOrderDetailKey
           ,ClientKey
           ,ProjectKey
           ,TaskKey
           ,ShortDescription
           ,ItemKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,Billable
           ,Markup
           ,BillableCost
           ,AmountBilled
           ,InvoiceLineKey
           ,WriteOff
           ,PrebillAmount
           ,ExpenseAccountKey
           ,ClassKey
           ,QuantityBilled
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DatePaidByClient
           ,DateBilled
           ,Taxable
           ,Taxable2
           ,OnHold
           ,FinalForPO
           ,BilledComment
           ,LastVoucher
           ,UnitRate
           ,OfficeKey
           ,DepartmentKey
           ,OldExpenseAccountKey
           ,AccruedExpenseOutAccountKey
           ,SourceDate
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,OldWIPAmount
           ,TargetGLCompanyKey
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
		   ,Commission
		   ,GrossAmount
		   )
     select VoucherKey
           ,LinkID
           ,LineNumber
           ,PurchaseOrderDetailKey
           ,ClientKey
           ,ProjectKey
           ,TaskKey
           ,ShortDescription
           ,ItemKey
           ,Quantity
           ,UnitCost
           ,UnitDescription
           ,TotalCost
           ,Billable
           ,Markup
           ,BillableCost
           ,0 --AmountBilled
           ,null --InvoiceLineKey
           ,WriteOff
           ,0 --PrebillAmount -- important so that we will not unaccrue
           ,ExpenseAccountKey
           ,ClassKey
           ,0 --QuantityBilled
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,null --DatePaidByClient 
           ,null -- DateBilled
           ,Taxable
           ,Taxable2
           ,OnHold
           ,FinalForPO
           ,null --BilledComment
           ,LastVoucher
           ,UnitRate
           ,OfficeKey
           ,DepartmentKey
           ,OldExpenseAccountKey
           ,AccruedExpenseOutAccountKey
           ,SourceDate
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,SalesTaxAmount
           ,SalesTax1Amount
           ,SalesTax2Amount
           ,0 --OldWIPAmount
           ,TargetGLCompanyKey
           ,BilledItem
           ,PCurrencyID
           ,PExchangeRate
           ,PTotalCost
		   ,Commission
		   ,GrossAmount
		from tVoucherDetail vd (nolock)
		where vd.VoucherDetailKey = @VoucherDetailKey

		select @Error = @@ERROR, @NewVoucherDetailKey = @@IDENTITY

		if @Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

		if exists (select 1 from tVoucherDetailTax (nolock) where VoucherDetailKey = @VoucherDetailKey) 
		begin
			insert tVoucherDetailTax (VoucherDetailKey, SalesTaxKey, SalesTaxAmount)
			select @VoidVoucherDetailKey, SalesTaxKey, -1 * SalesTaxAmount
			from tVoucherDetailTax (nolock) where VoucherDetailKey = @VoucherDetailKey

			if @@Error > 0 
			begin
				rollback transaction 
				return @kErrUnexpected
			end

			insert tVoucherDetailTax (VoucherDetailKey, SalesTaxKey, SalesTaxAmount)
			select @NewVoucherDetailKey, SalesTaxKey, SalesTaxAmount
			from tVoucherDetailTax (nolock) where VoucherDetailKey = @VoucherDetailKey

			if @@Error > 0 
			begin
				rollback transaction 
				return @kErrUnexpected
			end
		end

end


	-- Time entries

	INSERT tTime
           (TimeKey
           ,TimeSheetKey
           ,UserKey
           ,ProjectKey
           ,TaskKey
           ,ServiceKey
           ,RateLevel
           ,WorkDate
           ,StartTime
           ,EndTime
           ,ActualHours
           ,PauseHours
           ,ActualRate
           ,CostRate
           ,BilledService
           ,BilledHours
           ,BilledRate
           ,InvoiceLineKey
           ,WriteOff
           ,Comments
           ,Downloaded
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DateBilled
           ,OnHold
           ,BilledComment
           ,TaskAssignmentKey
           ,DetailTaskKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,Verified
           ,VoucherKey
           ,CurrencyID
           ,ExchangeRate
           ,HCostRate
		   ,DepartmentKey
		   ,TitleKey
		   ,Overtime
		   ,CompanyKey
		   )
     select
           #transactions.VoidEntityGuid
           ,TimeSheetKey
           ,UserKey
           ,ProjectKey
           ,TaskKey
           ,ServiceKey
           ,RateLevel
           ,WorkDate
           ,StartTime
           ,EndTime
           ,-1 * ActualHours
           ,-1 * PauseHours
           ,ActualRate
           ,CostRate
           ,BilledService
           ,-1 * BilledHours
           ,BilledRate
           ,#transactions.VoidInvoiceLineKey
           ,WriteOff
           ,Comments
           ,Downloaded
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,@VoidDate -- DateBilled
           ,OnHold
           ,BilledComment
           ,TaskAssignmentKey
           ,DetailTaskKey
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,Verified
           ,null --VoucherKey
           ,CurrencyID
           ,ExchangeRate
           ,HCostRate
		   ,DepartmentKey
		   ,TitleKey
		   ,Overtime
		   ,@CompanyKey
	from #transactions
		inner join tTime t (nolock) on #transactions.EntityGuid = t.TimeKey

		if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

	INSERT tTime
           (TimeKey
           ,TimeSheetKey
           ,UserKey
           ,ProjectKey
           ,TaskKey
           ,ServiceKey
           ,RateLevel
           ,WorkDate
           ,StartTime
           ,EndTime
           ,ActualHours
           ,PauseHours
           ,ActualRate
           ,CostRate
           ,BilledService
           ,BilledHours
           ,BilledRate
           ,InvoiceLineKey
           ,WriteOff
           ,Comments
           ,Downloaded
           ,WIPPostingInKey
           ,WIPPostingOutKey
           ,WIPAmount
           ,TransferComment
           ,WriteOffReasonKey
           ,DateBilled
           ,OnHold
           ,BilledComment
           ,TaskAssignmentKey
           ,DetailTaskKey
           ,TransferInDate
           ,TransferOutDate
           ,TransferFromKey
           ,TransferToKey
           ,Verified
           ,VoucherKey
           ,CurrencyID
           ,ExchangeRate
           ,HCostRate
		   ,DepartmentKey
		   ,TitleKey
		   ,Overtime
		   ,CompanyKey
		   )
     select
           #transactions.NewEntityGuid
           ,TimeSheetKey
           ,UserKey
           ,ProjectKey
           ,TaskKey
           ,ServiceKey
           ,RateLevel
           ,WorkDate
           ,StartTime
           ,EndTime
           ,ActualHours
           ,PauseHours
           ,ActualRate
           ,CostRate
           ,null --BilledService
           ,null --BilledHours
           ,null --BilledRate
           ,null --InvoiceLineKey
           ,WriteOff
           ,Comments
           ,Downloaded
           ,0 --WIPPostingInKey
           ,0 --WIPPostingOutKey
           ,0 --WIPAmount
           ,''Created when voiding invoice '' + isnull(@OrigInvoiceNumber, '''') --TransferComment
           ,WriteOffReasonKey
           ,null -- DateBilled
           ,OnHold
           ,null --BilledComment
           ,TaskAssignmentKey
           ,DetailTaskKey
           ,null --TransferInDate
           ,null --TransferOutDate
           ,null --TransferFromKey
           ,null --TransferToKey
           ,Verified
           ,null --VoucherKey
           ,CurrencyID
           ,ExchangeRate
           ,HCostRate
		   ,DepartmentKey
		   ,TitleKey
		   ,Overtime
		   ,@CompanyKey
	from #transactions
		inner join tTime t (nolock) on #transactions.EntityGuid = t.TimeKey

	if @@Error > 0 
		begin
			rollback transaction 
			return @kErrUnexpected
		end

	commit transaction 

	-- update invoice summary
	exec sptInvoiceSummary @VoidInvoiceKey

	exec sptInvoiceUpdateAmountPaid @InvoiceKey
	exec sptInvoiceUpdateAmountPaid @VoidInvoiceKey

	-- actuals should be OK, but we need to rollup billed info
	exec sptProjectRollupUpdateEntity ''tInvoice'',  @VoidInvoiceKey

	-- Remove the reference to this (now voided) invoice from the billing schedule
	-- so the scheduled milestone is freed up and can be billed again.
	-- InvoiceKey uniquely identifies the invoice, so no further scoping is needed;
	-- tBillingSchedule has no CompanyKey column.
	update tBillingSchedule
	set    InvoiceKey = null
	      ,BillingKey = null
	      ,BilledComment = null
	where  InvoiceKey = @InvoiceKey

	RETURN @VoidInvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateInlineImage]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateInlineImage]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateInlineImage]  
  
 @AttachmentKey INT,  
 @ContentID  VARCHAR(100),  
 @URL   VARCHAR(250)  
  
AS  
  
/*  
|| When		Who  Rel				What  
|| 11/16/21	QMD  21.12.19.0000		(572622) Created to update the cid when pulling inline images into tActivity from the TM  
||									Should only be executed if the beta is turned on
|| 07/30/25  AMP 25.08.17 (705266)  Reviewed - No trigger change needed at this time 
*/  

DECLARE @ActivityKey INT  
  
SELECT	@ActivityKey = EntityKey   
FROM	tAttachment (NOLOCK)  
WHERE	AssociatedEntity = ''tActivity''  
		AND AttachmentKey = @AttachmentKey  
  
UPDATE	tActivity  
SET		Notes = Replace(Notes, @ContentID, @URL)  
WHERE	ActivityKey = @ActivityKey  
  
  
  
  
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spMassBillingBill]'
GO
IF OBJECT_ID(N'[dbo].[spMassBillingBill]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[spMassBillingBill]
	 @ProjectKey int
	,@Rollup int
	,@UserKey int
	,@ThruDate datetime
	,@BillingStatusKey int
	,@PercentOfActual decimal(15,8)
	,@Time tinyint
	,@Expense tinyint
	,@PO tinyint
	,@POBeginDate datetime
	,@POEndDate datetime
	,@IO tinyint
	,@IOBeginDate datetime
	,@IOEndDate datetime
	,@BC tinyint
	,@BCBeginDate datetime
	,@BCEndDate datetime
	,@InvoiceDate smalldatetime
	,@PostingDate smalldatetime
	,@DefaultClassKey INT = NULL -- This is already validated on screen, no need to validate here
	,@CreateAsApproved INT = 0
	,@OpenOrdersOnly int = 1
	,@UnbilledAmount money = 0
	,@WJAPP int = 0
	,@LaborAtNet int = 0		-- 0 Bill labor at gross, 1 Bill labor at net
	,@AddTopProjectLine int = 0
	,@PostedOnly int = 0        -- Posted vendor Invoices only
	,@InvoiceKey int = NULL OUTPUT

AS --Encrypt

  /*
  || When     Who Rel   What
  || 02/23/07 GHL 8.4   Added Project Rollup section
  || 05/03/07 GHL 8.4.2.1 Added ClassKey for Partners Napier
  || 07/02/07 GHL 8.5   Added logic for GLCompanyKey and OfficeKey and ClassKey  
  || 07/09/07 GHL 8.5   Restricting ER to VoucherDetailKey null 
  || 04/08/08 GHL 8.508 (23712) Added new logic for classes  
  || 04/26/12 GHL 10.555 (141647) Added CreateAsApproved param  
  || 10/11/12 GHL 10.560 Added ProjectKey to #tProcWIPKeys because of execution errors in spProcessWIPWorksheet
  ||                     even if it is not needed
  || 08/28/13 RLB 10.571 (185871) Adding Date filters options for IO, PO and BO
  || 10/04/13 GHL 10.573 Added support for multi currency
  || 09/04/14 GHL 10.584 (228260) Added param @OpenOrdersOnly to support new media screens
  || 09/29/14 GHL 10.584 (230994, 231010) Use DetailOrderDate for BOs rather than DetailOrderEndDate
  || 03/16/16 GHL 10.602 Added parameter @wjapp to handle the case when we bill media separately
  || 07/21/16 GHL 10.606 Added action logging for MN''s ToDo 
  || 04/25/17 GHL 10.615 (338647) Removed project rollup, it is done in VB after billing now
  || 06/05/17 GHL 10.616 (338647) Added check of duplicate invoice before creating
  || 07/24/17 GHL 10.618 (355629) When checking for duplicate invoices, remove check on TotalNonTaxAmount
  || 08/22/17 GHL 10.619 (338747) If no records in tInvoiceSummary, delete the invoice
  || 09/21/17 GHL 10.620 (363995) Added AdvanceBill = 0 to where clause when checking if an invoice exists for the day 
  || 09/28/17 GHL 10.620 (363995) Also use DateCreated rather than InvoiceDate because some client have invoices with same client/project/invoice date
  || 02/20/19 GHL 19.300 (432772) Added LaborAtNet param to recalc the labor at net instead of gross for WONGDOODY
  || 07/15/19 GHL 19.080 (466585) Added param null CostRate when calling sptInvoiceLaborAtNet
  || 05/11/20 GHL 20.060 (515154) Added error -35 when the invoice has already been created for the project
  || 07/23/21 GHL 21.080 (560579) Adedd Posted Vendor Invoices only 
  || 08/03/23 GAR 23.11.19 (DEV2605) Added InvoiceKey as an output parameter to pass back for Avalara tax calcs
  || 07/08/26 AMP 26.07.19 (729259) Populate BilledComment on tBillingSchedule when invoiced from T&M mass billing
  */
	-- Note: Simulate code in WIP page before calling spProcessWIPWorksheet

	create table #tProcWIPKeys (ProjectKey int, EntityType varchar(20) null, EntityKey varchar(50) null, Action int null)
	TRUNCATE TABLE #tProcWIPKeys

	-- list of PO Kinds we use when we query vendor invoices VIs (when @Expense = 1)
	create table #pokind (POKind int null)
	if @WJAPP = 0
	begin
		-- flex code, take all
		insert #pokind (POKind) values (0)
		insert #pokind (POKind) values (1)
		insert #pokind (POKind) values (2)
	end
	else
	begin
		-- wjapp code, there is a setting BillMediaSeparately in wjapp
		-- if BillMediaSeparately = 1, IO and BC = 0, do not take applied VIs
		-- if BillMediaSeparately = 0, IO and BC = 1, take applied VIs  
		insert #pokind (POKind) values (0) -- POs always
		if @IO = 1
			insert #pokind (POKind) values (1)
		if @BC = 1
			insert #pokind (POKind) values (2)
	end

	-- Simulate code in the WIP ASP page
	------------------------------------

	DECLARE @CompanyKey int, @GLCompanyKey int, @OfficeKey int, @ClassKey int
			,@UseGLCompany int, @RequireGLCompany int
			
	-- Get info from project
	SELECT	@CompanyKey		= CompanyKey
			,@GLCompanyKey	= GLCompanyKey 
			,@OfficeKey		= OfficeKey
			,@ClassKey		= ClassKey
	FROM   tProject (NOLOCK)
	WHERE  ProjectKey = @ProjectKey

	SELECT @UseGLCompany = ISNULL(UseGLCompany, 0), @RequireGLCompany = ISNULL(RequireGLCompany, 0)
	FROM tPreference (NOLOCK)
	WHERE CompanyKey = @CompanyKey			
	
	-- try to override with the class on the project 					
	IF ISNULL(@ClassKey, 0) = 0
		SELECT @ClassKey = @DefaultClassKey

	IF @UseGLCompany = 1 And @RequireGLCompany = 1 And ISNULL(@GLCompanyKey, 0) = 0
		RETURN -1000

	IF @POBeginDate is null
		select @POBeginDate = ''1/1/1960''
	IF @IOBeginDate is null
		select @IOBeginDate = ''1/1/1960''
	IF @BCBeginDate is null
		select @BCBeginDate = ''1/1/1960''
	IF @ThruDate IS NULL
		SELECT @ThruDate = ''01/01/2050''
	IF @IOEndDate is null
		select @IOEndDate = ''01/01/2050''
	IF @BCEndDate is null
		select @BCEndDate = ''01/01/2050''
	IF @POEndDate is null
		select @POEndDate = ''01/01/2050''
			
	if @Time = 1
		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Time'', cast(TimeKey as VARCHAR(50)), 1
		FROM    tTime (NOLOCK), tTimeSheet (nolock)
		WHERE   ProjectKey = @ProjectKey
		AND		tTime.TimeSheetKey = tTimeSheet.TimeSheetKey
		AND		tTimeSheet.Status = 4
		AND     InvoiceLineKey IS NULL
		AND     (WriteOff IS NULL OR WriteOff = 0)
		AND		ISNULL(tTime.OnHold, 0) = 0
		AND     WorkDate <= @ThruDate
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
				WHERE b.CompanyKey = @CompanyKey
				AND   bd.EntityGuid = tTime.TimeKey  
				AND   bd.Entity = ''tTime''
				)
		
   
   if @Expense = 1
   BEGIN
		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Expense'', cast(ExpenseReceiptKey as VARCHAR(50)), 1
		FROM    tExpenseReceipt (NOLOCK), tExpenseEnvelope (nolock)
		WHERE   ProjectKey = @ProjectKey
		AND		tExpenseReceipt.ExpenseEnvelopeKey = tExpenseEnvelope.ExpenseEnvelopeKey
		AND		tExpenseEnvelope.Status = 4
		AND     InvoiceLineKey IS NULL
		AND     (WriteOff IS NULL OR WriteOff = 0)
		AND		ISNULL(tExpenseReceipt.OnHold, 0) = 0
		AND     ExpenseDate <= @ThruDate
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
				WHERE b.CompanyKey = @CompanyKey
				AND   b.Status < 5   -- Not Invoiced
				AND   bd.EntityKey = tExpenseReceipt.ExpenseReceiptKey  
				AND   bd.Entity = ''tExpenseReceipt''
				)
		AND		tExpenseReceipt.VoucherDetailKey IS NULL
		
		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''MiscExpense'', cast(MiscCostKey as VARCHAR(50)), 1
		FROM    tMiscCost (NOLOCK)
		WHERE   ProjectKey = @ProjectKey
		AND     InvoiceLineKey IS NULL
		AND     (WriteOff IS NULL OR WriteOff = 0)
		AND		ISNULL(tMiscCost.OnHold, 0) = 0
		AND     ExpenseDate <= @ThruDate
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
				WHERE b.CompanyKey = @CompanyKey
				AND   b.Status < 5   -- Not Invoiced
				AND   bd.EntityKey = tMiscCost.MiscCostKey  
				AND   bd.Entity = ''tMiscCost''
				)

		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Voucher'', cast(vd.VoucherDetailKey as VARCHAR(50)), 1
		FROM    tVoucherDetail vd (NOLOCK)
				,tVoucher       v  (NOLOCK)
		WHERE   vd.ProjectKey = @ProjectKey
		AND     vd.InvoiceLineKey IS NULL
		AND     ISNULL(vd.WriteOff, 0) = 0
		AND      vd.VoucherKey = v.VoucherKey
		AND		v.Status = 4
		AND		ISNULL(vd.OnHold, 0) = 0
		AND    v.InvoiceDate <= @ThruDate		-- Or DueDate ?
		AND    isnull(vd.PurchaseOrderDetailKey, 0) = 0 -- not applied
		AND    (@PostedOnly = 0 OR v.Posted = 1)
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
				WHERE b.CompanyKey = @CompanyKey
				AND   b.Status < 5   -- Not Invoiced
				AND bd.EntityKey = vd.VoucherDetailKey  
				AND   bd.Entity = ''tVoucherDetail''
				)

	INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Voucher'', cast(vd.VoucherDetailKey as VARCHAR(50)), 1
		FROM    tVoucherDetail vd (NOLOCK)
		INNER JOIN tVoucher v  (NOLOCK) on vd.VoucherKey = v.VoucherKey
		INNER JOIN tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
		INNER JOIN tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		WHERE   vd.ProjectKey = @ProjectKey
		AND     vd.InvoiceLineKey IS NULL
		AND     ISNULL(vd.WriteOff, 0) = 0
		AND		v.Status = 4
		AND		ISNULL(vd.OnHold, 0) = 0
		AND     v.InvoiceDate <= @ThruDate		-- Or DueDate ?
		AND     po.POKind in (select POKind from #pokind) -- applied to PO, IO or BC
		AND    (@PostedOnly = 0 OR v.Posted = 1)
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
				WHERE b.CompanyKey = @CompanyKey
				AND   b.Status < 5   -- Not Invoiced
				AND bd.EntityKey = vd.VoucherDetailKey  
				AND   bd.Entity = ''tVoucherDetail''
				)

	END
	
	IF @PO = 1
		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Order'', cast(pod.PurchaseOrderDetailKey as VARCHAR(50)), 1
		FROM    tPurchaseOrderDetail pod (NOLOCK)
				,tPurchaseOrder po  (NOLOCK)
		WHERE   pod.ProjectKey = @ProjectKey
		AND     pod.InvoiceLineKey IS NULL
		AND      pod.PurchaseOrderKey = po.PurchaseOrderKey
		AND		ISNULL(pod.AppliedCost, 0) = 0
		AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
		AND		ISNULL(pod.AmountBilled, 0) = 0
		AND		po.Status = 4
		AND		po.POKind = 0
		AND		ISNULL(pod.OnHold, 0) = 0
		AND		po.PODate >= @POBeginDate
		AND		po.PODate <= @POEndDate
		AND		NOT EXISTS (SELECT 1 
				FROM tBillingDetail bd (NOLOCK)
					INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
				WHERE b.CompanyKey = @CompanyKey
				AND   b.Status < 5   -- Not Invoiced
				AND   bd.EntityKey = pod.PurchaseOrderDetailKey  
				AND   bd.Entity = ''tPurchaseOrderDetail''
				)

	IF @IO = 1
		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Order'', cast(pod.PurchaseOrderDetailKey as VARCHAR(50)), 1
		FROM    tPurchaseOrderDetail pod (NOLOCK)
				,tPurchaseOrder po  (NOLOCK)
		WHERE   pod.ProjectKey = @ProjectKey
		AND     pod.InvoiceLineKey IS NULL
		AND      pod.PurchaseOrderKey = po.PurchaseOrderKey
		AND		ISNULL(pod.AppliedCost, 0) = 0
		AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
		AND		ISNULL(pod.AmountBilled, 0) = 0
		AND		po.Status = 4
		AND		po.POKind = 1
		AND		ISNULL(pod.OnHold, 0) = 0
		AND		pod.DetailOrderDate >= @IOBeginDate
		AND		pod.DetailOrderDate <= @IOEndDate	
		AND		NOT EXISTS (SELECT 1 
			FROM tBillingDetail bd (NOLOCK)
				INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
			WHERE b.CompanyKey = @CompanyKey
			AND   b.Status < 5   -- Not Invoiced
			AND   bd.EntityKey = pod.PurchaseOrderDetailKey  
			AND   bd.Entity = ''tPurchaseOrderDetail''
			)

	IF @BC = 1
		INSERT #tProcWIPKeys (EntityType, EntityKey, Action)
		SELECT  ''Order'', cast(pod.PurchaseOrderDetailKey as VARCHAR(50)), 1
		FROM    tPurchaseOrderDetail pod (NOLOCK)
				,tPurchaseOrder po  (NOLOCK)
		WHERE   pod.ProjectKey = @ProjectKey
		AND     pod.InvoiceLineKey IS NULL
		AND      pod.PurchaseOrderKey = po.PurchaseOrderKey
		AND		ISNULL(pod.AppliedCost, 0) = 0
		AND		(@OpenOrdersOnly = 0 OR pod.Closed = 0)
		AND		ISNULL(pod.AmountBilled, 0) = 0
		AND		po.Status = 4
		AND		po.POKind = 2
		AND		ISNULL(pod.OnHold, 0) = 0
		AND		pod.DetailOrderDate >= @BCBeginDate
		AND		pod.DetailOrderDate <= @BCEndDate	
		AND		NOT EXISTS (SELECT 1 
			FROM tBillingDetail bd (NOLOCK)
				INNER JOIN tBilling b (NOLOCK) ON bd.BillingKey = b.BillingKey
			WHERE b.CompanyKey = @CompanyKey
			AND   b.Status < 5   -- Not Invoiced
			AND   bd.EntityKey = pod.PurchaseOrderDetailKey  
			AND   bd.Entity = ''tPurchaseOrderDetail''
			)
							
	DECLARE @Ret INT
			,@InvoiceBy int
	 				
	SELECT @InvoiceBy = 0 -- Invoice By Project, not by Client
			 
	-- Patch for 338647, check for duplicate invoices before inserting a new one
	declare @ClientKey int
	select @ClientKey = ClientKey from tProject (nolock) where ProjectKey = @ProjectKey
	
	--Issue 363995: Instead of using InvoiceDate for the comparison, use the DateCreated
	declare @DateCreated smalldatetime
	select @DateCreated = convert (varchar(10), getdate(), 101)

	if exists (select 1 from tInvoice (nolock) 
		where ClientKey = @ClientKey 
		and ProjectKey = @ProjectKey
		and convert (varchar(10), DateCreated, 101) = @DateCreated 
		and AdvanceBill = 0
		)
		return -35

	EXEC @Ret = spProcessWIPWorksheet @ProjectKey ,@InvoiceBy, @Rollup, @UserKey, NULL, @PercentOfActual
	, @InvoiceDate, @PostingDate, @DefaultClassKey, @ClassKey, @GLCompanyKey, @OfficeKey, @CreateAsApproved, NULL, NULL
	
	-- If positive, this is an invoice key, not an error	
	-- No need to return an InvoiceKey in mass billing
	 		
	IF @Ret > 0
	BEGIN
		-- we should have some recs in tInvoiceSummary, if not, delete the Invoice, this is for Mass Mutual (338747)
		if @CompanyKey = 135308 and not exists (select 1 from tInvoiceSummary (nolock) where InvoiceKey = @Ret)
		begin
			exec sptInvoiceDelete @Ret
			return -1
		end

		if @AddTopProjectLine = 1
			exec sptInvoiceLineInsertTopLine @Ret

		IF @BillingStatusKey IS NOT NULL
			UPDATE tProject
			SET    ProjectBillingStatusKey = @BillingStatusKey
			WHERE  ProjectKey = @ProjectKey
		
		-- commented out because we do that after billing now
		--EXEC sptProjectRollupUpdateEntity ''tInvoice'', @Ret
	
		-- Now log 
		declare	@Entity varchar(50),
		@EntityKey int,
		@Action varchar(200),
		@ActionDate smalldatetime,
		@ActionBy varchar(500),
		@Comments varchar(4000),
		@Reference varchar(200),
		@SourceCompanyID varchar(100),
		@CampaignKey int 

		select @Entity = ''Client Invoice'',@EntityKey = @Ret,@Action = ''Generated'', @ActionDate = getutcdate(), @CampaignKey = 0

		select @Reference = i.InvoiceNumber
			  ,@SourceCompanyID = c.CustomerID
		from   tInvoice i (nolock)
			left outer join tCompany c (nolock) on i.ClientKey = c.CompanyKey
		where  i.InvoiceKey = @Ret

		select @Reference = isnull(@Reference,'''')
			  ,@SourceCompanyID = isnull(@SourceCompanyID,'''')
		
		-- the Invoice number may be missing if the user assign #s at approval time
		if len(@Reference) > 0
			select @Comments = ''Invoice '' + @Reference + '' was generated through mass billing''
		else
			select @Comments = ''Invoice was generated through mass billing''

		if @WJAPP = 1
			select @Comments = @Comments + ''.'' -- just to differentiate bewteen wjapp and wmj

		exec sptActionLogInsert @Entity, @EntityKey, @CompanyKey, @ProjectKey, @Action, @ActionDate, @ActionBy, @Comments, @Reference, @SourceCompanyID, @UserKey, @CampaignKey

		if @LaborAtNet = 1
		begin
			exec sptInvoiceLaborAtNet @Ret, @PercentOfActual, null
		end

		EXEC spFixedFeesUpdateBillingSchedule @Ret, @ProjectKey

		SET @InvoiceKey = @Ret

		RETURN 1
	END
	ELSE
		RETURN @Ret






'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tOFXGLAccountLink]'
GO
IF OBJECT_ID(N'[dbo].[tOFXGLAccountLink]', 'U') IS NULL
CREATE TABLE [dbo].[tOFXGLAccountLink]
(
[OFXGLAccountLinkKey] [int] NOT NULL IDENTITY(1, 1),
[CompanyKey] [int] NOT NULL,
[Org] [varchar] (50) NULL,
[FID] [varchar] (50) NULL,
[IntuBid] [varchar] (50) NULL,
[CCACCTTO] [varchar] (100) NOT NULL,
[GLAccountKey] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tOFXGLAccountLink] on [dbo].[tOFXGLAccountLink]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tOFXGLAccountLink]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tOFXGLAccountLink]', 'U'))
ALTER TABLE [dbo].[tOFXGLAccountLink] ADD CONSTRAINT [PK_tOFXGLAccountLink] PRIMARY KEY CLUSTERED ([OFXGLAccountLinkKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tOFXGLAccountLink_Lookup] on [dbo].[tOFXGLAccountLink]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tOFXGLAccountLink_Lookup' AND object_id = OBJECT_ID(N'[dbo].[tOFXGLAccountLink]'))
CREATE NONCLUSTERED INDEX [IX_tOFXGLAccountLink_Lookup] ON [dbo].[tOFXGLAccountLink] ([CompanyKey], [FID], [CCACCTTO])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCompanyBackup]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[spCompanyBackup]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spCompanyBackup]
	@CompanyKey int,
	@BackupPath varchar(1000) = ''d:\backup\'',
	@WithPassword int = 1
AS

/*
	Who		When		What
	GHL		09/19/05	Updated for version 800
	GHL		10/31/05	Updated for version 81
	GHL		01/26/06	Updated for version 82
	GHL		03/27/06	Updated for Vesrion 83
	GHL		06/30/06	Updated for Version 835
	CRG		08/10/06	Updated for Version 84
	GHL     03/16/07    Updated for Version 8407
	GHL		06/21/07	Updated for Version 843
	GWG		03/15/08	Added tMediaRevisionReason
	GHL     11/04/08    Updated for 85 and WMJ10
	GHL     06/09/09    Added cash basis tables
	GHL     06/09/09    Updated for WMJ105
	GHL     09/29/09    Added tVoucherTax, tVoucherDetailTax
	GHL     09/29/09    Added tInvoiceTax
	CRG		05/18/10    Modified because tTaskUser allows NULL UserKey now	
	RLB     01/31/11    added tAttachment Activity
	GWG		04/25/11	Added a comment at the bottom to show how to do an encrypted backup
	GHL     06/20/11    (111045) Added Password to backup + missing tables
	                    Fixed tReviewComment backup
	GHL     08/16/11    Removed Catalog tables
	CRG     08/22/11    Added tWebDavServer
	GHL     09/08/11    Added WithPassword parameter so that we can backup with or without password
						3 ways to backup:
						1) exec spCompanyBackup 100....................will backup to PABackup
						2) exec spCompanyBackup 100, ''c:\backup\''......will backup to drive without pwd
						3) exec spCompanyBackup 100, ''c:\backup\'', 1...will backup to drive with pwd
	GHL     09/29/11    Added tVoucherCC and tGLAccountUser for credit card charges
	GHL     04/19/12    (112800) Added explicit creation of tAttachment to prevent problems with FileID
	GHL     05/03/12    Added new attachments (ER and VI). Added tGLCompanyMap, tUserGLCompanyAccess
	CRG     11/13/12    Now backing up tAttachment based on CompanyKey
	GWG     01/16/13    Added a delete of Action Log
	GWG     07/16/13    Modified the password to include the month and day (0 padded)
	GHL     08/14/13    Changed final message
	GHL     09/19/14    Adding (nolock) when querying tTime + large tables because of timeouts 
	GWG     09/23/14    Modified how the file name is generated and got rid of the delete section. Gens name as key_yearmonthday.bak
	GHL     10/30/14    Added around 100 missing tables 
	GHL     11/03/14    Added other session entities for a user or company
	CRG     11/03/14    Added tVPaymentLog
	GWG		11/5/14		Added default path in the parms
	RLB		12/15/14    Fix how data was pulled for tNote and tLink since we no longer use notegroup also default @WithPassword to 1
	GHL     01/09/14    (240587) Added missing NOLOCKs, added calls to spTime, removed tEmailSendLog, reviewed tTaskUser and Time queries
	GHL     02/19/16    (290336) Added reset of tCompany.DoBackup and insert in backup log. The company backup will be initated now with an SQL job
	GHL     12/29/16    Fixed query for tAppSetting
	GHL     09/29/17    Added missing deliverable tables
	GHL     10/17/17    Put back the backup command at the end 
	KMC     04/04/18    Updated the process to exclusively use tBackupLog instead of tCompany and tBackupLog.  Changed default BackupPath to d:\backup
	                    for the new servers.
	KMC		04/13/18    Added unique identifier to file name to handle customers on individual hosted servers
	MAS		10/18/18    Added tPlaidItem and tPlaidAccount
	RLS		02/12/19	(441481) Changed references from tApprovalStepDefNotify to tApprovalStepNotifyDef
	KMC     08/15/19    (474366) Removed tDeliverableGroup
	KMC     03/16/21    Added missing tables
	GHL     03/18/21    Added media plan tables
	KMC     08/02/21    Added tClientServices
	KMC     09/07/21    Added tCampaignTeam, tCampaignUserServices, tPreferenceRTN
	KMC     05/04/22    Removed tAttribute, tAttributeEntityValue, and tAttributeValue
	CRG     11/07/22    Added tTimeRollup
	KMC     11/07/22    Added tAvalaraTaxCode
	KMC     05/16/23    Added tProjectServices
	GAR     05/16/23    Added tAvalaraRegion
	GAR     05/16/23    Added tInvoiceTaxAvalara
	CRG     05/16/23    Added tTaskPriority
	MAS		06/21/23	Removed Old Media tables
	GAR     04/01/24    Added tAvalaraTaxData, tProjectAddress
	RLS     05/06/24    Added condition to ''tUser'' section to catch users who have no CompanyKey but
						whos OwnerCompanyKey = this company
	GAR		01/21/25    Removed all references to tWidget and added tWidgetDef
	GAR		05/29/25    Temporarily removed tWidgetDef since the table isn''t in prod yet
	CRG     01/19/26    Added tTaskUserOrig and tTaskUserHourOrig
	KMC     06/01/26    Added tEmailTemplate and tEmailTemplateSection
	MAS     07/30/26    (733785) Added tOFXGLAccountLink
*/
/*
	Tables not needed in this routine
	tAttachmentBackup
	tBackupLog
	tConversion
	tConversionLog
	tEmailData
	tGridPrint
	tLMTimeSync
	tLMTimeSync_Archive
	tLMTimeSyncHistory
	tRelease
	tReleaseLog
	tTimer
*/

	declare @start datetime
	declare @t datetime
	select @t = getdate()
	select @start = getdate()

	DECLARE	@DataBackup varchar(1000)
	
	if exists (select * from PABackup.dbo.sysobjects where name=''cnvCustTermsMap'')
		drop table PABackup.dbo.cnvCustTermsMap

	Print ''cnvCustTermsMap''	 

	Select cnvCustTermsMap.* 
	Into PABackup.dbo.cnvCustTermsMap 
	From cnvCustTermsMap (nolock) 
	Where  CompanyKey = @CompanyKey
	
	exec spTime ''cnvCustTermsMap'', @t output

	if exists (select * from PABackup.dbo.sysobjects where name=''tActionLog'')
		drop table PABackup.dbo.tActionLog
		
	Print ''tActionLog: FileVersion''	 
	Select tActionLog.* 
	Into PABackup.dbo.tActionLog 
	From tActionLog (nolock) 
	Where  CompanyKey = @CompanyKey
	
	exec spTime ''tActionLog: FileVersion'', @t output
 
	Print ''tActivationLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivationLog'')
	drop table PABackup.dbo.tActivationLog
	 
	Select tActivationLog.* Into PABackup.dbo.tActivationLog 
	FROM tActivationLog  (nolock), tUser u  (nolock)
	where tActivationLog.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey

	exec spTime '''', @t output
 
	Print ''tActivity''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivity'')
	drop table PABackup.dbo.tActivity
	 
	Select tActivity.* Into PABackup.dbo.tActivity 
	FROM tActivity (nolock) 
	where tActivity.CompanyKey = @CompanyKey

	exec spTime ''tActivity'', @t output
 
	Print ''tActivityEmail''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivityEmail'')
	drop table PABackup.dbo.tActivityEmail
	 
	Select tActivityEmail.* Into PABackup.dbo.tActivityEmail 
	FROM   tActivityEmail (nolock) , tActivity a (nolock) 
	where  tActivityEmail.ActivityKey = a.ActivityKey 
	and    a.CompanyKey = @CompanyKey

	exec spTime ''tActivityEmail'', @t output
 
	Print ''tActivityHistory''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivityHistory'')
	drop table PABackup.dbo.tActivityHistory
	 
	Select tActivityHistory.* Into PABackup.dbo.tActivityHistory 
	FROM   tActivityHistory (nolock) , tActivity a (nolock) 
	where  tActivityHistory.ActivityKey = a.ActivityKey 
	and    a.CompanyKey = @CompanyKey

	exec spTime ''tActivityHistory'', @t output

	Print ''tActivityLink : tCompany''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivityLink'')
	drop table PABackup.dbo.tActivityLink
	 
	Select tActivityLink.* Into PABackup.dbo.tActivityLink 
	FROM   tActivityLink (nolock) , tActivity a (nolock) 
	where  tActivityLink.ActivityKey = a.ActivityKey 
	and    a.CompanyKey = @CompanyKey

	exec spTime ''tActivityLink : tCompany'', @t output

	Print ''tActivityStatus''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivityStatus'')
	drop table PABackup.dbo.tActivityStatus
	 
	Select tActivityStatus.* Into PABackup.dbo.tActivityStatus 
	FROM tActivityStatus (nolock)
	where tActivityStatus.CompanyKey = @CompanyKey

	exec spTime ''tActivityType'', @t output

	Print ''tActivityType''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tActivityType'')
	drop table PABackup.dbo.tActivityType
	 
	Select tActivityType.* Into PABackup.dbo.tActivityType 
	FROM tActivityType (nolock)
	where tActivityType.CompanyKey = @CompanyKey

	exec spTime ''tActivityType'', @t output

	Print ''tAddress''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAddress'')
	drop table PABackup.dbo.tAddress
	 
	Select tAddress.* Into PABackup.dbo.tAddress 
	FROM tAddress (nolock) 
	where tAddress.OwnerCompanyKey = @CompanyKey
	
	exec spTime ''tAddress'', @t output

	Print ''tApiHook''

	if exists (select * from PABackup.dbo.sysobjects where name=''tApiHook'')
		drop table PABackup.dbo.tApiHook

	Select tApiHook.* 
	Into PABackup.dbo.tApiHook 
	From tApiHook (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tApiHook'', @t output

	Print ''tApiLog''

	if exists (select * from PABackup.dbo.sysobjects where name=''tApiLog'')
		drop table PABackup.dbo.tApiLog

	Select tApiLog.* 
	Into PABackup.dbo.tApiLog 
	From tApiLog (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tApiLog'', @t output

	Print ''tApiQueue''

	if exists (select * from PABackup.dbo.sysobjects where name=''tApiQueue'')
		drop table PABackup.dbo.tApiQueue

	Select tApiQueue.* 
	Into PABackup.dbo.tApiQueue 
	From tApiQueue (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tApiQueue'', @t output

	Print ''tApiQueueArchive''

	if exists (select * from PABackup.dbo.sysobjects where name=''tApiQueueArchive'')
		drop table PABackup.dbo.tApiQueueArchive

	Select tApiQueueArchive.* 
	Into PABackup.dbo.tApiQueueArchive 
	From tApiQueueArchive (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tApiQueueArchive'', @t output

	if exists (select * from PABackup.dbo.sysobjects where name=''tAppFavorite'')
		drop table PABackup.dbo.tAppFavorite

	Print ''tAppFavorite''	 

	Select tAppFavorite.* 
	Into PABackup.dbo.tAppFavorite 
	From tAppFavorite (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tAppFavorite'', @t output

	if exists (select * from PABackup.dbo.sysobjects where name=''tAppHistory'')
		drop table PABackup.dbo.tAppHistory

	Print ''tAppHistory''	 

	Select tAppHistory.* 
	Into PABackup.dbo.tAppHistory 
	From tAppHistory (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tAppHistory'', @t output

	if exists (select * from PABackup.dbo.sysobjects where name=''tAppMenu'')
		drop table PABackup.dbo.tAppMenu

	Print ''tAppMenu''	 

	Select tAppMenu.* 
	Into PABackup.dbo.tAppMenu 
	From tAppMenu (nolock) 
	Where  CompanyKey = @CompanyKey

	exec spTime ''tAppMenu'', @t output

	if exists (select * from PABackup.dbo.sysobjects where name=''tAppRead'')
		drop table PABackup.dbo.tAppRead

	Print ''tAppRead''	 

	Select tAppRead.* 
	Into PABackup.dbo.tAppRead 
	From tAppRead (nolock)
		inner join tUser u (nolock) on tAppRead.UserKey = u.UserKey 
	Where  isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey

	exec spTime ''tAppRead'', @t output

	if exists (select * from PABackup.dbo.sysobjects where name=''tAppCalendar'')
	drop table PABackup.dbo.tAppCalendar

	Print ''tAppCalendar''	 

	Select tAppCalendar.* 
	Into PABackup.dbo.tAppCalendar 
	From tAppCalendar (nolock)
		inner join tUser u (nolock) on tAppCalendar.UserKey = u.UserKey 
	Where  isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey

	exec spTime ''tAppCalendar'', @t output

	Print ''tApproval''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApproval'')
	drop table PABackup.dbo.tApproval
	 
	Select tApproval.* Into PABackup.dbo.tApproval 
	FROM tApproval (nolock), tProject (nolock) 
	Where tApproval.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey

	exec spTime ''tApproval'', @t output

	Print ''tApprovalItem''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalItem'')
	drop table PABackup.dbo.tApprovalItem
	 
	Select tApprovalItem.* Into PABackup.dbo.tApprovalItem 
	FROM tApprovalItem (nolock) , tApproval (nolock) , tProject (nolock)  
	Where tApprovalItem.ApprovalKey = tApproval.ApprovalKey 
	and tApproval.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey

	exec spTime ''tApprovalItem'', @t output
	
	Print ''tApprovalItemReply''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalItemReply'')
	drop table PABackup.dbo.tApprovalItemReply
	 
	Select tApprovalItemReply.* Into PABackup.dbo.tApprovalItemReply 
	FROM tApprovalItemReply (nolock) , tApprovalItem (nolock) , tApproval (nolock) , tProject (nolock) 
	Where tApprovalItemReply.ApprovalItemKey = tApprovalItem.ApprovalItemKey 
	and	tApprovalItem.ApprovalKey = tApproval.ApprovalKey 
	and tApproval.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey

	exec spTime ''tApprovalItemReply'', @t output
	
	Print ''tApprovalList''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalList'')
	drop table PABackup.dbo.tApprovalList
	 
	Select tApprovalList.* Into PABackup.dbo.tApprovalList 
	FROM tApprovalList (nolock) , tApproval (nolock) , tProject (nolock) 
	Where tApprovalList.ApprovalKey = tApproval.ApprovalKey 
	and tApproval.ProjectKey = tProject.ProjectKey 
	and	tProject.CompanyKey = @CompanyKey

	exec spTime ''tApprovalList'', @t output

	Print ''tApprovalUpdateList''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalUpdateList'')
	drop table PABackup.dbo.tApprovalUpdateList
	 
	Select tApprovalUpdateList.* Into PABackup.dbo.tApprovalUpdateList 
	FROM tApprovalUpdateList (nolock), tApproval (nolock), tProject (nolock) 
	Where tApprovalUpdateList.ApprovalKey = tApproval.ApprovalKey 
	and tApproval.ProjectKey = tProject.ProjectKey 
	and	tProject.CompanyKey = @CompanyKey

	exec spTime ''tApprovalUpdateList'', @t output
	
	Print ''tApprovalStep''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalStep'')
	drop table PABackup.dbo.tApprovalStep
	 
	Select * Into PABackup.dbo.tApprovalStep FROM tApprovalStep WHERE CompanyKey = @CompanyKey

	exec spTime ''tApprovalStep'', @t output
	
	Print ''tApprovalStepDef''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalStepDef'')
	drop table PABackup.dbo.tApprovalStepDef
	 
	Select * Into PABackup.dbo.tApprovalStepDef FROM tApprovalStepDef (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tApprovalStepDef'', @t output

	Print ''tApprovalStepNotifyDef''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalStepNotifyDef'')
	drop table PABackup.dbo.tApprovalStepNotifyDef
	 
	Select tApprovalStepNotifyDef.* Into PABackup.dbo.tApprovalStepNotifyDef 
	FROM tApprovalStepNotifyDef (nolock), tApprovalStepDef  (nolock)
	WHERE tApprovalStepDef.CompanyKey = @CompanyKey
	and   tApprovalStepNotifyDef.ApprovalStepDefKey = tApprovalStepDef.ApprovalStepDefKey 

	exec spTime ''tApprovalStepNotifyDef'', @t output

	Print ''tApprovalStepNotify''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalStepNotify'')
	drop table PABackup.dbo.tApprovalStepNotify
	 
	Select tApprovalStepNotify.* Into PABackup.dbo.tApprovalStepNotify 
	FROM tApprovalStepNotify (nolock), tApprovalStep  (nolock)
	WHERE tApprovalStep.CompanyKey = @CompanyKey
	and   tApprovalStepNotify.ApprovalStepKey = tApprovalStep.ApprovalStepKey 

	exec spTime ''tApprovalStepNotify'', @t output

	Print ''tApprovalStepUser''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalStepUser'')
	drop table PABackup.dbo.tApprovalStepUser
	 
	Select tApprovalStepUser.* Into PABackup.dbo.tApprovalStepUser 
	FROM tApprovalStepUser (nolock), tApprovalStep aps (nolock) 
	where tApprovalStepUser.ApprovalStepKey = aps.ApprovalStepKey 
	and aps.CompanyKey = @CompanyKey

	exec spTime ''tApprovalStepUser'', @t output
	
	Print ''tApprovalStepUserDef''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalStepUserDef'')
	drop table PABackup.dbo.tApprovalStepUserDef
	 
	Select tApprovalStepUserDef.* Into PABackup.dbo.tApprovalStepUserDef 
	FROM tApprovalStepUserDef (nolock), tApprovalStepDef asd (nolock) 
	where tApprovalStepUserDef.ApprovalStepDefKey = asd.ApprovalStepDefKey 
	and asd.CompanyKey = @CompanyKey
	
	exec spTime ''tApprovalStepUserDef'', @t output

	Print ''tApprovalType''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tApprovalType'')
	drop table PABackup.dbo.tApprovalType
	 
	Select * Into PABackup.dbo.tApprovalType FROM tApprovalType (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tApprovalType'', @t output
	
	Print ''tAppSession:company''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAppSession'')
	drop table PABackup.dbo.tAppSession
	 
	Select tAppSession.* Into PABackup.dbo.tAppSession 
	FROM tAppSession (nolock), tCompany c (nolock) 
	where tAppSession.EntityKey = c.CompanyKey 
	and tAppSession.Entity = ''company''
	and isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey

	exec spTime ''tAppSession:company'', @t output
	
	Print ''tAppSession:user''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAppSession'')
	 
		Insert PABackup.dbo.tAppSession 
		Select tAppSession.*  
		FROM tAppSession (nolock), tUser u (nolock) 
		where tAppSession.EntityKey = u.UserKey 
		and tAppSession.Entity = ''user''
		and isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey

	else
	 
		Select tAppSession.* Into PABackup.dbo.tAppSession 
		FROM tAppSession (nolock), tUser u (nolock) 
		where tAppSession.EntityKey = u.UserKey 
		and tAppSession.Entity = ''user''
		and isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey

	exec spTime ''tAppSession:user'', @t output

	Print ''tAppSetting''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAppSetting'')
	drop table PABackup.dbo.tAppSetting
	 
	Select tAppSetting.* 
	Into PABackup.dbo.tAppSetting
	From tAppSetting (nolock) 

	exec spTime ''tAppSetting'', @t output

	Print ''tAppSettingGroup''	 

	if exists (select * from PABackup.dbo.sysobjects where name=''tAppSettingGroup'')
		drop table PABackup.dbo.tAppSettingGroup
	
	Select tAppSettingGroup.* 
	Into PABackup.dbo.tAppSettingGroup 
	From tAppSettingGroup (nolock) 

	exec spTime ''tAppSettingGroup'', @t output
	
	Print ''tAssignment''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAssignment'')
	drop table PABackup.dbo.tAssignment
	 
	Select tAssignment.* Into PABackup.dbo.tAssignment 
	FROM tAssignment (nolock) , tProject  (nolock) 
	Where tAssignment.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tAssignment'', @t output

	Print ''tAttachment''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAttachment'')
	drop table PABackup.dbo.tAttachment
	 
	-- The first Select	tAttachment.* Into PABackup.dbo.tAttachment  seems to miss FileID
	-- so do a real table creation
	CREATE TABLE PABackup.dbo.tAttachment (
	[AttachmentKey] [int] NOT NULL,
	[CompanyKey] int NULL,
	[AssociatedEntity] [varchar](50) NOT NULL,
	[EntityKey] [int] NOT NULL,
	[AddedBy] [int] NOT NULL,
	[FileName] [varchar](300) NOT NULL,
	[Comments] [varchar](1000) NULL,
	[Path] [varchar](2000) NULL,
	[FileID] [varchar](2000) NULL
	)

	Insert	PABackup.dbo.tAttachment (AttachmentKey,
			CompanyKey,
			AssociatedEntity,
			EntityKey,
			AddedBy,
			FileName,
			Comments,
			Path,
			FileID )
	Select  AttachmentKey,
			CompanyKey,
			AssociatedEntity,
			EntityKey,
			AddedBy,
			FileName,
			Comments,
			Path,
			FileID
	FROM	tAttachment (NOLOCK)
	where	CompanyKey = @CompanyKey

	exec spTime ''tAttachment'', @t output

	Print ''tAvalaraRegion''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAvalaraRegion'')
	drop table PABackup.dbo.tAvalaraRegion
	 
	Select * Into PABackup.dbo.tAvalaraRegion FROM tAvalaraRegion (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tAvalaraRegion'', @t output

	Print ''tAvalaraTaxCode''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAvalaraTaxCode'')
	drop table PABackup.dbo.tAvalaraTaxCode
	 
	Select * Into PABackup.dbo.tAvalaraTaxCode FROM tAvalaraTaxCode (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tAvalaraTaxCode'', @t output

	Print ''tAvalaraTaxData''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tAvalaraTaxData'')
	drop table PABackup.dbo.tAvalaraTaxData
	 
	Select tAvalaraTaxData.* Into PABackup.dbo.tAvalaraTaxData 
	FROM tAvalaraTaxData (nolock) , tEstimate  (nolock) 
	Where tAvalaraTaxData.EntityKey = tEstimate.EstimateKey 
	and tEstimate.CompanyKey = @CompanyKey
	and tAvalaraTaxData.Entity = ''tEstimate''

	exec spTime ''tAvalaraTaxData'', @t output

	Print ''tBilling''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tBilling'')
	drop table PABackup.dbo.tBilling
	 
	Select * Into PABackup.dbo.tBilling FROM tBilling (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tBilling'', @t output

	Print ''tBillingDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tBillingDetail'')
	drop table PABackup.dbo.tBillingDetail
	 
	Select tBillingDetail.* Into PABackup.dbo.tBillingDetail 
	FROM tBillingDetail (nolock), tBilling (nolock)
	WHERE tBillingDetail.BillingKey = tBilling.BillingKey
	and tBilling.CompanyKey = @CompanyKey

	exec spTime ''tBillingDetail'', @t output

	Print ''tBillingFixedFee''
	if exists (select * from PABackup.dbo.sysobjects where name=''tBillingFixedFee'')
	drop table PABackup.dbo.tBillingFixedFee
	 
	Select tBillingFixedFee.* Into PABackup.dbo.tBillingFixedFee 
	FROM tBillingFixedFee (nolock), tBilling (nolock)
	WHERE tBillingFixedFee.BillingKey = tBilling.BillingKey
	and tBilling.CompanyKey = @CompanyKey

	exec spTime ''tBillingFixedFee'', @t output

	Print ''tBillingGroup''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tBillingGroup'')
	drop table PABackup.dbo.tBillingGroup
	 
	Select * Into PABackup.dbo.tBillingGroup FROM tBillingGroup (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tBillingGroup'', @t output

	Print ''tBillingPayment''
	if exists (select * from PABackup.dbo.sysobjects where name=''tBillingPayment'')
	drop table PABackup.dbo.tBillingPayment
	 
	Select tBillingPayment.* Into PABackup.dbo.tBillingPayment 
	FROM tBillingPayment (nolock), tBilling (nolock)
	WHERE tBillingPayment.BillingKey = tBilling.BillingKey
	and tBilling.CompanyKey = @CompanyKey

	exec spTime ''tBillingPayment'', @t output

	Print ''tBillingSchedule''
	if exists (select * from PABackup.dbo.sysobjects where name=''tBillingSchedule'')
	drop table PABackup.dbo.tBillingSchedule
	 
	Select tBillingSchedule.* Into PABackup.dbo.tBillingSchedule 
	FROM tBillingSchedule (nolock), tProject (nolock)
	WHERE tBillingSchedule.ProjectKey = tProject.ProjectKey
	and tProject.CompanyKey = @CompanyKey

	exec spTime ''tBillingSchedule'', @t output

	Print ''tBoxFolderID''

	if exists (select * from PABackup.dbo.sysobjects where name=''tBoxFolderID'')
		drop table PABackup.dbo.tBoxFolderID

	Select tBoxFolderID.* 
	Into PABackup.dbo.tBoxFolderID
	From tBoxFolderID (nolock)
	Where CompanyKey = @CompanyKey

	exec spTime ''tBoxFolderID'', @t output

	Print ''tBurnChart''

	if exists (select * from PABackup.dbo.sysobjects where name=''tBurnChart'')
		drop table PABackup.dbo.tBurnChart

	Select tBurnChart.* 
	Into PABackup.dbo.tBurnChart
	from tBurnChart (nolock)
		left join tProject (nolock) on tBurnChart.Entity = ''tProject'' and tBurnChart.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tBurnChart.Entity = ''tCampaign'' and tBurnChart.EntityKey = tCampaign.CampaignKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey

	exec spTime ''tBurnChart'', @t output

	Print ''tBurnChartAssignmentOverUnder''

	if exists (select * from PABackup.dbo.sysobjects where name=''tBurnChartAssignmentOverUnder'')
		drop table PABackup.dbo.tBurnChartAssignmentOverUnder

	Select tBurnChartAssignmentOverUnder.* 
	Into PABackup.dbo.tBurnChartAssignmentOverUnder
	from tBurnChartAssignmentOverUnder (nolock)
		left join tProject (nolock) on tBurnChartAssignmentOverUnder.Entity = ''tProject'' and tBurnChartAssignmentOverUnder.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tBurnChartAssignmentOverUnder.Entity = ''tCampaign'' and tBurnChartAssignmentOverUnder.EntityKey = tCampaign.CampaignKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey

	exec spTime ''tBurnChartAssignmentOverUnder'', @t output

	Print ''tBurnChartDetail''

	if exists (select * from PABackup.dbo.sysobjects where name=''tBurnChartDetail'')
		drop table PABackup.dbo.tBurnChartDetail

	Select tBurnChartDetail.* 
	Into PABackup.dbo.tBurnChartDetail
	from tBurnChartDetail (nolock)
		left join tProject (nolock) on tBurnChartDetail.Entity = ''tProject'' and tBurnChartDetail.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tBurnChartDetail.Entity = ''tCampaign'' and tBurnChartDetail.EntityKey = tCampaign.CampaignKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey

	exec spTime ''tBurnChartDetail'', @t output

	Print ''tBurnChartFinalOverUnder''

	if exists (select * from PABackup.dbo.sysobjects where name=''tBurnChartFinalOverUnder'')
		drop table PABackup.dbo.tBurnChartFinalOverUnder

	Select tBurnChartFinalOverUnder.* 
	Into PABackup.dbo.tBurnChartFinalOverUnder
	from tBurnChartFinalOverUnder (nolock)
		left join tProject (nolock) on tBurnChartFinalOverUnder.Entity = ''tProject'' and tBurnChartFinalOverUnder.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tBurnChartFinalOverUnder.Entity = ''tCampaign'' and tBurnChartFinalOverUnder.EntityKey = tCampaign.CampaignKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey

	exec spTime ''tBurnChartFinalOverUnder'', @t output

	Print ''tBurnChartOverUnder''

	if exists (select * from PABackup.dbo.sysobjects where name=''tBurnChartOverUnder'')
		drop table PABackup.dbo.tBurnChartOverUnder

	Select tBurnChartOverUnder.* 
	Into PABackup.dbo.tBurnChartOverUnder
	from tBurnChartOverUnder (nolock)
		left join tProject (nolock) on tBurnChartOverUnder.Entity = ''tProject'' and tBurnChartOverUnder.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tBurnChartOverUnder.Entity = ''tCampaign'' and tBurnChartOverUnder.EntityKey = tCampaign.CampaignKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey

	exec spTime ''tBurnChartOverUnder'', @t output

	Print ''tBuyUpdateLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tBuyUpdateLog'')
	drop table PABackup.dbo.tBuyUpdateLog
	 
	Select * Into PABackup.dbo.tBuyUpdateLog FROM tBuyUpdateLog (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tBuyUpdateLog'', @t output

	Print ''tBuyUpdateLogDetail''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tBuyUpdateLogDetail'')
	drop table PABackup.dbo.tBuyUpdateLogDetail
	 
	Select tBuyUpdateLogDetail.* Into PABackup.dbo.tBuyUpdateLogDetail 
	FROM tBuyUpdateLogDetail (nolock) , tBuyUpdateLog (nolock)
	Where tBuyUpdateLogDetail.BuyUpdateLogKey = tBuyUpdateLog.BuyUpdateLogKey 
	and tBuyUpdateLog.CompanyKey = @CompanyKey

	exec spTime ''tBuyUpdateLogDetail'', @t output

	Print ''tCalendar454''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendar454'')
	drop table PABackup.dbo.tCalendar454
	 
	Select * Into PABackup.dbo.tCalendar454 FROM tCalendar454 (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCalendar454'', @t output

	Print ''tCalendarReport''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarReport'')
	drop table PABackup.dbo.tCalendarReport
	 
	Select * Into PABackup.dbo.tCalendarReport FROM tCalendarReport (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCalendarReport'', @t output

	Print ''tCalendar''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendar'')
	drop table PABackup.dbo.tCalendar
	 
	Select * Into PABackup.dbo.tCalendar FROM tCalendar (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tCalendar'', @t output
	 
	Print ''tCalendarAttendee''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarAttendee'')
	drop table PABackup.dbo.tCalendarAttendee
	 
	Select tCalendarAttendee.* Into PABackup.dbo.tCalendarAttendee 
	FROM tCalendarAttendee (nolock) , tCalendar (nolock)
	Where tCalendarAttendee.CalendarKey = tCalendar.CalendarKey 
	and tCalendar.CompanyKey = @CompanyKey

	exec spTime ''tCalendarAttendee'', @t output

	Print ''tCalendarAttendeeGroup''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarAttendeeGroup'')
	drop table PABackup.dbo.tCalendarAttendeeGroup
	 
	Select tCalendarAttendeeGroup.* Into PABackup.dbo.tCalendarAttendeeGroup 
	FROM tCalendarAttendeeGroup (nolock), tCalendar (nolock)  
	Where tCalendarAttendeeGroup.CalendarKey = tCalendar.CalendarKey 
	and tCalendar.CompanyKey = @CompanyKey
	
	exec spTime ''tCalendarAttendeeGroup'', @t output

	Print ''tCalendarAttendeeUpdateLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarAttendeeUpdateLog'')
	drop table PABackup.dbo.tCalendarAttendeeUpdateLog
	 
	Select tCalendarAttendeeUpdateLog.* Into PABackup.dbo.tCalendarAttendeeUpdateLog 
	FROM tCalendarAttendeeUpdateLog (nolock), tCalendar (nolock) 
	Where tCalendarAttendeeUpdateLog.CalendarKey = tCalendar.CalendarKey 
	and tCalendar.CompanyKey = @CompanyKey
	
	exec spTime ''tCalendarAttendeeUpdateLog'', @t output

	Print ''tCalendarFeed''

	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarFeed'')
		drop table PABackup.dbo.tCalendarFeed

	Select tCalendarFeed.* 
	Into PABackup.dbo.tCalendarFeed
	from tCalendarFeed (nolock)
		left join tProject (nolock) on tCalendarFeed.Entity = ''project'' and tCalendarFeed.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tCalendarFeed.Entity = ''campaign'' and tCalendarFeed.EntityKey = tCampaign.CampaignKey
		left join tCMFolder (nolock) on tCalendarFeed.Entity = ''calendar'' and tCalendarFeed.EntityKey = tCMFolder.CMFolderKey
		left join tPublishCalendar (nolock) on tCalendarFeed.Entity = ''publish'' and tCalendarFeed.EntityKey = tPublishCalendar.PublishCalendarKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey
	   or tCMFolder.CompanyKey = @CompanyKey
	   or tPublishCalendar.CompanyKey = @CompanyKey

	exec spTime ''tCalendarFeed'', @t output

	Print ''tCalendarFeedLog''

	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarFeedLog'')
		drop table PABackup.dbo.tCalendarFeedLog

	Select tCalendarFeedLog.* 
	Into PABackup.dbo.tCalendarFeedLog
	from tCalendarFeedLog (nolock)
		left join tProject (nolock) on tCalendarFeedLog.Entity = ''project'' and tCalendarFeedLog.EntityKey = tProject.ProjectKey
		left join tCampaign (nolock) on tCalendarFeedLog.Entity = ''campaign'' and tCalendarFeedLog.EntityKey = tCampaign.CampaignKey
		left join tCMFolder (nolock) on tCalendarFeedLog.Entity = ''calendar'' and tCalendarFeedLog.EntityKey = tCMFolder.CMFolderKey
		left join tPublishCalendar (nolock) on tCalendarFeedLog.Entity = ''publish'' and tCalendarFeedLog.EntityKey = tPublishCalendar.PublishCalendarKey
   where tProject.CompanyKey = @CompanyKey
       or tCampaign.CompanyKey = @CompanyKey
	   or tCMFolder.CompanyKey = @CompanyKey
	   or tPublishCalendar.CompanyKey = @CompanyKey

	exec spTime ''tCalendarFeedLog'', @t output

	Print ''tCalendarResource''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarResource'')
	drop table PABackup.dbo.tCalendarResource
	 
	Select tCalendarResource.* Into PABackup.dbo.tCalendarResource 
	FROM tCalendarResource (nolock)
	Where tCalendarResource.CompanyKey = @CompanyKey
	
	exec spTime ''tCalendarResource'', @t output

	Print ''tCalendarType''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarType'')
	drop table PABackup.dbo.tCalendarType
	 
	Select * Into PABackup.dbo.tCalendarType FROM tCalendarType (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tCalendarType'', @t output

	Print ''tCalendarUser''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarUser'')
	drop table PABackup.dbo.tCalendarUser
	 
	Select tCalendarUser.* Into PABackup.dbo.tCalendarUser 
	FROM tCalendarUser (nolock), tUser u (nolock) 
	where tCalendarUser.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	
	exec spTime ''tCalendarUser'', @t output

	Print ''tCalendarLink''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarLink'')
	drop table PABackup.dbo.tCalendarLink
	 
	Select tCalendarLink.* Into PABackup.dbo.tCalendarLink 
	FROM   tCalendarLink (nolock), tCalendar c (nolock)
	where  tCalendarLink.CalendarKey = c.CalendarKey 
	and    c.CompanyKey = @CompanyKey 

	exec spTime ''tCalendarLink'', @t output

	Print ''tCalendarReminder''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarReminder'')
	drop table PABackup.dbo.tCalendarReminder
	 
	Select tCalendarReminder.* Into PABackup.dbo.tCalendarReminder 
	FROM   tCalendarReminder (nolock), tUser u (nolock) 
	where  tCalendarReminder.UserKey = u.UserKey 
	and    isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey 
	
	exec spTime ''tCalendarReminder'', @t output

	Print ''tCalendarUpdateLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCalendarUpdateLog'')
	drop table PABackup.dbo.tCalendarUpdateLog
	 
	Select tCalendarUpdateLog.* Into PABackup.dbo.tCalendarUpdateLog 
	FROM   tCalendarUpdateLog (nolock), tCalendar c (nolock)
	where  tCalendarUpdateLog.CalendarKey = c.CalendarKey 
	and    c.CompanyKey = @CompanyKey 
	
	exec spTime ''tCalendarUpdateLog'', @t output

	Print ''tCampaign''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaign'')
	drop table PABackup.dbo.tCampaign
	 
	Select * Into PABackup.dbo.tCampaign FROM tCampaign (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCampaign'', @t output

	Print ''tCampaignBudget''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignBudget'')
	drop table PABackup.dbo.tCampaignBudget
	 
	Select tCampaignBudget.* Into PABackup.dbo.tCampaignBudget 
	FROM tCampaignBudget (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignBudget.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignBudget'', @t output

	Print ''tCampaignBudgetItem''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignBudgetItem'')
	drop table PABackup.dbo.tCampaignBudgetItem
	 
	Select tCampaignBudgetItem.* Into PABackup.dbo.tCampaignBudgetItem 
	FROM tCampaignBudgetItem (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignBudgetItem.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignBudgetItem'', @t output

	Print ''tCampaignEstByItem''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignEstByItem'')
	drop table PABackup.dbo.tCampaignEstByItem
	 
	Select tCampaignEstByItem.* Into PABackup.dbo.tCampaignEstByItem 
	FROM tCampaignEstByItem (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignEstByItem.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignEstByItem'', @t output

	Print ''tCampaignEstByTitle''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignEstByTitle'')
	drop table PABackup.dbo.tCampaignEstByTitle
	 
	Select tCampaignEstByTitle.* Into PABackup.dbo.tCampaignEstByTitle 
	FROM tCampaignEstByTitle (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignEstByTitle.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignEstByTitle'', @t output

	Print ''tCampaignRollup''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignRollup'')
	drop table PABackup.dbo.tCampaignRollup
	 
	Select tCampaignRollup.* Into PABackup.dbo.tCampaignRollup 
	FROM tCampaignRollup (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignRollup.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignRollup'', @t output

	Print ''tCampaignSegment''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignSegment'')
	drop table PABackup.dbo.tCampaignSegment
	 
	Select tCampaignSegment.* Into PABackup.dbo.tCampaignSegment 
	FROM tCampaignSegment (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignSegment.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignSegment'', @t output

	Print ''tCampaignTeam''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignTeam'')
	drop table PABackup.dbo.tCampaignTeam
	 
	Select tCampaignTeam.* Into PABackup.dbo.tCampaignTeam 
	FROM tCampaignTeam (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignTeam.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignTeam'', @t output

	Print ''tCampaignUserServices''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCampaignUserServices'')
	drop table PABackup.dbo.tCampaignUserServices
	 
	Select tCampaignUserServices.* Into PABackup.dbo.tCampaignUserServices 
	FROM tCampaignUserServices (nolock)
		,tCampaign c  (nolock)
	WHERE c.CompanyKey = @CompanyKey
	AND   tCampaignUserServices.CampaignKey = c.CampaignKey

	exec spTime ''tCampaignUserServices'', @t output

	Print ''tCardDavLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCardDavLog'')
	drop table PABackup.dbo.tCardDavLog
	 
	Select tCardDavLog.* Into PABackup.dbo.tCardDavLog 
	FROM tCardDavLog (nolock)
		,tUser u (nolock)
	WHERE isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
	AND   tCardDavLog.UserKey = u.UserKey

	exec spTime ''tCardDavLog'', @t output

	Print ''tCashConvert''

	if exists (select * from PABackup.dbo.sysobjects where name=''tCashConvert'')
		drop table PABackup.dbo.tCashConvert

	Select tCashConvert.* 
	Into PABackup.dbo.tCashConvert 
	From tCashConvert (nolock) 
	Where CompanyKey = @CompanyKey

	exec spTime ''tCashConvert'', @t output

	Print ''tCashTransaction''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCashTransaction'')
	drop table PABackup.dbo.tCashTransaction
	 
	Select * Into PABackup.dbo.tCashTransaction 
	FROM tCashTransaction (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tCashTransaction'', @t output

	Print ''tCashTransactionLine''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCashTransactionLine'')
	drop table PABackup.dbo.tCashTransactionLine
	 
	Select * Into PABackup.dbo.tCashTransactionLine 
	FROM tCashTransactionLine (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tCashTransactionLine'', @t output

	Print ''tCBBatch''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCBBatch'')
	drop table PABackup.dbo.tCBBatch
	 
	Select * Into PABackup.dbo.tCBBatch 
	FROM tCBBatch (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tCBBatch'', @t output

	Print ''tCBBatchAdjustment''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCBBatchAdjustment'')
	drop table PABackup.dbo.tCBBatchAdjustment
	 
	Select tCBBatchAdjustment.* Into PABackup.dbo.tCBBatchAdjustment 
	FROM tCBBatchAdjustment (NOLOCK)
		,tCBBatch b (NOLOCK)
	WHERE b.CompanyKey = @CompanyKey
	AND   tCBBatchAdjustment.BatchKey = b.CBBatchKey

	exec spTime ''tCBBatchAdjustment'', @t output

	Print ''tCBCode''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCBCode'')
	drop table PABackup.dbo.tCBCode
	 
	Select * Into PABackup.dbo.tCBCode 
	FROM tCBCode (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tCBCode'', @t output

	Print ''tCBCodePercent''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCBCodePercent'')
	drop table PABackup.dbo.tCBCodePercent
	 
	Select tCBCodePercent.* Into PABackup.dbo.tCBCodePercent 
	FROM tCBCodePercent (NOLOCK)
		,tCBCode b (NOLOCK)
	WHERE b.CompanyKey = @CompanyKey
	AND   tCBCodePercent.CBCodeKey = b.CBCodeKey

	exec spTime ''tCBCodePercent'', @t output

	Print ''tCBPosting''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCBPosting'')
	drop table PABackup.dbo.tCBPosting
	 
	Select tCBPosting.* Into PABackup.dbo.tCBPosting 
	FROM tCBPosting (NOLOCK)
		,tProject b (NOLOCK)
	WHERE b.CompanyKey = @CompanyKey
	AND   tCBPosting.ProjectKey = b.ProjectKey

	exec spTime ''tCBPosting'', @t output

	Print ''tCCEntry''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCCEntry'')
	drop table PABackup.dbo.tCCEntry
	 
	Select * Into PABackup.dbo.tCCEntry 
	FROM tCCEntry (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tCCEntry'', @t output

	Print ''tCCEntrySplit''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCCEntrySplit'')
	drop table PABackup.dbo.tCCEntrySplit
	 
	Select tCCEntrySplit.* Into PABackup.dbo.tCCEntrySplit 
	FROM tCCEntrySplit (NOLOCK)
		,tCCEntry b (NOLOCK)
	WHERE b.CompanyKey = @CompanyKey
	AND   tCCEntrySplit.CCEntryKey = b.CCEntryKey

	exec spTime ''tCCEntrySplit'', @t output

	Print ''tChange''

	if exists (select * from PABackup.dbo.sysobjects where name=''tChange'')
		drop table PABackup.dbo.tChange

	Select tChange.* 
	Into PABackup.dbo.tChange 
	From tChange (nolock) 
	Where CompanyKey = @CompanyKey

	exec spTime ''tChange'', @t output

	Print ''tChangeDef''

	if exists (select * from PABackup.dbo.sysobjects where name=''tChangeDef'')
		drop table PABackup.dbo.tChangeDef

	Select tChangeDef.* 
	Into PABackup.dbo.tChangeDef 
	From tChangeDef (nolock) 
	Where CompanyKey = @CompanyKey

	exec spTime ''tChangeDef'', @t output

	Print ''tCheck''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCheck'')
	drop table PABackup.dbo.tCheck
	 
	Select tCheck.* Into PABackup.dbo.tCheck 
	FROM tCheck (nolock), tCompany (nolock) 
	Where tCheck.ClientKey = tCompany.CompanyKey 
	and tCompany.OwnerCompanyKey = @CompanyKey
	
	exec spTime ''tCheck'', @t output

	Print ''tCheckAppl''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCheckAppl'')
	drop table PABackup.dbo.tCheckAppl
	 
	Select tCheckAppl.* Into PABackup.dbo.tCheckAppl 
	FROM tCheckAppl (nolock), tCheck (nolock), tCompany (nolock)
	Where tCheckAppl.CheckKey = tCheck.CheckKey 
	and tCheck.ClientKey = tCompany.CompanyKey 
	and tCompany.OwnerCompanyKey = @CompanyKey
	
	exec spTime ''tCheckAppl'', @t output

	Print ''tCheckFormat''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCheckFormat'')
	drop table PABackup.dbo.tCheckFormat
	 
	Select * Into PABackup.dbo.tCheckFormat FROM tCheckFormat (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tCheckFormat'', @t output

	Print ''tCheckMethod''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCheckMethod'')
	drop table PABackup.dbo.tCheckMethod
	 
	Select * Into PABackup.dbo.tCheckMethod FROM tCheckMethod (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tCheckMethod'', @t output

	Print ''tClass''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tClass'')
	drop table PABackup.dbo.tClass
	 
	Select * Into PABackup.dbo.tClass FROM tClass (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tClass'', @t output

	Print ''tClientProduct''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tClientProduct'')
	drop table PABackup.dbo.tClientProduct
	 
	Select * Into PABackup.dbo.tClientProduct FROM tClientProduct (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tClientProduct'', @t output

	Print ''tClientDivision''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tClientDivision'')
	drop table PABackup.dbo.tClientDivision
	 
	Select * Into PABackup.dbo.tClientDivision FROM tClientDivision (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tClientDivision'', @t output

	Print ''tClientServices''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tClientServices'')
	drop table PABackup.dbo.tClientServices
	 
	Select * Into PABackup.dbo.tClientServices FROM tClientServices (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tClientServices'', @t output

	Print ''tCMFolder''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCMFolder'')
	drop table PABackup.dbo.tCMFolder
	 
	Select * Into PABackup.dbo.tCMFolder FROM tCMFolder (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCMFolder'', @t output

	Print ''tCMFolderIncludeInSync''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCMFolderIncludeInSync'')
	drop table PABackup.dbo.tCMFolderIncludeInSync
	 
	Select tCMFolderIncludeInSync.* Into PABackup.dbo.tCMFolderIncludeInSync 
	From tCMFolderIncludeInSync (nolock), tCMFolder f (nolock)
	Where tCMFolderIncludeInSync.CMFolderKey = f.CMFolderKey
	and   f.CompanyKey = @CompanyKey

	exec spTime ''tCMFolderIncludeInSync'', @t output

	Print ''tCMFolderOffice''

	if exists (select * from PABackup.dbo.sysobjects where name=''tCMFolderOffice'')
		drop table PABackup.dbo.tCMFolderOffice

	Select tCMFolderOffice.* 
	Into PABackup.dbo.tCMFolderOffice
	From tCMFolderOffice (nolock) 
		Left Join tCMFolder (nolock) on tCMFolderOffice.CMFolderKey = tCMFolder.CMFolderKey
	Where tCMFolder.CompanyKey = @CompanyKey

	exec spTime ''tCMFolderOffice'', @t output

	Print ''tCMFolderSecurity''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCMFolderSecurity'')
	drop table PABackup.dbo.tCMFolderSecurity
	 
	Select tCMFolderSecurity.* Into PABackup.dbo.tCMFolderSecurity 
	FROM  tCMFolderSecurity (nolock), tCMFolder f (nolock)
	WHERE tCMFolderSecurity.CMFolderKey = f.CMFolderKey
	and   f.CompanyKey = @CompanyKey
	
	exec spTime ''tCMFolderSecurity'', @t output

	Print ''tColumnSet''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tColumnSet'')
	drop table PABackup.dbo.tColumnSet
	 
	Select * Into PABackup.dbo.tColumnSet 
	FROM tColumnSet (NOLOCK)
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tColumnSet'', @t output

	Print ''tColumnSetDetail''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tColumnSetDetail'')
	drop table PABackup.dbo.tColumnSetDetail
	 
	Select tColumnSetDetail.* Into PABackup.dbo.tColumnSetDetail 
	FROM tColumnSetDetail (NOLOCK)
		,tColumnSet b (NOLOCK)
	WHERE b.CompanyKey = @CompanyKey
	AND   tColumnSetDetail.ColumnSetKey = b.ColumnSetKey

	exec spTime ''tColumnSetDetail'', @t output

	Print ''tCompany''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompany'')
	drop table PABackup.dbo.tCompany
	 
	Select * Into PABackup.dbo.tCompany FROM tCompany WHERE CompanyKey = @CompanyKey or OwnerCompanyKey = @CompanyKey
	
	exec spTime ''tCompany'', @t output

	Print ''tCompanyMedia''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyMedia'')
	drop table PABackup.dbo.tCompanyMedia
	 
	Select * Into PABackup.dbo.tCompanyMedia FROM tCompanyMedia (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCompanyMedia'', @t output

	Print ''tCompanyMediaContact''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyMediaContact'')
	drop table PABackup.dbo.tCompanyMediaContact
	 
	Select tCompanyMediaContact.* Into PABackup.dbo.tCompanyMediaContact 
	FROM tCompanyMediaContact (NOLOCK)
		,tCompanyMedia b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tCompanyMediaContact.CompanyMediaKey = b.CompanyMediaKey
	
	exec spTime ''tCompanyMediaContact'', @t output
	 
    Print ''tCompanyMediaAttributeValue''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyMediaAttributeValue'')
	drop table PABackup.dbo.tCompanyMediaAttributeValue
	 
	Select tCompanyMediaAttributeValue.* Into PABackup.dbo.tCompanyMediaAttributeValue 
	FROM tCompanyMediaAttributeValue (NOLOCK)
		,tCompanyMedia b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tCompanyMediaAttributeValue.CompanyMediaKey = b.CompanyMediaKey
	
	exec spTime ''tCompanyMediaAttributeValue'', @t output	

	Print ''tCompanyMediaSpillMarket''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyMediaSpillMarket'')
	drop table PABackup.dbo.tCompanyMediaSpillMarket
	 
	Select tCompanyMediaSpillMarket.* Into PABackup.dbo.tCompanyMediaSpillMarket 
	FROM tCompanyMediaSpillMarket (NOLOCK)
		,tCompanyMedia b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tCompanyMediaSpillMarket.CompanyMediaKey = b.CompanyMediaKey

	exec spTime ''tCompanyMediaSpillMarket'', @t output

	Print ''tCompanyMediaVendor''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyMediaVendor'')
	drop table PABackup.dbo.tCompanyMediaVendor
	 
	Select tCompanyMediaVendor.* Into PABackup.dbo.tCompanyMediaVendor 
	FROM tCompanyMediaVendor (NOLOCK)
		,tCompanyMedia b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tCompanyMediaVendor.CompanyMediaKey = b.CompanyMediaKey

	exec spTime ''tCompanyMediaVendor'', @t output

	Print ''tCompanyMetrics''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyMetrics'')
	drop table PABackup.dbo.tCompanyMetrics
	 
	Select * Into PABackup.dbo.tCompanyMetrics FROM tCompanyMetrics (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCompanyMetrics'', @t output

	Print ''tCompanyType''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCompanyType'')
	drop table PABackup.dbo.tCompanyType
	 
	Select * Into PABackup.dbo.tCompanyType FROM tCompanyType (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCompanyType'', @t output

	Print ''tContactActivity''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tContactActivity'')
	drop table PABackup.dbo.tContactActivity
	 
	Select * Into PABackup.dbo.tContactActivity FROM tContactActivity (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tContactActivity'', @t output

	Print ''tContactDatabase''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tContactDatabase'')
	drop table PABackup.dbo.tContactDatabase
	 
	Select * Into PABackup.dbo.tContactDatabase FROM tContactDatabase (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tContactDatabase'', @t output

	Print ''tContactDatabaseAssignment''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tContactDatabaseAssignment'')
	drop table PABackup.dbo.tContactDatabaseAssignment
	 
	Select tContactDatabaseAssignment.* Into PABackup.dbo.tContactDatabaseAssignment 
	FROM tContactDatabaseAssignment (nolock), tContactDatabase cd (nolock)
	where tContactDatabaseAssignment.ContactDatabaseKey = cd.ContactDatabaseKey 
	and cd.CompanyKey = @CompanyKey 
	
	exec spTime ''tContactDatabaseAssignment'', @t output
		 
	Print ''tContactDatabaseUser''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tContactDatabaseUser'')
		drop table PABackup.dbo.tContactDatabaseUser
	 
	Select	tContactDatabaseUser.* Into PABackup.dbo.tContactDatabaseUser 
	FROM	tContactDatabaseUser (nolock), tContactDatabase cd (nolock)
	where	tContactDatabaseUser.ContactDatabaseKey = cd.ContactDatabaseKey 
	and		cd.CompanyKey = @CompanyKey
	
	exec spTime ''tContactDatabaseUser'', @t output

	Print ''tCrossProjectPredsErrors''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCrossProjectPredsErrors'')
		drop table PABackup.dbo.tCrossProjectPredsErrors
	 
	Select * Into PABackup.dbo.tCrossProjectPredsErrors FROM tCrossProjectPredsErrors (nolock) Where CompanyKey = @CompanyKey

	exec spTime ''tCrossProjectPredsErrors'', @t output

	Print ''tCrossProjectPredsQueue''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCrossProjectPredsQueue'')
		drop table PABackup.dbo.tCrossProjectPredsQueue
	 
	Select * Into PABackup.dbo.tCrossProjectPredsQueue FROM tCrossProjectPredsQueue (nolock) Where CompanyKey = @CompanyKey

	exec spTime ''tCrossProjectPredsQueue'', @t output

	Print ''tCurrency''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCurrency'')
		drop table PABackup.dbo.tCurrency
	 
	Select * Into PABackup.dbo.tCurrency FROM tCurrency (nolock)

	exec spTime ''tCurrency'', @t output

	Print ''tCurrencyCompany''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCurrencyCompany'')
		drop table PABackup.dbo.tCurrencyCompany
	 
	Select * Into PABackup.dbo.tCurrencyCompany FROM tCurrencyCompany (nolock)

	exec spTime ''tCurrencyCompany'', @t output

	Print ''tCurrencyRate''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tCurrencyRate'')
		drop table PABackup.dbo.tCurrencyRate
	 
	Select * Into PABackup.dbo.tCurrencyRate FROM tCurrencyRate (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tCurrencyRate'', @t output

	Print ''tDAClientFolder''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDAClientFolder'')
		drop table PABackup.dbo.tDAClientFolder
	 
	Select tDAClientFolder.* Into PABackup.dbo.tDAClientFolder 
	FROM tDAClientFolder (nolock), tProject p (nolock)
	where tDAClientFolder.ProjectKey = p.ProjectKey 
	and p.CompanyKey = @CompanyKey
	
	exec spTime ''tDAClientFolder'', @t output

	Print ''tDAFile''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDAFile'')
	drop table PABackup.dbo.tDAFile
	 
	Select	tDAFile.* Into PABackup.dbo.tDAFile 
	FROM	tDAFile (nolock), tDAFolder fol (nolock), tProject p (nolock)
	where	tDAFile.FolderKey = fol.FolderKey 
	and		fol.ProjectKey = p.ProjectKey 
	and		p.CompanyKey = @CompanyKey
	
	exec spTime ''tDAFile'', @t output

	Print ''tDAFileRight''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDAFileRight'')
	drop table PABackup.dbo.tDAFileRight
	 
	Select tDAFileRight.* Into PABackup.dbo.tDAFileRight 
	FROM tDAFileRight (nolock), tDAFile f (nolock), tDAFolder fol (nolock), tProject p (nolock)
	where tDAFileRight.FileKey = f.FileKey 
	and f.FolderKey = fol.FolderKey 
	and fol.ProjectKey = p.ProjectKey 
	and p.CompanyKey = @CompanyKey
	
	exec spTime ''tDAFileRight'', @t output

	Print ''tDAFileVersion''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDAFileVersion'')
	drop table PABackup.dbo.tDAFileVersion
	 
	Select tDAFileVersion.* Into PABackup.dbo.tDAFileVersion 
	FROM tDAFileVersion (nolock), tDAFile f (nolock), tDAFolder fol (nolock), tProject p (nolock)
	where tDAFileVersion.FileKey = f.FileKey 
	and f.FolderKey = fol.FolderKey 
	and fol.ProjectKey = p.ProjectKey 
	and p.CompanyKey = @CompanyKey
	
	exec spTime ''tDAFileVersion'', @t output

	Print ''tDAFolder''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDAFolder'')
	drop table PABackup.dbo.tDAFolder
	 
	Select	tDAFolder.* Into PABackup.dbo.tDAFolder 
	from	tDAFolder (nolock), tProject p (nolock)
	where	tDAFolder.ProjectKey = p.ProjectKey 
	and		p.CompanyKey = @CompanyKey
	
	exec spTime ''tDAFolder'', @t output

	Print ''tDAFolderRight''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDAFolderRight'')
	drop table PABackup.dbo.tDAFolderRight
	 
	Select tDAFolderRight.* Into PABackup.dbo.tDAFolderRight 
	FROM tDAFolderRight (nolock), tDAFolder fol (nolock), tProject p (nolock) 
	where tDAFolderRight.FolderKey = fol.FolderKey 
	and fol.ProjectKey = p.ProjectKey 
	and p.CompanyKey = @CompanyKey
	
	exec spTime ''tDAFolderRight'', @t output

	Print ''tDBLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDBLog'')
	drop table PABackup.dbo.tDBLog
	 
	Select tDBLog.* Into PABackup.dbo.tDBLog 
	FROM tDBLog (nolock), tUser u  (nolock)
	where tDBLog.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	
	exec spTime ''tDBLog'', @t output

	Print ''tDepartment''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDepartment'')
		drop table PABackup.dbo.tDepartment
	 
	Select * Into PABackup.dbo.tDepartment FROM tDepartment (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tDepartment'', @t output

	Print ''tDeliverableStatus''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDeliverableStatus'')
		drop table PABackup.dbo.tDeliverableStatus
	 
	Select * Into PABackup.dbo.tDeliverableStatus FROM tDeliverableStatus (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tDeliverableStatus'', @t output

	Print ''tDeliverableType''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDeliverableType'')
		drop table PABackup.dbo.tDeliverableType
	 
	Select * Into PABackup.dbo.tDeliverableType FROM tDeliverableType (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tDeliverableType'', @t output

	Print ''tDistributionGroup''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDistributionGroup'')
		drop table PABackup.dbo.tDistributionGroup
	 
	Select * Into PABackup.dbo.tDistributionGroup FROM tDistributionGroup (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tDistributionGroup'', @t output

	Print ''tDistributionGroupUser''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDistributionGroupUser'')
	drop table PABackup.dbo.tDistributionGroupUser
	 
	Select tDistributionGroupUser.* Into PABackup.dbo.tDistributionGroupUser
	FROM tDistributionGroupUser (NOLOCK)
	     ,tDistributionGroup b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tDistributionGroupUser.DistributionGroupKey = b.DistributionGroupKey
	
	exec spTime ''tDistributionGroupUser'', @t output
	 
	Print ''tDeposit''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tDeposit'')
	drop table PABackup.dbo.tDeposit
	 
	Select * Into PABackup.dbo.tDeposit FROM tDeposit (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tDeposit'', @t output

	Print ''tEmailError''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEmailError'')
		drop table PABackup.dbo.tEmailError
	
	Select * Into PABackup.dbo.tEmailError 
	From tEmailError (nolock) 
	Where CompanyKey = @CompanyKey 

	exec spTime ''tEmailError'', @t output

	Print ''tEmailOption''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEmailOption'')
		drop table PABackup.dbo.tEmailOption
	
	Select * Into PABackup.dbo.tEmailOption 
	From tEmailOption (nolock) 
	Where CompanyKey = @CompanyKey 

	exec spTime ''tEmailOption'', @t output

	Print ''tEmailSendLog''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEmailSendLog'')
		drop table PABackup.dbo.tEmailSendLog
	
	--Just select a recent amount of rows so the table gets created and if this is a migration some rows come over
	Select top 250 * Into PABackup.dbo.tEmailSendLog 
	From tEmailSendLog (nolock) 
	Where CompanyKey = @CompanyKey 
	Order By ActionDate Desc

	exec spTime ''tEmailSendLog'', @t output

	Print ''tEmailTemplateSection''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEmailTemplateSection'')
		drop table PABackup.dbo.tEmailTemplateSection
	
	Select tEmailTemplateSection.* Into PABackup.dbo.tEmailTemplateSection 
	From tEmailTemplateSection (nolock), tEmailTemplate (nolock) 
	Where tEmailTemplateSection.EmailTemplateKey = tEmailTemplate.EmailTemplateKey
	  and tEmailTemplate.CompanyKey = @CompanyKey 

	exec spTime ''tEmailTemplateSection'', @t output

	Print ''tEmailTemplate''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEmailTemplate'')
		drop table PABackup.dbo.tEmailTemplate
	
	Select * Into PABackup.dbo.tEmailTemplate 
	From tEmailTemplate (nolock)
	Where tEmailTemplate.CompanyKey = @CompanyKey 

	exec spTime ''tEmailTemplate'', @t output

	Print ''tEstimate''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimate'')
	drop table PABackup.dbo.tEstimate
	 
	Select tEstimate.* Into PABackup.dbo.tEstimate 
	FROM	tEstimate  (nolock)
	Where	tEstimate.CompanyKey = @CompanyKey 

	exec spTime ''tEstimate'', @t output

	Print ''tEstimateNotify''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateNotify'')
	drop table PABackup.dbo.tEstimateNotify
	 
	Select tEstimateNotify.* Into PABackup.dbo.tEstimateNotify 
	FROM tEstimateNotify (NOLOCK), tEstimate (NOLOCK) 
	Where tEstimateNotify.EstimateKey = tEstimate.EstimateKey 
	and	tEstimate.CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateNotify'', @t output
	
	Print ''tEstimateProject''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateProject'')
	drop table PABackup.dbo.tEstimateProject
	 
	Select tEstimateProject.* Into PABackup.dbo.tEstimateProject 
	FROM tEstimateProject (NOLOCK), tEstimate (NOLOCK) 
	Where tEstimateProject.EstimateKey = tEstimate.EstimateKey 
	and	tEstimate.CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateProject'', @t output
	
	Print ''tEstimateService''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateService'')
	drop table PABackup.dbo.tEstimateService
	 
	Select tEstimateService.* Into PABackup.dbo.tEstimateService 
	FROM tEstimateService (NOLOCK), tEstimate (NOLOCK) 
	Where tEstimateService.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateService'', @t output
	
	Print ''tEstimateTitle''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTitle'')
	drop table PABackup.dbo.tEstimateTitle
	 
	Select tEstimateTitle.* Into PABackup.dbo.tEstimateTitle 
	FROM tEstimateTitle (NOLOCK), tEstimate (NOLOCK) 
	Where tEstimateTitle.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateTitle'', @t output
	
	Print ''tEstimateTask''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTask'')
	drop table PABackup.dbo.tEstimateTask
	 
	Select tEstimateTask.* Into PABackup.dbo.tEstimateTask 
	FROM tEstimateTask  (nolock), tEstimate  (nolock)
	Where tEstimateTask.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.CompanyKey = @CompanyKey
	 
	exec spTime ''tEstimateTask'', @t output
	
	Print ''tEstimateTaskExpense''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskExpense'')
	drop table PABackup.dbo.tEstimateTaskExpense
	 
	Select tEstimateTaskExpense.* Into PABackup.dbo.tEstimateTaskExpense 
	FROM tEstimateTaskExpense (nolock), tEstimate e  (nolock)
	where tEstimateTaskExpense.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey
	 
	exec spTime ''tEstimateTaskExpense'', @t output
	
	Print ''tEstimateTaskExpenseOrder''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskExpenseOrder'')
	drop table PABackup.dbo.tEstimateTaskExpenseOrder
	 
	Select tEstimateTaskExpenseOrder.* Into PABackup.dbo.tEstimateTaskExpenseOrder 
	FROM tEstimateTaskExpenseOrder (nolock), tEstimateTaskExpense ete (nolock), tEstimate e  (nolock)
	where ete.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey
	and tEstimateTaskExpenseOrder.EstimateTaskExpenseKey = ete.EstimateTaskExpenseKey
	 
	exec spTime ''tEstimateTaskExpenseOrder'', @t output
	
	Print ''tEstimateTaskLabor''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskLabor'')
	drop table PABackup.dbo.tEstimateTaskLabor
	 
	Select tEstimateTaskLabor.* Into PABackup.dbo.tEstimateTaskLabor 
	FROM tEstimateTaskLabor (nolock), tEstimate e  (nolock)
	where tEstimateTaskLabor.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey

	exec spTime ''tEstimateTaskLabor'', @t output
	
	Print ''tEstimateTaskLaborLevel''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskLaborLevel'')
	drop table PABackup.dbo.tEstimateTaskLaborLevel
	 
	Select tEstimateTaskLaborLevel.* Into PABackup.dbo.tEstimateTaskLaborLevel 
	FROM tEstimateTaskLaborLevel  (nolock), tEstimate e  (nolock)
	where tEstimateTaskLaborLevel.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey

	exec spTime ''tEstimateTaskLaborLevel'', @t output
	
	Print ''tEstimateTaskLaborTitle''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskLaborTitle'')
	drop table PABackup.dbo.tEstimateTaskLaborTitle
	 
	Select tEstimateTaskLaborTitle.* Into PABackup.dbo.tEstimateTaskLaborTitle 
	FROM tEstimateTaskLaborTitle (nolock), tEstimate e  (nolock)
	where tEstimateTaskLaborTitle.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey

	exec spTime ''tEstimateTaskLaborTitle'', @t output
	
	Print ''tEstimateTaskAssignmentLabor''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskAssignmentLabor'')
	drop table PABackup.dbo.tEstimateTaskAssignmentLabor
	 
	Select tEstimateTaskAssignmentLabor.* Into PABackup.dbo.tEstimateTaskAssignmentLabor 
	FROM tEstimateTaskAssignmentLabor (nolock), tEstimate e  (nolock)
	where tEstimateTaskAssignmentLabor.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateTaskAssignmentLabor'', @t output
	
	Print ''tEstimateTaskTemp''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskTemp'')
	drop table PABackup.dbo.tEstimateTaskTemp
	 
	Select tEstimateTaskTemp.* Into PABackup.dbo.tEstimateTaskTemp 
	FROM tEstimateTaskTemp (nolock) , tProject p (nolock) 
	where tEstimateTaskTemp.ProjectKey = p.ProjectKey 
	and p.CompanyKey = @CompanyKey

	exec spTime ''tEstimateTaskTemp'', @t output
	
	Print ''tEstimateTaskTempPredecessor''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskTempPredecessor'')
	drop table PABackup.dbo.tEstimateTaskTempPredecessor
	 
	Select tEstimateTaskTempPredecessor.* Into PABackup.dbo.tEstimateTaskTempPredecessor 
	FROM tEstimateTaskTempPredecessor (nolock) , tTask t (nolock) , tProject p (nolock) 
	where tEstimateTaskTempPredecessor.TaskKey = t.TaskKey 
	and   t.ProjectKey = p.ProjectKey 
	and   p.CompanyKey = @CompanyKey
 
    exec spTime ''tEstimateTaskTempPredecessor'', @t output
	
	Print ''tEstimateTaskTempUser''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTaskTempUser'')
	drop table PABackup.dbo.tEstimateTaskTempUser
	 
	Select tEstimateTaskTempUser.* Into PABackup.dbo.tEstimateTaskTempUser 
	FROM tEstimateTaskTempUser, tTask t (nolock) , tProject p (nolock)  
	where tEstimateTaskTempUser.TaskKey = t.TaskKey 
	and   t.ProjectKey = p.ProjectKey 
	and   p.CompanyKey = @CompanyKey

	exec spTime ''tEstimateTaskTempUser'', @t output
	
	Print ''tEstimateTemplate''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateTemplate'')
	drop table PABackup.dbo.tEstimateTemplate
	 
	Select * Into PABackup.dbo.tEstimateTemplate FROM tEstimateTemplate (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateTemplate'', @t output
	
	Print ''tEstimateUser''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tEstimateUser'')
	drop table PABackup.dbo.tEstimateUser
	 
	Select tEstimateUser.* Into PABackup.dbo.tEstimateUser 
	FROM tEstimateUser (nolock), tEstimate e (nolock)
	where tEstimateUser.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey
	
	exec spTime ''tEstimateUser'', @t output
	
	Print ''tExpenseEnvelope''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tExpenseEnvelope'')
	drop table PABackup.dbo.tExpenseEnvelope
	 
	Select * Into PABackup.dbo.tExpenseEnvelope FROM tExpenseEnvelope (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tExpenseEnvelope'', @t output
	
	Print ''tExpenseReceipt''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tExpenseReceipt'')
	drop table PABackup.dbo.tExpenseReceipt
	 
	Select tExpenseReceipt.* Into PABackup.dbo.tExpenseReceipt 
	FROM tExpenseReceipt (nolock), tExpenseEnvelope (nolock) 
	Where tExpenseReceipt.ExpenseEnvelopeKey = tExpenseEnvelope.ExpenseEnvelopeKey 
	and tExpenseEnvelope.CompanyKey = @CompanyKey
	
	exec spTime ''tExpenseReceipt'', @t output
	
	Print ''tExpenseType''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tExpenseType'')
	drop table PABackup.dbo.tExpenseType
	 
	Select * Into PABackup.dbo.tExpenseType FROM tExpenseType (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tExpenseType'', @t output
	
	Print ''tFieldDef''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFieldDef'')
	drop table PABackup.dbo.tFieldDef
	 
	Select	* Into PABackup.dbo.tFieldDef 
	from	tFieldDef (nolock)
	where	OwnerEntityKey = @CompanyKey
	
	exec spTime ''tFieldDef'', @t output
	
	Print ''tFieldSet''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFieldSet'')
	drop table PABackup.dbo.tFieldSet
	 
	Select	* Into PABackup.dbo.tFieldSet 
	FROM	tFieldSet (nolock)
	WHERE	OwnerEntityKey = @CompanyKey
	and		AssociatedEntity != ''Forms''
	
	SET IDENTITY_INSERT PABackup.dbo.tFieldSet ON

	Insert	PABackup.dbo.tFieldSet (FieldSetKey, OwnerEntityKey, AssociatedEntity, FieldSetName, Active)
	Select	tFieldSet.FieldSetKey, tFieldSet.OwnerEntityKey, tFieldSet.AssociatedEntity, tFieldSet.FieldSetName, tFieldSet.Active
	FROM	tFieldSet (nolock), tFormDef fd (nolock)
	where	tFieldSet.AssociatedEntity = ''Forms''
	and		tFieldSet.OwnerEntityKey = fd.FormDefKey
	and		fd.CompanyKey = @CompanyKey 
	
	exec spTime ''tFieldSet'', @t output
	
	Print ''tFieldSetField''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFieldSetField'')
	drop table PABackup.dbo.tFieldSetField
	 
	Select	tFieldSetField.* Into PABackup.dbo.tFieldSetField
	FROM	tFieldSetField (nolock) , tFieldDef fd (nolock)
	where	tFieldSetField.FieldDefKey = fd.FieldDefKey
	and		fd.OwnerEntityKey = @CompanyKey
	 
	exec spTime ''tFieldSetField'', @t output
	
	Print ''tFieldValue''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFieldValue'')
	drop table PABackup.dbo.tFieldValue
	 
	Select	tFieldValue.* Into PABackup.dbo.tFieldValue 
	FROM	tFieldValue (nolock), tFieldDef fd (nolock)
	where	tFieldValue.FieldDefKey = fd.FieldDefKey
	and		fd.OwnerEntityKey = @CompanyKey
	

	exec spTime ''tFieldValue'', @t output
	
	Print ''tFlatFile''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFlatFile'')
	drop table PABackup.dbo.tFlatFile
	 
	Select * Into PABackup.dbo.tFlatFile FROM tFlatFile (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tFlatFile'', @t output
	
	Print ''tFlatFileDetail''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFlatFileDetail'')
	drop table PABackup.dbo.tFlatFileDetail
	 
	Select tFlatFileDetail.* Into PABackup.dbo.tFlatFileDetail 
	FROM tFlatFileDetail (nolock), tFlatFile (nolock) 
	Where tFlatFileDetail.FlatFileKey = tFlatFile.FlatFileKey 
	and tFlatFile.CompanyKey = @CompanyKey
	
	exec spTime ''tFlatFileDetail'', @t output
	
	Print ''tFinancialInstitution''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFinancialInstitution'')
	drop table PABackup.dbo.tFinancialInstitution
	 
	Select * Into PABackup.dbo.tFinancialInstitution FROM tFinancialInstitution (nolock) 
	
	exec spTime ''tFinancialInstitution'', @t output
	
	Print ''tForm''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tForm'')
	drop table PABackup.dbo.tForm
	 
	Select * Into PABackup.dbo.tForm FROM tForm (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tForm'', @t output
	
	Print ''tFormDef''

	if exists (select * from PABackup.dbo.sysobjects where name=''tFormDef'')
	drop table PABackup.dbo.tFormDef
	 
	Select * Into PABackup.dbo.tFormDef FROM tFormDef WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tFormDef'', @t output
	
	Print ''tFormDefSecurityGroup''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFormDefSecurityGroup'')
	drop table PABackup.dbo.tFormDefSecurityGroup
	 
	Select	tFormDefSecurityGroup.* Into PABackup.dbo.tFormDefSecurityGroup 
	FROM	tFormDefSecurityGroup (nolock), tFormDef fd (nolock)
	where	tFormDefSecurityGroup.FormDefKey = fd.FormDefKey
	and		fd.CompanyKey = @CompanyKey
	
	exec spTime ''tFormDefSecurityGroup'', @t output
	
	Print ''tFormSubscription''
	if exists (select * from PABackup.dbo.sysobjects where name=''tFormSubscription'')
	drop table PABackup.dbo.tFormSubscription
	 
	Select tFormSubscription.* Into PABackup.dbo.tFormSubscription 
	FROM tFormSubscription (nolock), tUser  (nolock)
	Where tFormSubscription.UserKey = tUser.UserKey 
	and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)	 

	exec spTime ''tFormSubscription'', @t output
	
	Print ''tFormTemplate''
	if exists (select * from PABackup.dbo.sysobjects where name=''tFormTemplate'')
	drop table PABackup.dbo.tFormTemplate
	
	Select * Into PABackup.dbo.tFormTemplate FROM tFormTemplate (nolock) WHERE CompanyKey = @CompanyKey
	

	exec spTime ''tFormTemplate'', @t output
	
	Print ''tForecast''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tForecast'')
	drop table PABackup.dbo.tForecast
	 
	Select * Into PABackup.dbo.tForecast FROM tForecast (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tForecast'', @t output
	
	Print ''tForecastDetail''

	if exists (select * from PABackup.dbo.sysobjects where name=''tForecastDetail'')
	drop table PABackup.dbo.tForecastDetail
	 
	Select	tForecastDetail.* Into PABackup.dbo.tForecastDetail 
	FROM	tForecastDetail (nolock), tForecast f (nolock)
	where	tForecastDetail.ForecastKey = f.ForecastKey
	and		f.CompanyKey = @CompanyKey

	exec spTime ''tForecastDetail'', @t output
	
	Print ''tForecastDetailItem''

	if exists (select * from PABackup.dbo.sysobjects where name=''tForecastDetailItem'')
	drop table PABackup.dbo.tForecastDetailItem
	 
	Select	tForecastDetailItem.* Into PABackup.dbo.tForecastDetailItem 
	FROM	tForecastDetailItem (nolock), tForecastDetail fd (nolock), tForecast f (nolock)
	where	fd.ForecastKey = f.ForecastKey
	and		f.CompanyKey = @CompanyKey
	and     tForecastDetailItem.ForecastDetailKey = fd.ForecastDetailKey

	exec spTime ''tForecastDetailItem'', @t output
	
	Print ''tFormDefSecurityGroup''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tFormDefSecurityGroup'')
	drop table PABackup.dbo.tFormDefSecurityGroup
	 
	Select	tFormDefSecurityGroup.* Into PABackup.dbo.tFormDefSecurityGroup 
	FROM	tFormDefSecurityGroup (nolock), tFormDef fd (nolock)
	where	tFormDefSecurityGroup.FormDefKey = fd.FormDefKey
	and		fd.CompanyKey = @CompanyKey


	exec spTime ''tFormDefSecurityGroup'', @t output
	
	Print ''tGLAccount''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLAccount'')
	drop table PABackup.dbo.tGLAccount
	 
	Select * Into PABackup.dbo.tGLAccount FROM tGLAccount (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tGLAccount'', @t output
	
	Print ''tGLAccountRec''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLAccountRec'')
	drop table PABackup.dbo.tGLAccountRec
	 
	Select * Into PABackup.dbo.tGLAccountRec FROM tGLAccountRec (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tGLAccountRec'', @t output
	
	Print ''tGLAccountRecDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLAccountRecDetail'')
	drop table PABackup.dbo.tGLAccountRecDetail
	 
	Select tGLAccountRecDetail.* Into PABackup.dbo.tGLAccountRecDetail 
	FROM tGLAccountRecDetail (nolock), tGLAccountRec glar (nolock) 
	where tGLAccountRecDetail.GLAccountRecKey = glar.GLAccountRecKey 
	and glar.CompanyKey = @CompanyKey
	
	exec spTime ''tGLAccountRecDetail'', @t output
	
	Print ''tGLAccountMultiCompanyPayments''
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLAccountMultiCompanyPayments'')
	drop table PABackup.dbo.tGLAccountMultiCompanyPayments
	 
	Select * Into PABackup.dbo.tGLAccountMultiCompanyPayments FROM tGLAccountMultiCompanyPayments (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tGLAccountMultiCompanyPayments'', @t output
	
	Print ''tGLAccountRecUnmatched''
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLAccountRecUnmatched'')
	drop table PABackup.dbo.tGLAccountRecUnmatched
	 
	Select * Into PABackup.dbo.tGLAccountRecUnmatched FROM tGLAccountRecUnmatched (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tGLAccountRecUnmatched'', @t output
	
	Print ''tGLAccountUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLAccountUser'')
	drop table PABackup.dbo.tGLAccountUser
	 
	Select tGLAccountUser.* Into PABackup.dbo.tGLAccountUser 
	FROM tGLAccountUser (nolock), tGLAccount gla  (nolock)
	where tGLAccountUser.GLAccountKey = gla.GLAccountKey 
	and gla.CompanyKey = @CompanyKey
	
	exec spTime ''tGLAccountUser'', @t output
	
	Print ''tGLBudget''
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLBudget'')
	drop table PABackup.dbo.tGLBudget
	 
	Select * Into PABackup.dbo.tGLBudget FROM tGLBudget (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tGLBudget'', @t output
	
	Print ''tGLBudgetDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLBudgetDetail'')
	drop table PABackup.dbo.tGLBudgetDetail
	 
	Select tGLBudgetDetail.* Into PABackup.dbo.tGLBudgetDetail 
	FROM tGLBudgetDetail (nolock), tGLAccount gla  (nolock)
	where tGLBudgetDetail.GLAccountKey = gla.GLAccountKey 
	and gla.CompanyKey = @CompanyKey
	
	exec spTime ''tGLBudgetDetail'', @t output
	
	Print ''tGLCompany''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLCompany'')
	drop table PABackup.dbo.tGLCompany
	 
	Select tGLCompany.* Into PABackup.dbo.tGLCompany 
	FROM tGLCompany (nolock)
	where tGLCompany.CompanyKey = @CompanyKey
	
	exec spTime ''tGLCompany'', @t output
	
	Print ''tGLCompanyAccess''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLCompanyAccess'')
		drop table PABackup.dbo.tGLCompanyAccess
	 
	Select tGLCompanyAccess.* Into PABackup.dbo.tGLCompanyAccess 
	FROM tGLCompanyAccess (nolock)
	where tGLCompanyAccess.CompanyKey = @CompanyKey

	exec spTime ''tGLCompanyAccess'', @t output
	
	Print ''tGLCompanyMap''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tGLCompanyMap'')
		drop table PABackup.dbo.tGLCompanyMap
	 
	Select tGLCompanyMap.* Into PABackup.dbo.tGLCompanyMap 
	FROM tGLCompanyMap (nolock), tGLCompany (nolock)
	where tGLCompanyMap.TargetGLCompanyKey = tGLCompany.GLCompanyKey 
	and   tGLCompany.CompanyKey = @CompanyKey
	
	exec spTime ''tGLCompanyMap'', @t output
	
	Print ''tGoal''

	if exists (select * from PABackup.dbo.sysobjects where name=''tGoal'')
		drop table PABackup.dbo.tGoal

	Select tGoal.* 
	Into PABackup.dbo.tGoal 
	From tGoal (nolock)
		Left Join tUser (nolock) on tGoal.Entity = ''tUser'' and tGoal.EntityKey = tUser.UserKey
	Where tUser.CompanyKey = @CompanyKey

	exec spTime ''tGoal'', @t output

	Print ''tGridColSet''

	if exists (select * from PABackup.dbo.sysobjects where name=''tGridColSet'')
		drop table PABackup.dbo.tGridColSet

	Select tGridColSet.* 
	Into PABackup.dbo.tGridColSet 
	From tGridColSet (nolock)
	Where CompanyKey = @CompanyKey

	exec spTime ''tGridColSet'', @t output

	Print ''tGridColSetSecurity''

	if exists (select * from PABackup.dbo.sysobjects where name=''tGridColSetSecurity'')
		drop table PABackup.dbo.tGridColSetSecurity

	Select tGridColSetSecurity.* 
	Into PABackup.dbo.tGridColSetSecurity 
	From tGridColSetSecurity (nolock)
		Left Join tSecurityGroup (nolock) on tGridColSetSecurity.SecurityGroupKey = tSecurityGroup.SecurityGroupKey
	Where tSecurityGroup.CompanyKey = @CompanyKey

	exec spTime ''tGridColSetSecurity'', @t output

	Print ''tImport''

	if exists (select * from PABackup.dbo.sysobjects where name=''tImport'')
		drop table PABackup.dbo.tImport
	 
	Select * Into PABackup.dbo.tImport FROM tImport (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tImport'', @t output
	
	Print ''tImportExport''

	if exists (select * from PABackup.dbo.sysobjects where name=''tImportExport'')
		drop table PABackup.dbo.tImportExport
	 
	Select * Into PABackup.dbo.tImportExport FROM tImportExport (nolock)
	
	exec spTime ''tImportExport'', @t output

	Print ''tImportExportDetail''

	if exists (select * from PABackup.dbo.sysobjects where name=''tImportExportDetail'')
		drop table PABackup.dbo.tImportExportDetail
	 
	Select * Into PABackup.dbo.tImportExportDetail FROM tImportExportDetail (nolock)
	
	exec spTime ''tImportExportDetail'', @t output

	Print ''tImportExportParms''

	if exists (select * from PABackup.dbo.sysobjects where name=''tImportExportParms'')
		drop table PABackup.dbo.tImportExportParms
	 
	Select * Into PABackup.dbo.tImportExportParms FROM tImportExportParms (nolock)
	
	exec spTime ''tImportExportParms'', @t output

	Print ''tImportExportSamples''

	if exists (select * from PABackup.dbo.sysobjects where name=''tImportExportSamples'')
		drop table PABackup.dbo.tImportExportSamples
	 
	Select * Into PABackup.dbo.tImportExportSamples FROM tImportExportSamples (nolock)
	
	exec spTime ''tImportExportSamples'', @t output

	Print ''tInvoice''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoice'')
		drop table PABackup.dbo.tInvoice
	 
	Select * Into PABackup.dbo.tInvoice FROM tInvoice (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tInvoice'', @t output
	
	Print ''tInvoiceAdvanceBill''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceAdvanceBill'')
		drop table PABackup.dbo.tInvoiceAdvanceBill
	 
	Select tInvoiceAdvanceBill.* Into PABackup.dbo.tInvoiceAdvanceBill 
	FROM tInvoiceAdvanceBill (nolock), tInvoice i  (nolock)
	where tInvoiceAdvanceBill.InvoiceKey = i.InvoiceKey 
	and i.CompanyKey = @CompanyKey

	exec spTime ''tInvoiceAdvanceBill'', @t output
	
	Print ''tInvoiceAdvanceBillSale''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceAdvanceBillSale'')
		drop table PABackup.dbo.tInvoiceAdvanceBillSale
	 
	Select tInvoiceAdvanceBillSale.* Into PABackup.dbo.tInvoiceAdvanceBillSale 
	FROM tInvoiceAdvanceBillSale (nolock), tInvoice i  (nolock)
	where tInvoiceAdvanceBillSale.InvoiceKey = i.InvoiceKey 
	and i.CompanyKey = @CompanyKey

	exec spTime ''tInvoiceAdvanceBillSale'', @t output
	
	Print ''tInvoiceAdvanceBillTax''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceAdvanceBillTax'')
		drop table PABackup.dbo.tInvoiceAdvanceBillTax
	 
	Select tInvoiceAdvanceBillTax.* Into PABackup.dbo.tInvoiceAdvanceBillTax 
	FROM tInvoiceAdvanceBillTax (nolock), tInvoice i  (nolock)
	where tInvoiceAdvanceBillTax.InvoiceKey = i.InvoiceKey 
	and i.CompanyKey = @CompanyKey
	
	exec spTime ''tInvoiceAdvanceBillTax'', @t output
	
	Print ''tInvoiceCredit''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceCredit'')
		drop table PABackup.dbo.tInvoiceCredit
	 
	Select	tInvoiceCredit.* Into PABackup.dbo.tInvoiceCredit 
	FROM	tInvoiceCredit (nolock), tInvoice  (nolock)
	Where	tInvoiceCredit.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey
	
	exec spTime ''tInvoiceCredit'', @t output
	
	Print ''tInvoiceLine''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceLine'')
		drop table PABackup.dbo.tInvoiceLine
	 
	Select	tInvoiceLine.* Into PABackup.dbo.tInvoiceLine 
	FROM	tInvoiceLine (nolock) , tInvoice (NOLOCK)
	Where	tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey

	exec spTime ''tInvoiceLine'', @t output
	
	Print ''tInvoiceLineTax''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceLineTax'')
		drop table PABackup.dbo.tInvoiceLineTax
	 
	Select	tInvoiceLineTax.* Into PABackup.dbo.tInvoiceLineTax 
	FROM	tInvoiceLineTax (NOLOCK), tInvoiceLine (NOLOCK), tInvoice (NOLOCK) 
	Where	tInvoiceLineTax.InvoiceLineKey = tInvoiceLine.InvoiceLineKey
	and     tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey
	
	exec spTime ''tInvoiceLineTax'', @t output
	
	Print ''tInvoiceSummary''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceSummary'')
		drop table PABackup.dbo.tInvoiceSummary
	 
	Select	tInvoiceSummary.* Into PABackup.dbo.tInvoiceSummary 
	FROM	tInvoiceSummary (nolock) , tInvoice (NOLOCK)
	Where	tInvoiceSummary.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey
	
	exec spTime ''tInvoiceSummary'', @t output
	
	Print ''tInvoiceSummaryTitle''
	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceSummaryTitle'')
	drop table PABackup.dbo.tInvoiceSummaryTitle
	 
	Select	tInvoiceSummaryTitle.* Into PABackup.dbo.tInvoiceSummaryTitle 
	FROM	tInvoiceSummaryTitle (nolock) , tInvoice (NOLOCK)
	Where	tInvoiceSummaryTitle.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey

	exec spTime ''tInvoiceSummaryTitle'', @t output
	
	Print ''tInvoiceTax''
	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceTax'')
	drop table PABackup.dbo.tInvoiceTax
	 
	Select	tInvoiceTax.* Into PABackup.dbo.tInvoiceTax 
	FROM	tInvoiceTax (nolock) , tInvoice (nolock) 
	Where	tInvoiceTax.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey
	
	exec spTime ''tInvoiceTax'', @t output
	
	Print ''tInvoiceTaxAvalara''

	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceTaxAvalara'')
		drop table PABackup.dbo.tInvoiceTaxAvalara
	 
	Select	tInvoiceTaxAvalara.* Into PABackup.dbo.tInvoiceTaxAvalara 
	FROM	tInvoiceTaxAvalara (nolock) , tInvoice (NOLOCK)
	Where	tInvoiceTaxAvalara.InvoiceKey = tInvoice.InvoiceKey 
	and		tInvoice.CompanyKey = @CompanyKey

	exec spTime ''tInvoiceTaxAvalara'', @t output

	Print ''tInvoiceTemplate''
	if exists (select * from PABackup.dbo.sysobjects where name=''tInvoiceTemplate'')
	drop table PABackup.dbo.tInvoiceTemplate
	 
	Select * Into PABackup.dbo.tInvoiceTemplate FROM tInvoiceTemplate (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tInvoiceTemplate'', @t output
	
	Print ''tISCI''
	if exists (select * from PABackup.dbo.sysobjects where name=''tISCI'')
	drop table PABackup.dbo.tISCI
	 
	Select tISCI.* Into PABackup.dbo.tISCI 
	FROM tISCI (nolock), tProject (nolock) 
	Where tISCI.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tISCI'', @t output
	
	Print ''tItem''
	if exists (select * from PABackup.dbo.sysobjects where name=''tItem'')
	drop table PABackup.dbo.tItem
	 
	Select * Into PABackup.dbo.tItem FROM tItem (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tItem'', @t output
	
	Print ''tItemRateSheet''
	if exists (select * from PABackup.dbo.sysobjects where name=''tItemRateSheet'')
	drop table PABackup.dbo.tItemRateSheet
	 
	Select * Into PABackup.dbo.tItemRateSheet FROM tItemRateSheet (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tItemRateSheet'', @t output
	
	Print ''tItemRateSheetDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tItemRateSheetDetail'')
	drop table PABackup.dbo.tItemRateSheetDetail
	 
	Select tItemRateSheetDetail.* Into PABackup.dbo.tItemRateSheetDetail 
	FROM tItemRateSheetDetail (nolock), tItemRateSheet ir (nolock)
	where tItemRateSheetDetail.ItemRateSheetKey = ir.ItemRateSheetKey 
	and ir.CompanyKey = @CompanyKey
	
	exec spTime ''tItemRateSheetDetail'', @t output
	
	Print ''tJournalEntry''
	if exists (select * from PABackup.dbo.sysobjects where name=''tJournalEntry'')
	drop table PABackup.dbo.tJournalEntry
	 
	Select * Into PABackup.dbo.tJournalEntry FROM tJournalEntry (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tJournalEntry'', @t output
	
	Print ''tJournalEntryDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tJournalEntryDetail'')
	drop table PABackup.dbo.tJournalEntryDetail
	 
	Select tJournalEntryDetail.* Into PABackup.dbo.tJournalEntryDetail 
	FROM tJournalEntryDetail (nolock) , tJournalEntry je (nolock) 
	where tJournalEntryDetail.JournalEntryKey = je.JournalEntryKey 
	and je.CompanyKey = @CompanyKey

	exec spTime ''tJournalEntryDetail'', @t output
	
	Print ''tLab''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLab'')
	drop table PABackup.dbo.tLab
	 
	Select * Into PABackup.dbo.tLab FROM tLab (nolock) 

	exec spTime ''tLab'', @t output
	
	Print ''tLabBeta''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLabBeta'')
	drop table PABackup.dbo.tLabBeta
	 
	Select * Into PABackup.dbo.tLabBeta FROM tLabBeta (nolock) where CompanyKey = @CompanyKey 
	
	exec spTime ''tLabBeta'', @t output
	
	Print ''tLabCompany''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLabCompany'')
	drop table PABackup.dbo.tLabCompany
	 
	Select * Into PABackup.dbo.tLabCompany FROM tLabCompany  (nolock) where CompanyKey = @CompanyKey 
	
	exec spTime ''tLabCompany'', @t output
	
	Print ''tLaborBudget''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLaborBudget'')
	drop table PABackup.dbo.tLaborBudget
	 
	Select * Into PABackup.dbo.tLaborBudget FROM tLaborBudget (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tLaborBudget'', @t output
	
	Print ''tLaborBudgetDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLaborBudgetDetail'')
	drop table PABackup.dbo.tLaborBudgetDetail
	 
	Select tLaborBudgetDetail.* Into PABackup.dbo.tLaborBudgetDetail 
	FROM tLaborBudgetDetail (nolock), tLaborBudget lb  (nolock)
	where tLaborBudgetDetail.LaborBudgetKey = lb.LaborBudgetKey 
	and lb.CompanyKey = @CompanyKey
	
	exec spTime ''tLaborBudgetDetail'', @t output
	
	Print ''tLayout''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLayout'')
	drop table PABackup.dbo.tLayout
	 
	Select * Into PABackup.dbo.tLayout FROM tLayout (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tLayout'', @t output
	
	Print ''tLayoutBilling''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLayoutBilling'')
	drop table PABackup.dbo.tLayoutBilling
	 
	Select tLayoutBilling.* Into PABackup.dbo.tLayoutBilling 
	FROM tLayoutBilling (nolock) , tLayout l (nolock) 
	where tLayoutBilling.LayoutKey = l.LayoutKey 
	and l.CompanyKey = @CompanyKey

	exec spTime ''tLayoutBilling'', @t output
	
	Print ''tLayoutReport''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLayoutReport'')
	drop table PABackup.dbo.tLayoutReport
	 
	Select tLayoutReport.* Into PABackup.dbo.tLayoutReport 
	FROM tLayoutReport (nolock) , tLayout l (nolock) 
	where tLayoutReport.LayoutKey = l.LayoutKey 
	and l.CompanyKey = @CompanyKey

	exec spTime ''tLayoutReport'', @t output
	
	Print ''tLayoutItems''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLayoutItems'')
	drop table PABackup.dbo.tLayoutItems
	 
	Select tLayoutItems.* Into PABackup.dbo.tLayoutItems 
	FROM tLayoutItems (nolock) , tLayoutReport (nolock) , tLayout l (nolock)  
	where tLayoutItems.LayoutReportKey = tLayoutReport.LayoutReportKey 
	and tLayoutReport.LayoutKey = l.LayoutKey 
	and l.CompanyKey = @CompanyKey

	exec spTime ''tLayoutItems'', @t output
	
	Print ''tLayoutSection''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLayoutSection'')
	drop table PABackup.dbo.tLayoutSection
	 
	Select tLayoutSection.* Into PABackup.dbo.tLayoutSection 
	FROM tLayoutSection (nolock) , tLayoutReport (nolock) , tLayout l (nolock) 
	where tLayoutSection.LayoutReportKey = tLayoutReport.LayoutReportKey 
	and tLayoutReport.LayoutKey = l.LayoutKey 
	and l.CompanyKey = @CompanyKey

	exec spTime ''tLayoutSection'', @t output
	
	Print ''tLead''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLead'')
	drop table PABackup.dbo.tLead
	 
	Select * Into PABackup.dbo.tLead FROM tLead (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tLead'', @t output
	
	Print ''tLeadStageHistory''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLeadStageHistory'')
	drop table PABackup.dbo.tLeadStageHistory
	 
	Select tLeadStageHistory.* Into PABackup.dbo.tLeadStageHistory 
	FROM tLeadStageHistory (nolock), tLead l  (nolock)
	where tLeadStageHistory.LeadKey = l.LeadKey 
	and l.CompanyKey = @CompanyKey
	 
	exec spTime ''tLeadStageHistory'', @t output
	
	Print ''tLeadOutcome''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLeadOutcome'')
	drop table PABackup.dbo.tLeadOutcome
	 
	Select * Into PABackup.dbo.tLeadOutcome FROM tLeadOutcome (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tLeadOutcome'', @t output
	
	Print ''tLeadStage''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLeadStage'')
	drop table PABackup.dbo.tLeadStage
	 
	Select * Into PABackup.dbo.tLeadStage FROM tLeadStage (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime '''', @t output
	
	Print ''tLeadStatus''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLeadStatus'')
	drop table PABackup.dbo.tLeadStatus
	 
	Select * Into PABackup.dbo.tLeadStatus FROM tLeadStatus (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tLeadStatus'', @t output
	
	Print ''tLeadUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLeadUser'')
	drop table PABackup.dbo.tLeadUser
	 
	Select tLeadUser.* Into PABackup.dbo.tLeadUser 
	FROM tLeadUser (nolock), tLead l  (nolock)
	where tLeadUser.LeadKey = l.LeadKey 
	and l.CompanyKey = @CompanyKey

	exec spTime ''tLeadUser'', @t output
	
	Print ''tLevelHistory : tCompany''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLevelHistory'')
	drop table PABackup.dbo.tLevelHistory
	 
	Select tLevelHistory.* Into PABackup.dbo.tLevelHistory 
	FROM tLevelHistory (nolock), tCompany c  (nolock)
	where tLevelHistory.Entity = ''tCompany''
	and   tLevelHistory.EntityKey = c.CompanyKey 
	and isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey
	
	exec spTime ''tLevelHistory : tCompany'', @t output
	
	Print ''tLevelHistory : tLead''
	
	Insert PABackup.dbo.tLevelHistory 
	Select tLevelHistory.*  
	FROM tLevelHistory (nolock), tLead l  (nolock)
	where tLevelHistory.Entity = ''tLead''
	and   tLevelHistory.EntityKey = l.LeadKey 
	and l.CompanyKey = @CompanyKey
	
	exec spTime ''tLevelHistory : tLead'', @t output
	
	Print ''tLevelHistory : tUser''
	
	Insert PABackup.dbo.tLevelHistory 
	Select tLevelHistory.*  
	FROM tLevelHistory (nolock), tUser u  (nolock)
	where tLevelHistory.Entity = ''tUser''
	and   tLevelHistory.EntityKey = u.UserKey 
	and isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
	
	exec spTime ''tLevelHistory : tUser'', @t output
	
	Print ''tLink''
	if exists (select * from PABackup.dbo.sysobjects where name=''tLink'')
	drop table PABackup.dbo.tLink
	 
	exec spTime ''tLink'', @t output
	
	Print ''tLink: ApprovalItem''
	Select	tLink.* Into PABackup.dbo.tLink 
	FROM	tLink (nolock), tApprovalItem ai (nolock) , tApproval a (nolock) , tProject p (nolock) 
	where	tLink.AssociatedEntity = ''ApprovalItem''
	and		tLink.EntityKey = ai.ApprovalItemKey
	and		ai.ApprovalKey = a.ApprovalKey
	and		a.ProjectKey = p.ProjectKey
	and		p.CompanyKey = @CompanyKey

	exec spTime ''tApprovalItem'', @t output
	
	Print ''tLink: Note''
	Insert	PABackup.dbo.tLink
	Select	tLink.* 
	FROM	tLink (nolock), tNote n  (nolock)
	where	tLink.AssociatedEntity = ''Note''
	and		tLink.EntityKey = n.NoteKey
	and     n.Entity = ''Company''
	and		n.EntityKey = @CompanyKey
	

	exec spTime ''tLink: Note'', @t output
	
	Print ''tLink: Lead''
	Insert	PABackup.dbo.tLink
	Select	tLink.*
	FROM	tLink (nolock), tLead ld (nolock)
	where	tLink.AssociatedEntity = ''Lead''
	and		tLink.EntityKey = ld.LeadKey
	and		ld.CompanyKey = @CompanyKey

	exec spTime ''tLink: Lead'', @t output
	
	Print ''tLink: Forms''
	Insert	PABackup.dbo.tLink
	Select	tLink.*
	FROM	tLink (nolock), tForm f (nolock)
	where	tLink.AssociatedEntity = ''Forms''
	and		tLink.EntityKey = f.FormKey
	and		f.CompanyKey = @CompanyKey

	exec spTime ''tLink: Forms'', @t output
	
	Print ''tMailing''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMailing'')
	drop table PABackup.dbo.tMailing
	 
	Select * Into PABackup.dbo.tMailing FROM tMailing (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tMailing'', @t output
	
	Print ''tMailingSetup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMailingSetup'')
	drop table PABackup.dbo.tMailingSetup
	 
	Select * Into PABackup.dbo.tMailingSetup FROM tMailingSetup (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tMailingSetup'', @t output
	
	Print ''tMarketingList''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMarketingList'')
	drop table PABackup.dbo.tMarketingList

	Select * Into PABackup.dbo.tMarketingList FROM tMarketingList (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tMarketingList'', @t output
	
	Print ''tMarketingListList''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMarketingListList'')
	drop table PABackup.dbo.tMarketingListList
	 
	Select tMarketingListList.* Into PABackup.dbo.tMarketingListList 
	FROM tMarketingListList (NOLOCK)
	     ,tMarketingList b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tMarketingListList.MarketingListKey = b.MarketingListKey

	exec spTime ''tMarketingListList'', @t output
	
	Print ''tMarketingListListDeleteLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMarketingListListDeleteLog'')
	drop table PABackup.dbo.tMarketingListListDeleteLog

	Select * Into PABackup.dbo.tMarketingListListDeleteLog FROM tMarketingListListDeleteLog (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tMarketingListListDeleteLog'', @t output
	
	Print ''tMasterTask''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMasterTask'')
	drop table PABackup.dbo.tMasterTask
	 
	Select * Into PABackup.dbo.tMasterTask FROM tMasterTask (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tMasterTask'', @t output
	
	Print ''tMasterTaskAssignment''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMasterTaskAssignment'')
	drop table PABackup.dbo.tMasterTaskAssignment
	 
	Select tMasterTaskAssignment.* Into PABackup.dbo.tMasterTaskAssignment 
	FROM tMasterTaskAssignment (NOLOCK)
	     ,tMasterTask b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tMasterTaskAssignment.MasterTaskKey = b.MasterTaskKey
	
	exec spTime ''tMasterTaskAssignment'', @t output
	
	Print ''tMobileMenu''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMobileMenu'')
	drop table PABackup.dbo.tMobileMenu
	 
	Select * Into PABackup.dbo.tMobileMenu FROM tMobileMenu  (nolock)
	
	exec spTime ''tMobileMenu'', @t output
	
	Print ''tMobilSearch''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMobileSearch'')
	drop table PABackup.dbo.tMobileSearch 
	 
	Select * Into PABackup.dbo.tMobileSearch 
	FROM tMobileSearch  (nolock)
	where CompanyKey is null or CompanyKey = @CompanyKey

	exec spTime ''tMobileSearch'', @t output
	
	Print ''tMobilSearchCondition''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMobileSearchCondition'')
	drop table PABackup.dbo.tMobileSearchCondition
	 
	Select tMobileSearchCondition.* Into PABackup.dbo.tMobileSearchCondition 
	FROM tMobileSearch (nolock) , tMobileSearchCondition (nolock)  
	where (tMobileSearch.CompanyKey is null or tMobileSearch.CompanyKey = @CompanyKey)
	and   tMobileSearchCondition.MobileSearchKey = tMobileSearch.MobileSearchKey 
	
	exec spTime ''tMobileSearchCondition'', @t output
	
	Print ''tMobileSearchDefault''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMobileSearchDefault'')
	drop table PABackup.dbo.tMobileSearchDefault
	 
	Select * Into PABackup.dbo.tMobileSearchDefault 
	FROM tMobileSearchDefault (nolock) 
	where CompanyKey is null or CompanyKey = @CompanyKey

	exec spTime ''tMobileSearchDefault'', @t output
	
	Print ''tMediaClientLink''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaClientLink'')
	drop table PABackup.dbo.tMediaClientLink
	 
	Select * Into PABackup.dbo.tMediaClientLink 
	FROM tMediaClientLink (NOLOCK), tCompany b (NOLOCK) 
	WHERE isnull(b.OwnerCompanyKey,b.CompanyKey) = @CompanyKey
	AND   b.CompanyKey =  tMediaClientLink.ClientKey

	exec spTime ''tMediaClientLink'', @t output
	
	Print ''tMediaEstimate''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaEstimate'')
	drop table PABackup.dbo.tMediaEstimate
	 
	Select * Into PABackup.dbo.tMediaEstimate FROM tMediaEstimate (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tMediaEstimate'', @t output
	
	Print ''tMediaRevisionReason''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaRevisionReason'')
	drop table PABackup.dbo.tMediaRevisionReason
	 
	Select * Into PABackup.dbo.tMediaRevisionReason FROM tMediaRevisionReason (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	
	exec spTime ''tMediaRevisionReason'', @t output
	
	Print ''tMediaMarket''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaMarket'')
	drop table PABackup.dbo.tMediaMarket
	 
	Select * Into PABackup.dbo.tMediaMarket FROM tMediaMarket (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tMediaMarket'', @t output
	
	----------------------------------------

	Print ''tMediaPlan''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlan'')
	drop table PABackup.dbo.tMediaPlan
	 
	Select * Into PABackup.dbo.tMediaPlan FROM tMediaPlan (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tMediaPlan'', @t output

	Print ''tMediaPlanVendor''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlanVendor'')
	drop table PABackup.dbo.tMediaPlanVendor
	 
	Select tMediaPlanVendor.* Into PABackup.dbo.tMediaPlanVendor 
	FROM tMediaPlanVendor (NOLOCK), tMediaPlan b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   b.MediaPlanKey =  tMediaPlanVendor.MediaPlanKey

	exec spTime ''tMediaPlanVendor'', @t output

	Print ''tMediaPlanDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlanDetail'')
	drop table PABackup.dbo.tMediaPlanDetail
	 
	Select tMediaPlanDetail.* Into PABackup.dbo.tMediaPlanDetail 
	FROM tMediaPlanDetail (nolock), tMediaPlanVendor (NOLOCK), tMediaPlan b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   b.MediaPlanKey =  tMediaPlanVendor.MediaPlanKey
	AND   tMediaPlanVendor.MediaPlanVendorKey = tMediaPlanDetail.MediaPlanVendorKey  

	exec spTime ''tMediaPlanDetail'', @t output

	Print ''tMediaPlanDetailHistory''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlanDetailHistory'')
	drop table PABackup.dbo.tMediaPlanDetailHistory
	 
	Select tMediaPlanDetailHistory.* Into PABackup.dbo.tMediaPlanDetailHistory 
	FROM tMediaPlanDetailHistory (nolock), tMediaPlanDetail (nolock), tMediaPlanVendor (NOLOCK), tMediaPlan b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   b.MediaPlanKey =  tMediaPlanVendor.MediaPlanKey
	AND   tMediaPlanVendor.MediaPlanVendorKey = tMediaPlanDetail.MediaPlanVendorKey  
	AND   tMediaPlanDetail.MediaPlanDetailKey = tMediaPlanDetailHistory.MediaPlanDetailKey  

	exec spTime ''tMediaPlanDetailHistory'', @t output

	Print ''tMediaPlanVoucher''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlanVoucher'')
	drop table PABackup.dbo.tMediaPlanVoucher
	 
	Select * Into PABackup.dbo.tMediaPlanVoucher FROM tMediaPlanVoucher (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tMediaPlanVoucher'', @t output

	Print ''tMediaPlanVoucherDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlanVoucherDetail'')
	drop table PABackup.dbo.tMediaPlanVoucherDetail
	 
	Select tMediaPlanVoucherDetail.* Into PABackup.dbo.tMediaPlanVoucherDetail 
	FROM tMediaPlanVoucherDetail (NOLOCK), tMediaPlanVoucher b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   b.MediaPlanVoucherKey =  tMediaPlanVoucherDetail.MediaPlanVoucherKey

	exec spTime ''tMediaPlanVoucherDetail'', @t output

	Print ''tMediaPlanVoucherDetailHistory''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMediaPlanVoucherDetailHistory'')
	drop table PABackup.dbo.tMediaPlanVoucherDetailHistory
	 
	Select tMediaPlanVoucherDetailHistory.* Into PABackup.dbo.tMediaPlanVoucherDetailHistory 
	FROM tMediaPlanVoucherDetailHistory (nolock), tMediaPlanVoucherDetail (NOLOCK), tMediaPlanVoucher b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   b.MediaPlanVoucherKey =  tMediaPlanVoucherDetail.MediaPlanVoucherKey
	AND   tMediaPlanVoucherDetail.MediaPlanVoucherDetailKey = tMediaPlanVoucherDetailHistory.MediaPlanVoucherDetailKey

	exec spTime ''tMediaPlanVoucherDetailHistory'', @t output

	----------------------------------------


	Print ''tMention''

	if exists (select * from PABackup.dbo.sysobjects where name=''tMention'')
		drop table PABackup.dbo.tMention
	 
	Select tMention.* Into PABackup.dbo.tMention 
	FROM tMention (NOLOCK) 
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tMention'', @t output

	Print ''tMergeContactLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMergeContactLog'')
	drop table PABackup.dbo.tMergeContactLog

	Select * Into PABackup.dbo.tMergeContactLog FROM tMergeContactLog (NOLOCK) WHERE OwnerCompanyKey = @CompanyKey
	
	exec spTime ''tMergeContactLog'', @t output
	
	Print ''tMessage''

	if exists (select * from PABackup.dbo.sysobjects where name=''tMessage'')
		drop table PABackup.dbo.tMessage
	 
	Select tMessage.* Into PABackup.dbo.tMessage 
	FROM tMessage (NOLOCK) 
	WHERE CompanyKey = @CompanyKey

	exec spTime ''tMessage'', @t output

	Print ''tMiscCost''
	if exists (select * from PABackup.dbo.sysobjects where name=''tMiscCost'')
	drop table PABackup.dbo.tMiscCost
	 
	Select tMiscCost.* Into PABackup.dbo.tMiscCost 
	FROM tMiscCost (nolock) , tProject (nolock) 
	Where tMiscCost.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tMiscCost'', @t output
	
	Print ''tNote''
	if exists (select * from PABackup.dbo.sysobjects where name=''tNote'')
	drop table PABackup.dbo.tNote
	 
	Select tNote.* Into PABackup.dbo.tNote 
	FROM tNote  (nolock)
	where tNote.Entity = ''Company''
	and tNote.EntityKey = @CompanyKey
	 
	exec spTime ''tNote'', @t output
	
	Print ''tNoteGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tNoteGroup'')
	drop table PABackup.dbo.tNoteGroup
	 
	Select * Into PABackup.dbo.tNoteGroup FROM tNoteGroup  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tNoteGroup'', @t output
	
	Print ''tNotification''
	if exists (select * from PABackup.dbo.sysobjects where name=''tNotification'')
	drop table PABackup.dbo.tNotification
	 
	Select * Into PABackup.dbo.tNotification FROM tNotification  (nolock)

	exec spTime ''tNotification'', @t output
	
	Print ''tObjectFieldSet''
	if exists (select * from PABackup.dbo.sysobjects where name=''tObjectFieldSet'')
	drop table PABackup.dbo.tObjectFieldSet
	 
	Select	tObjectFieldSet.* Into PABackup.dbo.tObjectFieldSet 
	FROM	tObjectFieldSet (nolock) , tFieldSet fs (nolock) 
	where	tObjectFieldSet.FieldSetKey = fs.FieldSetKey
	and		fs.OwnerEntityKey = @CompanyKey
	and		fs.AssociatedEntity != ''Forms''
	

	Insert	PABackup.dbo.tObjectFieldSet (ObjectFieldSetKey, FieldSetKey)
	Select	tObjectFieldSet.ObjectFieldSetKey, tObjectFieldSet.FieldSetKey
	FROM	tObjectFieldSet (nolock) , tFieldSet (nolock) , tFormDef fd (nolock) 
	where	tFieldSet.AssociatedEntity = ''Forms''
	and		tObjectFieldSet.FieldSetKey = tFieldSet.FieldSetKey
	and		tFieldSet.OwnerEntityKey = fd.FormDefKey
	and		fd.CompanyKey = @CompanyKey 
	
	exec spTime ''tObjectFieldSet'', @t output
	
	Print ''tOffice''
	if exists (select * from PABackup.dbo.sysobjects where name=''tOffice'')
	drop table PABackup.dbo.tOffice
	 
	Select * Into PABackup.dbo.tOffice FROM tOffice  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tOffice'', @t output
	
	Print ''tPayment''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPayment'')
	drop table PABackup.dbo.tPayment
	 
	Select * Into PABackup.dbo.tPayment FROM tPayment  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tPayment'', @t output
	
	Print ''tPaymentDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPaymentDetail'')
	drop table PABackup.dbo.tPaymentDetail
	 
	Select tPaymentDetail.* Into PABackup.dbo.tPaymentDetail 
	FROM tPaymentDetail (nolock) , tPayment p (nolock) 
	where tPaymentDetail.PaymentKey = p.PaymentKey 
	and p.CompanyKey = @CompanyKey
	
	exec spTime ''tPaymentDetail'', @t output
	
	Print ''tPaymentTerms''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPaymentTerms'')
	drop table PABackup.dbo.tPaymentTerms
	 
	Select * Into PABackup.dbo.tPaymentTerms FROM tPaymentTerms  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tPaymentTerms'', @t output
	
	Print ''tPlaidAccountLink''

	if exists (select * from PABackup.dbo.sysobjects where name=''tPlaidAccountLink'')
		drop table PABackup.dbo.tPlaidAccountLink
	 
	Select tPlaidAccountLink.* Into PABackup.dbo.tPlaidAccountLink 
	From tPlaidAccountLink (nolock) 
		Left Join tGLAccount (nolock) on tPlaidAccountLink.GLAccountKey = tGLAccount.GLAccountKey
	Where tGLAccount.CompanyKey = @CompanyKey
	
	exec spTime ''tPlaidAccountLink'', @t output

	Print ''tOFXGLAccountLink''

	if exists (select * from PABackup.dbo.sysobjects where name=''tOFXGLAccountLink'')
		drop table PABackup.dbo.tOFXGLAccountLink

	Select * Into PABackup.dbo.tOFXGLAccountLink
	From tOFXGLAccountLink (nolock)
	Where CompanyKey = @CompanyKey

	exec spTime ''tOFXGLAccountLink'', @t output

	Print ''tPlaidLinkError''

	if exists (select * from PABackup.dbo.sysobjects where name=''tPlaidLinkError'')
		drop table PABackup.dbo.tPlaidLinkError
	 
	Select * Into PABackup.dbo.tPlaidLinkError 
	From tPlaidLinkError (nolock) 
	Where CompanyKey = @CompanyKey
	
	exec spTime ''tPlaidLinkError'', @t output

	Print ''tPreference''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPreference'')
	drop table PABackup.dbo.tPreference
	 
	Select * Into PABackup.dbo.tPreference FROM tPreference  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tPreference'', @t output
	
	Print ''tPreferenceDARights''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPreferenceDARights'')
	drop table PABackup.dbo.tPreferenceDARights
	 
	Select * Into PABackup.dbo.tPreferenceDARights FROM tPreferenceDARights (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tPreferenceDARights'', @t output
	
	Print ''tPreferenceRTN''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPreferenceRTN'')
	drop table PABackup.dbo.tPreferenceRTN
	 
	Select * Into PABackup.dbo.tPreferenceRTN FROM tPreferenceRTN (NOLOCK) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tPreferenceRTN'', @t output

	Print ''tProject''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProject'')
	drop table PABackup.dbo.tProject
	 
	Select * Into PABackup.dbo.tProject FROM tProject (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tProject'', @t output

	Print ''tProjectAddress''
	
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectAddress'')
	drop table PABackup.dbo.tProjectAddress
	 
	Select tProjectAddress.* Into PABackup.dbo.tProjectAddress 
	FROM tProjectAddress (nolock) , tProject p (nolock)  
	WHERE tProjectAddress.ProjectKey = p.ProjectKey
	and p.CompanyKey = @CompanyKey

	exec spTime ''tProjectAddress'', @t output
	
	Print ''tProjectItemRollup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectItemRollup'')
	drop table PABackup.dbo.tProjectItemRollup
	 
	Select tProjectItemRollup.* Into PABackup.dbo.tProjectItemRollup 
	FROM tProjectItemRollup (nolock) , tProject p (nolock)  
	WHERE tProjectItemRollup.ProjectKey = p.ProjectKey
	and p.CompanyKey = @CompanyKey

	exec spTime ''tProjectItemRollup'', @t output
	
	Print ''tProjectRollup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectRollup'')
	drop table PABackup.dbo.tProjectRollup
	 
	Select tProjectRollup.* Into PABackup.dbo.tProjectRollup 
	FROM tProjectRollup (nolock) , tProject p (nolock) 
	WHERE tProjectRollup.ProjectKey = p.ProjectKey
	and p.CompanyKey = @CompanyKey
	
	exec spTime ''tProjectRollup'', @t output
	
	Print ''tProjectRollupQueue''

	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectRollupQueue'')
	drop table PABackup.dbo.tProjectRollupQueue
	 
	Select tProjectRollupQueue.* Into PABackup.dbo.tProjectRollupQueue 
	FROM tProjectRollupQueue (nolock)
	WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tProjectRollupQueue'', @t output

	Print ''tProjectTemplateGLCompanyAccess''

	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectTemplateGLCompanyAccess'')
	drop table PABackup.dbo.tProjectTemplateGLCompanyAccess
	 
	Select tProjectTemplateGLCompanyAccess.* Into PABackup.dbo.tProjectTemplateGLCompanyAccess 
	FROM tProjectTemplateGLCompanyAccess (nolock)
	WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tProjectTemplateGLCompanyAccess'', @t output

	Print ''tProjectTitleRollup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectTitleRollup'')
	drop table PABackup.dbo.tProjectTitleRollup
	 
	Select tProjectTitleRollup.* Into PABackup.dbo.tProjectTitleRollup 
	FROM tProjectTitleRollup (nolock) , tProject p (nolock)  
	WHERE tProjectTitleRollup.ProjectKey = p.ProjectKey
	and p.CompanyKey = @CompanyKey

	exec spTime ''tProjectTitleRollup'', @t output
	Print ''tProjectEstByTitle''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectEstByTitle'')
	drop table PABackup.dbo.tProjectEstByTitle
	 
	Select tProjectEstByTitle.* Into PABackup.dbo.tProjectEstByTitle 
	FROM tProjectEstByTitle (nolock) , tProject p (nolock)  
	WHERE tProjectEstByTitle.ProjectKey = p.ProjectKey
	and p.CompanyKey = @CompanyKey

	exec spTime ''tProjectEstByTitle'', @t output
	
	Print ''tProjectBillingStatus''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectBillingStatus'')
	drop table PABackup.dbo.tProjectBillingStatus
	 
	Select * Into PABackup.dbo.tProjectBillingStatus FROM tProjectBillingStatus  (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tProjectBillingStatus'', @t output
	
	Print ''tProjectCreativeBrief''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectCreativeBrief'')
	drop table PABackup.dbo.tProjectCreativeBrief
	 
	Select tProjectCreativeBrief.* Into PABackup.dbo.tProjectCreativeBrief 
	FROM tProjectCreativeBrief  (nolock), tProject p (nolock)  
	where tProjectCreativeBrief.ProjectKey = p.ProjectKey 
	and p.CompanyKey = @CompanyKey

	exec spTime ''tProjectCreativeBrief'', @t output
	
	Print ''tProjectEstByItem''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectEstByItem'')
	drop table PABackup.dbo.tProjectEstByItem 
	 
	Select tProjectEstByItem.* Into PABackup.dbo.tProjectEstByItem  
	FROM	tProjectEstByItem (NOLOCK), tProject (NOLOCK) 
	Where	tProjectEstByItem.ProjectKey = tProject.ProjectKey 
	and		tProject.CompanyKey = @CompanyKey 
	
	exec spTime ''tProjectEstByItem'', @t output
	
	Print ''tProjectNote''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectNote'')
	drop table PABackup.dbo.tProjectNote 
	 
	Select * Into PABackup.dbo.tProjectNote FROM tProjectNote (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tProjectNote'', @t output
	
	Print ''tProjectNoteLink''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectNoteLink'')
	drop table PABackup.dbo.tProjectNoteLink 
	 
	Select tProjectNoteLink.* Into PABackup.dbo.tProjectNoteLink 
	FROM tProjectNoteLink (NOLOCK)
	     ,tProjectNote b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tProjectNoteLink.ProjectNoteKey = b.ProjectNoteKey

	exec spTime ''tProjectNoteLink'', @t output
	
	Print ''tProjectNoteUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectNoteUser'')
	drop table PABackup.dbo.tProjectNoteUser 
	 
	Select tProjectNoteUser.* Into PABackup.dbo.tProjectNoteUser 
	FROM tProjectNoteUser (NOLOCK)
	     ,tProjectNote b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tProjectNoteUser.ProjectNoteKey = b.ProjectNoteKey
	
	exec spTime ''tProjectNoteUser'', @t output
	
	Print ''tProjectStatus''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectStatus'')
	drop table PABackup.dbo.tProjectStatus
	 
	Select * Into PABackup.dbo.tProjectStatus FROM tProjectStatus  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tProjectStatus'', @t output
	
	Print ''tProjectSplitBilling''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectSplitBilling'')
	drop table PABackup.dbo.tProjectSplitBilling 
	 
	Select tProjectSplitBilling.* Into PABackup.dbo.tProjectSplitBilling 
	FROM tProjectSplitBilling (NOLOCK)
	     ,tProject b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tProjectSplitBilling.ProjectKey = b.ProjectKey

	exec spTime ''tProjectSplitBilling'', @t output
	
	Print ''tProjectType''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectType'')
	drop table PABackup.dbo.tProjectType
	 
	Select * Into PABackup.dbo.tProjectType FROM tProjectType  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tProjectType'', @t output
	
	Print ''tProjectTypeMasterTask''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectTypeMasterTask'')
	drop table PABackup.dbo.tProjectTypeMasterTask 
	 
	Select tProjectTypeMasterTask.* Into PABackup.dbo.tProjectTypeMasterTask  
	FROM	tProjectTypeMasterTask (NOLOCK), tProjectType (NOLOCK) 
	Where	tProjectTypeMasterTask.ProjectTypeKey = tProjectType.ProjectTypeKey 
	and		tProjectType.CompanyKey = @CompanyKey 
	
	exec spTime ''tProjectTypeMasterTask'', @t output
	
	Print ''tProjectTypeService''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectTypeService'')
	drop table PABackup.dbo.tProjectTypeService 
	 
	Select tProjectTypeService.* Into PABackup.dbo.tProjectTypeService  
	FROM	tProjectTypeService  (nolock), tProjectType  (nolock)
	Where	tProjectTypeService.ProjectTypeKey = tProjectType.ProjectTypeKey 
	and		tProjectType.CompanyKey = @CompanyKey 
	
	exec spTime ''tProjectTypeService'', @t output
	
	Print ''tProjectTypeUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectTypeUser'')
	drop table PABackup.dbo.tProjectTypeUser 
	 
	Select tProjectTypeUser.* Into PABackup.dbo.tProjectTypeUser  
	FROM	tProjectTypeUser (nolock), tProjectType (nolock)
	Where	tProjectTypeUser.ProjectTypeKey = tProjectType.ProjectTypeKey 
	and		tProjectType.CompanyKey = @CompanyKey 

	exec spTime ''tProjectTypeUser'', @t output
	
	Print ''tProjectUserServices''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectUserServices'')
	drop table PABackup.dbo.tProjectUserServices 
	 
	Select tProjectUserServices.* Into PABackup.dbo.tProjectUserServices  
	FROM	tProjectUserServices  (nolock), tProject  (nolock)
	Where	tProjectUserServices.ProjectKey = tProject.ProjectKey 
	and		tProject.CompanyKey = @CompanyKey 
	
	exec spTime ''tProjectUserServices'', @t output
	
	Print ''tPublishCalendar''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPublishCalendar'')
	drop table PABackup.dbo.tPublishCalendar
	 
	Select * Into PABackup.dbo.tPublishCalendar FROM tPublishCalendar (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tPublishCalendar'', @t output
	
	Print ''tPublishCalendarSecurity''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPublishCalendarSecurity'')
	drop table PABackup.dbo.tPublishCalendarSecurity
	 
	Select tPublishCalendarSecurity.* Into PABackup.dbo.tPublishCalendarSecurity 
	FROM tPublishCalendarSecurity (nolock) , tPublishCalendar (nolock) 
	Where tPublishCalendarSecurity.PublishCalendarKey = tPublishCalendar.PublishCalendarKey 
	and	tPublishCalendar.CompanyKey = @CompanyKey

	exec spTime ''tPublishCalendarSecurity'', @t output
	
	Print ''tPullCalendarFeed''

	if exists (select * from PABackup.dbo.sysobjects where name=''tPullCalendarFeed'')
		drop table PABackup.dbo.tPullCalendarFeed
	 
	Select tPullCalendarFeed.* Into PABackup.dbo.tPullCalendarFeed 
	FROM tPullCalendarFeed (nolock)
		Left Join tCMFolder (nolock) on tPullCalendarFeed.CMFolderKey = tCMFolder.CMFolderKey
	Where tCMFolder.CompanyKey = @CompanyKey

	exec spTime ''tPullCalendarFeed'', @t output

	Print ''tPullCalendarFeedLog''

	if exists (select * from PABackup.dbo.sysobjects where name=''tPullCalendarFeedLog'')
		drop table PABackup.dbo.tPullCalendarFeedLog
	 
	Select tPullCalendarFeedLog.* Into PABackup.dbo.tPullCalendarFeedLog 
	FROM tPullCalendarFeedLog (nolock)
		Left Join tCMFolder (nolock) on tPullCalendarFeedLog.CMFolderKey = tCMFolder.CMFolderKey
	Where tCMFolder.CompanyKey = @CompanyKey

	exec spTime ''tPullCalendarFeedLog'', @t output

	Print ''tPurchaseOrder''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPurchaseOrder'')
	drop table PABackup.dbo.tPurchaseOrder
	 
	Select * Into PABackup.dbo.tPurchaseOrder FROM tPurchaseOrder  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tPurchaseOrder'', @t output
	
	Print ''tPurchaseOrderDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPurchaseOrderDetail'')
	drop table PABackup.dbo.tPurchaseOrderDetail
	 
	Select tPurchaseOrderDetail.* Into PABackup.dbo.tPurchaseOrderDetail 
	FROM tPurchaseOrderDetail (nolock) , tPurchaseOrder (nolock) 
	Where tPurchaseOrderDetail.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey 
	and	tPurchaseOrder.CompanyKey = @CompanyKey
	
	exec spTime ''tPurchaseOrderDetail'', @t output
	
	Print ''tPurchaseOrderDetailTax''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPurchaseOrderDetailTax'')
	drop table PABackup.dbo.tPurchaseOrderDetailTax
	 
	Select tPurchaseOrderDetailTax.* Into PABackup.dbo.tPurchaseOrderDetailTax 
	FROM tPurchaseOrderDetailTax (nolock) , tPurchaseOrderDetail (nolock) , tPurchaseOrder (nolock) 
	Where tPurchaseOrderDetail.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey 
	and	tPurchaseOrder.CompanyKey = @CompanyKey
	and tPurchaseOrderDetail.PurchaseOrderDetailKey =tPurchaseOrderDetailTax.PurchaseOrderDetailKey

	exec spTime ''tPurchaseOrderDetailTax'', @t output
	
	Print ''tPurchaseOrderTraffic''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPurchaseOrderTraffic'')
	drop table PABackup.dbo.tPurchaseOrderTraffic
	 
	Select tPurchaseOrderTraffic.* Into PABackup.dbo.tPurchaseOrderTraffic 
	FROM tPurchaseOrderTraffic (nolock) , tPurchaseOrder (nolock)  
	Where tPurchaseOrderTraffic.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey 
	and	tPurchaseOrder.CompanyKey = @CompanyKey
	
	exec spTime ''tPurchaseOrderTraffic'', @t output
	
	Print ''tPurchaseOrderType''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPurchaseOrderType'')
	drop table PABackup.dbo.tPurchaseOrderType
	 
	Select * Into PABackup.dbo.tPurchaseOrderType FROM tPurchaseOrderType  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tPurchaseOrderType'', @t output
	
	Print ''tPurchaseOrderUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPurchaseOrderUser'')
	drop table PABackup.dbo.tPurchaseOrderUser
	 
	Select tPurchaseOrderUser.* Into PABackup.dbo.tPurchaseOrderUser 
	FROM tPurchaseOrderUser (NOLOCK), tPurchaseOrder (NOLOCK) 
	Where tPurchaseOrderUser.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey 
	and	tPurchaseOrder.CompanyKey = @CompanyKey
	
	exec spTime ''tPurchaseOrderUser'', @t output
	
	Print ''tQuote''
	if exists (select * from PABackup.dbo.sysobjects where name=''tQuote'')
	drop table PABackup.dbo.tQuote
	 
	Select * Into PABackup.dbo.tQuote FROM tQuote  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tQuote'', @t output
	
	Print ''tQuoteDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tQuoteDetail'')
	drop table PABackup.dbo.tQuoteDetail
	 
	Select tQuoteDetail.* Into PABackup.dbo.tQuoteDetail 
	FROM tQuoteDetail  (nolock), tQuote  (nolock)
	Where tQuoteDetail.QuoteKey = tQuote.QuoteKey 
	and tQuote.CompanyKey = @CompanyKey
	
	exec spTime ''tQuoteDetail'', @t output
	
	Print ''tQuoteReply''
	if exists (select * from PABackup.dbo.sysobjects where name=''tQuoteReply'')
	drop table PABackup.dbo.tQuoteReply
	 
	Select tQuoteReply.* Into PABackup.dbo.tQuoteReply 
	FROM tQuoteReply  (nolock), tQuote  (nolock)
	Where tQuoteReply.QuoteKey = tQuote.QuoteKey 
	and tQuote.CompanyKey = @CompanyKey

	exec spTime ''tQuoteReply'', @t output
	
	Print ''tQuoteReplyDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tQuoteReplyDetail'')
	drop table PABackup.dbo.tQuoteReplyDetail
	 
	Select tQuoteReplyDetail.* Into PABackup.dbo.tQuoteReplyDetail 
	FROM tQuoteReplyDetail  (nolock), tQuoteReply  (nolock), tQuote  (nolock)
	Where tQuoteReplyDetail.QuoteReplyKey = tQuoteReply.QuoteReplyKey 
	and	tQuoteReply.QuoteKey = tQuote.QuoteKey 
	and tQuote.CompanyKey = @CompanyKey
	
	exec spTime ''tQuoteReplyDetail'', @t output
	
	Print ''tRecurTran''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRecurTran'')
	drop table PABackup.dbo.tRecurTran
	 
	Select * Into PABackup.dbo.tRecurTran FROM tRecurTran  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tRecurTran'', @t output
	
	Print ''tRecurTranUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRecurTranUser'')
	drop table PABackup.dbo.tRecurTranUser
	 
	Select tRecurTranUser.* Into PABackup.dbo.tRecurTranUser 
	FROM tRecurTranUser  (nolock), tRecurTran  (nolock)
	WHERE tRecurTran.CompanyKey = @CompanyKey
	and   tRecurTran.RecurTranKey = tRecurTranUser.RecurTranKey  


	exec spTime ''tRecurTranUser'', @t output
	
	Print ''tReport''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReport'')
	drop table PABackup.dbo.tReport
	 
	Select * Into PABackup.dbo.tReport FROM tReport  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tReport'', @t output
	
	Print ''tReportGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReportGroup'')
	drop table PABackup.dbo.tReportGroup
	 
	Select * Into PABackup.dbo.tReportGroup FROM tReportGroup  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tReportGroup'', @t output
	
	Print ''tRequest''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRequest'')
	drop table PABackup.dbo.tRequest
	 
	Select * Into PABackup.dbo.tRequest FROM tRequest  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tRequest'', @t output

	Print ''tRequestDef''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRequestDef'')
	drop table PABackup.dbo.tRequestDef
	 
	Select * Into PABackup.dbo.tRequestDef FROM tRequestDef  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tRequestDef'', @t output
	
	Print ''tRequestDefSpec''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRequestDefSpec'')
	drop table PABackup.dbo.tRequestDefSpec
	 
	Select tRequestDefSpec.* Into PABackup.dbo.tRequestDefSpec 
	FROM tRequestDefSpec  (nolock), tRequestDef rd  (nolock) 
	where tRequestDefSpec.RequestDefKey = rd.RequestDefKey 
	and rd.CompanyKey = @CompanyKey

	exec spTime ''tRequestDefSpec'', @t output
	
	Print ''tRequestDefSpecList''

	if exists (select * from PABackup.dbo.sysobjects where name=''tRequestDefSpecList'')
		drop table PABackup.dbo.tRequestDefSpecList
	 
	Select tRequestDefSpecList.* Into PABackup.dbo.tRequestDefSpecList 
	FROM tRequestDefSpecList  (nolock), tRequestDef rd  (nolock) 
	where tRequestDefSpecList.RequestDefKey = rd.RequestDefKey 
	and rd.CompanyKey = @CompanyKey

	exec spTime ''tRequestDefSpecList'', @t output

	Print ''tRequestDefTypeList''

	if exists (select * from PABackup.dbo.sysobjects where name=''tRequestDefTypeList'')
		drop table PABackup.dbo.tRequestDefTypeList
	 
	Select tRequestDefTypeList.* Into PABackup.dbo.tRequestDefTypeList 
	FROM tRequestDefTypeList  (nolock), tRequestDef rd  (nolock) 
	where tRequestDefTypeList.RequestDefKey = rd.RequestDefKey 
	and rd.CompanyKey = @CompanyKey

	exec spTime ''tRequestDefSpecList'', @t output

	Print ''tRequestRejectReason''

	if exists (select * from PABackup.dbo.sysobjects where name=''tRequestRejectReason'')
		drop table PABackup.dbo.tRequestRejectReason
	 
	Select tRequestRejectReason.* Into PABackup.dbo.tRequestRejectReason 
	FROM tRequestRejectReason  (nolock)
	where CompanyKey = @CompanyKey

	exec spTime ''tRequestRejectReason'', @t output

	Print ''tRetainer''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRetainer'')
	drop table PABackup.dbo.tRetainer
	 
	Select * Into PABackup.dbo.tRetainer FROM tRetainer (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tRetainer'', @t output
	
	Print ''tRetainerItems''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRetainerItems'')
	drop table PABackup.dbo.tRetainerItems
	 
	Select tRetainerItems.* Into PABackup.dbo.tRetainerItems 
	FROM tRetainerItems (nolock), tRetainer (nolock)
	WHERE tRetainerItems.RetainerKey = tRetainer.RetainerKey 
	And tRetainer.CompanyKey = @CompanyKey
	
	exec spTime ''tRetainerItems'', @t output
	
	Print ''tReviewComment''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewComment'')
	drop table PABackup.dbo.tReviewComment
	
	Select tReviewComment.* Into PABackup.dbo.tReviewComment 
	FROM tReviewComment  (nolock), tReviewRound  (nolock), tReviewDeliverable  (nolock), tProject (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
	and tReviewRound.ReviewRoundKey = tReviewComment.ReviewRoundKey

	exec spTime ''tReviewComment'', @t output

	Print ''tReviewCommentMarkup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewCommentMarkup'')
	drop table PABackup.dbo.tReviewCommentMarkup
	
	Select tReviewCommentMarkup.* Into PABackup.dbo.tReviewCommentMarkup 
	FROM tReviewCommentMarkup (nolock), tReviewComment (nolock), tReviewRound (nolock)
		, tReviewDeliverable (nolock), tProject (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
	and tReviewRound.ReviewRoundKey = tReviewComment.ReviewRoundKey
	and tReviewCommentMarkup.ReviewCommentKey = tReviewComment.ReviewCommentKey 

	exec spTime ''tReviewCommentMarkup'', @t output
	
	Print ''tReviewDeliverable''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewDeliverable'')
	drop table PABackup.dbo.tReviewDeliverable
	
	Select tReviewDeliverable.* Into PABackup.dbo.tReviewDeliverable 
	FROM tReviewDeliverable  (nolock), tProject  (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tReviewDeliverable'', @t output
	
	Print ''tReviewDeliverableUsers''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewDeliverableUsers'')
	drop table PABackup.dbo.tReviewDeliverableUsers
	
	Select tReviewDeliverableUsers.* Into PABackup.dbo.tReviewDeliverableUsers 
	FROM tReviewDeliverableUsers (nolock), tReviewDeliverable  (nolock), tProject  (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	And tReviewDeliverableUsers.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey

	exec spTime ''tReviewDeliverableUsers'', @t output

	Print ''tReviewLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewLog'')
	drop table PABackup.dbo.tReviewLog
	
	Select tReviewLog.* Into PABackup.dbo.tReviewLog 
	FROM tReviewLog  (nolock), tReviewDeliverable  (nolock), tProject  (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	and tReviewLog.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey 

	exec spTime ''tReviewLog'', @t output
	
	Print ''tReviewRound''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewRound'')
	drop table PABackup.dbo.tReviewRound
	
	Select tReviewRound.* Into PABackup.dbo.tReviewRound 
	FROM tReviewRound  (nolock), tReviewDeliverable  (nolock), tProject  (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey 

	exec spTime ''tReviewRound'', @t output
	
	Print ''tReviewRoundFile''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewRoundFile'')
	drop table PABackup.dbo.tReviewRoundFile
	
	Select tReviewRoundFile.* Into PABackup.dbo.tReviewRoundFile 
	FROM tReviewRoundFile  (nolock), tReviewRound  (nolock), tReviewDeliverable  (nolock), tProject  (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey 
	and tReviewRoundFile.ReviewRoundKey = tReviewRound.ReviewRoundKey

	exec spTime ''tReviewRoundFile'', @t output
	
	Print ''tReviewRoundFileChoice''
	if exists (select * from PABackup.dbo.sysobjects where name=''tReviewRoundFileChoice'')
	drop table PABackup.dbo.tReviewRoundFileChoice
	
	Select tReviewRoundFileChoice.* Into PABackup.dbo.tReviewRoundFileChoice 
	FROM tReviewRoundFileChoice (nolock), tReviewRoundFile  (nolock), tReviewRound  (nolock), tReviewDeliverable  (nolock), tProject  (nolock)
	WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
	And tProject.CompanyKey = @CompanyKey
	and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey 
	and tReviewRoundFile.ReviewRoundKey = tReviewRound.ReviewRoundKey
	and tReviewRoundFileChoice.ReviewRoundFileKey = tReviewRoundFile.ReviewRoundFileKey

	exec spTime ''tReviewRoundFileChoice'', @t output

	Print ''tRight''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRight'')
	drop table PABackup.dbo.tRight
	 
	Select * Into PABackup.dbo.tRight FROM tRight  (nolock)
	
	exec spTime ''tRight'', @t output
	
	Print ''tRightAssigned''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRightAssigned'')
	drop table PABackup.dbo.tRightAssigned
	 
	Select tRightAssigned.* Into PABackup.dbo.tRightAssigned 
	FROM tRightAssigned  (nolock), tSecurityGroup  (nolock) 
	Where tRightAssigned.EntityKey = tSecurityGroup.SecurityGroupKey 
	and	tSecurityGroup.CompanyKey = @CompanyKey 
	and tRightAssigned.EntityType = ''Security Group''
	
	exec spTime ''tRightAssigned'', @t output
	
	Print ''tRightLevel''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRightLevel'')
	drop table PABackup.dbo.tRightLevel
	 
	Select tRightLevel.* Into PABackup.dbo.tRightLevel 
	FROM tRightLevel (nolock), tCompany (nolock) 
	Where tRightLevel.CompanyKey = tCompany.CompanyKey 
	and isnull(tCompany.OwnerCompanyKey,tCompany.CompanyKey) = @CompanyKey 
	
	exec spTime ''tRightLevel'', @t output
	
	Print ''tRptSecurityGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tRptSecurityGroup'')
	drop table PABackup.dbo.tRptSecurityGroup
	 
	Select tRptSecurityGroup.* Into PABackup.dbo.tRptSecurityGroup 
	FROM tRptSecurityGroup  (nolock), tSecurityGroup  (nolock)
	Where tRptSecurityGroup.SecurityGroupKey = tSecurityGroup.SecurityGroupKey and
	tSecurityGroup.CompanyKey = @CompanyKey
	
	exec spTime ''tRptSecurityGroup'', @t output
	
	Print ''tSalesTax''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSalesTax'')
	drop table PABackup.dbo.tSalesTax
	 
	Select * Into PABackup.dbo.tSalesTax FROM tSalesTax  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tSalesTax'', @t output
	
	Print ''tSecurityGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSecurityGroup'')
	drop table PABackup.dbo.tSecurityGroup
	 
	Select * Into PABackup.dbo.tSecurityGroup FROM tSecurityGroup  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tSecurityGroup'', @t output
	
	Print ''tSecurityAccess''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSecurityAccess'')
	drop table PABackup.dbo.tSecurityAccess
	 
	Select * Into PABackup.dbo.tSecurityAccess FROM tSecurityAccess  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tSecurityAccess'', @t output
	
	Print ''tService''
	if exists (select * from PABackup.dbo.sysobjects where name=''tService'')
	drop table PABackup.dbo.tService
	 
	Select * Into PABackup.dbo.tService FROM tService  (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tService'', @t output
	
	Print ''tProjectServices''
	if exists (select * from PABackup.dbo.sysobjects where name=''tProjectServices'')
	drop table PABackup.dbo.tProjectServices
	 
	Select * Into PABackup.dbo.tProjectServices FROM tProjectServices  (nolock) WHERE ServiceKey in (select ServiceKey from tService where CompanyKey = 91554)
	 
	exec spTime ''tProjectServices'', @t output

	Print ''tSession''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSession'')
	drop table PABackup.dbo.tSession
	 
	exec spTime ''tSession'', @t output
	
	Print ''tSession:User + userDashboard''
	Select tSession.* Into PABackup.dbo.tSession 
	FROM tSession  (nolock), tUser u  (nolock)
	where	tSession.Entity in ( ''user'', ''userDashboard'', ''strings'', ''StandardReports'', ''DynamicReports'', ''rights'', ''recentTran'', ''Listings'')
	and		tSession.EntityKey = u.UserKey
	and		ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	
	exec spTime ''tSession:User + userDashboard'', @t output
	
	Print ''tSession:report style''
	Insert PABackup.dbo.tSession 
	Select *
	FROM    tSession  (nolock)
	where	tSession.Entity in ( ''report'', ''style'', ''CompanyMetrics'')
	and		tSession.EntityKey = @CompanyKey

	exec spTime ''tSession:report style'', @t output
	
	Print ''tSkill''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSkill'')
	drop table PABackup.dbo.tSkill
	 
	Select * Into PABackup.dbo.tSkill FROM tSkill  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tSkill'', @t output
	
	Print ''tSkillSpecialty''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSkillSpecialty'')
		drop table PABackup.dbo.tSkillSpecialty
	 
	Select tSkillSpecialty.* Into PABackup.dbo.tSkillSpecialty 
	FROM tSkillSpecialty  (nolock), tSkill  (nolock)
	Where tSkillSpecialty.SkillKey = tSkill.SkillKey 
	and tSkill.CompanyKey = @CompanyKey

	exec spTime ''tSkillSpecialty'', @t output
	
	Print ''tSource''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSource'')
	drop table PABackup.dbo.tSource
	 
	Select * Into PABackup.dbo.tSource FROM tSource  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tSource'', @t output
	
	Print ''tSpecSheet''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSpecSheet'')
	drop table PABackup.dbo.tSpecSheet
	 
	Select	sp.* Into PABackup.dbo.tSpecSheet 
	FROM	
	(Select tSpecSheet.*
		from tSpecSheet  (nolock), tProject p  (nolock)
		where	tSpecSheet.Entity = ''Project''
		and		tSpecSheet.EntityKey = p.ProjectKey
		and		p.CompanyKey = @CompanyKey
		
	UNION ALL
	
	Select tSpecSheet.*
		from tSpecSheet  (nolock), tRequest r  (nolock)
		where	tSpecSheet.Entity = ''ProjectRequest''
		and		tSpecSheet.EntityKey = r.RequestKey
		and		r.CompanyKey = @CompanyKey
		
	UNION ALL
	
	Select tSpecSheet.*
		from tSpecSheet  (nolock), tLead l  (nolock)
		where	tSpecSheet.Entity = ''Lead''
		and		tSpecSheet.EntityKey = l.LeadKey
		and		l.CompanyKey = @CompanyKey ) as sp
	
	exec spTime ''tSpecSheet'', @t output
	
	Print ''tSpecSheetLink''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSpecSheetLink'')
	drop table PABackup.dbo.tSpecSheetLink
	 
	Select * Into PABackup.dbo.tSpecSheetLink FROM tSpecSheetLink  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tSpecSheetLink'', @t output
	
	Print ''tStandardActivity''
	if exists (select * from PABackup.dbo.sysobjects where name=''tStandardActivity'')
	drop table PABackup.dbo.tStandardActivity
	 
	Select * Into PABackup.dbo.tStandardActivity FROM tStandardActivity  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tStandardActivity'', @t output
	
	Print ''tStandardText''
	if exists (select * from PABackup.dbo.sysobjects where name=''tStandardText'')
	drop table PABackup.dbo.tStandardText
	 
	Select * Into PABackup.dbo.tStandardText FROM tStandardText  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tStandardText'', @t output
	
	Print ''tString''
	if exists (select * from PABackup.dbo.sysobjects where name=''tString'')
	drop table PABackup.dbo.tString
	 
	Select * Into PABackup.dbo.tString FROM tString

	 
	exec spTime ''tString'', @t output
	
	Print ''tStringCompany''
	if exists (select * from PABackup.dbo.sysobjects where name=''tStringCompany'')
	drop table PABackup.dbo.tStringCompany
	 
	Select * Into PABackup.dbo.tStringCompany FROM tStringCompany  (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tStringCompany'', @t output
	
	Print ''tStringGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tStringGroup'')
	drop table PABackup.dbo.tStringGroup
	Select * Into PABackup.dbo.tStringGroup FROM tStringGroup  (nolock)
		 
	exec spTime ''tStringGroup'', @t output
	
	Print ''tSyncActivity''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSyncActivity'')
	drop table PABackup.dbo.tSyncActivity

	Select tSyncActivity.* Into PABackup.dbo.tSyncActivity 
	FROM   tSyncActivity (nolock), tCompany c (nolock)
	where  tSyncActivity.CompanyKey = c.CompanyKey
	and    isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey	 

	exec spTime ''tSyncActivity'', @t output
	
	Print ''tSyncFolder''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSyncFolder'')
	drop table PABackup.dbo.tSyncFolder

	Select tSyncFolder.* Into PABackup.dbo.tSyncFolder 
	FROM   tSyncFolder (nolock), tCompany c (nolock)
	where  tSyncFolder.CompanyKey = c.CompanyKey
	and    isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey	 

	exec spTime ''tSyncFolder'', @t output
	
	Print ''tSyncItem''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSyncItem'')
	drop table PABackup.dbo.tSyncItem

	Select tSyncItem.* Into PABackup.dbo.tSyncItem 
	FROM   tSyncItem (nolock), tCompany c (nolock)
	where  tSyncItem.CompanyKey = c.CompanyKey
	and    isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey	 
	
	exec spTime ''tSyncItem'', @t output
	
	Print ''tSyncCalendar''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSyncCalendar'')
	drop table PABackup.dbo.tSyncCalendar

	Select tSyncCalendar.* Into PABackup.dbo.tSyncCalendar 
	FROM   tSyncCalendar (nolock), tCalendar c (nolock)
	where  tSyncCalendar.CalendarKey = c.CalendarKey
	and    c.CompanyKey = @CompanyKey	 

	exec spTime ''tSyncCalendar'', @t output
	
	Print ''tSyncCalendarAttendee''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSyncCalendarAttendee'')
	drop table PABackup.dbo.tSyncCalendarAttendee

	Select tSyncCalendarAttendee.* Into PABackup.dbo.tSyncCalendarAttendee 
	FROM   tSyncCalendarAttendee (nolock), tCalendar c (nolock)
	where  tSyncCalendarAttendee.CalendarKey = c.CalendarKey
	and    c.CompanyKey = @CompanyKey	 

	exec spTime ''tSyncCalendarAttendee'', @t output
	
	Print ''tSystemMessage''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSystemMessage'')
	drop table PABackup.dbo.tSystemMessage
		 
	select * into PABackup.dbo.tSystemMessage from tSystemMessage  (nolock)

	exec spTime ''tSystemMessage'', @t output
	
	Print ''tSystemMessageUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tSystemMessageUser'')
	drop table PABackup.dbo.tSystemMessageUser
		 
	select tSystemMessageUser.* into PABackup.dbo.tSystemMessageUser 
	from tSystemMessageUser (nolock), tUser (nolock)
	where tSystemMessageUser.UserKey = tUser.UserKey
	and  isnull(tUser.OwnerCompanyKey, tUser.CompanyKey) = @CompanyKey


	exec spTime ''tSystemMessageUser'', @t output
	
	Print ''tTask''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTask'')
	drop table PABackup.dbo.tTask
	 
	Select tTask.* Into PABackup.dbo.tTask 
	FROM tTask (nolock) , tProject (nolock) 
	Where tTask.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey

	exec spTime ''tTask'', @t output
	
	Print ''tTaskAssignment''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskAssignment'')
		drop table PABackup.dbo.tTaskAssignment
	 
	Select tTaskAssignment.* Into PABackup.dbo.tTaskAssignment 
	From tTaskAssignment (nolock)
		Left Join tTask (nolock) on tTaskAssignment.TaskKey = tTask.TaskKey
		Left Join tProject (nolock) on tTask.ProjectKey = tProject.ProjectKey
	Where tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tTaskAssignment'', @t output

	Print ''tTaskAssignmentType''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskAssignmentType'')
	drop table PABackup.dbo.tTaskAssignmentType
	 
	Select * Into PABackup.dbo.tTaskAssignmentType FROM tTaskAssignmentType  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tTaskAssignmentType'', @t output
	
	Print ''tTaskAssignmentTypeService''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskAssignmentTypeService'')
	drop table PABackup.dbo.tTaskAssignmentTypeService
	 
	Select tTaskAssignmentTypeService.* Into PABackup.dbo.tTaskAssignmentTypeService 
	FROM tTaskAssignmentTypeService (NOLOCK), tTaskAssignmentType (NOLOCK) 
	Where tTaskAssignmentTypeService.TaskAssignmentTypeKey = tTaskAssignmentType.TaskAssignmentTypeKey 
	and tTaskAssignmentType.CompanyKey = @CompanyKey
	 
	exec spTime ''tTaskAssignmentTypeService'', @t output
	
	Print ''tTaskAssignmentUser''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskAssignmentUser'')
		drop table PABackup.dbo.tTaskAssignmentUser
	 
	Select tTaskAssignmentUser.* Into PABackup.dbo.tTaskAssignmentUser 
	From tTaskAssignmentUser (nolock)
		Left Join tTask (nolock) on tTaskAssignmentUser.TaskKey = tTask.TaskKey
		Left Join tProject (nolock) on tTask.ProjectKey = tProject.ProjectKey
	Where tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tTaskAssignmentUser'', @t output

	Print ''tTaskPredecessor''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskPredecessor'')
	drop table PABackup.dbo.tTaskPredecessor
	 
	Select tTaskPredecessor.* Into PABackup.dbo.tTaskPredecessor 
	FROM tTaskPredecessor (nolock) , tTask (nolock) , tProject  (nolock) 
	Where tTaskPredecessor.TaskKey = tTask.TaskKey 
	and tTask.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	
	exec spTime ''tTaskPredecessor'', @t output
	
	Print ''tTaskPriority''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskPriority'')
	drop table PABackup.dbo.tTaskPriority
	 
	Select tTaskPriority.* Into PABackup.dbo.tTaskPriority 
	FROM tTaskPriority (nolock)
	Where CompanyKey = @CompanyKey
	
	exec spTime ''tTaskPriority'', @t output
	
	Print ''tTaskUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUser'')
		drop table PABackup.dbo.tTaskUser
	 
	SELECT tTaskUser.* INTO PABackup.dbo.tTaskUser 
	FROM tTaskUser (nolock) 
		INNER JOIN tTask (nolock) ON tTaskUser.TaskKey = tTask.TaskKey
		INNER JOIN tProject (nolock) ON tTask.ProjectKey = tProject.ProjectKey
	WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tTaskUser'', @t output
	
	Print ''tTaskUserHour''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUserHour'')
		drop table PABackup.dbo.tTaskUserHour
	 
	SELECT	tTaskUserHour.* INTO PABackup.dbo.tTaskUserHour 
	FROM tTaskUserHour (nolock) 
		INNER JOIN tTaskUser (nolock) on tTaskUserHour.TaskUserKey = tTaskUser.TaskUserKey 
		INNER JOIN tTask (nolock) ON tTaskUser.TaskKey = tTask.TaskKey
		INNER JOIN tProject (nolock) ON tTask.ProjectKey = tProject.ProjectKey
	WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tTaskUserHour'', @t output

	Print ''tTaskUserHourLog''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUserHourLog'')
		drop table PABackup.dbo.tTaskUserHourLog
	 
	SELECT	tTaskUserHourLog.* INTO PABackup.dbo.tTaskUserHourLog 
	FROM tTaskUserHourLog (nolock) 
		INNER JOIN tTaskUser (nolock) on tTaskUserHourLog.TaskUserKey = tTaskUser.TaskUserKey 
		INNER JOIN tTask (nolock) ON tTaskUser.TaskKey = tTask.TaskKey
		INNER JOIN tProject (nolock) ON tTask.ProjectKey = tProject.ProjectKey
	WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tTaskUserHourLog'', @t output

	Print ''tTaskUserHourSnapshot''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUserHourSnapshot'')
		drop table PABackup.dbo.tTaskUserHourSnapshot
	 
	SELECT	tTaskUserHourSnapshot.* INTO PABackup.dbo.tTaskUserHourSnapshot 
	FROM tTaskUserHourSnapshot (nolock) 
		INNER JOIN tTaskUser (nolock) on tTaskUserHourSnapshot.TaskUserKey = tTaskUser.TaskUserKey 
		INNER JOIN tTask (nolock) ON tTaskUser.TaskKey = tTask.TaskKey
		INNER JOIN tProject (nolock) ON tTask.ProjectKey = tProject.ProjectKey
	WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tTaskUserHourSnapshot'', @t output

	Print ''tTaskUserOrig''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUserOrig'')
		drop table PABackup.dbo.tTaskUserOrig
	 
	SELECT	tTaskUserOrig.* INTO PABackup.dbo.tTaskUserOrig 
	FROM tTaskUserOrig (nolock) 
		INNER JOIN vTaskUser (nolock) on tTaskUserOrig.TaskUserKey = vTaskUser.TaskUserKey 
	WHERE vTaskUser.CompanyKey = @CompanyKey
	
	exec spTime ''tTaskUserOrig'', @t output

	Print ''tTaskUserHourOrig''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUserHourOrig'')
		drop table PABackup.dbo.tTaskUserHourOrig
	 
	SELECT	tTaskUserHourOrig.* INTO PABackup.dbo.tTaskUserHourOrig 
	FROM tTaskUserHourOrig (nolock) 
		INNER JOIN vTaskUser (nolock) on tTaskUserHourOrig.TaskUserKey = vTaskUser.TaskUserKey 
	WHERE vTaskUser.CompanyKey = @CompanyKey
	
	exec spTime ''tTaskUserHourOrig'', @t output

	Print ''tTaskUserStatus''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTaskUserStatus'')
	drop table PABackup.dbo.tTaskUserStatus
	 
	SELECT	tus.* INTO PABackup.dbo.tTaskUserStatus 
	FROM tTaskUserStatus tus (nolock) 
	WHERE	tus.EntityKey = @CompanyKey
	and     tus.Entity = ''company''

	exec spTime ''tTaskUserStatus'', @t output

	Print ''tTime''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTime'')
	drop table PABackup.dbo.tTime
	 
    /*
	Select tTime.* Into PABackup.dbo.tTime 
	FROM tTime (nolock), tUser (nolock) 
	Where tTime.UserKey = tUser.UserKey 
	and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
	*/

	Select tTime.* Into PABackup.dbo.tTime 
	FROM tTime with (index=IX_tTime_1, nolock) 
		inner join tUser (nolock) on tTime.UserKey = tUser.UserKey 
	Where isnull(tUser.OwnerCompanyKey, tUser.CompanyKey) = @CompanyKey

	exec spTime ''tTime'', @t output
	
	Print ''tTime_DELETED''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTime_DELETED'')
	drop table PABackup.dbo.tTime_DELETED
	 
	Select tTime_DELETED.* Into PABackup.dbo.tTime_DELETED 
	FROM tTime (nolock), tTime_DELETED (nolock), tUser (nolock) 
	Where tTime.UserKey = tUser.UserKey 
	and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
	and  tTime_DELETED.TimeKey = tTime.TimeKey 
	
	exec spTime ''tTime_DELETED'', @t output
	
	Print ''tTimelineSegment''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTimelineSegment'')
	drop table PABackup.dbo.tTimelineSegment
	 
	Select * Into PABackup.dbo.tTimelineSegment FROM tTimelineSegment (nolock) WHERE CompanyKey = @CompanyKey
	  
	exec spTime ''tTimelineSegment'', @t output
	
	Print ''tTimeOption''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTimeOption'')
	drop table PABackup.dbo.tTimeOption
	 
	Select * Into PABackup.dbo.tTimeOption FROM tTimeOption  (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tTimeOption'', @t output
	
	Print ''tTimeRateSheet''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTimeRateSheet'')
	drop table PABackup.dbo.tTimeRateSheet
	 
	Select * Into PABackup.dbo.tTimeRateSheet FROM tTimeRateSheet  (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tTimeRateSheet'', @t output
	
	Print ''tTimeRateSheetDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTimeRateSheetDetail'')
	drop table PABackup.dbo.tTimeRateSheetDetail
	 
	Select tTimeRateSheetDetail.* Into PABackup.dbo.tTimeRateSheetDetail 
	FROM tTimeRateSheetDetail (nolock), tTimeRateSheet (nolock)
	Where tTimeRateSheetDetail.TimeRateSheetKey = tTimeRateSheet.TimeRateSheetKey 
	and tTimeRateSheet.CompanyKey = @CompanyKey
 
	exec spTime ''tTimeRateSheetDetail'', @t output
	
	Print ''tTimeSheet''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTimeSheet'')
	drop table PABackup.dbo.tTimeSheet
	 
	Select * Into PABackup.dbo.tTimeSheet FROM tTimeSheet (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tTimeSheet'', @t output
	
	Print ''tTimeZone''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTimeZone'')
		drop table PABackup.dbo.tTimeZone
	 
	Select * Into PABackup.dbo.tTimeZone 
	From tTimeZone (nolock)

	exec spTime ''tTimeZone'', @t output

	Print ''tTimeRollup''

	if exists (select * from PABackup.dbo.sysobjects where name=''tTimeRollup'')
		drop table PABackup.dbo.tTimeRollup
	 
	SELECT	tr.* Into PABackup.dbo.tTimeRollup 
	FROM	tTimeRollup tr  (nolock)
	INNER JOIN tProject p (nolock) ON tr.ProjectKey = p.ProjectKey
	WHERE	p.CompanyKey = @CompanyKey

	exec spTime ''tTimeRollup'', @t output

	Print ''tTeam''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTeam'')
	drop table PABackup.dbo.tTeam
	 
	Select * Into PABackup.dbo.tTeam FROM tTeam (NOLOCK) WHERE CompanyKey = @CompanyKey

	exec spTime ''tTeam'', @t output
	
	Print ''tTeamUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTeamUser'')
	drop table PABackup.dbo.tTeamUser
	 
	Select tTeamUser.* Into PABackup.dbo.tTeamUser 
	FROM tTeamUser (NOLOCK)
	     ,tTeam b (NOLOCK) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tTeamUser.TeamKey = b.TeamKey
	 
	exec spTime ''tTeamUser'', @t output
	
	Print ''tTransaction''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTransaction'')
	drop table PABackup.dbo.tTransaction
	 
	Select * Into PABackup.dbo.tTransaction FROM tTransaction (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tTransaction'', @t output
	
	Print ''tTransactionUnpost''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTransactionUnpost'')
	drop table PABackup.dbo.tTransactionUnpost
	 
	Select * Into PABackup.dbo.tTransactionUnpost FROM tTransactionUnpost (nolock)  WHERE CompanyKey = @CompanyKey

	exec spTime ''tTransactionUnpost'', @t output
	
	Print ''tTransactionUnpostLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTransactionUnpostLog'')
	drop table PABackup.dbo.tTransactionUnpostLog
	 
	Select * Into PABackup.dbo.tTransactionUnpostLog FROM tTransactionUnpostLog (nolock)  WHERE CompanyKey = @CompanyKey

	exec spTime ''tTransactionUnpostLog'', @t output
	
	Print ''tTransactionOrderAccrual''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTransactionOrderAccrual'')
	drop table PABackup.dbo.tTransactionOrderAccrual
	 
	Select * Into PABackup.dbo.tTransactionOrderAccrual FROM tTransactionOrderAccrual (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tTransactionOrderAccrual'', @t output
	
	Print ''tTitle''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTitle'')
	drop table PABackup.dbo.tTitle
	 
	Select * Into PABackup.dbo.tTitle FROM tTitle (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tTitle'', @t output
	
	Print ''tTitleRateSheet''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTitleRateSheet'')
	drop table PABackup.dbo.tTitleRateSheet
	 
	Select * Into PABackup.dbo.tTitleRateSheet FROM tTitleRateSheet (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tTitleRateSheet'', @t output
	
	Print ''tTitleRateSheetDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTitleRateSheetDetail'')
	drop table PABackup.dbo.tTitleRateSheetDetail
	 
	Select tTitleRateSheetDetail.* Into PABackup.dbo.tTitleRateSheetDetail 
	FROM tTitleRateSheetDetail (nolock), tTitleRateSheet b (nolock) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tTitleRateSheetDetail.TitleRateSheetKey = b.TitleRateSheetKey

	exec spTime ''tTitleRateSheetDetail'', @t output
	
	Print ''tTitleService''
	if exists (select * from PABackup.dbo.sysobjects where name=''tTitleService'')
	drop table PABackup.dbo.tTitleService
	 
	Select tTitleService.* Into PABackup.dbo.tTitleService 
	FROM tTitleService (nolock), tTitle b (nolock) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tTitleService.TitleKey = b.TitleKey

	exec spTime ''tTitleService'', @t output
	
	Print ''tUrl''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUrl'')
	drop table PABackup.dbo.tUrl
	 
	Select * Into PABackup.dbo.tUrl FROM tUrl (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tUrl'', @t output
	
	Print ''tUser''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUser'')
	drop table PABackup.dbo.tUser
	 
	Select * Into PABackup.dbo.tUser 
	from tUser (nolock) 
	Where CompanyKey = @CompanyKey 
	or CompanyKey in (Select CompanyKey from tCompany  (nolock) where OwnerCompanyKey = @CompanyKey)
	or (ISNULL(CompanyKey, 0) = 0 and OwnerCompanyKey = @CompanyKey)
		 
	exec spTime ''tUser'', @t output
	
	Print ''tUserGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserGroup'')
	drop table PABackup.dbo.tUserGroup
	 
	Select * Into PABackup.dbo.tUserGroup FROM tUserGroup  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tUserGroup'', @t output
	
	Print ''tUserGLCompanyAccess''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserGLCompanyAccess'')
	drop table PABackup.dbo.tUserGLCompanyAccess
	 
	Select tUserGLCompanyAccess.* Into PABackup.dbo.tUserGLCompanyAccess 
	FROM tUserGLCompanyAccess  (nolock), tUser u  (nolock)
	where tUserGLCompanyAccess.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	
	exec spTime ''tUserGLCompanyAccess'', @t output
	
	Print ''tUserLead''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserLead'')
	drop table PABackup.dbo.tUserLead
	 
	Select * Into PABackup.dbo.tUserLead FROM tUserLead  (nolock) WHERE CompanyKey = @CompanyKey
	 
	exec spTime ''tUserLead'', @t output

	Print ''tUserLeadUpdateLog''

	if exists (select * from PABackup.dbo.sysobjects where name=''tUserLeadUpdateLog'')
		drop table PABackup.dbo.tUserLeadUpdateLog
	 
	Select * Into PABackup.dbo.tUserLeadUpdateLog
	From tUserLeadUpdateLog  (nolock) 
	Where CompanyKey = @CompanyKey
	 
	exec spTime ''tUserLead'', @t output
	
	Print ''tUserRole''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserRole'')
	drop table PABackup.dbo.tUserRole
	 
	Select * Into PABackup.dbo.tUserRole FROM tUserRole  (nolock) WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tUserRole'', @t output
	
	Print ''tUserNotification''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserNotification'')
	drop table PABackup.dbo.tUserNotification
	 
	Select tUserNotification.* Into PABackup.dbo.tUserNotification 
	FROM tUserNotification  (nolock), tUser u  (nolock)
	where tUserNotification.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	 
	exec spTime ''tUserNotification'', @t output
	
	Print ''tUserPassword''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserPassword'')
	drop table PABackup.dbo.tUserPassword
	 
	Select tUserPassword.* Into PABackup.dbo.tUserPassword 
	FROM tUserPassword  (nolock), tUser u  (nolock)
	where tUserPassword.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	
	exec spTime ''tUserPassword'', @t output
	
	Print ''tUserLoginLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserLoginLog'')
	drop table PABackup.dbo.tUserLoginLog
	 
	Select tUserLoginLog.* Into PABackup.dbo.tUserLoginLog 
	FROM tUserLoginLog  (nolock), tUser u (nolock) 
	where tUserLoginLog.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey

	exec spTime ''tUserLoginLog'', @t output
	
	Print ''tUserMapping''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserMapping'')
	drop table PABackup.dbo.tUserMapping
	 
	Select tUserMapping.* Into PABackup.dbo.tUserMapping 
	FROM tUserMapping  (nolock), tUser u (nolock) 
	where tUserMapping.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey

	exec spTime ''tUserMapping'', @t output
	
	Print ''tUserPreference''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserPreference'')
	drop table PABackup.dbo.tUserPreference
	 
	Select tUserPreference.* Into PABackup.dbo.tUserPreference 
	FROM tUserPreference  (nolock), tUser u  (nolock) 
	where tUserPreference.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
	 
	exec spTime '''', @t output
	
	Print ''tUserService''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserService'')
	drop table PABackup.dbo.tUserService
	 
	Select tUserService.* Into PABackup.dbo.tUserService 
	FROM tUserService  (nolock), tUser u  (nolock)
	where tUserService.UserKey = u.UserKey 
	and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
 
	exec spTime ''tUserService'', @t output
	
	Print ''tUserSkill''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserSkill'')
	drop table PABackup.dbo.tUserSkill
	 
	Select tUserSkill.* Into PABackup.dbo.tUserSkill 
	FROM tUserSkill  (nolock), tUser  (nolock)
	Where tUserSkill.UserKey = tUser.UserKey 
	and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
	 
	exec spTime ''tUserSkill'', @t output
	
	Print ''tUserSkillSpecialty''
	if exists (select * from PABackup.dbo.sysobjects where name=''tUserSkillSpecialty'')
	drop table PABackup.dbo.tUserSkillSpecialty
	 
	Select tUserSkillSpecialty.* Into PABackup.dbo.tUserSkillSpecialty 
	FROM tUserSkillSpecialty  (nolock), tUser  (nolock) 
	Where tUserSkillSpecialty.UserKey = tUser.UserKey 
	and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey) 

	exec spTime ''tUserSkillSpecialty'', @t output
	
	Print ''tUserUpdateLog''

	if exists (select * from PABackup.dbo.sysobjects where name=''tUserUpdateLog'')
		drop table PABackup.dbo.tUserUpdateLog
	 
	Select tUserUpdateLog.* Into PABackup.dbo.tUserUpdateLog 
	FROM tUserUpdateLog  (nolock)
	Where tUserUpdateLog.CompanyKey = @CompanyKey

	exec spTime ''tUserUpdateLog'', @t output

	Print ''tViewSecurityGroup''
	if exists (select * from PABackup.dbo.sysobjects where name=''tViewSecurityGroup'')
	drop table PABackup.dbo.tViewSecurityGroup

	Select tViewSecurityGroup.* Into PABackup.dbo.tViewSecurityGroup 
	From   tViewSecurityGroup  (nolock), tSecurityGroup sg  (nolock)
	Where  tViewSecurityGroup.SecurityGroupKey = sg.SecurityGroupKey
	and	   sg.CompanyKey = @CompanyKey

	exec spTime ''tViewSecurityGroup'', @t output
	
	Print ''tVoucher''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucher'')
	drop table PABackup.dbo.tVoucher
	 
	Select * Into PABackup.dbo.tVoucher FROM tVoucher  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tVoucher'', @t output
	
	Print ''tVoucherCC''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucherCC'')
	drop table PABackup.dbo.tVoucherCC
	 
	Select tVoucherCC.* Into PABackup.dbo.tVoucherCC 
	FROM tVoucherCC (nolock), tVoucher (nolock)
	WHERE tVoucherCC.VoucherKey = tVoucher.VoucherKey
	and tVoucher.CompanyKey = @CompanyKey

	exec spTime ''tVoucherCC'', @t output
	
	Print ''tVoucherCCDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucherCCDetail'')
	drop table PABackup.dbo.tVoucherCCDetail
	 
	Select tVoucherCCDetail.* Into PABackup.dbo.tVoucherCCDetail 
	FROM tVoucherCCDetail  (nolock), tVoucher (nolock)
	WHERE tVoucherCCDetail.VoucherKey = tVoucher.VoucherKey
	and tVoucher.CompanyKey = @CompanyKey


	exec spTime ''tVoucherCCDetail'', @t output
	
	Print ''tVoucherCredit''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucherCredit'')
	drop table PABackup.dbo.tVoucherCredit
	 
	Select tVoucherCredit.* Into PABackup.dbo.tVoucherCredit 
	FROM tVoucherCredit (nolock), tVoucher (nolock)
	WHERE tVoucherCredit.VoucherKey = tVoucher.VoucherKey
	and tVoucher.CompanyKey = @CompanyKey

	exec spTime ''tVoucherCredit'', @t output
	
	Print ''tVoucherTax''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucherTax'')
	drop table PABackup.dbo.tVoucherTax
	 
	Select tVoucherTax.* Into PABackup.dbo.tVoucherTax 
	FROM tVoucherTax (nolock), tVoucher (nolock)
	WHERE tVoucherTax.VoucherKey = tVoucher.VoucherKey
	and tVoucher.CompanyKey = @CompanyKey
	
	exec spTime ''tVoucherTax'', @t output
	
	Print ''tVoucherDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucherDetail'')
	drop table PABackup.dbo.tVoucherDetail
	 
	Select tVoucherDetail.* Into PABackup.dbo.tVoucherDetail 
	FROM tVoucherDetail (nolock) , tVoucher (nolock) 
	WHERE tVoucherDetail.VoucherKey = tVoucher.VoucherKey
	and tVoucher.CompanyKey = @CompanyKey

	exec spTime ''tVoucherDetail'', @t output
	
	Print ''tVoucherDetailTax''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVoucherDetailTax'')
	drop table PABackup.dbo.tVoucherDetailTax
	 
	Select	tVoucherDetailTax.* Into PABackup.dbo.tVoucherDetailTax 
	FROM	tVoucherDetailTax (NOLOCK), tVoucherDetail (NOLOCK), tVoucher (NOLOCK) 
	Where	tVoucherDetailTax.VoucherDetailKey = tVoucherDetail.VoucherDetailKey
	and     tVoucherDetail.VoucherKey = tVoucher.VoucherKey 
	and		tVoucher.CompanyKey = @CompanyKey
	
	exec spTime ''tVoucherDetailTax'', @t output
	
	Print ''tWIPPosting''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWIPPosting'')
	drop table PABackup.dbo.tWIPPosting
	 
	Select * Into PABackup.dbo.tWIPPosting FROM tWIPPosting (nolock)  WHERE CompanyKey = @CompanyKey
	
	exec spTime ''tWIPPosting'', @t output
	
	Print ''tWIPPostingDetail''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWIPPostingDetail'')
	drop table PABackup.dbo.tWIPPostingDetail
	 
	Select tWIPPostingDetail.* Into PABackup.dbo.tWIPPostingDetail 
	FROM tWIPPostingDetail (nolock) , tWIPPosting (nolock)
	WHERE tWIPPostingDetail.WIPPostingKey = tWIPPosting.WIPPostingKey
	and tWIPPosting.CompanyKey = @CompanyKey
	
	exec spTime ''tWIPPostingDetail'', @t output
	
	--Print ''tWidgetDef''
	--if exists (select * from PABackup.dbo.sysobjects where name=''tWidgetDef'')
	--drop table PABackup.dbo.tWidgetDef
	 
	--Select * Into PABackup.dbo.tWidgetDef FROM tWidgetDef (nolock) WHERE CompanyKey = @CompanyKey
	--Or CompanyKey IS NULL
	
	--exec spTime ''tWidgetDef'', @t output
	
	Print ''tWorkType''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWorkType'')
	drop table PABackup.dbo.tWorkType
	 
	Select * Into PABackup.dbo.tWorkType FROM tWorkType  (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tWorkType'', @t output
	
	Print ''tWorkTypeCustom''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWorkTypeCustom'')
	drop table PABackup.dbo.tWorkTypeCustom
	 
	Select tWorkTypeCustom.* Into PABackup.dbo.tWorkTypeCustom 
	FROM tWorkType (nolock), tWorkTypeCustom  (nolock)
	WHERE tWorkType.CompanyKey = @CompanyKey
	AND   tWorkType.WorkTypeKey = tWorkTypeCustom.WorkTypeKey

	exec spTime ''tWorkTypeCustom'', @t output
	
	Print ''tWriteOffReason''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWriteOffReason'')
	drop table PABackup.dbo.tWriteOffReason
	 
	Select * Into PABackup.dbo.tWriteOffReason FROM tWriteOffReason (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tWriteOffReason'', @t output
	
	Print ''tWebDavServer''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWebDavServer'')
	drop table PABackup.dbo.tWebDavServer
	 
	Select * Into PABackup.dbo.tWebDavServer FROM tWebDavServer (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime '''', @t output
	
	Print ''tWebDavFile''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWebDavFile'')
	drop table PABackup.dbo.tWebDavFile
	 
	Select * Into PABackup.dbo.tWebDavFile FROM tWebDavFile (nolock) WHERE CompanyKey = @CompanyKey

	exec spTime ''tWebDavFile'', @t output
	
	Print ''tWebDavFile_FromServer''

	if exists (select * from PABackup.dbo.sysobjects where name=''tWebDavFile_FromServer'')
		drop table PABackup.dbo.tWebDavFile_FromServer
	 
	Select * Into PABackup.dbo.tWebDavFile_FromServer 
	From tWebDavFile_FromServer (nolock) 
	Where CompanyKey = @CompanyKey

	exec spTime ''tWebDavFile_FromServer'', @t output

	Print ''tWebDavFileHistory''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWebDavFileHistory'')
	drop table PABackup.dbo.tWebDavFileHistory
	 
	Select tWebDavFileHistory.* Into PABackup.dbo.tWebDavFileHistory 
	FROM tWebDavFileHistory (nolock), tWebDavFile b (nolock) 
	WHERE b.CompanyKey = @CompanyKey
	AND   tWebDavFileHistory.FileKey = b.FileKey

	exec spTime ''tWebDavFileHistory'', @t output
	
	Print ''tWebDavLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWebDavLog'')
	drop table PABackup.dbo.tWebDavLog
	 
	Select tWebDavLog.* Into PABackup.dbo.tWebDavLog 
	FROM tWebDavLog (nolock)
	WHERE tWebDavLog.CompanyKey = @CompanyKey
	
	exec spTime ''tWebDavLog'', @t output
	
	Print ''tWebDavSecurity''
	if exists (select * from PABackup.dbo.sysobjects where name=''tWebDavSecurity'')
	drop table PABackup.dbo.tWebDavSecurity
	 
	Select tWebDavSecurity.* Into PABackup.dbo.tWebDavSecurity 
	FROM tWebDavSecurity (nolock)
	WHERE tWebDavSecurity.CompanyKey = @CompanyKey

	exec spTime ''tWebDavSecurity'', @t output
	
	Print ''tVPaymentLog''
	if exists (select * from PABackup.dbo.sysobjects where name=''tVPaymentLog'')
	drop table PABackup.dbo.tVPaymentLog

	Select tVPaymentLog.* Into PABackup.dbo.tVPaymentLog 
	FROM tVPaymentLog (nolock)
	WHERE tVPaymentLog.CompanyKey = @CompanyKey

	exec spTime ''tVPaymentLog'', @t output

	Print ''tPlaidItem''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPlaidItem'')
	drop table PABackup.dbo.tPlaidItem

	Select tPlaidItem.* Into PABackup.dbo.tPlaidItem 
	FROM tPlaidItem (nolock)
	WHERE tPlaidItem.CompanyKey = @CompanyKey

	exec spTime ''tPlaidAccount'', @t output

	Print ''tPlaidAccount''
	if exists (select * from PABackup.dbo.sysobjects where name=''tPlaidAccount'')
	drop table PABackup.dbo.tPlaidAccount

	Select tPlaidAccount.* Into PABackup.dbo.tPlaidAccount 
	FROM tPlaidAccount (nolock)
	JOIN tPlaidItem (nolock) on tPlaidItem.PlaidItemKey = tPlaidAccount.PlaidAccountKey
	WHERE tPlaidItem.CompanyKey = @CompanyKey

	exec spTime ''tPlaidAccount'', @t output

	IF @BackupPath IS NOT NULL
	BEGIN

		-- Password created WJ + company key 
		DECLARE @Pwd varchar(25)
		DECLARE @filename varchar(1000) 
		SELECT @Pwd = ''WJ'', @filename = cast(YEAR(GETDATE()) as varchar)


		if MONTH(GETDATE()) < 10
			Select @Pwd = @Pwd + ''0'', @filename = @filename + ''0'' 

		Select @Pwd = @Pwd + convert(varchar(2),MONTH(GETDATE())), @filename = @filename + convert(varchar(2),MONTH(GETDATE()))

		if DAY(GETDATE()) < 10
			Select @Pwd = @Pwd + ''0'', @filename = @filename + ''0'' 

		Select @Pwd = @Pwd + convert(varchar(2),DAY(GETDATE())), @filename = @filename + convert(varchar(2),DAY(GETDATE()))

		Select @Pwd = @Pwd +  convert(varchar(25),@CompanyKey), @filename = convert(varchar(25),@CompanyKey) + ''_'' + convert(varchar(25),DATEDIFF(s, ''1970-01-01 00:00:00'', GETUTCDATE())) + ''_'' +  @filename


		--Backup Database using CompanyKey as name of file
		--SELECT @DataBackup = @BackupPath + CAST(@CompanyKey AS varchar) + ''.bak''
		SELECT @DataBackup = @BackupPath + @filename + ''.bak''

-- SECTION TO DELETE A FILE (NEEDED BECAUSE OF THE PASSWORDS)
		/*

		Not needed anymore because we are using a unique name per day

		-- To allow advanced options to be changed.
		EXEC sp_configure ''show advanced options'', 1

		-- To update the currently configured value for advanced options.
		RECONFIGURE

		-- To enable the feature.
		EXEC sp_configure ''xp_cmdshell'', 1

		-- To update the feature.
		RECONFIGURE

		--EXEC xp_cmdshell ''del c:\backup\100.bak''
		declare @cmdDelete varchar(100)
		select @cmdDelete = ''del '' + @DataBackup
		EXEC xp_cmdshell @cmdDelete

		 -- To disable the feature.
		EXEC sp_configure ''xp_cmdshell'', 0

		-- To update the feature.
		RECONFIGURE

		-- To disallow advanced options to be changed.
		EXEC sp_configure ''show advanced options'', 0

		-- To update the currently configured value for advanced options.
		RECONFIGURE
		*/

-- END SECTION TO DELETE A FILE (NEEDED BECAUSE OF THE PASSWORDS)


		-- Create the backup device for the full backup.
		EXEC sp_addumpdevice ''disk'', ''PABackup_dat'', @DataBackup

		-- Back up the full database.
		-- If you get an ACCESS DENIED error, make sure that you have folder rights for NETWORK SERVICE
		-- Usually it will be c:\backup 

		IF @WithPassword = 0 
			BACKUP DATABASE PABackup TO PABackup_dat With INIT 
		ELSE 
			BACKUP DATABASE PABackup TO PABackup_dat With INIT--, MEDIAPASSWORD = @Pwd 

		EXEC sp_dropdevice ''PABackup_dat''

		/* To restore, use the following command

		RESTORE DATABASE PARestore 
		FROM DISK = ''c:\temp\100.bak''
		WITH MEDIAPASSWORD = ''WJ0813100''
		,MOVE ''PABackup'' to ''C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\PARestore.mdf''
		,MOVE ''PABackup_log'' to ''C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\PARestore_log.ldf''
		,REPLACE

		*/

		DECLARE @BackupComments VARCHAR(8000) = ''''
		
		SELECT @BackupComments = ''Hi there,'' + ''<br><br>''
		SELECT @BackupComments = @BackupComments + ''A backup of your Workamajig database has been created and can be downloaded at: '' + ''<br><br><br><br>''
		SELECT @BackupComments = @BackupComments + ''To restore database, type the following command:'' + ''<br><br>''
		SELECT @BackupComments = @BackupComments + '''' + ''<br><br>''
		SELECT @BackupComments = @BackupComments + ''RESTORE DATABASE PARestore'' + ''<br><br>''

		IF @WithPassword = 1 
		BEGIN
			SELECT @BackupComments = @BackupComments + ''FROM DISK = ''''c:\temp\'' + @filename + ''.bak'''''' + ''<br><br>''
			SELECT @BackupComments = @BackupComments + ''WITH MEDIAPASSWORD = '''''' + @Pwd + '''''''' + ''<br><br>''
			SELECT @BackupComments = @BackupComments + '',MOVE ''''PABackup'''' to ''''C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\PARestore.mdf'''''' + ''<br><br>''
			SELECT @BackupComments = @BackupComments + '',MOVE ''''PABackup_log'''' to ''''C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA\PARestore_log.ldf'''''' + ''<br><br>''
			SELECT @BackupComments = @BackupComments + '',REPLACE'' + ''<br><br>''
		END
		ELSE
		BEGIN
			SELECT @BackupComments = @BackupComments + ''FROM DISK = ''''c:\temp\'' + @filename + ''.bak'''''' + ''<br><br>''
			SELECT @BackupComments = @BackupComments + ''WITH MOVE ''''PABackup'''' TO ''''C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\PARestore.mdf'''''' + ''<br><br>''
			SELECT @BackupComments = @BackupComments + '',MOVE ''''PABackup_log'''' TO ''''C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\PARestore_log.ldf'''''' + ''<br><br>''
		END

		SELECT @BackupComments = @BackupComments + ''This script assumes that you have SQL server running on the C: drive of the server.'' + ''<br><br>''
		SELECT @BackupComments = @BackupComments + ''This backup will be available for 30 days or until you request another backup (whichever is sooner). Please download your database and store it in a secure location.'' + ''<br><br>''
		SELECT @BackupComments = @BackupComments + ''Please let me know if I can be of further assistance.'' + ''<br><br>''
		SELECT @BackupComments = @BackupComments + ''Regards,''

		PRINT @BackupComments

		DECLARE @BackupDuration INT -- in seconds
		SELECT @BackupDuration = DATEDIFF(ss, @start, @t)
		
		UPDATE tBackupLog
		   SET DoBackup = 0,
			   DateCreated = GETDATE(),
			   BackupFileName = @filename + ''.bak'',
			   BackupDuration = @BackupDuration,
			   BackupComments = @BackupComments
		 WHERE CompanyKey = @CompanyKey
		   and DateCreated IS NULL

	END

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptWidgetDashDelete]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[sptWidgetDashDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptWidgetDashDelete]
(
	@WidgetDashKey int
)

as


Delete tReport Where WidgetTabKey in (select WidgetTabKey from tWidgetTab (nolock) Where WidgetDashKey = @WidgetDashKey)

Delete tSecurityAccess Where Entity = ''tWidgetTab'' and EntityKey in (select WidgetTabKey from tWidgetTab (nolock) Where WidgetDashKey = @WidgetDashKey)

Delete tSecurityAccess Where Entity = ''tWidgetDash'' and EntityKey = @WidgetDashKey

Delete tWidgetTab Where WidgetDashKey = @WidgetDashKey

-- clear any recent/favorite rows pointing at this dashboard so no orphans remain
Delete tRecentFavorite Where Entity = ''tWidgetDash'' and EntityKey = @WidgetDashKey

Delete tWidgetDash Where WidgetDashKey = @WidgetDashKey


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCompanyDeleteAll]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[spCompanyDeleteAll]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[spCompanyDeleteAll]

	(
		@CompanyKey int
		,@DeleteSetupTables int = 1 
		,@DeleteTemplateProjects int = 1
		,@LeaveCoreCompany int = 1
	)

AS --Encrypt

/*
	Who		When		What
	GHL		09/19/05	Updated for version 800
	GHL		10/31/05	Updated for version 81
	GHL		01/26/05	Updated for version 82
	GHL		03/27/06	Updated for Version 83
	GHL		06/30/06	Updated for Version 835
						Added parameter @DeleteSetupTables for Harding
						If @DeleteSetupTables = 0 we delete transactions only
						If @DeleteSetupTables = 1 we delete setup + transactions table
    GHL     11/29/06    8.4 Changed order of some tables to prevent FK errors
    CRG		01/16/07    Updated to:
                          Delete tDashboardModuleUser where the UserKey is not in tUser
                          Delete tCalendarAttendeeGroup where CalendarKey is not in tCalendar
                          Delete tUser where CompanyKey is in tCompany where OwnerCompanyKey = @CompanyKey
    GHL     03/16/07    8.407 Added tProjectRollup, tSystemMessageUser                
    GHL		06/20/07	8.43 Added tInvoiceAdvanceBillTax
    QMD     07/16/07    8.4.3.2	Added the insert statement into tCalendarDelete  
    GHL     06/09/09    10.026 Added cash basis and wmj10.0 tables 
    GHL     06/09/09    10.5 Added wmj10.5 tables 
    GHL     09/29/09    10.5 Added deletion of tVoucherTax and tVoucherDetailTax
    GHL     09/29/09    10.5 Added deletion of tInvoiceTax 
    GHL     05/10/10    10.523 (80353) Added param @DeleteTemplateProjects so that we can keep template projects  
                        If you want to keep template projects, execute spCompanyDeleteAll 1, 0, 0   
    CRG     05/18/10    10.5.3.0 Modified because tTaskUser allows NULL UserKey now. Now the tTaskUser key is deleting based on tProject.CompanyKey rather than joining to tUser.
	GHL     06/20/11    (111045) Added missing tables
	GHL     08/16/11    Removed Catalog tables
	CRG     08/22/11    Added tWebDavSecurity
	GHL     09/29/11    Added tVoucherCC and tGLAccountUser for credit card charges
	CRG     11/13/12    Now deleting tAttachment based on CompanyKey
	KMC     05/06/13    (213678) Added @LeaveCoreCompany parameter to wipe everything but the main company,
						and the employees, tPreference record, tTimeOption. 
	GWG     4/22/15		If leave core company, it was still trying to delete tCompany and tWebdavsecurity.
	MAS     10/18/18	Added tPlaidItem and tPlaidAccount
	RLS		02/12/19	(441481) Changed references from tApprovalStepDefNotify to tApprovalStepNotifyDef
	GWG     01/02/20	Remove the check for delete setup tables for tApprovalStep and Deliverable Comments
	KMC     05/04/22    Removed tAttribute, tAttributeEntityValue, and tAttributeValue
						Temporarily disabled triggers around tCalendarAttendee and tCalendar
						Added delete of tReviewCommentMarkup for Approval Steps
	CRG     10/10/22    Added tBlockoutCache
	KMC     10/12/22    Added tCompanyMediaAttributeValue
	KMC     10/31/22    Added tAssignment by UserKey
	KMC     11/04/22	Added tAttachmentBackup
	CRG		11/07/22	Added tTimeRollup, tTimeRollupDetail, tReminderCache, tReminderCacheCompany
	KMC     11/07/22    Added tAvalaraTaxCode
	KMC     11/08/22    Added tTaskAssignmentType to tMasterTaskAssignment
	CRG		11/21/22	Added tTimeItemRollup
	KMC     05/16/23    Added tProjectServices
	GAR     05/16/23    Added tAvalaraRegion
	GAR     05/16/23    Added tInvoiceTaxAvalara
	CRG     05/16/23    Added tTaskPriority
	KMC     10/10/23    Changed tActivationLog to match tUser to only delete when @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
	GAR     04/01/24    Added tAvalaraTaxData, tProjectAddress
	GAR		01/21/25    Removed all references to tWidget and added tWidgetDef
	GAR		05/29/25    Temporarily removed tWidgetDef since the table isn''t in prod yet
	KMC     6/1/2026	Added tEmailTemplate and tEmailTemplateSection
	MAS     07/30/26    (733785) Added tOFXGLAccountLink
*/

Declare @OFSKey int
Declare @CurKey int
Declare @CurKey2 int

--begin tran

--Delete Entity Relationships first

Select ''tActionLog''

Select ''tActionLog: FileVersion''
--tActionLog: FileVersion
Delete tActionLog 
from	tDAFileVersion fv, tDAFile f, tDAFolder fol, tProject p 
where	tActionLog.Entity = ''FileVersion''
and		tActionLog.EntityKey = fv.FileVersionKey
and		fv.FileKey = f.FileKey 
and		f.FolderKey = fol.FolderKey 
and		fol.ProjectKey = p.ProjectKey 
and		p.CompanyKey = @CompanyKey

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActionLog: New Entities''
--tActionLog: New Entitys
Delete tActionLog 
WHERE  tActionLog.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReminderCache'' --Needs to be before tActivity, tUser, and tCalendar

DELETE	tReminderCache
FROM	tCalendar
WHERE	tReminderCache.CalendarKey = tCalendar.CalendarKey
AND		tCalendar.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReminderCacheCompany''

DELETE	tReminderCacheCompany
WHERE	CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActivityLink''
Delete tActivityLink
FROM   tActivity a 
where  tActivityLink.ActivityKey = a.ActivityKey 
and    a.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActivityHistory''
Delete tActivityHistory
FROM   tActivity a 
where  tActivityHistory.ActivityKey = a.ActivityKey 
and    a.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActivityEmail''
Delete tActivityEmail
FROM   tActivity a 
where  tActivityEmail.ActivityKey = a.ActivityKey 
and    a.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActivity''
Delete tActivity 
WHERE  tActivity.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActivityType''
If @DeleteSetupTables = 1
Delete tActivityType 
WHERE  tActivityType.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDBLog''
--tDBLog
Delete tDBLog
from   tUser u (nolock)   
where  tDBLog.UserKey = u.UserKey
and    isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSecurityAccess''
If @DeleteSetupTables = 1
Delete tSecurityAccess Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAttachmentBackup''
Delete tAttachmentBackup
where AttachmentKey in (select AttachmentKey from tAttachment (nolock) where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAttachment''
Delete tAttachment
where	CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLink: ApprovalItem''
--tLink: ApprovalItem
Delete tLink
from	tApprovalItem ai, tApproval a, tProject p
where	tLink.AssociatedEntity = ''ApprovalItem''
and		tLink.EntityKey = ai.ApprovalItemKey
and		ai.ApprovalKey = a.ApprovalKey
and		a.ProjectKey = p.ProjectKey
and		p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLink: Note''
--tLink: Note
If @DeleteSetupTables = 1
Delete tLink
from	tNote n, tNoteGroup ng
where	tLink.AssociatedEntity = ''Note''
and		tLink.EntityKey = n.NoteKey
and		n.NoteGroupKey = ng.NoteGroupKey
and		ng.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLink: Forms''
--tLink: Forms
If @DeleteSetupTables = 1
Delete tLink
from	tForm f
where	tLink.AssociatedEntity = ''Forms''
and		tLink.EntityKey = f.FormKey
and		f.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLink: Lead''
--tLink: Lead
Delete tLink
from	tLead l
where	tLink.AssociatedEntity = ''Lead''
and		tLink.EntityKey = l.LeadKey
and		l.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSession''
--tSession: User
If @DeleteSetupTables = 1
Delete tSession
from	tUser u
where	tSession.Entity = ''user''
and		tSession.EntityKey = u.UserKey
and		ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSession''
--tSession: Report and Style
If @DeleteSetupTables = 1
Delete tSession
where	tSession.Entity in( ''report'', ''style'')
and		tSession.EntityKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSpecSheetLink''
Delete tSpecSheetLink where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSpecSheet''
--tSpecSheet: Project
Delete tSpecSheet
from	tProject p
where	tSpecSheet.Entity = ''Project''
and		tSpecSheet.EntityKey = p.ProjectKey
and		p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSpecSheet''
--tSpecSheet: ProjectRequest
Delete tSpecSheet
from	tRequest r
where	tSpecSheet.Entity = ''Project''
and		tSpecSheet.EntityKey = r.RequestKey
and		r.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSpecSheet''
--tSpecSheet: Lead
Delete tSpecSheet
from	tLead l (NOLOCK)
where	tSpecSheet.Entity = ''Lead''
and		tSpecSheet.EntityKey = l.LeadKey
and		l.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tFieldValue''
--tFieldValue
If @DeleteSetupTables = 1
Delete tFieldValue
from	tFieldDef fd
where	tFieldValue.FieldDefKey = fd.FieldDefKey
and	fd.OwnerEntityKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tObjectFieldSet''
--tObjectFieldSet
If @DeleteSetupTables = 1
Delete tObjectFieldSet
from	tFieldSetField fsf, tFieldDef fd
where	tObjectFieldSet.FieldSetKey = fsf.FieldSetKey
and		fsf.FieldDefKey = fd.FieldDefKey
and		fd.OwnerEntityKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteSetupTables = 1
Delete tObjectFieldSet
where	FieldSetKey in (
	Select FieldSetKey from tFieldSet Where
	OwnerEntityKey = @CompanyKey
	and AssociatedEntity not in (''Forms'', ''TaskAssignmentTypes'')
)
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteSetupTables = 1
Delete tObjectFieldSet
where	tObjectFieldSet.FieldSetKey in (
	Select FieldSetKey 
	from tFieldSet, tFormDef fd 
	Where
		tFieldSet.AssociatedEntity = ''Forms''
	and	tFieldSet.OwnerEntityKey = fd.FormDefKey
	and	fd.CompanyKey = @CompanyKey
)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFieldSetField''
--tFieldSetField
If @DeleteSetupTables = 1
Delete tFieldSetField
from	tFieldDef fd
where	tFieldSetField.FieldDefKey = fd.FieldDefKey
and	fd.OwnerEntityKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFieldDef''
--tFieldDef
If @DeleteSetupTables = 1
Delete tFieldDef
where	OwnerEntityKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFieldSet''
--tFieldSet
If @DeleteSetupTables = 1
Delete tFieldSet
where	OwnerEntityKey = @CompanyKey
and		AssociatedEntity not in (''Forms'', ''TaskAssignmentTypes'')
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFieldSet''
If @DeleteSetupTables = 1
Delete tFieldSet
from	tFormDef fd
where	tFieldSet.AssociatedEntity = ''Forms''
and	tFieldSet.OwnerEntityKey = fd.FormDefKey
and	fd.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFormDefSecurityGroup''
--tFormDefSecurityGroup
If @DeleteSetupTables = 1
Delete tFormDefSecurityGroup
from	tFormDef fd
where	tFormDefSecurityGroup.FormDefKey = fd.FormDefKey
and		fd.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

--tViewSecurityGroup
-- Added for 835
If @DeleteSetupTables = 1
Delete tViewSecurityGroup
From   tSecurityGroup sg
Where  tViewSecurityGroup.SecurityGroupKey = sg.SecurityGroupKey
and	   sg.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTeamUser''
-- Added for 800
If @DeleteSetupTables = 1
Delete tTeamUser 
From tTeam t
Where t.CompanyKey = @CompanyKey
And t.TeamKey = tTeamUser.TeamKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTeam''
-- Added for 800
If @DeleteSetupTables = 1
Delete tTeam Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTaskUser''
-- Added for 800
Delete tTaskUser
From   tTask t
      ,tProject p
Where  tTaskUser.TaskKey = t.TaskKey
And    t.ProjectKey =  p.ProjectKey
And    p.CompanyKey = @CompanyKey
And    isnull(p.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tTaskUser
	From   tTask t
		  ,tProject p
	Where  tTaskUser.TaskKey = t.TaskKey
	And    t.ProjectKey =  p.ProjectKey
	And    p.CompanyKey = @CompanyKey
	And    isnull(p.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tPreferenceDARights''
-- Added for 800
If @DeleteSetupTables = 1
Delete tPreferenceDARights Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSpecSheetLink''

-- Added for 800
Delete tSpecSheetLink Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectTypeMasterTask''

-- Added for 800
If @DeleteSetupTables = 1
Delete tProjectTypeMasterTask
From   tProjectType pt 
Where pt.CompanyKey = @CompanyKey
And tProjectTypeMasterTask.ProjectTypeKey = pt.ProjectTypeKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectTypeService''

-- Added for 800
If @DeleteSetupTables = 1
Delete tProjectTypeService
From   tProjectType pt 
Where pt.CompanyKey = @CompanyKey
And tProjectTypeService.ProjectTypeKey = pt.ProjectTypeKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMasterTaskAssignment''

-- Added for 800
If @DeleteSetupTables = 1
Delete tMasterTaskAssignment
From   tMasterTask mt 
Where mt.CompanyKey = @CompanyKey
And tMasterTaskAssignment.MasterTaskKey = mt.MasterTaskKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMasterTaskAssignment2''

If @DeleteSetupTables = 1
Delete tMasterTaskAssignment
From   tTaskAssignmentType tat 
Where tat.CompanyKey = @CompanyKey
And tMasterTaskAssignment.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectUserServices''

-- Added for 800
Delete tProjectUserServices
From   tProject p 
Where p.CompanyKey = @CompanyKey
And tProjectUserServices.ProjectKey = p.ProjectKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectEstByItem''

-- Added for 800
Delete tProjectEstByItem from tProject Where tProjectEstByItem.ProjectKey = tProject.ProjectKey and tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectNoteLink''

-- Added for 800
Delete tProjectNoteLink
From tProjectNote pn 
Where tProjectNoteLink.ProjectNoteKey = pn.ProjectNoteKey
And pn.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectNoteUser''

-- Added for 800
Delete tProjectNoteUser
From tProjectNote pn 
Where tProjectNoteUser.ProjectNoteKey = pn.ProjectNoteKey
And pn.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectNote''

-- Added for 800
Delete tProjectNote Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTime_DELETED''

Delete tTime_DELETED from tUser Where tTime_DELETED.UserKey = tUser.UserKey and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTime_DELETED''

Delete tTimeSheet_DELETED from tUser Where tTimeSheet_DELETED.UserKey = tUser.UserKey and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTime''

Delete tTime from tUser Where tTime.UserKey = tUser.UserKey and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimeSheet''

Delete tTimeSheet Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimelineSegment''

Delete tTimelineSegment Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tExpenseReceipt''

Delete tExpenseReceipt from tExpenseEnvelope Where tExpenseReceipt.ExpenseEnvelopeKey = tExpenseEnvelope.ExpenseEnvelopeKey and 
	tExpenseEnvelope.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tExpenseEnvelope''

Delete tExpenseEnvelope Where tExpenseEnvelope.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMiscCost''

Delete tMiscCost from tProject Where tMiscCost.ProjectKey = tProject.ProjectKey and tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''spCF_tObjectFieldSetDelete''
If @DeleteSetupTables = 1
BEGIN

Select @CurKey = 0
While 1 = 1
Begin
	Select @CurKey = Min(FormKey) from tForm Where FormKey > @CurKey and CompanyKey = @CompanyKey
	if @CurKey IS NULL
		Break
	Select @OFSKey = CustomFieldKey from tForm Where FormKey = @CurKey
	exec spCF_tObjectFieldSetDelete @OFSKey

	if	@@error != 0
	begin
		--rollback tran
		return -1
	end

End
END

Select ''tApprovalItemReply''

Delete tApprovalItemReply from tApprovalItem, tApproval, tProject Where tApprovalItemReply.ApprovalItemKey = tApprovalItem.ApprovalItemKey and
	tApprovalItem.ApprovalKey = tApproval.ApprovalKey and tApproval.ProjectKey = tProject.ProjectKey and tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalItem''

Delete tApprovalItem from tApproval, tProject Where tApprovalItem.ApprovalKey = tApproval.ApprovalKey and tApproval.ProjectKey = tProject.ProjectKey and tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalList''

Delete tApprovalList from tApproval, tProject Where tApprovalList.ApprovalKey = tApproval.ApprovalKey and tApproval.ProjectKey = tProject.ProjectKey and
	tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalUpdateList''

-- Added for 800
Delete tApprovalUpdateList from tApproval, tProject Where tApprovalUpdateList.ApprovalKey = tApproval.ApprovalKey and tApproval.ProjectKey = tProject.ProjectKey and
	tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tReviewCommentMarkup''
Delete tReviewCommentMarkup
FROM tReviewComment, tReviewRound, tReviewDeliverable, tProject
WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
And tProject.CompanyKey = @CompanyKey
and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
and tReviewRound.ReviewRoundKey = tReviewComment.ReviewRoundKey
and tReviewComment.ReviewCommentKey = tReviewCommentMarkup.ReviewCommentKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReviewComment''
Delete tReviewComment
FROM tReviewRound, tReviewDeliverable, tProject
WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
And tProject.CompanyKey = @CompanyKey
and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
and tReviewRound.ReviewRoundKey = tReviewComment.ReviewRoundKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReviewRoundFile''
Delete tReviewRoundFile
FROM tReviewRound, tReviewDeliverable, tProject
WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
And tProject.CompanyKey = @CompanyKey
and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
and tReviewRound.ReviewRoundKey = tReviewRoundFile.ReviewRoundKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReviewRound''
Delete tReviewRound
FROM tReviewDeliverable, tProject
WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
And tProject.CompanyKey = @CompanyKey
and tReviewRound.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tReviewLog''
Delete tReviewLog
FROM tReviewDeliverable, tProject
WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
And tProject.CompanyKey = @CompanyKey
and tReviewLog.ReviewDeliverableKey = tReviewDeliverable.ReviewDeliverableKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReviewDeliverable''
Delete tReviewDeliverable
FROM tProject
WHERE tReviewDeliverable.ProjectKey = tProject.ProjectKey 
And tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApproval''

Delete tApproval from tProject Where tApproval.ProjectKey = tProject.ProjectKey and tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalStepUserDef''
If @DeleteSetupTables = 1
delete tApprovalStepUserDef from tApprovalStepDef asd where tApprovalStepUserDef.ApprovalStepDefKey = asd.ApprovalStepDefKey and asd.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalStepUser''
delete tApprovalStepUser from tApprovalStep aps where tApprovalStepUser.ApprovalStepKey = aps.ApprovalStepKey and aps.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalStepNotifyDef''
If @DeleteSetupTables = 1
delete tApprovalStepNotifyDef 
from tApprovalStepDef 
where tApprovalStepDef.CompanyKey = @CompanyKey
and tApprovalStepNotifyDef.ApprovalStepDefKey = tApprovalStepDef.ApprovalStepDefKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalStepDef''
If @DeleteSetupTables = 1
delete tApprovalStepDef where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalStepNotify''

delete tApprovalStepNotify 
from tApprovalStep 
where tApprovalStep.CompanyKey = @CompanyKey
and tApprovalStepNotify.ApprovalStepKey = tApprovalStep.ApprovalStepKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

select ''tReviewCommentMarkup''
delete tReviewCommentMarkup
 where ReviewCommentKey in (select ReviewCommentKey
							  from tReviewComment (nolock)
							 where ApprovalStepKey in (select ApprovalStepKey from tApprovalStep (nolock) where CompanyKey = @CompanyKey))

Select ''tReviewComment''
delete tReviewComment Where ApprovalStepKey in (select ApprovalStepKey from tApprovalStep (nolock) where CompanyKey = @CompanyKey)


Select ''tApprovalStep''
delete tApprovalStep where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tApprovalType''
If @DeleteSetupTables = 1
delete tApprovalType where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tActivationLog''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
delete tActivationLog from tUser u where tActivationLog.UserKey = u.UserKey and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarType''
If @DeleteSetupTables = 1
delete tCalendarType where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarUser''
delete tCalendarUser from tUser u where tCalendarUser.UserKey = u.UserKey and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarLink''

delete tCalendarLink
FROM   tCalendar c 
where  tCalendarLink.CalendarKey = c.CalendarKey 
and    c.CompanyKey = @CompanyKey 

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarReminder''

delete tCalendarReminder
FROM   tUser u 
where  tCalendarReminder.UserKey = u.UserKey 
and    isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey 

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarUpdateLog''

delete tCalendarUpdateLog
FROM   tCalendar c 
where  tCalendarUpdateLog.CalendarKey = c.CalendarKey 
and    c.CompanyKey = @CompanyKey 

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCMFolderIncludeInSync''
	
delete tCMFolderIncludeInSync
FROM  tCMFolder f
WHERE tCMFolderIncludeInSync.CMFolderKey = f.CMFolderKey
and   f.CompanyKey = @CompanyKey

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCMFolderSecurity''
	
delete tCMFolderSecurity
FROM  tCMFolder f
WHERE tCMFolderSecurity.CMFolderKey = f.CMFolderKey
and   f.CompanyKey = @CompanyKey

if	@@error != 0
begin
	--rollback tran
	return -1
end
		
Select ''tCampaignBudgetItem''

-- Added for 800
If @DeleteSetupTables = 1
delete tCampaignBudgetItem
from tCampaign c (NOLOCK)
where tCampaignBudgetItem.CampaignKey = c.CampaignKey
and c.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCampaignBudget''

-- Added for 800
If @DeleteSetupTables = 1
delete tCampaignBudget
from tCampaign c (NOLOCK)
where tCampaignBudget.CampaignKey = c.CampaignKey
and c.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCheckFormat''
If @DeleteSetupTables = 1
delete tCheckFormat where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCheckMethod''
If @DeleteSetupTables = 1
delete tCheckMethod where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tClass''
If @DeleteSetupTables = 1
delete tClass where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tContactDatabaseAssignment''
If @DeleteSetupTables = 1
delete tContactDatabaseAssignment from tContactDatabase cd where tContactDatabaseAssignment.ContactDatabaseKey = cd.ContactDatabaseKey and cd.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tContactDatabaseUser''
If @DeleteSetupTables = 1
delete tContactDatabaseUser from tContactDatabase cd where tContactDatabaseUser.ContactDatabaseKey = cd.ContactDatabaseKey and cd.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tContactDatabase''
If @DeleteSetupTables = 1
delete tContactDatabase where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDAFileRight''

delete tDAFileRight from tDAFile f, tDAFolder fol, tProject p where tDAFileRight.FileKey = f.FileKey and f.FolderKey = fol.FolderKey and fol.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDAFileVersion''

delete tDAFileVersion from tDAFile f, tDAFolder fol, tProject p where tDAFileVersion.FileKey = f.FileKey and f.FolderKey = fol.FolderKey and fol.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDAFolderRight''

delete tDAFolderRight from tDAFolder fol, tProject p where tDAFolderRight.FolderKey = fol.FolderKey and fol.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDAFile''

delete tDAFile from tDAFolder fol, tProject p where tDAFile.FolderKey = fol.FolderKey and fol.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDAFolder''

delete tDAFolder from tProject p where tDAFolder.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDAClientFolder''

delete tDAClientFolder from tProject p where tDAClientFolder.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tDeposit''
If @DeleteSetupTables = 1
delete tDeposit where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tItemRateSheetDetail''

-- Added for 800 
If @DeleteSetupTables = 1
Delete tItemRateSheetDetail 
from tItemRateSheet 
Where tItemRateSheetDetail.ItemRateSheetKey = tItemRateSheet.ItemRateSheetKey 
and tItemRateSheet.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

-- Added for 800 
Select ''tItemRateSheet''
If @DeleteSetupTables = 1
Delete tItemRateSheet where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tItem''
If @DeleteSetupTables = 1
Delete tItem where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tJournalEntryDetail''

Delete tJournalEntryDetail from tJournalEntry je where tJournalEntryDetail.JournalEntryKey = je.JournalEntryKey and je.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tJournalEntry''

Delete tJournalEntry where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLaborBudgetDetail''
If @DeleteSetupTables = 1
Delete tLaborBudgetDetail from tLaborBudget lb where tLaborBudgetDetail.LaborBudgetKey = lb.LaborBudgetKey and lb.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLaborBudget''
If @DeleteSetupTables = 1
Delete tLaborBudget where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tNote''
If @DeleteSetupTables = 1
Delete tNote from tNoteGroup ng where tNote.NoteGroupKey = ng.NoteGroupKey and ng.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tNoteGroup''
If @DeleteSetupTables = 1
Delete tNoteGroup where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tOffice''
If @DeleteSetupTables = 1
Delete tOffice where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPaymentDetail''

Delete tPaymentDetail from tPayment p where tPaymentDetail.PaymentKey = p.PaymentKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPayment''

Delete tPayment where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectCreativeBrief''

Delete tProjectCreativeBrief from tProject p where tProjectCreativeBrief.ProjectKey = p.ProjectKey and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tRequestDefSpec''

Delete tRequestDefSpec from tRequestDef rd where tRequestDefSpec.RequestDefKey = rd.RequestDefKey and rd.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tRequest''

Delete tRequest where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tRequestDef''

Delete tRequestDef where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tStandardText''
If @DeleteSetupTables = 1
Delete tStandardText where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tStandardText''
If @DeleteSetupTables = 1
Delete tStandardActivity where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSyncActivity''
Delete tSyncActivity
FROM   tCompany c
where  tSyncActivity.CompanyKey = c.CompanyKey
and    isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey	
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSyncFolder''
Delete tSyncFolder
FROM   tCompany c
where  tSyncFolder.CompanyKey = c.CompanyKey
and    isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey	
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSyncItem''
Delete tSyncItem
FROM   tCompany c
where  tSyncItem.CompanyKey = c.CompanyKey
and    isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey	
if	@@error != 0
begin
	--rollback tran
	return -1
end
	
Select ''tTransaction''

Delete tTransaction where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTransactionUnpostLog''

Delete tTransactionUnpostLog where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTransactionUnpost''

Delete tTransactionUnpost where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTransactionOrderAccrual''

Delete tTransactionOrderAccrual where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCashTransaction''

Delete tCashTransaction where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCashTransactionLine''

Delete tCashTransactionLine where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserGroup''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserGroup where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserPassword''

-- Added for 800
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserPassword from tUser u where tUserPassword.UserKey = u.UserKey and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserNotification''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserNotification from tUser u where tUserNotification.UserKey = u.UserKey and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserPreference''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserPreference from tUser u where tUserPreference.UserKey = u.UserKey and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserService''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserService from tUser u where tUserService.UserKey = u.UserKey and ISNULL(u.OwnerCompanyKey,u.CompanyKey) = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tWIPPostingDetail''

-- Added for 800
Delete tWIPPostingDetail 
From tWIPPosting w
where w.CompanyKey = @CompanyKey
And tWIPPostingDetail.WIPPostingKey = w.WIPPostingKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tWIPPosting''

Delete tWIPPosting where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tBillingDetail''

-- Added for 82
Delete tBillingDetail 
From tBilling b
where b.CompanyKey = @CompanyKey
And tBillingDetail.BillingKey = b.BillingKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tBillingFixedFee''

-- Added for 82
Delete tBillingFixedFee 
From tBilling b
where b.CompanyKey = @CompanyKey
And tBillingFixedFee.BillingKey = b.BillingKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tBillingPayment''

-- Added for 82
Delete tBillingPayment 
From tBilling b
where b.CompanyKey = @CompanyKey
And tBillingPayment.BillingKey = b.BillingKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tBilling''

Delete tBilling where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tBillingSchedule''

-- Added for 82
Delete tBillingSchedule 
From tProject p
where p.CompanyKey = @CompanyKey
And tBillingSchedule.ProjectKey = p.ProjectKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tWriteOffReason''
If @DeleteSetupTables = 1
Delete tWriteOffReason where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFormSubscription''

-- Moved for 800 (FK violation)
If @DeleteSetupTables = 1
Delete tFormSubscription from tUser Where tFormSubscription.UserKey = tUser.UserKey and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tForm''
If @DeleteSetupTables = 1
Delete tForm Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tFormDef''
If @DeleteSetupTables = 1
Delete tFormDef Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCompanyMediaAttributeValue''

If @DeleteSetupTables = 1
Delete tCompanyMediaAttributeValue
From tCompanyMedia cm (nolock)
Where cm.CompanyKey = @CompanyKey
And tCompanyMediaAttributeValue.CompanyMediaKey = cm.CompanyMediaKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCompanyMediaContact''

-- Added for 800
If @DeleteSetupTables = 1
Delete tCompanyMediaContact 
From tCompanyMedia cm (nolock)
Where cm.CompanyKey = @CompanyKey
And tCompanyMediaContact.CompanyMediaKey = cm.CompanyMediaKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCompanyMedia''

-- Added for 800
If @DeleteSetupTables = 1
Delete tCompanyMedia Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMediaEstimate''

-- Added for 800
If @DeleteSetupTables = 1
Delete tMediaEstimate Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPurchaseOrderUser''

-- Added for 800
Delete tPurchaseOrderUser from tPurchaseOrder Where tPurchaseOrderUser.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey and
	tPurchaseOrder.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPurchaseOrderTraffic''

-- Added for 800
Delete tPurchaseOrderTraffic from tPurchaseOrder Where tPurchaseOrderTraffic.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey and
	tPurchaseOrder.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPurchaseOrderDetail''

-- Still need to loop to take care of custom fields ? do in ASP
Delete tPurchaseOrderDetail from tPurchaseOrder Where tPurchaseOrderDetail.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey and
	tPurchaseOrder.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPurchaseOrder''

Delete tPurchaseOrder Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tQuoteReplyDetail''

Delete tQuoteReplyDetail from tQuoteReply, tQuote Where tQuoteReplyDetail.QuoteReplyKey = tQuoteReply.QuoteReplyKey and
	tQuoteReply.QuoteKey = tQuote.QuoteKey and tQuote.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tQuoteReply''

Delete tQuoteReply from tQuote Where tQuoteReply.QuoteKey = tQuote.QuoteKey and tQuote.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tQuoteDetail''

Delete tQuoteDetail from tQuote Where tQuoteDetail.QuoteKey = tQuote.QuoteKey and tQuote.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tQuote''

Delete tQuote Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceAdvanceBill''

Delete tInvoiceAdvanceBill from tInvoice i where tInvoiceAdvanceBill.InvoiceKey = i.InvoiceKey and i.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceAdvanceBillTax''

Delete tInvoiceAdvanceBillTax from tInvoice i where tInvoiceAdvanceBillTax.InvoiceKey = i.InvoiceKey and i.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tInvoiceAdvanceBillSale''

Delete tInvoiceAdvanceBillSale from tInvoice i where tInvoiceAdvanceBillSale.InvoiceKey = i.InvoiceKey and i.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceTemplate''
If @DeleteSetupTables = 1
Delete tInvoiceTemplate where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCheckAppl''

Delete tCheckAppl from tInvoice Where tCheckAppl.InvoiceKey = tInvoice.InvoiceKey and tInvoice.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCheckAppl''

Delete tCheckAppl from tCheck c, tCompany com where tCheckAppl.CheckKey = c.CheckKey and  c.ClientKey = com.CompanyKey and com.OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tCheck''

Delete tCheck from tCompany Where tCheck.ClientKey = tCompany.CompanyKey and tCompany.OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceLineTax''

-- Added for 800
Delete tInvoiceLineTax 
from tInvoice (nolock)
	,tInvoiceLine (nolock)
Where tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey and tInvoice.CompanyKey = @CompanyKey
and tInvoiceLineTax.InvoiceLineKey = tInvoiceLine.InvoiceLineKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceLine''

Delete tInvoiceLine from tInvoice Where tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey and tInvoice.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceLine''

Delete tInvoiceTax from tInvoice Where tInvoiceTax.InvoiceKey = tInvoice.InvoiceKey and tInvoice.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end
Select ''tInvoice''

Delete tInvoice Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimeRateSheetDetail''
If @DeleteSetupTables = 1
Delete tTimeRateSheetDetail 
from tTimeRateSheet 
Where tTimeRateSheetDetail.TimeRateSheetKey = tTimeRateSheet.TimeRateSheetKey 
and tTimeRateSheet.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tTimeRateSheet''
If @DeleteSetupTables = 1
Delete tTimeRateSheet Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tVoucherDetailTax''

Delete tVoucherDetailTax Where VoucherDetailKey in (Select tVoucherDetail.VoucherDetailKey 
from tVoucherDetail, tVoucher
Where tVoucher.CompanyKey = @CompanyKey
And tVoucher.VoucherKey = tVoucherDetail.VoucherKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tVoucherDetail''

Delete tVoucherDetail Where VoucherKey in (Select VoucherKey from tVoucher Where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tVoucherTax''

Delete tVoucherTax Where VoucherKey in (Select VoucherKey from tVoucher Where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tVoucherCC''

Delete tVoucherCC
from   tVoucher
Where  tVoucher.CompanyKey = @CompanyKey
and    tVoucher.VoucherKey = tVoucherCC.VoucherKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tVoucherCredit''

Delete tVoucherCredit
from   tVoucher
Where  tVoucher.CompanyKey = @CompanyKey
and    tVoucher.VoucherKey = tVoucherCredit.VoucherKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tVoucher''

Delete tVoucher Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tWorkType''
If @DeleteSetupTables = 1
Delete tWorkType Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEstimateTemplate''
If @DeleteSetupTables = 1
Delete tEstimateTemplate where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEstimateProject''
Delete tEstimateProject 
from tEstimate e
where tEstimateProject.EstimateKey = e.EstimateKey 
and e.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEstimateTaskTemp''
Delete tEstimateTaskTemp
from tProject p
where tEstimateTaskTemp.ProjectKey = p.ProjectKey 
and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEstimateTaskTempPredecessor''
Delete tEstimateTaskTempPredecessor
from tProject p, tTask t
where tEstimateTaskTempPredecessor.TaskKey = t.TaskKey
and t.ProjectKey = p.ProjectKey 
and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEstimateTaskTempUser''
Delete tEstimateTaskTempUser
from tProject p, tTask t
where tEstimateTaskTempUser.TaskKey = t.TaskKey
and t.ProjectKey = p.ProjectKey 
and p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tEstimateTaskExpense''
Delete tEstimateTaskExpense 
from tEstimate e
where tEstimateTaskExpense.EstimateKey = e.EstimateKey 
and e.CompanyKey = @CompanyKey
and e.ProjectKey is null
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimateTaskExpense 
from tEstimate e
, tProject p 
where tEstimateTaskExpense.EstimateKey = e.EstimateKey 
and e.ProjectKey = p.ProjectKey 
and e.CompanyKey = @CompanyKey
and isnull(p.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimateTaskExpense 
	from tEstimate e
	, tProject p 
	where tEstimateTaskExpense.EstimateKey = e.EstimateKey 
	and e.ProjectKey = p.ProjectKey 
	and e.CompanyKey = @CompanyKey
	and isnull(p.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tEstimateTaskLabor''

Delete tEstimateTaskLabor 
from tEstimate e
where tEstimateTaskLabor.EstimateKey = e.EstimateKey 
and e.CompanyKey = @CompanyKey
and e.ProjectKey is null 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimateTaskLabor 
from tEstimate e
, tProject p 
where tEstimateTaskLabor.EstimateKey = e.EstimateKey 
and e.ProjectKey = p.ProjectKey 
and e.CompanyKey = @CompanyKey
and isnull(p.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteTemplateProjects = 1
begin
	Delete tEstimateTaskLabor 
	from tEstimate e
	, tProject p 
	where tEstimateTaskLabor.EstimateKey = e.EstimateKey 
	and e.ProjectKey = p.ProjectKey 
	and e.CompanyKey = @CompanyKey
	and isnull(p.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tEstimateUser''

Delete tEstimateUser 
from tEstimate e
where tEstimateUser.EstimateKey = e.EstimateKey 
and e.CompanyKey = @CompanyKey
and e.ProjectKey is null 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimateUser 
from tEstimate e
, tProject p 
where tEstimateUser.EstimateKey = e.EstimateKey 
and e.CompanyKey = @CompanyKey
and e.ProjectKey = p.ProjectKey 
and isnull(p.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimateUser 
	from tEstimate e
	, tProject p 
	where tEstimateUser.EstimateKey = e.EstimateKey 
	and e.CompanyKey = @CompanyKey
	and e.ProjectKey = p.ProjectKey 
	and isnull(p.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end 

Select ''tEstimateTask''

Delete tEstimateTask 
from tEstimate
Where tEstimateTask.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey IS NULL 
and tEstimate.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimateTask 
from tEstimate
, tProject 
Where tEstimateTask.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey = tProject.ProjectKey 
and tEstimate.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimateTask 
	from tEstimate
	, tProject 
	Where tEstimateTask.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.ProjectKey = tProject.ProjectKey 
	and tEstimate.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tEstimateNotify''

-- Added for 800
Delete tEstimateNotify 
from tEstimate
Where tEstimateNotify.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey is null 
and tEstimate.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimateNotify 
from tEstimate
, tProject 
Where tEstimateNotify.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey = tProject.ProjectKey 
and tEstimate.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimateNotify 
	from tEstimate
	, tProject 
	Where tEstimateNotify.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.ProjectKey = tProject.ProjectKey 
	and tEstimate.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tEstimateService''

-- Added for 800
Delete tEstimateService 
from tEstimate
Where tEstimateService.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey is null 
and tEstimate.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Delete tEstimateService 
from tEstimate, tProject 
Where tEstimateService.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey = tProject.ProjectKey 
and tEstimate.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimateService 
	from tEstimate, tProject 
	Where tEstimateService.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.ProjectKey = tProject.ProjectKey 
	and tEstimate.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tEstimateTaskAssignmentLabor''

-- Added for 800
Delete tEstimateTaskAssignmentLabor 
from tEstimate
Where tEstimateTaskAssignmentLabor.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey is null 
and tEstimate.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimateTaskAssignmentLabor 
from tEstimate
, tProject 
Where tEstimateTaskAssignmentLabor.EstimateKey = tEstimate.EstimateKey 
and tEstimate.ProjectKey = tProject.ProjectKey 
and tEstimate.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimateTaskAssignmentLabor 
	from tEstimate
	, tProject 
	Where tEstimateTaskAssignmentLabor.EstimateKey = tEstimate.EstimateKey 
	and tEstimate.ProjectKey = tProject.ProjectKey 
	and tEstimate.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tAvalaraTaxData''
Delete tAvalaraTaxData Where EntityKey in (select EstimateKey from tEstimate where CompanyKey = @CompanyKey)
	and tAvalaraTaxData.Entity = ''tEstimate''
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEstimate''

Delete tEstimate 
Where tEstimate.ProjectKey is null 
and tEstimate.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tEstimate 
from tProject 
Where tEstimate.ProjectKey = tProject.ProjectKey 
and tEstimate.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

if @DeleteTemplateProjects = 1
begin
	Delete tEstimate 
	from tProject 
	Where tEstimate.ProjectKey = tProject.ProjectKey 
	and tEstimate.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tFormTemplate''

if @DeleteSetupTables = 1
delete tFormTemplate where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLabBeta''

if @DeleteSetupTables = 1
delete tLabBeta where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLabBeta''

if @DeleteSetupTables = 1
delete tLabCompany where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMobileSearchCondition''
If @DeleteSetupTables = 1
delete tMobileSearchCondition
from  tMobileSearch
where tMobileSearchCondition.MobileSearchKey = tMobileSearch.MobileSearchKey
and   tMobileSearch.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMobileSearch''
If @DeleteSetupTables = 1
delete tMobileSearch where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimeRollupDetail'' --Needs to be before tTask and tProject

DELETE	tTimeRollupDetail
FROM	tProject 
WHERE	tTimeRollupDetail.ProjectKey = tProject.ProjectKey
AND		tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimeItemRollup'' --Needs to be before tProject

DELETE	tTimeItemRollup
FROM	tProject 
WHERE	tTimeItemRollup.ProjectKey = tProject.ProjectKey
AND		tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimeRollup'' --Needs to be before tProject

DELETE	tTimeRollup
FROM	tProject 
WHERE	tTimeRollup.ProjectKey = tProject.ProjectKey
AND		tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tTaskPredecessor''

Delete tTaskPredecessor 
from tTask
, tProject 
Where tTaskPredecessor.TaskKey = tTask.TaskKey 
and tTask.ProjectKey = tProject.ProjectKey 
and tProject.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteTemplateProjects = 1
begin
	Delete tTaskPredecessor 
	from tTask
	, tProject 
	Where tTaskPredecessor.TaskKey = tTask.TaskKey 
	and tTask.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tTask''

Delete tTask 
from tProject 
Where tTask.ProjectKey = tProject.ProjectKey 
and tProject.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteTemplateProjects = 1
begin
	Delete tTask 
	from tProject 
	Where tTask.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tTaskPriority''
If @DeleteSetupTables = 1
Delete tTaskPriority where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTaskAssignmentTypeService''

-- Added for 800
If @DeleteSetupTables = 1
Delete tTaskAssignmentTypeService
From tTaskAssignmentType  
Where tTaskAssignmentType.CompanyKey = @CompanyKey
And tTaskAssignmentTypeService.TaskAssignmentTypeKey = tTaskAssignmentType.TaskAssignmentTypeKey 
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTaskAssignmentType''

-- Added for 800
If @DeleteSetupTables = 1
Delete tTaskAssignmentType  Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMasterTask''

-- Added for 800
If @DeleteSetupTables = 1
Delete tMasterTask  Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAssignment''
Delete tAssignment 
from tProject Where tAssignment.ProjectKey = tProject.ProjectKey 
and tProject.CompanyKey = @CompanyKey
and isnull(tProject.Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAssignment-2''
Delete tAssignment 
from tUser Where tAssignment.UserKey = tUser.UserKey 
and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteTemplateProjects = 1
begin
	Delete tAssignment 
	from tProject Where tAssignment.ProjectKey = tProject.ProjectKey 
	and tProject.CompanyKey = @CompanyKey
	and isnull(tProject.Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tRptSecurityGroup''
If @DeleteSetupTables = 1
Delete tRptSecurityGroup from tSecurityGroup Where tRptSecurityGroup.SecurityGroupKey = tSecurityGroup.SecurityGroupKey and
	tSecurityGroup.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tRightAssigned''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tRightAssigned from tSecurityGroup Where tRightAssigned.EntityKey = tSecurityGroup.SecurityGroupKey and
	tSecurityGroup.CompanyKey = @CompanyKey and tRightAssigned.EntityType = ''Security Group''
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUser''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Update	tUser 
set		SecurityGroupKey = NULL
from	tSecurityGroup sg
where	tUser.SecurityGroupKey = sg.SecurityGroupKey
and		sg.CompanyKey = @CompanyKey

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSecurityGroup''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tSecurityGroup Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarAttendeeGroup''

-- Added for 800
Delete tCalendarAttendeeGroup from tCalendar Where tCalendarAttendeeGroup.CalendarKey = tCalendar.CalendarKey and tCalendar.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tCalendarAttendeeGroup
Where CalendarKey NOT IN (SELECT CalendarKey FROM tCalendar)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDistributionGroupUser''

-- Added for 800
If @DeleteSetupTables = 1
Delete tDistributionGroupUser
From   tDistributionGroup dg 
Where dg.CompanyKey = @CompanyKey
And dg.DistributionGroupKey = tDistributionGroupUser.DistributionGroupKey

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDistributionGroup''

-- Added for 800
If @DeleteSetupTables = 1
Delete tDistributionGroup Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarAttendee'';

DISABLE TRIGGER dbo.tD_tCalendarAttendee on tCalendarAttendee

Delete tCalendarAttendee from tCalendar Where tCalendarAttendee.CalendarKey = tCalendar.CalendarKey and tCalendar.CompanyKey = @CompanyKey;

ENABLE TRIGGER dbo.tD_tCalendarAttendee on tCalendarAttendee

if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendarAttendeeUpdateLog''

Delete tCalendarAttendeeUpdateLog from tCalendar 
Where tCalendarAttendeeUpdateLog.CalendarKey = tCalendar.CalendarKey and tCalendar.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCalendar'';

DISABLE TRIGGER dbo.tD_tCalendar on tCalendar

Delete tCalendar Where tCalendar.CompanyKey = @CompanyKey;

ENABLE TRIGGER dbo.tD_tCalendar on tCalendar
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCBPosting''

-- Added for 800
Delete tCBPosting
From   tProject p (NOLOCK)
Where  tCBPosting.ProjectKey = p.ProjectKey
And    p.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCBBatchAdjustment''

-- Added for 800
Delete  tCBBatchAdjustment
From    tCBBatch b (NOLOCK)
Where   tCBBatchAdjustment.BatchKey = b.CBBatchKey
And     b.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCBBatch''

-- Added for 800
Delete  tCBBatch 
Where   CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCBCodePercent''

-- Added for 800
Delete tCBCodePercent
From   tCBCode b (NOLOCK)
Where  tCBCodePercent.CBCodeKey = b.CBCodeKey
And    b.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCBCode''

-- Added for 800
If @DeleteSetupTables = 1
Delete  tCBCode 
Where   CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMediaMarket''

-- Added for 800
If @DeleteSetupTables = 1
Delete tMediaMarket
Where   CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserSkill''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserSkill from tUser Where tUserSkill.UserKey = tUser.UserKey and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserSkillSpecialty''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUserSkillSpecialty from tUser Where tUserSkillSpecialty.UserKey = tUser.UserKey and (tUser.CompanyKey = @CompanyKey or tUser.OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSkillSpecialty''
If @DeleteSetupTables = 1
Delete tSkillSpecialty from tSkill Where tSkillSpecialty.SkillKey = tSkill.SkillKey and tSkill.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSkill''
If @DeleteSetupTables = 1
Delete tSkill Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tGLBudgetDetail''
If @DeleteSetupTables = 1
Delete tGLBudgetDetail from tGLAccount gla where tGLBudgetDetail.GLAccountKey = gla.GLAccountKey and gla.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tGLBudget''
If @DeleteSetupTables = 1
Delete tGLBudget where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tGLAccountRecDetail''

Delete tGLAccountRecDetail from tGLAccountRec glar where tGLAccountRecDetail.GLAccountRecKey = glar.GLAccountRecKey and glar.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tGLAccountUser''

Delete tGLAccountUser from tGLAccount gla where tGLAccountUser.GLAccountKey = gla.GLAccountKey and gla.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tGLAccountRec''

Delete tGLAccountRec where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tDepartment''
If @DeleteSetupTables = 1
Delete tDepartment Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tGLAccount''
If @DeleteSetupTables = 1
Delete tGLAccount Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLayoutItems''
If @DeleteSetupTables = 1
Delete tLayoutItems 
From tLayoutReport
,tLayout
Where tLayout.CompanyKey = @CompanyKey
and   tLayout.LayoutKey = tLayoutReport.LayoutKey
and   tLayoutReport.LayoutReportKey = tLayoutItems.LayoutReportKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLayoutSection''
If @DeleteSetupTables = 1
Delete tLayoutSection 
From tLayoutReport
,tLayout
Where tLayout.CompanyKey = @CompanyKey
and   tLayout.LayoutKey = tLayoutReport.LayoutKey
and   tLayoutReport.LayoutReportKey = tLayoutSection.LayoutReportKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLayoutReport''
If @DeleteSetupTables = 1
Delete tLayoutReport
from tLayout
Where tLayout.CompanyKey = @CompanyKey
and   tLayout.LayoutKey = tLayoutReport.LayoutKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLayoutBilling''
If @DeleteSetupTables = 1
Delete tLayoutBilling
from tLayout
Where tLayout.CompanyKey = @CompanyKey
and   tLayout.LayoutKey = tLayoutBilling.LayoutKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLayout''
If @DeleteSetupTables = 1
Delete tLayout
Where tLayout.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tContactActivity''
If @DeleteSetupTables = 1
Delete tContactActivity Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLeadUser''

Delete tLeadUser 
FROM tLead l 
where tLeadUser.LeadKey = l.LeadKey 
and l.CompanyKey = @CompanyKey
	
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLead''

Delete tLead Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLeadOutcome''
If @DeleteSetupTables = 1
Delete tLeadOutcome Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLeadStageHistory''
Delete tLeadStageHistory 
From   tLeadStage ls
Where  tLeadStageHistory.LeadStageKey = ls.LeadStageKey
and    ls.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLeadStage''
If @DeleteSetupTables = 1
Delete tLeadStage Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLeadStatus''
If @DeleteSetupTables = 1
Delete tLeadStatus Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tLevelHistory : tCompany''
Delete tLevelHistory
FROM tCompany c 
where tLevelHistory.Entity = ''tCompany''
and   tLevelHistory.EntityKey = c.CompanyKey 
and isnull(c.OwnerCompanyKey, c.CompanyKey) = @CompanyKey
	
Select ''tLevelHistory : tLead''
Delete tLevelHistory
FROM tLead l 
where tLevelHistory.Entity = ''tLead''
and   tLevelHistory.EntityKey = l.LeadKey 
and l.CompanyKey = @CompanyKey
	
Select ''tLevelHistory : tUser''
Delete tLevelHistory
FROM tUser u 
where tLevelHistory.Entity = ''tUser''
and   tLevelHistory.EntityKey = u.UserKey 
and isnull(u.OwnerCompanyKey, u.CompanyKey) = @CompanyKey
	
Select ''tMailing''
Delete tMailing Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end
	
Select ''tMailingSetup''
If @DeleteSetupTables = 1
Delete tMailingSetup Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMarketingListListDeleteLog''
Delete tMarketingListListDeleteLog where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMarketingListList''
Delete tMarketingListList
FROM   tMarketingList b (NOLOCK) 
WHERE  b.CompanyKey = @CompanyKey
AND    tMarketingListList.MarketingListKey = b.MarketingListKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMarketingList''
If @DeleteSetupTables = 1
Delete tMarketingList Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tMergeContactLog''
Delete tMergeContactLog Where OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tExpenseType''
If @DeleteSetupTables = 1
Delete tExpenseType Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


Select ''tProjectType''
If @DeleteSetupTables = 1
Delete tProjectType Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectStatus''
If @DeleteSetupTables = 1
Delete tProjectStatus Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectBillingStatus''
If @DeleteSetupTables = 1
Delete tProjectBillingStatus Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPaymentTerms''
If @DeleteSetupTables = 1
Delete tPaymentTerms Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPurchaseOrderType''
If @DeleteSetupTables = 1
Delete tPurchaseOrderType Where CompanyKey = @CompanyKey  -- Need to loop and take care of field sets and custom fields on POs
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReport''
If @DeleteSetupTables = 1
Delete tReport Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tReportGroup''
If @DeleteSetupTables = 1
Delete tReportGroup Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tStringCompany''
If @DeleteSetupTables = 1
Delete tStringCompany Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tService''
If @DeleteSetupTables = 1
Delete tService Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectServices''
Delete tProjectServices Where ServiceKey in (select ServiceKey from tService where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSalesTax''
If @DeleteSetupTables = 1
Delete tSalesTax Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

-- Added for 82
Select ''tRetainerItems''
If @DeleteSetupTables = 1
Delete tRetainerItems
From tRetainer 
Where tRetainer.CompanyKey = @CompanyKey
And   tRetainerItems.RetainerKey = tRetainer.RetainerKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


-- Added for 81
Select ''tRetainer''
If @DeleteSetupTables = 1
Delete tRetainer Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

-- Added for 81
Select ''tISCI''

Delete tISCI
From   tProject (NOLOCK)  
Where tISCI.ProjectKey = tProject.ProjectKey
And   tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end


-- Added for 8407
Select ''tProjectRollup''

Delete tProjectRollup
From   tProject (NOLOCK)  
Where tProjectRollup.ProjectKey = tProject.ProjectKey
And   tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectItemRollup''

Delete tProjectItemRollup
From   tProject (NOLOCK)  
Where tProjectItemRollup.ProjectKey = tProject.ProjectKey
And   tProject.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProjectAddress''
Delete tProjectAddress Where ProjectKey in (select ProjectKey from tProject where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tProject''

Delete tProject Where CompanyKey = @CompanyKey and isnull(Template, 0) = 0
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteTemplateProjects = 1
begin
	Delete tProject Where CompanyKey = @CompanyKey and isnull(Template, 0) = 1
	if	@@error != 0
	begin
		--rollback tran
		return -1
	end
end

Select ''tRecurTranUser''
Delete tRecurTranUser
From   tRecurTran
Where  tRecurTran.CompanyKey = @CompanyKey
and    tRecurTran.RecurTranKey = tRecurTranUser.RecurTranKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tRecurTran''
Delete tRecurTran Where  tRecurTran.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tClientProduct''

-- Added for 800
If @DeleteSetupTables = 1
Delete tClientProduct
Where  CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tClientDivision''

-- Added for 800
If @DeleteSetupTables = 1
Delete tClientDivision
Where  CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCampaignEstByItem''

If @DeleteSetupTables = 1
delete tCampaignEstByItem
from tCampaign 
where tCampaign.CompanyKey = @CompanyKey
and tCampaign.CampaignKey = tCampaignEstByItem.CampaignKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCampaignRollup''

If @DeleteSetupTables = 1
delete tCampaignRollup
from tCampaign 
where tCampaign.CompanyKey = @CompanyKey
and tCampaign.CampaignKey = tCampaignRollup.CampaignKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteSetupTables = 1
delete tCampaignSegment
from tCampaign 
where tCampaign.CompanyKey = @CompanyKey
and tCampaign.CampaignKey = tCampaignSegment.CampaignKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCampaign''

-- Moved here for 800
If @DeleteSetupTables = 1
delete tCampaign where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tSource''

If @DeleteSetupTables = 1
Delete tSource
Where  CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAddress''
If @DeleteSetupTables = 1
Delete tAddress Where OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserLeadUpdateLog''
Delete tUserLeadUpdateLog Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserLead''
Delete tUserLead Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUserRole''
Delete tUserRole Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tUser''
/*
Delete tUser Where OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end
*/
-- Added for 8407
Select ''tSystemMessageUser''

Delete tSystemMessageUser
From   tUser (NOLOCK)  
Where tSystemMessageUser.UserKey = tUser.UserKey
And   tUser.CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Delete tSystemMessageUser
From   tUser (NOLOCK)  
Where tSystemMessageUser.UserKey = tUser.UserKey
And   tUser.OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUser Where OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUser Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tUser 
Where CompanyKey in (select CompanyKey from tCompany where OwnerCompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tCompany''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tCompany Where OwnerCompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPreference''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tPreference Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tTimeOption''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tTimeOption Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

--Select ''tWidgetDef''
--If @DeleteSetupTables = 1
--Delete tWidgetDef WHERE CompanyKey = @CompanyKey
--if	@@error != 0
--begin
--	--rollback tran
--	return -1
--end

Select ''tCMFolder''
Delete tCMFolder WHERE CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tWebDavSecurity''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tWebDavSecurity WHERE CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end
	


Select ''tOFXGLAccountLink''
Delete tOFXGLAccountLink Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPlaidAccount''
Delete tPlaidAccount Where PlaidItemKey IN (Select PlaidItemKey from tPlaidItem Where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tPlaidItem''
Delete tPlaidItem Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tBlockoutCache''
Delete tBlockoutCache Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAvalaraTaxCode''
Delete tAvalaraTaxCode Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tAvalaraRegion''
Delete tAvalaraRegion Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tInvoiceTaxAvalara''
Delete tInvoiceTaxAvalara Where InvoiceKey in (select InvoiceKey from tInvoice where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEmailTemplateSection''
Delete tEmailTemplateSection Where EmailTemplateKey in (select EmailTemplateKey from tEmailTemplate where CompanyKey = @CompanyKey)
if	@@error != 0
begin
	--rollback tran
	return -1
end

Select ''tEmailTemplate''
Delete tEmailTemplate Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end

--***THIS SHOULD BE THE LAST DELETE STATEMENT IN THIS PROCEDURE***
Select ''tCompany''
If @DeleteSetupTables = 1 and @LeaveCoreCompany = 0
Delete tCompany Where CompanyKey = @CompanyKey
if	@@error != 0
begin
	--rollback tran
	return -1
end
--commit tran

return 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptWidgetDashUpdate]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[sptWidgetDashUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptWidgetDashUpdate]
(
	@CompanyKey int,
	@UserKey int,
	@WidgetDashKey int,
	@DashID varchar(50),
	@Label varchar(350),
	@Private tinyint,
	@DuplicateDashKey int,
	@CopyFrom int = 1
)

as

Declare @NewKey int, @CopyID varchar(50), @key int, @NewTabKey int

if @Private = 0
	Select @UserKey = 0

if @WidgetDashKey > 0
BEGIN
	Update tWidgetDash Set @UserKey = @UserKey, Label = @Label Where WidgetDashKey = @WidgetDashKey

	Select @NewKey = @WidgetDashKey

	Delete tSecurityAccess Where Entity = ''tWidgetDash'' and EntityKey = @WidgetDashKey

END
ELSE
BEGIN
	Insert tWidgetDash
	( CompanyKey, DashID, UserKey, Label )
	Values
	( @CompanyKey, @DashID, @UserKey, @Label )

	Select @NewKey = @@IDENTITY

	if @DuplicateDashKey = 0
		Insert tWidgetTab (WidgetDashKey, Label, DisplayOrder) Values (@NewKey, ''Home'', 1)

END


if @DuplicateDashKey > 0
BEGIN

	if @CopyFrom = 1
	BEGIN
		Select @key = 0
		While 1=1
		BEGIN
		Select @key = Min(WidgetTabKey) from tWidgetTab (nolock) Where WidgetDashKey = @DuplicateDashKey and WidgetTabKey > @key
			if @key is null
				break

		Insert into tWidgetTab ( WidgetDashKey, Label, DisplayOrder )
		Select @NewKey, Label, DisplayOrder from tWidgetTab (nolock) Where WidgetTabKey = @key

		Select @NewTabKey = @@IDENTITY

		Insert Into tReport 
		([ViewKey],[Name],[ReportType],[ReportFilter],[Definition],[FieldDefinition],[ConditionDefinition],[Private]
		,[UserKey],[CompanyKey],[ReportGroupKey],[ReportHeading1],[ReportHeading1Align],[ReportHeading2],[ReportHeading2Align],[Orientation],[GroupBy],[ShowConditions],[ReportID],[GroupByDefinition],[LockedColumns],[DefaultReportKey],[AutoExpandGroups],[Deleted],[LastModified],[ApplicationVersion],[AutoRun]
		,[Description],[DateAdded],[AddedBy],[DateModified],[ModifiedBy],[DateLastRun],[RunCnt],[XPos],[YPos]
		,[Width],[Height],[DisplayType],[TabName],[XAxisLabel],[YAxisLabel],[MaxItemCount],[DataTargetUpper]
		,[DataTargetLower],[RunCntAPI],[DateLastRunAPI],[PivotSettings],[XAxisHasCField],[YAxisHasCField],[SeriesHasCField],[DefaultReportView],[WidgetTabKey])

		Select 
		 [ViewKey],[Name],[ReportType],[ReportFilter],[Definition],[FieldDefinition],[ConditionDefinition],[Private]
		,[UserKey],[CompanyKey],[ReportGroupKey],[ReportHeading1],[ReportHeading1Align],[ReportHeading2],[ReportHeading2Align],[Orientation],[GroupBy],[ShowConditions],[ReportID],[GroupByDefinition],[LockedColumns],[DefaultReportKey],[AutoExpandGroups],[Deleted],[LastModified],[ApplicationVersion],[AutoRun]
		,[Description],[DateAdded],[AddedBy],[DateModified],[ModifiedBy],[DateLastRun],[RunCnt],[XPos],[YPos]
		,[Width],[Height],[DisplayType],[TabName],[XAxisLabel],[YAxisLabel],[MaxItemCount],[DataTargetUpper]
		,[DataTargetLower],[RunCntAPI],[DateLastRunAPI],[PivotSettings],[XAxisHasCField],[YAxisHasCField],[SeriesHasCField],[DefaultReportView],@NewTabKey

		from tReport Where WidgetTabKey = @key

		END
	END
	ELSE
	BEGIN

		/* figure out the report id, then copy everything onto one tab */
		Select @CopyID = Case When @CopyFrom = 2 then ''CreativeDash''  
							  When @CopyFrom = 3 then ''SalesDash''
							  When @CopyFrom = 4 then ''PMnDash''
							  When @CopyFrom = 5 then ''RMDash''
							  When @CopyFrom = 6 then ''BillingDash''
							  When @CopyFrom = 7 then ''PurchasingDash''
							  When @CopyFrom = 8 then ''AccountingDash''
							  When @CopyFrom = 9 then ''MediaDash''
							  When @CopyFrom = 10 then ''AdminDash'' 
							  When @CopyFrom = 11 then ''OwnerDash'' END
						  
		Insert tWidgetTab ( WidgetDashKey, Label, DisplayOrder )
		Values (@NewKey, ''Home'', 1)

		Select @NewTabKey = @@IDENTITY

		Insert Into tReport 
		([ViewKey],[Name],[ReportType],[ReportFilter],[Definition],[FieldDefinition],[ConditionDefinition],[Private]
		,[UserKey],[CompanyKey],[ReportGroupKey],[ReportHeading1],[ReportHeading1Align],[ReportHeading2],[ReportHeading2Align],[Orientation],[GroupBy],[ShowConditions],[ReportID],[GroupByDefinition],[LockedColumns],[DefaultReportKey],[AutoExpandGroups],[Deleted],[LastModified],[ApplicationVersion],[AutoRun]
		,[Description],[DateAdded],[AddedBy],[DateModified],[ModifiedBy],[DateLastRun],[RunCnt],[XPos],[YPos]
		,[Width],[Height],[DisplayType],[TabName],[XAxisLabel],[YAxisLabel],[MaxItemCount],[DataTargetUpper]
		,[DataTargetLower],[RunCntAPI],[DateLastRunAPI],[PivotSettings],[XAxisHasCField],[YAxisHasCField],[SeriesHasCField],[DefaultReportView],[WidgetTabKey])

		Select 
		 [ViewKey],[Name],[ReportType],[ReportFilter],[Definition],[FieldDefinition],[ConditionDefinition],[Private]
		,[UserKey],[CompanyKey],[ReportGroupKey],[ReportHeading1],[ReportHeading1Align],[ReportHeading2],[ReportHeading2Align],[Orientation],[GroupBy],[ShowConditions],[ReportID],[GroupByDefinition],[LockedColumns],[DefaultReportKey],[AutoExpandGroups],[Deleted],[LastModified],[ApplicationVersion],[AutoRun]
		,[Description],[DateAdded],[AddedBy],[DateModified],[ModifiedBy],[DateLastRun],[RunCnt],[XPos],[YPos]
		,[Width],[Height],[DisplayType],[TabName],[XAxisLabel],[YAxisLabel],[MaxItemCount],[DataTargetUpper]
		,[DataTargetLower],[RunCntAPI],[DateLastRunAPI],[PivotSettings],[XAxisHasCField],[YAxisHasCField],[SeriesHasCField],[DefaultReportView],@NewTabKey

		from tReport Where ReportID = @CopyID and CompanyKey = @CompanyKey

	END
END


return @NewKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptTaskAssignFromScheduleTemp]'
GO
IF OBJECT_ID(N'[dbo].[sptTaskAssignFromScheduleTemp]', 'P') IS NOT NULL
EXEC sp_executesql N'



ALTER PROCEDURE [dbo].[sptTaskAssignFromScheduleTemp]
	(
		@ProjectKey int
		,@EstimateKey int
		,@UsePermanentTables int = 0
	)

AS --Encrypt

  /*
  || When     Who Rel   What
  || 04/02/08 GHL 8.5   (16332) This is the opposite from sptTaskAssignFromEstimate  
  ||
  ||                    In sptTaskAssignFromEstimate, we populate tTaskUser from tEstimateTaskLabor
  ||					We go from estimate to schedule
  ||                    In sptTaskAssignFromSchedule, we populate tEstimateTaskLabor from tTaskUser
  ||					We go from schedule to estimate      
  ||					Difference is it only works with estimate by task/person 
  || 07/29/10 GHL 10.533 (86398) Added pull for estimates by task/service or by service only or by task only
  ||                    only valid if estimate is for a project
  || 09/15/10 GHL 10.535 (89676) Only pull records where Hours <> 0
  || 09/20/10 GHL 10.535 (90453) For estimates by task/person, do not error out if there is a missing person on a task user record
  || 09/23/10 GHL 10.535 (90693) For estimates by service, do not error out if there is a missing service on a task user record
  || 11/02/10 GHL 10.537 Cloned sptTaskAssignFromSchedule to get results into temp table instead of permanent table
  || 11/17/10 GHL 10.538 Fixed bad joins with permanent tables instead of temp tables (only apparent on SQL 2000)
  || 12/21/10 GHL 10.539 (97437) For Change Orders, Hours = Hours on the Schedule - Hours on other estimates
  || 03/08/11 GHL 10.542 (105651) For estimate by tasks, added the initial insert into temp tb
  || 06/27/11 GHL 10.545 (115226) For estimate by tasks, recalculating now the LaborGross (EstLabor) after changing hours
  || 10/04/11 GHL 10.549 Fixed typo for expenses
  || 02/16/12 GHL 10.553 (134167) calc labor as sum(round(hours * rate))
  || 05/03/12 GHL 10.555 (142274) If get rate from client, query client not project
  || 05/04/12 GHL 10.555 (142429) For change orders, allow for negative hours
  || 07/11/12 GHL 10.557 (147312) Added cost to estimate user and estimate service
  || 10/15/15 GHL 10.597 Added @UsePermanentTables param so that I can use this sp with WJAPP (direct insert in permanent tables)
  ||                     I could have used sptTaskAssignFromSchedule but it processes change orders differently
  ||                     + it is always better to have only one sp to maintain in case we have to make a change
  ||                     Flex uses @UsePermanentTables = 0 
  || 04/12/16 GHL 10.603 Added protection against null client rate
  || 01/26/17 KMC 10.612 (329824) Added ISNULL for insert into tEstimateTaskLabor
  || 11/21/17 MCM 10.622 (373203) Updated if it is a template to @GetRateFrom =  @kGetRateFromService
  || 07/25/19 GHL 19.080 (471746) Rolledback 373203 because we can change the GetRateFrom/Rates on the project templates now
  ||                     (before the project rate was 0)
  || 03/25/24 MCM 24.03x (658620) updated to pull hourly costs from timeRatesheet if exists
   */

/* 142429
If they are shifting hours from Copy to Design and changed the allocated hours in the Schedule and now create a change order 
using pull from schedule, it will add the new hours for Design but shows zero (instead of negative hours) for Copy.

Assume on schedule
Branding 10
Copy     5
Design   0

Pull from Schedule once and approve, on approved estimates
Branding 10
Copy     5
Design   0

Change on schedule
Branding 10
Copy     0
Design   5

Pull from Schedule on change order
Branding 10 - 10 = 0
Copy     0 - 5 = -5
Design   5 - 0 = 5

Same logic if By Task/Person, Task/Service, Task Only
*/

/* 86398
On a project estimate, need a function to pull labor from the assignments on the project. 
If task and service, use the service on the tTaskUser record. if its blank, use the person''s default service. if both are blank, then do not include them and show an error.

If task and person, pull by person, if person is blank, then do not include and show an error. (removed for 90453)
*/
  
	SET NOCOUNT ON 
	
	-- Estimate Types
	declare @kByTaskOnly int            select @kByTaskOnly = 1
	declare @kByTaskService int         select @kByTaskService = 2
	declare @kByTaskPerson int          select @kByTaskPerson = 3
	declare @kByServiceOnly int         select @kByServiceOnly = 4
	declare @kBySegmentService int      select @kBySegmentService = 5

	-- get rate from	
	declare @kGetRateFromClient int             select @kGetRateFromClient = 1
	declare @kGetRateFromProject int            select @kGetRateFromProject = 2
	declare @kGetRateFromProjectUser int        select @kGetRateFromProjectUser = 3
	declare @kGetRateFromService int            select @kGetRateFromService = 4
	declare @kGetRateFromServiceRateSheet int   select @kGetRateFromServiceRateSheet = 5
	declare @kGetRateFromTask int               select @kGetRateFromTask = 6

	declare @EstType int, @ChangeOrder int, @GetRateFrom int, @ProjectHourlyRate money, @TimeRateSheetKey INT
	declare @ClientKey int, @ClientHourlyRate money 

	select @EstType = EstType, @ChangeOrder = ChangeOrder from tEstimate (nolock) where EstimateKey = @EstimateKey

	select @GetRateFrom = GetRateFrom
	     , @ProjectHourlyRate = isnull(HourlyRate, 0)
		 , @TimeRateSheetKey = isnull(TimeRateSheetKey, 0)
		 , @ClientKey = ClientKey
	from tProject (nolock) where ProjectKey = @ProjectKey

	if @TimeRateSheetKey = 0 and @GetRateFrom = @kGetRateFromServiceRateSheet
		select @GetRateFrom = @kGetRateFromService

	if @GetRateFrom = @kGetRateFromClient
		select @ClientHourlyRate = HourlyRate from tCompany (nolock) where CompanyKey = @ClientKey

	select @ClientHourlyRate = isnull(@ClientHourlyRate, 0)

CREATE TABLE #tEstimateUser(
	[EstimateKey] [int] NULL,
	[UserKey] [int] NULL,
	[BillingRate] [money] NULL)

CREATE TABLE #tEstimateTaskLabor(
	[EstimateKey] [int] NULL,
	[TaskKey] [int] NULL,
	[ServiceKey] [int] NULL,
	[UserKey] [int] NULL,
	[Hours] [decimal](24, 4) NULL,
	[EstimatedHours] [decimal](24, 4) NULL, -- Used for Change Orders to capture other approved estimates
	[Rate] [money] NULL,
	[Cost] [money] NULL,
	[CampaignSegmentKey] [int] NULL
) 

CREATE TABLE #tEstimateTask(
	[EstimateTaskKey] [int] NULL,
	[EstimateKey] [int] NULL,
	[TaskKey] [int] NULL,
	[Hours] [decimal](24, 4) NULL,
	[EstimatedHours] [decimal](24, 4) NULL,
	[Rate] [money] NULL,
	[EstLabor] [money] NULL,
	[BudgetExpenses] [money] NULL,
	[Markup] [decimal](24, 4) NULL,
	[EstExpenses] [money] NULL,
	[Cost] [money] NULL
)

CREATE TABLE #tEstimateService(
	[EstimateKey] [int] NULL,
	[ServiceKey] [int] NULL,
	[Rate] [money] NULL
)

	if @EstType = @kByTaskPerson
	begin
		/*
		if exists (select 1 from tTaskUser tu (nolock) 
					inner join tTask t (nolock) on tu.TaskKey = t.TaskKey
					where t.ProjectKey = @ProjectKey
					and   tu.UserKey is null)
			return -1
		*/

        -- original code from CMP

		DELETE #tEstimateUser 
		WHERE  EstimateKey = @EstimateKey
	
		DELETE #tEstimateTaskLabor 
		WHERE  EstimateKey = @EstimateKey

			
		-- group by budget task
		INSERT #tEstimateTaskLabor (EstimateKey, TaskKey, ServiceKey, UserKey, Hours, Rate, Cost)
		SELECT @EstimateKey, t.BudgetTaskKey, NULL, tu.UserKey, SUM(tu.Hours), ISNULL(u.HourlyRate, 0), isnull(u.HourlyCost, 0) 
		FROM   tTaskUser tu (NOLOCK)
			INNER JOIN tTask t (NOLOCK) ON tu.TaskKey = t.TaskKey
			INNER JOIN tUser u (NOLOCK) ON tu.UserKey = u.UserKey
		WHERE t.ProjectKey = @ProjectKey
		AND   ISNULL(t.BudgetTaskKey, 0) > 0
		and   tu.Hours <> 0
		GROUP BY t.BudgetTaskKey, tu.UserKey, isnull(u.HourlyRate, 0), isnull(u.HourlyCost, 0) 
	
	-- because of 142429, we must add what is on the other estimates (we will show negatives)
		if @ChangeOrder = 1
		begin
			insert #tEstimateTaskLabor (EstimateKey, TaskKey, ServiceKey, UserKey, Hours, Rate, Cost)
			select distinct @EstimateKey, etl.TaskKey, null, etl.UserKey, 0, ISNULL(u.HourlyRate, 0), isnull(u.HourlyCost, 0)		
			from   tEstimateTaskLabor etl (nolock)
				inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
				inner join tUser u (nolock) on etl.UserKey = u.UserKey
			where  e.ProjectKey = @ProjectKey
			and    e.EstimateKey <> @EstimateKey
			and    e.Approved = 1
			and    etl.UserKey is not null
			and    etl.TaskKey is not null
			-- trick to compare 2 keys: concatenate
			and    isnull(convert(varchar(50),etl.TaskKey), '''') + ''|'' + isnull(convert(varchar(50),etl.UserKey), '''') 
			not in (select isnull(convert(varchar(50),TaskKey), '''') + ''|'' + isnull(convert(varchar(50),UserKey), '''') from #tEstimateTaskLabor)
		end

		-- should we update the rate when get rate from project/client/task????????

		-- Correct if get rate from project/user
		if @GetRateFrom = @kGetRateFromProjectUser
		Update #tEstimateTaskLabor
		Set    #tEstimateTaskLabor.Rate = ISNULL(a.HourlyRate, 0)
		From   tAssignment a (nolock)	
		Where  a.ProjectKey = @ProjectKey
		And	   #tEstimateTaskLabor.EstimateKey = @EstimateKey
		And    #tEstimateTaskLabor.UserKey = a.UserKey

		
		insert #tEstimateUser (EstimateKey, UserKey, BillingRate)
		select @EstimateKey, UserKey, AVG(Rate)
		from   #tEstimateTaskLabor
		GROUP BY UserKey 

		if @ChangeOrder = 1
		begin
			update #tEstimateTaskLabor
			set    #tEstimateTaskLabor.EstimatedHours = isnull((
				select sum(etl.Hours)
				from   tEstimateTaskLabor etl (nolock)
					inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
				where  e.ProjectKey = @ProjectKey
				and    e.EstimateKey <> @EstimateKey
				and    e.Approved = 1
				and    etl.TaskKey = #tEstimateTaskLabor.TaskKey
				and    etl.UserKey = #tEstimateTaskLabor.UserKey        
			),0)

			update #tEstimateTaskLabor 
			set    Hours = isnull(Hours, 0) - isnull(EstimatedHours, 0)
			
			-- we show now negative hours
			delete #tEstimateTaskLabor where Hours = 0
			
			delete #tEstimateUser where UserKey not in (select UserKey from #tEstimateTaskLabor) 
			 
		end

	end

	
	if @EstType in (@kByTaskService, @kByServiceOnly)
	begin
	
		create table #taskuser (TaskKey int null, UserKey int null, ServiceKey int null,  Hours decimal(24,4) null, Rate money null, Cost money null, Type varchar(50) null)

		insert  #taskuser (TaskKey, UserKey, ServiceKey, Hours, Type)
		select t.BudgetTaskKey, tu.UserKey, tu.ServiceKey, tu.Hours, ''On Schedule''
		FROM tTaskUser tu (NOLOCK)
			INNER JOIN tTask t (NOLOCK) ON tu.TaskKey = t.TaskKey
		WHERE t.ProjectKey = @ProjectKey
		AND   ISNULL(t.BudgetTaskKey, 0) > 0 -- only if a task points to a budget task
        and   tu.Hours <> 0

		-- because of 142429, we must add what is on the other estimates (we will show negatives)
		if @ChangeOrder = 1
		begin
			if @EstType = @kByServiceOnly
				insert  #taskuser (TaskKey, UserKey, ServiceKey, Hours, Type)
				select distinct null, null, etl.ServiceKey, 0, ''On Approved Estimates''		
				from   tEstimateTaskLabor etl (nolock)
					inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
				where  e.ProjectKey = @ProjectKey
				and    e.EstimateKey <> @EstimateKey
				and    e.Approved = 1
				and    etl.ServiceKey is not null
				and    etl.ServiceKey not in (select ServiceKey from #taskuser)
			else
				insert  #taskuser (TaskKey, UserKey, ServiceKey, Hours, Type)
				select distinct etl.TaskKey, null, etl.ServiceKey, 0, ''On Approved Estimates''		
				from   tEstimateTaskLabor etl (nolock)
					inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
				where  e.ProjectKey = @ProjectKey
				and    e.EstimateKey <> @EstimateKey
				and    e.Approved = 1
				and    etl.ServiceKey is not null
				and    etl.TaskKey is not null
				-- trick to compare 2 keys: concatenate
				and    isnull(convert(varchar(50),etl.TaskKey), '''') + ''|'' + isnull(convert(varchar(50),etl.ServiceKey), '''') 
				not in (select isnull(convert(varchar(50),TaskKey), '''') + ''|'' + isnull(convert(varchar(50),ServiceKey), '''') from #taskuser)
		end

		--select * from #taskuser

		update #taskuser
		set    #taskuser.ServiceKey = u.DefaultServiceKey
		from   tUser u (nolock)
		where  #taskuser.UserKey = u.UserKey  
		and    #taskuser.ServiceKey is null

		/*
		if exists (select 1 from #taskuser (nolock) 
				where isnull(ServiceKey, 0) = 0)
			return -2
		*/

		delete from #taskuser where isnull(ServiceKey, 0) = 0

/*
	declare @kGetRateFromClient int             select @kGetRateFromClient = 1
	declare @kGetRateFromProject int            select @kGetRateFromProject = 2
	declare @kGetRateFromProjectUser int        select @kGetRateFromProjectUser = 3
	declare @kGetRateFromService int            select @kGetRateFromService = 4
	declare @kGetRateFromServiceRateSheet int   select @kGetRateFromServiceRateSheet = 5
	declare @kGetRateFromTask int               select @kGetRateFromTask = 6
*/

		if @GetRateFrom in (@kGetRateFromClient, @kGetRateFromProject)
		begin
			if @GetRateFrom = @kGetRateFromClient
				update #taskuser
				set    #taskuser.Rate = @ClientHourlyRate
			else
				update #taskuser
				set    #taskuser.Rate = @ProjectHourlyRate
			
			update #taskuser
			set    #taskuser.Cost = s.HourlyCost
			from   tService s (nolock)
			where  #taskuser.ServiceKey = s.ServiceKey
		end
		else if @GetRateFrom = @kGetRateFromServiceRateSheet
			update #taskuser
		    set    #taskuser.Rate = ISNULL(trsd.HourlyRate1, s.HourlyRate1) 
			      ,#taskuser.Cost = ISNULL(trsd.HourlyCost, s.HourlyCost)
			FROM   tTimeRateSheetDetail trsd (NOLOCK)
				  INNER JOIN tService s (NOLOCK) ON trsd.ServiceKey = s.ServiceKey		
			WHERE  trsd.TimeRateSheetKey = @TimeRateSheetKey
			and    s.ServiceKey = #taskuser.ServiceKey
		else --@kGetRateFromService or @kGetRateFromTask
			update #taskuser
		    set    #taskuser.Rate = s.HourlyRate1
			      ,#taskuser.Cost = s.HourlyCost
			FROM   tService s (NOLOCK) 		
			WHERE  s.ServiceKey = #taskuser.ServiceKey
		   

		DELETE #tEstimateService 
		WHERE  EstimateKey = @EstimateKey
	
		DELETE #tEstimateTaskLabor 
		WHERE  EstimateKey = @EstimateKey

		insert #tEstimateService (EstimateKey, ServiceKey, Rate)
		select @EstimateKey, ServiceKey, AVG(Rate)
		from   #taskuser
		GROUP BY ServiceKey 
		
		if @EstType = @kByServiceOnly
		begin
			INSERT #tEstimateTaskLabor 
			      (EstimateKey,  TaskKey, ServiceKey, UserKey, Hours,         Rate,      Cost)
			SELECT @EstimateKey, null,    ServiceKey, null,    SUM(Hours),  AVG(Rate), AVG(Cost) 
			FROM   #taskuser (NOLOCK)
			GROUP BY ServiceKey 
		
			if @ChangeOrder = 1
			begin
				update #tEstimateTaskLabor
				set    #tEstimateTaskLabor.EstimatedHours = isnull((
					select sum(etl.Hours)
					from   tEstimateTaskLabor etl (nolock)
						inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
					where  e.ProjectKey = @ProjectKey
					and    e.EstimateKey <> @EstimateKey
					and    e.Approved = 1
					and    etl.ServiceKey = #tEstimateTaskLabor.ServiceKey
				),0)

				update #tEstimateTaskLabor 
				set    Hours = isnull(Hours, 0) - isnull(EstimatedHours, 0)
			
				-- we show negative numbers now
				delete #tEstimateTaskLabor where Hours = 0
			
				delete #tEstimateService where ServiceKey not in (select ServiceKey from #tEstimateTaskLabor) 
			 
			end
		
		end
		else
		begin
			-- task/service
			INSERT #tEstimateTaskLabor 
			      (EstimateKey,  TaskKey, ServiceKey, UserKey, Hours,         Rate,      Cost)
			SELECT @EstimateKey, TaskKey, ServiceKey, null,    SUM(Hours),  AVG(Rate), AVG(Cost) 
			FROM   #taskuser (NOLOCK)
			GROUP BY TaskKey, ServiceKey 

			if @ChangeOrder = 1
			begin
				update #tEstimateTaskLabor
				set    #tEstimateTaskLabor.EstimatedHours = isnull((
					select sum(etl.Hours)
					from   tEstimateTaskLabor etl (nolock)
						inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
					where  e.ProjectKey = @ProjectKey
					and    e.EstimateKey <> @EstimateKey
					and    e.Approved = 1
					and    etl.TaskKey = #tEstimateTaskLabor.TaskKey
					and    etl.ServiceKey = #tEstimateTaskLabor.ServiceKey
				),0)

				update #tEstimateTaskLabor 
				set    Hours = isnull(Hours, 0) - isnull(EstimatedHours, 0)
			
				-- we show negative numbers now
				delete #tEstimateTaskLabor where Hours = 0
			
				delete #tEstimateService where ServiceKey not in (select ServiceKey from #tEstimateTaskLabor) 
			 
			end
	
		end

	end

	if @EstType = @kByTaskOnly
	begin

		INSERT #tEstimateTask(EstimateTaskKey,EstimateKey,TaskKey,Hours,EstimatedHours,Rate,EstLabor,BudgetExpenses,Markup,EstExpenses,Cost)
		select EstimateTaskKey,EstimateKey,TaskKey,0,0,Rate,EstLabor,BudgetExpenses,Markup,EstExpenses,Cost
		from   tEstimateTask (nolock)
		where  EstimateKey = @EstimateKey

		update #tEstimateTask
		set    #tEstimateTask.Hours = ISNULL((
			select sum(tu.Hours)
			from   tTaskUser tu (nolock)
			inner join tTask t (nolock) on tu.TaskKey = t.TaskKey
			where t.BudgetTaskKey = #tEstimateTask.TaskKey
		),0)
		where  	#tEstimateTask.EstimateKey = @EstimateKey
	
		if @ChangeOrder = 1
		begin
			update #tEstimateTask
				set    #tEstimateTask.EstimatedHours = isnull((
					select sum(et.Hours)
					from   tEstimateTask et (nolock)
						inner join vEstimateApproved e (nolock) on et.EstimateKey = e.EstimateKey
					where  e.ProjectKey = @ProjectKey
					and    e.EstimateKey <> @EstimateKey
					and    e.Approved = 1
					and    et.TaskKey = #tEstimateTask.TaskKey
				),0)

				update #tEstimateTask 
				set    Hours = isnull(Hours, 0) - isnull(EstimatedHours, 0)
			
				-- we show negative hours now
				--update #tEstimateTask set Hours = 0 where Hours < 0
			
		end

		--select * from #tEstimateTask

		-- recalc LaborGross
		update #tEstimateTask
		set    #tEstimateTask.EstLabor = ROUND(ISNULL(#tEstimateTask.Hours, 0) * ISNULL(#tEstimateTask.Rate, 0), 2) 
		where  #tEstimateTask.EstimateKey = @EstimateKey
	
	end
	
/*
This is the WJApp/Platinum case
If we insert in permanent tables, do the inserts now and recalculate the totals on the estimate and on the project
*/

if @UsePermanentTables = 1
begin
	if @EstType = @kByTaskOnly
	begin
		-- simply update tEstimateTask 
		update tEstimateTask
		set    tEstimateTask.Hours = #tEstimateTask.Hours
		      ,tEstimateTask.EstLabor = ROUND(#tEstimateTask.EstLabor, 2)
		from   #tEstimateTask  
		where  tEstimateTask.EstimateKey = @EstimateKey
	    and    tEstimateTask.TaskKey = #tEstimateTask.TaskKey
	end

	if @EstType = @kByTaskPerson
	begin
		delete tEstimateUser where EstimateKey = @EstimateKey

		insert tEstimateUser (EstimateKey, UserKey, BillingRate, Cost)
		select @EstimateKey, eu.UserKey, eu.BillingRate, u.HourlyCost 
		from   #tEstimateUser eu 
			inner join tUser u (nolock) on eu.UserKey = u.UserKey
		
		delete tEstimateTaskLabor where EstimateKey = @EstimateKey

		--(329824) Added ISNULL wrappers
		insert tEstimateTaskLabor (EstimateKey, TaskKey, UserKey, Hours, Rate, Cost)
		select @EstimateKey, TaskKey, UserKey, ISNULL(Hours, 0), ROUND(ISNULL(Rate, 0),4), ISNULL(Cost, 0)
		from   #tEstimateTaskLabor (nolock) 

	end

	if @EstType in ( @kByTaskService, @kByServiceOnly )
	begin
		delete tEstimateService where EstimateKey = @EstimateKey

		if @GetRateFrom <> @kGetRateFromServiceRateSheet
			begin
				insert tEstimateService (EstimateKey, ServiceKey, Rate, Cost)
				select @EstimateKey, es.ServiceKey, es.Rate, s.HourlyCost 
				from   #tEstimateService es 
					inner join tService s (nolock) on es.ServiceKey = s.ServiceKey
			end
		else
			begin
				insert tEstimateService (EstimateKey, ServiceKey, Rate, Cost)
				select @EstimateKey, es.ServiceKey, es.Rate, ISNULL(trsd.HourlyCost, s.HourlyCost )
				from   #tEstimateService es 	
					inner join tService s (nolock) on es.ServiceKey = s.ServiceKey
					left outer join  tTimeRateSheetDetail trsd (NOLOCK) on es.ServiceKey = trsd.ServiceKey
				WHERE trsd.TimeRateSheetKey = @TimeRateSheetKey
			end
		
		delete tEstimateTaskLabor where EstimateKey = @EstimateKey

		--(329824) Added ISNULL wrappers
		insert tEstimateTaskLabor (EstimateKey, TaskKey, ServiceKey, Hours, Rate, Cost)
		select @EstimateKey, TaskKey, ServiceKey, ISNULL(Hours, 0), ROUND(ISNULL(Rate, 0),4), ISNULL(Cost, 0)
		from   #tEstimateTaskLabor (nolock)
	end

	-- Now do rollups	
	Declare @ApprovedQty smallint,@SalesTax1Amount MONEY, @SalesTax2Amount MONEY
	Select @ApprovedQty = ApprovedQty from tEstimate (nolock) where EstimateKey = @EstimateKey
	Exec sptEstimateRecalcSalesTax @EstimateKey, @ApprovedQty, @SalesTax1Amount OUTPUT, @SalesTax2Amount OUTPUT
	Update tEstimate set SalesTaxAmount = @SalesTax1Amount, SalesTax2Amount = @SalesTax2Amount where EstimateKey = @EstimateKey
	Exec sptEstimateTaskRollupDetail @EstimateKey

	return 1
end


/*
This is the Flex case
If we do not insert in permanent tables, do the joins like in sptEstimateGetAllDetails
The UI will separate the results into various datasets
*/

	-- estimate user
	select ''estimate user'' as TableName -- help with debugging
			, eu.*
	       ,ltrim(rtrim( isnull(u.FirstName, '''') + '' '' + isnull(u.LastName, '''') )) as UserName
	       ,eu.BillingRate as Rate
		   ,u.HourlyCost as Cost
	from   #tEstimateUser eu (nolock)  
	   inner join tUser u (nolock) on eu.UserKey = u.UserKey

	-- estimate task labor
	select ''estimate task labor'' as TableName -- help with debugging
			,*
			,ROUND(Hours * Rate, 2) as Gross
		from   #tEstimateTaskLabor (nolock) 

	-- estimate task

	-- like in sptEstimateTaskGetTree
	IF @GetRateFrom = 6 AND @EstType = 1
		select ''like in sptEstimateTaskGetTree'' as TableName -- help with debugging
		    ,ta1.TaskKey
			,ta1.TaskID
			,ta1.TaskName
			,ta1.TaskLevel
			,ta1.TaskType
			,ta1.Markup
			,ta1.SummaryTaskKey
			,ta1.TaskConstraint
			,ta1.MoneyTask
			,ta1.ScheduleTask
			,ta1.ShowDescOnEst
			,ta1.Description
			,ta1.ProjectOrder
			,ta1.TrackBudget
			,case
				when ta1.TaskType=1 and isnull(ta1.TrackBudget,0) = 0 then 1
				else 0
			end as NonTrackSummary
			,case when ta1.TaskType = 1 and isnull(ta1.TrackBudget,0) = 0 then 1
			else 2 end as BudgetTaskType
			,et.EstimateKey
			,et.EstimateTaskKey
			,et.Hours
			,isnull(et.Cost, et.Rate) As Cost
			,round(isnull(et.Cost, isnull(et.Rate, 0)) * isnull(et.Hours, 0), 2) as BudgetLabor 
			,ISNULL(et.Rate, ta1.HourlyRate) AS Rate
			,et.EstLabor
			,et.BudgetExpenses
			,et.Markup as EstMarkup
			,et.EstExpenses
			,(select sum(et2.Hours * et2.Cost)
			from  tTask ta2 (nolock)
					inner join #tEstimateTask et2 (nolock) on et2.TaskKey = ta2.TaskKey
				where ta2.SummaryTaskKey = ta1.TaskKey
				) AS DetailBudgetLabor						-- To display on estimate_tasks.aspx grid
		from tTask ta1 (nolock)
			left outer join #tEstimateTask et (nolock) on ta1.TaskKey = et.TaskKey 
		where ta1.ProjectKey = @ProjectKey
		and isnull(ta1.MoneyTask,0) = 1
		order by ta1.ProjectOrder
	ELSE	 
		select ''like in sptEstimateTaskGetTree'' as TableName -- help with debugging
		    ,ta1.TaskKey
			,ta1.TaskID
			,ta1.TaskName
			,ta1.TaskLevel
			,ta1.TaskType
			,ta1.Markup
			,ta1.SummaryTaskKey
			,ta1.TaskConstraint
			,ta1.MoneyTask
			,ta1.ScheduleTask
			,ta1.ShowDescOnEst
			,ta1.Description
			,ta1.ProjectOrder
			,ta1.TrackBudget
			,case
				when ta1.TaskType=1 and isnull(ta1.TrackBudget,0) = 0 then 1
				else 0
			end as NonTrackSummary
			,case when ta1.TaskType = 1 and isnull(ta1.TrackBudget,0) = 0 then 1
			else 2 end as BudgetTaskType
			,et.EstimateKey
			,et.EstimateTaskKey
			,et.Hours
			,isnull(et.Cost, et.Rate) As Cost
			,round(isnull(et.Cost, isnull(et.Rate, 0)) * isnull(et.Hours, 0), 2) as BudgetLabor 
			,et.Rate
			,et.EstLabor
			,et.BudgetExpenses
			,et.Markup as EstMarkup
			,et.EstExpenses
			,(select sum(et2.Hours * et2.Cost)
			from  tTask ta2 (nolock)
					inner join #tEstimateTask et2 (nolock) on et2.TaskKey = ta2.TaskKey
				where ta2.SummaryTaskKey = ta1.TaskKey
				) AS DetailBudgetLabor						-- To display on estimate_tasks.aspx grid
		from tTask ta1 (nolock)
			left outer join #tEstimateTask et (nolock) on ta1.TaskKey = et.TaskKey 
		where ta1.ProjectKey = @ProjectKey
		and isnull(ta1.MoneyTask,0) = 1
		order by ta1.ProjectOrder
	
		-- estimate service 	
		
		select ''estimate service'' as TableName -- help with debugging
		       ,es.*
			   ,s.ServiceCode
			   ,s.Description
			   ,s.HourlyCost as Cost
		from   #tEstimateService es (nolock)
			inner join tService s (nolock) on es.ServiceKey = s.ServiceKey 
		order by s.Description

	-- Labor summary
	if @EstType = @kByTaskService
	begin
		select  ''labor summary'' as TableName -- help with debugging
			,s.Description
			,ISNULL((
			select SUM(etl.Hours) from #tEstimateTaskLabor etl (nolock) 
			where etl.EstimateKey = @EstimateKey
			and   etl.ServiceKey = es.ServiceKey 
			),0) as Hours
			,ROUND(ISNULL((
			select SUM(ROUND(etl.Hours * etl.Rate,2)) from #tEstimateTaskLabor etl (nolock) 
			where etl.EstimateKey = @EstimateKey
			and   etl.ServiceKey = es.ServiceKey 
			),0),2) as LaborGross
		from    #tEstimateService es (nolock)
		inner   join tService s (nolock) on es.ServiceKey = s.ServiceKey
		where   es.EstimateKey = @EstimateKey
		and     es.EstimateKey > 0
		order   by s.Description
	end
	else if @EstType = @kByTaskPerson
	begin
		select  ''labor summary'' as TableName -- help with debugging
		    ,u.FirstName + '' '' + u.LastName as Description
			,ISNULL((
			select SUM(etl.Hours) from #tEstimateTaskLabor etl (nolock) 
			where etl.EstimateKey = @EstimateKey
			and   etl.UserKey = eu.UserKey 
			),0) as Hours
			,ROUND(ISNULL((
			select SUM(ROUND(etl.Hours * etl.Rate, 2)) from #tEstimateTaskLabor etl (nolock) 
			where etl.EstimateKey = @EstimateKey
			and   etl.UserKey = eu.UserKey 
			),0),2) as LaborGross
		from    #tEstimateUser eu (nolock)
		inner   join tUser u (nolock) on eu.UserKey = u.UserKey
		where   eu.EstimateKey = @EstimateKey
		and     eu.EstimateKey > 0
		order   by u.FirstName + '' '' + u.LastName
	end
	else 
		select ''labor summary'' as TableName -- help with debugging
			, '''' as Description,  0 as LaborGross, *
		from   #tEstimateTaskLabor where 1=2

	-- for tasks on left side
	select ''tasks on the left side'' as TableName -- help with debugging
		,t.TaskKey
		,t.TaskID
		,t.TaskName
		,t.Description
		,t.SummaryTaskKey
		,t.BudgetTaskKey
		,t.TaskType
		,t.TaskLevel
		,t.ScheduleTask
		,t.TrackBudget
		,t.MoneyTask
		,case when TaskType=1 and isnull(TrackBudget,0) = 0 then 1
		else 0 end as NonTrackSummary
		,case when TaskType = 1 and isnull(TrackBudget,0) = 0 then 1
	     else 2 end as BudgetTaskType
	    ,ISNULL((
	    select sum(et.Hours) from #tEstimateTask et (nolock) 
	    where et.EstimateKey = @EstimateKey and et.TaskKey = t.TaskKey
	    ),0)
	    +ISNULL((
	    select sum(etl.Hours) from #tEstimateTaskLabor etl (nolock) 
	    where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
	    ),0) As Hours
	    ,ROUND(
			ISNULL((
			select sum(round(et.Hours * et.Rate, 2)) from #tEstimateTask et (nolock) 
			where et.EstimateKey = @EstimateKey and et.TaskKey = t.TaskKey
			),0) 
			+ISNULL((
			select sum(round(etl.Hours * etl.Rate,2)) from #tEstimateTaskLabor etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
			),0)
	    ,2) As Gross
	
		-- Added to display expenses for each task on the grid 
		,ISNULL((
			select sum(BillableCost) from tEstimateTaskExpense etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
		),0) As ExpenseGross1
		,ISNULL((
			select sum(BillableCost2) from tEstimateTaskExpense etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
		),0) As ExpenseGross2
		,ISNULL((
			select sum(BillableCost3) from tEstimateTaskExpense etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
		),0) As ExpenseGross3
		,ISNULL((
			select sum(BillableCost4) from tEstimateTaskExpense etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
		),0) As ExpenseGross4
		,ISNULL((
			select sum(BillableCost5) from tEstimateTaskExpense etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey =t.TaskKey
		),0) As ExpenseGross5
		,ISNULL((
			select sum(BillableCost6) from tEstimateTaskExpense etl (nolock) 
			where etl.EstimateKey = @EstimateKey and etl.TaskKey = t.TaskKey
		),0) As ExpenseGross6

		, 0 As ExpenseGross -- we will calc on client based on ApprovedQty
		, 0 As TotalGross -- we will calc on client based on ApprovedQty
	
	  from tTask t (nolock)
	 where t.ProjectKey = @ProjectKey
	 and t.MoneyTask = 1
	order by t.ProjectOrder


	RETURN 1


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptWidgetTabUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptWidgetTabUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptWidgetTabUpdate]
(
	@WidgetTabKey int,
	@WidgetDashKey int,
	@Label varchar(300)
)

as



if @WidgetTabKey > 0 
BEGIN
	Update tWidgetTab Set Label = @Label Where WidgetTabKey = @WidgetTabKey
END
ELSE
BEGIN
	
	Declare @DisplayOrder int = 0
	Select @DisplayOrder = ISNULL(Max(DisplayOrder), 0) + 1 from tWidgetTab (nolock) Where WidgetDashKey = @WidgetDashKey
	
	Insert tWidgetTab (WidgetDashKey, Label, DisplayOrder) values (@WidgetDashKey, @Label, @DisplayOrder)
	Select @WidgetTabKey = @@IDENTITY
END


Delete tSecurityAccess Where Entity = ''tWidgetTab'' and EntityKey = @WidgetTabKey

return @WidgetTabKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptWidgetTabDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptWidgetTabDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptWidgetTabDelete]
(
	@WidgetTabKey int
)

as


Delete tReport Where WidgetTabKey = @WidgetTabKey

Delete tSecurityAccess Where Entity = ''tWidgetTab'' and EntityKey = @WidgetTabKey

Delete tWidgetTab Where WidgetTabKey = @WidgetTabKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityUpdateNotes]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityUpdateNotes]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActivityUpdateNotes]
	@ActivityKey int,
	@Notes nvarchar(max)
AS

/*
|| When		 Who Rel			   What
|| 03/25/21	 GAR 21.05.00.0000	   TextEditor - Created for replacing Base64 image tags with actual image links
|| 07/30/25  AMP 25.08.17 (705266) Reviewed - No trigger change needed at this time. Internal process to convert base64 images to webdav links.
*/

	UPDATE	tActivity
	SET		Notes = @Notes
	WHERE	ActivityKey = @ActivityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMentionGet]'
GO
IF OBJECT_ID(N'[dbo].[sptMentionGet]', 'P') IS NULL
EXEC sp_executesql N'

CREATE PROCEDURE [dbo].[sptMentionGet]
	@CompanyKey int,
	@EntityKey int,
	@Entity varchar(100),
	@TargetType varchar(100)
AS

/*
|| When      Who Rel      What
|| 07/17/26  RLB 26.08.16 (733017) Created so email pages can look up notified/mentioned users for an entity (e.g. review comment email recipients) instead of receiving the name list as a parameter
*/

SELECT	v.UserName as userName
FROM tMention m (nolock)
INNER JOIN vUserName v (nolock) ON v.UserKey = m.TargetKey
WHERE m.CompanyKey = @CompanyKey
AND m.Entity = @Entity
AND m.EntityKey = @EntityKey
AND m.TargetType = @TargetType
ORDER BY v.UserName
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptOFXGLAccountLinkGet]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[sptOFXGLAccountLinkGet]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[sptOFXGLAccountLinkGet]
	(
		@CompanyKey int,
		@FID varchar(50),
		@IntuBid varchar(50),
		@CCACCTTO varchar(100),
		@Org varchar(50) = NULL
	)

AS --Encrypt

/*
|| When      Who Rel         What
|| 07/30/26  MAS 26.08.16    (733785) Created. Resolve the GL Account for one OFX transaction account (CCACCTTO).
||                          Matches on CompanyKey + FID + CCACCTTO (IntuBid/Org are stored for reference only).
||                          Returns the mapped GLAccountKey (>0). If no mapping row exists, inserts an
||                          unmapped row (GLAccountKey NULL) and returns 0 so the caller skips the transaction.
*/

DECLARE @GLAccountKey int
DECLARE @OFXGLAccountLinkKey int

SELECT TOP 1 @OFXGLAccountLinkKey = OFXGLAccountLinkKey, @GLAccountKey = GLAccountKey
FROM tOFXGLAccountLink (nolock)
WHERE CompanyKey = @CompanyKey
AND ISNULL(FID, '''') = ISNULL(@FID, '''')
AND CCACCTTO = @CCACCTTO

IF @OFXGLAccountLinkKey IS NULL
	BEGIN
		-- First time we''ve seen this account in a file - record it as unmapped for an admin to map.
		INSERT tOFXGLAccountLink (CompanyKey, FID, Org, IntuBid, CCACCTTO, GLAccountKey)
		VALUES (@CompanyKey, @FID, @Org, @IntuBid, @CCACCTTO, NULL)

		RETURN 0
	END

RETURN ISNULL(@GLAccountKey, 0)
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActivityGetDiary]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[sptActivityGetDiary]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptActivityGetDiary]
	(
		@CompanyKey int,
		@Entity varchar(50),
		@EntityKey int,
		@StartDate smalldatetime, 
		@EndDate smalldatetime,
		@VisibleToClient tinyint,
		@UserKey int,
		@SubscribedUserKey int,
		@ActivityKey int = null,
		@RootOnly tinyint = 0,
		@Max tinyint = 1,
		@ProjectDiary tinyint = 0,
		@IncludeActivities tinyint = 0,
		@ActivityTypeKey int = 0,
		@GetLatestOnly tinyint = 0,
		@TaskKey int = 0,
		@SearchText nvarchar(512) = ''''
	)
AS --Encrypt

/*

	************* READ THIS ********************
	NOTE:  If you add a new parameter to this proc please check to make sure the API version doesn''t break. See Q if you have any questions.
	*********************************************

|| When      Who Rel      What
|| 1/16/09   CRG 10.5.0.0 Added IsThread column.
||                        Added Order By to the calendar queries.
||                        Also changed ProjectKey to check for 0 rather than NULL because it''s 0 in Calendar.
|| 4/30/09   CRG 10.5.0.0 Added ActivityTypeKey so history search will work for Activity Types
|| 6/03/09   RTC 10.5.0.0 Added date range logic, UserKey logic
|| 6/30/09   CRG 10.5.0.0 Fixed joins to prevent duplicate rows
|| 07/20/09  GWG 10.5.0.5 Added Start time to the sort date.
|| 08/12/09  GHL 10.5.0.7 (59630) Added attachment count
|| 09/18/09  GWG 10.5.1.0 Modified sort date
|| 9/23/09   CRG 10.5.1.1 (59625) Modified for threaded view.
|| 11/23/09  RLB 10.5.1.4 (68940) Changed the join to a.UserLeadKey.
|| 7/15/10   CRG 10.5.3.2 Added ProjectNumber, TaskID, TaskName
|| 7/22/10   GHL 10.5.3.2 Added AssignedUserName and TaskName to meetings since meetings are joined with activities
||                        and part of the groups on the grid display
|| 12/3/10   GHL 10.5.3.9 Cloned sptActivityGetHistory for the new diary functionality
|| 12/14/10  GHL 10.5.3.9 Added parameter ActivityKey to get the thread for a single activity
|| 12/16/10  GHL 10.5.3.9 Added IsSubscribed column to support subscription function
|| 12/29/10  GHL 10.5.3.9 Added RootActivityKey in joins used in subqueries (i.e. use IX_RootActivityKey)
|| 01/17/11  GHL 10.5.4.0 Changed ThreadSort date as max(DateUpdated, LastReplyDate) for root activities
|| 04/01/11  GHL 10.5.4.2 (107646) Added AddedByUserName to show true idendity of diary post creator
|| 03/14/14  MAS 10.5.7.8 Added IsRead to support the ''New App''
|| 03/17/15  GWG 10.5.9.0 Added rootonly param to pull just top level posts for the project diary.
|| 06/15/15  RLB 10.5.9.3 Added for new Plat Project Dashboard
|| 11/11/15  GAR 10.5.9.8 (276592) Added ProjectOrder from tasks for sorting
|| 03/03/16  MCM 10.6.0.1 adding fields for the API
|| 03/11/16  MCM 10.6.0.2 removed api fields since we created a seperate stored proc
|| 07/19/16  RLB 10.6.0.6 (307095) set project order to 0 for project views
|| /9/01/17  GWG 10.6.1.9 Adding @IncludeActivities for the case where you want to see activities as well as diaries to work like the advanced diary.
|| 10/28/17  GWG 10.6.2.1 Changing reply count to only look at Root ActivityKey
|| 12/05/17  GAR 18.1.0   (373510) - ENH - Adding a flag to show if the conversation was updated from an inbound email
|| 05/01/18  RLB 18.5.0.0 To Do enhancement
|| 05/15/18  GAR 18.5.0.0 (401361) The temp table field for ActivitySubject (LeadSubject) was too small and it was blowing up - changed to 2000
|| 08/23/18  GAR 18.9.0.0 (416097) Added SendNotification to store notification send status
|| 01/15/19  RLS 19.0.2.0 (440187) Added @ActivityTypeKey
|| 05/08/19  WDF 19.0.5.0 (458899) Changed tProject from ''inner join'' to ''left outer join''.
|| 05/09/19  WDF 19.0.6.0 (459536) Added ActivityEntity
|| 05/10/19  RLS 19.0.6.0 Fixed a bug introduced by 458899 (two above); Moved al.Entity = @Entity and al.EntityKey = @EntityKey from the outer join back into the WHERE caluse. 
|| 05/26/20  CRG 20.0.7.0 (516752) Converted Notes to nvarchar
|| 06/24/20  RLS 20.0.7.0 (518686) Converted Subject to nvarchar
|| 08/03/20  RLS 20.0.8.0 (524320) Added a.AssignedUserKey & a.Private
|| 11/30/20  WDF 20.1.2.0 (538256) Set LeadSubject size to varchar(max) as defined in the tActivity table
|| 11/30/20  RLS 20.1.2.0 (538256) Set LeadSubject size BACK TO to varchar(4000) due to the re-definition of the tActivity table
|| 11/30/20  RLS 21.0.4.0 (546075) Changed AddedByUserName and UpdatedByUserName to nvarchar
|| 11/30/20  RLS 21.0.4.0 (564254) Changed LastReplyUserName,ProjectFullName,TaskID,TaskName,TaskFullName to nvarchar
|| 09/15/21  RLB 21.10.17 (569520) adding favorite option to project diary dash
|| 09/24/21  RLB 21.10.17 (569520c) making conversation favorite all the same id
|| 10/28/21  GAR 21.12.19 (DEV2501-514) Added CreatedFromSlack, SentToSlack for the Slack integration
|| 02/11/22  RLS 22.03.20 (582281) Added IsFavorite desc to the ORDER BYs
|| 04/12/22  GAR 22.05.15 (591331) Only use Entity if it is passed in
|| 05/19/22  GAR 22.05.19 (599562) Changed the way the query grabs data to help speed it up
|| 08/26/22  RLB 22.09.18 (610285) moving projectnumber up to varchar100
|| 10/25/24  CRG 24.11.17 (677514) Added EMLAttachmentKey
|| 05/12/25  RLB 25.06.15 (699286) Added option parm to pull last updated only when pull the rootonly
|| 05/27/25  RLB 25.06.15 (699286) change made to pull all not just one row 
|| 07/11/25  RLS 25.07.20 (705669) Changed the query for the field UnReadCount for the issue number above (699286)
|| 10/06/25  RLB 25.11.16 (709945) Added OriginalEmailsSent to display the emails names sent out
|| 07/14/26  GAR 26.08.16 (731247) Adding parameters for searchText and taskKey so we can search in the project diary

*/

declare @RootActivityKey int

if @ActivityKey is not null
	Select @RootActivityKey = RootActivityKey from tActivity (nolock) Where ActivityKey = @ActivityKey

if @StartDate is null
	Select @StartDate = ''1/1/1920''

if @EndDate is null
	Select @EndDate = ''12/31/2040''

	create table #act (ActivityKey int null)
	create index idx_activity on #act (ActivityKey)

	create table #activity (
			EntityKey int null
			,Entity varchar(25) null
			,IconStyle varchar(25) null

			,SortDate datetime null
			,ThreadSort datetime null
			,DateAdded datetime null
			,DateUpdated datetime null
			,ActivityDate datetime null


			,ActivityKey int null
			,ParentActivityKey int null
			,RootActivityKey int null
			,CustomFieldKey int null
			
			,Subject nvarchar(4000) null
			,Notes nvarchar(max) null
			,VisibleToClient int null
			,ActivityTypeKey int null
			,TypeName varchar(500) null
			
			,Private int null
			,AssignedUserKey int null
			,OriginatorUserKey int null
			,AddedByKey int null
			,OriginatorUserName varchar(250) null
			,AddedByUserName nvarchar(250) null
			
			,ProjectKey int null
			,ProjectNumber varchar(100) null
			,ProjectFullName nvarchar(155) null
			,ProjectOrder int null
			
			,TaskKey int null
			,TaskFullName nvarchar(535) null
			,TaskID nvarchar(30) null
			,TaskName nvarchar(500) null

			,AttachmentCount int null
			,ReplyCount int null

			,LastReplyUserName nvarchar(250) null
			,LastReplyDate Datetime null
			,IsSubscribed int null
			,IsRead int null
			,UnreadCount int null
			,CreatedFromEmail tinyint null	
			
			,LeadKey int null	
			,LeadSubject nvarchar(4000) null
			,SendNotification tinyint null
			,UpdatedByUserName nvarchar(250) null
			,ActivityEntity varchar(50) null
			,IsFavorite int null
			,IsFavoriteFrom nvarchar(250) null
			,CreatedFromSlack tinyint null
			,SentToSlack tinyint null
			,EMLAttachmentKey int null
			,OriginalEmailsSent nvarchar(max) null
			)

	-- the problem is with:  (@Entity = '''' Or al.Entity = @Entity) and (@EntityKey = 0 Or al.EntityKey = @EntityKey) which is not a clean entry point
	-- this is faster by having: where Entity = @Entity and EntityKey = @EntityKey
	if isnull(@EntityKey,0) > 0 and len(isnull(@Entity, '''')) > 0
		insert #act (ActivityKey)
		select DISTINCT ActivityKey
		from tActivityLink al (nolock)
		where Entity = @Entity and EntityKey = @EntityKey 
	else
		insert #act (ActivityKey)
		select ActivityKey	
		from tActivity a (nolock)
	Where ((@IncludeActivities = 0 and a.ActivityEntity = ''Diary'') OR (@IncludeActivities = 1 and a.ActivityEntity <> ''ToDo''))
	--and (@Entity = '''' Or al.Entity = @Entity) and (@EntityKey = 0 Or al.EntityKey = @EntityKey)
	--and al.Entity = @Entity and al.EntityKey = @EntityKey
	and a.CompanyKey = @CompanyKey
	and (a.ActivityDate is null OR (a.ActivityDate > @StartDate and a.ActivityDate < @EndDate))
	and ISNULL(a.VisibleToClient, 0) >= @VisibleToClient
	and (@RootActivityKey is null Or a.RootActivityKey = @RootActivityKey)
	and (@RootOnly = 0 OR a.ActivityKey = a.RootActivityKey)
	and (@ActivityTypeKey = 0 OR a.ActivityTypeKey = @ActivityTypeKey) 
	and (@TaskKey = 0 OR a.TaskKey = @TaskKey)	

	if @RootOnly = 1 and @GetLatestOnly = 1
	BEGIN
		insert #activity (
				EntityKey 
				,Entity 
				,IconStyle 

				,SortDate
				,ThreadSort 
				,DateAdded 
				,DateUpdated 
				,ActivityDate 


				,ActivityKey 
				,ParentActivityKey 
				,RootActivityKey 
				,CustomFieldKey
			
				,Subject 
				,Notes 
				,VisibleToClient 
				,ActivityTypeKey 
				,TypeName 
			
				,Private
				,AssignedUserKey
				,OriginatorUserKey 
				,AddedByKey 
				,OriginatorUserName 
				,AddedByUserName 

				,ProjectKey
				,ProjectNumber 
				,ProjectFullName 
				,ProjectOrder
			
				,TaskKey 
				,TaskFullName 
				,TaskID 
				,TaskName 

				,AttachmentCount 
				,ReplyCount 

				,LastReplyUserName 
				,LastReplyDate 
				,IsSubscribed 
				,IsRead
				,UnreadCount
				,CreatedFromEmail
				,LeadKey
				,LeadSubject
				,SendNotification
				,UpdatedByUserName
				,ActivityEntity
				,IsFavorite
				,IsFavoriteFrom
				,CreatedFromSlack
				,SentToSlack
				,EMLAttachmentKey
				,OriginalEmailsSent
				)	

		Select  a.ActivityKey as EntityKey
				,''Activity'' as Entity
				,''menuCMActivities'' as IconStyle
			
				,ISNULL(a.StartTime, a.DateAdded) as SortDate
				,a.DateUpdated AS ThreadSort
				,a.DateAdded 
				,a.DateUpdated
				,a.ActivityDate
			
				,a.ActivityKey
				,a.ParentActivityKey
				,a.RootActivityKey
				,a.CustomFieldKey
			
				,a.Subject
				,a.Notes
				,ISNULL(a.VisibleToClient, 0) as VisibleToClient
				,a.ActivityTypeKey
				,aty.TypeName
			
				,a.Private
				,a.AssignedUserKey
				,a.OriginatorUserKey
				,a.AddedByKey
				,isnull(u.FirstName + '' '', '''') + isnull(u.LastName, '''') as OriginatorUserName
				,isnull(uadd.FirstName + '' '', '''') + isnull(uadd.LastName, '''') as AddedByUserName
			
				,isnull(p.ProjectKey, 0)
				,isnull(p.ProjectNumber, '''')
				,isnull(p.ProjectNumber, '''') + '' '' + isnull(p.ProjectName, '''') as ProjectFullName
				,case @ProjectDiary
					when 1 then 0
					else ISNULL(ta.ProjectOrder,0)					
				end AS ProjectOrder			
				,a.TaskKey
				,ISNULL((case when ta.TaskID is null then ta.TaskName else ta.TaskID + '' - '' + ta.TaskName end), '' '') as TaskFullName
				,ta.TaskID
				,ta.TaskName
			
			
				,(SELECT COUNT(att.AttachmentKey) FROM tAttachment att (NOLOCK)
						WHERE att.AssociatedEntity = ''tActivity'' 
					AND att.EntityKey = a.ActivityKey)
				AS AttachmentCount
			
				,(SELECT COUNT(*) FROM tActivity a2 (nolock) 
					where a.RootActivityKey = a2.RootActivityKey and a2.ParentActivityKey > 0 ) 
				As ReplyCount
		
				,(
				SELECT lru.FirstName + '' '' + lru.LastName 
				from    tUser lru (nolock)
					inner join tActivity a3 (nolock) on a3.AddedByKey = lru.UserKey
				where  a3.ActivityKey = 
					(SELECT MAX(a4.ActivityKey) FROM tActivity a4 (nolock) 
					where a.RootActivityKey = a4.RootActivityKey 
					and a.ActivityKey = a4.ParentActivityKey)
					) 
				As LastReplyUserName
			
				,(SELECT MAX(a5.DateAdded) FROM tActivity a5 (nolock) 
					where a.RootActivityKey = a5.RootActivityKey 
					and a.ActivityKey = a5.ParentActivityKey)
				As LastReplyDate
			
				, isnull((
					select count(*) from tActivityEmail ae (nolock)
					where ae.ActivityKey = a.ActivityKey
					and   ae.UserKey = @SubscribedUserKey
				),0) as IsSubscribed

				,(SELECT COUNT(ap.IsRead) 
					FROM tAppRead ap (NOLOCK)
					WHERE ap.UserKey = @SubscribedUserKey
					AND ap.Entity = ''tActivity''
					AND ap.EntityKey = a.ActivityKey and ap.IsRead > 0)
				AS IsRead
				,CASE When @RootOnly = 1 then  --only gets called when looking for the root only ie. platinum
					(select count(*)
					from tActivity ur (nolock)
					left outer join (Select * from tAppRead (nolock) Where UserKey = @SubscribedUserKey and Entity = ''tActivity'') as appRead on ur.ActivityKey = appRead.EntityKey
					Where ur.RootActivityKey = a.RootActivityKey 
					and ISNULL(appRead.IsRead, 0) = 0) ELSE 0 END as UnReadCount
				,a.CreatedFromEmail
				,p.LeadKey
				,a.Subject As LeadSubject
				,a.SendNotification
				,isnull(uupd.FirstName + '' '', '''') + isnull(uupd.LastName, '''') as UpdatedByUserName
				,a.ActivityEntity
				,CASE WHEN ISNULL(af.AppFavoriteKey, 0) > 0 THEN 1 ELSE 0 END AS IsFavorite
				,ISNULL(af.ActionID, '''') AS IsFavoriteFrom
				,a.CreatedFromSlack
				,a.SentToSlack
				,a.EMLAttachmentKey
				,a.OriginalEmailsSent
		From tActivity a (nolock)
		inner join #act on #act.ActivityKey = a.ActivityKey -- this replaces the where clause below
		--left outer join tActivityLink al (nolock) on a.ActivityKey = al.ActivityKey
		left outer join tUser u (nolock) on a.OriginatorUserKey = u.UserKey
		left outer join tUser uadd (nolock) on a.AddedByKey = uadd.UserKey
		left outer join tUser uupd (nolock) on a.UpdatedByKey = uupd.UserKey
		left outer join tProject p (nolock) on a.ProjectKey = p.ProjectKey
		left outer join tTask ta (nolock) on a.TaskKey = ta.TaskKey
		left outer join tActivityType aty (nolock) on a.ActivityTypeKey = aty.ActivityTypeKey
		left outer join tLead ld (nolock) on a.LeadKey = ld.LeadKey
		left outer join tAppFavorite af (nolock) ON a.ParentActivityKey = af.ActionKey AND af.ActionID = ''cm.activities'' AND af.UserKey = @SubscribedUserKey
	
		Where ((@IncludeActivities = 0 and a.ActivityEntity = ''Diary'') OR (@IncludeActivities = 1 and a.ActivityEntity <> ''ToDo''))
		--and (@Entity = '''' Or al.Entity = @Entity) and (@EntityKey = 0 Or al.EntityKey = @EntityKey)
		--and al.Entity = @Entity and al.EntityKey = @EntityKey
		and a.CompanyKey = @CompanyKey
		and (a.ActivityDate is null OR (a.ActivityDate > @StartDate and a.ActivityDate < @EndDate))
		and ISNULL(a.VisibleToClient, 0) >= @VisibleToClient
		and (@RootActivityKey is null Or a.RootActivityKey = @RootActivityKey)
		and (@ActivityTypeKey = 0 OR a.ActivityTypeKey = @ActivityTypeKey)
		and (@TaskKey = 0 OR a.TaskKey = @TaskKey)	
		and (isnull(@SearchText, '''') = '''' OR (
			(lower(isnull(u.FirstName + '' '', '''') + isnull(u.LastName, '''')) LIKE ''%'' + lower(@SearchText) + ''%'') OR 
			(lower(isnull(uadd.FirstName + '' '', '''') + isnull(uadd.LastName, '''')) LIKE ''%'' + lower(@SearchText) + ''%'') OR 
			(lower(a.Subject) LIKE ''%'' + lower(@SearchText + ''%'')) OR 
			(lower(a.Notes) LIKE ''%'' + lower(@SearchText + ''%''))
		))

	END
	ELSE


		insert #activity (
				EntityKey 
				,Entity 
				,IconStyle 

				,SortDate
				,ThreadSort 
				,DateAdded 
				,DateUpdated 
				,ActivityDate 


				,ActivityKey 
				,ParentActivityKey 
				,RootActivityKey 
				,CustomFieldKey
			
				,Subject 
				,Notes 
				,VisibleToClient 
				,ActivityTypeKey 
				,TypeName 
			
				,Private
				,AssignedUserKey
				,OriginatorUserKey 
				,AddedByKey 
				,OriginatorUserName 
				,AddedByUserName 

				,ProjectKey
				,ProjectNumber 
				,ProjectFullName 
				,ProjectOrder
			
				,TaskKey 
				,TaskFullName 
				,TaskID 
				,TaskName 

				,AttachmentCount 
				,ReplyCount 

				,LastReplyUserName 
				,LastReplyDate 
				,IsSubscribed 
				,IsRead
				,UnreadCount
				,CreatedFromEmail
				,LeadKey
				,LeadSubject
				,SendNotification
				,UpdatedByUserName
				,ActivityEntity
				,IsFavorite
				,IsFavoriteFrom
				,CreatedFromSlack
				,SentToSlack
				,EMLAttachmentKey
				,OriginalEmailsSent
				)

	

		Select  a.ActivityKey as EntityKey
				,''Activity'' as Entity
				,''menuCMActivities'' as IconStyle
			
				,ISNULL(a.StartTime, a.DateAdded) as SortDate
				,a.DateUpdated AS ThreadSort
				,a.DateAdded 
				,a.DateUpdated
				,a.ActivityDate
			
				,a.ActivityKey
				,a.ParentActivityKey
				,a.RootActivityKey
				,a.CustomFieldKey
			
				,a.Subject
				,a.Notes
				,ISNULL(a.VisibleToClient, 0) as VisibleToClient
				,a.ActivityTypeKey
				,aty.TypeName
			
				,a.Private
				,a.AssignedUserKey
				,a.OriginatorUserKey
				,a.AddedByKey
				,isnull(u.FirstName + '' '', '''') + isnull(u.LastName, '''') as OriginatorUserName
				,isnull(uadd.FirstName + '' '', '''') + isnull(uadd.LastName, '''') as AddedByUserName
			
				,isnull(p.ProjectKey, 0)
				,isnull(p.ProjectNumber, '''')
				,isnull(p.ProjectNumber, '''') + '' '' + isnull(p.ProjectName, '''') as ProjectFullName
				,case @ProjectDiary
					when 1 then 0
					else ISNULL(ta.ProjectOrder,0)					
				end AS ProjectOrder			
				,a.TaskKey
				,ISNULL((case when ta.TaskID is null then ta.TaskName else ta.TaskID + '' - '' + ta.TaskName end), '' '') as TaskFullName
				,ta.TaskID
				,ta.TaskName
			
			
				,(SELECT COUNT(att.AttachmentKey) FROM tAttachment att (NOLOCK)
					 WHERE att.AssociatedEntity = ''tActivity'' 
					AND att.EntityKey = a.ActivityKey)
				AS AttachmentCount
			
				,(SELECT COUNT(*) FROM tActivity a2 (nolock) 
					where a.RootActivityKey = a2.RootActivityKey and a2.ParentActivityKey > 0 ) 
				As ReplyCount
		
				,(
				SELECT lru.FirstName + '' '' + lru.LastName 
				from    tUser lru (nolock)
					inner join tActivity a3 (nolock) on a3.AddedByKey = lru.UserKey
				where  a3.ActivityKey = 
					(SELECT MAX(a4.ActivityKey) FROM tActivity a4 (nolock) 
					where a.RootActivityKey = a4.RootActivityKey 
					and a.ActivityKey = a4.ParentActivityKey)
					) 
				As LastReplyUserName
			
				,(SELECT MAX(a5.DateAdded) FROM tActivity a5 (nolock) 
					where a.RootActivityKey = a5.RootActivityKey 
					and a.ActivityKey = a5.ParentActivityKey)
				As LastReplyDate
			
				, isnull((
					select count(*) from tActivityEmail ae (nolock)
					where ae.ActivityKey = a.ActivityKey
					and   ae.UserKey = @SubscribedUserKey
				),0) as IsSubscribed

				,(SELECT COUNT(ap.IsRead) 
					FROM tAppRead ap (NOLOCK)
					WHERE ap.UserKey = @SubscribedUserKey
					AND ap.Entity = ''tActivity''
					AND ap.EntityKey = a.ActivityKey and ap.IsRead > 0)
				AS IsRead
				,CASE When @RootOnly = 1 then  --only gets called when looking for the root only ie. platinum
					(select count(*)
					from tActivity ur (nolock)
					left outer join (Select * from tAppRead (nolock) Where UserKey = @SubscribedUserKey and Entity = ''tActivity'') as appRead on ur.ActivityKey = appRead.EntityKey
					Where ur.RootActivityKey = a.ActivityKey 
					and ISNULL(appRead.IsRead, 0) = 0) ELSE 0 END as UnReadCount
				,a.CreatedFromEmail
				,p.LeadKey
				,a.Subject As LeadSubject
				,a.SendNotification
				,isnull(uupd.FirstName + '' '', '''') + isnull(uupd.LastName, '''') as UpdatedByUserName
				,a.ActivityEntity
				,CASE WHEN ISNULL(af.AppFavoriteKey, 0) > 0 THEN 1 ELSE 0 END AS IsFavorite
				,ISNULL(af.ActionID, '''') AS IsFavoriteFrom
				,a.CreatedFromSlack
				,a.SentToSlack
				,a.EMLAttachmentKey
				,a.OriginalEmailsSent
		From tActivity a (nolock)
		inner join #act on #act.ActivityKey = a.ActivityKey -- this replaces the where clause below
		--left outer join tActivityLink al (nolock) on a.ActivityKey = al.ActivityKey
		left outer join tUser u (nolock) on a.OriginatorUserKey = u.UserKey
		left outer join tUser uadd (nolock) on a.AddedByKey = uadd.UserKey
		left outer join tUser uupd (nolock) on a.UpdatedByKey = uupd.UserKey
		left outer join tProject p (nolock) on a.ProjectKey = p.ProjectKey
		left outer join tTask ta (nolock) on a.TaskKey = ta.TaskKey
		left outer join tActivityType aty (nolock) on a.ActivityTypeKey = aty.ActivityTypeKey
		left outer join tLead ld (nolock) on a.LeadKey = ld.LeadKey
		left outer join tAppFavorite af (nolock) ON a.ActivityKey = af.ActionKey AND af.ActionID = ''cm.activities'' AND af.UserKey = @SubscribedUserKey
	
		Where ((@IncludeActivities = 0 and a.ActivityEntity = ''Diary'') OR (@IncludeActivities = 1 and a.ActivityEntity <> ''ToDo''))
		--and (@Entity = '''' Or al.Entity = @Entity) and (@EntityKey = 0 Or al.EntityKey = @EntityKey)
		--and al.Entity = @Entity and al.EntityKey = @EntityKey
		and a.CompanyKey = @CompanyKey
		and (a.ActivityDate is null OR (a.ActivityDate > @StartDate and a.ActivityDate < @EndDate))
		and ISNULL(a.VisibleToClient, 0) >= @VisibleToClient
		and (@RootActivityKey is null Or a.RootActivityKey = @RootActivityKey)
		and (@RootOnly = 0 OR a.ActivityKey = a.RootActivityKey)
		and (@ActivityTypeKey = 0 OR a.ActivityTypeKey = @ActivityTypeKey)
		and (@TaskKey = 0 OR a.TaskKey = @TaskKey)	
		and (isnull(@SearchText, '''') = '''' OR (
			(lower(isnull(u.FirstName + '' '', '''') + isnull(u.LastName, '''')) LIKE ''%'' + lower(@SearchText) + ''%'') OR 
			(lower(isnull(uadd.FirstName + '' '', '''') + isnull(uadd.LastName, '''')) LIKE ''%'' + lower(@SearchText) + ''%'') OR 
			(lower(a.Subject) LIKE ''%'' + lower(@SearchText + ''%'')) OR 
			(lower(a.Notes) LIKE ''%'' + lower(@SearchText + ''%''))
		))

	--Order by a.DateUpdated DESC

	update #activity
	set    ThreadSort = LastReplyDate 
	where  ActivityKey = RootActivityKey 
	and    LastReplyDate is not null
	and    LastReplyDate > ThreadSort


	if @SearchText = ''''
	BEGIN
		if @Max = 1
		BEGIN
			if @GetLatestOnly = 1
				SELECT *
				FROM (
					SELECT *,
						   ROW_NUMBER() OVER (PARTITION BY RootActivityKey ORDER BY DateUpdated DESC) AS rn
					FROM #activity
				) sub
				WHERE rn = 1
				Order By IsFavorite desc, ProjectOrder, ThreadSort DESC
			else
				select * 
				from #activity
				Order By IsFavorite desc, ProjectOrder, ThreadSort DESC
		END
		ELSE
		BEGIN
			if @GetLatestOnly = 1
				SELECT top 5 * 
				FROM (
					SELECT *,
						   ROW_NUMBER() OVER (PARTITION BY RootActivityKey ORDER BY DateUpdated DESC) AS rn
					FROM #activity
				) sub
				WHERE rn = 1
				Order By IsFavorite desc, ProjectOrder, ThreadSort DESC
			else
				select top 5 * 
				from #activity
				Order By IsFavorite desc, ProjectOrder, ThreadSort DESC
		END
	END
	ELSE
	BEGIN
		select * 
			from #activity
			Order By IsFavorite desc, RootActivityKey DESC, ParentActivityKey DESC, ProjectOrder, ThreadSort DESC
	END
	

	if @RootActivityKey is null and @RootOnly = 0
	Select
		c.CalendarKey as EntityKey,
		''Meeting'' as Entity,
		''menuMainCalendar'' as IconStyle,
		c.EventStart as SortDate,
		org.FirstName + '' '' + org.LastName as Organizer,
		u.FirstName + '' '' + u.LastName as ContactName,
		u.Phone1,
		u.Phone2,
		u.Cell,
		u.Email,
		co.CompanyName as ContactCompany,
		c.ContactCompanyKey,
		u.CompanyKey as LinkedCompanyKey,
		ct.TypeName,
		c.*,
		0 AS ParentActivityKey,
		c.EventStart as ThreadSort,
		
		-- these are groups on the ActivityHistory
		org.FirstName + '' '' + org.LastName as AssignedUserName,
		'''' as TaskName

	From tCalendar c (nolock)
		inner join tCalendarLink cl (nolock) on c.CalendarKey = cl.CalendarKey
		inner join tCalendarAttendee ca (nolock) on c.CalendarKey = ca.CalendarKey and ca.Entity = ''Organizer''
		left outer join tCalendarAttendee au (nolock) on c.CalendarKey = au.CalendarKey and au.Entity = ''Attendee'' and au.EntityKey = @UserKey --Restrict EntityKey here to prevent multiple rows
		left outer join tUser org (nolock) on org.UserKey = ca.EntityKey
		left outer join tCompany co (nolock) on c.ContactCompanyKey = co.CompanyKey
		left outer join tUser u (nolock) on c.ContactUserKey = u.UserKey
		left outer join tCalendarType ct (nolock) on c.CalendarTypeKey = ct.CalendarTypeKey
	Where
		cl.Entity = @Entity and cl.EntityKey = @EntityKey
		and (@StartDate is null or (EventStart > @StartDate and EventStart < @EndDate))
		and (@UserKey is null or ca.EntityKey = @UserKey or au.EntityKey = @UserKey)
		ORDER BY EventStart DESC
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptOFXGLAccountLinkGetList]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[sptOFXGLAccountLinkGetList]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[sptOFXGLAccountLinkGetList]
	(
		@CompanyKey int
	)

AS --Encrypt

/*
|| When      Who Rel         What
|| 07/30/26  MAS 26.08.16    (733785) Created. Lists OFX account -> GL Account mappings for the admin grid
||                          (System Setup > Connections > Banking > OFX Mappings). Includes unmapped rows.
*/

Select	ol.OFXGLAccountLinkKey as OFXGLAccountLinkKey
		,ol.CompanyKey as companyKey
		,ol.FID as FID
		,ol.Org as Org
		,ol.IntuBid as intuBid
		,ol.CCACCTTO as CCACCTTO
		,ol.GLAccountKey as GLAccountKey
		,gla.AccountName as accountName
		,gla.AccountNumber as accountNumber
From tOFXGLAccountLink ol (nolock)
Left outer join tGLAccount gla (nolock) on gla.GLAccountKey = ol.GLAccountKey
Where ol.CompanyKey = @CompanyKey
Order By ol.FID, ol.CCACCTTO
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptRequestGetApproval]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[sptRequestGetApproval]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptRequestGetApproval]
 @RequestKey INT,
 @UserKey INT = 0
 
AS --Encrypt

  /*
  || When		Who Rel			What
  || 08/27/15	GAR 10.5.9.5	Created for new project request approval process.
  || 05/20/16   CRG 10.6.0.4    Added CampaignID, CampaignName, and tRequestDef.DisplayCampaign to the Request query
  || 08/20/16   GWG 10.6.0.7    Added calls for split billing
  || 01/09/17   RLB 10.1.0.1    Per GG removing inner join on ClientKey
  || 05/25/17   KMC 10.6.1.6    Remove backup approver for project requests
  || 05/26/17   KMC 10.6.1.6    Replace join to get backup approver
  || 06/29/17   KMC 10.6.1.7    (346353) Added DISTINCT to subquery for approval status. If there are multiple active steps/users and    
  ||                            both have the same backup approver then the same approval step key was being returned in multiple rows
  || 01/26/18   GHL 18.2.0      (380560) Added division and product + display setting from tRequestDef.DisplayDivisionProduct
  || 04/03/18   RLB 18.4.0      Added backup approver for each of the approval users
  || 04/04/18   RLB 18.5.0      added check for ActiveStep = 1 on approval status subquery because it could pull more than one row if there multiple steps with same user
  || 12/11/18   RLB 19.1.0.0    (418293) Adding Campaign Segment information
  || 05/29/19   RLS 19.0.6.0    (461835) Added ParentCompany and ParentCompanyKey
  || 10/18/19   GWG 19.1.1.0    Adding IncludesDeliverables
  || 09/08/20	KMC 20.1.0.0    (528430) Changed the SELECT DISTINCT to TOP 1 to avoid data problem where more than 1 active step exists
  || 11/23/20   RLB 20.1.2.0    (523390) slightly changed how approved and notify list are pulled for common approvals changes
  || 06/21/22   RLB 22.07.17    (603608) pull client glcompany to default on project create
  || 02/06/24   RLB 24.03.17    (658052) adding requestkey to campaign 
  || 05/15/25   GAR 25.06.15    (701767) Added tRequestDef.Active
  || 05/07/26   RLB 26.06.14    (721431) Added tRequestDef.SendIndividualApprovedEmails
  || 07/22/26   RLB 26.08.16    (733049) SendIndividualApprovedEmails did not have the correct label and not passing in correctly
  */
  
  SELECT tRequest.*
			,u.FirstName + '' '' + u.LastName as CreatedBy
			,u2.FirstName + '' '' + u2.LastName as UpdatedBy
			,tRequestDef.RequestName
			,tRequestDef.DisplayProjectFields
			,tRequestDef.DisplayClientProjNbr
			,ISNULL(tRequestDef.SendConfirmation, 0) AS SendConfirmation
			,tRequestDef.ConfirmationMessage
			,tRequestDef.DisplayCampaign
			,tRequestDef.DisplayDivisionProduct
			,ISNULL(tRequestDef.IncludesDeliverables, 0) as IncludesDeliverables
			,ISNULL(tRequestDef.SendIndividualApprovedEmails, 1) as SendIndividualApprovedEmails
			,ISNULL(c.CustomerID, '''') as CustomerID
			,ISNULL(c.CompanyName, '''') as CompanyName
			,ISNULL(c.ParentCompany, 0) as ParentCompany
			,ISNULL(c.ParentCompanyKey, 0) as ParentCompanyKey
			,ca.CampaignKey
			,ca.CampaignID
			,ca.CampaignName
			,cs.SegmentName
			,(Select count(*) from tSpecSheet (NOLOCK) Where Entity = ''ProjectRequest'' and EntityKey = @RequestKey) as StepCount
			,tRequestDef.PrintSpecOnSeparatePages
			,rrr.ReasonName AS RejectReasonName
			,-- Get whether or not this request is ready for the user to approve or reject.
				(SELECT TOP 1(tApprovalStep.ApprovalStepKey)
				FROM tApprovalStep (nolock) 
					inner join tApprovalStepUser on tApprovalStep.ApprovalStepKey = tApprovalStepUser.ApprovalStepKey
					inner join tRequest on tApprovalStep.EntityKey = tRequest.RequestKey
					inner join tRequestDef on tRequest.RequestDefKey = tRequestDef.RequestDefKey
					left outer join tCompany on tRequest.ClientKey = tCompany.CompanyKey
				WHERE
				tApprovalStep.Entity = ''ProjectRequest'' and ActiveStep = 1 and
				(tApprovalStepUser.AssignedUserKey = @UserKey or tApprovalStepUser.AssignedUserKey in (select UserKey from tUser (nolock) where BackupApprover = @UserKey)) and
				tApprovalStepUser.ActiveUser = 1 and 
				tApprovalStep.EntityKey = @RequestKey) AS ApprovalStatus
				,cd.DivisionName 
				,cp.ProductName
				,c.GLCompanyKey as DefaultGLCompanyKey
				,glc.GLCompanyName as DefaultGLCompanyName
				,glc.GLCompanyID as DefaultGLCompanyID
				,tRequestDef.Active
		FROM tRequest (NOLOCK) 
			inner join tRequestDef (NOLOCK) on tRequest.RequestDefKey = tRequestDef.RequestDefKey
			left join tCompany c (NOLOCK) on tRequest.ClientKey = c.CompanyKey
			left join tCampaign ca (NOLOCK) on tRequest.CampaignID = ca.CampaignID AND tRequest.CompanyKey = ca.CompanyKey
			left join tUser u (nolock) on tRequest.EnteredByKey = u.UserKey
			left join tUser u2 (nolock) on tRequest.UpdatedByKey = u2.UserKey
			LEFT JOIN tRequestRejectReason rrr (NOLOCK) ON tRequest.RequestRejectReasonKey = rrr.RequestRejectReasonKey
			left outer join tClientDivision cd (nolock) on tRequest.ClientDivisionKey = cd.ClientDivisionKey
			left outer join tClientProduct cp (nolock) on tRequest.ClientProductKey = cp.ClientProductKey
			left outer join tCampaignSegment cs (nolock) on tRequest.CampaignSegmentKey = cs.CampaignSegmentKey
			left outer join tGLCompany glc (nolock) on c.GLCompanyKey = glc.GLCompanyKey
		WHERE
			tRequest.RequestKey = @RequestKey

  -- Get all the steps for this request	  
  SELECT s.*, ISNULL(a.Rejected,0) AS Rejected, s.TimeZoneIndex,
	(Case s.Action When 1 then ''Edit'' when 2 then ''Approve'' when 3 then ''Notify'' end) as ActionText
  FROM tApprovalStep s (NOLOCK) 
			LEFT JOIN ( SELECT	s.ApprovalStepKey, COUNT(ISNULL(asu.Action,0)) as Rejected
					 FROM	tApprovalStep s (NOLOCK) INNER JOIN tApprovalStepUser asu (NOLOCK) ON s.ApprovalStepKey = asu.ApprovalStepKey
					 WHERE	asu.Action = 2
					 GROUP BY s.ApprovalStepKey ) a ON s.ApprovalStepKey = a.ApprovalStepKey
  WHERE s.Entity = ''ProjectRequest''
		And s.EntityKey = @RequestKey
  ORDER BY s.DisplayOrder ASC


  -- Get all the approval (or notify) users for this particular round across all steps
  SELECT su.*,
	LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName, ''''))) As UserName,
	su.AssignedUserKey as UserKey,
	su.DueDate as OriginalDueDate,
	su.NextReminder as OriginalNextReminder,
	CASE 
		WHEN su.DateActivated IS NULL THEN CASE 
											WHEN ISNULL(s.Completed, 0) = 1 THEN CASE su.Action
																					WHEN 1 THEN CASE su.WithChanges
																						WHEN 1 THEN ''Approved With Changes''
																						ELSE ''Approved'' END
																					WHEN 2 THEN ''Resubmit''
																					WHEN 3 THEN ''Skipped''
																					ELSE ''Not Required'' END
											else CASE su.Action
												WHEN 1 THEN CASE su.WithChanges
													WHEN 1 THEN ''Approved With Changes''
													ELSE ''Approved'' END
												WHEN 2 THEN ''Resubmit''
												WHEN 3 THEN ''Skipped''
												ELSE ''Waiting'' END
											end
		else CASE 
				WHEN ISNULL(su.CompletedUser, 0) = 1 THEN CASE su.Action
										WHEN 1 THEN CASE su.WithChanges
											WHEN 1 THEN ''Approved With Changes''
											ELSE ''Approved'' END
										WHEN 2 THEN ''Resubmit''
										WHEN 3 THEN ''Skipped''
										ELSE ''Not Required'' END
				else CASE su.Action
				WHEN 1 THEN CASE su.WithChanges
					WHEN 1 THEN ''Approved With Changes''
					ELSE ''Approved'' END
				WHEN 2 THEN ''Resubmit''
				WHEN 3 THEN ''Skipped''
				ELSE ''Reviewing'' END
		END
	END as ActionDescription,
	u.Email,
	s.Completed,
	su.AssignedUserKey as UserKey,
	rrr.ReasonName AS RejectReasonName,
	u.BackupApprover
  FROM tApprovalStepUser su (NOLOCK)
  INNER JOIN tApprovalStep s (NOLOCK) ON s.ApprovalStepKey = su.ApprovalStepKey
  INNER JOIN tUser u (NOLOCK) ON u.UserKey = su.AssignedUserKey 
  LEFT OUTER JOIN tRequest r (NOLOCK) ON s.EntityKey = r.RequestKey AND s.Entity = ''ProjectRequest''
  LEFT JOIN tRequestRejectReason rrr (NOLOCK) ON r.RequestRejectReasonKey = rrr.RequestRejectReasonKey
  WHERE Entity = ''ProjectRequest''
  And EntityKey = @RequestKey
  Order By su.DisplayOrder


  -- Get all the notify users for this particular round across all steps
  SELECT sn.*,
	LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName, ''''))) As UserName,
	sn.AssignedUserKey as UserKey,
	rrr.ReasonName AS RejectReasonName
  FROM tApprovalStepNotify sn (NOLOCK)
  INNER JOIN tApprovalStep s (NOLOCK) ON s.ApprovalStepKey = sn.ApprovalStepKey
  INNER JOIN tUser u (NOLOCK) ON u.UserKey = sn.AssignedUserKey
  LEFT OUTER JOIN tRequest r (NOLOCK) ON s.EntityKey = r.RequestKey AND s.Entity = ''ProjectRequest''
  LEFT JOIN tRequestRejectReason rrr (NOLOCK) ON r.RequestRejectReasonKey = rrr.RequestRejectReasonKey
  WHERE Entity = ''ProjectRequest''
  And EntityKey = @RequestKey

-- Get whether or not this request is ready for the user to approve or reject.
SELECT ISNULL(step.ApprovalStepKey, 0)
FROM tApprovalStep step (nolock) 
	inner join tApprovalStepUser asu on step.ApprovalStepKey = asu.ApprovalStepKey
	inner join tRequest r on step.EntityKey = r.RequestKey
	inner join tRequestDef rd on r.RequestDefKey = rd.RequestDefKey
	left outer join tCompany c on r.ClientKey = c.CompanyKey
WHERE
step.Entity = ''ProjectRequest'' and
asu.AssignedUserKey = @UserKey and
asu.ActiveUser = 1 and 
step.Entity = ''ProjectRequest'' and
step.EntityKey = @RequestKey


-- get any split billing
Select RequestKey, CompanyKey as ClientKey, CompanyName as ClientName, CustomerID as ClientID, Split
from tRequestSplit rs (nolock)
Inner join tCompany c (nolock) on rs.ClientKey = c.CompanyKey
Where rs.RequestKey = @RequestKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptOFXGLAccountLinkUpdate]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[sptOFXGLAccountLinkUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[sptOFXGLAccountLinkUpdate]
	(
		@OFXGLAccountLinkKey int,
		@GLAccountKey int,
		@CompanyKey int,
		@FID varchar(50) = NULL,
		@IntuBid varchar(50) = NULL,
		@CCACCTTO varchar(100) = NULL
	)

AS --Encrypt

/*
|| When      Who Rel         What
|| 07/30/26  MAS 26.08.16    (733785) Created. Sets (or clears) the GL Account on an OFX mapping row.
||                          Clearing the GL Account (0/NULL) unmaps the row but keeps it for future imports.
||                          Supports a manual add (@OFXGLAccountLinkKey = 0) when the identifying fields are supplied.
||                          Return codes: -1 = GL Account is not a Credit Card account (type 23).
*/

DECLARE @AccountType int

-- A GL Account is optional (clearing unmaps the row). When supplied it must be a Credit Card account.
IF ISNULL(@GLAccountKey, 0) > 0
	BEGIN
		SELECT @AccountType = AccountType From tGLAccount (nolock) WHERE GLAccountKey = @GLAccountKey AND CompanyKey = @CompanyKey

		IF ISNULL(@AccountType, 0) <> 23 -- credit card
			RETURN -1
	END

IF ISNULL(@OFXGLAccountLinkKey, 0) > 0
	BEGIN
		UPDATE tOFXGLAccountLink
		SET GLAccountKey = NULLIF(@GLAccountKey, 0)
		WHERE OFXGLAccountLinkKey = @OFXGLAccountLinkKey
		AND CompanyKey = @CompanyKey

		RETURN @OFXGLAccountLinkKey
	END
ELSE
	BEGIN
		INSERT tOFXGLAccountLink (CompanyKey, FID, IntuBid, CCACCTTO, GLAccountKey)
		VALUES (@CompanyKey, @FID, @IntuBid, @CCACCTTO, NULLIF(@GLAccountKey, 0))

		RETURN @@IDENTITY
	END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptOFXGLAccountLinkDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptOFXGLAccountLinkDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[sptOFXGLAccountLinkDelete]
	(
		@OFXGLAccountLinkKey int,
		@CompanyKey int
	)

AS --Encrypt

/*
|| When      Who Rel         What
|| 07/30/26  MAS 26.08.16    (733785) Created. Removes an OFX account -> GL Account mapping row.
*/

DELETE tOFXGLAccountLink
Where OFXGLAccountLinkKey = @OFXGLAccountLinkKey
And CompanyKey = @CompanyKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptBillingScheduleGetExistingInvoices]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[sptBillingScheduleGetExistingInvoices]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptBillingScheduleGetExistingInvoices]
	@ProjectKey int,
	@AdvanceBill tinyint = 0
AS --Encrypt

/*
|| When      Who Rel      What
|| 07/30/26  MFT 26.07.30 (729259) Created
*/

	SET NOCOUNT ON

	select
		i.InvoiceKey
		,i.InvoiceNumber
		,i.InvoiceDate
		,i.AdvanceBill
		,sum(isum.Amount) as TotalAmount
		,sum(case when il.BillFrom = 1 then isum.Amount else 0 end) as TotalAmountFF
		,sum(case when il.BillFrom = 2 then isum.Amount else 0 end) as TotalAmountTM
	from   tInvoiceSummary isum (nolock)
	inner join tInvoice i (nolock) on isum.InvoiceKey = i.InvoiceKey
	inner join tInvoiceLine il (nolock) on isum.InvoiceLineKey = il.InvoiceLineKey
	where  isum.ProjectKey = @ProjectKey
	and    isnull(i.AdvanceBill, 0) = isnull(@AdvanceBill, 0)
	-- exclude voided invoices (and the void invoices themselves)
	and    isnull(i.VoidInvoiceKey, 0) = 0
	-- exclude invoices already linked to a billing schedule row
	and    not exists (select 1 from tBillingSchedule bs (nolock) where bs.InvoiceKey = i.InvoiceKey)
	group by i.InvoiceKey, i.InvoiceNumber, i.InvoiceDate, i.AdvanceBill
	order by i.InvoiceDate, i.InvoiceNumber

return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
COMMIT TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
-- This statement writes to the SQL Server Log so SQL Monitor can show this deployment.
IF HAS_PERMS_BY_NAME(N'sys.xp_logevent', N'OBJECT', N'EXECUTE') = 1
BEGIN
    DECLARE @databaseName AS nvarchar(2048), @eventMessage AS nvarchar(2048)
    SET @databaseName = REPLACE(REPLACE(DB_NAME(), N'\', N'\\'), N'"', N'\"')
    SET @eventMessage = N'Redgate SQL Compare: { "deployment": { "description": "Redgate SQL Compare deployed to ' + @databaseName + N'", "database": "' + @databaseName + N'" }}'
    EXECUTE sys.xp_logevent 55000, @eventMessage
END
GO
DECLARE @Success AS BIT
SET @Success = 1
SET NOEXEC OFF
IF (@Success = 1) PRINT 'The database update succeeded'
ELSE BEGIN
	IF @@TRANCOUNT > 0 ROLLBACK TRANSACTION
	PRINT 'The database update failed'
END
GO
