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'Altering [dbo].[tPreference]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tPreference]', N'AdvBillPrefix') IS NULL
ALTER TABLE [dbo].[tPreference] ADD[AdvBillPrefix] [varchar] (50) NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptActionLogInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptActionLogInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptActionLogInsert]
	@Entity varchar(50),
	@EntityKey int,
	@CompanyKey int,
	@ProjectKey int,
	@Action varchar(200),
	@ActionDate datetime,
	@ActionBy nvarchar(500),
	@Comments nvarchar(4000),
	@Reference varchar(200),
	@SourceCompanyID varchar(100),
	@UserKey int = NULL,
	@CampaignKey int = NULL
AS --Encrypt

/*
|| When     Who	Rel			What
|| 12/06/12 MAS 10.5.6.3	Added Optional @UserKey and UserName lookup if @ActionBy is NULL
|| 12/19/12 RLB 10.5.6.3    Made Action column bigger
|| 10/13/15 RLB 10.5.9.8    Added CampaignKey for Plat
|| 02/05/16 CRG 10.6.0.1    We are not logging project template actions anymore
|| 03/05/18 RLB 18.3.0.0    (386618) We are now logging project template actions fixed my error as well
|| 06.05.18 GWG 18.6.0		Changed actiondate to a datetime so seconds are logged
|| 08.26.19 GAR 19.0.9.0    (473546) Changed the CompanyKey to be either the OwnerCompanyKey or the CompanyKey when no CompanyKey is passed in
|| 12/02/20 RLS 20.1.2.0    (535729) Changed the @Comments to nvarchar
|| 02/22/21 RLS 21.0.3.0    (546075) Changed the @ActionBy to nvarchar
|| 05/29/26 CRG 26.06.14    (729635) Added check to prevent duplicate "Project Made Live" log entries for the same project
*/

If @ActionBy IS NULL AND ISNULL(@UserKey,0) > 0
	Select @ActionBy = UserName from vUserName Where UserKey = @UserKey

If ISNULL(@CompanyKey,0) = 0 AND ISNULL(@UserKey,0) > 0
	Select @CompanyKey = ISNULL(OwnerCompanyKey, CompanyKey) from tUser (nolock) Where UserKey = @UserKey

IF UPPER(@Action) = ''PROJECT MADE LIVE''
BEGIN
	--Special case where users are hitting Make Project Live multiple times, causing duplicate log entries
	--The duplicate log entries are causing duplicate records in project custom reports and views
	IF EXISTS
			(SELECT NULL
			FROM	tActionLog (nolock)
			WHERE	CompanyKey = @CompanyKey
			AND		Entity = @Entity
			AND		EntityKey = @EntityKey
			AND		UPPER(@Action) = ''PROJECT MADE LIVE'')
		RETURN 1
END

INSERT tActionLog
	(
	Entity,
	EntityKey,
	CompanyKey,
	ProjectKey,
	Action,
	ActionDate,
	ActionBy,
	Comments,
	Reference,
	SourceCompanyID,
	UserKey,
	CampaignKey
	)

VALUES
	(
	@Entity,
	@EntityKey,
	@CompanyKey,
	@ProjectKey,
	@Action,
	@ActionDate,
	@ActionBy,
	@Comments,
	@Reference,
	@SourceCompanyID,
	@UserKey,
	@CampaignKey
	)
	
Return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spRptProfitCalcOverheadAllocation]'
GO
IF OBJECT_ID(N'[dbo].[spRptProfitCalcOverheadAllocation]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spRptProfitCalcOverheadAllocation]
	@CompanyKey int,
	@UserKey int,	
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@AllocateBy smallint,
	@TotalOverhead50 money OUTPUT,
	@TotalOverhead51 money OUTPUT,
	@TotalOverhead52 money OUTPUT,
	@TotalAGI money OUTPUT,
	@TotalHours decimal(24,4) OUTPUT,
	@TotalLaborCost money OUTPUT,
	@TotalBillings money OUTPUT,
	@TotalOridnaryIncome money OUTPUT

AS --Encrypt

/*
|| When      Who Rel     What
|| 10/16/07  CRG 8.5     Created to be used by the Profitability Reports to calculate Overhead Allocation
|| 11/12/07  GWG 8.5     Modified to not include income in the overhead calculation
|| 11/20/07  CRG 8.5     Modified to use the new #tTime temp table to improve performance.
|| 05/21/13  GHL 10.568  (176115) Added @ClassKey param to filter out by class
|| 01/02/14  GHL 10.575  Reading now vHTransaction for home currency amounts
|| 06/08/20  AMP 20.1.0.0 (510311) Changed GL Company, Office, and Class to be ''Any Of'' options on the Client P&L multi report
|| 08/19/20  MFT 20.0.9.0 (526310) Correct GLCompanyKey subquery
|| 07/13/23  RLB 23.08.20 (631002) adding sorting by GL Account DisplayOrder
|| 09/11/25  RLB 25.10.19 (706734) Added TotalOridnaryIncome
|| 05/01/26  MCM 26.06.01 (727593) Updated formula for TotalLaborCosts to be done when allocateby = 4 (totalBill)
*/

	DECLARE	@HasGLCompanyKeys int	SELECT	@HasGLCompanyKeys = COUNT(*) FROM	#GLCompanyKeys
	DECLARE	@HasClassKeys int		SELECT	@HasClassKeys = COUNT(*) FROM #ClassKeys
	DECLARE	@HasOfficeKeys int		SELECT	@HasOfficeKeys = COUNT(*) FROM #OfficeKeys

	Declare @RestrictToGLCompany int 
 
	Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
	from tPreference
	where  CompanyKey = @CompanyKey
 
	select @RestrictToGLCompany = isnull(@RestrictToGLCompany, 0) 

	--overhead allocation, all overhead clients or no client transactions
	select @TotalOverhead50 = 
		isnull((
			select sum(Debit - Credit)
			from vHTransaction t (nolock) 
			inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
			where t.CompanyKey = @CompanyKey
			and gl.CompanyKey = @CompanyKey
			and t.TransactionDate >= @StartDate and t.TransactionDate <= @EndDate
			and gl.AccountType = 50
			and (isnull(t.Overhead, 0) = 1 or t.ClientKey is null)			
			AND (
				-- All companies
				(
				@HasGLCompanyKeys = 0 AND
					(
					@RestrictToGLCompany = 0 OR 
					(t.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
				-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
				OR ISNULL(t.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
				)			
			    AND	(@HasOfficeKeys = 0 OR ISNULL(t.OfficeKey, 0) IN (SELECT OfficeKey FROM #OfficeKeys))
			    AND	(@HasClassKeys = 0 OR ISNULL(t.ClassKey, 0) IN (SELECT ClassKey FROM #ClassKeys))
		), 0)
		
	select @TotalOverhead51 = 
		isnull((
			select sum(Debit - Credit)
			from vHTransaction t (nolock) 
			inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
			where t.CompanyKey = @CompanyKey
			and gl.CompanyKey = @CompanyKey
			and t.TransactionDate >= @StartDate and t.TransactionDate <= @EndDate
			and gl.AccountType = 51
			and (isnull(t.Overhead, 0) = 1 or t.ClientKey is null)					
			AND (
				-- All companies
				(
				@HasGLCompanyKeys = 0 AND
					(
					@RestrictToGLCompany = 0 OR 
					(t.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
				-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
				OR ISNULL(t.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
				)			
			AND	(@HasOfficeKeys = 0 OR ISNULL(t.OfficeKey, 0) IN (SELECT OfficeKey FROM #OfficeKeys))
			AND	(@HasClassKeys = 0 OR ISNULL(t.ClassKey, 0) IN (SELECT ClassKey FROM #ClassKeys))
		), 0)
		
	select @TotalOverhead52 = 
		isnull((
			select sum(Debit - Credit)
			from vHTransaction t (nolock) 
			inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
			where t.CompanyKey = @CompanyKey
			and gl.CompanyKey = @CompanyKey
			and t.TransactionDate >= @StartDate and t.TransactionDate <= @EndDate
			and gl.AccountType = 52
			and (isnull(t.Overhead, 0) = 1 or t.ClientKey is null)		
			AND (
				-- All companies
				(
				@HasGLCompanyKeys = 0 AND
					(
					@RestrictToGLCompany = 0 OR 
					(t.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
				-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
				OR ISNULL(t.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
				)		
			AND	(@HasOfficeKeys = 0 OR ISNULL(t.OfficeKey, 0) IN (SELECT OfficeKey FROM #OfficeKeys))
			AND	(@HasClassKeys = 0 OR ISNULL(t.ClassKey, 0) IN (SELECT ClassKey FROM #ClassKeys))
		), 0)
	
	--Overhead Allocations
	--by labor (#tTime must be created before calling this SP)
	IF @AllocateBy IN (2, 3, 4)
		SELECT	@TotalHours = ISNULL(SUM(ActualHours), 0),
				@TotalLaborCost = ISNULL(SUM(Cost), 0)
		FROM	#tTime
	
	--by billings			
	if @AllocateBy = 4
		begin 
			select @TotalBillings =
				isnull((
					select isnull(sum(Credit - Debit), 0)
					from vHTransaction t (nolock) 
					inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
					where t.CompanyKey = @CompanyKey
					and gl.CompanyKey = @CompanyKey
					and t.TransactionDate >= @StartDate and t.TransactionDate <= @EndDate
					and gl.AccountType = 40
					and isnull(t.Overhead, 0) = 0
					and t.ClientKey is not null					
					AND (
				-- All companies
				(
				@HasGLCompanyKeys = 0 AND
					(
					@RestrictToGLCompany = 0 OR 
					(t.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
				-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
				OR ISNULL(t.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
				)
				AND	(@HasOfficeKeys = 0 OR ISNULL(t.OfficeKey, 0) IN (SELECT OfficeKey FROM #OfficeKeys))
		    	AND	(@HasClassKeys = 0 OR ISNULL(t.ClassKey, 0) IN (SELECT ClassKey FROM #ClassKeys))
				), 0)
		end
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vListing_TaskAssignment]'
GO
IF OBJECT_ID(N'[dbo].[vListing_TaskAssignment]', 'V') IS NOT NULL
EXEC sp_executesql N'-- View

ALTER VIEW [dbo].[vListing_TaskAssignment]
AS

/*
  || When     Who Rel     What
  || 12/14/06 GHL 8.4     Replaced NULL columns (assignments) by tTask or tTaskUser values 
  || 12/21/06 GHL 8.4     Fixed bad vUserName JOIN. Somebody changed my change from 12/14/06!
  || 01/25/07 GHL 8.402   Added Timestamp related columns 
  || 03/27/07 RTC 8.41    (7915) Added Client Division and Client Product columns 
  || 10/10/07 CRG 8.5     Added GLCompany, Class, and OfficeID
  || 11/06/07 CRG 8.5     (12657) Added Task Priority  
  || 01/29/08 GHL 8.503   (19631) Added hint with ProjectKey (tTask51 index)  to join with tTask. 
  ||                                    For some reason was doing a table scan
  || 02/06/08 CRG 1.0.0.0 Added ASC_Selected
  || 10/13/08 QMD 10.0.1.0(36501) Added CustomFieldKey for projects
  || 10/27/08 RTC 10.0.1.1 (38647) Wrapped ''Project Type Name'' with isnull in case no project type is specified on the project  
  || 03/17/09 RTC 10.5	  Removed user defined fields.
  || 09/15/09 GWG 10.510  Added fields to default project number, name, task and user for addinga  new activity
  || 01/22/10 RLB 10.517  (73008) Added Project Full Name
  || 02/10/10 GWG 10.518  Added Project Closed to be able to find people assigned to non closed jobs for staff schedule
  || 07/29/10 GHL 10.533  (86321) Removed Active flag. Because was causing confusion among users.
  || 08/13/10 RLB 10.533   (87534) Added Parent Company
  || 11/1/10  RLB 10.537  (89862)  Added few fields  to display task health on listing
  || 11/2/10  RLB 10.537  (91358) Added Client Primary Contact
  || 11/16/10 CRG 10.5.3.8 Added PlanDuration.
  ||                       Also, for the Assigned Staff field, if UserName is null, then returning the service Description.
  || 03/05/11 GWG 10.5.4.2 Added To Do Count
  || 03/28/11 GHL 10.5.4.3 (107252) Added TaskUserKey to help when UserKey is null, added ServiceKey
  || 07/27/11 RLB 10.5.4.6 (114500) Added Line Number
  || 01/09/12 MFT 10.5.5.2 (112748) Added Hide from Client
  || 01/09/12 MFT 10.5.5.2 (111249) Added ptu subquery for Actual Hours
  || 01/20/12 GWG 10.5.5.2 Fixed the actual hours query
  || 10/26/10 RLB 10.5.5.4 (65197) Added Billing Contact
  || 04/20/12 CRG 10.5.5.5 (140685) Now defaulting the SegmentColor based on the TaskStatus if there is not Segment, or the Segment does not have a color defined
  || 04/25/12 GHL 10.5.5.5 Added GLCompanyKey for map/restrict
  || 05/22/12 GHL 10.5.5.6 (143650) Added ProjectKey when calculating ActualHours. This way the index IX_tTime10 is used in the proper order
  ||                        query went from 2min to 10sec 
  || 07/26/12 GWG 10.5.5.8 added 1 2 3 to priority label so it sorts in order
  || 09/02/12 GWG 10.5.5.9 Actual Hours are filtered to the Person as well as task now
  || 10/09/12 WDF 10.5.6.1 (151302) Added KeyPersons(1-6) to output
  || 10/10/12 WDF 10.5.6.1 (152558) Added Billing Method
  || 11/07/12 MFT 10.5.6.2 Added To Do Items and modified Open To Do Items to check AssignedUserKey
  || 11/26/12 WDF 10.5.6.2 (152986) Added Assigned Staff Department and Office
  || 06/27/13 RLB 10.5.6.9 Enhancement added DisplayName
  || 07/9/13  GWG 10.5.6.9 Added in an or condition so null services are counted on hours
  || 11/04/13 WDF 10.5.7.4 (193655) Added Summary Task fields
  || 11/15/13 RLB 10.5.7.4 (191407) Added Yes OR No for tax 1 and 2
  || 07/01/14 QMD 10.5.8.1 (221006) ProjectFullName, FormattedName and TaskHours
  || 01/19/15 WDF 10.5.8.8 (242835) Added ISNULL to percentage fields
  || 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
  || 09/03/15 WDF 10.5.9.5 (269154) [Assigned Role] renamed to [Assigned Service] which was missed during Issue #185818, Release 10.5.7.1
  || 10/15/15 GWG 10.5.9.7 Added UserChangedDate
  || 05/20/16 GWG 10.6.0.4 Only count root activities for todos
  || 05/12/18 GWG 18.5		Added assignment status
  || 07/02/18 GAR 18.7.0.0 (408654) Added Description of Assignment (ADescription) - can be found in the new schedule in the assignment
  || 07/18/18 RLS 18.8.0.0 (408867) Added Title and Default Service Description
  || 11/05/18 RLS 18.9.3   (428022) Use tu.APlanStart and tu.APlanComplete if they''re populated
  || 01/03/19 RLS 19.1.0.0 (437795) Added [Constraint]
  || 07/29/19 RLB 19.0.8.0 (470152) Added Project Manager
  || 09/09/19 AMP 19.1.0.0 (476313) Added Traffic Comments (same as Description of Assignment ADescription) 
  || 09/10/19 GAR 19.1.0.0 (477645) Added Task Status Color
  || 09/20/19 GAR 19.1.0.0 (479427) Added Last Task Due Date
  || 01/14/20 RLB 20.0.2.0 (494049) Added My Superviser
  || 01/16/20 GAR 20.0.2.0 (488883) Added Project Client Notes
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 08/09/21 MCM 21.09    (566488) Added CampaignID, Campaign Segment Name, task billing item
  || 08/17/21 MCM 21.09    (568456) Fix issue with how we''re joining the campaign segments
  || 09/03/21 RLS 21.0.9.0 (569012) Added [Task Status Name]
  || 07/18/22 GAR 22.08.14 (604336) Added [Client Company Type]
  || 08/05/22 GAR 22.09.18 (607739) Added Campaign Segment Start Date and Due Date
  || 11/28/22 GAR 22.12.18 (619862) Added Team Name
  || 04/25/23 RLB 23.05.14 (623383) Added new col ADescriptionLastModified as Traffic Comment Date Updated
  || 05/08/23 CRG 23.06.18 (604775) Now using tTaskPriority
  || 06/07/23 RLS 23.07.16 (636332) Added [Opportunity Stage] and [Opportunity Status]
  || 07/21/23 AMP 23.09.17 (646689) Added [Next Steps]
  || 07/31/23 CRG 23.08.20 (604775) Removed DisplayOrder from Assignment Priority so it would match the lookup values for filtering
  || 08/11/23 RLB 23.09.17 (648008) added project type color, Assigned Depart, Office, service colors and timeline Segment color
  || 11/16/23 RLS 23.11.19 (653825) Change t.HideFromClient to YES/NO
  || 01/16/23 RLB 24.02.18 (661710) added Predecessor and Successor
  || 03/15/24 GAR 23.04.14 (666856) Added [Task Line Number]
  || 05/09/24 RLS 24.06.16 (668311) Added [Campaign End Date] and [Campaign End Date]
  || 10/28/24 GAR 24.11.17 (685861) Added [Exclude From Status]
  || 02/28/25 CRG 25.03.16 (695455) Added [Manually Adjusted Buckets]
  || 03/27/25 RLS 25.04.20 (698104) Removed [Deliverable Name] and the join from tReviewDeliverable to tTaskUser since tTaskUser.DeliverableKey is never populated. See issue. Mike W is aware of the issue of removing a field from a view.
  || 01/29/26 RLS 26.02.15 (719979) Added [Billing Group] and [Non Billable Project]
  || 05/04/26 GAR 26.06.14 (727581) Added [Project Settings Date Updated]
  || 05/05/26 CRG 26.06.14 (727946) Removed restriction that limited it to just detail tasks
*/
Select
	 p.CompanyKey
	,p.GLCompanyKey
	,p.ProjectKey
	,p.CustomFieldKey
	,t.TaskKey
	,CAST(t.TaskKey as varchar) + ''_'' + CAST(tu.UserKey as varchar) as TaskUserKey
	,tu.TaskUserKey as TaskUserKeyPK
	,CASE 
		WHEN ts.SegmentColor IS NOT NULL THEN ts.SegmentColor
		ELSE 
			CASE t.TaskStatus
				WHEN 1 THEN 65280 --Green
				WHEN 2 THEN 16776960 --Yellow
				WHEN 3 THEN 16711680 --Red
			END
	END AS SegmentColor
	,p.ProjectNumber 
	,p.ProjectName
	,t.TaskID
	,t.TaskName	
    ,st.TaskID AS [SummaryTaskID] 
    ,st.TaskName AS [SummaryTaskName] 
    ,ISNULL(st.TaskID, '''') + ''-'' + ISNULL(st.TaskName, '''') AS [SummaryTask]
	,ts.SegmentName as [Timeline Segment]
	,ts.SegmentColor as [Timeline Segment Color]
	,ISNULL(t.TimelineSegmentDisplayName, ts.DisplayName) as [DisplayName]
	,taun.UserName
	,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber as [Project Number]
	,Case p.Closed When 1 then ''YES'' else ''NO'' end as [Project Closed]
	,cl.CompanyName as [Client Name]
	,cl.CustomerID as [Client ID]
	,pc.CompanyName as [Parent Company]
	,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]
	,cd.DivisionName as [Client Division]
	,cd.DivisionID as [Client Division ID]
	,cpr.ProductName as [Client Product]
	,cpr.ProductID as [Client Product ID]
	,p.StatusNotes as [Project Status Note]
	,p.DetailedNotes as [Project Status Description]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project Due Date]
	,dbo.fFormatDateNoTime(p.CreatedDate) as [Project Created Date]
 	,Case p.BillingMethod
		When 1 then ''Time and Materials''
		When 2 then ''Fix Fee''
		When 3 then ''Retainer''
		end as [Billing Method]
	,LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Client Primary Contact]
	,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Billing Contact]
	,LTRIM(RTRIM(ISNULL(kp1.FirstName + '' '','''')  + ISNULL(kp1.LastName,''''))) AS [Key Person 1]
	,LTRIM(RTRIM(ISNULL(kp2.FirstName + '' '','''')  + ISNULL(kp2.LastName,''''))) AS [Key Person 2]
	,LTRIM(RTRIM(ISNULL(kp3.FirstName + '' '','''')  + ISNULL(kp3.LastName,''''))) AS [Key Person 3]
	,LTRIM(RTRIM(ISNULL(kp4.FirstName + '' '','''')  + ISNULL(kp4.LastName,''''))) AS [Key Person 4]
	,LTRIM(RTRIM(ISNULL(kp5.FirstName + '' '','''')  + ISNULL(kp5.LastName,''''))) AS [Key Person 5]
	,LTRIM(RTRIM(ISNULL(kp6.FirstName + '' '','''')  + ISNULL(kp6.LastName,''''))) AS [Key Person 6]
	,cp.CampaignName as [Campaign Name]
	,cp.CampaignID as [Campaign ID]
	,cp.StartDate as [Campaign Start Date]
	,cp.EndDate as [Campaign End Date]
	,cs.SegmentName as [Segment Name]
	,cs.PlanStart as [Campaign Segment Start Date]
	,cs.PlanComplete as [Campaign Segment Due Date]
	,o.OfficeName as [Project Office]
	,t.TaskID as [Task ID]
	,t.TaskName as [Task Name]
	,t.TaskStatus
	,t.TaskType
	,t.ScheduleTask
	,t.PlanStart
	,t.PlanComplete
	,ISNULL(t.PercComp, 0) as PercComp
	,t.ScheduleNote
	,p.ProjectNumber + '' - '' + p.ProjectName  as ProjectFullName
	,ISNULL(t.TaskID + ''-'', '''') + t.TaskName as FormattedName 
	,tu.Hours as TaskHours
	,t.Description as [Task Description]
	,Case t.Taxable When 1 then ''YES'' else ''NO'' end as [Task Taxable]
	,Case t.Taxable2 When 1 then ''YES'' else ''NO'' end as [Task Taxable 2]
	,t.PlanStart as [Task Plan Start Date]
	,t.PlanComplete as [Task Plan Completion Date]
	,t.ActStart as [Task Actual Start Date]
	,t.ActComplete as [Task Actual Completion Date]
	,ISNULL(t.PercComp, 0) as [Task Percentage Complete]
	,t.BaseStart as [Task Baseline Start Date]
	,t.BaseComplete as [Task Baseline Completion Date]
	,Case t.MoneyTask When 1 then ''YES'' else ''NO'' end as [Track Budgets]
	,Case t.ScheduleTask When 1 then ''YES'' else ''NO'' end as [Track Schedules]
	,t.EstHours as [Original Budget Hours]
	,t.EstLabor as [Original Budget Labor]
	,t.BudgetExpenses as [Original Budget Net Expense]
	,t.EstExpenses as [Original Budget Gross Expense]
	,t.ApprovedCOHours as [Approved Change Order Hours]
	,t.ApprovedCOLabor as [Approved Change Order Labor]
	,t.ApprovedCOExpense as [Approved Change Order Gross Expense]
	,t.DueBy as [Due By]
	,t.AssignedNames as [Assigned People]
	,t.UserChangedDate as [Date Task Assigned]
	,CAST(t.Description as varchar (4000)) as [Description of Work]
	,tu.ActStart as [Assignment Actual Start Date]
	,tu.ActComplete as [Assignment Actual Completion Date]
	,ISNULL(tu.APlanStart, t.PlanStart) as [Assignment Plan Start Date]
	,ISNULL(tu.APlanComplete, t.PlanComplete) as [Assignment Plan Completion Date]
	,t.PlanDuration as [Assignment Duration]
	,ISNULL(tu.PercComp, 0) as [Assignment Percentage Complete]
	,t.Comments as [Assignment Comments]
	,ISNULL(tp.PriorityName, '''') AS [Assignment Priority]
	,Case t.PredecessorsComplete When 1 then ''YES'' else ''NO'' end as [Predecessors Completed]
	,Case tu.ReviewedByTraffic When 1 then ''YES'' else ''NO'' end as [Traffic Review Complete]
	,tu.ReviewedByDate as [Traffic Review Date]
	,tr.UserName as [Traffic Review By]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
    ,taun.UserName as [Assigned Staff]
	,dpt.DepartmentName as [Assigned Staff Department]
	,dpt.DepartmentKey
	,dpt.DepartmentColor as [Assigned Staff Department Color]
	,tof.OfficeName as [Assigned Staff Office]
	,tof.OfficeKey
	,tof.OfficeColor as  [Assigned Staff Office Color]
	,tas.Description as [Assigned Service]
	,tas.ServiceColor as [Assigned Service Color]
	,tu.UserKey
	,tu.ServiceKey
	--for backward compatability with user''s saved listings
	,ISNULL(tu.PercComp, 0) as [Assigned Percentage of Work]
	,t.TaskName  as [Assignment Subject]
	,t.ProjectOrder as [Line Number]
	,tu.Hours as [Allocated Hours]
	,tat.TaskAssignmentType as [Task Type]
	,tu.CompletedByDate as [Time Completed]
	,LTRIM(RTRIM(ISNULL(tsu.FirstName + '' '','''')  + ISNULL(tsu.LastName,''''))) AS [Time Completed By]
	,taun.Title as [Title]
	,taun.Description as [Default Service]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,cla.ClassID as [Class ID]
	,cla.ClassName as [Class Name]
	,o.OfficeID as [Office ID]
	,CAST(ISNULL(tp.DisplayOrder, '''') as varchar) + '' - '' + ISNULL(tp.PriorityName, '''') AS [Task Priority]
	,0 AS ASC_Selected
	,t.PlanDuration
	,case t.HideFromClient WHEN 1 THEN ''YES'' Else ''NO'' END as [Hide from Client]
	,tus.StatusName as [Assignment Status]
    ,ISNULL((
		Select Sum(ActualHours) from tTime (nolock)
		Where p.ProjectKey = tTime.ProjectKey -- uses index IX_tTime10 in proper order, i.e. ProjectKey first
		and t.TaskKey = ISNULL(tTime.DetailTaskKey, tTime.TaskKey)
		and tu.UserKey = tTime.UserKey
		and (ISNULL(pr.ShowActualHours, 0) = 1 OR tu.ServiceKey is null OR tu.ServiceKey = tTime.ServiceKey)
		), 0)
		As [Actual Hours]
	,(SELECT COUNT(*) FROM tActivity a (nolock) WHERE a.ActivityEntity = ''ToDo'' AND ParentActivityKey = 0 AND a.TaskKey = t.TaskKey AND (a.AssignedUserKey = tu.UserKey OR a.AssignedUserKey IS NULL)) AS [To Do Items]
	,(SELECT COUNT(*) FROM tActivity a (nolock) WHERE a.ActivityEntity = ''ToDo'' AND ParentActivityKey = 0 AND a.TaskKey = t.TaskKey AND (a.AssignedUserKey = tu.UserKey OR a.AssignedUserKey IS NULL) AND a.Completed = 0) AS [Open To Do Items]
	,tu.ADescription as [Description of Assignment]
	,tu.ADescription as [Traffic Comments]
	,tu.ADescriptionLastModified as [Traffic Comment Date Updated]
	,Case t.TaskConstraint
		When 0 then ''As Soon As Possible''
		When 1 then ''Must Start On''
		When 2 then ''Must Finish On''
		When 3 then ''Finish No Earlier Than''
		When 4 then ''Finish No Later Than''
		When 5 then ''Start No Earlier Than''
		When 6 then ''Start No Later Than''
		When 7 then ''Duration of Project''
		else ''''
	end as [Constraint]
	,Case t.TaskStatus
		When 1 then ''#7bb724''
		When 2 then ''#f9c301''
		When 3 then ''#d0333e''
		else ''red''
	end as [Task Status Color]
	,Case t.TaskStatus
		When 1 then ''Green''
		When 2 then ''Yellow''
		When 3 then ''Red''
		else ''Red''
	end as [Task Status Name]
	,(SELECT MAX(t.PlanComplete) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as [Last Task Due Date]
	,msvn.UserName as [My Supervisor]
	,p.ClientNotes as [Project Client Notes]
	,wt.WorkTypeID + '' - '' + wt.WorkTypeName [Task Billing Item]
	,ct.CompanyTypeName AS [Client Company Type]
	,team.TeamName as [Team Name]
	,lstage.LeadStageName as [Opportunity Stage]
	,lstatus.LeadStatusName as [Opportunity Status]
	,p.DetailedNotes as [Next Steps]
	,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')
		FROM
			tTaskPredecessor tpi (nolock)
			INNER JOIN tTask ti (nolock) ON tpi.PredecessorKey = ti.TaskKey
		WHERE tpi.TaskKey = t.TaskKey
		ORDER BY ti.TaskID
		   FOR XML PATH('''')) ,1,1,''''))), '''') AS [Predecessor]
	,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')
		FROM
			tTaskPredecessor tpi (nolock)
			INNER JOIN tTask ti (nolock) ON tpi.TaskKey = ti.TaskKey
		WHERE tpi.PredecessorKey = t.TaskKey
		ORDER BY ti.TaskID
		   FOR XML PATH('''')) ,1,1,''''))), '''') AS [Successor]
	,t.ProjectOrder as [Task Line Number]
	,CASE ISNULL(t.ExcludeFromStatus, 0) WHEN 0 THEN ''NO'' Else ''YES'' END as [Exclude From Status]
	,Case tu.ManualAdjustment When 1 then ''YES'' else ''NO'' end as [Manually Adjusted Buckets]
	,bg.BillingGroupCode as [Billing Group]
	,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
	,p.DateUpdated as [Project Settings Date Updated] 
From
	tProject p (nolock)
	inner join tTask t with  (nolock, index=tTask51) on p.ProjectKey = t.ProjectKey
	inner join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey
	inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	inner join tPreference pr (nolock) on p.CompanyKey = pr.CompanyKey
	left outer join tTask st (NOLOCK) on t.SummaryTaskKey = st.TaskKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	left outer join tTimelineSegment ts (nolock) on t.TimelineSegmentKey = ts.TimelineSegmentKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
	left outer join tClientProduct cpr (nolock) on p.ClientProductKey = cpr.ClientProductKey
	left outer join tOffice o (nolock) on p.OfficeKey = o.OfficeKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey  
	left outer join vUserName tr (nolock) on t.ReviewedByKey = tr.UserKey
	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 vUserName taun (nolock) on tu.UserKey = taun.UserKey
	left outer join vUserName msvn (nolock) on taun.MySupervisorKey = msvn.UserKey
	left outer join tDepartment dpt (nolock) on taun.DepartmentKey = dpt.DepartmentKey
	left outer join tOffice tof (nolock) on taun.OfficeKey = tof.OfficeKey
	left outer join tTaskAssignmentType tat (nolock) on t.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey
	left outer join tUser tsu (nolock) on tu.CompletedByKey = tsu.UserKey
	left outer join tClass cla (nolock) on p.ClassKey = cla.ClassKey
	left outer join tGLCompany glc (nolock) on p.GLCompanyKey = glc.GLCompanyKey
	left outer join tCompany pc (nolock) on cl.ParentCompanyKey = pc.CompanyKey
	left outer join tUser u1 (nolock) on cl.PrimaryContact = u1.UserKey
	left outer join tService tas (nolock) on tu.ServiceKey = tas.ServiceKey
	left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey
	left outer join tUser kp1 (nolock) on p.KeyPeople1 = kp1.UserKey
	left outer join tUser kp2 (nolock) on p.KeyPeople2 = kp2.UserKey
	left outer join tUser kp3 (nolock) on p.KeyPeople3 = kp3.UserKey
	left outer join tUser kp4 (nolock) on p.KeyPeople4 = kp4.UserKey
	left outer join tUser kp5 (nolock) on p.KeyPeople5 = kp5.UserKey
	left outer join tUser kp6 (nolock) on p.KeyPeople6 = kp6.UserKey
	left outer join tTaskUserStatus tus (nolock) on tu.TaskUserStatusKey = tus.TaskUserStatusKey
	left outer join tWorkType wt (nolock) on t.WorkTypeKey = wt.WorkTypeKey
	left outer join tCompanyType ct (nolock) on cl.CompanyTypeKey = ct.CompanyTypeKey
	left outer join tTeam team (nolock) on p.TeamKey = team.TeamKey
	left outer join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey
	left outer JOIN tLead le (nolock) on p.LeadKey = le.LeadKey
	left outer JOIN tLeadStage lstage (nolock) on le.LeadStageKey = lstage.LeadStageKey
	left outer JOIN tLeadStatus lstatus (nolock) on le.LeadStatusKey = lstatus.LeadStatusKey
	left outer join tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey 
Where
	p.Active = 1 
And 	ISNULL(ps.OnHold, 0) = 0































'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptCashPostCheck]'
GO
IF OBJECT_ID(N'[dbo].[sptCashPostCheck]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptCashPostCheck]
	(
		@CompanyKey int
		,@CheckKey int
		,@CreateTemp int = 0	-- Can be used for testing	
	)

AS --Encrypt

/*
|| When     Who Rel     What
|| 02/26/09 GHL 10.019 Creation for cash basis posting 
|| 05/07/09 GHL 10.024 Added reading of Unapplied Account from pref
|| 07/15/11 GWG 10.546 Added a check to make sure posting date does not have a time component
|| 03/27/12 GHL 10.554 Changes for ICT
|| 07/03/12 GHL 10.557 Added call to spGLPostICTCreateDTDF for Inter Company Transactions
|| 07/03/12 GHL 10.557 Added tCashTransaction.ICTGLCompanyKey
|| 08/07/13 GHL 10.571 Added Multi Currency stuff
||                     This does not create a realized gain like sptCashPostInvoice
||                     The exchange rate from the check just propagates to the invoices
|| 03/15/17 GHL 10.614 (336444) If opening transaction = 1, do not post cash. For this issue, I had to repost vouchers
||                     which caused the associated payments to be reposted as well, only do this if OpeningTransaction = 0
|| 10/31/19 GHL 19.110 (455860) Allow to receive with a bank account of a different currency
|| 09/23/20 GHL 20.100 (451878) Changes for GL companies diff currency
|| 11/09/20 GHL 20.120 (516678) Added support for bank fees
|| 05/27/26 MFT 26.060 (729536) Changed SP execs to name/value; Don''t reset @DepositKey on each exec, just push explicit NULL
*/
	
	IF @CreateTemp = 1
	BEGIN
	
		-- This table will track of which cash basis transactions are not valid anymore
		-- Just to get the same Entity''s collation
		SELECT Entity, EntityKey, 1 AS Unpost INTO #tCashTransactionUnpost 
		FROM tCashTransaction (NOLOCK) WHERE 1 = 2 
		
		CREATE TABLE #tCashTransaction (
			UIDCashHistoryKey uniqueidentifier null,
			
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL, 
			ICTGLCompanyKey int null,

			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,

			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null, 

			ICTExchangeRate decimal(24,7) null, -- this is to be used by spGLPostICTCreateCurrencyDTDF
			ICTGLCExchangeRate decimal(24,7) null,	-- contains the current rate on payments instead of rate to reverse out

			-- Application fields
			AEntity varchar (50) NULL ,
			AEntityKey int NULL ,
			AReference varchar (100) NULL ,
			AEntity2 varchar (50) NULL ,
			AEntity2Key int NULL ,
			AReference2 varchar (100) NULL ,
			AAmount MONEY NULL,
			LineAmount MONEY NULL,
			CashTransactionLineKey INT NULL

			-- our work space
			,GLValid int null
			,GLAccountErrRet int null
			,GPFlag int null -- General purpose flag
			
			,UpdateTranLineKey int null
			)	 	
		END

-- Register all constants
DECLARE @kErrInvalidGLAcct INT					SELECT @kErrInvalidGLAcct = -1
DECLARE @kErrInvalidLineAcct INT				SELECT @kErrInvalidLineAcct = -2
DECLARE @kErrInvalidPrePayAcct INT				SELECT @kErrInvalidPrePayAcct = -3
DECLARE @kErrInvalidFeeAcct INT					SELECT @kErrInvalidFeeAcct = -4

DECLARE @kErrGLClosedDate INT					SELECT @kErrGLClosedDate = -100
DECLARE @kErrPosted INT							SELECT @kErrPosted = -101
DECLARE @kErrBalance INT						SELECT @kErrBalance = -102
DECLARE @kErrICTBlankGLAccount INT				SELECT @kErrICTBlankGLAccount = -103
DECLARE @kErrInvoiceOpeningTransaction INT      SELECT @kErrInvoiceOpeningTransaction = -104
DECLARE @kErrMissingDeptOffice INT				SELECT @kErrMissingDeptOffice = -105
DECLARE @kErrUnexpected INT						SELECT @kErrUnexpected = -1000

-- Also declared in spGLPostInvoice
DECLARE @kSectionHeader int						SELECT @kSectionHeader = 1
DECLARE @kSectionLine int						SELECT @kSectionLine = 2
DECLARE @kSectionPrepayments int				SELECT @kSectionPrepayments = 3
DECLARE @kSectionPrebillAccruals int			SELECT @kSectionPrebillAccruals = 4
DECLARE @kSectionSalesTax int					SELECT @kSectionSalesTax = 5
DECLARE @kSectionICT int						SELECT @kSectionICT = 8
DECLARE @kSectionMCRounding int					SELECT @kSectionMCRounding = 9
DECLARE @kSectionMCGain int						SELECT @kSectionMCGain = 10

-- Vars for tPreference
Declare @PostToGL tinyint
Declare @RequireAccounts tinyint
Declare @RequireDepartment tinyint
Declare @RequireOffice tinyint
Declare @GLClosedDate smalldatetime
Declare @UnappliedCashAccountKey int
		,@MultiCurrency tinyint
		,@RoundingDiffAccountKey int -- for rounding errors
		,@RealizedGainAccountKey int -- for realized gains after applications of checks to invoices, invoices to invoices etc..  
		,@FeeAccountKey int

-- Vars for check/receipt info
Declare @CashAccountKey int
Declare @PrepayAccountKey int
Declare @CheckAmount money
Declare @AppliedAmount money
Declare @PrepayAmount money
Declare @ReferenceNumber varchar(100)
Declare @Amount money
Declare @Posted tinyint
Declare @OpeningTransaction tinyint
Declare @FeeAmount money
Declare @FeeDepartmentKey int
Declare @FeeOfficeKey int

-- Vars for the payments in other currencies
Declare @CurrencyID varchar(10)
Declare @ExchangeRate decimal(24,7)
Declare @CashAmount money
Declare @CashCurrencyID varchar(10)
Declare @CashExchangeRate decimal(24,7)

-- Vars for GL companies with different currencies
Declare @GLCCurrencyID varchar(10)				-- Currency of the GL company
Declare @GLCExchangeRate decimal(24,7)			-- Exchange rate to convert payment amounts to currency of the GL company 
Declare @CashGLCExchangeRate decimal(24,7)		-- Exchange rate to convert CASH amounts to currency of the GL company


-- Vars for GL tran
DECLARE @TransactionDate smalldatetime
		,@Entity VARCHAR(50)
		,@EntityKey INT
		,@Reference VARCHAR(100)
		,@GLAccountKey INT
		,@ClassKey int
		,@Memo varchar(500)
		,@PostSide char(1)
		,@ClientKey int
		,@ProjectKey int
		,@SourceCompanyKey INT
		,@DepositKey INT
		,@GLCompanyKey INT
		,@OfficeKey INT
		,@DepartmentKey INT
		,@DetailLineKey INT
		,@Section INT
		,@GLAccountErrRet INT
		,@RetVal INT
		,@TransactionCount INT
 		 
	Select
		@RequireAccounts = ISNULL(RequireGLAccounts, 0)
		,@RequireDepartment = ISNULL(RequireDepartment,0)
		,@RequireOffice = ISNULL(RequireOffice,0)
		,@PostToGL = ISNULL(PostToGL, 0)
		,@GLClosedDate = GLClosedDate
		,@UnappliedCashAccountKey = isnull(UnappliedCashAccountKey, 0) -- for conversion mainly
		,@MultiCurrency = ISNULL(MultiCurrency, 0)
		,@RoundingDiffAccountKey = RoundingDiffAccountKey
		,@RealizedGainAccountKey = RealizedGainAccountKey  
		,@FeeAccountKey = FeeAccountKey
	From
		tPreference (nolock)
	Where
		CompanyKey = @CompanyKey
		
	Select
		@GLCompanyKey = GLCompanyKey
		,@ClientKey = ClientKey
		,@CheckAmount = ISNULL(CheckAmount, 0)
		,@TransactionDate = dbo.fFormatDateNoTime(PostingDate)
		,@ReferenceNumber = ReferenceNumber
		,@CashAccountKey = CashAccountKey
		,@PrepayAccountKey = ISNULL(PrepayAccountKey, 0)
		,@ClassKey = ClassKey
		,@DepositKey = DepositKey
		,@Posted = Posted
		,@ProjectKey = NULL
		,@OpeningTransaction = ISNULL(OpeningTransaction, 0)
		,@CurrencyID = CurrencyID
		,@ExchangeRate = isnull(ExchangeRate, 1)
		,@CashCurrencyID = CashCurrencyID
		,@CashExchangeRate = isnull(CashExchangeRate, 1)
		,@CashAmount = CashAmount

		-- for the GL companies with different currencies
		,@GLCCurrencyID = GLCCurrencyID
		,@GLCExchangeRate = isnull(GLCExchangeRate, 1)
		,@CashGLCExchangeRate = isnull(CashGLCExchangeRate, 1)

		,@FeeAmount = isnull(FeeAmount,0)
		,@FeeDepartmentKey = FeeDepartmentKey
		,@FeeOfficeKey = FeeOfficeKey
	from tCheck (nolock)
	Where CheckKey = @CheckKey

	-- No posting if this is opening transaction
	if isnull(@OpeningTransaction,0) = 1
		return 1

	-- if the GL company currency is null, the currency is the home currency 
	if @GLCCurrencyID is null
		select @GLCExchangeRate = @ExchangeRate
		      ,@CashGLCExchangeRate = @CashExchangeRate

	IF @PrepayAccountKey = 0
		SELECT @PrepayAccountKey = @UnappliedCashAccountKey
	
	Select @AppliedAmount = ISNULL(sum(Amount), 0) 
	from tCheckAppl (nolock) 
	where CheckKey = @CheckKey 
	and Prepay = 0
	Select @PrepayAmount = @CheckAmount - @AppliedAmount
		
	if @OpeningTransaction = 1
		Select @PostToGL = 0	

	-- for the bank fee expense amount, we need to test if dept and office exist 
	if @FeeAmount <> 0 and isnull(@FeeDepartmentKey,0) = 0 and @RequireDepartment = 1
		return @kErrMissingDeptOffice
	if @FeeAmount <> 0 and isnull(@FeeOfficeKey,0) = 0 and @RequireOffice = 1
		return @kErrMissingDeptOffice

	-- These should not change
	Select	@Entity = ''RECEIPT''
			,@EntityKey = @CheckKey
			,@Reference = @ReferenceNumber
			,@Memo = ''Reference # '' + @ReferenceNumber
			,@SourceCompanyKey = @ClientKey			
	-- TransactionDate, ProjectKey, GLCompanyKey, ClassKey, ClientKey already set
	
	/*
	* Insert the header Amount
	*/
	
	SELECT @PostSide = ''D''
		  ,@GLAccountKey = @CashAccountKey
		  ,@GLAccountErrRet = @kErrInvalidGLAcct 
		  ,@Amount = @CheckAmount, @Section = @kSectionHeader 
		  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

	if @CashAmount is not null and isnull(@CurrencyID, '''') != isnull(@CashCurrencyID, '''')		  		
		EXEC sptCashInsertTranTemp
			@UIDCashTransactionKey  = NULL,
			@CompanyKey             = @CompanyKey,
			@PostSide               = @PostSide,
			@TransactionDate        = @TransactionDate,
			@Entity                 = @Entity,
			@EntityKey              = @EntityKey,
			@Reference              = @Reference,
			@GLAccountKey           = @GLAccountKey,
			@Amount                 = @CashAmount,
			@ClassKey               = @ClassKey,
			@Memo                   = @Memo,
			@ClientKey              = @ClientKey,
			@ProjectKey             = @ProjectKey,
			@SourceCompanyKey       = @SourceCompanyKey,
			@DepositKey             = @DepositKey,
			@GLCompanyKey           = @GLCompanyKey,
			@OfficeKey              = @OfficeKey,
			@DepartmentKey          = @DepartmentKey,
			@DetailLineKey          = @DetailLineKey,
			@Section                = @Section,
			@GLAccountErrRet        = @GLAccountErrRet,
			@AEntity                = NULL,
			@AEntityKey             = NULL,
			@AReference             = NULL,
			@AEntity2               = NULL,
			@AEntity2Key            = NULL,
			@AReference2            = NULL,
			@AAmount                = 0,
			@LineAmount             = 0,
			@CashTransactionLineKey = NULL,
			@UpdateTranLineKey      = 0,
			@CurrencyID             = @CashCurrencyID,
			@ExchangeRate           = @CashExchangeRate
	else
		EXEC sptCashInsertTranTemp
			@UIDCashTransactionKey  = NULL,
			@CompanyKey             = @CompanyKey,
			@PostSide               = @PostSide,
			@TransactionDate        = @TransactionDate,
			@Entity                 = @Entity,
			@EntityKey              = @EntityKey,
			@Reference              = @Reference,
			@GLAccountKey           = @GLAccountKey,
			@Amount                 = @Amount,
			@ClassKey               = @ClassKey,
			@Memo                   = @Memo,
			@ClientKey              = @ClientKey,
			@ProjectKey             = @ProjectKey,
			@SourceCompanyKey       = @SourceCompanyKey,
			@DepositKey             = @DepositKey,
			@GLCompanyKey           = @GLCompanyKey,
			@OfficeKey              = @OfficeKey,
			@DepartmentKey          = @DepartmentKey,
			@DetailLineKey          = @DetailLineKey,
			@Section                = @Section,
			@GLAccountErrRet        = @GLAccountErrRet,
			@AEntity                = NULL,
			@AEntityKey             = NULL,
			@AReference             = NULL,
			@AEntity2               = NULL,
			@AEntity2Key            = NULL,
			@AReference2            = NULL,
			@AAmount                = 0,
			@LineAmount             = 0,
			@CashTransactionLineKey = NULL,
			@UpdateTranLineKey      = 0,
			@CurrencyID             = @CurrencyID,
			@ExchangeRate           = @ExchangeRate
		
	/*
	* Insert the prepayed amount if there is one
	*/
	
	if ISNULL(@PrepayAmount, 0) <> 0
	Begin
		SELECT @PostSide = ''C''
		      ,@GLAccountKey = @PrepayAccountKey
			  ,@GLAccountErrRet = @kErrInvalidPrePayAcct 
			  ,@Amount = @PrepayAmount, @Section = @kSectionHeader 
			  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

		EXEC sptCashInsertTranTemp
			@UIDCashTransactionKey  = NULL,
			@CompanyKey             = @CompanyKey,
			@PostSide               = @PostSide,
			@TransactionDate        = @TransactionDate,
			@Entity                 = @Entity,
			@EntityKey              = @EntityKey,
			@Reference              = @Reference,
			@GLAccountKey           = @GLAccountKey,
			@Amount                 = @Amount,
			@ClassKey               = @ClassKey,
			@Memo                   = @Memo,
			@ClientKey              = @ClientKey,
			@ProjectKey             = @ProjectKey,
			@SourceCompanyKey       = @SourceCompanyKey,
			@DepositKey             = NULL,
			@GLCompanyKey           = @GLCompanyKey,
			@OfficeKey              = @OfficeKey,
			@DepartmentKey          = @DepartmentKey,
			@DetailLineKey          = @DetailLineKey,
			@Section                = @Section,
			@GLAccountErrRet        = @GLAccountErrRet,
			@AEntity                = NULL,
			@AEntityKey             = NULL,
			@AReference             = NULL,
			@AEntity2               = NULL,
			@AEntity2Key            = NULL,
			@AReference2            = NULL,
			@AAmount                = 0,
			@LineAmount             = 0,
			@CashTransactionLineKey = NULL

	End
	

		/*
	* Insert the fee amount if there is one
	*/
	
	if ISNULL(@FeeAmount, 0) <> 0
	Begin
		-- This is a mini JE where we reduce the amount on the cash account and debit the bank fee expense account 
		
		-- this will reduce the cash amount
		SELECT @PostSide = ''C'' 
		  ,@GLAccountKey = @CashAccountKey
		  ,@GLAccountErrRet = @kErrInvalidPrePayAcct 
		  ,@Amount = @FeeAmount, @Section = @kSectionHeader 
		  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
		
		
		if @CashAmount is not null and isnull(@CurrencyID, '''') != isnull(@CashCurrencyID, '''')
		begin			 
			-- convert FeeAmount from amount in check currency to amount in the currency of the cash/bank account 
			-- see design doc on cash account with different currency for that conversion
			select @Amount = round((@FeeAmount * @ExchangeRate) / @CashExchangeRate, 2)
			 		
			EXEC sptCashInsertTranTemp
				@UIDCashTransactionKey  = NULL,
				@CompanyKey             = @CompanyKey,
				@PostSide               = @PostSide,
				@TransactionDate        = @TransactionDate,
				@Entity                 = @Entity,
				@EntityKey              = @EntityKey,
				@Reference              = @Reference,
				@GLAccountKey           = @GLAccountKey,
				@Amount                 = @Amount,
				@ClassKey               = @ClassKey,
				@Memo                   = @Memo,
				@ClientKey              = @ClientKey,
				@ProjectKey             = @ProjectKey,
				@SourceCompanyKey       = @SourceCompanyKey,
				@DepositKey             = @DepositKey,
				@GLCompanyKey           = @GLCompanyKey,
				@OfficeKey              = @OfficeKey,
				@DepartmentKey          = @DepartmentKey,
				@DetailLineKey          = @DetailLineKey,
				@Section                = @Section,
				@GLAccountErrRet        = @GLAccountErrRet,
				@AEntity                = NULL,
				@AEntityKey             = NULL,
				@AReference             = NULL,
				@AEntity2               = NULL,
				@AEntity2Key            = NULL,
				@AReference2            = NULL,
				@AAmount                = 0,
				@LineAmount             = 0,
				@CashTransactionLineKey = NULL,
				@UpdateTranLineKey      = 0,
				@CurrencyID             = @CashCurrencyID,
				@ExchangeRate           = @CashExchangeRate
		end
		else
			EXEC sptCashInsertTranTemp
				@UIDCashTransactionKey  = NULL,
				@CompanyKey             = @CompanyKey,
				@PostSide               = @PostSide,
				@TransactionDate        = @TransactionDate,
				@Entity                 = @Entity,
				@EntityKey              = @EntityKey,
				@Reference              = @Reference,
				@GLAccountKey           = @GLAccountKey,
				@Amount                 = @Amount,
				@ClassKey               = @ClassKey,
				@Memo                   = @Memo,
				@ClientKey              = @ClientKey,
				@ProjectKey             = @ProjectKey,
				@SourceCompanyKey       = @SourceCompanyKey,
				@DepositKey             = @DepositKey,
				@GLCompanyKey           = @GLCompanyKey,
				@OfficeKey              = @OfficeKey,
				@DepartmentKey          = @DepartmentKey,
				@DetailLineKey          = @DetailLineKey,
				@Section                = @Section,
				@GLAccountErrRet        = @GLAccountErrRet,
				@AEntity                = NULL,
				@AEntityKey             = NULL,
				@AReference             = NULL,
				@AEntity2               = NULL,
				@AEntity2Key            = NULL,
				@AReference2            = NULL,
				@AAmount                = 0,
				@LineAmount             = 0,
				@CashTransactionLineKey = NULL,
				@UpdateTranLineKey      = 0,
				@CurrencyID             = @CurrencyID,
				@ExchangeRate           = @ExchangeRate

		-- now debit the Fee account key
		SELECT @PostSide = ''D''
		      ,@GLAccountKey = @FeeAccountKey
			  ,@GLAccountErrRet = @kErrInvalidFeeAcct 
			  ,@Amount = @FeeAmount, @Section = @kSectionHeader  
			  ,@OfficeKey = @FeeOfficeKey, @DepartmentKey = @FeeDepartmentKey, @DetailLineKey = NULL

		EXEC sptCashInsertTranTemp
			@UIDCashTransactionKey  = NULL,
			@CompanyKey             = @CompanyKey,
			@PostSide               = @PostSide,
			@TransactionDate        = @TransactionDate,
			@Entity                 = @Entity,
			@EntityKey              = @EntityKey,
			@Reference              = @Reference,
			@GLAccountKey           = @GLAccountKey,
			@Amount                 = @Amount,
			@ClassKey               = @ClassKey,
			@Memo                   = @Memo,
			@ClientKey              = @ClientKey,
			@ProjectKey             = @ProjectKey,
			@SourceCompanyKey       = @SourceCompanyKey,
			@DepositKey             = NULL,
			@GLCompanyKey           = @GLCompanyKey,
			@OfficeKey              = @OfficeKey,
			@DepartmentKey          = @DepartmentKey,
			@DetailLineKey          = @DetailLineKey,
			@Section                = @Section,
			@GLAccountErrRet        = @GLAccountErrRet,
			@AEntity                = NULL,
			@AEntityKey             = NULL,
			@AReference             = NULL,
			@AEntity2               = NULL,
			@AEntity2Key            = NULL,
			@AReference2            = NULL,
			@AAmount                = 0,
			@LineAmount             = 0,
			@CashTransactionLineKey = NULL

	End


	/*
	* Insert the lines
	*/
	
	SELECT @PostSide = ''C'', @Section = @kSectionLine, @GLAccountErrRet = @kErrInvalidGLAcct, @DepositKey = NULL 
	
	-- credit each line tCheckAppl where InvoiceKey is null and prepay = 0
	INSERT #tCashTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,
		AEntity,AEntityKey,AReference,AEntity2,AEntity2Key,AReference2,AAmount,LineAmount,CashTransactionLineKey
		)
	
	SELECT @CompanyKey, @TransactionDate, @Entity, @EntityKey, @Reference,
		SalesAccountKey, 0, ISNULL(Amount, 0), ClassKey, @Memo,
		@ClientKey, @ProjectKey, @SourceCompanyKey, @DepositKey, @PostSide

		-- ICT
		, case when isnull(TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else TargetGLCompanyKey end
		
		, OfficeKey, DepartmentKey, CheckApplKey, @kSectionLine ,@GLAccountErrRet
		,NULL, NULL, NULL, NULL,NULL, NULL, 0, 0, NULL
	From  tCheckAppl (nolock)
	Where CheckKey = @CheckKey 
	and   InvoiceKey is null
	and Prepay = 0
		
	/*
	if the invoice is not posted consider it does not exist yet
	Things could go wrong during the posting of the invoice
	so post the receipt against the unapplied account
	when posting the invoice, repost the check
	*/
	
	-- credit each line tCheckAppl where InvoiceKey is not null and prepay = 0 and invoice not posted 
	-- against unapplied account
	-- same if invoice is posted but posting date > check posting date
	-- Talked to Greg 02/23/2009. We should use the AR account on the invoice
	INSERT #tCashTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,
		AEntity,AEntityKey,AReference,AEntity2,AEntity2Key,AReference2,AAmount,LineAmount,CashTransactionLineKey
		)
	
	SELECT @CompanyKey, @TransactionDate, @Entity, @EntityKey, @Reference,
		i.ARAccountKey, 0, ISNULL(ca.Amount, 0), ca.ClassKey, @Memo,
		@ClientKey, @ProjectKey, @SourceCompanyKey, @DepositKey, @PostSide

		-- ICT
		, case when isnull(ca.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else ca.TargetGLCompanyKey end
		
		, ca.OfficeKey, ca.DepartmentKey, ca.CheckApplKey, @kSectionLine ,@GLAccountErrRet
		,NULL, NULL, NULL, NULL,NULL, NULL, 0, 0, NULL
	From  tCheckAppl ca (nolock)
		inner join tInvoice i (nolock) on ca.InvoiceKey = i.InvoiceKey
	Where ca.CheckKey = @CheckKey 
	--and   ca.InvoiceKey is not null
	and ca.Prepay = 0
	and (	
		-- Unposted AND not in the process of being posted to ACCRUAL
		(i.Posted = 0 AND i.InvoiceKey NOT IN (SELECT EntityKey FROM #tCashQueue 
			WHERE Entity = ''INVOICE'' AND PostingOrder = 1 AND Action=0))
		-- Or posted in the future  
		OR (i.Posted = 1 AND i.PostingDate > @TransactionDate)
		-- Or we are in the process from unposting from ACCRUAL
		OR	i.InvoiceKey IN (SELECT EntityKey FROM #tCashQueue 
			WHERE Entity = ''INVOICE'' AND PostingOrder = 1 AND Action=1)
		
	) 
	 
	--select * from #tCashTransaction
	--SELECT * FROM #tCashQueue
	
	-- if an invoice is on same posting date as a check, we can consider it like before the check
	-- similar to the convention of the invoices linked to an Advance Bill
 	
 	-- now process the posted invoices
	DECLARE @InvoiceKey INT
	DECLARE @AdvanceBill INT
	DECLARE @IsLastApplication INT
	DECLARE @ApplyAmount MONEY
	DECLARE @CheckApplKey INT
	
	SELECT @InvoiceKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @InvoiceKey = MIN(ca.InvoiceKey)
		FROM   tCheckAppl ca (NOLOCK)
			INNER JOIN tInvoice i (NOLOCK) ON ca.InvoiceKey = i.InvoiceKey
		WHERE ca.CheckKey = @CheckKey 
		and ca.Prepay = 0
		and (i.Posted = 1
			OR
			-- Or we are in the process of posting it to Accrual
			ca.InvoiceKey IN (SELECT EntityKey FROM #tCashQueue 
				WHERE Entity = ''INVOICE'' AND PostingOrder = 1 AND Action=0)
			)	 
		AND i.PostingDate <= @TransactionDate 
		AND  ca.InvoiceKey > @InvoiceKey  
		-- And we are not in the process of unposting it from Accrual
		AND	ca.InvoiceKey NOT IN (SELECT EntityKey FROM #tCashQueue 
			WHERE Entity = ''INVOICE'' AND PostingOrder = 1 AND Action=1)
		
		--SELECT * FROM #tCashQueue
		
		IF @InvoiceKey IS NULL
			BREAK
			
		--select @InvoiceKey
			
		SELECT @CheckApplKey = CheckApplKey
			  ,@ApplyAmount = Amount
		FROM   tCheckAppl (NOLOCK)
		WHERE  CheckKey = @CheckKey
		AND    InvoiceKey = @InvoiceKey
					
		SELECT @AdvanceBill = AdvanceBill
		FROM   tInvoice (NOLOCK)
		WHERE  InvoiceKey =	@InvoiceKey
		
			
		IF @AdvanceBill = 1
		BEGIN
			-- Prevent the situation of an advance bill with a negative check
			-- and no invoices before this check
			IF NOT EXISTS (
				SELECT i.InvoiceKey
				FROM   tInvoiceAdvanceBill iab (NOLOCK)
				INNER JOIN tInvoice i (NOLOCK) ON iab.InvoiceKey = i.InvoiceKey
				WHERE  iab.AdvBillInvoiceKey = @InvoiceKey   
				-- They should be posted
				AND (i.Posted = 1
						OR
						-- Or we are in the process of posting it to Accrual
						i.InvoiceKey IN (SELECT EntityKey FROM #tCashQueue 
							WHERE Entity = ''INVOICE'' AND PostingOrder = 1 AND Action=0)
						)	 
				-- And we are not in the process of unposting it from Accrual
				AND	i.InvoiceKey NOT IN (SELECT EntityKey FROM #tCashQueue 
					WHERE Entity = ''INVOICE'' AND PostingOrder = 1 AND Action=1)		
					
				-- we consider that if the invoices have the same posting date
				-- they are BEFORE the check
				AND    i.PostingDate <= @TransactionDate  
				AND    iab.InvoiceKey <> iab.AdvBillInvoiceKey -- filter out self applications
			)
			
			SELECT @AdvanceBill = 0
		END
		
			
		IF @AdvanceBill = 0
		BEGIN
			EXEC sptCashPostCheckFillInvoice @CompanyKey, @InvoiceKey,@CheckKey, @CheckApplKey, @ApplyAmount
		END
		ELSE
		BEGIN
			--EXEC sptCashPostCheckFillAB @CompanyKey, @InvoiceKey,@CheckKey, @CheckApplKey, @ApplyAmount
			EXEC sptCashPostCheckFillABInvoice @CompanyKey, @InvoiceKey,@CheckKey, @CheckApplKey, @ApplyAmount
		END
	END 	
 	
	if @MultiCurrency = 1
	begin
		-- Make corrections before anything else because this creates the ''Added to balance cash transaction records'' record if Debits <> Credits
		EXEC sptCashPostCleanupTemp @Entity, @EntityKey, @TransactionDate 

		exec sptCashPostSetExchangeRate @Entity,@EntityKey

		-- and reload the correct currency and exch rate in case we are paying with a bank with different currency 
		if @CashAmount is not null and isnull(@CurrencyID, '''') != isnull(@CashCurrencyID, '''') 
		update #tCashTransaction
		set    #tCashTransaction.CurrencyID = @CashCurrencyID
			  ,#tCashTransaction.ExchangeRate = @CashExchangeRate
			  ,#tCashTransaction.GLCExchangeRate = @CashGLCExchangeRate
		where  #tCashTransaction.EntityKey = @EntityKey
		and    #tCashTransaction.Entity = ''RECEIPT''
		and    #tCashTransaction.Section = 1
		and    #tCashTransaction.GLAccountKey = @CashAccountKey

		-- do this after the ICT stuff now
		-- this will set HDebit/HCredit from 
		-- 0 Cash Basis, 1 Force to rounding account
		--exec spGLPostCalcRoundingDiff @CompanyKey,@Entity,@EntityKey,0,1,@GLCompanyKey,@TransactionDate,@Reference, @RoundingDiffAccountKey,@RealizedGainAccountKey 
	end

	-- Create DT and DF for ICT -- 0 Cash Basis
	--exec spGLPostICTCreateDTDF @CompanyKey,@Entity,@EntityKey,0,@GLCompanyKey,@TransactionDate,@Memo,@Reference 
	exec spGLPostICTCreateCurrencyDTDF @CompanyKey,@Entity,@EntityKey,0,@GLCompanyKey,@TransactionDate,@Memo,@Reference, @GLCExchangeRate 

	if @MultiCurrency = 1
	begin
		-- this will set HDebit/HCredit  
		-- 0 Cash Basis, 1 Force to rounding account
		exec spGLPostCalcRoundingDiff @CompanyKey,@Entity,@EntityKey,0,1,@GLCompanyKey,@TransactionDate,@Reference, @RoundingDiffAccountKey,@RealizedGainAccountKey, @GLCCurrencyID 
	end

	-- Correct and prepared data for final insert
	EXEC sptCashPostCleanupTemp @Entity, @EntityKey, @TransactionDate 


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

ALTER VIEW [dbo].[vReport_TaskAssignment]
AS

/*
|| When     Who Rel   What
|| 01/25/07 GHL 8.402 Added Timestamp related columns 
|| 04/05/07 GWG 8.5   Added predecessors completed field
|| 05/07/07 CRG 8.4.3 (8947) Added KeyPeople 1-6
|| 10/11/07 CRG 8.5   Added Class and GLCompany
|| 11/06/07 CRG 8.5   (13010) Added Row
|| 11/06/07 CRG 8.5   (12657) Added Task Priority
|| 01/29/08 GHL 8.503 (19631) Added hint with ProjectKey (tTask51 index)  to join with tTask. 
||                                    For some reason was doing a table scan
|| 04/13/09 RLB 10.0.2.3 (50834) Added where t.Tasktype=2 to just pull detail tasks.
|| 03/15/10 RLB 10.5.2.0 (76460) Add User Department
|| 10/26/10 RLB 10.5.3.7 (65197) Added Billing Contact
|| 02/11/11 RLB 10.5.4.1 (103245) Added Role to report
|| 04/07/11 RLB 10.543 (108045) Removed Project Short Name
|| 07/27/11 RLB 10.546  (111324) Added Campaign Segment
|| 11/16/11 RLB 10.550  (126449) Added Client ID
|| 02/29/12 MFT 10.553 (124662) Added Summary Task ID & Name
|| 04/24/12 GHL 10.555   Added GLCompanyKey in order to map/restrict
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey
|| 5/15/13  GWG 10.5.6.7 Added Exclude from Status
|| 08/07/13 WDF 10.571  (185818) Changed [Role] to [Service]
|| 11/15/13 RLB 10.5.7.4 (191407) Added Yes OR No for tax 1 and tax 2 on summary and detail tasks
|| 10/28/14 WDF 10.5.8.5 (226655) Added Users Default GLCompany ID/Name
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product
|| 02/10/15 GWG 10.5.8.9  Added allocated hours
|| 10/15/15 GWG 10.5.9.7 Added UserChangedDate
|| 04/24/16 GWG 10.6.0.3 Adding assigned names and department for abelson
|| 06/02/16 MCM 10.6.0.4 (302483) Adding team
|| 06/21/16 GWG 10.6.0.5 Fixed the team join
|| 02/06/17 WDF 10.6.1.3 (330555) Added [Campaign ID]
|| 01/26/18 WDF 18.2.0   (383052) Added [Project Full Name]
|| 07/02/18 GAR 18.7.0.0 (408654) Added Description of Assignment (ADescription) - can be found in the new schedule in the assignment
|| 07/18/18 RLS 18.8.0.0 (408867) Added Title and Default Service Description
|| 11/05/18 RLS 18.9.3 0 (428022) Use tu.APlanStart and tu.APlanComplete if they''re populated
|| 12/13/18 RLS 19.1.0.0 (434180) Added [Time Approver]
|| 01/25/19 GWG 19.0.2   (441880) Adding different text for the first constraint option based on direction
|| 04/18/19 RLS 19.0.5.0 (449221) Added Open To Do Items
|| 05/02/19 GAR 19.0.5.0 (457457) Added call to UDF fGetTaskUserList and fGetTaskUserInitialList to show a list of full user names and current initials
|| 05/09/19 RLS 19.0.6.0 (457996) Added [Created Date]
|| 07/01/19 RLB 19.0.7.0 (467305) Adding Hide From Client yes/no field
|| 07/29/19 RLB 19.0.8.0 (470152) Added Project Manager
|| 09/20/19 GAR 19.1.0.0 (479427) Added Last Task Due Date
|| 01/14/20 RLB 20.0.2.0 (494049) Added My Superviser
|| 01/16/20 GAR 20.0.2.0 (488883) Added Project Client Notes
|| 02/27/20 RLS 20.0.3.0 (502338) Added StartDate and EndDate
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 10/15/20 GAR 20.1.1.0 (532646) Added Campaign Active
|| 10/19/20 RLS 20.1.1.0 (526418) Added Project Description
|| 11/06/20 WDF 20.1.2.0 (536302) Modified [Assigned User] to use vUserName
|| 03/19/21 WDF 20.0.4.0 (552105) Added [Billing Method]
|| 09/30/21 RLB 21.10.21 (572763) added Allocated Gross pulled from vTaskUserHour
|| 10/01/21 RLS 21.10.21 (572091) added [Constraint Date]
|| 12/28/21 GAR 22.01.16 (581427) Added fields ''Successor'' and ''Predecessor''
|| 04/26/22 RLS 22.05.15 (594804) added [Company Type]
|| 08/05/22 GAR 22.09.18 (607739) Added Campaign Segment Start Date and Due Date
|| 11/15/22 RLS 22.12.18 (618575) Added [Parent Client Name] and [Parent Client ID]
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color and department and service
|| 04/25/23 RLS 23.05.14 (631367) Added [Project Percent Complete]
|| 04/25/23 RLB 23.05.14 (623383) Added new col ADescriptionLastModified as Traffic Comment Date Updated and Traffic comments
|| 05/08/23 CRG 23.06.18 (604775) Now using tTaskPriority
|| 06/20/23 RLS 23.07.16 (636332) Added [Opportunity Stage] and [Opportunity Status]
|| 08/11/23 RLB 23.09.17 (648008) added project type color and timeline segment color
|| 03/15/24 GAR 23.04.14 (666856) Added [Task Line Number]
|| 07/15/24 RLB 24.08.18 (676884) Added Project Team
|| 07/16/24 RLS 24.08.18 (674265) Added [Assigned User ID] and [Assigned User Email]
|| 01/29/25 RLS 25.02.16 (693216) Added [Task Status Comments]
|| 02/28/25 CRG 25.03.16 (695455) Added [Manually Adjusted Buckets]
|| 05/05/25 CRG 25.06.15 (699404) Added [Allocated Assignment Gross]
|| 09/22/25 MCM 25.10.x  (711882) Added TaskUserKey so can return it through the api
|| 10/01/25 GAR 25.10.19 (710659) Added Billable Rate
|| 01/29/26 RLS 26.02.15 (719979) Added [Billing Group] and [Non Billable Project]
|| 05/05/26 CRG 26.06.14 (727946) Removed restriction that limited it to just detail tasks
|| 05/04/26 GAR 26.06.14 (727581) Added [Project Settings Date Updated]
*/ 

Select
	 p.CompanyKey
	,p.GLCompanyKey
	,p.CustomFieldKey
	,u.CustomFieldKey as CustomFieldKey2
	,p.ProjectName as [Project Name]
	,p.ProjectNumber as [Project Number]
	,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]
	,cl.CompanyName as [Client Name]
	,cl.CustomerID as [Client ID]
	,p.ClientProjectNumber [Client Project Number]
	,ps.ProjectStatus as [Project Status]
	,pbs.ProjectBillingStatus as [Project Billing Status]
	,pt.ProjectTypeName as [Project Type]
	,pt.ProjectTypeColor as [Project Type Color]
	,p.StatusNotes as [Project Status Note]
	,p.DetailedNotes as [Project Status Description]
	,p.ProjectCloseDate as [Project Close Date]
	,Case p.Active When 1 then ''YES'' else ''NO'' end as [Active]
	,p.CreatedDate as [Created Date]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project Due Date]
	,cp.CampaignName as [Campaign Name]
	,cp.CampaignID as [Campaign ID]
	,cp.StartDate as [Campaign Start Date]
	,cp.EndDate as [Campaign End Date]
	,cs.SegmentName as [Campaign Segment]
	,cs.PlanStart as [Campaign Segment Start Date]
	,cs.PlanComplete as [Campaign Segment Due Date]
	,o.OfficeName as [Office]
	,o.OfficeColor as [Office Color]
	,t.TaskID as [Task ID]
	,t.TaskName as [Task Name]
	,t.Description as [Task Description]
	,tat.TaskAssignmentType as [Task Type]
	,Case ISNULL(t.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable]
	,Case ISNULL(t.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable 2]
	,t.PlanStart as [Plan Start Date]
	,t.PlanComplete as [Plan Completion Date]
	,Case ISNULL(t.HideFromClient, 0) When 1 then ''YES'' else ''NO'' end as [Hide From Client]
	,t.ActStart as [Actual Start Date]
	,t.ActComplete as [Actual Completion Date]
	,t.PercComp as [Percentage Complete]
	,t.BaseStart as [Baseline Start Date]
	,t.BaseComplete as [Baseline Completion Date]
	,Case t.MoneyTask When 1 then ''YES'' else ''NO'' end as [Track Budgets]
	,Case t.ScheduleTask When 1 then ''YES'' else ''NO'' end as [Track Schedules]
	,t.EstHours as [Original Budget Hours]
	,t.EstLabor as [Original Budget Labor]
	,t.BudgetExpenses as [Original Budget Net Expense]
	,t.EstExpenses as [Original Budget Gross Expense]
	,t.ApprovedCOHours as [Approved Change Order Hours]
	,t.ApprovedCOLabor as [Approved Change Order Labor]
	,t.ApprovedCOExpense as [Approved Change Order Gross Expense]
	,Case t.PredecessorsComplete When 1 then ''YES'' else ''NO'' end as [Predecessors Completed]
	,Case t.ExcludeFromStatus When 1 then ''YES'' else ''NO'' end as [Exclude From Status]
	,ISNULL((Select Sum(ActualHours * ActualRate) from tTime (nolock) Where tTime.TaskKey = t.TaskKey), 0) as [Actual Task Labor Total]
	,ISNULL((Select Sum(ActualHours) from tTime (nolock) Where tTime.TaskKey = t.TaskKey), 0) as [Actual Task Labor Hours]
	,ISNULL((Select Sum(ActualHours * ActualRate) from tTime (nolock) Where tTime.TaskKey = t.TaskKey and tTime.UserKey = tu.UserKey), 0) as [Actual Task Assignment Labor Total]
	,ISNULL((Select Sum(ActualHours) from tTime (nolock) Where tTime.TaskKey = t.TaskKey and tTime.UserKey = tu.UserKey), 0) as [Actual Task Assignment Labor Hours]
	,u.UserName AS [Assigned User]
	,u.UserID as [Assigned User ID]
	,u.Email as [Assigned User Email]
	,taun.Title [Title]
	,taun.Description [Default Service]
	,glc.GLCompanyID AS [Default GLCompany ID]
	,glc.GLCompanyID + '' - '' + glc.GLCompanyName AS [Default GLCompany Full Name]
	,ISNULL(d.DepartmentName, sd.DepartmentName) as [User Department]
	,ISNULL(d.DepartmentColor, sd.DepartmentColor) as [User Department Color]
	,t.TaskName as [Assignment Subject]
	,t.DueBy as [Due By]
	,CAST(t.Description as varchar(4000)) as [Description of Work]
	,tu.ActStart as [Assignment Actual Start Date]
	,tu.ActComplete as [Assignment Actual Completion Date]
	,ISNULL(tu.APlanStart, t.PlanStart) as [Assignment Plan Start Date]
	,ISNULL(tu.APlanComplete, t.PlanComplete) as [Assignment Plan Completion Date]
	,t.PlanDuration as [Assignment Duration]
	,t.DisplayOrder as [Assignment Work Order]
	--,t.AssignedNames as [All Assigned People]
	,dbo.fGetTaskUserInitialList(t.TaskKey) as [All Assigned People]
	,dbo.fGetTaskUserList(t.TaskKey) as [All Assigned People Full Name]
	,tu.PercComp as [Assignment Percentage Complete]
	,se.Description as [Role]
	,se.Description as [Service]
	,se.ServiceColor as [Service Color]
	,t.Comments as [Assignment Comments]
	,t.UserChangedDate as [Date Task Assigned]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Account Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
	,tu.CompletedByDate as [Time Completed]
	,tu.Hours as [Allocated Hours]
	,LTRIM(RTRIM(ISNULL(tsu.FirstName + '' '','''')  + ISNULL(tsu.LastName,''''))) AS [Time Completed By]
	,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Billing Contact]
	,u3.UserName as [Key People 1]
	,u4.UserName as [Key People 2]
	,u5.UserName as [Key People 3]
	,u6.UserName as [Key People 4]
	,u7.UserName as [Key People 5]
	,u8.UserName as [Key People 6]
	,glcp.GLCompanyID as [Company ID]
	,glcp.GLCompanyName as [Company Name]
	,cla.ClassID as [Class ID]
	,cla.ClassName as [Class Name]
	,t.ProjectOrder as Row
	,CASE t.ScheduleTask
		WHEN 1 THEN t.PlanDuration
		ELSE NULL
	END AS [Task Days]
	,tp.PriorityName AS [Task Priority]
	,st.TaskID as [Summary Task ID]
	,st.TaskName as [Summary Task Name]
	,Case ISNULL(st.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Summary Taxable]
	,Case ISNULL(st.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Summary Taxable 2]
	,Case p.BillingMethod  
		When 1 then ''Time and Materials'' 
		When 2 then ''Fixed Fee'' 
		When 3 then ''Retainer'' 
		end as [Billing Method] 
	,p.ProjectKey
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,pc.ProductID as [Client Product ID]
    ,pc.ProductName as [Client Product]
	,ts.SegmentName as [Timeline Segment]
	,ts.SegmentColor as [Timeline Segment Color]
	,team.TeamName as [Team Name]
	,tu.ADescription as [Description of Assignment]
	,tu.ADescription as [Traffic Comments]
	,tu.ADescriptionLastModified as [Traffic Comment Date Updated]
	,LTRIM(RTRIM(ISNULL(ta.FirstName + '' '','''')  + ISNULL(ta.LastName,''''))) AS [Time Approver]
	,Case t.TaskConstraint
		When 0 then case when p.ScheduleDirection = 1 then ''As Soon As Possible'' else ''As Late as Possible'' end
		When 1 then ''Must Start On''
		When 2 then ''Must Finish On''
		When 3 then ''Finish No Earlier Than''
		When 4 then ''Finish No Later Than''
		When 5 then ''Start No Earlier Than''
		When 6 then ''Start No Later Than''
		When 7 then ''Duration of Project''
		else ''''
	end as [Constraint]
	,CASE t.TaskType
        WHEN 2 THEN CASE 
                       WHEN t.TaskConstraint NOT IN (0,7) THEN t.ConstraintDate
                       ELSE NULL
                    END
        ELSE NULL
     END as [Constraint Date]
	,(SELECT COUNT(*) FROM tActivity a (nolock) WHERE a.ActivityEntity = ''ToDo'' AND ParentActivityKey = 0 AND a.TaskKey = t.TaskKey AND (a.AssignedUserKey = tu.UserKey OR a.AssignedUserKey IS NULL) AND a.Completed = 0) AS [Open To Do Items]
	,(SELECT MAX(t.PlanComplete) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as [Last Task Due Date]
	,msvn.UserName as [My Supervisor]
	,p.ClientNotes as [Project Client Notes]
	,Case cp.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active]
	,p.Description as [Project Description]
	,taskAllocated.TaskAssignedAllocated as [Allocated Gross] --uses SUM of tTaskUserHour.Hours
	,(ISNULL(tu.AHourlyRate, 0) * ISNULL(tu.Hours, 0)) as [Allocated Assignment Gross]  --uses tTaskUser.Hours
	,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')
		FROM
			tTaskPredecessor tpi (nolock)
			INNER JOIN tTask ti (nolock) ON tpi.PredecessorKey = ti.TaskKey
		WHERE tpi.TaskKey = t.TaskKey
		ORDER BY ti.TaskID
		   FOR XML PATH('''')) ,1,1,''''))), '''') AS [Predecessor]
	,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')
		FROM
			tTaskPredecessor tpi (nolock)
			INNER JOIN tTask ti (nolock) ON tpi.TaskKey = ti.TaskKey
		WHERE tpi.PredecessorKey = t.TaskKey
		ORDER BY ti.TaskID
		   FOR XML PATH('''')) ,1,1,''''))), '''') AS [Successor]
	,ISNULL(ct.CompanyTypeName, '''') as [Company Type]
	,par.CustomerID as [Parent Client ID]
	,par.CompanyName as [Parent Client Name]
	,p.PercComp as [Project Percent Complete]
	,lstage.LeadStageName as [Opportunity Stage]
	,lstatus.LeadStatusName as [Opportunity Status]
	,t.ProjectOrder as [Task Line Number]
	,Substring((Select '', ''+ UserName  AS [text()]   
            From vUserName un (nolock)
            inner join tAssignment a (nolock) on a.UserKey = un.UserKey
			Where p.ProjectKey = a.ProjectKey
            ORDER BY un.UserName
            For XML PATH ('''')
        ), 2, 4000) as [Project Team]
	,t.Comments as [Task Status Comments]
	,Case tu.ManualAdjustment When 1 then ''YES'' else ''NO'' end as [Manually Adjusted Buckets]
	,tu.TaskUserKey
	,ISNULL(CASE p.GetRateFrom
		WHEN 2 THEN p.HourlyRate 
		WHEN 3 THEN u.HourlyRate
		WHEN 4 THEN 
			(SELECT 
					CASE
						WHEN u.RateLevel = 1
							THEN se.HourlyRate1
						WHEN u.RateLevel = 2
							THEN ISNULL(se.HourlyRate2,se.HourlyRate1)
						WHEN u.RateLevel = 3
							THEN ISNULL(se.HourlyRate3,se.HourlyRate1)
						WHEN u.RateLevel = 4
							THEN ISNULL(se.HourlyRate4,se.HourlyRate1)
						WHEN u.RateLevel = 5
							THEN ISNULL(se.HourlyRate5,se.HourlyRate1)
					END)
		WHEN 5 THEN 
			(SELECT 
					CASE
						WHEN u.RateLevel = 1
							THEN (SELECT HourlyRate1 FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 2
							THEN (SELECT ISNULL(HourlyRate2,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 3
							THEN (SELECT ISNULL(HourlyRate3,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 4
							THEN (SELECT ISNULL(HourlyRate4,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 5
							THEN (SELECT ISNULL(HourlyRate5,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
					END)
		WHEN 6 THEN t.HourlyRate
		WHEN 9 THEN (SELECT HourlyRate FROM tTitle (nolock) WHERE TitleKey = u.TitleKey)
		WHEN 10 THEN 
				CASE 
					WHEN ISNULL((SELECT HourlyRate FROM tTitleRateSheetDetail (nolock) WHERE TitleRateSheetKey = p.TitleRateSheetKey),'''') = ''''
						THEN (SELECT HourlyRate FROM tTitle (nolock) WHERE TitleKey = u.TitleKey)
					ELSE
						(SELECT HourlyRate FROM tTitleRateSheetDetail (nolock) WHERE TitleRateSheetKey = p.TitleRateSheetKey)
				END
	END, u.HourlyRate) AS [Billable Rate]
	,bg.BillingGroupCode as [Billing Group]
	,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
	,p.DateUpdated as [Project Settings Date Updated] 
From
	tProject p (nolock)
	inner join tTask t with (nolock, index=tTask51) on p.ProjectKey = t.ProjectKey
	left outer join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey
	left outer join vUserName u on tu.UserKey = u.UserKey
	left outer join tUser tsu (nolock) on tu.CompletedByKey = tsu.UserKey
	inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tOffice o (nolock) on p.OfficeKey = o.OfficeKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
	left outer join tUser u2 (nolock) on p.AccountManager = u2.UserKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey
	left outer join tTaskAssignmentType tat (nolock) on t.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey
	left outer join vUserName u3 on p.KeyPeople1 = u3.UserKey
	left outer join vUserName u4 on p.KeyPeople2 = u4.UserKey
	left outer join vUserName u5 on p.KeyPeople3 = u5.UserKey
	left outer join vUserName u6 on p.KeyPeople4 = u6.UserKey
	left outer join vUserName u7 on p.KeyPeople5 = u7.UserKey
	left outer join vUserName u8 on p.KeyPeople6 = u8.UserKey
	left outer join vUserName taun (nolock) on tu.UserKey = taun.UserKey
	left outer join vUserName msvn (nolock) on u.MySupervisorKey = msvn.UserKey
	left outer join tClass cla (nolock) on p.ClassKey = cla.ClassKey
	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 tDepartment d (nolock) on u.DepartmentKey = d.DepartmentKey
	left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey
	left outer join tService se (nolock) on tu.ServiceKey = se.ServiceKey
	left outer join tDepartment sd (nolock) on se.DepartmentKey = sd.DepartmentKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey
	left outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey
	left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
    left outer join tClientProduct  pc (nolock) on p.ClientProductKey  = pc.ClientProductKey
	left outer join tTimelineSegment ts (nolock) on t.TimelineSegmentKey = ts.TimelineSegmentKey
	left outer join tTeam team on p.TeamKey =  team.TeamKey 
	left outer join tUser ta (nolock) on u.TimeApprover = ta.UserKey
	left outer join tCompanyType ct on cl.CompanyTypeKey = ct.CompanyTypeKey
	LEFT OUTER JOIN (
				select sum(ISNULL(tuh.AHourlyRate, 0) * tuh.Hours) as TaskAssignedAllocated, tuh.TaskUserKey 
				from vTaskUserHour tuh (nolock)
				group by tuh.TaskUserKey			
	) as taskAllocated on tu.TaskUserKey = taskAllocated.TaskUserKey
	left outer join tCompany par (nolock) on cl.ParentCompanyKey = par.CompanyKey
	left outer join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey
	left outer join tLead le (nolock) on p.LeadKey = le.LeadKey
	left outer join tLeadStage lstage (nolock) on le.LeadStageKey = lstage.LeadStageKey
	left outer join tLeadStatus lstatus (nolock) on le.LeadStatusKey = lstatus.LeadStatusKey
	left outer join tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey 





















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

ALTER PROCEDURE [dbo].[spGLPostCredit]
	(
	@CompanyKey int,
	@Entity varchar(25),
	@EntityKey int,
	@PostingFromRegular bit = 0  -- 0 = credit invoice being posted (existing), 1 = regular invoice being posted
	)

AS --Encrypt


/*
|| When     Who Rel     What
|| 01/16/14 GHL 10.576  Creation to handle the posting of credits with foreign currencies
||                      For each credit application, the following should be done:
||                      - create an entry for credit amount * diff of exchange rates (section 10 = MC gain)
||                      - create an adjustment of the AR/AP account on the other side for same amount (section 1 = Header)
||                      Set DetailLineKey = VoucherCreditKey or InvoiceCreditKey on both sides
|| 09/23/20 GHL 20.100 (451878) Changes for GL companies diff currency
|| 05/19/25 MCM 25.06x (701762) Updated code to leave the currency ID in.. commented out --,@CurrencyID = null -- this is what we do for other applications
|| 05/28/26 MCM 26.06x (729596) Added PostingFromRegular so we can handle when the credit memo is posted prior to the revenue invoice being posted
*/

/* Assume done in calling sp

		CREATE TABLE #tTransaction (
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL,
			ICTGLCompanyKey int null,

			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null
			
			-- our work space
			,GLValid int null
			,GLAccountErrRet int null
			,GPFlag int null -- General purpose flag
			
			,TempTranLineKey int IDENTITY(1,1) NOT NULL
			)	 


*/

DECLARE @kMemoRealizedGain VARCHAR(100)			SELECT @kMemoRealizedGain = ''Multi Currency Realized Gain/Loss ''

declare @AP_AR_GLAccountKey int
declare @CurrencyID varchar(10)
declare @CreditExchangeRate decimal(24,7)
declare @CreditApplicationKey int
declare @RegularInvoiceKey int
declare @RegularExchangeRate decimal(24,7)
declare @RegularInvoiceNumber varchar(50)
declare @GainLossAmount money
declare @AppliedAmount money

declare @GLCCurrencyID varchar(10)
declare @GLCCreditExchangeRate decimal(24,7)
declare @GLCRegularExchangeRate decimal(24,7)
declare @GLCGainLossAmount money

-- Copied from tTransaction
declare		@TransactionDate smalldatetime,
			@Reference varchar (100) ,
			@GLAccountKey int,
			@Debit money,
			@Credit money,
			@ClassKey int,
			@Memo varchar (500),
			@PostSide char (1),
			@ClientKey int,
			@ProjectKey int,
			@SourceCompanyKey int,
			@GLCompanyKey int,
			@OfficeKey int,
			@DepartmentKey int,
			@DetailLineKey int,
			@Section int, 
			@Overhead tinyint,
			@ICTGLCompanyKey int,

			@ExchangeRate decimal(24,7),
			@HDebit money,
			@HCredit money,
			
			@GLCExchangeRate decimal(24,7),
			@GLCDebit money,
			@GLCCredit money,

			-- our work space
			@GLValid int,
			@GLAccountErrRet int,
			@GPFlag int -- General purpose flag
			
declare @MultiCurrency int
declare @RealizedGainAccountKey int
declare @CreditInvoiceKey int

Select
		 @MultiCurrency = ISNULL(MultiCurrency, 0)
		,@RealizedGainAccountKey = RealizedGainAccountKey  
	From
		tPreference (nolock)
	Where
		CompanyKey = @CompanyKey

if @MultiCurrency = 0
	return 1

if @Entity = ''VOUCHER''
begin
	select @AP_AR_GLAccountKey = APAccountKey
	      ,@CurrencyID = CurrencyID
		  ,@GLCCurrencyID = GLCCurrencyID
		  ,@CreditExchangeRate = isnull(ExchangeRate, 1)
		  ,@GLCCreditExchangeRate = isnull(GLCExchangeRate, 1)
	from  tVoucher (nolock)
	where VoucherKey = @EntityKey

	if isnull(@CurrencyID, '''') = ''''
	return 1

	select @CreditApplicationKey = -1
	while (1=1)
	begin
		select @CreditApplicationKey = min(VoucherCreditKey)
		from   tVoucherCredit (nolock)
		where  CreditVoucherKey = @EntityKey
		and    VoucherCreditKey > @CreditApplicationKey

		if @CreditApplicationKey is null
			break

		select @RegularInvoiceKey = VoucherKey
		     , @AppliedAmount = Amount
		from   tVoucherCredit (nolock)
		where  VoucherCreditKey = @CreditApplicationKey

		select @RegularExchangeRate = isnull(ExchangeRate, 1)
		      ,@RegularInvoiceNumber = InvoiceNumber
			  ,@GLCRegularExchangeRate = isnull(GLCExchangeRate, 1)
		from   tVoucher (nolock)
		where  VoucherKey =@RegularInvoiceKey


		select @GainLossAmount = isnull(@AppliedAmount * (@CreditExchangeRate - @RegularExchangeRate), 0)
		select @GainLossAmount = round(@GainLossAmount, 2)

		select @GLCGainLossAmount = isnull(@AppliedAmount * (@GLCCreditExchangeRate - @GLCRegularExchangeRate), 0)
		select @GLCGainLossAmount = round(@GLCGainLossAmount, 2)

		if @GainLossAmount <> 0 or @GLCGainLossAmount <> 0
		begin
			-- capture data from the header (AR/AP account)
			select @TransactionDate = TransactionDate
				  ,@Reference = Reference
				  ,@ClassKey = ClassKey
			      ,@Memo = Memo 
			      ,@ClientKey = ClientKey
			      ,@ProjectKey = ProjectKey
			      ,@SourceCompanyKey = SourceCompanyKey
			      ,@GLCompanyKey = GLCompanyKey
			      ,@OfficeKey = OfficeKey
			      ,@DepartmentKey = DepartmentKey
			      ,@Overhead  = Overhead
			      ,@ICTGLCompanyKey = ICTGLCompanyKey
			from  #tTransaction
			where Entity = @Entity
			and   EntityKey = @EntityKey
			and   GLAccountKey = @AP_AR_GLAccountKey
			and   [Section] = 1 -- Header

			-- common to 2 transactions
			select @DetailLineKey = @CreditApplicationKey
			      --,@CurrencyID = null -- this is what we do for other applications

			select @Section = 1
			      ,@Debit = 0
			      ,@Credit = 0
				  ,@HDebit = 0
				  ,@HCredit =@GainLossAmount
				  ,@GLCDebit = 0
				  ,@GLCCredit =@GLCGainLossAmount
				  ,@PostSide = ''C''
				  ,@GLAccountKey = @AP_AR_GLAccountKey
				  ,@GLAccountErrRet = -2 -- Invalid AP account
				  ,@ExchangeRate = 1 -- does not matter because this is a difference of exchange rates
				  ,@GLCExchangeRate = 1
				  ,@Memo = @Memo + '' AP Adjustment''

			INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate, HDebit, HCredit
			,GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)

			values (@CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Debit,@Credit,@ClassKey,
					@Memo,@ClientKey,@ProjectKey,@SourceCompanyKey,null,@PostSide,@GLCompanyKey,@OfficeKey,
					@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, @CurrencyID, @ExchangeRate, @HDebit, @HCredit
					,@GLCCurrencyID, @GLCExchangeRate, @GLCDebit, @GLCCredit)

			select @Section = 10
			      ,@Debit = 0
			      ,@Credit = 0
				  ,@HDebit = @GainLossAmount
				  ,@HCredit = 0 
				  ,@GLCDebit = @GLCGainLossAmount
				  ,@GLCCredit = 0 
				  ,@PostSide = ''D''
				  ,@GLAccountKey = @RealizedGainAccountKey
				  ,@GLAccountErrRet = -351 -- Invalid MC account
				  ,@ExchangeRate = 1 -- does not matter because this is a difference of exchange rates
				  ,@GLCExchangeRate = 1
				  ,@Memo = @kMemoRealizedGain + '' - '' + @RegularInvoiceNumber
				  ,@OfficeKey = null
				  ,@DepartmentKey = null
				  ,@ClassKey = null
				  ,@ProjectKey = null

			INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate, HDebit, HCredit
			,GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)

			values (@CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Debit,@Credit,@ClassKey,
					@Memo,@ClientKey,@ProjectKey,@SourceCompanyKey,null,@PostSide,@GLCompanyKey,@OfficeKey,
					@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, @CurrencyID, @ExchangeRate, @HDebit, @HCredit
					,@GLCCurrencyID, @GLCExchangeRate, @GLCDebit, @GLCCredit)

		end -- end amount <> 0

	end -- end credit loop

end -- end AP side
else
begin
	if @PostingFromRegular = 0
	begin
		-- @EntityKey is the credit invoice; find all regular invoices this credit was applied to
		select @AP_AR_GLAccountKey = ARAccountKey
		      ,@CurrencyID = CurrencyID
			  ,@GLCCurrencyID = GLCCurrencyID
			  ,@CreditExchangeRate = isnull(ExchangeRate, 1)
			  ,@GLCCreditExchangeRate = isnull(GLCExchangeRate, 1)
		from  tInvoice (nolock)
		where InvoiceKey = @EntityKey

		if isnull(@CurrencyID, '''') = ''''
		return 1

		select @CreditApplicationKey = -1
		while (1=1)
		begin
			select @CreditApplicationKey = min(InvoiceCreditKey)
			from   tInvoiceCredit (nolock)
			where  CreditInvoiceKey = @EntityKey
			and    InvoiceCreditKey > @CreditApplicationKey

			if @CreditApplicationKey is null
				break

			select @RegularInvoiceKey = InvoiceKey
			     , @AppliedAmount = Amount
			from   tInvoiceCredit (nolock)
			where  InvoiceCreditKey = @CreditApplicationKey

			select @RegularExchangeRate = isnull(ExchangeRate, 1)
			      ,@RegularInvoiceNumber = InvoiceNumber
				  ,@GLCRegularExchangeRate = isnull(GLCExchangeRate, 1)
			from   tInvoice (nolock)
			where  InvoiceKey =@RegularInvoiceKey


			select @GainLossAmount = isnull(@AppliedAmount * (@CreditExchangeRate - @RegularExchangeRate), 0)
			select @GainLossAmount = round(@GainLossAmount, 2)

			select @GLCGainLossAmount = isnull(@AppliedAmount * (@GLCCreditExchangeRate - @GLCRegularExchangeRate), 0)
			select @GLCGainLossAmount = round(@GLCGainLossAmount, 2)

			if @GainLossAmount <> 0 or @GLCGainLossAmount <> 0
			begin
				-- capture data from the header (AR/AP account)
				select @TransactionDate = TransactionDate
					  ,@Reference = Reference
					  ,@ClassKey = ClassKey
				      ,@Memo = Memo
				      ,@ClientKey = ClientKey
				      ,@ProjectKey = ProjectKey
				      ,@SourceCompanyKey = SourceCompanyKey
				      ,@GLCompanyKey = GLCompanyKey
				      ,@OfficeKey = OfficeKey
				      ,@DepartmentKey = DepartmentKey
				      ,@Overhead  = Overhead
				      ,@ICTGLCompanyKey = ICTGLCompanyKey
				from  #tTransaction
				where Entity = @Entity
				and   EntityKey = @EntityKey
				and   GLAccountKey = @AP_AR_GLAccountKey
				and   [Section] = 1 -- Header

				-- common to 2 transactions
				select @DetailLineKey = @CreditApplicationKey
				      --,@CurrencyID = null -- this is what we do for other applications

				select @Section = 1
				      ,@Debit = 0
				      ,@Credit = 0
					  ,@HDebit = @GainLossAmount
					  ,@HCredit = 0
					  ,@GLCDebit = @GLCGainLossAmount
					  ,@GLCCredit = 0
					  ,@PostSide = ''D''
					  ,@GLAccountKey = @AP_AR_GLAccountKey
					  ,@GLAccountErrRet = -2 -- Invalid AP account
					  ,@ExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@GLCExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@Memo = @Memo + '' AR Adjustment''

				INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
				Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
				DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate, HDebit, HCredit
				,GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)

				values (@CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Debit,@Credit,@ClassKey,
						@Memo,@ClientKey,@ProjectKey,@SourceCompanyKey,null,@PostSide,@GLCompanyKey,@OfficeKey,
						@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, @CurrencyID, @ExchangeRate, @HDebit, @HCredit
						,@GLCCurrencyID, @GLCExchangeRate, @GLCDebit, @GLCCredit)

				select @Section = 10
				      ,@Debit = 0
				      ,@Credit = 0
					  ,@HDebit = 0
					  ,@HCredit = @GainLossAmount
					  ,@GLCDebit = 0
					  ,@GLCCredit = @GLCGainLossAmount
					  ,@PostSide = ''C''
					  ,@GLAccountKey = @RealizedGainAccountKey
					  ,@GLAccountErrRet = -351 -- Invalid MC account
					  ,@ExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@GLCExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@Memo = @kMemoRealizedGain + '' - '' + @RegularInvoiceNumber
					  ,@OfficeKey = null
					  ,@DepartmentKey = null
					  ,@ClassKey = null
					  ,@ProjectKey = null

				INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
				Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
				DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate, HDebit, HCredit
				,GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)

				values (@CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Debit,@Credit,@ClassKey,
						@Memo,@ClientKey,@ProjectKey,@SourceCompanyKey,null,@PostSide,@GLCompanyKey,@OfficeKey,
						@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, @CurrencyID, @ExchangeRate, @HDebit, @HCredit
						,@GLCCurrencyID, @GLCExchangeRate, @GLCDebit, @GLCCredit)

			end -- end amount <> 0

		end -- end credit loop

	end -- end @PostingFromRegular = 0
	else
	begin
		-- @EntityKey is the regular (revenue) invoice being posted.
		-- Handle FX for any already-posted credit memos applied to it that have not yet created
		-- an FX entry (i.e. the credit was posted before the application was recorded).
		select @AP_AR_GLAccountKey = ARAccountKey
		      ,@CurrencyID = CurrencyID
			  ,@GLCCurrencyID = GLCCurrencyID
			  ,@RegularExchangeRate = isnull(ExchangeRate, 1)
			  ,@GLCRegularExchangeRate = isnull(GLCExchangeRate, 1)
		from  tInvoice (nolock)
		where InvoiceKey = @EntityKey

		if isnull(@CurrencyID, '''') = ''''
			return 1

		select @CreditApplicationKey = -1
		while (1=1)
		begin
			select @CreditApplicationKey = min(InvoiceCreditKey)
			from   tInvoiceCredit (nolock)
			where  InvoiceKey = @EntityKey
			and    InvoiceCreditKey > @CreditApplicationKey

			if @CreditApplicationKey is null
				break

			select @CreditInvoiceKey = CreditInvoiceKey
			     , @AppliedAmount = Amount
			from   tInvoiceCredit (nolock)
			where  InvoiceCreditKey = @CreditApplicationKey

			-- Only process credits that are already posted; unposted credits will create their own FX when posted
			if not exists (select 1 from tInvoice (nolock) where InvoiceKey = @CreditInvoiceKey and isnull(Posted, 0) = 1)
				continue

			-- Skip if FX was already created for this application (credit was posted while application existed)
			if exists (select 1 from tTransaction (nolock)
			           where DetailLineKey = @CreditApplicationKey
			           and   Section = 10
			           and   Entity = ''INVOICE''
			           and   EntityKey = @CreditInvoiceKey)
				continue

			select @CreditExchangeRate = isnull(ExchangeRate, 1)
			      ,@RegularInvoiceNumber = InvoiceNumber  -- credit invoice number used in memo
			      ,@GLCCreditExchangeRate = isnull(GLCExchangeRate, 1)
			from   tInvoice (nolock)
			where  InvoiceKey = @CreditInvoiceKey

			select @GainLossAmount = isnull(@AppliedAmount * (@CreditExchangeRate - @RegularExchangeRate), 0)
			select @GainLossAmount = round(@GainLossAmount, 2)

			select @GLCGainLossAmount = isnull(@AppliedAmount * (@GLCCreditExchangeRate - @GLCRegularExchangeRate), 0)
			select @GLCGainLossAmount = round(@GLCGainLossAmount, 2)

			if @GainLossAmount <> 0 or @GLCGainLossAmount <> 0
			begin
				-- capture data from the header of the revenue invoice being posted
				select @TransactionDate = TransactionDate
					  ,@Reference = Reference
					  ,@ClassKey = ClassKey
				      ,@Memo = Memo
				      ,@ClientKey = ClientKey
				      ,@ProjectKey = ProjectKey
				      ,@SourceCompanyKey = SourceCompanyKey
				      ,@GLCompanyKey = GLCompanyKey
				      ,@OfficeKey = OfficeKey
				      ,@DepartmentKey = DepartmentKey
				      ,@Overhead  = Overhead
				      ,@ICTGLCompanyKey = ICTGLCompanyKey
				from  #tTransaction
				where Entity = @Entity
				and   EntityKey = @EntityKey
				and   GLAccountKey = @AP_AR_GLAccountKey
				and   [Section] = 1 -- Header

				select @DetailLineKey = @CreditApplicationKey

				select @Section = 1
				      ,@Debit = 0
				      ,@Credit = 0
					  ,@HDebit = @GainLossAmount
					  ,@HCredit = 0
					  ,@GLCDebit = @GLCGainLossAmount
					  ,@GLCCredit = 0
					  ,@PostSide = ''D''
					  ,@GLAccountKey = @AP_AR_GLAccountKey
					  ,@GLAccountErrRet = -2 -- Invalid AR account
					  ,@ExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@GLCExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@Memo = @Memo + '' AR Adjustment''

				INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
				Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
				DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate, HDebit, HCredit
				,GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)

				values (@CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Debit,@Credit,@ClassKey,
						@Memo,@ClientKey,@ProjectKey,@SourceCompanyKey,null,@PostSide,@GLCompanyKey,@OfficeKey,
						@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, @CurrencyID, @ExchangeRate, @HDebit, @HCredit
						,@GLCCurrencyID, @GLCExchangeRate, @GLCDebit, @GLCCredit)

				select @Section = 10
				      ,@Debit = 0
				      ,@Credit = 0
					  ,@HDebit = 0
					  ,@HCredit = @GainLossAmount
					  ,@GLCDebit = 0
					  ,@GLCCredit = @GLCGainLossAmount
					  ,@PostSide = ''C''
					  ,@GLAccountKey = @RealizedGainAccountKey
					  ,@GLAccountErrRet = -351 -- Invalid MC account
					  ,@ExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@GLCExchangeRate = 1 -- does not matter because this is a difference of exchange rates
					  ,@Memo = @kMemoRealizedGain + '' - '' + @RegularInvoiceNumber
					  ,@OfficeKey = null
					  ,@DepartmentKey = null
					  ,@ClassKey = null
					  ,@ProjectKey = null

				INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
				Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
				DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate, HDebit, HCredit
				,GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)

				values (@CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Debit,@Credit,@ClassKey,
						@Memo,@ClientKey,@ProjectKey,@SourceCompanyKey,null,@PostSide,@GLCompanyKey,@OfficeKey,
						@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, @CurrencyID, @ExchangeRate, @HDebit, @HCredit
						,@GLCCurrencyID, @GLCExchangeRate, @GLCDebit, @GLCCredit)

			end -- end amount <> 0

		end -- end credit loop

	end -- end @PostingFromRegular = 1

end -- end AR case

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


ALTER VIEW [dbo].[vInvoicePrint]
AS

  /*
  || When      Who Rel     What
  || 12/05/06 GHL 8.4      Added ShowBillingSummary flag
  || 04/24/07 GHL 8.42     Added BCGroupByOrder, IOGroupByOrder
  || 02/25/08 GHL 8.505    (21518) Added HideClientName
  || 09/22/09 GHL 10.511   (63345) Added ShowExpComments
  || 03/26/10 MFT 10.520   Added SalesTax1Name and SalesTax2Name
  || 4/16/10  CRG 10.5.2.1 Added LayoutKey
  || 06/06/11 GHL 10.5.4.5 Added Address from GL company
  || 06/07/11 GHL 10.5.4.5 Added CompanyName/Phone/Fax from GL Company to be consistent
  ||                       with what we did for the POs vPurchaseOrderDetail (issue 37963)
  || 10/21/11 GHL 10.5.4.9 (124386) Split RetainerAmount in 2 fields, 1 for sales, 1 for taxes
  || 07/10/12 GHL 10.5.5.8 (148091) Added BillingName
  || 07/18/12 RLB 10.5.5.8 (143447) Added CampaignName
  || 09/10/12 RLB 10.5.6.0 (153617) Added Show Campaign option
  || 11/14/13 RLB 10.5.7.4 (196356) Added CampaignID to CampaignName
  || 01/10/14 GHL 10.5.7.6  Added CurrencyID for multicurrency invoices
  || 09/08/15 WDF 10.5.9.5  Added GLCompany ReportLogo-- Do not end with this
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 11/18/20 GHL 20.1.2.0 (533381) If there is no invoice template, show the campaign by default (for new campaign billing methods)
  ||                       Will be displayed if a campaign exists and ShowCampaign = 1
  ||                       If there is an invoice template, read isnull(it.ShowCampaign, 0)
  || 05/18/22 MFT 22.0.6.0 (599876) CAST BillingName as nvarchar(200) to allow extended characters in CompanyName to show. May be remvoed after field converted to nvarchar.
  || 10/25/22 RLS 22.11.20 (600017) Removed CAST to nvarchar on BillingName since the field itself is now nvarchar
  || 06/14/23 AMP 23.09.17 (636559) Added ShowPM and PMName to display Project Manager on the printed invoice
  || 05/26/26 AMP 26.07.19 (728858) Added ClientCampaignNumber for display on invoice when ShowCampaign is on
  */

SELECT  i.InvoiceKey, 
	c.CompanyKey AS ClientKey, 
	c1.CompanyName, 
	c1.Phone,
	c1.Fax,
	
	glc.GLCompanyKey,
	glc.PrintedName as GLCCompanyName,
	glc.Phone as GLCPhone,
	glc.Fax as GLCFax,
	glc.ReportLogo,

	-- Default Company Address
	a_c1.Address1 as CAddress1, 
	a_c1.Address2 as CAddress2, 
	a_c1.Address3 as CAddress3, 
	a_c1.City as CCity, 
	a_c1.State as CState, 
	a_c1.PostalCode as CPostalCode, 
	a_c1.Country as CCountry, 
	
	-- Company Address from the GL Company
	a_glc.AddressKey as GLCAddressKey,
	a_glc.Address1 as GLCAddress1,
	a_glc.Address2 as GLCAddress2,
	a_glc.Address3 as GLCAddress3,
	a_glc.City as GLCCity,
	a_glc.State as GLCState,
	a_glc.PostalCode as GLCPostalCode,
	a_glc.Country as GLCCountry,
	
	-- Billing Address: 1) From Invoice, 2) Client Billing Addr, 3) Client Default Addr 
	isnull(c.BillingName, c.CompanyName) AS BCompanyName,
	CASE
	    WHEN i.AddressKey IS NOT NULL THEN a_i.Address1 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.Address1
	             ELSE a_dc.Address1 
		END 
	END  AS BAddress1, 
	CASE
	    WHEN i.AddressKey IS NOT NULL THEN a_i.Address2 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.Address2
	             ELSE a_dc.Address2
		END 
	END  AS BAddress2, 
	CASE
	    WHEN i.AddressKey IS NOT NULL THEN a_i.Address3 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.Address3
	             ELSE a_dc.Address3
		END 
	END  AS BAddress3, 
	CASE
	    WHEN i.AddressKey IS NOT NULL THEN a_i.City 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.City
	             ELSE a_dc.City
		END 
	END  AS BCity, 
	CASE   
	    WHEN i.AddressKey IS NOT NULL THEN a_i.State 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.State
	             ELSE a_dc.State
		END 
	END  AS BState, 
	CASE   
	    WHEN i.AddressKey IS NOT NULL THEN a_i.PostalCode 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.PostalCode
	             ELSE a_dc.PostalCode
		END 
	END  AS BPostalCode, 
	CASE   
	    WHEN i.AddressKey IS NOT NULL THEN a_i.Country 
	    ELSE
	        CASE WHEN c.BillingAddressKey IS NOT NULL THEN a_bc.Country
	             ELSE a_dc.Country
		END 
	END  AS BCountry, 
	c.CustomerID,
	c.UserDefined1 as CLUserDefined1,
	c.UserDefined2 as CLUserDefined2,
	c.UserDefined3 as CLUserDefined3,
	c.UserDefined4 as CLUserDefined4,
	c.UserDefined5 as CLUserDefined5,
	c.UserDefined6 as CLUserDefined6,
	c.UserDefined7 as CLUserDefined7,
	c.UserDefined8 as CLUserDefined8,
	c.UserDefined9 as CLUserDefined9,
	c.UserDefined10 as CLUserDefined10,
	i.ContactName AS BillingContact, 
	pt.TermsDescription, 
	i.InvoiceNumber, 
	i.InvoiceDate, 
	i.DueDate, 
	i.RecurringParentKey,
	i.UserDefined1,
	i.UserDefined2,
	i.UserDefined3,
	i.UserDefined4,
	i.UserDefined5,
	i.UserDefined6,
	i.UserDefined7,
	i.UserDefined8,
	i.UserDefined9,
	i.UserDefined10,
	i.Posted,
	i.InvoiceStatus,
	i.HeaderComment,
	i.SalesTaxKey,
	i.SalesTax2Key,
	i.ClassKey,
	i.ARAccountKey,
	i.ParentInvoiceKey,
	i.ParentInvoice,
	i.PercentageSplit,
	ISNULL(i.AmountReceived, 0) AS PaymentAmount,
	ISNULL(i.DiscountAmount, 0) AS DiscountAmount,
	ISNULL(i.WriteoffAmount, 0) AS WriteoffAmount,
	ISNULL(i.RetainerAmount, 0) AS RetainerAmount,
	ISNULL(i.RetainerAmount, 0)
	-ISNULL((select sum(iabt.Amount) from tInvoiceAdvanceBillTax iabt (nolock) where iabt.InvoiceKey = i.InvoiceKey), 0) as RetainerAmountSales,
	ISNULL((select sum(iabt.Amount) from tInvoiceAdvanceBillTax iabt (nolock) where iabt.InvoiceKey = i.InvoiceKey), 0) as RetainerAmountTaxes,
	ISNULL(i.AmountReceived, 0) AS AmountReceived,
	ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) AS BilledAmount,
    	ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.WriteoffAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - isnull(i.AmountReceived, 0) AS OpenAmount,
    	ISNULL(i.SalesTaxAmount, 0) AS SalesTaxAmount,
	ISNULL(i.SalesTax1Amount, 0) AS SalesTax1Amount,
	ISNULL(i.SalesTax2Amount, 0) AS SalesTax2Amount,
    	ISNULL(i.TotalNonTaxAmount, 0) AS TotalNonTaxAmount,
	ISNULL(i.InvoiceTotalAmount, 0) AS InvoiceTotalAmount,
	ISNULL(st.Description, ''Sales Tax'') AS SalesTaxDescription,
	st2.Description AS SalesTax2Description,
	st.SalesTaxName AS SalesTax1Name,
	st2.SalesTaxName AS SalesTax2Name,
	it.InvoiceTemplateKey,
	it.ShowAmountsAtSummary,
	it.ShowDetailLines,
	it.ShowTime,
	it.TimeSummaryLevel,
	it.ShowComments,
	it.ShowExpenses,
	it.ShowProjectCustFields,
	it.ShowProjectNumber,
	it.ShowClientProjectNumber,
	it.ClientProjectNumberLabel,
	it.ShowProjectDescription,
	it.HidePageNumbers,
	it.HideZeroReceipts,
	it.QtyDescription,
	it.LabelUserDefined1,
	it.LabelUserDefined2,
	it.LabelUserDefined3,
	it.LabelUserDefined4,
	it.LabelUserDefined5,
	it.LabelUserDefined6,
	it.LabelUserDefined7,
	it.LabelUserDefined8,
	it.LabelUserDefined9,
	it.LabelUserDefined10,
	it.FooterMessage,
	it.LogoTop,
	it.LogoLeft,
	it.LogoHeight,
	it.LogoWidth,
	it.CompanyAddressTop,
	it.CompanyAddressLeft,
	it.CompanyAddressWidth,
	it.AddPhoneFaxToAddress,
	it.ClientAddressTop,
	it.ClientAddressLeft,
	it.ClientAddressWidth,
	
	-- Company Address from the Template
	it.AddressKey as TAddressKey,
	a_it.Address1 as TAddress1,
	a_it.Address2 as TAddress2,
	a_it.Address3 as TAddress3,
	a_it.City as TCity,
	a_it.State as TState,
	a_it.PostalCode as TPostalCode,
	a_it.Country as TCountry,
	
	it.CustomLogo,
	it.NumberTop,
	it.NumberLeft,
	it.ShowInvoiceNum,
	it.ShowInvoiceDate,
	it.ShowTerms,
	it.ShowDueDate,
	it.ShowAE,
    it.ShowPM,
	-- by default, if no template, show the campaign (for the new campaign billing) 
	case when it.InvoiceTemplateKey is null then 1 else isnull(it.ShowCampaign,0) end as ShowCampaign,
	it.RepeatHeader,
	it.LabelTop,
	it.LabelLeft,
	it.LabelWidth,
	it.InvoiceLabel,
	it.InvoiceLabelSize,
	it.InvoiceLabelForAll,
	it.FontName,
	it.HeaderFontSize,
	it.DetailFontSize,
	it.ShowClientUserDefined,
	it.AddressFont,
	it.AddressSize,
	it.AddressBold,
	it.AddressItalic,
	it.HeaderFont,
	it.HeaderSize,
	it.HeaderBold,
	it.HeaderItalic,
	it.SummaryLineFont,
	it.SummaryLineSize,
	it.SummaryLineBold,
	it.SummaryLineItalic,
	it.SummaryDescFont,
	it.SummaryDescSize,
	it.SummaryDescBold,
	it.SummaryDescItalic,
	it.DetailLineFont,
	it.DetailLineSize,
	it.DetailLineBold,
	it.DetailLineItalic,
	it.DetailDescFont,
	it.DetailDescSize,
	it.DetailDescBold,
	it.DetailDescItalic,
	it.DetailsHeaderFont,
	it.DetailsHeaderSize,
	it.DetailsHeaderBold,
	it.DetailsHeaderItalic,
	it.DetailsHeaderBorder,
	it.DetailsFont,
	it.DetailsSize,
	it.DetailsBold,
	it.DetailsItalic,
	it.FooterFont,
	it.FooterSize,
	it.FooterBold,
	it.FooterItalic,
	it.ShowLaborHrs,
	it.ShowLaborRate,
	it.ShowTitle,
	it.GroupLaborDetailBy,
	it.ShowExpDate,
	it.ShowExpDescription,
	it.ShowExpComments,
	it.ShowExpItemDesc,
	it.ShowExpQty,
	it.ShowExpRate,
	it.ShowExpNet,
	it.ShowExpMarkup,
	it.ShowExpGross,
	it.SortExpBy,
	it.GroupExpByItem,
	it.ShowZeroTaxes,
	it.BCGroup1,
	it.BCGroup2,
	it.BCGroup3,
	it.BCGroup4,
	it.BCGroup5,
	it.BCTotal1,
	it.BCTotal2,
	it.BCTotal3,
	it.BCTotal4,
	it.BCTotal5,
	it.BCHideDetails,
	it.BCCol1,
	it.BCCol2,
	it.BCCol3,
	it.BCCol4,
	it.BCCol5,
	it.BCCol6,
	it.BCCol7,
	it.BCCol8,
	it.BCColWidth1,
	it.BCColWidth2,
	it.BCColWidth3,
	it.BCColWidth4,
	it.BCColWidth5,
	it.BCColWidth6,
	it.BCColWidth7,
	it.BCColWidth8,
	it.IOGroup1,
	it.IOGroup2,
	it.IOGroup3,
	it.IOGroup4,
	it.IOGroup5,
	it.IOTotal1,
	it.IOTotal2,
	it.IOTotal3,
	it.IOTotal4,
	it.IOTotal5,
	it.IOHideDetails,
	it.IOCol1,
	it.IOCol2,
	it.IOCol3,
	it.IOCol4,
	it.IOCol5,
	it.IOCol6,
	it.IOCol7,
	it.IOColWidth1,
	it.IOColWidth2,
	it.IOColWidth3,
	it.IOColWidth4,
	it.IOColWidth5,
	it.IOColWidth6,
	it.IOColWidth7,
	it.ShowLineQuantityRate,
	it.HideCompanyName,
	it.HideClientName,
	it.ShowProduct,
	it.ShowDivision,
	it.KeepFooterTogether,
	it.ShowBillingSummary,
	it.BCGroupByOrder,
	it.IOGroupByOrder,
	p.ProjectKey,
	p.ProjectNumber,
	p.ProjectName,
	p.Description as ProjectDescription,
	LTRIM(RTRIM(ISNULL(ae.FirstName + '' '','''')  + ISNULL(ae.LastName,''''))) AS AEName,
	LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS PMName,
	p.ClientProjectNumber,
	p.CustomFieldKey,
	cp.ProductName,
	cd.DivisionName,
    c.CustomFieldKey as CompanyCustomFieldKey,
	i.LayoutKey,
	i.CampaignKey,
	cpn.CampaignID + '' - '' + cpn.CampaignName AS CampaignName,
	cpn.ClientCampaignNumber,
	i.CurrencyID
FROM tInvoice i (nolock)
	INNER JOIN tCompany c (nolock) ON i.ClientKey = c.CompanyKey 
	INNER JOIN tCompany c1 (nolock) ON i.CompanyKey = c1.CompanyKey
	LEFT OUTER JOIN tGLCompany glc (nolock) on i.GLCompanyKey = glc.GLCompanyKey 
	LEFT OUTER JOIN tPaymentTerms pt (nolock) ON i.TermsKey = pt.PaymentTermsKey
	LEFT OUTER JOIN tSalesTax st (nolock) ON i.SalesTaxKey = st.SalesTaxKey
	LEFT OUTER JOIN tSalesTax st2 (nolock) ON i.SalesTax2Key = st2.SalesTaxKey
	LEFT OUTER JOIN tInvoiceTemplate it (nolock) ON i.InvoiceTemplateKey = it.InvoiceTemplateKey
	LEFT OUTER JOIN tProject p ON i.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tUser ae ON p.AccountManager = ae.UserKey
	LEFT OUTER JOIN tUser pm ON p.ProjectManager = pm.UserKey
	LEFT OUTER JOIN tAddress a_c1 (nolock) ON c1.DefaultAddressKey = a_c1.AddressKey -- Company
	LEFT OUTER JOIN tAddress a_dc (nolock) ON c.DefaultAddressKey = a_dc.AddressKey -- Client default
	LEFT OUTER JOIN tAddress a_bc (nolock) ON c.BillingAddressKey = a_bc.AddressKey -- Client billing
	LEFT OUTER JOIN tAddress a_it (nolock) ON it.AddressKey = a_it.AddressKey -- Company on template	
	LEFT OUTER JOIN tAddress a_i (nolock) ON i.AddressKey = a_i.AddressKey -- Client on invoice
	LEFT OUTER JOIN tAddress a_glc (nolock) ON glc.AddressKey =  a_glc.AddressKey -- Company on GL company
	LEFT OUTER JOIN tClientProduct cp (NOLOCK) ON p.ClientProductKey = cp.ClientProductKey
	LEFT OUTER JOIN tClientDivision cd (NOLOCK) ON p.ClientDivisionKey = cd.ClientDivisionKey
	LEFT OUTER JOIN tCampaign cpn (NOLOCK) ON i.CampaignKey = cpn.CampaignKey

Where ParentInvoice = 0

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spConvertAppSeedSetting]'
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/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/26/26  RLS 26.06.14 (729061) Added Billed Variance to the clientInvoiceExpense section

 */

-- 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, CFEntity1, CFPrefix1) 
Values (''myTasks'', ''grdMyTasksCols'', 22, ''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'', 23, ''Auto Expand Tasks'', ''0'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H3'', 24, ''Feed'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
VALUES (''myTasks'', ''DailyFeed'', 25, ''Daily Feed'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H6'', 26, ''Conversations'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint)
Values (''myTasks'', ''SortConversations'', 27, ''Sort Conversations'', ''ASC'', NULL, ''lookup'', ''ASC|DESC'', NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''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 (''myTasks'', ''H4'', 29, ''Timeline Options'', NULL, NULL, ''sectionheader'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''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 (''myTasks'', ''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 (''myTasks'', ''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 (''myTasks'', ''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 (''myTasks'', ''IncludePublicMeetings'', 34, ''Include Public Meetings'', ''1'', NULL, ''checkbox'', NULL, NULL, NULL)
INSERT tAppSetting(GroupID, SessionID, DisplayOrder, Label, DefaultValue, DefaultLabel, EditorType, ValueList, LookupID, Hint) 
Values (''myTasks'', ''H5'', 35, ''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'', 36, ''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)



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"}
]''
	 , 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"}
 ]''
	 , 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"}
]''
 , 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"}
]''
 , 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"}
]''
 , 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'Altering [dbo].[spGetNextTranNo]'
GO
IF OBJECT_ID(N'[dbo].[spGetNextTranNo]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spGetNextTranNo]
(
	@_iCompanyKey	INTEGER,
	@_iTranType		VARCHAR(50),
	@_oRetVal		INTEGER OUTPUT,
	@_oNextTranNo 	VARCHAR(100) OUTPUT
	)
AS --Encrypt
BEGIN

/*
|| When      Who Rel      What
|| 6/25/13   CRG 10.5.6.9 Added TranType for Media Worksheet
|| 1/13/14   CRG 10.5.7.5 Added TranType for Interactive
|| 2/26/14   CRG 10.5.7.7 Added separate TranTypes for different Media Worksheet types rather than one for all Media Worksheets
|| 6/21/23   MAS 23.07.16 Removed old media references, tMediaWorksheet
|| 8/06/25   GAR 25.08.17 (708266) Trailing spaces in the invoice number was causing issues with Avalara - added RTRIM to @_oNextTranNo
|| 04/21/26  AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
*/

	DECLARE		@_lNextTranNo		INTEGER			/* local work variable */
	DECLARE 	@_lNextTranNoC	 	CHAR(100)		/* character version of tran number */		
	DECLARE 	@_lNextTranNoPC         CHAR(100)		/* character version of tran number padded with 0''s on the left */
	DECLARE 	@_lTempTranNo           VARCHAR(200)

	DECLARE		@NumPrefix 		VARCHAR(10)
				,@NumPlaces		INTEGER
				,@Zeroes		VARCHAR(100)
				,@NumUsed		INTEGER
				,@TwoDigitPrefix tinyint

	/* initialize return value to failure status */
	SELECT	@_oRetVal = 0
	SELECT	@_oNextTranNo = NULL
	SELECT	@Zeroes = ''00000000000000000000000000000000000000000000000000000000000000000000000000000000000000''

	/* find next tran number (with lock on row) */
	IF @_iTranType = ''PO''
		SELECT	@_lNextTranNo = ISNULL(NextPONum, 1)
  				,@NumPrefix = ISNULL(PONumPrefix, '''')
				,@NumPlaces = ISNULL(PONumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	ELSE 
	IF @_iTranType = ''IO''
		SELECT	@_lNextTranNo = ISNULL(NextIONum, 1)
  				,@NumPrefix = ISNULL(IONumPrefix, '''')
				,@NumPlaces = ISNULL(IONumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	ELSE 
	IF @_iTranType = ''BC''
		SELECT	@_lNextTranNo = ISNULL(NextBCNum, 1)
  				,@NumPrefix = ISNULL(BCNumPrefix, '''')
				,@NumPlaces = ISNULL(BCNumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	ELSE 
	IF @_iTranType = ''INT''
		SELECT	@_lNextTranNo = ISNULL(NextIntNum, 1)
  				,@NumPrefix = ISNULL(IntNumPrefix, '''')
				,@NumPlaces = ISNULL(IntNumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	ELSE
	IF @_iTranType = ''AR''
		SELECT	@_lNextTranNo = ISNULL(NextARNum, 1)
  				,@NumPrefix = ISNULL(ARNumPrefix, '''')
				,@NumPlaces = ISNULL(ARNumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
    ELSE
	IF @_iTranType = ''AdvBill''
		SELECT	@_lNextTranNo = ISNULL(NextARNum, 1)
		        ,@NumPrefix = ISNULL(AdvBillPrefix, '''')  				
				,@NumPlaces = ISNULL(ARNumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	ELSE
	IF @_iTranType = ''Expense''
		SELECT	@_lNextTranNo = ISNULL(NextExpenseNum, 1)
  				,@NumPrefix = ISNULL(ExpenseNumPrefix, '''')
				,@NumPlaces = ISNULL(ExpenseNumPlaces, 6)
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	IF @_iTranType = ''MediaWkshtPrint''
		SELECT	@_lNextTranNo = ISNULL(NextMediaWorksheetNum, 1)
  				,@NumPrefix = ''''
				,@NumPlaces = 6
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	IF @_iTranType = ''MediaWkshtInt''
		SELECT	@_lNextTranNo = ISNULL(NextMediaWorksheetIntNum, 1)
  				,@NumPrefix = ''''
				,@NumPlaces = 6
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	IF @_iTranType = ''MediaWkshtBC''
		SELECT	@_lNextTranNo = ISNULL(NextMediaWorksheetBCNum, 1)
  				,@NumPrefix = ''''
				,@NumPlaces = 6
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey
	IF @_iTranType = ''MediaWkshtOOH''
		SELECT	@_lNextTranNo = ISNULL(NextMediaWorksheetNum, 1)
  				,@NumPrefix = ''''
				,@NumPlaces = 6
		FROM	tPreference
		WHERE	CompanyKey = @_iCompanyKey


		
	/* loop until unused tran number found */
	WHILE( 1=1 )
	BEGIN

		SELECT @_lNextTranNoC = CONVERT(CHAR(100), @_lNextTranNo)
		IF @NumPlaces < LEN(LTRIM(RTRIM(@_lNextTranNoC)))
			SELECT @_lNextTranNoPC = @_lNextTranNoC
		ELSE
		BEGIN
			SELECT @_lTempTranNo = @Zeroes +LTRIM(RTRIM(@_lNextTranNoC))
			SELECT @_lNextTranNoPC = RIGHT(@_lTempTranNo, @NumPlaces)
		END
		IF @NumPrefix <> '''' 
			SELECT @_lNextTranNoPC = @NumPrefix+''-''+@_lNextTranNoPC
		
		/* see if next tran number already exists in tran log */
		IF @_iTranType = ''PO''
			IF EXISTS (SELECT 1 FROM tPurchaseOrder (NOLOCK)
					WHERE 	PurchaseOrderNumber IN (@_lNextTranNoC, @_lNextTranNoPC)
					AND     CompanyKey = @_iCompanyKey
					AND		POKind = 0)
				SELECT @NumUsed = 1
			ELSE
				SELECT @NumUsed = 0
		ELSE
		IF @_iTranType = ''IO''
			IF EXISTS (SELECT 1 FROM tPurchaseOrder (NOLOCK)
					WHERE 	PurchaseOrderNumber IN (@_lNextTranNoC, @_lNextTranNoPC)
					AND     CompanyKey = @_iCompanyKey
					AND		POKind = 1)
				SELECT @NumUsed = 1
			ELSE
				SELECT @NumUsed = 0
		ELSE
		IF @_iTranType = ''BC''
			IF EXISTS (SELECT 1 FROM tPurchaseOrder (NOLOCK)
					WHERE 	PurchaseOrderNumber IN (@_lNextTranNoC, @_lNextTranNoPC)
					AND     CompanyKey = @_iCompanyKey
					AND		POKind = 2)
				SELECT @NumUsed = 1
			ELSE
				SELECT @NumUsed = 0
		ELSE
		IF @_iTranType = ''INT''
			IF EXISTS (SELECT 1 FROM tPurchaseOrder (NOLOCK)
					WHERE 	PurchaseOrderNumber IN (@_lNextTranNoC, @_lNextTranNoPC)
					AND     CompanyKey = @_iCompanyKey
					AND		POKind = 4)
				SELECT @NumUsed = 1
			ELSE
				SELECT @NumUsed = 0
		ELSE
		IF @_iTranType = ''AR'' OR @_iTranType = ''AdvBill''
			IF EXISTS (SELECT 1 FROM tInvoice (NOLOCK)
					WHERE 	InvoiceNumber IN (@_lNextTranNoC, @_lNextTranNoPC)
					AND     CompanyKey = @_iCompanyKey)
				SELECT @NumUsed = 1
			ELSE
				SELECT @NumUsed = 0		
		ELSE
		IF @_iTranType = ''Expense''
			IF EXISTS (SELECT 1 FROM tExpenseEnvelope (NOLOCK)
					WHERE 	EnvelopeNumber IN (@_lNextTranNoC, @_lNextTranNoPC)
					AND     CompanyKey = @_iCompanyKey)
				SELECT @NumUsed = 1
			ELSE
				SELECT @NumUsed = 0		
		
		IF @NumUsed = 0

		BEGIN
			/* not found, return as valid choice */
			SELECT	@_oNextTranNo = RTRIM(@_lNextTranNoPC)

			/* increment to next number */
			SELECT	@_lNextTranNo = @_lNextTranNo + 1

			/* check if we''ve hit the limit */
			IF @_lNextTranNo >  2147483647
			BEGIN
				SELECT	@_oRetVal = 2
				RETURN
			END

			/* update next number */
			IF @_iTranType = ''PO''
				UPDATE tPreference
				SET    NextPONum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			ELSE
			IF @_iTranType = ''IO''
				UPDATE tPreference
				SET    NextIONum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			ELSE
			IF @_iTranType = ''BC''
				UPDATE tPreference
				SET    NextBCNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			ELSE
			IF @_iTranType = ''INT''
				UPDATE tPreference
				SET    NextIntNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			ELSE
			IF @_iTranType = ''AR'' OR @_iTranType = ''AdvBill''
				UPDATE tPreference
				SET    NextARNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			ELSE
			IF @_iTranType = ''Expense''
				UPDATE tPreference
				SET    NextExpenseNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			IF @_iTranType = ''MediaWkshtPrint''
				UPDATE	tPreference
				SET		NextMediaWorksheetNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			IF @_iTranType = ''MediaWkshtInt''
				UPDATE	tPreference
				SET		NextMediaWorksheetIntNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			IF @_iTranType = ''MediaWkshtBC''
				UPDATE	tPreference
				SET		NextMediaWorksheetBCNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			IF @_iTranType = ''MediaWkshtOOH''
				UPDATE	tPreference
				SET		NextMediaWorksheetOOHNum = @_lNextTranNo
				WHERE	CompanyKey = @_iCompanyKey
			
			SELECT	@_oRetVal = 1

			/* return to caller */
			RETURN
		END

		/* increment to next number */
		SELECT	@_lNextTranNo = @_lNextTranNo + 1

		/* check if we''ve hit the limit */
		IF @_lNextTranNo > 2147483647
		BEGIN
			SELECT	@_oRetVal = 2
	
		RETURN
		END

		/* loop until we find a free tran no*/
	END
END'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'-- Stored Procedure

ALTER PROCEDURE [dbo].[sptInvoiceInsert]
	@CompanyKey int,
	@ClientKey int,
	@ContactName Varchar(100),
	@PrimaryContactKey int,
	@AddressKey int,
	@AdvanceBill tinyint,
	@InvoiceNumber varchar(35),
	@InvoiceDate smalldatetime,
	@DueDate smalldatetime,
	@PostingDate smalldatetime,
	@TermsKey int,
	@ARAccountKey int,
	@ClassKey int,
	@ProjectKey int,
	@HeaderComment nvarchar(max),
	@SalesTaxKey int,
	@SalesTax2Key int,
	@InvoiceTemplateKey int,
	@ApprovedByKey int,
	@UserDefined1 varchar(250),
	@UserDefined2 varchar(250),
	@UserDefined3 varchar(250),
	@UserDefined4 varchar(250),
	@UserDefined5 varchar(250),
	@UserDefined6 varchar(250),
	@UserDefined7 varchar(250),
	@UserDefined8 varchar(250),
	@UserDefined9 varchar(250),
	@UserDefined10 varchar(250),
	@Downloaded tinyint,
	@Printed tinyint,
	@ParentInvoice tinyint,
	@Emailed tinyint,
	@CreatedByKey INT,
	@GLCompanyKey INT = NULL,
    @OfficeKey INT = NULL,    
    @OpeningTransaction tinyint = 0,
    @LayoutKey int = NULL,
	@CurrencyID varchar(10) = null,
    @ExchangeRate decimal(14,7) = 1, -- pass exchange rate
	@RequestExchangeRate int = 0, -- or request to get it for you
	@IsForRetainer tinyint = 0,
	@LiabilityAccountKey int = NULL,
    @oIdentity INT OUTPUT
AS --Encrypt

/*
|| When     Who Rel   What
|| 10/11/06 CRG 8.35  Added Emailed column.
|| 06/21/07 GHL 8.5   Added GLCompanyKey + OfficeKey
|| 10/22/07 CRG 8.5   (13583) Added logic for projects with Split Billing
|| 01/18/08 GHL 8.502 Removed all project locking in UI, but added validation here 
|| 06/18/08 GHL 8.513 Added OpeningTransaction
|| 03/24/10 GHL 10.521 Added LayoutKey
|| 09/12/12 GHL 10.560 Added pulling of AlternatePayerKey from the client
|| 10/01/13 GHL 10.673 Added currency and rate to support multi currency
|| 01/03/14 WDF 10.576 (188500) Added CreatedByKey and DateCreated
|| 02/22/15 GHL 10.589 (245992) When billing by client, get the approver from the AE on the client
||                      if Default Approver = AE From Project
|| 08/05/15 KMC 10.595 (264823) Added parameter to sptInvoiceInsert for when call is coming from Retainer process
|| 04/18/18 GWG 18.5   Added protection against posting date having time on it.
|| 04/17/20 AMP 20.050 (510663) Changed the HeaderComment to varch(max) to prevent Invoice Comments from being cutoff. 
|| 06/16/20 GHL 20.070 (451878) Added GL company currency info. Since sptInvoiceInsert is used by mass billing, GLCExchangeRate is not passed in
||                     and is calculated here + nvarchar @HeaderComment
|| 07/08/21 GHL 21.080 (566359) Added support for Project Manager as approver (linked to 543392)
|| 10/23/25 MCM 25.11.x (656423) Added Liability Account Key
|| 04/09/26 AMP 26.05.17 (718171) Added an Advance Bill Prefix option that will be used if set in preferences
|| 05/13/26 RLS 26.06.14 (725399) Added IF @ApproverPref = 5
*/

DECLARE @Error INT

 IF EXISTS(
  SELECT 
   *
  FROM 
   tInvoice (nolock)
  WHERE
   CompanyKey = @CompanyKey AND
   InvoiceNumber = @InvoiceNumber)
 BEGIN
  SELECT @oIdentity = 0
  RETURN 0
 END

	DECLARE @RetVal	INTEGER
			,@NextTranNo VARCHAR(100)
			,@InvoiceNumberRequired INT
			,@UseGLCompany INT
			,@ProjectGLCompanyKey INT

-- DefaultARApprover/ApproverDef 
-- 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

Declare @Status smallint, @ApproverPref smallint, @SetInvoiceNumberOnApproval tinyint, @DefaultApprover int
       ,@AlternatePayerKey int

Select @ApproverPref = ISNULL(DefaultARApprover, 0) 
      ,@SetInvoiceNumberOnApproval = ISNULL(SetInvoiceNumberOnApproval, 0)
      ,@DefaultApprover = ISNULL(DefaultARApproverKey, 0)
	  ,@UseGLCompany = ISNULL(UseGLCompany, 0)	
from tPreference (NOLOCK) 
Where CompanyKey = @CompanyKey

Declare @AE int -- Account Manager
Declare @PM int -- Project Manager

select @Status = 1

IF @IsForRetainer = 0
BEGIN
	--If it is for a retainer, then just use the ApprovedByKey passed in, which is specified on the retainer
	IF @ApproverPref = 1
	BEGIN 
		IF ISNULL(@ProjectKey, 0) > 0
		BEGIN
			Select @AE = ISNULL(AccountManager, 0) from tProject (nolock) Where ProjectKey = @ProjectKey
			if @AE > 0
				Select @ApprovedByKey = @AE
		END
		ELSE
		BEGIN
			Select @AE = ISNULL(AccountManagerKey, 0) from tCompany (nolock) Where CompanyKey = @ClientKey
			if @AE > 0
				Select @ApprovedByKey = @AE
		END
	END

	IF @ApproverPref = 4
	BEGIN 
		IF ISNULL(@ProjectKey, 0) > 0
		BEGIN
			Select @PM = ISNULL(ProjectManager, 0) from tProject (nolock) Where ProjectKey = @ProjectKey
			if @PM > 0
				Select @ApprovedByKey = @PM
		END
	END
	IF @ApproverPref = 5
	BEGIN 
		IF ISNULL(@ProjectKey, 0) > 0
		BEGIN
			Select @PM = ISNULL(BillingManagerKey, 0) from tProject (nolock) Where ProjectKey = @ProjectKey
			if @PM > 0
				Select @ApprovedByKey = @PM

		END
		ELSE
		BEGIN
			Select @PM = ISNULL(BillingManagerKey, 0) from tCompany (nolock) Where CompanyKey = @ClientKey
			if @PM > 0
				Select @ApprovedByKey = @PM
		END
	END
END

if @ApproverPref = 2
	Select @Status = 4

IF @IsForRetainer = 0
BEGIN
	--If it is for a retainer, then just use the ApprovedByKey passed in, which is specified on the retainer
	if @ApproverPref = 3 AND @DefaultApprover > 0
		Select @ApprovedByKey = @DefaultApprover
END

-- Only case when Invoice Number is not required
If @SetInvoiceNumberOnApproval = 1 And @ApproverPref <> 2
	Select @InvoiceNumberRequired = 0
Else
	Select @InvoiceNumberRequired = 1

 IF @InvoiceNumberRequired = 1
 BEGIN			
	-- Get the next number
	IF @InvoiceNumber IS NULL OR @InvoiceNumber = ''''
	BEGIN
		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
	ELSE
			SELECT @NextTranNo = @InvoiceNumber

		-- At this time, do not worry about InvoiceDate, PostingDate, DueDate
		-- Should be handled by UI, can be null now
		-- sptInvoiceChangeStatus will take care of nulls during approval	
END

ELSE
	-- Invoice Number not required
	-- Take null or what user gives us
	SELECT @NextTranNo = @InvoiceNumber

IF @GLCompanyKey = 0
	SELECT @GLCompanyKey = NULL
IF @OfficeKey = 0
	SELECT @OfficeKey = NULL
IF @ClassKey = 0
	SELECT @ClassKey = NULL	
IF @ProjectKey = 0
	SELECT @ProjectKey = NULL	

IF @UseGLCompany = 1 AND @ProjectKey IS NOT NULL
BEGIN
	SELECT @ProjectGLCompanyKey = GLCompanyKey
	FROM   tProject (NOLOCK)
	WHERE  ProjectKey = @ProjectKey

	IF ISNULL(@ProjectGLCompanyKey, 0) <> ISNULL(@GLCompanyKey, 0)
		RETURN -2

END

SELECT @AlternatePayerKey = AlternatePayerKey FROM tCompany (nolock) WHERE CompanyKey = @ClientKey

 -- Now multi currency
DECLARE @MultiCurrency int
DECLARE @RateHistory int
DECLARE @GLCCurrencyID varchar(10)
DECLARE @GLCExchangeRate decimal(24,7)

select @MultiCurrency = isnull(MultiCurrency, 0) from tPreference (nolock) where CompanyKey = @CompanyKey

if @MultiCurrency = 0
begin
	select @CurrencyID = null 
		  ,@ExchangeRate = 1
		  ,@GLCExchangeRate = 1
end
else 
begin
	if isnull(@CurrencyID, '''') = ''''
		select @CurrencyID = null -- no empty string
			  ,@ExchangeRate = 1

	-- get the exchange rate for day/gl comp/curr if requested
	if @RequestExchangeRate = 1 and isnull(@CurrencyID, '''') <> ''''
		exec sptCurrencyGetRate @CompanyKey, @GLCompanyKey, @CurrencyID, @InvoiceDate, @ExchangeRate output, @RateHistory output

	if isnull(@ExchangeRate, 0) <=0
		select @ExchangeRate = 1

	select @GLCCurrencyID = CurrencyID
	from   tGLCompany (nolock)
	where  GLCompanyKey = @GLCompanyKey 

	select @GLCExchangeRate = 1

	if isnull(@GLCCurrencyID, '''') = ''''
		select @GLCExchangeRate = @ExchangeRate
	else
	begin
		if @RequestExchangeRate = 1
			exec sptCurrencyGetRateToCurrency @CompanyKey, @GLCompanyKey, @CurrencyID, @GLCCurrencyID, @InvoiceDate, @GLCExchangeRate output, @RateHistory output
	end
end

 INSERT tInvoice
  (
	CompanyKey,
	ClientKey,
	ContactName,
	PrimaryContactKey,
	AddressKey,
	AdvanceBill,
	InvoiceNumber,
	InvoiceDate,
	DueDate,
	PostingDate,
	TermsKey,
	ARAccountKey,
	ClassKey,
	ProjectKey,
	InvoiceStatus,
	HeaderComment,
	SalesTaxKey,
	SalesTax2Key,
	SalesTaxAmount,
	TotalNonTaxAmount,
	InvoiceTotalAmount,
	InvoiceTemplateKey,
	ApprovedByKey,
	UserDefined1,
	UserDefined2,
	UserDefined3,
	UserDefined4,
	UserDefined5,
	UserDefined6,
	UserDefined7,
	UserDefined8,
	UserDefined9,
	UserDefined10,
	Downloaded,
	Printed,
	ParentInvoice,
	Emailed,
	GLCompanyKey,
	OfficeKey,
	OpeningTransaction,
	LayoutKey,
	AlternatePayerKey,
	CurrencyID,
	ExchangeRate,
	CreatedByKey,
	DateCreated,
	GLCCurrencyID,
	GLCExchangeRate,
	LiabilityAccountKey
  )
 VALUES
  (
	@CompanyKey,
	@ClientKey,
	@ContactName,
	@PrimaryContactKey,
	@AddressKey,
	@AdvanceBill,
	RTRIM(LTRIM(@NextTranNo)),
	dbo.fFormatDateNoTime(@InvoiceDate),
	@DueDate,
	dbo.fFormatDateNoTime(@PostingDate),
	@TermsKey,
	@ARAccountKey,
	@ClassKey,
	@ProjectKey,
	@Status,  -- Not sent for approval
	@HeaderComment,
	@SalesTaxKey,
	@SalesTax2Key,
	0,	-- SalesTaxAmount,
	0,	-- TotalNonTaxAmount,
	0,		-- InvoiceTotalAmount
	@InvoiceTemplateKey,
	@ApprovedByKey,
	@UserDefined1,
	@UserDefined2,
	@UserDefined3,
	@UserDefined4,
	@UserDefined5,
	@UserDefined6,
	@UserDefined7,
	@UserDefined8,
	@UserDefined9,
	@UserDefined10,
	@Downloaded,
	@Printed,
	@ParentInvoice,
	@Emailed,
	@GLCompanyKey,
	@OfficeKey,
	@OpeningTransaction,
	@LayoutKey,
	@AlternatePayerKey,
	@CurrencyID,
	@ExchangeRate,
	@CreatedByKey,
	GETDATE(),
	@GLCCurrencyID,
	@GLCExchangeRate,
	@LiabilityAccountKey
  )

 SELECT @oIdentity = @@IDENTITY
       ,@Error = @@ERROR

 IF @Error <> 0
	RETURN -2

 if ISNULL(@ProjectKey, 0) > 0
 BEGIN
	DECLARE	@SplitBilling tinyint,
			@ProjectSplitBillingKey int,
			@PercentageSplit decimal(24,4)

	SELECT	@SplitBilling = SplitBilling
	FROM	tPreference (nolock)
	WHERE	CompanyKey = @CompanyKey

	IF @SplitBilling = 1
	BEGIN
		IF EXISTS
				(SELECT	NULL
				FROM	tProjectSplitBilling (nolock)
				WHERE	ProjectKey = @ProjectKey)
		BEGIN
			SELECT	@ProjectSplitBillingKey = 0
			Update tInvoice Set ParentInvoice = 1 Where InvoiceKey = @oIdentity

			WHILE (1=1)
			BEGIN
				SELECT	@ProjectSplitBillingKey = MIN(ProjectSplitBillingKey)
				FROM	tProjectSplitBilling (nolock)
				WHERE	ProjectKey = @ProjectKey
				AND		ProjectSplitBillingKey > @ProjectSplitBillingKey

				IF @ProjectSplitBillingKey IS NULL
					BREAK

				SELECT	@ClientKey = ClientKey,
						@PercentageSplit = PercentageSplit
				FROM	tProjectSplitBilling (nolock)
				WHERE	ProjectSplitBillingKey = @ProjectSplitBillingKey

				EXEC @Error = sptInvoiceInsertSplit @oIdentity, @ClientKey, @PercentageSplit

				IF @Error < 0
					RETURN @Error
			END
		END
	END			
END

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 	
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
 */

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
	*/
	if @Rollup = 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
	*/
	if @InvoiceBy in (4, 5)
	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].[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
*/


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)'')


-- 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 (126,  0, 0, ''recurringTasks'', ''Recurring Tasks'', ''This will allow you to set up recurring tasks on the project schedule.'', '''')

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'')

-- 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.'', '''')

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.'', '''')

--  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.'', '''')

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.'', '''')

-- active plat betas   **************   Next Key: 131  *****************  exec spConvertAppSeed 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spGLPostCheck]'
GO
IF OBJECT_ID(N'[dbo].[spGLPostCheck]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spGLPostCheck]

	(
		@CompanyKey int
		,@CheckKey int
		,@UserKey int -- Used to report the Posted By user
		,@Prepost int = 0		-- Can be used by Preposting as well, Preposting does not validate GL accounts 
		,@CreateTemp int = 1	-- In some cases (PrePost) do not create temp table
	)

AS --Encrypt

  /*
  || When     Who Rel   What
  || 02/21/07 GHL 8.4   Added protection against double postings 
  || 04/05/07 GHL 8.4   Added another protection against double postings. Bug 8799.    
  || 04/05/07 GHL 8.4   Changed memo to ''Reference #'' instead of ''Check #'' because receipts can be cash or card 
  ||                    Bug 8818        
  || 06/19/07 GHL 8.5   Modifications for GLCompanyKey, OfficeKey, DepartmentKey + complete rework
  || 09/17/07 GHL 8.5   Added overhead (more)
  || 10/06/07 GWG 8.5   Fixed posting side for the receipt
  || 02/07/08 GWG 8.53  Changed posting of the lines so that it does not take into account prepays
  || 03/05/08 GHL 8.505 (22514) Removed validation of GL Closing Date when preposting   
  || 06/18/08 GHL 8.513 Added logic for OpeningTransaction
  || 02/26/09 GHL 10.019 Added cash basis process
  || 07/15/11 GWG 10.546 Added a check to make sure posting date does not have a time component
  || 03/27/12 GHL 10.554 Made changes for ICT 
  || 06/27/12 GHL 10.557  Added separate errors for header and line gl accounts
  || 07/03/12 GHL 10.557  Removed call to spGLPostICTCreateDTDF (cash basis) and added to cash basis function
  || 07/03/12 GHL 10.557  Added tTransaction.ICTGLCompanyKey
  || 09/28/12 RLB 10.560  Add MultiCompanyGLClosingDate preference check
  || 01/22/13 GHL 10.564 (164475) Added error @kErrICTBlankGLAccount = -103 as a last defense protection
  ||                     against null gl accounts linked to ICT
  || 02/15/13 GHL 10.565 TrackCash = 1 now 
  || 06/24/13 GHL 10.569 (182080) Using now #tTransaction.GPFlag (general purpose flag) to validate missing offices and depts 
  ||                      This is why I execute sptGLValidatePostTemp before exiting in case of preposting
  || 08/05/13 GHL 10.571 Added Multi Currency stuff
  || 10/28/13 GHL 10.573 (194612) Cannot post a receipt if there are unposted applied invoices with OpeningTransaction = 1
  || 05/31/16 GHL 10.604 (302066) Resetting correct memo for ICT recs (was picking up incorrect MC one)
  || 09/18/19 MFT 19.100 (479413) Delete items from tGLAccountRecDetail if does not include full Deposit
  || 10/31/19 GHL 19.110 (455860) Allow to receive with a bank account of a different currency
  || 06/23/20 GHL 20.070 (451878) Changes for GL companies with different currency 
  || 11/09/20 GHL 20.120 (516678) Added support for bank fees
  || 02/16/23 AMP 23.030 (630382) Added @UserKey to be able to report on the user that Posted the transaction
  || 05/27/26 MFT 26.060 (729536) Changed SP execs to name/value; Don''t reset @DepositKey on each exec, just push explicit NULL
  */
  
	-- Bypass cash basis process or not
	DECLARE @TrackCash INT SELECT @TrackCash = 1
	
	IF @CreateTemp = 1
	BEGIN
		CREATE TABLE #tTransaction (
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL,
			ICTGLCompanyKey int null,
			
			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,
 
 			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null, 

			ICTExchangeRate decimal(24,7) null, -- this is to be used by spGLPostICTCreateCurrencyDTDF
			ICTGLCExchangeRate decimal(24,7) null	-- contains the current rate on payments instead of rate to reverse out

			-- our work space
			,GLValid int null
			,GLAccountErrRet int null
			,GPFlag int null -- General purpose flag
			
			,TempTranLineKey int IDENTITY(1,1) NOT NULL
			)	 
	END

	CREATE TABLE #tCashTransactionLine (
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL,
			
			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,

			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null,

			AdvBillAmount money NULL,
			PrepaymentAmount money NULL,
			ReceiptAmount money NULL,
			
			TempTranLineKey int NULL
			)	 
			
	CREATE TABLE #tInvoiceAdvanceBillSale (
		InvoiceKey int null
		,AdvBillInvoiceKey int null
		,CashTransactionLineKey int null
		,Amount money null
		,TempTranLineKey int NULL
		)	
		
-- Register all constants
DECLARE @kErrInvalidHeaderAcct INT				SELECT @kErrInvalidHeaderAcct = -1
DECLARE @kErrInvalidLineAcct INT				SELECT @kErrInvalidLineAcct = -2
DECLARE @kErrInvalidPrePayAcct INT				SELECT @kErrInvalidPrePayAcct = -3
DECLARE @kErrInvalidFeeAcct INT					SELECT @kErrInvalidFeeAcct = -4

DECLARE @kErrInvalidRoundingDiffAcct int		SELECT @kErrInvalidRoundingDiffAcct = -350
DECLARE @kErrInvalidRealizedGainAcct int		SELECT @kErrInvalidRealizedGainAcct = -351

DECLARE @kErrGLClosedDate INT					SELECT @kErrGLClosedDate = -100
DECLARE @kErrPosted INT							SELECT @kErrPosted = -101
DECLARE @kErrBalance INT						SELECT @kErrBalance = -102
DECLARE @kErrICTBlankGLAccount INT				SELECT @kErrICTBlankGLAccount = -103
DECLARE @kErrInvoiceOpeningTransaction INT      SELECT @kErrInvoiceOpeningTransaction = -104
DECLARE @kErrMissingDeptOffice INT				SELECT @kErrMissingDeptOffice = -105
DECLARE @kErrUnexpected INT						SELECT @kErrUnexpected = -1000

-- Also declared in spGLPostInvoice
DECLARE @kSectionHeader int						SELECT @kSectionHeader = 1
DECLARE @kSectionLine int						SELECT @kSectionLine = 2
DECLARE @kSectionPrepayments int				SELECT @kSectionPrepayments = 3
DECLARE @kSectionPrebillAccruals int			SELECT @kSectionPrebillAccruals = 4
DECLARE @kSectionSalesTax int					SELECT @kSectionSalesTax = 5
DECLARE @kSectionWIP int						SELECT @kSectionWIP = 6
DECLARE @kSectionVoucherCC int					SELECT @kSectionVoucherCC = 7
DECLARE @kSectionICT int						SELECT @kSectionICT = 8
DECLARE @kSectionMCRounding int					SELECT @kSectionMCRounding = 9
DECLARE @kSectionMCGain int						SELECT @kSectionMCGain = 10

DECLARE @kMemoRealizedGain VARCHAR(100)			SELECT @kMemoRealizedGain = ''Multi Currency Realized Gain/Loss ''
DECLARE @kMemoMCRounding VARCHAR(100)			SELECT @kMemoMCRounding = ''Multi Currency Rounding Diff ''

-- Vars for tPreference
Declare @PostToGL tinyint
Declare @RequireAccounts tinyint
Declare @RequireDepartment tinyint
Declare @RequireOffice tinyint
Declare @GLClosedDate smalldatetime
Declare @Customizations varchar(1000)
Declare @UseMultiCompanyGLCloseDate tinyint
Declare @MultiCurrency int
Declare @RoundingDiffAccountKey int
Declare @RealizedGainAccountKey int 
Declare @FeeAccountKey int

-- Vars for check/receipt info
Declare @CashAccountKey int
Declare @PrepayAccountKey int
Declare @CheckAmount money
Declare @AppliedAmount money
Declare @PrepayAmount money
Declare @ReferenceNumber varchar(100)
Declare @Amount money
Declare @Posted tinyint
Declare @OpeningTransaction tinyint
Declare @CurrencyID varchar(10)					-- currency of the payment
Declare @ExchangeRate decimal(24,7)				-- Exchange rate to convert payment amounts to the main home currency
Declare @FeeAmount money
Declare @FeeDepartmentKey int
Declare @FeeOfficeKey int

-- Vars for the payments in other currencies
Declare @CashAmount money
Declare @CashCurrencyID varchar(10)				-- currency of the bank account
Declare @CashExchangeRate decimal(24,7)			-- Exchange rate to convert CASH amounts to the main home currency

-- Vars for GL companies with different currencies
Declare @GLCCurrencyID varchar(10)				-- Currency of the GL company
Declare @GLCExchangeRate decimal(24,7)			-- Exchange rate to convert payment amounts to currency of the GL company 
Declare @CashGLCExchangeRate decimal(24,7)		-- Exchange rate to convert CASH amounts to currency of the GL company

-- Vars for GL tran
DECLARE @TransactionDate smalldatetime
		,@Entity VARCHAR(50)
		,@EntityKey INT
		,@Reference VARCHAR(100)
		,@GLAccountKey INT
		,@ClassKey int
		,@Memo varchar(500)
		,@PostSide char(1)
		,@ClientKey int
		,@ProjectKey int
		,@SourceCompanyKey INT
		,@DepositKey INT
		,@GLCompanyKey INT
		,@OfficeKey INT
		,@DepartmentKey INT
		,@DetailLineKey INT
		,@Section INT
		,@GLAccountErrRet INT
		,@RetVal INT
		,@TransactionCount INT
 		 
	Select
		@RequireAccounts = ISNULL(RequireGLAccounts, 0)
		,@RequireDepartment = ISNULL(RequireDepartment,0)
		,@RequireOffice = ISNULL(RequireOffice,0)
		,@PostToGL = ISNULL(PostToGL, 0)
		,@GLClosedDate = GLClosedDate
		,@Customizations = ISNULL(Customizations, '''')
		,@UseMultiCompanyGLCloseDate = ISNULL(MultiCompanyClosingDate, 0)
		,@MultiCurrency = ISNULL(MultiCurrency, 0)
		,@RoundingDiffAccountKey = RoundingDiffAccountKey
		,@RealizedGainAccountKey = RealizedGainAccountKey  
		,@FeeAccountKey = FeeAccountKey
	From
		tPreference (nolock)
	Where
		CompanyKey = @CompanyKey

				
	Select
		@GLCompanyKey = GLCompanyKey
		,@ClientKey = ClientKey
		,@CheckAmount = ISNULL(CheckAmount, 0)
		,@TransactionDate = dbo.fFormatDateNoTime(PostingDate)
		,@ReferenceNumber = ReferenceNumber
		,@CashAccountKey = CashAccountKey
		,@PrepayAccountKey = PrepayAccountKey
		,@ClassKey = ClassKey
		,@DepositKey = DepositKey
		,@Posted = Posted
		,@ProjectKey = NULL
		,@OpeningTransaction = ISNULL(OpeningTransaction, 0)
		,@CurrencyID = CurrencyID
		,@ExchangeRate = isnull(ExchangeRate, 1)

		-- for the bank accounts with different currencies
		,@CashCurrencyID = CashCurrencyID
		,@CashExchangeRate = isnull(CashExchangeRate, 1)
		,@CashAmount = CashAmount

		-- for the GL companies with different currencies
		,@GLCCurrencyID = GLCCurrencyID
		,@GLCExchangeRate = isnull(GLCExchangeRate, 1)
		,@CashGLCExchangeRate = isnull(CashGLCExchangeRate, 1)

		,@FeeAmount = isnull(FeeAmount,0)
		,@FeeDepartmentKey = FeeDepartmentKey
		,@FeeOfficeKey = FeeOfficeKey

	from tCheck (nolock)
	Where CheckKey = @CheckKey

	-- if the GL company currency is null, the currency is the home currency 
	if @GLCCurrencyID is null
		select @GLCExchangeRate = @ExchangeRate
		      ,@CashGLCExchangeRate = @CashExchangeRate

	--select @GLCExchangeRate as GLCExchangeRate, @CashGLCExchangeRate as CashGLCExchangeRate 

	if @UseMultiCompanyGLCloseDate = 1 And ISNULL(@GLCompanyKey, 0) > 0
	BEGIN
		Select 
			@GLClosedDate = GLCloseDate
		From 
			tGLCompany (nolock)
		Where
			GLCompanyKey = @GLCompanyKey			

	END

	Select @AppliedAmount = ISNULL(sum(Amount), 0) 
	from tCheckAppl (nolock) 
	where CheckKey = @CheckKey 
	and Prepay = 0
	Select @PrepayAmount = @CheckAmount - @AppliedAmount
		
	if @Posted = 1
		return @kErrPosted
		
	if @OpeningTransaction = 1
		Select @PostToGL = 0	

	If @PostToGL = 0 And @RequireAccounts = 0 And @Prepost = 0
	Begin
		Update tCheck
		Set Posted = 1
		Where CheckKey = @CheckKey
		
		return 1
	End
		
	-- Can not post before gl close date
	if @Prepost = 0 and not @GLClosedDate is null
		if @GLClosedDate > @TransactionDate
			return @kErrGLClosedDate

	-- cannot post if there exists invoices applied with OpeningTransaction = 1 which are unposted
	-- the reason is they are posted temporarily against AR instead of the sales accounts when posting the receipt
	-- The receipt should be reposted when posting the invoice (this is what happens normally) but this will not be done
	-- because the invoice has OpeningTransaction = 1 i.e. nothing happens, leaving the invoice posted permanently to AR
	-- so error out now
	if exists  (select 1 
				from tCheckAppl ca (nolock)
				inner join tInvoice i (nolock) on ca.InvoiceKey = i.InvoiceKey
				where ca.CheckKey = @CheckKey
				and   i.OpeningTransaction = 1
				and   i.Posted = 0)
		return @kErrInvoiceOpeningTransaction 

	--EXEC @TrackCash = sptCashEnableCashBasis @CompanyKey, @Customizations

	-- for the bank fee expense amount, we need to test if dept and office exist 
	if @FeeAmount <> 0 and isnull(@FeeDepartmentKey,0) = 0 and @RequireDepartment = 1
		return @kErrMissingDeptOffice
	if @FeeAmount <> 0 and isnull(@FeeOfficeKey,0) = 0 and @RequireOffice = 1
		return @kErrMissingDeptOffice

	-- These should not change
	Select	@Entity = ''RECEIPT''
			,@EntityKey = @CheckKey
			,@Reference = @ReferenceNumber
			,@Memo = ''Reference # '' + @ReferenceNumber
			,@SourceCompanyKey = @ClientKey			
	-- TransactionDate, ProjectKey, GLCompanyKey, ClassKey, ClientKey already set
	
	/*
	* Insert the header Amount
	*/
	
	SELECT @PostSide = ''D''
		  ,@GLAccountKey = @CashAccountKey
		  ,@GLAccountErrRet = @kErrInvalidHeaderAcct 
		  ,@Amount = @CheckAmount, @Section = @kSectionHeader 
		  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
		
	if @CashAmount is not null and isnull(@CurrencyID, '''') != isnull(@CashCurrencyID, '''') 
		EXEC spGLInsertTranTemp
			@CompanyKey       = @CompanyKey,
			@PostSide         = @PostSide,
			@TransactionDate  = @TransactionDate,
			@Entity           = @Entity,
			@EntityKey        = @EntityKey,
			@Reference        = @Reference,
			@GLAccountKey     = @GLAccountKey,
			@Amount           = @CashAmount,
			@ClassKey         = @ClassKey,
			@Memo             = @Memo,
			@ClientKey        = @ClientKey,
			@ProjectKey       = @ProjectKey,
			@SourceCompanyKey = @SourceCompanyKey,
			@DepositKey       = @DepositKey,
			@GLCompanyKey     = @GLCompanyKey,
			@OfficeKey        = @OfficeKey,
			@DepartmentKey    = @DepartmentKey,
			@DetailLineKey    = @DetailLineKey,
			@Section          = @Section,
			@GLAccountErrRet  = @GLAccountErrRet,
			@CurrencyID       = @CashCurrencyID,
			@ExchangeRate     = @CashExchangeRate,
			@GLCCurrencyID    = @GLCCurrencyID,
			@GLCExchangeRate  = @CashGLCExchangeRate
	else
		EXEC spGLInsertTranTemp
			@CompanyKey       = @CompanyKey,
			@PostSide         = @PostSide,
			@TransactionDate  = @TransactionDate,
			@Entity           = @Entity,
			@EntityKey        = @EntityKey,
			@Reference        = @Reference,
			@GLAccountKey     = @GLAccountKey,
			@Amount           = @Amount,
			@ClassKey         = @ClassKey,
			@Memo             = @Memo,
			@ClientKey        = @ClientKey,
			@ProjectKey       = @ProjectKey,
			@SourceCompanyKey = @SourceCompanyKey,
			@DepositKey       = @DepositKey,
			@GLCompanyKey     = @GLCompanyKey,
			@OfficeKey        = @OfficeKey,
			@DepartmentKey    = @DepartmentKey,
			@DetailLineKey    = @DetailLineKey,
			@Section          = @Section,
			@GLAccountErrRet  = @GLAccountErrRet,
			@CurrencyID       = @CurrencyID,
			@ExchangeRate     = @ExchangeRate,
			@GLCCurrencyID    = @GLCCurrencyID,
			@GLCExchangeRate  = @GLCExchangeRate

	/*
	* Insert the prepayed amount if there is one
	*/
	
	if ISNULL(@PrepayAmount, 0) <> 0
	Begin
		SELECT @PostSide = ''C''
		      ,@GLAccountKey = @PrepayAccountKey
			  ,@GLAccountErrRet = @kErrInvalidPrePayAcct 
			  ,@Amount = @PrepayAmount, @Section = @kSectionHeader 
			  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
			  		
		EXEC spGLInsertTranTemp
			@CompanyKey       = @CompanyKey,
			@PostSide         = @PostSide,
			@TransactionDate  = @TransactionDate,
			@Entity           = @Entity,
			@EntityKey        = @EntityKey,
			@Reference        = @Reference,
			@GLAccountKey     = @GLAccountKey,
			@Amount           = @Amount,
			@ClassKey         = @ClassKey,
			@Memo             = @Memo,
			@ClientKey        = @ClientKey,
			@ProjectKey       = @ProjectKey,
			@SourceCompanyKey = @SourceCompanyKey,
			@DepositKey       = NULL,
			@GLCompanyKey     = @GLCompanyKey,
			@OfficeKey        = @OfficeKey,
			@DepartmentKey    = @DepartmentKey,
			@DetailLineKey    = @DetailLineKey,
			@Section          = @Section,
			@GLAccountErrRet  = @GLAccountErrRet,
			@CurrencyID       = @CurrencyID,
			@ExchangeRate     = @ExchangeRate,
			@GLCCurrencyID    = @GLCCurrencyID,
			@GLCExchangeRate  = @GLCExchangeRate

	End
	

		/*
	* Insert the fee amount if there is one
	*/
	
	if ISNULL(@FeeAmount, 0) <> 0
	Begin
		-- This is a mini JE where we reduce the amount on the cash account and debit the bank fee expense account 
		
		-- this will reduce the cash amount
		SELECT @PostSide = ''C'' 
		  ,@GLAccountKey = @CashAccountKey
		  ,@GLAccountErrRet = @kErrInvalidHeaderAcct 
		  ,@Amount = @FeeAmount, @Section = @kSectionHeader 
		  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
		
		if @CashAmount is not null and isnull(@CurrencyID, '''') != isnull(@CashCurrencyID, '''') 
		begin
			-- convert FeeAmount from amount in check currency to amount in the currency of the cash/bank account 
			-- see design doc on cash account with different currency for that conversion
			select @Amount = round((@FeeAmount * @ExchangeRate) / @CashExchangeRate, 2)

			EXEC spGLInsertTranTemp
				@CompanyKey       = @CompanyKey,
				@PostSide         = @PostSide,
				@TransactionDate  = @TransactionDate,
				@Entity           = @Entity,
				@EntityKey        = @EntityKey,
				@Reference        = @Reference,
				@GLAccountKey     = @GLAccountKey,
				@Amount           = @Amount,
				@ClassKey         = @ClassKey,
				@Memo             = @Memo,
				@ClientKey        = @ClientKey,
				@ProjectKey       = @ProjectKey,
				@SourceCompanyKey = @SourceCompanyKey,
				@DepositKey       = @DepositKey,
				@GLCompanyKey     = @GLCompanyKey,
				@OfficeKey        = @OfficeKey,
				@DepartmentKey    = @DepartmentKey,
				@DetailLineKey    = @DetailLineKey,
				@Section          = @Section,
				@GLAccountErrRet  = @GLAccountErrRet,
				@CurrencyID       = @CashCurrencyID,
				@ExchangeRate     = @CashExchangeRate,
				@GLCCurrencyID    = @GLCCurrencyID,
				@GLCExchangeRate  = @CashGLCExchangeRate
		end
		else
			EXEC spGLInsertTranTemp
				@CompanyKey       = @CompanyKey,
				@PostSide         = @PostSide,
				@TransactionDate  = @TransactionDate,
				@Entity           = @Entity,
				@EntityKey        = @EntityKey,
				@Reference        = @Reference,
				@GLAccountKey     = @GLAccountKey,
				@Amount           = @Amount,
				@ClassKey         = @ClassKey,
				@Memo             = @Memo,
				@ClientKey        = @ClientKey,
				@ProjectKey       = @ProjectKey,
				@SourceCompanyKey = @SourceCompanyKey,
				@DepositKey       = @DepositKey,
				@GLCompanyKey     = @GLCompanyKey,
				@OfficeKey        = @OfficeKey,
				@DepartmentKey    = @DepartmentKey,
				@DetailLineKey    = @DetailLineKey,
				@Section          = @Section,
				@GLAccountErrRet  = @GLAccountErrRet,
				@CurrencyID       = @CurrencyID,
				@ExchangeRate     = @ExchangeRate,
				@GLCCurrencyID    = @GLCCurrencyID,
				@GLCExchangeRate  = @GLCExchangeRate

		-- now debit the Fee account key
		SELECT @PostSide = ''D''
		      ,@GLAccountKey = @FeeAccountKey
			  ,@GLAccountErrRet = @kErrInvalidFeeAcct  
			  ,@Amount = @FeeAmount, @Section = @kSectionHeader  
			  ,@OfficeKey = @FeeOfficeKey, @DepartmentKey = @FeeDepartmentKey, @DetailLineKey = NULL
			  		
		EXEC spGLInsertTranTemp
			@CompanyKey       = @CompanyKey,
			@PostSide         = @PostSide,
			@TransactionDate  = @TransactionDate,
			@Entity           = @Entity,
			@EntityKey        = @EntityKey,
			@Reference        = @Reference,
			@GLAccountKey     = @GLAccountKey,
			@Amount           = @Amount,
			@ClassKey         = @ClassKey,
			@Memo             = @Memo,
			@ClientKey        = @ClientKey,
			@ProjectKey       = @ProjectKey,
			@SourceCompanyKey = @SourceCompanyKey,
			@DepositKey       = NULL,
			@GLCompanyKey     = @GLCompanyKey,
			@OfficeKey        = @OfficeKey,
			@DepartmentKey    = @DepartmentKey,
			@DetailLineKey    = @DetailLineKey,
			@Section          = @Section,
			@GLAccountErrRet  = @GLAccountErrRet,
			@CurrencyID       = @CurrencyID,
			@ExchangeRate     = @ExchangeRate,
			@GLCCurrencyID    = @GLCCurrencyID,
			@GLCExchangeRate  = @GLCExchangeRate

	End

	/*
	* Insert the lines
	*/
	
	SELECT @PostSide = ''C'', @Section = @kSectionLine, @GLAccountErrRet = @kErrInvalidLineAcct, @DepositKey = NULL 
	
	-- One entry per detail line
	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID,ExchangeRate
		,GLCCurrencyID,GLCExchangeRate,ICTExchangeRate, ICTGLCExchangeRate
		)
	
	SELECT @CompanyKey, @TransactionDate, @Entity, @EntityKey, @Reference,
		SalesAccountKey, 0, ISNULL(Amount, 0), ca.ClassKey, @Memo,
		@ClientKey, @ProjectKey, @SourceCompanyKey, @DepositKey, @PostSide
		
		-- ICT
		, case when isnull(TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else TargetGLCompanyKey end
		
		, ca.OfficeKey, DepartmentKey, CheckApplKey, @kSectionLine ,@GLAccountErrRet

		-- these curr ID and rates to reverse out will be extracted from the voucher
		,@CurrencyID,@ExchangeRate 

		-- ICT
		, case when isnull(ca.TargetGLCompanyKey, 0) = 0 --or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
		then @GLCCurrencyID else glc.CurrencyID end
		, case when isnull(ca.TargetGLCompanyKey, 0) = 0 --or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
		then @GLCExchangeRate else isnull(ca.GLCExchangeRate, 1) end

		-- this is to be used by the ICT sp, these are the new rates
		,@ExchangeRate 
		, case when isnull(ca.TargetGLCompanyKey, 0) = 0 --or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
		then @GLCExchangeRate else isnull(ca.GLCExchangeRate, 1) end

	From  tCheckAppl ca (nolock)
		left outer join tInvoice i (nolock) on ca.InvoiceKey = i.InvoiceKey
		left outer join tGLCompany glc (nolock) on ca.TargetGLCompanyKey = glc.GLCompanyKey
	Where CheckKey = @CheckKey and Prepay = 0
	
	-- now pull the exchange rate from invoices
	if @MultiCurrency = 1
	begin
		-- need to get the exchange rate for vouchers
		update #tTransaction
		set    #tTransaction.CurrencyID = i.CurrencyID
			  ,#tTransaction.ExchangeRate = isnull(i.ExchangeRate, 1)
			  ,#tTransaction.GLCCurrencyID = i.GLCCurrencyID
			  ,#tTransaction.GLCExchangeRate = isnull(i.GLCExchangeRate, 1)
		from   tCheckAppl ca (nolock)
			  ,tInvoice i (nolock) 
		where  #tTransaction.Entity = @Entity
		and    #tTransaction.EntityKey = @EntityKey
		and    #tTransaction.DetailLineKey = ca.CheckApplKey
		and    ca.InvoiceKey = i.InvoiceKey

		-- and create the realized gain/loss
		SELECT @PostSide = ''D'', @GLAccountKey = @RealizedGainAccountKey, @GLAccountErrRet = @kErrInvalidRealizedGainAcct 
			,@Memo = @kMemoRealizedGain, @Section = @kSectionMCGain    
			,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
	
	
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GPFlag, CurrencyID, ExchangeRate, HDebit, HCredit
			, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
	
		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
			@GLAccountKey, 0, 0,
			null, -- @ClassKey, null it like ICT  
			@Memo + isnull(i.InvoiceNumber, '''') ,@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
			i.GLCompanyKey,@OfficeKey,@DepartmentKey,ca.CheckApplKey,@Section,@GLAccountErrRet, 0,
			null, -- Home Currency
			1, -- Exchange Rate = 1
			Round(ca.Amount * (isnull(i.ExchangeRate, 1) - @ExchangeRate), 2) -- HDebit
			, 0 -- HCredit
			, case when isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
			then @GLCCurrencyID else glc.CurrencyID end, 
			1, -- GLC Exchange Rate = 1
			case when isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') then -- GLCDebit
			Round(ca.Amount * (isnull(i.GLCExchangeRate, 1) - @GLCExchangeRate), 2)
			else
			Round(ca.Amount * (isnull(i.GLCExchangeRate, 1) - isnull(ca.GLCExchangeRate,1)), 2)
			end,
			0 -- GLCCredit
		From   tCheckAppl ca (nolock)
			Inner Join tInvoice i (NOLOCK) ON ca.InvoiceKey = i.InvoiceKey
			Left outer Join tGLCompany glc (nolock) on i.GLCompanyKey = glc.GLCompanyKey
		Where	ca.CheckKey = @CheckKey
		And		ca.Prepay = 0
	
		-- Next flip sides to make it positive like Xero does
		update #tTransaction
		set    HDebit = -1 * HCredit
			  ,HCredit = 0
			  ,PostSide = ''D''
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(HCredit, 0) < 0 

		update #tTransaction
		set    HCredit = -1 * HDebit
			  ,HDebit = 0
			  ,PostSide = ''C''
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(HDebit, 0) < 0 

		-- do the same for the GLC Debit/Credit, do not change PostSide
		update #tTransaction
		set    GLCDebit = -1 * GLCCredit
				,GLCCredit = 0
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(GLCCredit, 0) < 0 

		update #tTransaction
		set    GLCCredit = -1 * GLCDebit
				,GLCDebit = 0
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(GLCDebit, 0) < 0 

		--1 Accrual Basis, 1 Force to Rounding account -- do this after the ICT DT DF now
		--exec spGLPostCalcRoundingDiff @CompanyKey,@Entity,@EntityKey,1,1,@GLCompanyKey,@TransactionDate,@Reference, @RoundingDiffAccountKey,@RealizedGainAccountKey 
	end

	-- Create DT and DF for ICT -- 1 Accrual Basis
	select @Memo = ''Reference # '' + @ReferenceNumber
	--exec spGLPostICTCreateDTDF @CompanyKey,@Entity,@EntityKey,1,@GLCompanyKey,@TransactionDate,@Memo,@Reference 
	exec spGLPostICTCreateCurrencyDTDF @CompanyKey,@Entity,@EntityKey,1,@GLCompanyKey,@TransactionDate,@Memo,@Reference , @GLCExchangeRate 

	if @MultiCurrency = 1
	begin
		--1 Accrual Basis, 1 Force to Rounding account
		exec spGLPostCalcRoundingDiff @CompanyKey,@Entity,@EntityKey,1,1,@GLCompanyKey,@TransactionDate,@Reference, @RoundingDiffAccountKey,@RealizedGainAccountKey,@GLCCurrencyID 
	end

	-- Correct and prepared data for final insert
	EXEC spGLPostCleanupTemp @Entity, @EntityKey, @TransactionDate 
	
	-- Exit when we are not really posting, but preposting
	--IF @Prepost = 1
	--	RETURN 1
		
	/*
	 * Validations
	 */

	
	Select @TransactionCount = COUNT(*) from #tTransaction Where Entity = @Entity and EntityKey = @EntityKey

	EXEC @RetVal = spGLValidatePostTemp @CompanyKey, @Entity, @EntityKey, @kErrBalance, @kErrPosted 

	-- Exit when we are not really posting, but preposting
	IF @Prepost = 1
		RETURN 1

	IF @RetVal <> 1
		RETURN @RetVal
	
	-- We have validated the accounts in case @RequireAccounts = 1, but stop here if PostToGL = 0 
	IF @PostToGL = 0
	BEGIN	
		Update tCheck
		Set Posted = 1
		Where CheckKey = @CheckKey
		
		RETURN 1 
	END
	
	If Exists (Select 1 From #tTransaction Where [Section] = @kSectionICT and isnull(GLAccountKey, 0) = 0)
	return @kErrICTBlankGLAccount

	--select Debit, Credit, CurrencyID, ExchangeRate, HDebit, HCredit, GLCCurrencyID
	--,GLCDebit, GLCCredit, GLCExchangeRate, * from #tTransaction
	--return

	/*
	 * Cash-Basis prep
	 */
	
	IF @TrackCash = 1 
	BEGIN
		CREATE TABLE #tCashQueue(
			Entity varchar(25) NULL,
			EntityKey int NULL,
			PostingDate smalldatetime NULL,
			QueueOrder int identity(1,1),
			PostingOrder int NULL,
			Action smallint NULL, 
			AdvanceBill int NULL
			)
	
		-- This table will track of which cash basis transactions are not valid anymore
		/*
		CREATE TABLE #tCashTransactionUnpost (
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Unpost int NULL)
		*/
		
		-- So that we get the same Entity''s collation
		SELECT Entity, EntityKey, 1 AS Unpost INTO #tCashTransactionUnpost 
		FROM tCashTransaction (NOLOCK) WHERE 1 = 2 
		
		CREATE TABLE #tCashTransaction (
			UIDCashTransactionKey uniqueidentifier null,
			
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL, 
			ICTGLCompanyKey int null,

			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,

			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null, 

			ICTExchangeRate decimal(24,7) null, -- this is to be used by spGLPostICTCreateCurrencyDTDF
			ICTGLCExchangeRate decimal(24,7) null,	-- contains the current rate on payments instead of rate to reverse out

			-- Application fields
			AEntity varchar (50) NULL ,
			AEntityKey int NULL ,
			AReference varchar (100) NULL ,
			AEntity2 varchar (50) NULL ,
			AEntity2Key int NULL ,
			AReference2 varchar (100) NULL ,
			AAmount MONEY NULL,
			LineAmount MONEY NULL,
			CashTransactionLineKey INT NULL

			-- our work space
			,GLValid int null
			,GLAccountErrRet int null
			,GPFlag int null -- General purpose flag
			
			,UpdateTranLineKey int null
			)	 
			
	Declare @PostingOrder int
	Declare @Action int Select @Action = 0 -- Posting
	Declare @CashEntity varchar(25)
	Declare @CashEntityKey varchar(25)
	Declare @CashPostingDate smalldatetime
	
	exec @RetVal = sptCashQueue @CompanyKey, @Entity, @EntityKey, @TransactionDate, @Action
	 
	INSERT #tCashTransactionUnpost (Entity, EntityKey, Unpost)
	Select Entity, EntityKey, 1
	From   #tCashQueue (NOLOCK)
	Where  Action = 1 -- UnPosting
 
	-- then post
	Select @PostingOrder = -1
	While (1=1)
	Begin
		Select @PostingOrder = MIN(PostingOrder)
		From   #tCashQueue (NOLOCK)
		Where  PostingOrder > @PostingOrder
		And    Action = 0 -- Posting
		
		If @PostingOrder is null
			break
			
		Select @CashEntity = Entity
		      ,@CashEntityKey = EntityKey
			  ,@CashPostingDate = PostingDate
		From   #tCashQueue (NOLOCK)
		Where  PostingOrder = @PostingOrder
		And    Action = 0 -- Posting
	
		If @CashEntity = ''INVOICE''
			exec @RetVal = sptCashPostInvoice @CompanyKey, @CashEntityKey
	
		If @CashEntity = ''RECEIPT''
			exec @RetVal = sptCashPostCheck @CompanyKey, @CashEntityKey
					  	
	End
	
		If Exists (Select 1 From #tCashTransaction Where [Section] = @kSectionICT and isnull(GLAccountKey, 0) = 0)
		return @kErrICTBlankGLAccount


	END -- End Track Cash
				
					
	/*
	 * Posting!!
	 */
			  		
	Begin Tran

	-- Will have to do the unposting of cash here within the transaction
	
	Update tCheck
	Set Posted = 1
	Where CheckKey = @CheckKey
	
	if @@ERROR <> 0 
	begin
		rollback tran 
		return @kErrUnexpected
	end
	
	IF NOT EXISTS (SELECT 1 FROM tTransaction (NOLOCK) WHERE Entity = @Entity AND EntityKey = @EntityKey)
	BEGIN
		INSERT tTransaction(CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, Reversed, Cleared, CurrencyID, ExchangeRate, HDebit, HCredit
		, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit, PostedByKey)
		
		SELECT CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, 0, 0, CurrencyID, ExchangeRate, HDebit, HCredit
		, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit, @UserKey	
		FROM #tTransaction 	
		WHERE Entity = @Entity AND EntityKey = @EntityKey
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END		
	END
	
	IF @TrackCash = 1 
	BEGIN
		DELETE tCashTransaction
		FROM   #tCashTransactionUnpost
		WHERE  tCashTransaction.Entity = #tCashTransactionUnpost.Entity 
		AND    tCashTransaction.EntityKey = #tCashTransactionUnpost.EntityKey
		AND    #tCashTransactionUnpost.Unpost = 1
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END
			
		INSERT tCashTransaction(CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, Reversed, Cleared
		,UIDCashTransactionKey,AEntity,AEntityKey,AReference,AEntity2,AEntity2Key,AReference2,AAmount, LineAmount,CashTransactionLineKey
		,CurrencyID, ExchangeRate, HDebit, HCredit
		, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit
		)
		
		SELECT CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, 0, 0	
		,UIDCashTransactionKey,AEntity,AEntityKey,AReference,AEntity2,AEntity2Key,AReference2,AAmount, LineAmount,CashTransactionLineKey
		,CurrencyID, ExchangeRate, HDebit, HCredit
		, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit

		FROM #tCashTransaction 	
		--WHERE Entity = @Entity AND EntityKey = @EntityKey
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END
	
	END
	
	
	-- Protect against double postings
	IF (SELECT COUNT(*) FROM tTransaction (NOLOCK) WHERE Entity = @Entity AND EntityKey = @EntityKey)
	<> @TransactionCount
	BEGIN
		ROLLBACK TRAN
		RETURN @kErrUnexpected 	
	END

	--If this Check was part of a Deposit that had other Checks AND is on an Account Rec, remove the Deposit from the Rec
	DELETE FROM tGLAccountRecDetail
	WHERE TransactionKey IN (
		SELECT ard.TransactionKey
		FROM
			tCheck c (nolock)
			INNER JOIN tDeposit d (nolock) ON c.DepositKey = d.DepositKey
			INNER JOIN tTransaction t (nolock) ON t.Entity = ''RECEIPT'' AND c.CheckKey = t.EntityKey
			INNER JOIN tGLAccountRecDetail ard (nolock) ON ard.TransactionKey = t.TransactionKey
		WHERE
			d.DepositKey = (SELECT DepositKey FROM tCheck (nolock) WHERE CheckKey = @CheckKey) AND
			c.CheckKey != @CheckKey
	)
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN @kErrUnexpected 	
	END

	commit tran
	
Return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spGLPostInvoice]'
GO
SET QUOTED_IDENTIFIER OFF
GO
IF OBJECT_ID(N'[dbo].[spGLPostInvoice]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[spGLPostInvoice]
	(
		@CompanyKey int
		,@InvoiceKey int
		,@UserKey int -- Used to report the Posted By user
		,@Prepost int = 0		-- Can be used by Preposting as well, Preposting does not validate GL accounts 
		,@CreateTemp int = 1	-- In some cases (PrePost) do not create temp table		
	)
AS --Encrypt

	SET NOCOUNT ON
	
/*
|| When     Who Rel     What
|| 02/07/07 RTC 8.403  When posting an invoice for PO lines that are billed at commission only (IO or BC),
||                     close only the individual POD line not all lines with the same LineNumber
|| 02/19/07 GHL 8.404  Wrapped the update of Posted and InvoiceStatus within the transaction
||                     To prevent double postings. Bug 8318.
|| 04/05/07 GHL 8.410  Added more protection against double postings. Bug 8799.
|| 05/02/07 GHL 8.43   Added changes for advance bill sales taxes
|| 06/13/07 GHL 8.5    Modifications for GLCompanyKey, OfficeKey, DepartmentKey + complete rework
|| 08/01/07 GHL 8.5    Corrected memo for prebill acrruals
|| 09/17/07 GHL 8.5    Added overhead
|| 12/19/07 GHL 8.5    Replaced query of vSalesGLDetail by direct queries in 5 transaction tables 
||                     Was taking too long on app/app2
|| 01/18/08 GHL 8.502  (19399) Rounding now before inserting into temp table to prevent rounding errors with splits
|| 02/07/08 GHL 8.503  (20961) Modified the way I round invoice lines detail because of persistent problems with splits
||                      Rounding the sum of details rather than summing the rounded details
|| 03/05/08 GHL 8.505  (22514) Removed validation of GL Closing Date when preposting 
|| 05/09/08 GHL 8.510  (21023) When doing the prebill accruals we must remember the GL account used
||                      It will be used during the prebill accrual reversals in spGLPostVoucher  
|| 05/14/08 GHL 8.510  (26731) Changed order of prebill accruals to eliminate rounding errors 
||                     (Detail/Debit first then Summary/Credit)
|| 06/10/08 GHL 8.513  Added a patch for rounding errors (when there is a discrepancy between the lines and the header
||                     in the case of split billing)
|| 06/18/08 GHL 8.513  Added logic for OpeningTransaction
|| 11/20/08 GHL 10.013 (40387) Modified logic for prebill accruals to allow Brothers and Co 
||                     to delete client invoices
|| 12/03/08 GHL 10.013 (41544) Had to review the way I apply the rounding error in case
||                     of split billing, it should be applied to a unique line GL transaction 
||                     instead of a GL tran for an invoice line record because we may have 
||                     several GL transactions associated to a invoice line
|| 02/03/09 GHL 10.018 Split invoice adv bill tax records by tax key to help with cash basis
||                     Also place SalesTaxKey on DetailLineKey 
|| 02/26/09 GHL 10.019 Added cash basis process
|| 03/06/09 GHL 10.020 (48426) Using now tTime.BilledService to get GLAccountKey
|| 03/27/09 GHL 10.022 (49542) Even if OpeningTransaction = 1, save cash basis prep tables
|| 04/09/09 GHL 10.223 (50761) Using now AccruedCost instead of TotalCost since we found at Third Degree
||                      many instances where TotalCost <> AccruedCost and PrebilAmount used in spGLPostVoucher
||                      is calculated from AccruedCost. This creates discrepancies between GL and accrued order report
|| 04/16/09 GHL 10.223  Added support of tTransactionOrderAccrual to help with prebilled order accruals
|| 07/20/09 GHL 10.505  (57521) Corrected source of ClassKey for MC/VC/PO (same as vSaleGLDetail)
|| 09/25/09 GHL 10.505  (61519) Post Prebill Accruals only for parent invoices (not child invoices) or reg inv
|| 09/30/09 GHL 10.5    Using now tInvoiceTax
|| 01/22/10 GHL 10.517  (72848) Getting now the office and department from POD and VD lines instead of from project on lines
||                      or items. Important when linking orders through media estimates
|| 09/16/10 GHL 10.535  Added insert in tTransactionOrderAccrual when OpeningTransaction = 1 or no posting to GL
|| 07/15/11 GWG 10.546 Added a check to make sure posting date does not have a time component
|| 03/26/12 GHL 10.554 Made changes for ICT 
||                     - read tInvoiceLine.TargetCompanyKey (will be null if not ICT)
||                     - call spGLPostCreateDTDF to create Due To/Due From GL trans (level = GLCompanyKey only)
||                     - calc taxes from tInvoiceTax (grouped by GLCompanyKey)
||                     - group accrued order by GLCompanyKey  
|| 03/29/12 GHL 10.554  Added logic for GLCompanySource
|| 06/27/12 GHL 10.557  Added separate errors for header and line gl accounts
|| 07/03/12 GHL 10.557  Removed call to spGLPostICTCreateDTDF (cash basis) and added to cash basis function
|| 07/03/12 GHL 10.557  Added tTransaction.ICTGLCompanyKey
|| 09/28/12 RLB 10.560  Add MultiCompanyGLClosingDate preference check
|| 10/21/12 GWG 10.561  Modified the posting with glcompany source. Added in the getting of class from the person.
|| 10/25/12 GHL 10.561  For line details, if PostSalesUsingDetail = 0, get the GL Company Key from the client invoice
||                      (either from il.TargetGLCompanyKey or i.GLCompanyKey)
||                      only if PostSalesUsingDetail = 1, get the GL Company Key from the transaction detail
||                      only if PostSalesUsingDetail = 1 and time/ERs, take in account p.GLCompanySource
|| 12/13/12 GHL 10.563  (161899) Insert Project in both sides of the accrual gl posting
|| 01/22/13 GHL 10.564 (164475) Added error @kErrICTBlankGLAccount = -103 as a last defense protection
||                     against null gl accounts linked to ICT
|| 01/23/13 GHL 10.564 (166010) Removed deletion on media accruals if one of the corresponding vouchers is posted and
||                     the GL account is null. With multiple voucher details associated to a POD (adjustments? like 5 at Fry Hammond)
||                     there could be gl account null and some not null. Do the accrual no matter what 
|| 02/15/13 GHL 10.565 TrackCash = 1 now 
|| 05/13/13 GHL 10.567 (171627) Instead of closing PO details at Commission Only in a loop, do it in a single shot
|| 06/24/13 GHL 10.569 (182080) Using now #tTransaction.GPFlag (general purpose flag) to validate missing offices and depts 
||                      This is why I execute sptGLValidatePostTemp before exiting in case of preposting
|| 08/05/13 GHL 10.571 Added Multi Currency stuff
|| 01/14/14 GHL 10.576 (201908) When opening transaction = 1, allow payments to be reposted in cash basis  
|| 01/16/14 GHL 10.576 Calling now spGLPostCredit for multicurrency credits
|| 02/06/14 GHL 10.576 (205570) Since there is a department on the misc costs, take it from the misc cost then if null the item
|| 04/11/14 GHL 10.579 (212612) If the Item is null, get #tAccruedExpenseAccount.GLAccountKey from BilledItem
|| 08/28/14 GHL 10.584 (226613) An Adv Bill can be applied to posted regular invoices, need to split AB process
|| 01/05/15 GHL 10.588 Taking in account now tPreference.DefaultDepartmentFromUser for time entries
|| 03/10/15 GHL 10.590 Pick tTime.DepartmentKey instead of taking in account tPreference.DefaultDepartmentFromUser 
||                     The handling of DefaultDepartmentFromUser has been moved to the time entry insert and update
|| 05/12/15 GHL 10.592 (255657) Added check: the currency on the AR account and the invoice must match
|| 05/31/16 GHL 10.604 (302066) Resetting correct memo for ICT recs (was picking up incorrect MC one)
|| 09/28/17 GHL 10.620 (365313) Added last line of defense against missing invoice numbers
|| 01/10/18 GHL 18.200 (379264) Do not post if the invoice is overapplied (because the UI lets the user go now into overapplied territory) 
|| 09/14/18 GHL 18.910 (420743) If the company requires classes and it is missing on the POD, get it from the PO
|| 10/23/18 GHL 18.920 (427348) If there is no item to get the sales account, use BilledItem i.e. use isnull(t.BilledItem, t.ItemKey) 
|| 07/24/19 GHL 19.080 (462782) Added comments for the Adv Bill reversals 
|| 07/30/19 GHL 19.080 (472262) Since an adv bill and a revenue invoice may have different AR accounts, we cannot use the same @ARAccountKey 
||                     for the reversals of the advance bills...see places changed below with 472262
|| 09/05/19 GHL 19.090 (477624) The users do not like the AB reversals done for 472262 when the AR accounts are the same on the regular and AB
||                     So if the AR accounts are the same, deduct the amount from the Invoice amount and enter a single transaction
||                     If the AR accounts are not the same, enter separate reversals against the AR accounts on the AB  
|| 09/12/19 GHL 19.100 (479102) Rolled back 472262 and 477624 because too many users complain
|| 06/17/20 GHL 20.070 (451878) Changes for GL companies with different currency
|| 10/26/20 GHL 20.120 (523060) Added support for Media Prebill Accrual Account
|| 02/24/21 MCC 21.04.14 (539749) Updated GLCompanyKey for the prepayment section for the intercompany posting
|| 05/14/21 GHL 21.06.18 (558576) Updating now the office with the AR account 
|| 06/30/21 GHL 21.070  For prebill accrual, take 0 for GLCDebit/GLCCredit, need to discuss more  
||                      Ex: CI in GBP, HC = USD, GLC HC = CAD, PO in EUR
||                      How can I calc AccruedCost in CAD? How can I calculate PrebillAmount in CAD using a rate on the client invoice?
||                      Need to convert from EUR to CAD...or USD to CAD 
|| 02/16/23 AMP 23.03.19 (630382) Added @UserKey to be able to report on the user that Posted the transaction
|| 11/11/25 MCM 25.12.x (656423) Updated for the LiabilityAccountKey
|| 05/28/26 MCM 26.06.x (729596) Added PostingFromRegular so we can handle when the credit memo is posted prior to the revenue invoice being posted
*/
-- Bypass cash basis process or not
DECLARE @TrackCash INT SELECT @TrackCash = 1
	
-- Register all constants
DECLARE @kErrNotApproved INT					SELECT @kErrNotApproved = -1
DECLARE @kErrInvalidARAcct INT					SELECT @kErrInvalidARAcct = -2
DECLARE @kErrInvalidLineAcct INT				SELECT @kErrInvalidLineAcct = -3
DECLARE @kErrInvalidAdvBillAcct INT				SELECT @kErrInvalidAdvBillAcct = -4
DECLARE @kErrInvalidSalesTaxAcct INT			SELECT @kErrInvalidSalesTaxAcct = -5
DECLARE @kErrInvalidSalesTax2Acct INT			SELECT @kErrInvalidSalesTax2Acct = -6
DECLARE @kErrInvalidSalesTax3Acct INT			SELECT @kErrInvalidSalesTax3Acct = -7
DECLARE @kErrInvalidPrepayAcct INT				SELECT @kErrInvalidPrepayAcct = -8
DECLARE @kErrInvalidSalesAcct INT				SELECT @kErrInvalidSalesAcct = -9
DECLARE @kErrInvalidExpenseAcct INT				SELECT @kErrInvalidExpenseAcct = -10
DECLARE @kErrInvalidOUAcct INT					SELECT @kErrInvalidOUAcct = -11
DECLARE @kErrInvalidPOAccruedExpenseAcct INT	SELECT @kErrInvalidPOAccruedExpenseAcct = -12
DECLARE @kErrInvalidPOPrebillAccrualAcct INT	SELECT @kErrInvalidPOPrebillAccrualAcct = -13
DECLARE @kErrInvalidARCurrency INT				SELECT @kErrInvalidARCurrency = -14
DECLARE @kErrMissingInvoiceNumber INT			SELECT @kErrMissingInvoiceNumber = -15
DECLARE @kErrOverApplied INT					SELECT @kErrOverApplied = -16

DECLARE @kErrInvalidRoundingDiffAcct int		SELECT @kErrInvalidRoundingDiffAcct = -350
DECLARE @kErrInvalidRealizedGainAcct int		SELECT @kErrInvalidRealizedGainAcct = -351

DECLARE @kErrGLClosedDate INT					SELECT @kErrGLClosedDate = -100
DECLARE @kErrPosted INT							SELECT @kErrPosted = -101
DECLARE @kErrBalance INT						SELECT @kErrBalance = -102
DECLARE @kErrICTBlankGLAccount INT				SELECT @kErrICTBlankGLAccount = -103
DECLARE @kErrUnexpected INT						SELECT @kErrUnexpected = -1000

DECLARE @kMemoHeader VARCHAR(100)				SELECT @kMemoHeader = ''Invoice # ''
DECLARE @kMemoAdvBill VARCHAR(100)				SELECT @kMemoAdvBill = ''Advance Billing for Invoice # ''
DECLARE @kMemoSalesTax VARCHAR(100)				SELECT @kMemoSalesTax = ''Sales Tax for Invoice # ''
DECLARE @kMemoSalesTax2 VARCHAR(100)			SELECT @kMemoSalesTax2 = ''Sales Tax 2 for Invoice # ''
DECLARE @kMemoSalesTax3 VARCHAR(100)			SELECT @kMemoSalesTax3 = ''Other Sales Tax for Invoice # ''
DECLARE @kMemoPrepayments VARCHAR(100)			SELECT @kMemoPrepayments = ''Prepayment Reversal Check # ''
DECLARE @kMemoPrebillAccruals VARCHAR(100)		SELECT @kMemoPrebillAccruals = ''Prebilled Order Accrual for Invoice # ''
DECLARE @kMemoLine VARCHAR(100)					SELECT @kMemoLine = ''Invoice # ''
DECLARE @kMemoRealizedGain VARCHAR(100)			SELECT @kMemoRealizedGain = ''Multi Currency Realized Gain/Loss ''
DECLARE @kMemoMCRounding VARCHAR(100)			SELECT @kMemoMCRounding = ''Multi Currency Rounding Diff ''

DECLARE @kSectionHeader int						SELECT @kSectionHeader = 1
DECLARE @kSectionLine int						SELECT @kSectionLine = 2
DECLARE @kSectionPrepayments int				SELECT @kSectionPrepayments = 3
DECLARE @kSectionPrebillAccruals int			SELECT @kSectionPrebillAccruals = 4
DECLARE @kSectionSalesTax int					SELECT @kSectionSalesTax = 5
DECLARE @kSectionICT int						SELECT @kSectionICT = 8
DECLARE @kSectionMCRounding int					SELECT @kSectionMCRounding = 9
DECLARE @kSectionMCGain int						SELECT @kSectionMCGain = 10

DECLARE @kLineNoTransactions int				SELECT @kLineNoTransactions = 1
DECLARE @kLineUseTransactions int				SELECT @kLineUseTransactions = 2
DECLARE @kLineTypeDetail int					SELECT @kLineTypeDetail = 2

-- Vars for tPref
DECLARE @PostToGL tinyint
		,@GLClosedDate smalldatetime
		,@TrackOverUnder tinyint
		,@AccrueCostToItemExpenseAccount tinyint
		,@LaborOUAccountKey int
		,@ExpenseOUAccountKey int
		,@POAccruedExpenseAccountKey int
		,@POPrebillAccrualAccountKey int
		,@MediaPrebillAccrualAccountKey int
		,@AdvBillAccountKey int
		,@Customizations varchar(1000)
		,@UseMultiCompanyGLCloseDate tinyint
		,@MultiCurrency tinyint
		,@RoundingDiffAccountKey int -- for rounding errors
		,@RealizedGainAccountKey int -- for realized gains after applications of checks to invoices, invoices to invoices etc..  
		,@IsCreditInvoice int -- for multi currency, if it is a credit, we need to post the credits
		,@DefaultDepartmentFromUser int

-- Vars for invoice info
DECLARE @InvoiceStatus int
		,@ARAccountKey int
		,@Amount money
		,@SalesTaxKey int
		,@SalesTaxAccountKey int
		,@SalesTaxAmount money
		,@SalesTax2Key int
		,@SalesTax2AccountKey int
		,@SalesTax2Amount money
		,@AdvBillAmount money
		,@AdvBillAmountForARAccount money -- added for 477624, the adv bill amount for invoices with same AR account
		,@AdvBillTaxAmount money
		,@AdvBillNoTaxAmount money
		,@AdvBillAmountFromAB money -- added for 226613 AB can apply against posted inv
		,@AdvBillTaxAmountFromAB money
		,@AdvBillNoTaxAmountFromAB money
		,@InvoiceNumber varchar(100)
		,@Posted tinyint
		,@ParentInvoiceKey int
		,@ParentInvoice tinyint
		,@PercentageSplit decimal(24,4)
		,@Percent decimal (20,8)
		,@LineInvoiceKey int -- This is the invoice where to get the lines from (the parent invoice)
		,@HeaderOfficeKey int
		,@OpeningTransaction tinyint
		,@AdvanceBill int
		,@CurrencyID varchar(10)
		,@ExchangeRate decimal(24,7)	
		,@GLCCurrencyID varchar(10)
		,@GLCExchangeRate decimal(24,7)	
		,@OrderAccrualExchangeRate decimal(24,7)

-- Other vars for GL tran
DECLARE @TransactionDate smalldatetime
		,@Entity VARCHAR(50)
		,@EntityKey INT
		,@Reference VARCHAR(100)
		,@GLAccountKey INT
		,@ClassKey int
		,@Memo varchar(500)
		,@PostSide char(1)
		,@ClientKey int
		,@ProjectKey int
		,@SourceCompanyKey INT
		,@DepositKey INT
		,@GLCompanyKey INT
		,@OfficeKey INT
		,@DepartmentKey INT
		,@DetailLineKey INT
		,@Section INT
		,@GLAccountErrRet INT
		,@RetVal INT
		,@TransactionCount INT
		,@PostPrebillAccruals INT
		,@PostBody INT

		
	-- validate the invoice and make sure that it is not overapplied
	exec @RetVal = sptInvoiceValidate @InvoiceKey

	if @RetVal <> 1
		return @kErrOverApplied

	Select
		 @GLClosedDate = GLClosedDate
		,@PostToGL = ISNULL(PostToGL, 0)
		,@TrackOverUnder = ISNULL(TrackOverUnder, 0)
		,@AccrueCostToItemExpenseAccount = ISNULL(AccrueCostToItemExpenseAccount, 0)
		,@LaborOUAccountKey = LaborOverUnderAccountKey
		,@ExpenseOUAccountKey = ExpenseOverUnderAccountKey
		,@POAccruedExpenseAccountKey = POAccruedExpenseAccountKey
		,@POPrebillAccrualAccountKey = POPrebillAccrualAccountKey
		,@MediaPrebillAccrualAccountKey = isnull(MediaPrebillAccrualAccountKey, POPrebillAccrualAccountKey)
		,@AdvBillAccountKey = AdvBillAccountKey
		,@Customizations = ISNULL(Customizations, '''')
		,@UseMultiCompanyGLCloseDate = ISNULL(MultiCompanyClosingDate, 0)
		,@MultiCurrency = ISNULL(MultiCurrency, 0)
		,@RoundingDiffAccountKey = RoundingDiffAccountKey
		,@RealizedGainAccountKey = RealizedGainAccountKey
		,@DefaultDepartmentFromUser = isnull(DefaultDepartmentFromUser, 0)  
	From
		tPreference (nolock)
	Where
		CompanyKey = @CompanyKey
		
	Select 
		@InvoiceStatus = InvoiceStatus
		,@TransactionDate =  dbo.fFormatDateNoTime(ISNULL(PostingDate, InvoiceDate))
		,@ARAccountKey = ARAccountKey
		,@Amount = InvoiceTotalAmount
		,@AdvBillAmount = ISNULL(RetainerAmount, 0)
		,@SalesTaxKey = SalesTaxKey
		,@SalesTaxAmount = ISNULL(SalesTax1Amount, 0)
		,@SalesTax2Key = SalesTax2Key
		,@SalesTax2Amount = ISNULL(SalesTax2Amount, 0)
		,@ClassKey = ClassKey
		,@InvoiceNumber = rtrim(ltrim(InvoiceNumber))
		,@ProjectKey = NULL
		,@ClientKey = ClientKey
		,@Posted = Posted
		,@ParentInvoice = ISNULL(ParentInvoice, 0)
		,@ParentInvoiceKey = ISNULL(ParentInvoiceKey, 0)
		,@PercentageSplit = ISNULL(PercentageSplit, 0)
		,@LineInvoiceKey = InvoiceKey -- By default, we get the lines from this invoice
		,@GLCompanyKey = GLCompanyKey
		,@HeaderOfficeKey = OfficeKey
		,@OpeningTransaction = ISNULL(OpeningTransaction, 0)
		,@AdvanceBill = AdvanceBill 
		,@CurrencyID = CurrencyID
		,@ExchangeRate = isnull(ExchangeRate, 1)
		,@GLCCurrencyID = GLCCurrencyID
		,@AdvBillAccountKey = ISNULL(LiabilityAccountKey, @AdvBillAccountKey)
		,@GLCExchangeRate = case when GLCCurrencyID is null then isnull(ExchangeRate, 1) 
		                    else isnull(GLCExchangeRate, 1) end

	From vInvoice (nolock)
	Where InvoiceKey = @InvoiceKey

if isnull(@InvoiceNumber, '''') = ''''
	return @kErrMissingInvoiceNumber

-- for order accruals we need a rate to go from main home currency to GL company home currency
if @ExchangeRate <= 0
	select @ExchangeRate = 1

select @OrderAccrualExchangeRate = @GLCExchangeRate / @ExchangeRate

-- for now we will report rate = 1, GLCDebit = GLCCredit = 0, we need to review how that works for 
select @OrderAccrualExchangeRate = 1

if @Amount <0 
	select @IsCreditInvoice = 1
else
	select @IsCreditInvoice = 0


	if @UseMultiCompanyGLCloseDate = 1 And ISNULL(@GLCompanyKey, 0) > 0
	BEGIN
		Select 
			@GLClosedDate = GLCloseDate
		From 
			tGLCompany (nolock)
		Where
			GLCompanyKey = @GLCompanyKey			

	END

	if @MultiCurrency = 1 
	begin
		if exists (select 1 from tGLAccount (nolock)
			where GLAccountKey = @ARAccountKey
			and isnull(CurrencyID, '''') <> isnull(@CurrencyID, '''') 
			)
			return @kErrInvalidARCurrency
	end

	/* issue 462782...simply added comments
	tInvoiceAdvanceBill.FromAB indicates where the GL reversal takes place
	Example: apply 500 to an Adv Bill

	FromAB = 0, the GL reversal takes place on the Regular invoice side

    Advance Bill  DR     CR
    AR1           1000
	AB                   1000

	Regular       DR     CR
	AR2           1000
	Sales                1000            
	AR1                  500 (reversal) (472262)
	AB            500        (reversal)

	if AR1 = AR2 = Same AR Account (477624)
	AR            500		  
	AB            500
	Sales                 1000

	Note: when working on 558576 noticed that this is not a reversal of AR 
	AR can only be reversed by a receipt
	It is rather a decrease of AR

	FromAB = 1, the GL reversal takes place on the Adv Bill invoice side

	Regular       DR     CR
	AR2           1000
	Sales                1000            
	
	Advance Bill  DR     CR
    AR1           1000
	AB                   1000
	AR2                  500 (reversal)
	AB            500        (reversal)

	Note: when working on 558576 noticed that the correction of AR , AB 
	should be probably done using Office/Class on the AB invoice, not the rev/reg invoice
	because we are reversing/decreasing something on the AB invoice
    (did not change the posting of AB though)

	*/

	-- 174684,226613 recalc advbill amounts because RetainerAmount has both IAB applications
	-- we need to split FromAB = 0 and FromAB = 1

	-- Process records where FromAB = 0

	select @AdvBillAmount = sum(Amount)
	from   tInvoiceAdvanceBill (NOLOCK)
	Where  InvoiceKey = @InvoiceKey
	And    isnull(FromAB, 0) = 0

	select @AdvBillAmountForARAccount = sum(Amount)
	from   tInvoiceAdvanceBill iab (NOLOCK)
		inner join tInvoice ab (nolock) on iab.AdvBillInvoiceKey = ab.InvoiceKey -- AB invoice
	Where  iab.InvoiceKey = @InvoiceKey			-- real invoice
	And    ab.ARAccountKey = @ARAccountKey		-- for the same AR account 
	And    isnull(FromAB, 0) = 0

	Select @AdvBillTaxAmount = SUM(iabt.Amount)
	From   tInvoiceAdvanceBillTax iabt (NOLOCK)
		inner join tInvoiceAdvanceBill iab (NOLOCK) on iabt.InvoiceKey = iab.InvoiceKey
		and iabt.AdvBillInvoiceKey = iab.AdvBillInvoiceKey 
	Where  iabt.InvoiceKey = @InvoiceKey
	And    isnull(iab.FromAB, 0) = 0 


	Select @AdvBillAmount = ISNULL(@AdvBillAmount, 0)
		,@AdvBillAmountForARAccount = ISNULL(@AdvBillAmountForARAccount, 0)
	    ,@AdvBillTaxAmount = ISNULL(@AdvBillTaxAmount, 0)
		,@AdvBillNoTaxAmount = ISNULL(@AdvBillAmount, 0) - ISNULL(@AdvBillTaxAmount, 0)

	--Set the advance Bill account Key to the advance bill invoice Liability Account 
    SELECT @AdvBillAccountKey = ISNULL(ab.LiabilityAccountKey, @AdvBillAccountKey)  --656423
		from   tInvoiceAdvanceBill iab (NOLOCK)
		inner join tInvoice ab (nolock) on iab.AdvBillInvoiceKey = ab.InvoiceKey -- AB invoice
	Where  iab.InvoiceKey = @InvoiceKey			-- real invoice
	And    ab.ARAccountKey = @ARAccountKey		-- for the same AR account 
	And    isnull(FromAB, 0) = 0
	
	-- Now correct the total amount against AR ---472262 this does not work if the AR accounts are different 
	--select @Amount = @Amount - @AdvBillAmount

	-- Added for 477624, we combine the 2 if the AR Accounts are the same
	--select @Amount = @Amount - @AdvBillAmountForARAccount

	-- Rolling back for 479102
	select @Amount = @Amount - @AdvBillAmount

	-- Process records where FromAB = 1

	select @AdvBillAmountFromAB = sum(Amount)
	from   tInvoiceAdvanceBill (NOLOCK)
	Where  AdvBillInvoiceKey = @InvoiceKey
	And    isnull(FromAB, 0) = 1

	Select @AdvBillTaxAmountFromAB = SUM(iabt.Amount)
	From   tInvoiceAdvanceBillTax iabt (NOLOCK)
		inner join tInvoiceAdvanceBill iab (NOLOCK) on iabt.InvoiceKey = iab.InvoiceKey
		and iabt.AdvBillInvoiceKey = iab.AdvBillInvoiceKey 
	Where  iabt.AdvBillInvoiceKey = @InvoiceKey
	And    isnull(iab.FromAB, 0) = 1 


	Select @AdvBillAmountFromAB = ISNULL(@AdvBillAmountFromAB, 0)
	    ,@AdvBillTaxAmountFromAB = ISNULL(@AdvBillTaxAmountFromAB, 0)
		,@AdvBillNoTaxAmountFromAB = ISNULL(@AdvBillAmountFromAB, 0) - ISNULL(@AdvBillTaxAmountFromAB, 0)


	-- Invoice is not approved
	if @InvoiceStatus < 4
		return @kErrNotApproved

	if @Posted = 1
		return @kErrPosted
	/* Allow for the saving of cash basis prep tables	
	if @OpeningTransaction = 1
		Select @PostToGL = 0	
	*/
	
	if @ParentInvoice = 1
	BEGIN
		-- Parent invoices are never posted, only child invoices, execpt for Prebill Accruals
		Select @Percent = 1, @PostPrebillAccruals = 1, @PostBody = 0
	END
	else
	BEGIN
		if @ParentInvoiceKey > 0
			Select	@Percent = @PercentageSplit / 100.0
					,@LineInvoiceKey = @ParentInvoiceKey -- The lines belong to the parent invoice
					,@PostPrebillAccruals = 0,@PostBody = 1
		else
			Select @Percent = 1, @PostPrebillAccruals = 1,@PostBody =1
	END

	IF @PostToGL = 0 And @Prepost = 0
	BEGIN
		-- Case when we do not post to GL
		Update tInvoice
		Set Posted = 1, InvoiceStatus = 4
		Where InvoiceKey = @InvoiceKey
	
		insert tTransactionOrderAccrual (PurchaseOrderDetailKey, CompanyKey, AccrualAmount, TransactionKey, Entity, EntityKey, PostingDate)
		select pod.PurchaseOrderDetailKey, @CompanyKey, ROUND(ISNULL(pod.AccruedCost, 0) * @Percent, 2), -1, ''INVOICE'', @InvoiceKey, @TransactionDate
		from   tPurchaseOrderDetail pod (nolock)
			inner Join tPurchaseOrder po (NOLOCK) ON pod.PurchaseOrderKey = po.PurchaseOrderKey
			inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
		Where	il.InvoiceKey = @LineInvoiceKey  -- must point to invoice where lines are
		And po.BillAt in (0,1)

		RETURN 1		
	END

	if @OpeningTransaction = 1 And @Prepost = 0
	begin
		insert tTransactionOrderAccrual (PurchaseOrderDetailKey, CompanyKey, AccrualAmount, TransactionKey, Entity, EntityKey, PostingDate)
		select pod.PurchaseOrderDetailKey, @CompanyKey, ROUND(ISNULL(pod.AccruedCost, 0) * @Percent, 2), -1, ''INVOICE'', @InvoiceKey, @TransactionDate
		from   tPurchaseOrderDetail pod (nolock)
			inner Join tPurchaseOrder po (NOLOCK) ON pod.PurchaseOrderKey = po.PurchaseOrderKey
			inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
		Where	il.InvoiceKey = @LineInvoiceKey  -- must point to invoice where lines are
		And po.BillAt in (0,1)

	end

	-- Make sure the invoice is not posted prior to the closing date
	if @Prepost = 0 and @GLClosedDate is not null
		if @GLClosedDate > @TransactionDate
			return @kErrGLClosedDate

	--EXEC @TrackCash = sptCashEnableCashBasis @CompanyKey, @Customizations

	IF @CreateTemp = 1
	BEGIN
		CREATE TABLE #tTransaction (
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL,
			ICTGLCompanyKey int null,

			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,
			
			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null, 

			ICTExchangeRate decimal(24,7) null, -- this is to be used by spGLPostICTCreateCurrencyDTDF
			ICTGLCExchangeRate decimal(24,7) null	-- contains the current rate on payments instead of rate to reverse out

			-- our work space
			,GLValid int null
			,GLAccountErrRet int null
			,GPFlag int null -- General purpose flag
			
			,TempTranLineKey int IDENTITY(1,1) NOT NULL
			)	 
								
	END
	
	If exists(Select 1 from tInvoiceLine (nolock) Where InvoiceKey = @LineInvoiceKey And BillFrom = @kLineUseTransactions)
		-- create a temp table to hold the Keys and amounts
		create table #tLineDetail
			(
			InvoiceLineKey int null
			,GLAccountKey int null
			,GLAccountErrRet int null
			,ClassKey int null
			,OfficeKey int null
			,DepartmentKey int null
			,ProjectKey int null
			,Amount money null 
			
			-- ICT -- need to get the GLCompanyKey and Office from various places
			,Entity varchar(20) null
			,EntityKey int null
			,GLCompanySource int null
			,GLCompanyKey int null
			,UserKey int null

			-- for GL companies and different currency
			,GLCCurrencyID varchar(100)
			,GLCExchangeRate decimal(24,7)
			)
	
	-- create a temp table to hold the accrued expense account Keys
	-- This is for the po where BillAt = 0 and 1  (net/Gross)
	create table #tAccruedExpenseAccount
		(
		PurchaseOrderDetailKey int null
		,GLAccountKey int null
		,GLAccountErrRet int null
		,AccrualGLAccountKey int null
		,AccrualGLAccountErrRet int null
		,VoucherPosted int null
		
		-- added for tTransactionOrderAccrual
		,GLCompanyKey int null -- ICT
		,ProjectKey int null
		,ClassKey int null
		,OfficeKey int null
		,DepartmentKey int null
		
		,AccruedCost money null -- straight from POD
		,AccrualAmount money null -- rounded for GL
		,TempTranLineKey int null
		,TransactionKey int null 

		-- we need to convert AccruedCost/PrebillAmount expressed in main home currency to GLC home currency
		-- GLC AccruedCost = (AccruedCost / ExchangeRate) * GLCExchangeRate
		,GLCAccruedCost money null
		)	
	
	-- This is for the po where BillAt = 2  (commission only)
	create table #tPODCommissionOnly
		(
		PurchaseOrderDetailKey int null
		,PurchaseOrderKey int null
        ,ProjectKey int null
		,UpdateFlag int null
		)	

	CREATE TABLE #tCashTransactionLine (
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL,
			
			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,

			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null,

			AdvBillAmount money NULL,
			PrepaymentAmount money NULL,
			ReceiptAmount money NULL,
			
			TempTranLineKey int NULL
			)	 
			
	CREATE TABLE #tInvoiceAdvanceBillSale (
		InvoiceKey int null
		,AdvBillInvoiceKey int null
		,CashTransactionLineKey int null
		,Amount money null
		,TempTranLineKey int NULL
		)	
		
	-- These should not change
	Select	@Entity = ''INVOICE''
			,@EntityKey = @InvoiceKey
			,@Reference = @InvoiceNumber
			,@SourceCompanyKey = @ClientKey			
			,@DepositKey = NULL 
	-- TransactionDate, ProjectKey, GLCompanyKey, ClientKey already set

	 /*
	 * Prebill Accruals
	 */

if @PostPrebillAccruals = 1 
begin
	-- Step 1: determine AccruedExpenseAccountKey
	
	-- Capture all pods
	-- because of split billings, where 2 child invoices could be linked to 1 pod
	-- one invoice could already be posted and the other not, so try to get an existing GLAccountKey from the pod 
	-- i.e. from a posted invoice 
	Insert #tAccruedExpenseAccount (PurchaseOrderDetailKey, GLAccountKey, GLAccountErrRet, VoucherPosted, AccrualGLAccountKey, AccrualGLAccountErrRet
			,AccruedCost, GLCompanyKey, ProjectKey, ClassKey, OfficeKey, DepartmentKey
			)
	Select pod.PurchaseOrderDetailKey, pod.AccruedExpenseInAccountKey
	      , @kErrInvalidPOAccruedExpenseAcct, 0
		  ,case when po.POKind = 0 then @POPrebillAccrualAccountKey else  @MediaPrebillAccrualAccountKey end
		  ,@kErrInvalidPOPrebillAccrualAcct

	      ,ROUND(ISNULL(pod.AccruedCost, 0) * @Percent, 2)
		
		  -- ICT
		 , isnull(po.GLCompanyKey, 0)
		
		  , ISNULL(pod.ProjectKey, 0), ISNULL(pod.ClassKey, ISNULL(po.ClassKey, 0)), ISNULL(pod.OfficeKey, 0), ISNULL(pod.DepartmentKey, 0)
	From   tPurchaseOrderDetail pod (nolock)
		Inner Join tPurchaseOrder po (NOLOCK) ON pod.PurchaseOrderKey = po.PurchaseOrderKey
		Inner Join tInvoiceLine il (NOLOCK) ON pod.InvoiceLineKey = il.InvoiceLineKey
	Where	il.InvoiceKey = @LineInvoiceKey  -- must point to invoice where lines are
	And po.BillAt in (0,1)
	
	-- now calculate the PrebillAmount in the GLC currency
	-- we need to convert AccruedCost or PrebillAmount expressed in main home currency to GLC home currency
	-- Assume transaction in CAD with home currency in USD, but GL company in EUR
	
	-- we have ExchangeRate from CAD to USD = .7329
	-- GLCExchangeRate from CAD to EUR = .6
	-- TotalCost = 136.61 CAD and PrebillAmount = 100.12 USD
	-- 1) convert PrebillAmount from USD to CAD = 100.12 / .7329 = 136.608 
	-- 2) convert to EUR 136.608 * .6 = 81.96

	-- GLC PrebillAmount = (PrebillAmount / ExchangeRate) * GLCExchangeRate
	-- or GLC PrebillAmount = (PrebillAmount * GLCExchangeRate) / ExchangeRate		
	Update #tAccruedExpenseAccount
	Set    GLCAccruedCost = ROUND((AccruedCost * @GLCExchangeRate )/ @ExchangeRate, 2) 

	-- we need more discussion on this, take 0 for now
	Update #tAccruedExpenseAccount
	Set    GLCAccruedCost = 0 

	-- Then look for a valid Accrued Expense Account on a voucher detail
	-- we could have several vds associated to each pod, I suggest we take anyone
	-- Having AccruedExpenseOutAccountKey could happen but should be rare
	-- I would think they bill the clients first, unless they delete client invoices like Brothers Co
	Update #tAccruedExpenseAccount
	Set    #tAccruedExpenseAccount.GLAccountKey = 
			Case When ISNULL(#tAccruedExpenseAccount.GLAccountKey, 0) = 0 
			     Then vd.AccruedExpenseOutAccountKey
                 Else #tAccruedExpenseAccount.GLAccountKey
            End
          ,#tAccruedExpenseAccount.VoucherPosted = v.Posted 
	From   tVoucherDetail vd (NOLOCK)
		Inner Join tVoucher v (NOLOCK) ON vd.VoucherKey = v.VoucherKey
	Where  #tAccruedExpenseAccount.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
	
	-- If the voucher is posted AND there is no accrued expense account
	-- do not try to set a prebill accrual, we will not be able to reverse the accrual
	-- removed for 166010: with all these vendor invoices linked to adjustments, some gl accounts could be null and others not
	--Delete #tAccruedExpenseAccount Where VoucherPosted = 1 And ISNULL(#tAccruedExpenseAccount.GLAccountKey, 0) = 0
		
	-- Now set the prebill accrual accounst based on preferences	
	If @AccrueCostToItemExpenseAccount = 0
	Begin
		Update #tAccruedExpenseAccount
		Set    #tAccruedExpenseAccount.GLAccountKey = @POAccruedExpenseAccountKey
		      ,#tAccruedExpenseAccount.GLAccountErrRet = @kErrInvalidPOAccruedExpenseAcct
		Where ISNULL(#tAccruedExpenseAccount.GLAccountKey, 0) = 0 
	End
	Else
	Begin
		Update #tAccruedExpenseAccount
		Set    #tAccruedExpenseAccount.GLAccountKey = it.ExpenseAccountKey
		      ,#tAccruedExpenseAccount.GLAccountErrRet = @kErrInvalidExpenseAcct
		From   tPurchaseOrderDetail pod (nolock)
			Left Outer Join tItem it (nolock) ON pod.ItemKey = it.ItemKey
		Where ISNULL(#tAccruedExpenseAccount.GLAccountKey, 0) = 0 
		And   #tAccruedExpenseAccount.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey 

		-- in case pod.ItemKey is null, pick from BilledItem 
		Update #tAccruedExpenseAccount
		Set    #tAccruedExpenseAccount.GLAccountKey = it.ExpenseAccountKey
		      ,#tAccruedExpenseAccount.GLAccountErrRet = @kErrInvalidExpenseAcct
		From   tPurchaseOrderDetail pod (nolock)
			Left Outer Join tItem it (nolock) ON pod.BilledItem = it.ItemKey
		Where ISNULL(#tAccruedExpenseAccount.GLAccountKey, 0) = 0 
		And   #tAccruedExpenseAccount.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey 
	End

	UPDATE #tAccruedExpenseAccount SET GLAccountKey = ISNULL(GLAccountKey, 0)

	-- Step 2: Debit vd.AccruedExpenseOutKey OR @POAccruedExpenseAccountKey OR it.ExpenseAccountKey
	--, group by office, department, class on the order detail, and project
	SELECT @PostSide = ''D'',@Memo = @kMemoPrebillAccruals + @InvoiceNumber , @Section = @kSectionPrebillAccruals    
			,@DetailLineKey = NULL

	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,GLCDebit,GLCCredit, ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GLCCurrencyID, GLCExchangeRate)
	
	SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
		GLAccountKey, Sum(AccruedCost), 0, Sum(GLCAccruedCost), 0,ClassKey,  @Memo,
		@ClientKey,ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
		GLCompanyKey,OfficeKey,DepartmentKey,@DetailLineKey,@Section, GLAccountErrRet,@GLCCurrencyID, @OrderAccrualExchangeRate
	From   #tAccruedExpenseAccount  
	Group By GLAccountKey, GLCompanyKey, GLAccountErrRet, ClassKey,ProjectKey,OfficeKey,DepartmentKey

	-- Step 3: Credit @POPrebillAccrualAccountKey, group by class on the order detail
	SELECT @PostSide = ''C'', @GLAccountKey = @POPrebillAccrualAccountKey, @GLAccountErrRet = @kErrInvalidPOPrebillAccrualAcct   
			,@Memo = @kMemoPrebillAccruals + @InvoiceNumber , @Section = @kSectionPrebillAccruals    
			,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

	-- One entry per class and project from the pod detail
	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,GLCDebit,GLCCredit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GLCCurrencyID, GLCExchangeRate)
	
	SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
		isnull(AccrualGLAccountKey,0), 0, Sum(AccruedCost),0, Sum(GLCAccruedCost),
		ISNULL(ClassKey, 0), @Memo,
		@ClientKey,isnull(ProjectKey,0),@SourceCompanyKey,@DepositKey,@PostSide,
		ISNULL(GLCompanyKey,0),@OfficeKey,@DepartmentKey,@DetailLineKey,@Section,AccrualGLAccountErrRet
		,@GLCCurrencyID, @OrderAccrualExchangeRate
	From   #tAccruedExpenseAccount
	--From   #tTransaction (nolock)
	--Where	EntityKey = @EntityKey
	--And     Entity = @Entity
	--And     Section = @kSectionPrebillAccruals
	--And     PostSide = ''D'' 
	Group By  isnull(AccrualGLAccountKey,0), AccrualGLAccountErrRet,ISNULL(GLCompanyKey, 0), ISNULL(ClassKey, 0), ISNULL(ProjectKey, 0)


	-- Step 4: Save the TempTranLineKey  so that we can use later when saving in tTransactionOrderAccrual
	
	-- we will need a way to update the TransactionKey from TempTranLineKey in #tAccruedExpenseAccount later 
	UPDATE #tTransaction SET DetailLineKey = TempTranLineKey WHERE Section = @kSectionPrebillAccruals
	
	DECLARE @TempTranLineKey int
	DECLARE @AccrualClassKey int, @AccrualGLCompanyKey int, @AccrualProjectKey int, @AccrualGLAccountKey int
	
	SELECT @TempTranLineKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @TempTranLineKey = MIN(TempTranLineKey)
		FROM   #tTransaction
		WHERE  Section = @kSectionPrebillAccruals
		AND    TempTranLineKey > @TempTranLineKey
		AND    PostSide = ''C''
		
		IF @TempTranLineKey IS NULL
			BREAK
		
		SELECT @AccrualClassKey = ISNULL(ClassKey, 0)
		      ,@AccrualGLCompanyKey =  ISNULL(GLCompanyKey, 0)
			  ,@AccrualProjectKey = ISNULL(ProjectKey, 0)
			  ,@AccrualGLAccountKey = ISNULL(GLAccountKey, 0)
		FROM   #tTransaction
		WHERE  TempTranLineKey = @TempTranLineKey
		
		UPDATE #tAccruedExpenseAccount
		SET    TempTranLineKey = @TempTranLineKey
			  ,AccrualAmount = AccruedCost
		WHERE  ClassKey	= @AccrualClassKey 
		AND    GLCompanyKey	= @AccrualGLCompanyKey 
		AND    ProjectKey = @AccrualProjectKey
		AND    AccrualGLAccountKey = @AccrualGLAccountKey -- because it could be a PO or Media accrual account		
	END

end -- Prebill Accruals and not a child invoice

if @PostBody = 1
begin	
	/*
	* Insert the header/AR Amount
	*/
	
	SELECT @PostSide = ''D''
		  ,@GLAccountKey = @ARAccountKey
		  ,@GLAccountErrRet = @kErrInvalidARAcct 
		  ,@Memo = @kMemoHeader + @InvoiceNumber, @Section = @kSectionHeader 
		  ,@OfficeKey = @HeaderOfficeKey -- @OfficeKey = NULL -- 558576 take the office on the header instead of null
		  ,@DepartmentKey = NULL, @DetailLineKey = NULL
			
	exec spGLInsertTranTemp @CompanyKey,@PostSide,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Amount,@ClassKey,@Memo, 
		@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@GLCompanyKey,@OfficeKey,@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet
		,@CurrencyID,@ExchangeRate,@GLCCurrencyID,@GLCExchangeRate
					
	/* 
	 * Because of ICT, read now tInvoiceTax for sales taxes
	*/

	SELECT @PostSide = ''C'', @GLAccountErrRet = @kErrInvalidSalesTaxAcct
			,@Memo = @kMemoSalesTax + @InvoiceNumber, @Section = @kSectionSalesTax  
			,@OfficeKey = @HeaderOfficeKey, @DepartmentKey = NULL, @DetailLineKey = NULL

	-- One entry per GL Account
	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet, CurrencyID, ExchangeRate,
		GLCCurrencyID,GLCExchangeRate,ICTExchangeRate,ICTGLCExchangeRate)

	SELECT @CompanyKey,@TransactionDate,@Entity, @EntityKey,@Reference,
		st.PayableGLAccountKey, 0, Sum(it.SalesTaxAmount), @ClassKey
		, case when it.Type = 1 then @kMemoSalesTax + @InvoiceNumber 
		       when it.Type = 2 then @kMemoSalesTax2 + @InvoiceNumber
			   else @kMemoSalesTax3 + @InvoiceNumber end

		,@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide

		-- ICT
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 then isnull(@GLCompanyKey, 0) else il.TargetGLCompanyKey end
		
		,@OfficeKey,@DepartmentKey,st.SalesTaxKey,@Section
		, case when it.Type = 1 then @kErrInvalidSalesTaxAcct else @kErrInvalidSalesTax2Acct end
		,@CurrencyID, @ExchangeRate 

		-- ICT
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 -- or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
		then @GLCCurrencyID else glc.CurrencyID end
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 -- or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
		then @GLCExchangeRate else isnull(il.GLCExchangeRate, 1) end

		-- this is expected by the ICT sp, should be the new rates when we apply payments to invoice
		,@ExchangeRate 
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 --or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
			then @GLCExchangeRate else isnull(il.GLCExchangeRate, 1) end


	From   tInvoiceTax it (nolock)
		Inner Join tInvoiceLine il (NOLOCK) ON it.InvoiceLineKey = il.InvoiceLineKey
		Inner Join tSalesTax st (NOLOCK) ON it.SalesTaxKey = st.SalesTaxKey
		Left Join tGLCompany glc (nolock) on il.TargetGLCompanyKey = glc.GLCompanyKey
	Where  it.InvoiceKey = @InvoiceKey	
	Group by it.Type, 
		--case when isnull(il.TargetGLCompanyKey, 0) = 0 then isnull(@GLCompanyKey, 0) else il.TargetGLCompanyKey end
		 case when isnull(il.TargetGLCompanyKey, 0) = 0 then isnull(@GLCompanyKey, 0) else il.TargetGLCompanyKey end
		--,case when isnull(il.TargetGLCompanyKey, 0) = 0 or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') then @GLCCurrencyID else glc.CurrencyID end
		--,case when isnull(il.TargetGLCompanyKey, 0) = 0 or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') then @GLCExchangeRate else isnull(il.GLCExchangeRate, 1) end
		,case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCCurrencyID else glc.CurrencyID end
		,case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCExchangeRate else isnull(il.GLCExchangeRate, 1) end

		, st.SalesTaxKey,st.PayableGLAccountKey
	
		
	/*		
	* Now take care of Advance Billings (see Billing/Invoice Entry.doc)
	*/
	
	-- Credit AR with InvoiceTotalAmount and Debit Adv Bill Amount @AdvBillAmount
	-- Logically we should do this but because we take BilledAmount for the header
	-- instead of InvoiceTotalAmount, we can skip....do not skip because of 472262
	
	---------------------------------
	-- Advance Bills with  FromAB = 0
	---------------------------------

	-- Credit AR with total applied amount, this is a reversal of AR with a possible diff account..added for 472262 and removed for 479102
	/*
	SELECT @PostSide = ''C''
			   ,@GLAccountKey = @ARAccountKey
				,@GLAccountErrRet = @kErrInvalidARAcct 
			  ,@Amount = @AdvBillAmountFromAB -- will not be used
			  ,@Memo = @kMemoAdvBill  + @InvoiceNumber + '' Credit AR'', @Section = @kSectionHeader  
			  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID, ExchangeRate)

		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,abi.ARAccountKey, -- take AR account on the other invoice which may be different
			0, iab.Amount
			, ISNULL(abi.ClassKey, 0),  @Memo ,
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
			@GLCompanyKey,@OfficeKey,@DepartmentKey,iab.InvoiceAdvanceBillKey,@Section,@GLAccountErrRet,
			abi.CurrencyID, @ExchangeRate
		From   tInvoiceAdvanceBill iab (nolock)
			Inner Join tInvoice abi (NOLOCK) ON iab.AdvBillInvoiceKey = abi.InvoiceKey -- go to the AdvBill invoice
		Where  iab.InvoiceKey = @InvoiceKey	-- Real invoice, not like invoice line tax
		And    abi.ARAccountKey <> @ARAccountKey -- reverse only if the AR accounts are different (477624)
		And    isnull(iab.FromAB, 0) = 0
	*/

	-- Debit Deferred Revenue
	if @AdvBillNoTaxAmount <> 0
	BEGIN		
		SELECT @PostSide = ''D''
			  ,@GLAccountKey = @AdvBillAccountKey
			  ,@GLAccountErrRet = @kErrInvalidAdvBillAcct 
			  ,@Amount = @AdvBillNoTaxAmount
			  ,@Memo = @kMemoAdvBill  + @InvoiceNumber + '' Debit Deferred Revenue'', @Section = @kSectionHeader  
			  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

		/* We need to split this debit to include the possible various ExchangeRate values on the AB invoices
		exec spGLInsertTranTemp @CompanyKey,@PostSide,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Amount,@ClassKey,@Memo, 
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@GLCompanyKey,@OfficeKey,@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, null, 1
		*/
		
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID, ExchangeRate,GLCCurrencyID, GLCExchangeRate)

		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
			ISNULL(abi.LiabilityAccountKey, @GLAccountKey), 
			iab.Amount - ISNULL((
				select sum(iabt.Amount) from tInvoiceAdvanceBillTax iabt (nolock)
				where iabt.InvoiceKey = @InvoiceKey
				and   iabt.AdvBillInvoiceKey = iab.AdvBillInvoiceKey  
			),0)
			, 0, ISNULL(abi.ClassKey, 0),  @Memo ,
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
			@GLCompanyKey,ISNULL(abi.OfficeKey, 0),@DepartmentKey,iab.InvoiceAdvanceBillKey,@Section,@GLAccountErrRet,
			abi.CurrencyID, isnull(abi.ExchangeRate, 1), abi.GLCCurrencyID, isnull(abi.GLCExchangeRate, 1)
		From   tInvoiceAdvanceBill iab (nolock)
			Inner Join tInvoice abi (NOLOCK) ON iab.AdvBillInvoiceKey = abi.InvoiceKey -- go to the AdvBill invoice
		Where  iab.InvoiceKey = @InvoiceKey	-- Real invoice, not like invoice line tax
		And    isnull(iab.FromAB, 0) = 0

	END
	
	-- Debit Advance Bill Sales Taxes
	SELECT @PostSide = ''D'',@GLAccountErrRet = @kErrInvalidSalesTax3Acct
			,@Memo = @kMemoAdvBill + @InvoiceNumber, @Section = @kSectionSalesTax  
			,@DepartmentKey = NULL, @DetailLineKey = NULL

	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID, ExchangeRate,GLCCurrencyID, GLCExchangeRate)
	
	-- group probably by gl account, class, office
	SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
		st.PayableGLAccountKey, Sum(iabt.Amount), 0,
		ISNULL(abi.ClassKey, 0),  @Memo + '' Debit sales tax '',
		@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
		@GLCompanyKey,ISNULL(abi.OfficeKey, 0),@DepartmentKey,st.SalesTaxKey,@Section,@GLAccountErrRet,
		abi.CurrencyID, isnull(abi.ExchangeRate, 1), abi.GLCCurrencyID, isnull(abi.GLCExchangeRate, 1)
	From   tInvoiceAdvanceBillTax iabt (nolock)
		Inner Join tInvoiceAdvanceBill iab (nolock) on iabt.AdvBillInvoiceKey = iab.AdvBillInvoiceKey
				and iabt.InvoiceKey = iab.InvoiceKey  
		Inner Join tInvoice abi (NOLOCK) ON iabt.AdvBillInvoiceKey = abi.InvoiceKey -- go to the AdvBill invoice
		Inner Join tSalesTax st (NOLOCK) ON iabt.SalesTaxKey = st.SalesTaxKey
	Where  iabt.InvoiceKey = @InvoiceKey	-- Real invoice, not like invoice line tax
	and    isnull(iab.FromAB, 0) = 0
	Group by st.SalesTaxKey, st.PayableGLAccountKey, ISNULL(abi.ClassKey, 0), ISNULL(abi.OfficeKey, 0) 
			,abi.CurrencyID, isnull(abi.ExchangeRate, 1),abi.GLCCurrencyID, isnull(abi.GLCExchangeRate, 1)

	-- Now process the Realized Gain/Loss for the advance bills
	if @MultiCurrency = 1
	begin
	
		SELECT @PostSide = ''C'', @GLAccountKey = @RealizedGainAccountKey, @GLAccountErrRet = @kErrInvalidRealizedGainAcct 
				,@Memo = @kMemoRealizedGain, @Section = @kSectionMCGain    
				,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
	
	
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GPFlag, CurrencyID, ExchangeRate, HDebit, HCredit,
			GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
	
		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
			@GLAccountKey, 0, 0,
			null, -- @ClassKey, null it like ICT  
			@Memo + '' Adv Bill '' + abi.InvoiceNumber, 
			@ClientKey,
			null, --@ProjectKey
			@SourceCompanyKey,
			@DepositKey,@PostSide,
			@GLCompanyKey,@OfficeKey,@DepartmentKey,iab.InvoiceAdvanceBillKey,@Section,@GLAccountErrRet, 0,
			null, -- Home Currency
			1, -- Exchange Rate = 1
			0,
			Round(iab.Amount * (isnull(abi.ExchangeRate, 1) - @ExchangeRate), 2),
			-- this is for GLCDebit/GLCCredit
			@GLCCurrencyID, 
			1, -- Exchange Rate = 1
			0,
			Round(iab.Amount * (isnull(abi.GLCExchangeRate, 1) - @GLCExchangeRate), 2) 
		From   tInvoiceAdvanceBill iab (nolock)
			Inner Join tInvoice abi (NOLOCK) ON iab.AdvBillInvoiceKey = abi.InvoiceKey -- go to the AdvBill invoice
		Where	iab.InvoiceKey = @InvoiceKey
		And     isnull(iab.FromAB, 0) = 0
	
	end

	---------------------------------
	-- Advance Bills with  FromAB = 1
	-- Again here, since we are dealing with reversals, get ExchangeRate from the other side
	---------------------------------

	-- Credit AR with total applied amount, this is a reversal
	SELECT @PostSide = ''C''
			   ,@GLAccountKey = @ARAccountKey
				,@GLAccountErrRet = @kErrInvalidARAcct 
			  ,@Amount = @AdvBillAmountFromAB
			  ,@Memo = @kMemoAdvBill  + @InvoiceNumber + '' Credit AR'', @Section = @kSectionHeader  
			  ,@OfficeKey = @HeaderOfficeKey -- @OfficeKey = NULL -- 558576 take the office on the header instead of null...but below we get it from the other invoice
			  ,@DepartmentKey = NULL, @DetailLineKey = NULL

		/* We need to split this debit to include the possible various ExchangeRate values on the AB invoices
		exec spGLInsertTranTemp @CompanyKey,@PostSide,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Amount,@ClassKey,@Memo, 
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@GLCompanyKey,@OfficeKey,@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, null, 1
		*/
		
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID, ExchangeRate,GLCCurrencyID, GLCExchangeRate)

		--SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,abi.ARAccountKey, --@GLAccountKey,   -- 472262 Invoices could have different AR accounts 
		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,   -- rolled back for 479102 
			0,
			iab.Amount   
			,ISNULL(abi.ClassKey, 0),  @Memo ,
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
			@GLCompanyKey,ISNULL(abi.OfficeKey, 0),@DepartmentKey,iab.InvoiceAdvanceBillKey,@Section,@GLAccountErrRet,
			abi.CurrencyID, @ExchangeRate -- or isnull(abi.ExchangeRate, 1) -- or @ExchangeRate
			,abi.GLCCurrencyID, @GLCExchangeRate
		From   tInvoiceAdvanceBill iab (nolock)
			Inner Join tInvoice abi (NOLOCK) ON iab.InvoiceKey = abi.InvoiceKey -- go to the Real invoice
		Where  iab.AdvBillInvoiceKey = @InvoiceKey	-- AdvBill invoice
		And    isnull(iab.FromAB, 0) = 1

	-- Debit Deferred Revenue with total NONTAX amount
	if @AdvBillNoTaxAmountFromAB <> 0
	BEGIN		
		SELECT @PostSide = ''D''
			  ,@GLAccountKey = @AdvBillAccountKey
			  ,@GLAccountErrRet = @kErrInvalidAdvBillAcct 
			  ,@Amount = @AdvBillNoTaxAmountFromAB
			  ,@Memo = @kMemoAdvBill  + @InvoiceNumber + '' Debit Deferred Revenue'', @Section = @kSectionHeader  
			  ,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

		/* We need to split this debit to include the possible various ExchangeRate values on the AB invoices
		exec spGLInsertTranTemp @CompanyKey,@PostSide,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Amount,@ClassKey,@Memo, 
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@GLCompanyKey,@OfficeKey,@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, null, 1
		*/
		
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID, ExchangeRate,GLCCurrencyID, GLCExchangeRate)

		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey, 
			iab.Amount - ISNULL((
				select sum(iabt.Amount) from tInvoiceAdvanceBillTax iabt (nolock)
				where iabt.InvoiceKey = iab.InvoiceKey
				and   iabt.AdvBillInvoiceKey = @InvoiceKey  
			),0)
			, 0, ISNULL(abi.ClassKey, 0),  @Memo ,
			@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
			@GLCompanyKey,ISNULL(abi.OfficeKey, 0),@DepartmentKey,iab.InvoiceAdvanceBillKey,@Section,@GLAccountErrRet,
			abi.CurrencyID, isnull(abi.ExchangeRate, 1), abi.GLCCurrencyID, isnull(abi.GLCExchangeRate, 1)
		From   tInvoiceAdvanceBill iab (nolock)
			Inner Join tInvoice abi (NOLOCK) ON iab.InvoiceKey = abi.InvoiceKey -- go to the Real invoice
		Where  iab.AdvBillInvoiceKey = @InvoiceKey	-- AdvBill invoice
		And    isnull(iab.FromAB, 0) = 1

	END
	
	-- Debit Advance Bill Sales Taxes
	SELECT @PostSide = ''D'',@GLAccountErrRet = @kErrInvalidSalesTax3Acct
			,@Memo = @kMemoAdvBill + @InvoiceNumber, @Section = @kSectionSalesTax  
			,@DepartmentKey = NULL, @DetailLineKey = NULL

	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,CurrencyID, ExchangeRate,GLCCurrencyID, GLCExchangeRate)
	
	-- group probably by gl account, class, office
	SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
		st.PayableGLAccountKey, Sum(iabt.Amount), 0,
		ISNULL(abi.ClassKey, 0),  @Memo + '' Debit sales tax '',
		@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
		@GLCompanyKey,ISNULL(abi.OfficeKey, 0),@DepartmentKey,st.SalesTaxKey,@Section,@GLAccountErrRet,
		abi.CurrencyID, isnull(abi.ExchangeRate, 1), abi.GLCCurrencyID, isnull(abi.GLCExchangeRate, 1)
	From   tInvoiceAdvanceBillTax iabt (nolock)
		Inner Join tInvoiceAdvanceBill iab (nolock) on iabt.AdvBillInvoiceKey = iab.AdvBillInvoiceKey
				and iabt.InvoiceKey = iab.InvoiceKey  
		Inner Join tInvoice abi (NOLOCK) ON iabt.InvoiceKey = abi.InvoiceKey -- go to the Real invoice
		Inner Join tSalesTax st (NOLOCK) ON iabt.SalesTaxKey = st.SalesTaxKey
	Where  iabt.AdvBillInvoiceKey = @InvoiceKey	-- AdvBill invoice
	and    isnull(iab.FromAB, 0) = 1
	Group by st.SalesTaxKey, st.PayableGLAccountKey, ISNULL(abi.ClassKey, 0), ISNULL(abi.OfficeKey, 0) 
			,abi.CurrencyID, isnull(abi.ExchangeRate, 1),abi.GLCCurrencyID, isnull(abi.GLCExchangeRate, 1)

	-- Now process the Realized Gain/Loss for the advance bills
	if @MultiCurrency = 1
	begin
	
		SELECT @PostSide = ''C'', @GLAccountKey = @RealizedGainAccountKey, @GLAccountErrRet = @kErrInvalidRealizedGainAcct 
				,@Memo = @kMemoRealizedGain, @Section = @kSectionMCGain    
				,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
	
	
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GPFlag, CurrencyID, ExchangeRate, HDebit, HCredit,
			GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
	
		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
			@GLAccountKey, 0, 0,
			null, -- @ClassKey, null it like ICT  
			@Memo + '' Adv Bill '' + abi.InvoiceNumber, 
			@ClientKey,
			null, --@ProjectKey
			@SourceCompanyKey,
			@DepositKey,@PostSide,
			@GLCompanyKey,@OfficeKey,@DepartmentKey,iab.InvoiceAdvanceBillKey,@Section,@GLAccountErrRet, 0,
			null, -- Home Currency
			1, -- Exchange Rate = 1
			0,
			Round(iab.Amount * (-1 * @ExchangeRate + isnull(abi.ExchangeRate, 1) ), 2),
			-- GLC info
			@GLCCurrencyID, -- GL company Home Currency
			1, -- Exchange Rate = 1
			0,
			Round(iab.Amount * (-1 * @GLCExchangeRate + isnull(abi.GLCExchangeRate, 1) ), 2) 
		From   tInvoiceAdvanceBill iab (nolock)
			Inner Join tInvoice abi (NOLOCK) ON iab.InvoiceKey = abi.InvoiceKey -- go to the Real invoice
		Where	iab.AdvBillInvoiceKey = @InvoiceKey
		And     isnull(iab.FromAB, 0) = 1
	
	end


	/*		
	*Reverse the prepayments 
	*/
	
	SELECT @PostSide = ''D'' ,@GLAccountErrRet = @kErrInvalidPrepayAcct 
			,@Memo = @kMemoPrepayments , @Section = @kSectionPrepayments   
			,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL

	-- One entry per payment applied
	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GPFlag, CurrencyID, ExchangeRate,GLCCurrencyID, GLCExchangeRate)
	
	SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
		c.PrepayAccountKey, ca.Amount, 0,
		c.ClassKey,  @Memo + c.ReferenceNumber ,
		@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide,
		c.GLCompanyKey,@OfficeKey,@DepartmentKey,ca.CheckApplKey,@Section,@GLAccountErrRet, 1,
		c.CurrencyID, isnull(c.ExchangeRate, 1),c.GLCCurrencyID, isnull(c.GLCExchangeRate, 1)
	From   tCheckAppl ca (nolock)
		Inner Join tCheck c (NOLOCK) ON ca.CheckKey = c.CheckKey
	Where	ca.InvoiceKey = @InvoiceKey
	And		ca.Prepay = 1
	
	-- We must also reverse the AR -- Credit -- Use Class on Invoice Header
	-- One entry for all prepayments
	SELECT @PostSide = ''C'', @GLAccountKey = @ARAccountKey, @GLAccountErrRet = @kErrInvalidARAcct 
			,@Memo = @kMemoPrepayments, @Section = @kSectionPrepayments    
			,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
	
	
	SELECT @Amount = SUM(Debit) FROM #tTransaction WHERE [Section]=@kSectionPrepayments AND Entity = @Entity AND EntityKey = @EntityKey
	UPDATE #tTransaction SET GPFlag = 0 WHERE Entity = @Entity AND EntityKey = @EntityKey

	exec spGLInsertTranTemp @CompanyKey,@PostSide,@TransactionDate,@Entity,@EntityKey,@Reference,@GLAccountKey,@Amount,@ClassKey,@Memo, 
		@ClientKey,@ProjectKey,@SourceCompanyKey,@DepositKey,@GLCompanyKey,@OfficeKey,@DepartmentKey,@DetailLineKey,@Section,@GLAccountErrRet, 
		@CurrencyID, @ExchangeRate, @GLCCurrencyID, @GLCExchangeRate
	
	-- Now process the Realized Gain/Loss for the prepayments
	if @MultiCurrency = 1
	begin
		SELECT @PostSide = ''C'', @GLAccountKey = @RealizedGainAccountKey, @GLAccountErrRet = @kErrInvalidRealizedGainAcct 
				,@Memo = @kMemoRealizedGain, @Section = @kSectionMCGain    
				,@OfficeKey = NULL, @DepartmentKey = NULL, @DetailLineKey = NULL
	
	
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
			Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
			DepartmentKey,DetailLineKey,Section,GLAccountErrRet, GPFlag, CurrencyID, ExchangeRate, HDebit, HCredit,
			GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
	
		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
			@GLAccountKey, 0, 0,
			null, -- @ClassKey, null it like ICT  
			@Memo + '' Check # '' + c.ReferenceNumber ,
			@ClientKey,
			null, -- @ProjectKey,
			@SourceCompanyKey,@DepositKey,@PostSide,
			@GLCompanyKey,@OfficeKey,@DepartmentKey,ca.CheckApplKey,@Section,@GLAccountErrRet, 0,
			null, -- Home Currency
			1, -- Exchange Rate = 1
			0,
			Round(ca.Amount * (isnull(c.ExchangeRate, 1) - @ExchangeRate), 2),
			@GLCCurrencyID, -- GL company Home Currency
			1, -- Exchange Rate = 1
			0,
			Round(ca.Amount * (isnull(c.GLCExchangeRate, 1) - @GLCExchangeRate), 2)
		From   tCheckAppl ca (nolock)
			Inner Join tCheck c (NOLOCK) ON ca.CheckKey = c.CheckKey
		Where	ca.InvoiceKey = @InvoiceKey
		And		ca.Prepay = 1
		
	end

	 /*
	 * Invoice Lines
	 */

	-- If No Transactions, just look at the invoice lines, not the detail transactions
	-- GL Sales Account, office, department, class, project from the line
	SELECT @PostSide = ''C'', @GLAccountErrRet = @kErrInvalidLineAcct   
			,@Memo = @kMemoLine + @InvoiceNumber , @Section = @kSectionLine   

	-- One entry per line
	INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,
		-- CurrencyID and ExchangeRate are set below, but take care of GL companies and ICT now 
		GLCCurrencyID, GLCExchangeRate,ICTExchangeRate, ICTGLCExchangeRate)
	
	SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
		il.SalesAccountKey, 0, ROUND(il.TotalAmount * @Percent, 2),
		il.ClassKey, Left(@Memo + '' '' + rtrim(ltrim(il.LineSubject)), 500),
		@ClientKey,il.ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide

		-- ICT
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end

		,il.OfficeKey,il.DepartmentKey,il.InvoiceLineKey,@Section,@GLAccountErrRet

		-- ICT
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 -- or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
			then @GLCCurrencyID else glc.CurrencyID end
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 -- or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
			then @GLCExchangeRate else isnull(il.GLCExchangeRate, 1) end

		-- this is expected by the ICT sp, should be the new rates when we apply payments to invoice
		,@ExchangeRate 
		, case when isnull(il.TargetGLCompanyKey, 0) = 0 -- or isnull(glc.CurrencyID, '''') = isnull(@GLCCurrencyID, '''') 
			then @GLCExchangeRate else isnull(il.GLCExchangeRate, 1) end

	From  tInvoiceLine il (nolock)
		Left Join tGLCompany glc (nolock) on il.TargetGLCompanyKey = glc.GLCompanyKey
	Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
	And    il.BillFrom = @kLineNoTransactions
	And    il.LineType = @kLineTypeDetail

	-- If Use Transactions, look at the detail transactions for some fields, not the invoice lines 
	-- If PostSalesUsingDetail = 1 get GL Sales Account + class from transactions
	-- If PostSalesUsingDetail = 0 get GL Account + class from lines
	-- Office, Department, project from the transactions
	If exists(Select 1 from tInvoiceLine (nolock) Where InvoiceKey = @LineInvoiceKey 
				and BillFrom = @kLineUseTransactions And LineType = @kLineTypeDetail)
	Begin			
	
		If @TrackOverUnder = 0
		Begin 		
			-- we do not care about standard, over under amount, just take amount	
			/*
			
			-- This View takes too long on APP/APP2!!!!!
			
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount)
			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(v.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(v.ClassKey,0) ELSE ISNULL(il.ClassKey, 0) END
			,ISNULL(v.OfficeKey, 0), ISNULL(v.DepartmentKey, 0), ISNULL(v.ProjectKey, 0)
			, v.Amount * @Percent
			From tInvoiceLine il (nolock)
				Inner Join vSalesGLDetail v (nolock) on il.InvoiceLineKey = v.InvoiceLineKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			*/
			
			-- Labor
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(s.GLAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
						ELSE ISNULL(s.ClassKey, 0) 
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0)
			--, case when @DefaultDepartmentFromUser = 0 then ISNULL(s.DepartmentKey, 0) else ISNULL(u.DepartmentKey, 0) end 
			, case when t.DepartmentKey is not null then t.DepartmentKey else
				case when @DefaultDepartmentFromUser = 0 then ISNULL(s.DepartmentKey, 0) else ISNULL(u.DepartmentKey, 0) end
			 end
			, ISNULL(t.ProjectKey, 0)
			, ROUND(t.BilledHours * t.BilledRate, 2) 

			,''tTime'', null, null 
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey -- we will look later at p.GLCompanySource
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, t.UserKey
			
			From tInvoiceLine il (nolock)
				Inner Join tTime t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tUser u (nolock) on t.UserKey = u.UserKey
				left outer join tService s (nolock) on t.BilledService = s.ServiceKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- Misc Cost
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0), ISNULL(t.DepartmentKey, isnull(it.DepartmentKey,0)), ISNULL(t.ProjectKey, 0)
			, t.AmountBilled

			,''tMiscCost'', t.MiscCostKey, null

			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tMiscCost t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- ER
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
						ELSE ISNULL(it.ClassKey, 0) 
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0), ISNULL(it.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, t.AmountBilled 

			,''tExpenseReceipt'', t.ExpenseReceiptKey, null
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey -- we will look later at p.GLCompanySource
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, t.UserKey
			
			From tInvoiceLine il (nolock)
				Inner Join tExpenseReceipt t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- VI
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(t.OfficeKey, 0), ISNULL(t.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, t.AmountBilled 

			,''tVoucherDetail'', t.VoucherDetailKey, null

			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN case when isnull(t.TargetGLCompanyKey, 0) = 0 then v.GLCompanyKey else t.TargetGLCompanyKey end 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null

			From tInvoiceLine il (nolock)
				Inner Join tVoucherDetail t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tVoucher v (nolock) on t.VoucherKey = v.VoucherKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail

			-- PO
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			
			,ISNULL(t.OfficeKey, 0), ISNULL(t.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, t.AmountBilled 

			-- for PO our best bet is to get the GLCompany from the PO (could come from the media estimate) 
			,''tPurchaseOrderDetail'', t.PurchaseOrderDetailKey, null
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN po.GLCompanyKey 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tPurchaseOrderDetail t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tPurchaseOrder po (nolock) on t.PurchaseOrderKey = po.PurchaseOrderKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail

						
		End -- @TrackOverUnder = 0

		If @TrackOverUnder = 1
		Begin
			/*
			-- Standard Part
			
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount)
			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(v.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(v.ClassKey,0) ELSE ISNULL(il.ClassKey, 0) END
			,ISNULL(v.OfficeKey, 0), ISNULL(v.DepartmentKey, 0), ISNULL(v.ProjectKey, 0)
			,v.Standard * @Percent
			From tInvoiceLine il (nolock)
				Inner Join vSalesGLDetail v (nolock) on il.InvoiceLineKey = v.InvoiceLineKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
	
			*/
			
			-- Standard Part
			
			-- Labor
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(s.GLAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(p.ClassKey, 0) > 0 
						THEN ISNULL(p.ClassKey, 0) 
						ELSE ISNULL(s.ClassKey, 0) 
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0)
			--, case when @DefaultDepartmentFromUser = 0 then ISNULL(s.DepartmentKey, 0) else ISNULL(u.DepartmentKey, 0) end 
			, case when t.DepartmentKey is not null then t.DepartmentKey else
				case when @DefaultDepartmentFromUser = 0 then ISNULL(s.DepartmentKey, 0) else ISNULL(u.DepartmentKey, 0) end
			 end
			, ISNULL(t.ProjectKey, 0)
			, ROUND(t.ActualHours * t.ActualRate, 2) 

			,''tTime'', null, null

			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey -- we will look later at p.GLCompanySource
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			
			, t.UserKey
			
			From tInvoiceLine il (nolock)
				Inner Join tTime t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tUser u (nolock) on t.UserKey = u.UserKey
				left outer join tService s (nolock) on t.BilledService = s.ServiceKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- Misc Cost
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0), ISNULL(t.DepartmentKey, isnull(it.DepartmentKey,0)), ISNULL(t.ProjectKey, 0)
			, t.BillableCost 

			-- for misc costs, we can only take GLCompanyKey from project...so we should be done
			,''tMiscCost'', t.MiscCostKey, null
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tMiscCost t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- ER
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
						ELSE ISNULL(it.ClassKey, 0) 
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0), ISNULL(it.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, t.BillableCost
			
			,''tExpenseReceipt'', t.ExpenseReceiptKey, null
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey -- we will look later at p.GLCompanySource
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, t.UserKey
			 
			From tInvoiceLine il (nolock)
				Inner Join tExpenseReceipt t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- VI
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(t.OfficeKey, 0), ISNULL(t.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, t.BillableCost 

			,''tVoucherDetail'', t.VoucherDetailKey, null
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN case when isnull(t.TargetGLCompanyKey, 0) = 0 then v.GLCompanyKey else t.TargetGLCompanyKey end 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tVoucherDetail t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tVoucher v (nolock) on t.VoucherKey = v.VoucherKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail

			-- PO
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(it.SalesAccountKey,0) ELSE ISNULL(il.SalesAccountKey, 0) END
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN @kErrInvalidSalesAcct ELSE @kErrInvalidLineAcct END
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(t.OfficeKey, 0), ISNULL(t.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			,CASE 
				WHEN po.BillAt = 0 THEN t.BillableCost
				WHEN po.BillAt = 1 THEN t.TotalCost 
				WHEN po.BillAt = 2 THEN (t.BillableCost - t.TotalCost) 
				ELSE t.BillableCost
			END 
			
			-- for PO our best bet is to get the GLCompany from the PO (could come from the media estimate) 
			,''tPurchaseOrderDetail'', t.PurchaseOrderDetailKey, null
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN po.GLCompanyKey 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tPurchaseOrderDetail t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tPurchaseOrder po (nolock) on t.PurchaseOrderKey = po.PurchaseOrderKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail

			
			/*
			
			-- Over Under Part
			
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount)
			Select il.InvoiceLineKey 
			,CASE WHEN v.Type = ''L'' THEN ISNULL(@LaborOUAccountKey, 0) ELSE ISNULL(@ExpenseOUAccountKey, 0) END
			,@kErrInvalidOUAcct
			,CASE WHEN il.PostSalesUsingDetail = 1 THEN ISNULL(v.ClassKey,0) ELSE ISNULL(il.ClassKey, 0) END
			,ISNULL(v.OfficeKey, 0), ISNULL(v.DepartmentKey, 0), ISNULL(v.ProjectKey, 0)
			, (v.Amount - v.Standard) * @Percent
			From tInvoiceLine il (nolock)
				Inner Join vSalesGLDetail v (nolock) on il.InvoiceLineKey = v.InvoiceLineKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			*/
			
			-- Over Under Part
			
			-- Labor
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,ISNULL(@LaborOUAccountKey, 0)
			,@kErrInvalidOUAcct
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(p.ClassKey, 0) > 0 
						THEN ISNULL(p.ClassKey, 0) 
						ELSE ISNULL(s.ClassKey, 0) 
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0)
			--, case when @DefaultDepartmentFromUser = 0 then ISNULL(s.DepartmentKey, 0) else ISNULL(u.DepartmentKey, 0) end 
			, case when t.DepartmentKey is not null then t.DepartmentKey else
				case when @DefaultDepartmentFromUser = 0 then ISNULL(s.DepartmentKey, 0) else ISNULL(u.DepartmentKey, 0) end
			 end
			, ISNULL(t.ProjectKey, 0)
			,ROUND(t.BilledHours * t.BilledRate, 2) - ROUND(t.ActualHours * t.ActualRate, 2)
			
			,''tTime'', null, null
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey -- we will look later at p.GLCompanySource
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, t.UserKey
			 
			From tInvoiceLine il (nolock)
				Inner Join tTime t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tUser u (nolock) on t.UserKey = u.UserKey
				left outer join tService s (nolock) on t.BilledService = s.ServiceKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- Misc Cost
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,ISNULL(@ExpenseOUAccountKey, 0)
			,@kErrInvalidOUAcct
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0), ISNULL(t.DepartmentKey, isnull(it.DepartmentKey,0)), ISNULL(t.ProjectKey, 0)
			, t.AmountBilled - t.BillableCost

			-- for misc costs, we can only take GLCompanyKey from project...so we should be done
			,''tMiscCost'', t.MiscCostKey, null
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null

			From tInvoiceLine il (nolock)
				Inner Join tMiscCost t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- ER
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,ISNULL(@ExpenseOUAccountKey, 0)
			,@kErrInvalidOUAcct
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
						ELSE ISNULL(it.ClassKey, 0) 
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(p.OfficeKey, 0), ISNULL(it.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			,(t.AmountBilled - t.BillableCost)

			,''tExpenseReceipt'', t.ExpenseReceiptKey, null
			
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN p.GLCompanyKey -- we will look later at p.GLCompanySource
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, t.UserKey

			From tInvoiceLine il (nolock)
				Inner Join tExpenseReceipt t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- VI
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,ISNULL(@ExpenseOUAccountKey, 0)
			,@kErrInvalidOUAcct
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(t.OfficeKey, 0), ISNULL(t.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, (t.AmountBilled - t.BillableCost)

			,''tVoucherDetail'', t.VoucherDetailKey, null
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN case when isnull(t.TargetGLCompanyKey, 0) = 0 then v.GLCompanyKey else t.TargetGLCompanyKey end 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tVoucherDetail t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tVoucher v (nolock) on t.VoucherKey = v.VoucherKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
			-- PO
			INSERT 	#tLineDetail(InvoiceLineKey, GLAccountKey, GLAccountErrRet, ClassKey, 
			OfficeKey, DepartmentKey, ProjectKey, Amount
			,Entity, EntityKey, GLCompanySource, GLCompanyKey, UserKey)

			Select il.InvoiceLineKey 
			,ISNULL(@ExpenseOUAccountKey, 0)
			,@kErrInvalidOUAcct
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN 
					CASE WHEN ISNULL(t.ClassKey, 0) > 0 THEN t.ClassKey
					ELSE
						CASE WHEN ISNULL(p.ClassKey, 0) > 0 THEN ISNULL(p.ClassKey, 0) 
							ELSE ISNULL(it.ClassKey, 0) 
						END
					END 
				ELSE 
					ISNULL(il.ClassKey, 0) 
			END
			,ISNULL(t.OfficeKey, 0), ISNULL(t.DepartmentKey, 0), ISNULL(t.ProjectKey, 0)
			, (t.AmountBilled 
			- CASE 
				WHEN po.BillAt = 0 THEN t.BillableCost 
				WHEN po.BillAt = 1 THEN t.TotalCost
				WHEN po.BillAt = 2 THEN t.BillableCost - t.TotalCost
				ELSE t.BillableCost			
			END 
			) 

			-- for PO our best bet is to get the GLCompany from the PO (could come from the media estimate) 
			,''tPurchaseOrderDetail'', t.PurchaseOrderDetailKey, null
			,CASE WHEN il.PostSalesUsingDetail = 1 
				THEN po.GLCompanyKey 
				else
					case when isnull(il.TargetGLCompanyKey, 0) = 0 then @GLCompanyKey else il.TargetGLCompanyKey end
			end
			, null
			
			From tInvoiceLine il (nolock)
				Inner Join tPurchaseOrderDetail t (nolock) on il.InvoiceLineKey = t.InvoiceLineKey
				Inner Join tPurchaseOrder po (nolock) on t.PurchaseOrderKey = po.PurchaseOrderKey
				left outer join tItem it (nolock) on isnull(t.BilledItem,t.ItemKey) = it.ItemKey
				left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
			Where  il.InvoiceKey = @LineInvoiceKey -- Point to invoice where the lines are
			And    il.BillFrom = @kLineUseTransactions And il.LineType = @kLineTypeDetail
			
		End

		-- GLCompanySource will only be used for Time/Exp Receipts

		-- correct the GLCompanySource if there is project
		update #tLineDetail
		set    #tLineDetail.GLCompanySource = isnull(p.GLCompanySource, 0)
		from   tProject p (nolock)
		where  #tLineDetail.ProjectKey = p.ProjectKey
		and    isnull(#tLineDetail.ProjectKey, 0) > 0
		
		-- if there is no project, get it from user
		update #tLineDetail
		set    #tLineDetail.GLCompanySource = 1
		where  isnull(#tLineDetail.ProjectKey, 0) = 0
		
		-- but this has to be done only if PostSalesUsingDetail = 1
		-- if PostSalesUsingDetail = 0, we already got it from the invoice line
		update #tLineDetail
		set    #tLineDetail.GLCompanySource = 0 -- do not get from user
		from   tInvoiceLine il (nolock)
		where  #tLineDetail.InvoiceLineKey = il.InvoiceLineKey
		and    isnull(il.PostSalesUsingDetail, 0) = 0
		

		-- by default GLCompanyKey and Office Key were obtained from project
		-- get them from user if GLCompanySource = 1 
		-- Also Added Class
		update #tLineDetail
		set    #tLineDetail.GLCompanyKey = ISNULL(u.GLCompanyKey, #tLineDetail.GLCompanyKey)
		      ,#tLineDetail.OfficeKey = ISNULL(u.OfficeKey, #tLineDetail.OfficeKey)  -- must overwrite the office initially from project
			  ,#tLineDetail.ClassKey = ISNULL(u.ClassKey, #tLineDetail.ClassKey)  
		from   tUser u (nolock)
		where  #tLineDetail.UserKey = u.UserKey
		and    isnull(#tLineDetail.GLCompanySource, 0) = 1 -- From User
		and    #tLineDetail.Entity in (''tTime'', ''tExpenseReceipt'')

		--cleanup for groupings

		update #tLineDetail
		set    #tLineDetail.GLCompanyKey = isnull(#tLineDetail.GLCompanyKey, 0)
		      ,#tLineDetail.OfficeKey = isnull(#tLineDetail.OfficeKey, 0)
			  ,#tLineDetail.GLCExchangeRate = @GLCExchangeRate -- by default use the rate on the header

		-- now find the GLCExchangeRate
		update #tLineDetail
		set    #tLineDetail.GLCCurrencyID = glc.CurrencyID 
		from   tGLCompany glc (nolock)
		where  #tLineDetail.GLCompanyKey = glc.GLCompanyKey
	
		-- use the rate on the line
		update #tLineDetail
		set    #tLineDetail.GLCExchangeRate = il.GLCExchangeRate 
		from   tInvoiceLine il (nolock)
		where  #tLineDetail.InvoiceLineKey = il.InvoiceLineKey
		and isnull(il.TargetGLCompanyKey,0) >0 and isnull(#tLineDetail.GLCCurrencyID, '''') != isnull(@GLCCurrencyID, '''') 

		-- if the GL currency is blank, that means it is = the home currency, so take the @ExchangeRate
		update #tLineDetail
		set    #tLineDetail.GLCExchangeRate = @ExchangeRate 
		where  isnull(#tLineDetail.GLCCurrencyID, '''') = '''' 

		-- It is possible that there could be a GLC rate not correctly extracted, in that case we could get it from tCurrencyRate 

		SELECT @PostSide = ''C'', @Memo = @kMemoLine + @InvoiceNumber , @Section = @kSectionLine   
		
		INSERT #tTransaction(CompanyKey,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section,GLAccountErrRet,GLCCurrencyID,GLCExchangeRate,ICTExchangeRate,ICTGLCExchangeRate)
				
		SELECT @CompanyKey,@TransactionDate,@Entity,@EntityKey,@Reference,
			b.GLAccountKey, 0, ROUND(Sum(b.Amount) * @Percent, 2), b.ClassKey,
			Left(@Memo + '' '' + rtrim(ltrim(il.LineSubject)), 500), 
			@ClientKey,b.ProjectKey,@SourceCompanyKey,@DepositKey,@PostSide, b.GLCompanyKey, b.OfficeKey
			,b.DepartmentKey,b.InvoiceLineKey,@Section,b.GLAccountErrRet
			,b.GLCCurrencyID,b.GLCExchangeRate,@ExchangeRate,b.GLCExchangeRate
		From #tLineDetail b
		Inner Join tInvoiceLine il on b.InvoiceLineKey = il.InvoiceLineKey
		Group By b.InvoiceLineKey, il.LineSubject, b.GLAccountKey, b.GLAccountErrRet, b.GLCompanyKey,b.GLCCurrencyID,b.GLCExchangeRate
		,b.ClassKey, b.OfficeKey, b.DepartmentKey, b.ProjectKey
						 
	 End
	 		
	-- on the lines TM or FF, copy currency and exch rate from header			 		
	update #tTransaction
	set    CurrencyID = @CurrencyID
	      ,ExchangeRate = @ExchangeRate
	where  Entity = @Entity
	and    EntityKey = @EntityKey
	and    [Section] = @kSectionLine

	/*
	 * End Invoice Lines
	 */

end -- @PostBody = 1

	-- Correct and prepared data for final insert
	EXEC spGLPostCleanupTemp @Entity, @EntityKey, @TransactionDate 
	
	-- Patch To fix rounding errors with split billing
	If @Percent <> 1 -- or @Percentage <> 100 
	BEGIN
		DECLARE @SplitDetailLineKey INT
		DECLARE @SplitRoundingError MONEY
		DECLARE @SplitMaxAmount MONEY
		
		--select * from #tTransaction
		
		SELECT @SplitRoundingError = 
		(SELECT SUM(Debit - Credit)
		FROM   #tTransaction
		WHERE  Entity = @Entity
		AND    EntityKey = @EntityKey
		)
		
		--select @SplitRoundingError
		
		-- If there is a rounding error, add it to one line		
		IF @SplitRoundingError <> 0
		BEGIN
			-- use our general purpose flag to identify each line
			SELECT @SplitDetailLineKey = 0
			UPDATE #tTransaction
			SET    #tTransaction.GPFlag = @SplitDetailLineKey
			       ,@SplitDetailLineKey = @SplitDetailLineKey + 1
			WHERE  Entity = @Entity
			AND    EntityKey = @EntityKey
			AND    [Section] = 2 -- line
			
			-- We will modify the line with the max amount
			SELECT @SplitMaxAmount = MAX(ABS(Debit - Credit))
			FROM   #tTransaction
			WHERE  Entity = @Entity
			AND    EntityKey = @EntityKey
			AND    [Section] = 2 -- line
			
			SELECT @SplitDetailLineKey = NULL
			
			SELECT @SplitDetailLineKey = GPFlag
			FROM   #tTransaction
			WHERE  Entity = @Entity
			AND    EntityKey = @EntityKey
			AND    [Section] = 2 -- line
			AND    ABS(Debit - Credit) = @SplitMaxAmount
			
			IF @SplitDetailLineKey IS NOT NULL
				UPDATE #tTransaction
				SET    Credit = Credit + @SplitRoundingError
				       ,HCredit = HCredit + @SplitRoundingError
				WHERE  Entity = @Entity
				AND    EntityKey = @EntityKey
				AND    [Section] = 2 -- line
				AND    GPFlag = @SplitDetailLineKey
			
		END
	END


    --select CurrencyID, ExchangeRate, GLCCurrencyID, GLCExchangeRate, * from #tTransaction
	--return 1

	-- Exit when we are not really posting, but preposting
	--IF @Prepost = 1
	--	RETURN 1
		
	/*
	 * Validations
	 */

	if @MultiCurrency = 1
	begin
		-- Next flip sides to make it positive like Xero does
		update #tTransaction
		set    HDebit = -1 * HCredit
			  ,HCredit = 0
			  ,PostSide = ''D''
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(HCredit, 0) < 0 

		update #tTransaction
		set    HCredit = -1 * HDebit
			  ,HDebit = 0
			  ,PostSide = ''C''
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(HDebit, 0) < 0 

		-- do the same for the GLC Debit/Credit, do not change PostSide
		update #tTransaction
		set    GLCDebit = -1 * GLCCredit
				,GLCCredit = 0
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(GLCCredit, 0) < 0 

		update #tTransaction
		set    GLCCredit = -1 * GLCDebit
				,GLCDebit = 0
		where  Entity = @Entity and EntityKey = @EntityKey  
		and    [Section] = @kSectionMCGain
		and    isnull(GLCDebit, 0) < 0 
	
		-- spGLPostCalcRoundingDiff was moved below so do not do that now, must be done after ICT
		--1 Accrual Basis, 1 Force to Rounding account
		--exec spGLPostCalcRoundingDiff @CompanyKey,@Entity,@EntityKey,1,1,@GLCompanyKey,@TransactionDate,@Reference, @RoundingDiffAccountKey,@RealizedGainAccountKey 
		
		/*
		if @IsCreditInvoice = 1 and isnull(@CurrencyID, '''') <> ''''
			exec spGLPostCredit @CompanyKey,@Entity,@EntityKey

		 
		if exists (select 1 from #tTransaction where Section in (@kSectionMCRounding, @kSectionMCGain))
		begin
			-- Correct and prepared data for final insert
			EXEC spGLPostCleanupTemp @Entity, @EntityKey, @TransactionDate 
		end
		*/
	end
	
	-- Create DT and DF for ICT -- 1 Accrual Basis
	select @Memo = @kMemoHeader + @InvoiceNumber
	exec spGLPostICTCreateCurrencyDTDF @CompanyKey,@Entity,@EntityKey,1,@GLCompanyKey,@TransactionDate,@Memo,@Reference, @GLCExchangeRate  

	if @MultiCurrency = 1
	begin
	-- 1 Accrual, 1 Rounding acct
		exec spGLPostCalcRoundingDiff @CompanyKey,@Entity,@EntityKey,1,1,@GLCompanyKey,@TransactionDate
			,@Reference, @RoundingDiffAccountKey,@RealizedGainAccountKey, @GLCCurrencyID 

        -- these credits should be balanced
		if @IsCreditInvoice = 1 and isnull(@CurrencyID, '''') <> ''''
			exec spGLPostCredit @CompanyKey,@Entity,@EntityKey

		-- if a regular invoice is posted 2nd, handle FX for any already-posted credits applied to it
		if @IsCreditInvoice = 0 and isnull(@CurrencyID, '''') <> ''''
			exec spGLPostCredit @CompanyKey,@Entity,@EntityKey, @PostingFromRegular = 1

	end

	--if exists (select 1 from #tTransaction where Section = @kSectionICT)
	--begin
		-- Correct and prepared data for final insert
		EXEC spGLPostCleanupTemp @Entity, @EntityKey, @TransactionDate 
	--end

	Select @TransactionCount = COUNT(*) from #tTransaction Where Entity = @Entity and EntityKey = @EntityKey
	
	EXEC @RetVal = spGLValidatePostTemp @CompanyKey, @Entity, @EntityKey, @kErrBalance, @kErrPosted 

	-- Exit when we are not really posting, but preposting
	IF @Prepost = 1
		RETURN 1

	IF @RetVal <> 1
		RETURN @RetVal
	
	-- once the transaction lines have been validated, store them in #tCashTransactionLine
	INSERT #tCashTransactionLine(CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, TempTranLineKey,
		AdvBillAmount, PrepaymentAmount, ReceiptAmount, CurrencyID, ExchangeRate, HDebit, HCredit, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
		
	SELECT CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, TempTranLineKey,
		0,0,0, CurrencyID, ExchangeRate, HDebit, HCredit, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit	
		FROM #tTransaction 	
		WHERE Entity = @Entity AND EntityKey = @EntityKey
		AND   [Section] IN (2, 5) -- line or sales taxes
		AND   PostSide = ''C'' -- only credits

if @PostBody = 1
begin		 
	-- this will populate #tInvoiceAdvanceBillSale and #tCashTransactionLine.AdvBillAmount	 
	EXEC @RetVal = sptCashPostInvoiceFillABSale @InvoiceKey	
			
	-- and calculate the Prepayment and Receipt amounts
	EXEC @RetVal = sptCashPostInvoiceCalcLineAmounts @InvoiceKey
end	

	If Exists (Select 1 From #tTransaction Where [Section] = @kSectionICT and isnull(GLAccountKey, 0) = 0)
		return @kErrICTBlankGLAccount

	--select * from #tCashTransactionLine
					
	/*
	 * Cash-Basis prep
	 */
	
	IF @TrackCash = 1 --AND @OpeningTransaction = 0  --issue 201908 allow payments to reposted
	BEGIN

		CREATE TABLE #tCashQueue(
			Entity varchar(25) NULL,
			EntityKey int NULL,
			PostingDate smalldatetime NULL,
			QueueOrder int identity(1,1),
			PostingOrder int NULL,
			Action smallint NULL, 
			AdvanceBill int NULL
			)
			
		-- This table will track of which cash basis transactions are not valid anymore
		/*
		CREATE TABLE #tCashTransactionUnpost (
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Unpost int NULL)
		*/
		
		-- Just to get the same Entity''s collation
		SELECT Entity, EntityKey, 1 AS Unpost INTO #tCashTransactionUnpost 
		FROM tCashTransaction (NOLOCK) WHERE 1 = 2 
			
		CREATE TABLE #tCashTransaction (
			UIDCashTransactionKey uniqueidentifier null,
			
			-- Copied from tTransaction
			CompanyKey int NULL ,
			DateCreated smalldatetime NULL ,
			TransactionDate smalldatetime NULL ,
			Entity varchar (50) NULL ,
			EntityKey int NULL ,
			Reference varchar (100) NULL ,
			GLAccountKey int NULL ,
			Debit money NULL ,
			Credit money NULL ,
			ClassKey int NULL ,
			Memo varchar (500) NULL ,
			PostMonth int NULL,
			PostYear int NULL,
			PostSide char (1) NULL ,
			ClientKey int NULL ,
			ProjectKey int NULL ,
			SourceCompanyKey int NULL ,
			DepositKey int NULL ,
			GLCompanyKey int NULL ,
			OfficeKey int NULL ,
			DepartmentKey int NULL ,
			DetailLineKey int NULL ,
			Section int NULL, 
			Overhead tinyint NULL, 
			ICTGLCompanyKey int null,

			CurrencyID varchar(10) null,	-- 4 lines added for multicurrency
			ExchangeRate decimal(24,7) null,
			HDebit money null,
			HCredit money null,

			GLCCurrencyID varchar(10) null,	-- 4 lines added for multicurrency on GL companies
			GLCExchangeRate decimal(24,7) null,
			GLCDebit money null,
			GLCCredit money null, 

			ICTExchangeRate decimal(24,7) null, -- this is to be used by spGLPostICTCreateCurrencyDTDF
			ICTGLCExchangeRate decimal(24,7) null,	-- contains the current rate on payments instead of rate to reverse out

			-- Application fields
			AEntity varchar (50) NULL ,
			AEntityKey int NULL ,
			AReference varchar (100) NULL ,
			AEntity2 varchar (50) NULL ,
			AEntity2Key int NULL ,
			AReference2 varchar (100) NULL ,
			AAmount MONEY NULL,
			LineAmount MONEY NULL,
			
			CashTransactionLineKey INT NULL

			-- our work space
			,GLValid int null
			,GLAccountErrRet int null
			,GPFlag int null -- General purpose flag
			
			,UpdateTranLineKey int null
			)	 	
		
	Declare @PostingOrder int
	Declare @Action int Select @Action = 0 -- Posting
	Declare @CashEntity varchar(25)
	Declare @CashEntityKey varchar(25)
	Declare @CashPostingDate smalldatetime
	
	exec @RetVal = sptCashQueue @CompanyKey, @Entity, @EntityKey, @TransactionDate, @Action , @AdvanceBill
	
	--select * from #tCashQueue
	
	INSERT #tCashTransactionUnpost (Entity, EntityKey, Unpost)
	Select Entity, EntityKey, 1
	From   #tCashQueue (NOLOCK)
	Where  Action = 1 -- UnPosting
		 
	if @PostBody = 1
		begin
			 
			Select @PostingOrder = -1
			While (1=1)
			Begin
				Select @PostingOrder = MIN(PostingOrder)
				From   #tCashQueue (NOLOCK)
				Where  PostingOrder > @PostingOrder
				And    Action = 0 -- Posting
				
				If @PostingOrder is null
					break
					
				Select @CashEntity = Entity
					  ,@CashEntityKey = EntityKey
					  ,@CashPostingDate = PostingDate
				From   #tCashQueue (NOLOCK)
				Where  PostingOrder = @PostingOrder
				And    Action = 0 -- Posting
			
				If @CashEntity = ''INVOICE''
					exec @RetVal = sptCashPostInvoice @CompanyKey, @CashEntityKey	 
				
				If @CashEntity = ''RECEIPT''
					exec @RetVal = sptCashPostCheck @CompanyKey, @CashEntityKey
				  	
			End -- PostingOrder loop

			
		end -- PostBody = 1
	
		If Exists (Select 1 From #tCashTransaction Where [Section] = @kSectionICT and isnull(GLAccountKey, 0) = 0)
		return @kErrICTBlankGLAccount

	END -- End Track Cash


	/*
	 * Posting!!
	 */
	
	BEGIN TRAN
	
	Update tInvoice
	Set Posted = 1, InvoiceStatus = 4
	Where InvoiceKey = @InvoiceKey
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN @kErrUnexpected 	
	END		
	
	-- only do this if @OpeningTransaction = 0
	IF NOT EXISTS (SELECT 1 FROM tTransaction (NOLOCK) WHERE Entity = @Entity AND EntityKey = @EntityKey)
	AND @OpeningTransaction = 0
	BEGIN
		INSERT tTransaction(CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, ICTGLCompanyKey ,Reversed, Cleared, CurrencyID, ExchangeRate, HDebit, HCredit,
		GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit, PostedByKey)
		
		SELECT CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, ICTGLCompanyKey , 0, 0, CurrencyID, ExchangeRate, HDebit, HCredit,
		GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit, @UserKey
		FROM #tTransaction 	
		WHERE Entity = @Entity AND EntityKey = @EntityKey
		  
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END		
		
		UPDATE #tAccruedExpenseAccount
		SET    #tAccruedExpenseAccount.TransactionKey = t.TransactionKey 
		FROM   tTransaction t (NOLOCK)
		WHERE  t.Entity = @Entity AND t.EntityKey = @EntityKey 
		AND    t.Section = @kSectionPrebillAccruals AND t.DetailLineKey = #tAccruedExpenseAccount.TempTranLineKey
		
		INSERT tTransactionOrderAccrual (PurchaseOrderDetailKey, CompanyKey, AccrualAmount, TransactionKey, Entity, EntityKey, PostingDate)
		SELECT PurchaseOrderDetailKey, @CompanyKey, AccrualAmount, TransactionKey, @Entity, @EntityKey, @TransactionDate 
		FROM   #tAccruedExpenseAccount	 
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END		
		
	END		
	
	-- This must be done no matter what @OpeningTransaction is 0 or  1	
	--IF @TrackCash = 1 
	--BEGIN
		-- we may not have to do that deletion
		Delete tCashTransactionLine WHERE Entity = @Entity AND EntityKey = @EntityKey
	
		INSERT tCashTransactionLine(CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, Reversed, Cleared, TempTranLineKey,
		AdvBillAmount, PrepaymentAmount, ReceiptAmount, CurrencyID, ExchangeRate, HDebit, HCredit,
		GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
		
		SELECT CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, 0, 0, TempTranLineKey,	
		AdvBillAmount, PrepaymentAmount, ReceiptAmount, CurrencyID, ExchangeRate, HDebit, HCredit,
		GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit
		FROM #tCashTransactionLine 	
		WHERE Entity = @Entity AND EntityKey = @EntityKey
		AND   [Section] IN (2, 5) -- line or sales taxes
		AND   PostSide = ''C'' -- only credits
		  
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END		
	
		UPDATE #tInvoiceAdvanceBillSale
		SET    #tInvoiceAdvanceBillSale.CashTransactionLineKey = ctl.CashTransactionLineKey
		FROM   tCashTransactionLine ctl (NOLOCK)
		WHERE  ctl.Entity = ''INVOICE''
		AND    ctl.EntityKey = @InvoiceKey  
		AND    #tInvoiceAdvanceBillSale.TempTranLineKey = ctl.TempTranLineKey
		
		DELETE #tInvoiceAdvanceBillSale WHERE CashTransactionLineKey IS NULL
			
		INSERT tInvoiceAdvanceBillSale (InvoiceKey,AdvBillInvoiceKey,CashTransactionLineKey,Amount)		
		SELECT InvoiceKey,AdvBillInvoiceKey,CashTransactionLineKey,Amount
		FROM   #tInvoiceAdvanceBillSale
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END
	--END
	
	-- only do this if @OpeningTransaction = 0	
	IF @TrackCash = 1 -- AND @OpeningTransaction = 0 --issue 201908 allow payments to be reposted
	BEGIN
		
		DELETE tCashTransaction
		FROM   #tCashTransactionUnpost
		WHERE  tCashTransaction.Entity = #tCashTransactionUnpost.Entity 
		AND    tCashTransaction.EntityKey = #tCashTransactionUnpost.EntityKey
		AND    #tCashTransactionUnpost.Unpost = 1
		AND    (@OpeningTransaction = 0 OR
			tCashTransaction.Entity = ''RECEIPT'' -- only payments if OpeningTransaction = 1  
		)

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END
		
		-- must do 3 updates, one per each entity
		UPDATE #tCashTransaction
		SET    #tCashTransaction.CashTransactionLineKey = ctl.CashTransactionLineKey
		FROM   tCashTransactionLine ctl (NOLOCK)
		WHERE  ctl.Entity = ''INVOICE''
		AND    #tCashTransaction.Entity = ''INVOICE'' -- cannot equate Entity from temp to real table
		AND    #tCashTransaction.EntityKey = ctl.EntityKey
		AND    #tCashTransaction.CashTransactionLineKey = ctl.TempTranLineKey
		AND    #tCashTransaction.UpdateTranLineKey = 1
		
		UPDATE #tCashTransaction
		SET    #tCashTransaction.CashTransactionLineKey = ctl.CashTransactionLineKey
		FROM   tCashTransactionLine ctl (NOLOCK)
		WHERE  ctl.Entity = ''INVOICE''
		AND    #tCashTransaction.AEntity = ''INVOICE'' -- cannot equate Entity from temp to real table
		AND    #tCashTransaction.AEntityKey = ctl.EntityKey
		AND    #tCashTransaction.CashTransactionLineKey = ctl.TempTranLineKey
		AND    #tCashTransaction.UpdateTranLineKey = 1
		
		UPDATE #tCashTransaction
		SET    #tCashTransaction.CashTransactionLineKey = ctl.CashTransactionLineKey
		FROM   tCashTransactionLine ctl (NOLOCK)
		WHERE  ctl.Entity = ''INVOICE''
		AND    #tCashTransaction.AEntity2 = ''INVOICE'' -- cannot equate Entity from temp to real table
		AND    #tCashTransaction.AEntity2Key = ctl.EntityKey
		AND    #tCashTransaction.CashTransactionLineKey = ctl.TempTranLineKey
		AND    #tCashTransaction.UpdateTranLineKey = 1
		
		--select * from #tCashTransaction
		
		INSERT tCashTransaction(CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, ICTGLCompanyKey, Reversed, Cleared
		,UIDCashTransactionKey,AEntity,AEntityKey,AReference,AEntity2,AEntity2Key,AReference2,AAmount, LineAmount,CashTransactionLineKey
		,CurrencyID, ExchangeRate, HDebit, HCredit, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit)
		
		SELECT CompanyKey,DateCreated,TransactionDate,Entity,EntityKey,Reference,GLAccountKey,Debit,Credit,ClassKey,
		Memo,PostMonth,PostYear,ClientKey,ProjectKey,SourceCompanyKey,DepositKey,PostSide,GLCompanyKey,OfficeKey,
		DepartmentKey,DetailLineKey,Section, Overhead, ICTGLCompanyKey, 0, 0	
		,UIDCashTransactionKey,AEntity,AEntityKey,AReference,AEntity2,AEntity2Key,AReference2,AAmount, LineAmount,CashTransactionLineKey
		,CurrencyID, ExchangeRate, HDebit, HCredit, GLCCurrencyID, GLCExchangeRate, GLCDebit, GLCCredit
		FROM #tCashTransaction 	
		WHERE   (@OpeningTransaction = 0 OR
			#tCashTransaction.Entity = ''RECEIPT'' -- only payments if OpeningTransaction = 1  --issue 201908 allow payments to reposted
		)
		--WHERE Entity = @Entity AND EntityKey = @EntityKey
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END
	
	END
	
	-- only do this if @OpeningTransaction = 0	
	IF @OpeningTransaction = 0
	BEGIN
		-- Protect against double postings
		IF (SELECT COUNT(*) FROM tTransaction (NOLOCK) WHERE Entity = @Entity AND EntityKey = @EntityKey)
		<> @TransactionCount
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END		

		-- save the accrued expense account key, they will be used for the reversals in spGLPostVoucher 					
		-- these are BillAt = Net and Gross
		UPDATE tPurchaseOrderDetail
		SET    tPurchaseOrderDetail.AccruedExpenseInAccountKey = b.GLAccountKey
		FROM   #tAccruedExpenseAccount b
		WHERE  tPurchaseOrderDetail.PurchaseOrderDetailKey = b.PurchaseOrderDetailKey
		
		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected 	
		END		
	
		--now close PO detail lines prebilled at Commission Only since they will 
		--never have vendor invoices applied against them and they were not included
		--in the media prebill accrual posting totals above
		-- same logic as in sptPurchaseOrderSpotChangeClose()
				
		Declare @Today smalldatetime
		Select @Today = CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime)

		-- capture commission only PODs still open
		insert #tPODCommissionOnly (PurchaseOrderDetailKey, PurchaseOrderKey ,ProjectKey, UpdateFlag)
		select pod.PurchaseOrderDetailKey, pod.PurchaseOrderKey ,pod.ProjectKey, 1
		from   tPurchaseOrderDetail pod (nolock)
		inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		where il.InvoiceKey = @LineInvoiceKey
		and po.BillAt = 2  --Commission Only 		
		and pod.Closed = 0

		-- close them
		update tPurchaseOrderDetail
		set    tPurchaseOrderDetail.Closed = 1
				,tPurchaseOrderDetail.DateClosed = @Today 
		from   #tPODCommissionOnly b
		where  tPurchaseOrderDetail.PurchaseOrderDetailKey = b.PurchaseOrderDetailKey

		if @@ERROR <> 0 
		begin
			ROLLBACK TRAN
			RETURN @kErrUnexpected
		end

		-- we will not close POs if there are some open PO details
		update #tPODCommissionOnly
		set    #tPODCommissionOnly.UpdateFlag = 0
		from   tPurchaseOrderDetail pod (nolock)
		where  #tPODCommissionOnly.PurchaseOrderKey = pod.PurchaseOrderKey 
		and    pod.Closed = 0 -- still open

		update tPurchaseOrder 
		set    tPurchaseOrder.Closed = 1 
		from   #tPODCommissionOnly b
		where  tPurchaseOrder.PurchaseOrderKey = b.PurchaseOrderKey
		and    b.UpdateFlag = 1
	
		if @@ERROR <> 0 
		begin
			ROLLBACK TRAN
			RETURN @kErrUnexpected
		end
		
			
	END -- OpeningTransaction = 0
				
	COMMIT TRAN

	-- do this after SQL tran only
	select @ProjectKey = 0
	while (1=1)
	begin
		select @ProjectKey = min(ProjectKey)
		from   #tPODCommissionOnly
		where  ProjectKey > @ProjectKey
		and    isnull(ProjectKey, 0) > 0

		if @ProjectKey is null
			break

        -- Update 
		EXEC sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1
	end
		 		
	RETURN 1

















'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectCreate]'
GO
SET QUOTED_IDENTIFIER ON
GO
IF OBJECT_ID(N'[dbo].[sptProjectCreate]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptProjectCreate]
 (
 @UserKey int,
 @ProjectName nvarchar(100),
 @ProjectNumber varchar(100),
 @CompanyKey int,
 @ProjectStatusKey int,
 @ProjectTypeKey int,
 @ClientDivisionKey int,
 @ClientProductKey int,
 @OfficeKey int,
 @GLCompanyKey int,
 @ClientKey int,
 @CampaignKey int,
 @ProjectColor varchar(10), 
 @SparkCustomization int = 0,
 @AveraCustomization int = 0,
 @CopyProjectKey int = 0,
 @SparkModelYear varchar(10) = null,
 @Template tinyint = 0,
 @ValidateRetainer int = 1, 
 @IsLegacy bit = 0, --To be deprecated
 @oIdentity INT OUTPUT
 )
AS --Encrypt

  /*
  || When     Who Rel   What
  || 12/21/06 GHL 8.4   Added logic to prevent duplicates in tAssignment
  || 03/01/07 GHL 8.4   Added project rollup creation
  || 04/10/07 QMD 8.4.2	Added ProjectColor field -- See Issue 8638 for more information
  || 10/22/08 CRG 10.0.1.1 (38462) Added protection from ProjectStatusKey = 0
  || 11/06/08 GHL 10.0.1.2 Added protection against missing client
  || 01/10/09 GWG 10.0.1.6 Forced custom field key to 0
  || 01/27/09 MFT 10.0.1.8 (45458) Trim leading and trailing spaces from ProjectNumber
  || 12/12/09 GWG 10.5.1.4 Added protection against creating a project if default bill method is retainer and no retainer.
  || 10/5/10  RLB 10.5.3.6 (91563) Get default layout key from client if there is a client key
  || 02/27/12 GHL 10.5.5.3 (135372) Error out if the retainer is inactive and billing method is by retainer
  || 05/08/12 GHL 10.5.5.6 Do not auto assign users if we restrict to gl companies
  ||                       because if we create a project in one gl company, users in other gl companies would be assigned also
  || 08/24/12 MFT 10.5.5.9 Insert into tAssignment based on GLCompany restrictions 
  || 02/12/13 GHL 10.5.6.5 (167857) Added ModelYear for a custom for Spark44
  || 06/18/13 GHL 10.5.6.9 (181721) Added campaign key for new project numbers by campaign
  || 03/25/14 WDF 10.5.7.8 (210499) Added BillingMethod check for RetainerKey
  || 10/22/14 GAR 10.5.8.5 (233507) Moving the code that gets next project number below all validations so we don''t increment
  ||						the project number if the validation fails.
  || 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 template param, templates may not have a project status
  || 10/14/15 RLB 10.598 added check for campaignID''s matching project number
  || 10/30/15 WDF 10.5.9.7 (257042) Added customization for ''AVERA''
  || 11/09/15 MCM 10.5.9.8 (276320) Adding layout to default to Project if company doesn''t have one 
  || 03/16/15 RLB 10.6.0.2 If new project is a template then set Active = 0
  || 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
  || 03/15/17 MFT 10.6.1.4 (335742) Added DefaultAccountManager setting
  || 05/31/18 GHL 18.6.0.0  Added parameter @ValidateRetainer because in the new retainer functionality, we do not want to validate
  ||                        the default retainer key on the client
  || 08/30/18 GHL/WDF 18.900 Setting now the AccountManager when there is no client
  || 12/06/18 MFT 19.1.0.0 (434596) Removed ISNULL wrap from the LayoutKey when setting @ProjectLayoutKey
  || 01/19/19 RLS 19.1.0.0 (438571) Removed getting HourlyRate from tPreference if Company.HourlyRate is NULL
  || 06/06/19 RLB 19.0.7.0 (446229) Added Project Manager logic
  || 08/12/19 RLS 19.0.9.0 (472905) Added the work days (WorkMon, WorkTue, etc.)
  || 01/28/20 CRG 20.0.2.0 (498769) We are now allowing Get Rate From "Task" in Platinum
  || 01/27/20 GHL 20.0.2.0 (495024) Added the defaulting of LayoutKey from tGLCompany
  || 01/29/20 CRG 20.0.2.0 (498588) Now only auto assigning users who are not free users
  || 11/23/20 RLS 20.1.2.0 (535729) Changed @ProjectName to nvarchar
  || 08/25/21 CRG 21.09.19 (562791) Now defaulting Campaign Team onto Project Team
  || 10/12/21 MCM 21.10.17 (570477) Wrapped logic in transaction
  || 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
  || 03/15/23 RLB 23.04.16 (634783) Made sure users from campaign are active before added to tAssignment
  || 06/01/23 CRG 23.07.16 (639524) Added OverrideScheduleOptions, AutoScheduleProjects, AutoScheduleTaskEndDate, and ActualDateUpdatesPlan
  || 05/18/26 CRG 26.05.18 Defaulting the work days if no CopyProjectKey was passed in
*/

DECLARE @Error int
DECLARE @Active tinyint
Declare @AccountManager int
Declare @ProjectManager int
DECLARE @RetVal	INTEGER
Declare @NextTranNo VARCHAR(100)

 -- Get the active status of the project status
 SELECT @Active = IsActive
 FROM tProjectStatus (NOLOCK) 
 WHERE ProjectStatusKey = @ProjectStatusKey 

  
 --Determine Billing Defaults
 Declare @GetRateFrom smallint, @TimeRateSheetKey int, @TitleRateSheetKey int, @HourlyRate money, @GetMarkupFrom smallint, @ItemRateSheetKey int, @ItemMarkup decimal(24,4), @IOCommission decimal(24,4), @BCCommission decimal(24,4), @DefaultRetainerKey int
 Declare @BillingMethod smallint, @ExpensesNotIncluded tinyint, @LayoutKey int, @RestrictToGLCompany int, @UseGLCompany int, @DefaultAccountManager tinyint, @ShowProjectManager tinyint, @DefaultProjectManager tinyint
 Declare @LayoutFromGLCompany int

--Need ProjectLayoutKey in case company doesn''t have one.  Then we want to use the template layoutKey
DECLARE @ProjectLayoutKey INT 
SELECT @ProjectLayoutKey = LayoutKey from tProject (nolock) WHERE ProjectKey = @CopyProjectKey

-- Added for (472905)
DECLARE @WorkMon TINYINT 
DECLARE @WorkTue  TINYINT 
DECLARE @WorkWed TINYINT 
DECLARE @WorkThur TINYINT 
DECLARE @WorkFri TINYINT 
DECLARE @WorkSat TINYINT 
DECLARE @WorkSun TINYINT
DECLARE @OverrideScheduleOptions TINYINT
DECLARE @AutoScheduleProjects TINYINT
DECLARE @AutoScheduleTaskEndDate TINYINT
DECLARE @ActualDateUpdatesPlan TINYINT

SELECT 
	@WorkMon = ISNULL(WorkMon, 1),
	@WorkTue = ISNULL(WorkTue, 1),
	@WorkWed = ISNULL(WorkWed, 1),
	@WorkThur = ISNULL(WorkThur, 1),
	@WorkFri = ISNULL(WorkFri, 1),
	@WorkSat = ISNULL(WorkSat, 0),
	@WorkSun = ISNULL(WorkSun, 0),
	@OverrideScheduleOptions = ISNULL(OverrideScheduleOptions, 0),
	@AutoScheduleProjects = AutoScheduleProjects,
	@AutoScheduleTaskEndDate = AutoScheduleTaskEndDate,
	@ActualDateUpdatesPlan = ActualDateUpdatesPlan
FROM tProject (nolock) WHERE ProjectKey = @CopyProjectKey

--Default the values if there was no @CopyProjectKey passed in
SELECT 
	@WorkMon = ISNULL(@WorkMon, 1),
	@WorkTue = ISNULL(@WorkTue, 1),
	@WorkWed = ISNULL(@WorkWed, 1),
	@WorkThur = ISNULL(@WorkThur, 1),
	@WorkFri = ISNULL(@WorkFri, 1),
	@WorkSat = ISNULL(@WorkSat, 0),
	@WorkSun = ISNULL(@WorkSun, 0)

 if ISNULL(@ClientKey, 0) = 0
	Select 
		@GetRateFrom = ISNULL(GetRateFrom, 2),
		@TimeRateSheetKey = TimeRateSheetKey,
		@TitleRateSheetKey = TitleRateSheetKey,
		@HourlyRate = ISNULL(HourlyRate, 0),
		@GetMarkupFrom = ISNULL(GetMarkupFrom, 2),
		@ItemRateSheetKey = ItemRateSheetKey,
		@ItemMarkup = ISNULL(ItemMarkup, 0),
		@IOCommission = ISNULL(IOCommission, 0),
		@BCCommission = ISNULL(BCCommission, 0),
		@BillingMethod = 1,
		@ExpensesNotIncluded = 0,
		@LayoutKey = @ProjectLayoutKey,
		@UseGLCompany = ISNULL(UseGLCompany, 0),
		@RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0),
		@DefaultAccountManager = ISNULL(DefaultAccountManager, 0),
		@AccountManager = CASE isnull(DefaultAccountManager,0) WHEN 1 THEN @UserKey ELSE null END,
		@DefaultProjectManager = ISNULL(DefaultProjectManager, 0),
		@ProjectManager = Case ISNULL(ShowProjectManager, 0)
							WHEN 1 THEN case isnull(DefaultProjectManager,0)
											when 1 then @UserKey 
											else null 
										end
							ELSE NULL
						  END
		,@LayoutFromGLCompany = isnull(LayoutFromGLCompany, 0)

	From
		tPreference (nolock)
	Where CompanyKey = @CompanyKey
 else
 begin
 	Select
		@GetRateFrom = 
			CASE @IsLegacy
				WHEN 1 THEN ISNULL(c.GetRateFrom, ISNULL(p.GetRateFrom, 2))
				ELSE
					CASE ISNULL(c.GetRateFrom, ISNULL(p.GetRateFrom, 2))
						WHEN 1 THEN 2
						--Removed for 498769. We are allowing GetRateFrom "Task" for Platinum now
						--WHEN 6 THEN 4
						ELSE ISNULL(c.GetRateFrom, ISNULL(p.GetRateFrom, 2))
					END
			END,
		@TimeRateSheetKey = ISNULL(c.TimeRateSheetKey, p.TimeRateSheetKey),
		@TitleRateSheetKey = ISNULL(c.TitleRateSheetKey, p.TitleRateSheetKey),
		@HourlyRate = ISNULL(c.HourlyRate, 0),
		@GetMarkupFrom = ISNULL(c.GetMarkupFrom, ISNULL(p.GetMarkupFrom, 2)),
		@ItemRateSheetKey = ISNULL(c.ItemRateSheetKey, p.ItemRateSheetKey),
		@ItemMarkup = ISNULL(c.ItemMarkup, ISNULL(p.ItemMarkup, 0)),
		@IOCommission = ISNULL(c.IOCommission, ISNULL(p.IOCommission, 0)),
		@BCCommission = ISNULL(c.BCCommission, ISNULL(p.BCCommission, 0)),
		@AccountManager = CASE isnull(p.DefaultAccountManager,0) WHEN 1 THEN @UserKey ELSE c.AccountManagerKey END,
		@ProjectManager = CASE ISNULL(p.ShowProjectManager, 0)
							WHEN 1 THEN case isnull(p.DefaultProjectManager,0)
											when 1 then @UserKey
											else c.ProjectManagerKey
											end
							ELSE NULL
						  END,						  
		--@DefaultRetainerKey = c.DefaultRetainerKey,
		@DefaultRetainerKey = CASE WHEN ISNULL(c.DefaultBillingMethod, 1) = 3 THEN c.DefaultRetainerKey ELSE NULL END,
		@BillingMethod = ISNULL(c.DefaultBillingMethod, 1),
		@ExpensesNotIncluded = ISNULL(c.DefaultExpensesNotIncluded, 0),
		@LayoutKey =ISNULL(c.LayoutKey, @ProjectLayoutKey),
		@UseGLCompany = ISNULL(p.UseGLCompany, 0),
		@RestrictToGLCompany = ISNULL(p.RestrictToGLCompany, 0),
		@LayoutFromGLCompany = isnull(p.LayoutFromGLCompany, 0)
	From
		tCompany c (nolock) 
		inner join tPreference p (nolock) on c.OwnerCompanyKey = p.CompanyKey
	Where c.CompanyKey = @ClientKey
 
	If @@ROWCOUNT = 0
		RETURN -3
 end
 
if @LayoutFromGLCompany = 1 and @GLCompanyKey > 0
begin
	if exists (select 1 from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey and LayoutKey > 0)
		select @LayoutKey = LayoutKey from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey
	else
		select @LayoutKey = @ProjectLayoutKey
end

if @UseGLCompany = 0
	select @RestrictToGLCompany = 0

if @ValidateRetainer = 1
begin
	if @BillingMethod = 3 and ISNULL(@DefaultRetainerKey, 0) = 0
		return -5
	
	-- make sure that the retainer is still active
	if @BillingMethod = 3 
	begin 
		if not exists (select 1 from tRetainer (nolock) 
					where RetainerKey = @DefaultRetainerKey
					and   Active = 1)
			return -5
	end
end

 --Protect against ProjectStatusKey = 0
 IF ISNULL(@ProjectStatusKey, 0) = 0 and isnull(@Template, 0) = 0
	RETURN -1

IF isnull(@Template, 0) = 1
	SELECT @Active = 0
 
 -- Last resort protection against null
 Select
		@GetRateFrom = ISNULL(@GetRateFrom, 2),
		@HourlyRate = ISNULL(@HourlyRate, 0),
		@GetMarkupFrom = ISNULL(@GetMarkupFrom, 2),
		@ItemMarkup = ISNULL(@ItemMarkup, 0),
		@IOCommission = ISNULL(@IOCommission, 0),
		@BCCommission = ISNULL(@BCCommission, 0)

BEGIN TRANSACTION

 -- Get the next number - only called if all validations pass.
 IF @ProjectNumber IS NULL OR @ProjectNumber = ''''
 BEGIN
	if @AveraCustomization = 1
		BEGIN
			SELECT @ProjectNumber = ProjectNumber from tProject (nolock) where ProjectKey = @CopyProjectKey
			SELECT @RetVal = 1, @NextTranNo = @ProjectNumber + ''-REV'' + REPLACE(REPLACE(REPLACE(CONVERT(VARCHAR(19), CONVERT(DATETIME, getdate(), 112), 126), ''-'', ''''), ''T'', ''_''), '':'', '''') 
		END
	ELSE
	
	if @SparkCustomization = 1

		EXEC sptProjectGetNextProjectNumSpark
			@CompanyKey,
			@ClientKey,
			@ProjectTypeKey,
			@ClientProductKey,
			@SparkModelYear,
			@RetVal OUTPUT,
			@NextTranNo OUTPUT

	ELSE

		EXEC sptProjectGetNextProjectNum
			@CompanyKey,
			@ClientKey,
			@OfficeKey,
			@ProjectTypeKey,
			@ClientDivisionKey,
			@CampaignKey,
			@GLCompanyKey,
			@RetVal OUTPUT,
			@NextTranNo OUTPUT

	IF @RetVal <> 1
	BEGIN
		ROLLBACK TRAN
		RETURN -2
	END

END
ELSE
BEGIN
	-- Check for a duplicate project number
	IF EXISTS(
		SELECT 1 FROM tProject (NOLOCK) 
		WHERE
			ProjectNumber = @ProjectNumber AND
			CompanyKey = @CompanyKey
			)
		BEGIN
			ROLLBACK TRAN
			RETURN -2
		END

	IF EXISTS(
		SELECT 1 FROM tCampaign (NOLOCK) 
		WHERE
			CampaignID = @ProjectNumber AND
			CompanyKey = @CompanyKey
			)
		BEGIN
			ROLLBACK TRAN
			RETURN -2
		END
		
	SELECT @NextTranNo = @ProjectNumber
END

SELECT @NextTranNo = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(@NextTranNo, ''&'', ''''), '','', ''''), ''"'', ''''), '''''''', '''')))
	
 -- Insert the project
 INSERT tProject (
  ProjectName,
  ProjectNumber,
  CompanyKey,
  ProjectStatusKey,
  ProjectTypeKey,
  ClientDivisionKey,
  ClientProductKey,
  ClientKey,
  OfficeKey,
  GLCompanyKey,
  Active,
  CreatedDate,
  CreatedByKey,
  GetRateFrom,
  TimeRateSheetKey,
  TitleRateSheetKey,
  HourlyRate,
  GetMarkupFrom,
  ItemRateSheetKey,
  ItemMarkup,
  IOCommission,
  BCCommission,
  AccountManager,
  ProjectManager,
  RetainerKey,
  BillingMethod,
  ExpensesNotIncluded,
  LayoutKey,
  ProjectColor,
  CampaignKey,
  WorkMon,
  WorkTue,
  WorkWed,
  WorkThur,
  WorkFri,
  WorkSat,
  WorkSun,
  CustomFieldKey,
  Template,
  OverrideScheduleOptions,
  AutoScheduleProjects,
  AutoScheduleTaskEndDate,
  ActualDateUpdatesPlan
  ) 
 VALUES (
  @ProjectName,
  @NextTranNo, -- @ProjectNumber,
  @CompanyKey,
  @ProjectStatusKey,
  @ProjectTypeKey,
  @ClientDivisionKey,
  @ClientProductKey,
  @ClientKey,
  @OfficeKey,
  @GLCompanyKey,
  @Active,
  CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime),
  @UserKey,
  @GetRateFrom,
  @TimeRateSheetKey,
  @TitleRateSheetKey,
  @HourlyRate,
  @GetMarkupFrom,
  @ItemRateSheetKey,
  @ItemMarkup,
  @IOCommission,
  @BCCommission,
  @AccountManager,
  @ProjectManager,
  CASE WHEN @BillingMethod = 3 THEN @DefaultRetainerKey ELSE NULL END,
  @BillingMethod,
  @ExpensesNotIncluded,
  @LayoutKey,
  @ProjectColor,
  @CampaignKey,
  @WorkMon,
  @WorkTue,
  @WorkWed,
  @WorkThur,
  @WorkFri,
  @WorkSat,
  @WorkSun,
  0,
  isnull(@Template, 0),
  @OverrideScheduleOptions,
  @AutoScheduleProjects,
  @AutoScheduleTaskEndDate,
  @ActualDateUpdatesPlan
  )
  
 SELECT @oIdentity = @@IDENTITY, @Error = @@Error  

IF @Error <> 0 OR @oIdentity <= 0
	BEGIN
		ROLLBACK TRANSACTION
		Return -2
	END

COMMIT TRANSACTION


 INSERT tProjectRollup (ProjectKey) VALUES (@oIdentity)
 
------------------------------------------------------------
--GL Company restrictions
DECLARE @tGLCompanies table (UserKey int, GLCompanyKey int)
IF @RestrictToGLCompany = 0
	BEGIN --@RestrictToGLCompany = 0
		--All GLCompanyKeys + 0 to get NULLs
		INSERT INTO @tGLCompanies
		SELECT UserKey, 0
		FROM tUser (nolock)
		WHERE
			(OwnerCompanyKey = @CompanyKey OR CompanyKey = @CompanyKey) AND
			AutoAssign = 1
		INSERT INTO @tGLCompanies
			SELECT
				u.UserKey,
				glc.GLCompanyKey
			FROM
				tGLCompany glc (nolock),
				tUser u (nolock)
			WHERE
				glc.CompanyKey = @CompanyKey AND
				(u.OwnerCompanyKey = @CompanyKey OR u.CompanyKey = @CompanyKey) AND
				u.AutoAssign = 1
	END --@RestrictToGLCompany = 0
ELSE
	BEGIN --@RestrictToGLCompany = 1
		 --Only GLCompanyKeys @UserKey has access to
		INSERT INTO @tGLCompanies
			SELECT
				glca.UserKey,
				glca.GLCompanyKey
			FROM
				tUserGLCompanyAccess glca (nolock)
				INNER JOIN tUser u (nolock) ON glca.UserKey = u.UserKey
			WHERE
				(u.OwnerCompanyKey = @CompanyKey OR u.CompanyKey = @CompanyKey) AND
				u.AutoAssign = 1
	END --@RestrictToGLCompany = 1
--GL Company restrictions
------------------------------------------------------------
INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
SELECT
	@oIdentity, -- new ProjectKey
	UserKey,
	HourlyRate
FROM
	tUser u (nolock)
WHERE
	(OwnerCompanyKey = @CompanyKey OR CompanyKey = @CompanyKey) AND
	AutoAssign = 1 AND
	ClientVendorLogin <> 1 AND
	Active = 1 AND
	UserKey <> @UserKey AND -- Do not Assign the creator first
	UserKey NOT IN (Select UserKey from tAssignment (nolock) Where ProjectKey = @oIdentity) AND
	UserKey IN (SELECT UserKey FROM @tGLCompanies WHERE GLCompanyKey = ISNULL(@GLCompanyKey, 0))

IF @@Error <> 0
BEGIN
--ROLLBACK TRANSACTION   
RETURN -1
END

-- Assign the creator even if AutoAssign = 0
INSERT tAssignment (ProjectKey, UserKey, HourlyRate)
SELECT @oIdentity  -- new ProjectKey
		 ,UserKey
		 ,HourlyRate
FROM   tUser (NOLOCK)
WHERE  UserKey = @UserKey
AND    UserKey NOT IN (Select UserKey from tAssignment (nolock) Where ProjectKey = @oIdentity)

IF @@Error <> 0
BEGIN
--ROLLBACK TRANSACTION
RETURN -1
END 

IF @CampaignKey > 0
BEGIN
	--If this project is getting linked to a Campaign, add the Campaign Team
	INSERT	tAssignment (ProjectKey, UserKey, HourlyRate)
	SELECT	@oIdentity, --new ProjectKey
			ct.UserKey,
			u.HourlyRate
	FROM	tCampaignTeam ct (nolock)
	INNER JOIN tUser u (nolock) ON ct.UserKey = u.UserKey
	WHERE	ct.CampaignKey = @CampaignKey
	AND    u.Active = 1
	AND    ct.UserKey NOT IN (Select UserKey from tAssignment (nolock) Where ProjectKey = @oIdentity)

	IF @@Error <> 0
	BEGIN
	--ROLLBACK TRANSACTION
	RETURN -1
	END 
 END

 /* 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

    )
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.
*/

-- 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

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
begin
    -- 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

-- ========================================
-- 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

    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
    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,
        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

    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
    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))

    -- ========================================
    -- 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
                    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 = @UserKey,
                    @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

	 -- 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,
       @IsUpdate as wasUpdated
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'Altering [dbo].[spRptStatementRunningBalance]'
GO
IF OBJECT_ID(N'[dbo].[spRptStatementRunningBalance]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spRptStatementRunningBalance]
	@CompanyKey int,
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@ClientKey int,
	@ParentClientKey int,
	@ProjectKey int,
	@PostStatus tinyint,
	@IncludeZeroBal tinyint,
	@GLCompanyKey int, ---1 All, 0 NULL, >0 valid company
	@UserKey int = null,
	@AccountManager int = null,
	@CurrencyID varchar(10) = null, -- Null Home Currency, or a foreign currency
	@Receipts tinyint = 0, -- Include unapplied receipts
	@ExcludeRevInvoices tinyint = 1 -- Exclude revenue invoices (AdvanceBill = 0)

AS --Encrypt

/*
|| When     Who Rel  What
|| 12/4/06  CRG 8.4  Added IncludeZeroBal parameter.
|| 12/4/06  CRG 8.4  Added TranSort to temp table in order to sort the transaction that appear on the same day.
|| 12/5/06  CRG 8.4  Wrapped Beginning Balance calculations with ISNULL.
|| 10/18/07 CRG 8.5  Added GLCompanyKey parameter.
|| 11/19/07 GHL 8.5  Fixed bad alias
|| 02/10/09 GHL 10.018 (37631) Changed logic of GLCompanyKey to make it similar to spRptInvoiceAging
|| 06/09/11 RLB 10.545 (108018) Checking the Checks GL Company instead of the one on the client
|| 08/08/11 GHL 10.546 (118116) Getting payments for the BeginningBalance  from tCheckApp.Amount instead of tCheck.CheckAmount
||                     so that we can ignore payments against sales accts (i.e. tCheckAppl.InvoiceKey is not null)
||                     But in the date window display them as 2 lines 1 negative and 1 positive so that end result is 0 
|| 03/19/12 RLB 10.554 (137443) increased Temp Table TranRef to 100 since payment ref is 100 and was causing an error 4 a client
|| 04/16/12 GHL 10.555  Added UserKey for UserGLCompanyAccess
|| 09/30/13 RLB 10.573 (191660) should have been added for (185716) Adding filter for client Account mananger
|| 11/21/13 MFT 10.574 (191660) pushed @AccountManager filter to the last 6 gets, patched App servers for 10.573
|| 03/04/14 GHL 10.577 Added CurrencyID param to support multi currency fucntionality
|| 05/09/14 GHL 10.580 (215708) Added ParentClientKey parameter for enhancement
|| 05/14/14 GHL 10.580 (216216) Added param @Receipts so that unapplied receipts can be added
|| 09/20/17 GHL 10.620 (363866) When calculating Beginning Balance and payments, make sure that since we 
||                     take invoices for the client, the tCheckAppl.Amount in the subtraction should also be for invoices for that same client
||                     in other words get the client from the invoices, not from the checks (case when clients have parent companies/sibling companies)
|| 10/24/17 GHL 10.621 (368503) Also take in account the credits for the child/parent companies
|| 03/25/21 MFT 10.040 (553223) Changed the final DELETE to remove all in balance clients, not just a single zero row
|| 03/20/25 RLS 25.04.20 (695915) Added check for CampaignKeys
|| 04/11/25 AMP 25.05.18 (699569) Correction for displaying Project/Campaign Full Name or just the numbers
|| 05/18/26 AMP 26.05.18 (718179) Added @ExcludeRevInvoices parameter to exclude revenue invoices (AdvanceBill = 0)
*/

-- check for the cbre customization
declare @Customizations varchar(2000), @RollUpMatching int
Select @Customizations = LOWER(ISNULL(Customizations, '''')) from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
Select @RollUpMatching = CHARINDEX(''cbre'', @Customizations)

Declare @RestrictToGLCompany int
Declare @MultiCurrency int

Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
	,@MultiCurrency = ISNULL(MultiCurrency, 0)
	from tUser u (nolock)
	inner join tPreference p (nolock) on p.CompanyKey = ISNULL(u.OwnerCompanyKey, u.CompanyKey)
	Where u.UserKey = @UserKey

select @RestrictToGLCompany = isnull(@RestrictToGLCompany, 0)
	,@MultiCurrency = isnull(@MultiCurrency, 0)


DECLARE	@HasCampaignKeys int
DECLARE @CampCount int = 0

SET @HasCampaignKeys = NULL
SELECT	@CampCount = COUNT(*)
FROM	#CampaignKeys -- Created in VB

IF @CampCount > 0
SELECT	@HasCampaignKeys = @CampCount

--Create the Temp Table
CREATE TABLE #ClientStmt
	(LoggedCompanyKey int,
	TranType varchar(20) null,
	ClientKey int null,
	TranDate smalldatetime null,
	TranRef varchar(100) null,
	DueDate smalldatetime null,
	ProjectKey int null,
	CampaignKey int NULL,
	TranAmt money null,
	Sort int null,
	TranSort int null,
	Action int null)

--Add all clients with Invoices for the company
INSERT	#ClientStmt (ClientKey)
SELECT DISTINCT ClientKey
FROM	tInvoice i (nolock)
INNER JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey 
WHERE	i.CompanyKey = @CompanyKey
AND		(i.ClientKey = @ClientKey OR @ClientKey IS NULL)
And     (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
AND		(i.ProjectKey = @ProjectKey OR @ProjectKey IS NULL)
And     (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
AND		(c.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
AND		ISNULL(Posted, 0) >= @PostStatus
--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(GLCompanyKey, 0)) ) 
AND     (-- case when @GLCompanyKey = ALL
				(@GLCompanyKey = -1 AND 
					(
					@RestrictToGLCompany = 0 OR 
					(i.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
			--case when @GLCompanyKey = X or Blank(0)
			 OR (@GLCompanyKey != -1 AND ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey)
			)
AND (@MultiCurrency = 0
	OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )


--Add all clients with Receipts that weren''t already added above
INSERT	#ClientStmt (ClientKey)
SELECT DISTINCT ClientKey
FROM	tCheck c (nolock)
INNER JOIN tCompany com (nolock) ON c.ClientKey = com.CompanyKey
WHERE	com.OwnerCompanyKey = @CompanyKey
AND		(c.ClientKey = @ClientKey OR @ClientKey IS NULL)
And     (@ParentClientKey IS NULL or (c.ClientKey = @ParentClientKey or c.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
AND		(com.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
AND		c.ClientKey NOT IN (SELECT ClientKey FROM #ClientStmt)
AND		ISNULL(c.Posted, 0) >= @PostStatus
--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(c.GLCompanyKey, 0)) ) 
AND     (-- case when @GLCompanyKey = ALL
				(@GLCompanyKey = -1 AND 
					(
					@RestrictToGLCompany = 0 OR 
					(c.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
			--case when @GLCompanyKey = X or Blank(0)
			 OR (@GLCompanyKey != -1 AND ISNULL(c.GLCompanyKey, 0) = @GLCompanyKey)
			)
AND		(@ProjectKey IS NULL 
		OR
		c.CheckKey IN 
			(SELECT	ca.CheckKey
			FROM	tCheckAppl ca (nolock)
			INNER JOIN tInvoice i (nolock) ON ca.InvoiceKey = i.InvoiceKey
			WHERE	i.ProjectKey = @ProjectKey)
		)
AND (@MultiCurrency = 0
	OR isnull(c.CurrencyID, '''') = isnull(@CurrencyID, '''') )

--Get the Beginning Balance for each Client
UPDATE	#ClientStmt
SET		TranDate = @StartDate
		,TranRef = ''Beginning Balance''
		,TranAmt =	--Invoices
				ISNULL((SELECT	SUM(ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0))
				FROM	tInvoice i (nolock)
				WHERE	i.ClientKey = #ClientStmt.ClientKey
				AND		i.PostingDate < @StartDate
				AND		ISNULL(i.Posted, 0) >= @PostStatus
				--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) ) 
				AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(i.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey)
				)
				AND (@MultiCurrency = 0
					OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
				), 0)

				- --less Receipts...8/8/11 read tCheckAppl.Amount rather tCheck.CheckAmount
				ISNULL((SELECT SUM(ca.Amount)
				FROM	tCheck c (nolock)
					INNER JOIN tCheckAppl ca (nolock) on c.CheckKey = ca.CheckKey
					INNER JOIN tInvoice i (nolock) on ca.InvoiceKey = i.InvoiceKey -- added for 363866
				--WHERE	c.ClientKey = #ClientStmt.ClientKey -- removed for 363866
				WHERE  	i.ClientKey = #ClientStmt.ClientKey  -- added for 363866
				AND     ca.InvoiceKey is not null
				AND		c.PostingDate < @StartDate
				AND		ISNULL(c.Posted, 0) >= @PostStatus
				--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(c.GLCompanyKey, 0)) )
				AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(c.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(c.GLCompanyKey, 0) = @GLCompanyKey)
				)
				AND (@MultiCurrency = 0
					OR isnull(c.CurrencyID, '''') = isnull(@CurrencyID, '''') )
				
				), 0)

				- --less credits, applied added for 363866/368503
				ISNULL((SELECT SUM(icr.Amount)
				FROM	tInvoice cr (nolock)
					INNER JOIN tInvoiceCredit icr (nolock) on icr.CreditInvoiceKey = cr.InvoiceKey
					INNER JOIN tInvoice i (nolock) on icr.InvoiceKey = i.InvoiceKey 
				WHERE  	i.ClientKey = #ClientStmt.ClientKey  
				AND		cr.PostingDate < @StartDate
				AND		ISNULL(cr.Posted, 0) >= @PostStatus
				AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(cr.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(cr.GLCompanyKey, 0) = @GLCompanyKey)
				)
				AND (@MultiCurrency = 0
					OR isnull(cr.CurrencyID, '''') = isnull(@CurrencyID, '''') )
				
				), 0)
				 
				 + --this is to make the credits disappear, added for 363866/368503
				   --basically if they are applied, they are considered paid 
				ISNULL((SELECT SUM(icr.Amount)
				FROM	tInvoice cr (nolock)
					INNER JOIN tInvoiceCredit icr (nolock) on icr.CreditInvoiceKey = cr.InvoiceKey
				WHERE  	cr.ClientKey = #ClientStmt.ClientKey 
				AND		cr.PostingDate < @StartDate
				AND		ISNULL(cr.Posted, 0) >= @PostStatus
				AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(cr.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(cr.GLCompanyKey, 0) = @GLCompanyKey)
				)
				AND (@MultiCurrency = 0
					OR isnull(cr.CurrencyID, '''') = isnull(@CurrencyID, '''') )
				
				), 0)

--This ensures that the Beginning Balances are sorted to the top of the statement
UPDATE	#ClientStmt
SET		Sort = 0

-- temp table for the unapplied receipts
create table #UnappliedRec
	(CheckKey int 
	,ClientKey int null
	,PostingDate datetime null
	,CheckAmt money null
	,AppliedAmt money null
	)

if @Receipts = 1 And @ProjectKey is Null
BEGIN
	-- Add Back any unapplied receipts from the client

	insert #UnappliedRec(CheckKey,ClientKey,PostingDate,CheckAmt,AppliedAmt)
	select ch.CheckKey,ch.ClientKey,ch.PostingDate,ch.CheckAmount, 0
	From tCheck ch (nolock)
	Inner Join tCompany c (nolock) On ch.ClientKey = c.CompanyKey
	-- join with a possible voided check, make sure that CheckKey <> VoidCheckKey on the void
	left Join tCheck void_ch (nolock) on ch.CheckKey = void_ch.VoidCheckKey and void_ch.CheckKey <> void_ch.VoidCheckKey 
	Where
		c.OwnerCompanyKey = @CompanyKey 
	And	ch.PostingDate <= @EndDate 
	And	(isnull(ch.VoidCheckKey, 0) = 0
		Or
		void_ch.PostingDate > @EndDate
		)
	--And	(@GLCompanyKey IS NULL OR ISNULL(ch.GLCompanyKey, 0) = @GLCompanyKey)
	AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(ch.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(ch.GLCompanyKey, 0) = @GLCompanyKey)
				)
	And	(@ClientKey IS NULL OR ch.ClientKey = @ClientKey)  -- Reduce # of records upfront
	And (@ParentClientKey IS NULL or (ch.ClientKey = @ParentClientKey or ch.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	--And	(@ClassKey IS NULL OR ch.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	And ch.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
			OR isnull(ch.CurrencyID, '''') = isnull(@CurrencyID, '''') )


	-- now calc the applied amounts, do we have to take in account the dates of the invoices?
	update #UnappliedRec
	set    #UnappliedRec.AppliedAmt = (select sum (ca.Amount) from tCheckAppl ca (nolock) 
		where ca.CheckKey = #UnappliedRec.CheckKey)

	update #UnappliedRec
	set    CheckAmt = isnull(CheckAmt, 0), AppliedAmt = isnull(AppliedAmt, 0) 

	-- delete if completely applied
	delete #UnappliedRec where CheckAmt - AppliedAmt = 0

	-- now add the contributions of the unapplied receipts
	UPDATE	#ClientStmt
	SET		#ClientStmt.TranAmt =isnull(#ClientStmt.TranAmt, 0) - ISNULL((
		select sum(b.CheckAmt - b.AppliedAmt)
		from   #UnappliedRec b
		where  #ClientStmt.ClientKey = b.ClientKey
		AND	b.PostingDate < @StartDate
	),0)

END


--Now Get the Transactions in the date range

--Get Invoices
INSERT	#ClientStmt
		(TranType
		,ClientKey
		,TranDate
		,TranRef
		,DueDate
		,ProjectKey
		,CampaignKey
		,TranAmt
		,Sort
		,TranSort)
SELECT	''Invoice''
		,i.ClientKey
		,i.InvoiceDate
		,i.InvoiceNumber
		,i.DueDate
		,i.ProjectKey
		,i.CampaignKey
		,ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0)
		,1	
		,1
FROM	tInvoice i (nolock)
INNER JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey 
WHERE	i.CompanyKey = @CompanyKey
AND		(c.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
AND		(i.ClientKey = @ClientKey OR @ClientKey IS NULL)
And     (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
AND		(i.ProjectKey = @ProjectKey OR @ProjectKey IS NULL)
And		(@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
AND		ISNULL(i.Posted, 0) >= @PostStatus
AND		ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0) > 0
AND		i.PostingDate BETWEEN @StartDate AND @EndDate
--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) ) 
AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(i.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey)
				)
AND (@MultiCurrency = 0
	OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
AND (ISNULL(@ExcludeRevInvoices, 0) = 0 OR ISNULL(i.AdvanceBill, 0) = 1)

--Get Credit Memos
INSERT	#ClientStmt
		(TranType
		,ClientKey
		,TranDate
		,TranRef
		,DueDate
		,ProjectKey
		,CampaignKey
		,TranAmt
		,Sort
		,TranSort)
SELECT	''Credit''
		,i.ClientKey
		,i.InvoiceDate
		,i.InvoiceNumber
		,i.DueDate
		,i.ProjectKey
		,i.CampaignKey
		,ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0)
		,1
		,2
FROM	tInvoice i (nolock)
INNER JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey 
WHERE	i.CompanyKey = @CompanyKey
AND		(c.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
AND		(i.ClientKey = @ClientKey OR @ClientKey IS NULL)
And     (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
AND		(i.ProjectKey = @ProjectKey OR @ProjectKey IS NULL)
And		(@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
AND		ISNULL(i.Posted, 0) >= @PostStatus
AND		ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0) < 0
AND		i.PostingDate BETWEEN @StartDate AND @EndDate
--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) ) 
AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(i.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey)
				)
AND (@MultiCurrency = 0
	OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )

if ISNULL(@ProjectKey, 0) = 0
BEGIN
	--Get Payments applied to invoices
	INSERT	#ClientStmt
			(TranType
			,ClientKey
			,TranDate
			,TranRef
			,ProjectKey
			,CampaignKey
			,TranAmt
			,Sort
			,TranSort)
	SELECT	''Payment''
			,i.ClientKey
			,c.CheckDate
			,c.ReferenceNumber
			,NULL
			,NULL
			--,ca.CheckAmount * -1
			,Sum(ca.Amount) * -1 -- added 8/8/11
			,1
			,3
	FROM	tCheck c (nolock)
	INNER JOIN tCheckAppl ca (nolock) on c.CheckKey = ca.CheckKey -- added 8/8/11
	INNER JOIN tInvoice i (nolock) on ca.InvoiceKey = i.InvoiceKey -- added for 363866
	INNER JOIN tCompany com (nolock) ON i.ClientKey = com.CompanyKey -- for 363866, the client comes from the invoice
	WHERE	com.OwnerCompanyKey = @CompanyKey
	-- for 363866, the client comes from the invoice on the 2 following lines
	AND		(i.ClientKey = @ClientKey OR @ClientKey IS NULL) 
	And     (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	AND		(com.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
	AND		ISNULL(c.Posted, 0) >= @PostStatus
	AND		c.PostingDate BETWEEN @StartDate AND @EndDate	
	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(c.GLCompanyKey, 0)) ) 
	AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(c.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(c.GLCompanyKey, 0) = @GLCompanyKey)
				)
	AND (@MultiCurrency = 0
		OR isnull(c.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	AND  ca.InvoiceKey is not null -- added 8/8/11 Applied to Invoices
	Group By -- added 8/8/11
		 i.ClientKey
		,c.CheckDate
		,c.ReferenceNumber


	-- now get payments applied to  sales accts (2 lines 1 neg + 1 pos)
	INSERT	#ClientStmt
			(TranType
			,ClientKey
			,TranDate
			,TranRef
			,ProjectKey
			,CampaignKey
			,TranAmt
			,Sort
			,TranSort)
	SELECT	''Payment''
			,c.ClientKey
			,c.CheckDate
			,c.ReferenceNumber
			,NULL
			,NULL
			,Sum(ca.Amount) * -1 -- negative
			,1
			,3
	FROM	tCheck c (nolock)
	INNER JOIN tCheckAppl ca (nolock) on c.CheckKey = ca.CheckKey 
	INNER JOIN tCompany com (nolock) ON c.ClientKey = com.CompanyKey
	WHERE	com.OwnerCompanyKey = @CompanyKey
	AND		(c.ClientKey = @ClientKey OR @ClientKey IS NULL)
	And     (@ParentClientKey IS NULL or (c.ClientKey = @ParentClientKey or c.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	AND		(com.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
	AND		ISNULL(c.Posted, 0) >= @PostStatus
	AND		c.PostingDate BETWEEN @StartDate AND @EndDate	
	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(c.GLCompanyKey, 0)) ) 
	AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(c.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(c.GLCompanyKey, 0) = @GLCompanyKey)
				)
	AND (@MultiCurrency = 0
		OR isnull(c.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	AND  ca.InvoiceKey is null -- Applied to Sales
	Group By 
		 c.ClientKey
		,c.CheckDate
		,c.ReferenceNumber
 
	INSERT	#ClientStmt
			(TranType
			,ClientKey
			,TranDate
			,TranRef
			,ProjectKey
			,CampaignKey
			,TranAmt
			,Sort
			,TranSort)
	SELECT	''Payment''
			,c.ClientKey
			,c.CheckDate
			,c.ReferenceNumber
			,NULL
			,NULL
			,Sum(ca.Amount) -- Positive
			,1
			,3
	FROM	tCheck c (nolock)
	INNER JOIN tCheckAppl ca (nolock) on c.CheckKey = ca.CheckKey -- added 8/8/11
	INNER JOIN tCompany com (nolock) ON c.ClientKey = com.CompanyKey
	WHERE	com.OwnerCompanyKey = @CompanyKey
	AND		(c.ClientKey = @ClientKey OR @ClientKey IS NULL)
	And     (@ParentClientKey IS NULL or (c.ClientKey = @ParentClientKey or c.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	AND		(com.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
	AND		ISNULL(c.Posted, 0) >= @PostStatus
	AND		c.PostingDate BETWEEN @StartDate AND @EndDate	
	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(c.GLCompanyKey, 0)) ) 
	AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(c.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(c.GLCompanyKey, 0) = @GLCompanyKey)
				)
	AND (@MultiCurrency = 0
		OR isnull(c.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	AND  ca.InvoiceKey is null -- Applied to Sales
	Group By 
		 c.ClientKey
		,c.CheckDate
		,c.ReferenceNumber

END
ELSE
BEGIN
	--Get Payments
	INSERT	#ClientStmt
			(TranType
			,ClientKey
			,TranDate
			,TranRef
			,ProjectKey
			,CampaignKey
			,TranAmt
			,Sort
			,TranSort)
	SELECT	''Payment''
			,c.ClientKey
			,c.CheckDate
			,c.ReferenceNumber
			,i.ProjectKey
			,i.CampaignKey
			,Sum(ca.Amount) * -1
			,1
			,3
	FROM	tCheck c (nolock)
	INNER JOIN tCompany com (nolock) ON c.ClientKey = com.CompanyKey
	LEFT JOIN tCheckAppl ca (nolock) ON c.CheckKey = ca.CheckKey
	LEFT JOIN tInvoice i (nolock) ON ca.InvoiceKey = i.InvoiceKey
	WHERE	com.OwnerCompanyKey = @CompanyKey
	AND		(c.ClientKey = @ClientKey OR @ClientKey IS NULL)
	And     (@ParentClientKey IS NULL or (c.ClientKey = @ParentClientKey or c.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	AND		(com.AccountManagerKey = @AccountManager OR @AccountManager IS NULL)
	AND		ISNULL(c.Posted, 0) >= @PostStatus
	AND		i.ProjectKey = @ProjectKey
	And		(@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	AND		c.PostingDate BETWEEN @StartDate AND @EndDate
	--AND		(ISNULL(com.GLCompanyKey, 0) = @GLCompanyKey OR @GLCompanyKey IS NULL)
	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(c.GLCompanyKey, 0)) ) 
	AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(c.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(c.GLCompanyKey, 0) = @GLCompanyKey)
				)
	AND (@MultiCurrency = 0
		OR isnull(c.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	Group By
		 c.ClientKey
		,c.CheckDate
		,c.ReferenceNumber
		,i.ProjectKey
		,i.CampaignKey
END

-- now add unapplied receipts
if @Receipts = 1 and @ProjectKey is null
begin
	INSERT	#ClientStmt
				(TranType
				,ClientKey
				,TranDate
				,TranRef
				,ProjectKey
				,CampaignKey
				,TranAmt
				,Sort
				,TranSort)
		SELECT	''Payment''
				,c.ClientKey
				,c.CheckDate
				,c.ReferenceNumber
				,NULL
				,NULL
				,-1 * (unapp.CheckAmt - unapp.AppliedAmt)
				,1
				,3
		from #UnappliedRec unapp (nolock)
		inner join tCheck c (nolock) on unapp.CheckKey = c.CheckKey
		where unapp.PostingDate >= @StartDate
end

UPDATE	#ClientStmt
SET		LoggedCompanyKey = @CompanyKey

--Delete rows where the Client is in Balance
IF @IncludeZeroBal = 0
	DELETE	#ClientStmt
	WHERE ClientKey IN (
		SELECT ClientKey
		FROM #ClientStmt
		GROUP BY ClientKey
		HAVING SUM(TranAmt) = 0
	)

if @RollUpMatching > 0
BEGIN
-- cbre custom functions
	INSERT #ClientStmt (LoggedCompanyKey, TranType, ClientKey, TranDate, TranRef, DueDate, TranAmt, Sort, TranSort, Action)
	SELECT LoggedCompanyKey, TranType, ClientKey, MAX(TranDate), TranRef, MAX(DueDate), SUM(TranAmt), MAX(Sort), MAX(TranSort), 1
	From #ClientStmt
	GROUP BY LoggedCompanyKey, TranType, ClientKey, TranRef

	DELETE #ClientStmt Where Action is null

END
		
SELECT	#ClientStmt.*, c.CompanyName
	,ISNULL(p.ProjectNumber,'''') AS ProjectNumber
	,RTRIM(ISNULL(p.ProjectNumber, '''')) + RTRIM(ISNULL('' - '' + p.ProjectName, '''')) AS ProjectFullName
	,CASE 
		WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
			RTRIM(ISNULL(ca.CampaignID, ''''))
		ELSE
			RTRIM(ISNULL(p.ProjectNumber, ''''))
		END AS ProjCamp	
	,CASE 
		WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
			RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, ''''))
		ELSE
			RTRIM(ISNULL(p.ProjectNumber, '''')) + RTRIM(ISNULL('' - '' + p.ProjectName, '''')) 
		END AS ProjCampFullName	
	,RTRIM(ISNULL(cl.CustomerID, ''NO ID'')) as ClientID
	,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName
	,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName
	,ad.Address1
	,ad.Address2
	,ad.Address3
	,ad.City
	,ad.State
	,ad.PostalCode
	,ad.Country
	,cl.CompanyName as BCompanyName
	,case when cl.BillingAddressKey IS NOT NULL then bad.Address1
	else cad.Address1 end as BAddress1,	
	case when cl.BillingAddressKey IS NOT NULL then bad.Address2
	else cad.Address2 end as BAddress2,	
	case when cl.BillingAddressKey IS NOT NULL then bad.Address3
	else cad.Address3 end as BAddress3,
	case when cl.BillingAddressKey IS NOT NULL then bad.City
	else cad.City end as BCity,
	case when cl.BillingAddressKey IS NOT NULL then bad.State
	else cad.State end as BState,	
	case when cl.BillingAddressKey IS NOT NULL then bad.PostalCode
	else cad.PostalCode end as BPostalCode,
	case when cl.BillingAddressKey IS NOT NULL then bad.Country
	else cad.Country end as BCountry
FROM	#ClientStmt
INNER JOIN tCompany cl (nolock) ON #ClientStmt.ClientKey = cl.CompanyKey
inner join tCompany c (nolock) on #ClientStmt.LoggedCompanyKey = c.CompanyKey
LEFT JOIN tProject p (nolock) ON #ClientStmt.ProjectKey = p.ProjectKey
LEFT JOIN tAddress ad (nolock) ON c.DefaultAddressKey = ad.AddressKey
LEFT JOIN tAddress cad (nolock) ON cl.DefaultAddressKey = cad.AddressKey
LEFT JOIN tAddress bad (nolock) ON cl.BillingAddressKey = bad.AddressKey
LEFT JOIN tCampaign ca (nolock) on #ClientStmt.CampaignKey = ca.CampaignKey

ORDER BY cl.CustomerID, Sort, TranDate, TranSort
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptCCEntryFindSuggestion]'
GO
IF OBJECT_ID(N'[dbo].[sptCCEntryFindSuggestion]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptCCEntryFindSuggestion]
    @CCEntryKey int
AS
BEGIN
    SET NOCOUNT ON;

    /*
    || When       Who Rel            What
	|| 07/22/25  MAS 25.08.17		(704930) Created
	|| 09/10/25  MAS 25.09.21		(711066) Added missing ExpenseAccountKey to the results
	|| 03/13/26  MAS 26.04.19		(722368) Added voucher lookup by Company/Vendor/NormalizedMemo/Amount
	|| 04/24/26  MAS 26.05.17		(727105) Excluded inactive item matches from AI suggestions
	|| 05/14/26  MAS 26.06.14		(727957) Added voucher fallback by date+amount; allow re-suggest when vendor set but no voucher
	|| 06/17/26  MAS 26.06.14		(730937) Added Pass 4: fallback match on ExpenseAccountKey/ProjectKey/OfficeKey/DepartmentKey/ClassKey for entries never coded with Item/Task/Vendor
    */

    -- =================================================================
    -- Step 1: Get the details of the new transaction to be matched
    -- =================================================================
    DECLARE @GLAccountKey INT;
    DECLARE @CompanyKey INT;
    DECLARE @NormalizedPayeeName VARCHAR(100);
    DECLARE @PayeeName VARCHAR(100);
    DECLARE @OriginalMemo VARCHAR(MAX);
    DECLARE @NormalizedMemo VARCHAR(100);
    DECLARE @Amount DECIMAL(19, 4);
    DECLARE @TransactionPostedDate SMALLDATETIME;

    SELECT
        @CompanyKey = CompanyKey,
        @GLAccountKey = GLAccountKey,
        @PayeeName = PayeeName,
        @NormalizedPayeeName = NormalizedPayeeName,
        @OriginalMemo = OriginalMemo,
        @NormalizedMemo = NormalizedMemo,
        @Amount = Amount,
        @TransactionPostedDate = TransactionPostedDate
    FROM
        tCCEntry (NOLOCK)
    WHERE
        CCEntryKey = @CCEntryKey

    IF ISNULL(@CCEntryKey, 0) = 0 OR ISNULL(@GLAccountKey, 0) = 0 OR ISNULL(LTRIM(RTRIM(@NormalizedPayeeName)), '''') = ''''
    BEGIN
        RETURN -1;
    END

    DECLARE @MatchResult TABLE (
        CCEntryKey INT,
        GLAccountKey INT,
        ProjectKey INT,
        ItemKey INT,
        TaskKey INT,
        OfficeKey INT,
        DepartmentKey INT,
        ExpenseAccountKey INT,
        ClassKey INT,
        VendorKey INT
    );

    DECLARE @MatchedProjectKey INT;
    DECLARE @MatchedItemKey INT;
    DECLARE @MatchedTaskKey INT;
    DECLARE @MatchedOfficeKey INT;
    DECLARE @MatchedDepartmentKey INT;
    DECLARE @MatchedExpenseAccountKey INT;
    DECLARE @MatchedClassKey INT;
    DECLARE @MatchedVendorKey INT;
    DECLARE @MatchedVoucherKey INT;

    -- =================================================================
    -- Main passes: only run when the entry is fully unmatched
    -- =================================================================
    IF EXISTS (
        SELECT 1 FROM tCCEntry (NOLOCK)
        WHERE CCEntryKey = @CCEntryKey
            AND ProjectKey IS NULL AND ItemKey IS NULL AND TaskKey IS NULL
            AND OfficeKey IS NULL AND DepartmentKey IS NULL
            AND ExpenseAccountKey IS NULL AND ClassKey IS NULL AND VendorKey IS NULL
    )
    BEGIN

        -- =================================================================
        -- Pass 1: Exact match on PayeeName AND OriginalMemo
        -- =================================================================
        INSERT INTO @MatchResult
        SELECT TOP 1
            CCEntryKey, GLAccountKey, ProjectKey, ItemKey, TaskKey, OfficeKey, DepartmentKey, ExpenseAccountKey, ClassKey, VendorKey
        FROM
            tCCEntry (NOLOCK)
        WHERE
            CompanyKey = @CompanyKey
            AND GLAccountKey = @GLAccountKey
            AND PayeeName = @PayeeName
            AND OriginalMemo = @OriginalMemo
            AND CCEntryKey <> @CCEntryKey
            AND ISNULL(CCVoucherKey, 0) > 0
            AND (ISNULL(SplitOrders, 0) = 0 AND ISNULL(SplitProjects, 0) = 0 AND ISNULL(SplitVouchers, 0) = 0)
            AND (ItemKey IS NOT NULL OR TaskKey IS NOT NULL OR VendorKey IS NOT NULL)
            AND (
                ItemKey IS NULL
                OR EXISTS (
                    SELECT 1
                    FROM tItem (NOLOCK)
                    WHERE tItem.ItemKey = tCCEntry.ItemKey
                        AND ISNULL(tItem.Active, 0) = 1
                )
            )
        ORDER BY
            TransactionPostedDate DESC;

        -- =================================================================
        -- Pass 2: Exact match on NormalizedPayeeName AND OriginalMemo
        -- =================================================================
        IF NOT EXISTS (SELECT 1 FROM @MatchResult)
        BEGIN
            INSERT INTO @MatchResult
            SELECT TOP 1
                CCEntryKey, GLAccountKey, ProjectKey, ItemKey, TaskKey, OfficeKey, DepartmentKey, ExpenseAccountKey, ClassKey, VendorKey
            FROM
                tCCEntry (NOLOCK)
            WHERE
                CompanyKey = @CompanyKey
                AND GLAccountKey = @GLAccountKey
                AND NormalizedPayeeName = @NormalizedPayeeName
                AND OriginalMemo = @OriginalMemo
                AND CCEntryKey <> @CCEntryKey
                AND ISNULL(CCVoucherKey, 0) > 0
                AND (ISNULL(SplitOrders, 0) = 0 AND ISNULL(SplitProjects, 0) = 0 AND ISNULL(SplitVouchers, 0) = 0)
                AND (ItemKey IS NOT NULL OR TaskKey IS NOT NULL OR VendorKey IS NOT NULL)
                AND (
                    ItemKey IS NULL
                    OR EXISTS (
                        SELECT 1
                        FROM tItem (NOLOCK)
                        WHERE tItem.ItemKey = tCCEntry.ItemKey
                            AND ISNULL(tItem.Active, 0) = 1
                    )
                )
            ORDER BY
                TransactionPostedDate DESC;
        END

        -- =================================================================
        -- Pass 3: Normalized Payee Name Match
        -- =================================================================
        IF NOT EXISTS (SELECT 1 FROM @MatchResult)
        BEGIN
            INSERT INTO @MatchResult
            SELECT TOP 1
                CCEntryKey, GLAccountKey, ProjectKey, ItemKey, TaskKey, OfficeKey, DepartmentKey, ExpenseAccountKey, ClassKey, VendorKey
            FROM
                tCCEntry (NOLOCK)
            WHERE
                CompanyKey = @CompanyKey
                AND GLAccountKey = @GLAccountKey
                AND NormalizedPayeeName = @NormalizedPayeeName
                AND CCEntryKey <> @CCEntryKey
                AND ISNULL(CCVoucherKey, 0) > 0
                AND (ISNULL(SplitOrders, 0) = 0 AND ISNULL(SplitProjects, 0) = 0 AND ISNULL(SplitVouchers, 0) = 0)
                AND (ItemKey IS NOT NULL OR TaskKey IS NOT NULL OR VendorKey IS NOT NULL)
                AND (
                    ItemKey IS NULL
                    OR EXISTS (
                        SELECT 1
                        FROM tItem (NOLOCK)
                        WHERE tItem.ItemKey = tCCEntry.ItemKey
                            AND ISNULL(tItem.Active, 0) = 1
                    )
                )
            ORDER BY
                TransactionPostedDate DESC;
        END

        -- =================================================================
        -- Pass 4: Fallback - match on any other coding field when no
        -- Item/Task/Vendor match exists (e.g. ExpenseAccountKey-only entries)
        -- =================================================================
        IF NOT EXISTS (SELECT 1 FROM @MatchResult)
        BEGIN
            INSERT INTO @MatchResult
            SELECT TOP 1
                CCEntryKey, GLAccountKey, ProjectKey, ItemKey, TaskKey, OfficeKey, DepartmentKey, ExpenseAccountKey, ClassKey, VendorKey
            FROM
                tCCEntry (NOLOCK)
            WHERE
                CompanyKey = @CompanyKey
                AND GLAccountKey = @GLAccountKey
                AND NormalizedPayeeName = @NormalizedPayeeName
                AND CCEntryKey <> @CCEntryKey
                AND ISNULL(CCVoucherKey, 0) > 0
                AND (ISNULL(SplitOrders, 0) = 0 AND ISNULL(SplitProjects, 0) = 0 AND ISNULL(SplitVouchers, 0) = 0)
                AND (ProjectKey IS NOT NULL OR OfficeKey IS NOT NULL OR DepartmentKey IS NOT NULL
                    OR ExpenseAccountKey IS NOT NULL OR ClassKey IS NOT NULL)
                AND ItemKey IS NULL AND TaskKey IS NULL AND VendorKey IS NULL
            ORDER BY
                TransactionPostedDate DESC;
        END

        -- =================================================================
        -- Final Update and Select
        -- =================================================================
        IF EXISTS (SELECT 1 FROM @MatchResult)
        BEGIN
            SELECT TOP 1
                @MatchedProjectKey = ProjectKey,
                @MatchedItemKey = ItemKey,
                @MatchedTaskKey = TaskKey,
                @MatchedOfficeKey = OfficeKey,
                @MatchedDepartmentKey = DepartmentKey,
                @MatchedExpenseAccountKey = ExpenseAccountKey,
                @MatchedClassKey = ClassKey,
                @MatchedVendorKey = VendorKey
            FROM @MatchResult;

            -- Voucher pass A: vendor + InvoiceNumber + open balance (most specific)
            SELECT TOP 1
                @MatchedVoucherKey = v.VoucherKey
            FROM tVoucher v (NOLOCK)
            WHERE v.CompanyKey = @CompanyKey
                AND ISNULL(@MatchedVendorKey, 0) > 0
                AND v.VendorKey = @MatchedVendorKey
                AND ISNULL(@NormalizedMemo, '''') <> ''''
                AND v.InvoiceNumber = @NormalizedMemo
                AND @Amount IS NOT NULL
                AND ROUND(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 2) = ROUND(@Amount, 2)
            ORDER BY v.InvoiceDate DESC, v.VoucherKey DESC;

            -- Voucher pass B: vendor + open balance + exact posted date
            IF ISNULL(@MatchedVoucherKey, 0) = 0
                AND ISNULL(@MatchedVendorKey, 0) > 0
                AND @TransactionPostedDate IS NOT NULL
            BEGIN
                SELECT TOP 1
                    @MatchedVoucherKey = v.VoucherKey
                FROM tVoucher v (NOLOCK)
                WHERE v.CompanyKey = @CompanyKey
                    AND v.VendorKey = @MatchedVendorKey
                    AND ROUND(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 2) = ROUND(@Amount, 2)
                    AND CAST(v.InvoiceDate AS DATE) = CAST(@TransactionPostedDate AS DATE)
                ORDER BY v.InvoiceDate DESC, v.VoucherKey DESC;
            END

            -- Voucher pass C: vendor + open balance + posted date A�1 day
            IF ISNULL(@MatchedVoucherKey, 0) = 0
                AND ISNULL(@MatchedVendorKey, 0) > 0
                AND @TransactionPostedDate IS NOT NULL
            BEGIN
                SELECT TOP 1
                    @MatchedVoucherKey = v.VoucherKey
                FROM tVoucher v (NOLOCK)
                WHERE v.CompanyKey = @CompanyKey
                    AND v.VendorKey = @MatchedVendorKey
                    AND ROUND(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 2) = ROUND(@Amount, 2)
                    AND CAST(v.InvoiceDate AS DATE)
                        BETWEEN DATEADD(DAY, -1, CAST(@TransactionPostedDate AS DATE))
                            AND DATEADD(DAY,  1, CAST(@TransactionPostedDate AS DATE))
                ORDER BY v.InvoiceDate DESC, v.VoucherKey DESC;
            END

            UPDATE tCCEntry
            SET
                AISuggested = 1,
                ItemKey = @MatchedItemKey,
                ProjectKey = @MatchedProjectKey,
                TaskKey = @MatchedTaskKey,
                OfficeKey = @MatchedOfficeKey,
                DepartmentKey = @MatchedDepartmentKey,
                ExpenseAccountKey = @MatchedExpenseAccountKey,
                ClassKey = @MatchedClassKey,
                VendorKey = @MatchedVendorKey,
                VoucherKey = @MatchedVoucherKey
            WHERE CCEntryKey = @CCEntryKey;

            -- Return the result to the UI
            SELECT
                @CCEntryKey AS CCEntryKey,
                ta.TaskKey, ta.TaskID, ta.TaskName,
                p.ProjectKey, p.ProjectNumber, p.ProjectName,
                i.ItemKey, i.ItemName, i.ItemID,
                o.OfficeKey, o.OfficeID, o.OfficeName,
                cl.ClassKey, cl.ClassID, cl.ClassName,
                r.VendorKey, c.VendorID, c.CompanyName AS VendorName,
                r.DepartmentKey, d.DepartmentName,
                r.ExpenseAccountKey, ea.AccountNumber as ExpenseAccountNumber, ea.AccountName as ExpenseAccountName,
                @MatchedVoucherKey AS VoucherKey,
                ISNULL(v.InvoiceNumber, '''') as InvoiceNumber,
                ISNULL(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 0) as VoucherAmountOpen
            FROM @MatchResult r
            LEFT OUTER JOIN tTask ta (NOLOCK) ON r.TaskKey = ta.TaskKey
            LEFT OUTER JOIN tProject p (NOLOCK) ON r.ProjectKey = p.ProjectKey
            LEFT OUTER JOIN tItem i (NOLOCK) on r.ItemKey = i.ItemKey
            LEFT OUTER JOIN tOffice o (NOLOCK) ON r.OfficeKey = o.OfficeKey
            LEFT OUTER JOIN tClass cl (NOLOCK) ON r.ClassKey = cl.ClassKey
            LEFT OUTER JOIN tCompany c (NOLOCK) ON r.VendorKey = c.CompanyKey
            LEFT OUTER JOIN tDepartment d (NOLOCK) ON r.DepartmentKey = d.DepartmentKey
            LEFT OUTER JOIN tGLAccount ea (NOLOCK) ON r.ExpenseAccountKey = ea.GLAccountKey
            LEFT OUTER JOIN tVoucher v (NOLOCK) ON v.VoucherKey = @MatchedVoucherKey;
        END

        RETURN 0;

    END -- end main passes

    -- =================================================================
    -- Re-suggest fallback: entry already has vendor assigned but no
    -- voucher.  Tries to attach a voucher without touching any field
    -- the user may have set manually.
    -- =================================================================
    DECLARE @ResuggestVendorKey INT;
    DECLARE @ResuggestVoucherKey INT;

    SELECT
        @ResuggestVendorKey = VendorKey
    FROM tCCEntry (NOLOCK)
    WHERE CCEntryKey = @CCEntryKey
        AND VendorKey IS NOT NULL
        AND VoucherKey IS NULL
        AND ISNULL(SplitOrders, 0) = 0
        AND ISNULL(SplitProjects, 0) = 0
        AND ISNULL(SplitVouchers, 0) = 0;

    IF ISNULL(@ResuggestVendorKey, 0) > 0
    BEGIN
        -- Voucher pass A: vendor + InvoiceNumber + open balance (most specific)
        SELECT TOP 1
            @ResuggestVoucherKey = v.VoucherKey
        FROM tVoucher v (NOLOCK)
        WHERE v.CompanyKey = @CompanyKey
            AND v.VendorKey = @ResuggestVendorKey
            AND ISNULL(@NormalizedMemo, '''') <> ''''
            AND v.InvoiceNumber = @NormalizedMemo
            AND ROUND(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 2) = ROUND(@Amount, 2)
        ORDER BY v.InvoiceDate DESC, v.VoucherKey DESC;

        -- Voucher pass B: vendor + open balance + exact posted date
        IF ISNULL(@ResuggestVoucherKey, 0) = 0 AND @TransactionPostedDate IS NOT NULL
        BEGIN
            SELECT TOP 1
                @ResuggestVoucherKey = v.VoucherKey
            FROM tVoucher v (NOLOCK)
            WHERE v.CompanyKey = @CompanyKey
                AND v.VendorKey = @ResuggestVendorKey
                AND ROUND(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 2) = ROUND(@Amount, 2)
                AND CAST(v.InvoiceDate AS DATE) = CAST(@TransactionPostedDate AS DATE)
            ORDER BY v.InvoiceDate DESC, v.VoucherKey DESC;
        END

        -- Voucher pass C: vendor + open balance + posted date A�1 day
        IF ISNULL(@ResuggestVoucherKey, 0) = 0 AND @TransactionPostedDate IS NOT NULL
        BEGIN
            SELECT TOP 1
                @ResuggestVoucherKey = v.VoucherKey
            FROM tVoucher v (NOLOCK)
            WHERE v.CompanyKey = @CompanyKey
                AND v.VendorKey = @ResuggestVendorKey
                AND ROUND(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 2) = ROUND(@Amount, 2)
                AND CAST(v.InvoiceDate AS DATE)
                    BETWEEN DATEADD(DAY, -1, CAST(@TransactionPostedDate AS DATE))
                        AND DATEADD(DAY,  1, CAST(@TransactionPostedDate AS DATE))
            ORDER BY v.InvoiceDate DESC, v.VoucherKey DESC;
        END

        IF ISNULL(@ResuggestVoucherKey, 0) > 0
        BEGIN
            -- Only update VoucherKey; never overwrite fields the user may have set
            UPDATE tCCEntry
            SET VoucherKey = @ResuggestVoucherKey,
                AISuggested = 1
            WHERE CCEntryKey = @CCEntryKey
                AND VoucherKey IS NULL;

            SELECT
                @CCEntryKey AS CCEntryKey,
                ta.TaskKey, ta.TaskID, ta.TaskName,
                p.ProjectKey, p.ProjectNumber, p.ProjectName,
                i.ItemKey, i.ItemName, i.ItemID,
                o.OfficeKey, o.OfficeID, o.OfficeName,
                cl.ClassKey, cl.ClassID, cl.ClassName,
                cmp.CompanyKey AS VendorKey, cmp.VendorID, cmp.CompanyName AS VendorName,
                dep.DepartmentKey, dep.DepartmentName,
                ea.GLAccountKey AS ExpenseAccountKey, ea.AccountNumber as ExpenseAccountNumber, ea.AccountName as ExpenseAccountName,
                @ResuggestVoucherKey AS VoucherKey,
                ISNULL(v.InvoiceNumber, '''') as InvoiceNumber,
                ISNULL(ISNULL(v.VoucherTotal, 0) - ISNULL(v.AmountPaid, 0), 0) as VoucherAmountOpen
            FROM tCCEntry cc (NOLOCK)
            LEFT OUTER JOIN tTask ta (NOLOCK) ON cc.TaskKey = ta.TaskKey
            LEFT OUTER JOIN tProject p (NOLOCK) ON cc.ProjectKey = p.ProjectKey
            LEFT OUTER JOIN tItem i (NOLOCK) ON cc.ItemKey = i.ItemKey
            LEFT OUTER JOIN tOffice o (NOLOCK) ON cc.OfficeKey = o.OfficeKey
            LEFT OUTER JOIN tClass cl (NOLOCK) ON cc.ClassKey = cl.ClassKey
            LEFT OUTER JOIN tCompany cmp (NOLOCK) ON cc.VendorKey = cmp.CompanyKey
            LEFT OUTER JOIN tDepartment dep (NOLOCK) ON cc.DepartmentKey = dep.DepartmentKey
            LEFT OUTER JOIN tGLAccount ea (NOLOCK) ON cc.ExpenseAccountKey = ea.GLAccountKey
            LEFT OUTER JOIN tVoucher v (NOLOCK) ON v.VoucherKey = @ResuggestVoucherKey
            WHERE cc.CCEntryKey = @CCEntryKey;

            RETURN 0;
        END
    END

    RETURN -1;
END


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

	(
		@InvoiceKey int,
		@Status smallint,
		@ApprovalComments nvarchar(500) = NULL,
		@CreateRollupTempTable int = 1,
		@SubmittedByKey int = null
	)

AS --Encrypt

/*
|| When     Who Rel   What
|| 06/18/08 GHL 8.513 Added logic for Opening Transactions.
|| 04/21/09 GWG 10.023 Modify approval of child invoices so it sets inv number on approval
|| 02/17/10 GHL 10.518 (73756) Added logic for rollup of the Billed Amount Approved field
|| 05/24/12 GHL 10.556 Added update of ApprovedDate
|| 01/08/15 GHL 10.588 (241726) Added checking of posted status before unapproving
|| 09/29/15 GHL 10.596 Trimming now InvoiceNumber
|| 05/05/16 GHL 10.603 Added final validation when submitting or approving 
|| 03/08/21 RLS 21.0.4 (550747) Changed @ApprovalComments to nvarchar
|| 04/03/25 MCM 25.05.x  (652187) Added SubmittedByKey in order to email back to the submitted user
|| 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
*/

Declare @CurStatus int, 
		@InvoiceDate smalldatetime, 
		@PostingDate smalldatetime, 
		@DueDate smalldatetime, 
		@InvoiceNumber varchar(100), 
		@NextTranNo varchar(100),
		@CompanyKey int,
		@RetVal int,
		@TermsKey int,
		@DueDays int,
		@PostToGL tinyint,
		@OpeningTransaction tinyint,
		@ApprovedDate smalldatetime,
		@Posted int,
		@ExistingSubmittedByKey int,
		@AdvanceBill tinyint
		
Select @CurStatus = InvoiceStatus 
	   ,@InvoiceDate = InvoiceDate 
	   ,@PostingDate = PostingDate 
	   ,@DueDate = DueDate 
	   ,@InvoiceNumber = InvoiceNumber
	   ,@CompanyKey = CompanyKey	
	   ,@TermsKey = TermsKey
	   ,@OpeningTransaction = ISNULL(OpeningTransaction, 0)
	   ,@Posted = Posted
	   ,@ExistingSubmittedByKey = SubmittedByKey
	   ,@AdvanceBill = AdvanceBill
from tInvoice (NOLOCK) 
Where InvoiceKey = @InvoiceKey

if @CurStatus = 4 and @Status <> 4
BEGIN
	if exists(Select 1 from tInvoiceAdvanceBill (nolock) Where AdvBillInvoiceKey = @InvoiceKey)
		return -1
	if exists(Select 1 from tInvoiceCredit (nolock) Where CreditInvoiceKey = @InvoiceKey)
		return -2
	if exists(Select 1 from tInvoice (nolock) Where ParentInvoiceKey = @InvoiceKey and InvoiceStatus = 4)
		return -3
	if exists(Select 1 from tCheckAppl (nolock) Where InvoiceKey = @InvoiceKey and ISNULL(Prepay, 0) = 0)
		return -4
	if @Posted = 1
		return -5
END	

if @Status in (2, 4)
begin
	-- if we submit or approve, validate the invoice
	exec @RetVal = sptInvoiceValidate @InvoiceKey

	-- if there is an error, return error with an offset of -10 to avoid conflict with local returns
	if @RetVal <> 1
		return @RetVal - 10
end

if @Status = 4
	select @ApprovedDate = Cast(Cast(DatePart(mm,GETDATE()) as varchar) + ''/'' + Cast(DatePart(dd,GETDATE()) as varchar) + ''/'' + Cast(DatePart(yyyy,GETDATE()) as varchar) as smalldatetime)
-- else we leave ApprovedDate at null

-- Make sure that we have an InvoiceNumber before approving	
-- tPreference.SetInvoiceNumberOnApproval allows for delaying assignment of InvoiceNumber
IF @Status = 4 And (@InvoiceNumber IS NULL OR @InvoiceNumber = '''')
BEGIN
		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
	
	IF @InvoiceDate IS NULL
		SELECT 	@InvoiceDate = CONVERT(VARCHAR(10), GETDATE(), 101)
	
	SELECT @PostToGL = ISNULL(PostToGL, 0)
	FROM   tPreference (NOLOCK)
	WHERE  CompanyKey = @CompanyKey
	
	IF @OpeningTransaction = 1
		SELECT @PostToGL = 0
		
	IF @PostingDate IS NULL AND @PostToGL = 1  
		SELECT 	@PostingDate = @InvoiceDate
			
	IF @DueDate IS NULL
	BEGIN
		SELECT @DueDays = DueDays
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @TermsKey
		
		SELECT @DueDate = DATEADD(day, @DueDays, @InvoiceDate)	
	END

	UPDATE tInvoice 
	SET InvoiceNumber	= LTRIM(RTRIM(@NextTranNo)) 
		,InvoiceDate	= @InvoiceDate
		,PostingDate	= @PostingDate
		,DueDate		= @DueDate
	WHERE InvoiceKey	= @InvoiceKey
			
END

if @ApprovalComments is null
	Update tInvoice
	Set
		InvoiceStatus = @Status,
		SubmittedByKey = case when @Status = 2 then @SubmittedByKey else @ExistingSubmittedByKey end,
		ApprovedDate = @ApprovedDate
	Where
		InvoiceKey = @InvoiceKey
else
	Update tInvoice
	Set
		InvoiceStatus = @Status,
		SubmittedByKey = case when @Status = 2 then @SubmittedByKey else @ExistingSubmittedByKey end,
		ApprovalComments = @ApprovalComments,
		ApprovedDate = @ApprovedDate
	Where
		InvoiceKey = @InvoiceKey
		
if @CreateRollupTempTable = 1
	create table #tProjectItemRollup (ProjectKey int null, Entity varchar(50) null, EntityKey int null, BilledAmountApproved money null) 
			
if @Status = 4 Or @CurStatus = 4
begin
		truncate table #tProjectItemRollup
		
		INSERT #tProjectItemRollup(ProjectKey,Entity,EntityKey)
		SELECT ProjectKey, isnull(Entity, ''tService''), ISNULL(EntityKey, 0)
		FROM   tInvoiceSummary (NOLOCK)
		WHERE  ProjectKey IN (SELECT ProjectKey FROM tInvoiceSummary (NOLOCK) WHERE InvoiceKey = @InvoiceKey)
		GROUP BY ProjectKey, isnull(Entity, ''tService''), isnull(EntityKey, 0)

		UPDATE #tProjectItemRollup
        SET	#tProjectItemRollup.BilledAmountApproved = 
			ISNULL((SELECT SUM(isum.Amount + isum.SalesTaxAmount)
			FROM tInvoiceSummary isum (NOLOCK) 
				INNER JOIN tInvoice i (NOLOCK) ON isum.InvoiceKey = i.InvoiceKey 
			WHERE i.AdvanceBill = 0 
			and   i.InvoiceStatus = 4
			and isum.ProjectKey = #tProjectItemRollup.ProjectKey
			AND   ISNULL(isum.Entity, ''tService'') = #tProjectItemRollup.Entity COLLATE DATABASE_DEFAULT
			AND   ISNULL(isum.EntityKey, 0) = #tProjectItemRollup.EntityKey
			),0)


		UPDATE tProjectItemRollup
		SET    tProjectItemRollup.BilledAmountApproved = pir.BilledAmountApproved
		FROM   #tProjectItemRollup pir
		WHERE  tProjectItemRollup.ProjectKey = pir.ProjectKey
		AND    tProjectItemRollup.Entity = pir.Entity COLLATE DATABASE_DEFAULT
		AND    tProjectItemRollup.EntityKey = pir.EntityKey
		
		UPDATE tProjectRollup
		SET    tProjectRollup.BilledAmountApproved = pir.BilledAmountApproved
		FROM   (
				SELECT SUM(BilledAmountApproved) AS BilledAmountApproved , ProjectKey
				FROM  #tProjectItemRollup
				GROUP BY ProjectKey
				) AS pir
		WHERE  tProjectRollup.ProjectKey = pir.ProjectKey		
end
		
		
-- modified to handle assigning numbers to child invoices on approval.
if @Status = 4
BEGIN
	declare @curKey int
	Select @curKey = -1
	While 1=1
	BEGIN
		Select @curKey = min(InvoiceKey) from tInvoice (nolock) Where ParentInvoiceKey = @InvoiceKey and InvoiceKey > @curKey
			if @curKey is null break
			exec sptInvoiceChangeStatus @curKey, 4, @ApprovalComments, 0 -- 0: do not create a temp table
	END
END

		
		
 RETURN 1 		
		

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptForecastCalcBuckets]'
GO
IF OBJECT_ID(N'[dbo].[sptForecastCalcBuckets]', 'P') IS NOT NULL
EXEC sp_executesql N'
-- Stored Procedure

ALTER PROCEDURE [dbo].[sptForecastCalcBuckets]
	(
	@ForecastDetailKey int
	,@Sequence int
	,@Debug int = 0
	)
AS --Encrypt

/*
|| When      Who Rel      What
|| 10/11/12  GHL 10.5.6.1 Created for revenue forecasting
||                        This sp breaks down the total into 14 buckets
|| 10/31/12  GHL 10.5.6.1 For item and service entities, do not update tForecastDetailItem but tForecastDetail
|| 11/02/12  GHL 10.5.6.1 Working now with 15 buckets instead of 14 (in case the item end date is several years after)
||                        Prior Years      1 bucket
||                        Current Years   12 buckets
||                        Next 12 Months   1 bucket
||                        Years After      1 bucket
|| 11/05/12  GHL 10.5.6.2 The amount for each bucket should be a function of the number of days in the bucket 
|| 09/30/19  GHL 19.1.0.0 (446232) Added support for multicurrency
|| 02/25/26  AMP 26.03.15 (697399) Added the ByMonth option for opptys only - will divide the amount evenly across the number of months instead of by number of days in each month
|| 04/23/26  MCM 26.05.x  (727238) Updated logic for the ByMonth to default to 0 if null
|| 05/06/26  MCM 26.05.x  (728028) Added logic back in the to spread at Start, End that was accidentally removed in a previous change
|| 05/08/26  AMP 26.06.14 (728319) Fixed a bug so that the ByMonth option does not effect any other types but Opportunities
*/

	SET NOCOUNT ON

	/* Prepare a table of 15 buckets (only 14 buckets will be displayed, and Total = sum(14 buckets))

	Example:
	StartMonth = 2
	StartYear = 2010

	StartDate  EndDate     Idx    #Days Total
	------------------------------------------
    null       01/31/2010   0     null   null   -- Prior Years (all)    

	02/01/2010 02/28/2010   1     28      null
    03/01/2010 03/31/2010   2     31      null
    04/01/2010 04/30/2010   3     30      null
    05/01/2010 05/31/2010   4     31      null
    06/01/2010 06/30/2010   5     30      null
    07/01/2010 07/31/2010   6     30      null
    08/01/2010 08/31/2010   7     30      null
    09/01/2010 09/30/2010   8     30      null
    10/01/2010 10/31/2010   9     30      null
    11/01/2010 11/30/2010   10    30      null
    12/01/2010 12/31/2010   11    30      null
	01/01/2011 01/31/2011   12    30      null

	02/01/2011 null         13    null     null  -- Next Year
	02/01/2012 null         14    null     null  -- All years after

	null and #Days will be recalculated for each record 

	update #tBuckets
	set    StartDate = @StartDate
	where  StartDate
	*/

	/*
	Can do this if you want the sequence unique

	declare @Sequence int
	select @Sequence = 0
	update tForecastDetailItem
	set    Sequence = @Sequence
		   ,@Sequence = @Sequence + 1
	where  ForecastDetailKey = @ForecastDetailKey

	select * from tForecastDetailItem

	*/

	/*
	Create and prepare the buckets from the forecast
	Could be done once
	*/

	-- inputs from tForecast or tForecastDetail 
	declare @StartMonth int
	declare @StartYear int
	declare @SpreadExpense int
	declare @Entity varchar(50)
	declare @Months int

	-- inputs from tForecastDetailItem
	declare @Total money
	declare @StartDate smalldatetime
	declare @EndDate smalldatetime
	declare @Spread int
	declare @Labor int -- is it labor or expense?

	declare @kSpreadAtStart int		select @kSpreadAtStart = 0
	declare @kSpreadAtEnd int		select @kSpreadAtEnd = 1
	declare @kSpreadEvenly int		select @kSpreadEvenly = 2
	declare @ByMonth int
	declare @Opportunity int
	declare @UseByMonth int
	declare @MonthTotal decimal (24,4)


	select @StartMonth = f.StartMonth 
	      ,@StartYear = f.StartYear
		  ,@SpreadExpense = f.SpreadExpense

		  ,@Entity = fd.Entity
		  ,@StartDate = fd.StartDate
		  ,@Months = fd.Months
		  ,@Total = fd.Total
		  ,@ByMonth = isnull(f.ByMonth,0)
		  ,@Opportunity = isnull(p.Opportunity,0)
	from   tForecast f (nolock)
           inner join tForecastDetail fd (nolock) on f.ForecastKey = fd.ForecastKey
		   LEFT JOIN tProject p (nolock) on fd.EntityKey = p.ProjectKey AND fd.Entity in (''tProject-Potential'', ''tProject-Approved'')
	where  fd.ForecastDetailKey = @ForecastDetailKey

	-- cannot find forecast
	if @@ROWCOUNT = 0
		return -1

	select @UseByMonth = case 
		when isnull(@ByMonth, 0) = 1 
			and isnull(@Months, 0) > 0 
			and (@Entity = ''tLead'' or (@Entity in (''tProject-Potential'', ''tProject-Approved'') and isnull(@Opportunity, 0) = 1)) then 1
		else 0
	end

	if @Entity = ''tRetainer''
	begin
		exec sptForecastCalcBucketsRetainer @ForecastDetailKey
		return 1
	end

	if @Entity = ''tInvoice''
	begin
		return 1
	end

	create table #tBuckets (
		StartDate smalldatetime null
		,EndDate smalldatetime null
		,Idx int null
		,NumDays int null
		,Total money null
		)

	-- Current Year
	declare @ForecastStartDate smalldatetime
	declare @ForecastEndDate smalldatetime

	-- Prior Years
	declare @PriorEndDate smalldatetime

	-- Next 12 months
	declare @NextYearStartDate smalldatetime
	declare @NextYearEndDate smalldatetime

	-- Years after
	declare @YearAfterStartDate smalldatetime

	-- vars for loop
	declare @BucketStartDate smalldatetime
	declare @BucketIdx int

	select @ForecastStartDate = cast (@StartMonth as varchar(2)) + ''/01/'' + cast (@StartYear as varchar(4))
	select @ForecastEndDate = dateadd(yy, 1, @ForecastStartDate)
	select @ForecastEndDate = dateadd(d, -1, @ForecastEndDate)

	select @PriorEndDate = dateadd(d, -1, @ForecastStartDate)

	select @NextYearStartDate = dateadd(d, 1, @ForecastEndDate)
	select @NextYearEndDate = dateadd(yy, 1, @NextYearStartDate)
	select @NextYearEndDate = dateadd(d, -1, @NextYearEndDate)

	select @YearAfterStartDate = dateadd(d, 1, @NextYearEndDate)

	--select @ForecastStartDate, @ForecastEndDate 

	select @BucketStartDate = @ForecastStartDate
	select @BucketIdx = 1
	while (@BucketIdx <= 12)
	begin
		insert #tBuckets (StartDate,EndDate,Idx)
		values (@BucketStartDate, null, @BucketIdx)

		select @BucketStartDate = dateadd(m, 1,@BucketStartDate)
		select @BucketIdx = @BucketIdx + 1 
	end

	-- add 1 month and subtract 1 day to find the end of the month
	update #tBuckets 
	set    EndDate = dateadd(m, 1, StartDate)
	update #tBuckets 
	set    EndDate = dateadd(d, -1, EndDate)

	-- insert the bucket for Prev Years
	insert #tBuckets (StartDate,EndDate,Idx)
	values (''01/01/1900'', @PriorEndDate, 0)

	-- insert the bucket for the next 12 months
	insert #tBuckets (StartDate,EndDate,Idx)
	values (@NextYearStartDate, @NextYearEndDate, 13)

	-- insert the bucket for the Years after the next 12 months
	insert #tBuckets (StartDate,EndDate,Idx)
	values (@YearAfterStartDate, ''01/01/2050'', 14)


	/*
	Now process the record
	Basically expand Total into 15 buckets
	*/

	if @Entity in (''tItem'', ''tService'', ''tInvoice'')
	begin	
		-- total and startdate already known, calc other fields
		if @Months > 0
		begin
			select @EndDate = dateadd(m, @Months, @StartDate)
			select @EndDate = dateadd(d, -1, @EndDate)
		end
		else
			select @EndDate = @StartDate

		if @Entity = ''tItem''
			select @Labor = 0
		else if @Entity = ''tService'' 
			select @Labor = 1
		else
			select @Labor = 1
	end
	else
	begin 
		if @UseByMonth = 1
		begin
			select  @Total = fdi.Total
				   ,@StartDate = fd.StartDate
				   ,@EndDate = DATEADD(DAY, -1, DATEADD(MONTH, @Months, fd.StartDate))
				   ,@Labor = fdi.Labor 
			from tForecastDetailItem fdi  (nolock)
				inner join tForecastDetail fd (nolock) on fd.ForecastDetailKey = fdi.ForecastDetailKey
			where fdi.ForecastDetailKey = @ForecastDetailKey
			and   fdi.[Sequence] = @Sequence
		end
		else
		begin
			select  @Total = Total
				   ,@StartDate = StartDate
				   ,@EndDate = EndDate
				   ,@Labor = Labor 
			from tForecastDetailItem  (nolock)
			where  ForecastDetailKey = @ForecastDetailKey
			and    [Sequence] = @Sequence
		end

		-- abort if we cannot find detail item
		if @@ROWCOUNT = 0
			return -2
	end


	if @Labor = 1
		select @Spread = @kSpreadEvenly
	else
		select @Spread = @SpreadExpense

	declare @NumDays int
	declare @DayTotal decimal (24,4)
	declare @RoundError money

	-- Add 1 because diff between 10/01/12 and 10/31/12 is 0
	select @NumDays = datediff(d, @StartDate, @EndDate) + 1

	-- protect against div by 0
	if @NumDays < 1
		select @NumDays = 1

	select @DayTotal = @Total / @NumDays

	-- resets Totals to 0
	update #tBuckets 
	set    Total = 0

	update #tBuckets
	set    StartDate = @StartDate
	where @StartDate > StartDate

	update #tBuckets
	set    EndDate = @EndDate
	where  @EndDate < EndDate

	update #tBuckets
	set    NumDays = datediff(d, StartDate, EndDate) + 1

	update #tBuckets
	set NumDays = 0
	where isnull(NumDays, 0) <=0

	-- if evenly by number of days in the month
	if @UseByMonth = 0
	begin

		update #tBuckets	
		set    Total = ROUND(NumDays * @DayTotal, 2)
	end

	if @UseByMonth = 1
	begin
		-- This is for the option for opptys only for dividing the amount evenly across the number of months instead of by number of days in each month
		select @MonthTotal = @Total / nullif(@Months, 0)

		update #tBuckets
		set    Total =
			case 
				when b.StartDate >= DATEFROMPARTS(YEAR(@StartDate), MONTH(@StartDate), 1)
					and b.StartDate < DATEADD(MONTH, @Months, DATEFROMPARTS(YEAR(@StartDate), MONTH(@StartDate), 1))
					and b.EndDate >= b.StartDate
				then ROUND(@MonthTotal, 4)
				else 0
			end
		from #tBuckets b
	end
	
	select @RoundError = sum(Total) from #tBuckets
	select @RoundError = @Total - isnull(@RoundError, 0)	

	if @RoundError <> 0
	begin
		-- Place the rounding error in the last bucket with a valid NumMonths
		select @BucketIdx = max(Idx) 
		from #tBuckets 
		where NumDays <> 0	

		update #tBuckets
		set    Total = isnull(Total, 0) + @RoundError
		where  Idx = @BucketIdx	
	end

	if @UseByMonth = 0 and @Spread in ( @kSpreadAtStart, @kSpreadAtEnd)
	begin

		update #tBuckets
		set    Total = 0

		if @Spread = @kSpreadAtStart

			select  @BucketIdx = min(Idx) 
			from #tBuckets 
			where NumDays <> 0
		else

			select  @BucketIdx = max(Idx) 
			from #tBuckets 
			where NumDays <> 0 		

		update #tBuckets
		set    Total = @Total
		where  Idx = @BucketIdx

	end

	if @Debug = 1
	begin
		select @StartDate as StartDate
				,@EndDate as EndDate
				, @NumDays as NumDays
				, @RoundError as RoundingError
				,@DayTotal as DayTotal
				, sum(NumDays) as SumNumDays
				, sum(Total) as SumTotal 
		from #tBuckets
		select * from #tBuckets order by Idx
		return
	end

	declare @Bucket0 money,@Bucket1 money,@Bucket2 money,@Bucket3 money,@Bucket4 money,@Bucket5 money,@Bucket6 money
	       ,@Bucket7 money,@Bucket8 money,@Bucket9 money,@Bucket10 money,@Bucket11 money,@Bucket12 money,@Bucket13 money

	select @Bucket0 = Total from #tBuckets where Idx = 0
	select @Bucket1 = Total from #tBuckets where Idx = 1
	select @Bucket2 = Total from #tBuckets where Idx = 2
	select @Bucket3 = Total from #tBuckets where Idx = 3
	select @Bucket4 = Total from #tBuckets where Idx = 4
	select @Bucket5 = Total from #tBuckets where Idx = 5
	select @Bucket6 = Total from #tBuckets where Idx = 6
	select @Bucket7 = Total from #tBuckets where Idx = 7
	select @Bucket8 = Total from #tBuckets where Idx = 8
	select @Bucket9 = Total from #tBuckets where Idx = 9
	select @Bucket10 = Total from #tBuckets where Idx = 10
	select @Bucket11 = Total from #tBuckets where Idx = 11
	select @Bucket12 = Total from #tBuckets where Idx = 12
	select @Bucket13 = Total from #tBuckets where Idx = 13
	-- Note: Bucket 14 (Years After Next 12 months) is lost

	if @Entity in (''tItem'', ''tService'', ''tInvoice'')
	begin
		update tForecastDetail
		set    [Prior] =isnull(@Bucket0, 0)
			  ,Month1 =isnull(@Bucket1, 0)
			  ,Month2 =isnull(@Bucket2, 0)
			  ,Month3 =isnull(@Bucket3, 0)
			  ,Month4 =isnull(@Bucket4, 0)
			  ,Month5 =isnull(@Bucket5, 0)
			  ,Month6 =isnull(@Bucket6, 0)
			  ,Month7 =isnull(@Bucket7, 0)
			  ,Month8 =isnull(@Bucket8, 0)
			  ,Month9 =isnull(@Bucket9, 0)
			  ,Month10 =isnull(@Bucket10, 0)
			  ,Month11 =isnull(@Bucket11, 0)
			  ,Month12 =isnull(@Bucket12, 0)
			  ,NextYear =isnull(@Bucket13, 0)

			  -- by default, the Home Currency amounts are the regular amounts
			  ,[HPrior] =isnull(@Bucket0, 0)
			  ,HMonth1 =isnull(@Bucket1, 0)
			  ,HMonth2 =isnull(@Bucket2, 0)
			  ,HMonth3 =isnull(@Bucket3, 0)
			  ,HMonth4 =isnull(@Bucket4, 0)
			  ,HMonth5 =isnull(@Bucket5, 0)
			  ,HMonth6 =isnull(@Bucket6, 0)
			  ,HMonth7 =isnull(@Bucket7, 0)
			  ,HMonth8 =isnull(@Bucket8, 0)
			  ,HMonth9 =isnull(@Bucket9, 0)
			  ,HMonth10 =isnull(@Bucket10, 0)
			  ,HMonth11 =isnull(@Bucket11, 0)
			  ,HMonth12 =isnull(@Bucket12, 0)
			  ,HNextYear =isnull(@Bucket13, 0)

			  ,HTotal = Total
		where  ForecastDetailKey = @ForecastDetailKey 
	end
	else
		update tForecastDetailItem
		set    [Prior] =isnull(@Bucket0, 0)
			  ,Month1 =isnull(@Bucket1, 0)
			  ,Month2 =isnull(@Bucket2, 0)
			  ,Month3 =isnull(@Bucket3, 0)
			  ,Month4 =isnull(@Bucket4, 0)
			  ,Month5 =isnull(@Bucket5, 0)
			  ,Month6 =isnull(@Bucket6, 0)
			  ,Month7 =isnull(@Bucket7, 0)
			  ,Month8 =isnull(@Bucket8, 0)
			  ,Month9 =isnull(@Bucket9, 0)
			  ,Month10 =isnull(@Bucket10, 0)
			  ,Month11 =isnull(@Bucket11, 0)
			  ,Month12 =isnull(@Bucket12, 0)
			  ,NextYear =isnull(@Bucket13, 0)

			  -- by default, the Home Currency amounts are the regular amounts
			   ,[HPrior] =isnull(@Bucket0, 0)
			  ,HMonth1 =isnull(@Bucket1, 0)
			  ,HMonth2 =isnull(@Bucket2, 0)
			  ,HMonth3 =isnull(@Bucket3, 0)
			  ,HMonth4 =isnull(@Bucket4, 0)
			  ,HMonth5 =isnull(@Bucket5, 0)
			  ,HMonth6 =isnull(@Bucket6, 0)
			  ,HMonth7 =isnull(@Bucket7, 0)
			  ,HMonth8 =isnull(@Bucket8, 0)
			  ,HMonth9 =isnull(@Bucket9, 0)
			  ,HMonth10 =isnull(@Bucket10, 0)
			  ,HMonth11 =isnull(@Bucket11, 0)
			  ,HMonth12 =isnull(@Bucket12, 0)
			  ,HNextYear =isnull(@Bucket13, 0)

			  ,HTotal = Total
		where  ForecastDetailKey = @ForecastDetailKey 
		and    [Sequence] = @Sequence


	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
 */

 /*
 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

-- 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

			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 = 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 = @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

					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 

						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
*/ 

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]
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
|| 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
*/

/*
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 (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 (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 (39, NULL, N''AccountingFinancialReports'', N''Accounting Financial Reports'', N''Shows financial reports for accounting.'', NULL, 1, 1, 2, 4, 1, N''HTML2'', N''loadAccountingFinancialReports'', NULL, N''dashboards.widgets.today.accountingFinancialReports'', N''AccountingFinancialReports'')

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'')

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 (39, 3, 39)
INSERT [dbo].[tWidgetEntityAssigned] ([WidgetEntityAssignedKey], [WidgetEntityKey], [WidgetDefKey]) 
VALUES (40, 3, 40)
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].[vListing_Project]'
GO
IF OBJECT_ID(N'[dbo].[vListing_Project]', 'V') IS NOT NULL
EXEC sp_executesql N'














ALTER VIEW [dbo].[vListing_Project]
AS

  /*
  || When     Who Rel     What
  || 03/05/07 GHL 8.4     Added join with project rollup table to improve perfo           
  || 04/16/07 GHL 8.4     Added Actual Expense Net. Bug 8898       
  || 04/19/07 GHL 8.4     Corrected Get Markup From. Bug 8958    
  || 04/23/07 GWG 8.42    Added Parent Company on the client  
  || 04/27/07 CRG 8.5     Added Actual Project Total
  || 10/10/07 CRG 8.5     Added GLCompany, Class, and Office (OfficeID only, OfficeName was already there)     
  || 11/08/07 GHL 8.5     Synch''ed names with flash reports
  || 11/07/07 CRG 8.5     Added Client Billing Contact Email
  || 11/07/07 CRG 8.4.4.0 (15872) Added Service Rate Sheet
  || 11/20/07 GHL 8.5     Changed w/o Orders to wo Orders because this crashes the report engine
  || 11/28/07 GHL 8.5    (16797) Added Open Orders Gross + Net
  || 11/28/07 GHL 8.5    (16801) Added Last Task Due Date
  || 02/27/08 GHL 8.5    Added hint on index for CompanyKey
  || 10/16/08 GHL 10.011 (34827)(36763) Removed Orders from Total Costs
  || 11/17/08 GHL 10.013 (40529) Added Account Manager Active field
  || 03/17/09 RTC 10.5	  Removed user defined fields.
  || 08/25/09 GHL 10.508  (60402)Using now VoucherOutsideCostsGross in [Total Costs Gross wo Orders] rather than VoucherGross
  ||                      so that they are equal when orders prebilled = 0  
  || 08/25/09 GHL 10.508  (61462) Added roll.OpenOrderNet to [Total Costs Net]
  || 11/18/09 GWG 10.513  Added the custom field key from tCompany to include thier user defined fields.
  || 11/19/09 GWG 10.513  Added ISNULL(roll.AdvanceBilledOpen, 0) as [Amount Advance Billed Open]
  || 01/11/10 RLB 10.516  Added Billing Method (71832)
  || 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
  || 06/21/10 GHL 10.531 (83389) Modified [Total Gross Unbilled] to use OpenOrderUnbilled instead of OpenOrderGross
  ||                      Also removed OrderPrebilled from [Total Gross] because OpenOrderGross includes now prebilled orders
  || 08/15/10 GWG 10.533  Added task status and project perc comp for changes to the proto listing
  || 08/24/10 GWG 10.534  Added project color and plan start/complete as hidden fields
  || 11/15/10 GHL 10.538  (93504) Added OrderPrebilled to TotalGross
  || 02/08/11 RLB 10.541  (101805) Added Campaign Segment
  || 04/07/11 RLB 10.543 (108045) Removed Project Short Name
  || 04/22/11 RLB 10.543 (109178) Added Retainer Name
  || 07/27/11 RLB 10.546 (96614) Added Account Team
  || 09/08/11 GHL 10.548 Added Billed Amount wo Taxes
  || 09/21/11 RLB 10.548 (119193) Added Project Close Date to listing
  || 03/01/12 GHL 10.553 (135218) [Total Gross wo Orders] uses now VoucherOutsideCostsGross instead of VoucherGross
  || 03/07/12 GHL 10.554 (103259) Added [Opportunity Name]
  || 03/29/12 MFT 10.554 Added GLCompanyKey in order to map/restrict
  || 05/05/12 GWG 10.555 Added Requested By and Request Type
  || 08/17/12 RLB 10.559 (151960) Added Billing Group Code
  || 08/27/12 RLB 10.559 Added Schedule Status Color to match the ProjectTraffic View
  || 09/28/12 GHL 10.560 Getting now BillingGroupCode from tBillingGroup
  || 11/07/12 KMC 10.562 (158998) Added DoNotPostWIP
  || 12/14/12 WDF 10.563 (162624) Changed BillingMethod ''Fix Fee'' to ''Fixed Fee''
  || 08/02/13 GHL 10.570 (185610) Added individual expense Gross amounts
  || 10/07/13 GHL 10.573  Added Currency info
  || 10/16/13 GWG 10.573 Added the max work date from tTime (request from Integer)
  || 03/31/14 GHL 10.578 (186315) Added Open Orders Gross Unbilled for On deck request
  || 09/26/14 WDF 10.584 (Abelson Taylor) Added Billing Title and Billing Title Rate Sheet to GetRateFrom
  || 10/15/14 WDF 10.585 (Abelson Taylor) Added Title Rate Sheet
  || 10/15/14 WDF 10.586 (228961) Added FinancialStatusImage
  || 12/16/14 RLB 10.587 (239555) Added Flight Start and End Dates as well as Flight Interval from project setup accounting
  || 1/15/15  GWG 10.588 Added Item Rate Sheet
  || 1/26/15  GHL 10.588 Added Biling Group Description for Abelson Taylor
  || 01/27/15 WDF 10.588 (Abelson Taylor) Added Division and Product ID
  || 04/05/15 GWG 10.590 Added Earliest Task Start Date
  || 06/25/15 MCM 10.593 (261476) Adding Auto ID Task
  || 01/19/16 WDF 10.600 (285751) Added [Future Allocated Hours] taken from the Project Dashboard
  || 01/28/16 MCM 10.600 (274838) Added Billing Manager
  || 03/07/16 GWG 10.601 Added Misc Cost Net
  || 03/18/16 WDF 10.600 (293854) Added [Layout Name]
  || 04/05/16 WDF 10.603 (292564) Added [Client Open Tasks]
  || 05/12/16 WDF 10.604 (289238) Added [Client Sales Person]
  || 05/27/16 GHL 10.604 (295137) Added write off data for Abelson Taylor
  || 07/28/16 GAR 10.606 (308537) Add HasEstimate for project listing
  || 08/16/16 KMC 10.607 (308209) Added [Parent Division Name] from the company page (Client Setup...Billing).
  || 11/03/16 RLB 10.609 (319065) Added fields for this enhancement
  || 11/16/16 WDF 10.610 (318451) Added [Date Updated]
  || 01/04/17 GWG 10.611 Adding Source project number and name
  || 01/06/17 GHL 10.611 (326322) Added Vendor Invoice Net/Billed to compare with Project Budget Analysis
  || 01/10/17 GHL 10.612 (326322) Changed VoucherGross to VoucherOutsideCosts for Costs After WriteOff
  || 02/27/17 GWG 10.613 Added Allow anyone to charge time flag
  || 05/01/17 GHL 10.616 (343746) pull now billing manager from the project not the client
  || 06/02/17 GWG 10.616 Added Campaign start and end date
  || 07/17/17 MCM 10.617 (353717) Added campaign fields to the view
  || 07/17/17 GHL 10.619 (354660) Corrected Total Gross after WO (was missing labor WO)
  || 09/19/17 GHL 10.620 (337575) Added timestamps whenc changing status, next steps and client notes
  || 01/23/18 WDF 18.2.0 (382365) Added CustmFieldKey3 which was not added when applied to views.xml
  || 06/05/18 GAR 18.6.0 (404485) Addded FilesArchived field.
  || 06/12/18 GWG 18.7.0 Added allocated hours
  || 07/25/18 RLB 18.8.0 (401369) Added Project Hourly Rate
  || 08/29/18 MFT 18.9.0 (408947) Added Amount Received
  || 10/11/18 WDF 18.2.0 (418916) Added eqivalent of ''FinancialStatusImage'' but display the Color name (Red, Yellow, Green)
  || 10/30/18 GWG 18.9.2 Fix display of Auto ID Task
  || 11/12/18 MFT 10.9.3 (430344) added [Current Budget Labor Net]
  || 11/14/18 RLB 18.9.3 (426295) Added [Campaign Bill By]
  || 11/15/18 KMC 18.9.3 (431057) Changed the join on tProjectStatus to LEFT OUTER JOIN so Platinum templates would be included
  || 01/11/19 KMC 19.0.1 (439996) Rolling back the join to tProjectStatus above per Mike Wang
  || 01/28/19 GWG 19.2.0 Added Month started and completed for graphing
  || 02/14/19 GHL 19.300 (445252) Removed LATIN1_GENERAL_ CI_AS collation, this creates conflicts when comparing to other strings 
  || 03/21/19 RLS 19.0.4 (451384) Added [Campaign Active]
  || 04/18/19 RLS 19.5.0 (452745) added [Purchasing Markup Rate], [IO Commission Rate], [BO Commission Rate]
  || 06/06/19 RLB 19.070 (446229) Adding Project Manager
  || 09/16/19 GAR 19.100 (479426) Added campaign description
  || 09/23/19 GAR 19.100 (480171) Added Project Type Color
  || 10/07/19 AMP 19.1.1.0 (481102) Added ''Next Steps'' column to match UI, currently on report as ''Project Status Description''
  || 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
  || 11/14/19 GAR 19.1.2.0 (487738) Added Opportunity ID
  || 11/22/19 WDF 19.1.2.0 (489285) Modified [Future Allocated Hours] to be in sync with spRptProjectBudgetAnalysis
  || 12/11/19 CRG 19.2.0.0 (491800) Modified Service Rate Sheet to only show data if GetRateFrom = 5 (Service Rate Sheets)
  || 01/13/20 AMP 20.0.2.0 (488210) Added a new column to show the count of Billing Schedules
  || 02/03/20 GHL 20.0.2.0 (499882) Added Total Percentage Split
  || 06/29/20 RLS 20.0.2.0 (518686) Added [Revenue Source]
  || 07/09/20 GAR 20.0.8.0 (518830) Change Project Requested By field to grab the name based on the key instead of the text name
  || 08/17/20 GAR 20.0.9.0 (522505) Added [Retainer Active]
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 11/03/20 RLB 20.1.2.0 (535113) added opportunity outcome field
  || 12/17/20 RLS 21.0.1.0 (535729) Changed Project Description to nvarchar
  || 12/30/20 GHL 21.01.24.0 (541935) Added Split Billing column to display the % per client of split billing
  || 01/25/21 RLB 21.02.14 (544820) copied Project Total Gross field can Named it Campaign Total Gross because that is what it is
  || 02/16/21 GAR 21.03.14 (547160) Planning Project Number, Name, Full Name
  || 07/29/21 AMP 21.08.15 (565984) Added Client Account Manager
  || 07/30/21 GHL 21.08.15 (566322) Added Charge Code Percentage for LLNL
  || 10/07/21 AMP 21.11.14 (573781) Bug Fix for dispaly of Project Color    
  || 10/25/21 GWG 21.10.21 (574044) added specialized metrics for RNL
  || 10/26/21 WDF 21.11.14 (575361) Added [Has Spec Sheet]
  || 01/25/22 RLS 22.02.20 (583391) Added [First Task Start Date]
  || 02/21/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
  || 04/06/22 MFT 22.05.00 (594924) Fixed the calculation for Amount Received with CAST as float
  || 08/05/22 GAR 22.09.18 (607739) Added Campaign Segment Start Date and Due Date
  || 02/22/23 RLS 23.03.19 (631413) Added [Locked Schedule]
  || 05/01/23 RLS 23.08.20 (635501) Added [Expense Billed]
  || 07/27/23 AMP 23.08.20 (647190) Added [Project Status ID]
  || 09/08/23 AMP 23.10.15 (650819) Added [Open Amount of Adv Bill wo Tax] and [Amount Advance Billed wo Tax] logic same as vReport_Project
  || 05/09/24 GAR 24.06.16 (671523) Added OverrideScheduleOptions
  || 09/05/24 GAR 24.10.20 (682270) Added Avalara Tax Code and Description
  || 11/05/24 GAR 24.12.25 (686791) Added Expenses Are Not Included
  || 11/26/24 RLS 24.12.25 (685555) Added [Campaign Account Manager]
  || 12/31/24 RLS 25.01.19 (688590) Added ISNULL() to CurrencyID and join to tPreference
  || 01/07/25 CRG 25.02.16 (687612) Per Mike, modified the Billing Manager to only pull it from the project.  If it''s NULL on the project, do not default it from the client
  || 01/21/25 RLS 25.02.16 (687223) Added [Exclude from Resource Manager]
  || 03/04/25 KMC 25.04.20 (696096) Added Tax Address field for Avalara from a project
  || 10/01/25 RLS 25.10.19 (711191) Added [Project Account Manager Email] and [Campaign Account Manager Email]
  || 11/24/25 RLS 25.12.14 (712146) Added [Project Made Live Date]
  || 12/11/25 RLB 26.01.18 (717026) added [Hours Billed] from the rollup
  || 01/26/26 RLS 26.02.15 (718366) Added [Company Owner]
  || 02/24/26 RLS 26.03.15 (720029) Added [Require Comments on Time Entries]
  || 03/31/26 GAR 26.04.19 (723332) Added ProjectStatusColor
  || 05/18/26 RLS 26.06.14 (728860) Changed left outer join tActionLog ON tProject to outer apply to avoid dupes
 */

WITH BudgetWarning (EntityKey, Warning) AS
(
	Select EntityKey, Value
	  From tAppSession (nolock) 
	 Where Entity = ''company''
	  And GroupID = ''productionDash'' 
	  And SessionID = ''BudgetWarning''
),
	DefaultWarning (Warning) AS  
(	
	Select DefaultValue 
	  From tAppSetting (nolock) 
	 Where GroupID = ''productionDash'' 
	  And SessionID = ''BudgetWarning''
)

Select
	 p.CompanyKey
	,p.ProjectKey
	,p.ClientKey
	,p.BillingContact
	,p.ProjectNumber
	,p.ProjectName
	,p.CustomFieldKey
	,cl.CustomFieldKey as CustomFieldKey2
	,cam.CustomFieldKey as CustomFieldKey3
	,ISNULL(p.TaskStatus, 1) as ProjectTaskStatus
	,Case p.TaskStatus When 1 then ''Green'' When 2 then ''Yellow'' When 3 then ''Red'' else ''Green'' end as [Schedule Status Color]
    ,ISNULL(p.ProjectColor, ''#000000'') as ProjectColor --10/8/21-AMP-leaving this as a hidden field, not being used
	,ISNULL(p.ProjectColor, ''#000000'') as [Project Color] --10/8/21-AMP added this field, no reason it should be hidden 
	,p.StartDate
	,p.CompleteDate
	,ISNULL(p.PercComp, 0) as [Progress]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber as [Project Number]
	,Case p.AnyoneChargeTime When 1 then ''YES'' else ''NO'' end as [Allow Anyone to Charge Time]
	,cl.CustomerID as [Client ID]
	,cl.CustomerID + '' - '' + cl.CompanyName  as [Client ID and Name]
	,cl.CompanyName as [Client Name]	
	,LTRIM(RTRIM(ISNULL(clientam.FirstName + '' '','''')  + ISNULL(clientam.LastName,''''))) AS [Client Account Manager]
	,cl.Comments as [Client Comments]
	,cl.Fax as [Client Fax]
	,cl.Phone as [Client Phone]
	,cl.WebSite as [Client Website]
	,cl.DBA as [Client DBA]
	,cl.CVV as [Client Verification Code ]
	,Case cl.OneInvoicePer
		When 0 then ''Project''
		When 1 then ''Client''
		When 2 then ''Parent Client''
		When 3 then ''Division''
		When 4 then ''Product''
		When 5 then ''Campaign''
		end as [Client One Invoice Per]
	,pc.CompanyName as [Parent Company]
	,pcd.DivisionName as [Parent Division name]
	,p.ClientProjectNumber [Client Project Number]
	,LTRIM(RTRIM(ISNULL(bu.FirstName + '' '','''')  + ISNULL(bu.LastName,''''))) AS [Client Billing Contact]
	,bu.Email as [Client Billing Contact Email]
	,LTRIM(RTRIM(ISNULL(csp.FirstName + '' '','''')  + ISNULL(csp.LastName,''''))) AS [Client Sales Person]
	,Case p.BillingMethod
		When 1 then ''Time and Materials''
		When 2 then ''Fixed Fee''
		When 3 then ''Retainer''
		end as [Billing Method]
	,Case p.GetRateFrom 
        when 9 then ''Billing Title''
        when 10 then ''Billing Title Rate Sheet''
		When 1 then ''Client''
		When 2 then ''Project''
		When 3 then ''Project User''
		When 4 then ''Service''
		When 5 then ''Service Rate Sheet''
		When 6 then ''Task''
		end as [Get Labor Rate From]
	,Case p.GetMarkupFrom 
		When 1 then ''Client''
		When 2 then ''Project''
		When 3 then ''Item''
		When 4 then ''Item Rate Sheet''
		When 5 then ''Task''
		end as [Get Markup From]
	,Case p.Active When 1 then ''YES'' else ''NO'' end as [Active]
	,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
	,Case p.Closed When 1 then ''YES'' else ''NO'' end as [Closed Project]
	,ps.ProjectStatus as [Project Status]
	,ps.ProjectStatusID as [Project Status ID]
	,pbs.ProjectBillingStatus as [Project Billing Status]
	,pt.ProjectTypeName as [Project Type]
	,pt.ProjectTypeColor as [Project Type Color]
	,cd.DivisionName as [Client Division]
	,cd.DivisionID as [Client Division ID]
	,cpr.ProductName as [Client Product]
	,cpr.ProductID as [Client Product ID]
	,p.StatusNotes as [Project Status Note]
	,p.DetailedNotes as [Project Status Description]
	,p.DetailedNotes as [Next Steps]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project Due Date]
	,RIGHT(''0'' + CAST(DATEPART(Month, p.StartDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, p.StartDate) AS [Month Started]
	,RIGHT(''0'' + CAST(DATEPART(Month, p.CompleteDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, p.CompleteDate) AS [Month Completed]
	,p.CreatedDate as [Created Date]
	,p.DateUpdated as [Date Updated]
	,p.ProjectCloseDate as [Project Close Date]
	,p.StatusNotesUpdated as [Status Notes Updated]
	,p.DetailedNotesUpdated as [Next Steps Updated]
	,p.ClientNotesUpdated as [Client Notes Updated]
	,bg.BillingGroupCode as [Billing Group Code]
	,bg.Description as [Billing Group Description]
	,put.TeamName as [Account Team]
	,(SELECT MAX(t.PlanComplete) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as [Last Task Due Date]
	,(SELECT MIN(t.PlanStart) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as [First Task Start Date] 
	,(Select MIN(tTask.PlanStart) from tTask (nolock) Where tTask.ProjectKey = p.ProjectKey) as [Earliest Task Start Date]
	,CAST(p.Description AS NVARCHAR(4000)) as [Project Description]
	,LTRIM(RTRIM(ISNULL(cu.FirstName + '' '','''')  + ISNULL(cu.LastName,''''))) AS [Created By]
	,o.OfficeName as [Office]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager]
    ,Case am.Active When 1 then ''YES'' else ''NO'' end as [Account Manager Active]
	,LTRIM(RTRIM(ISNULL(upm.FirstName + '' '','''')  + ISNULL(upm.LastName,''''))) AS [Project Manager]
    ,Case upm.Active When 1 then ''YES'' else ''NO'' end as [Project Manager Active]
	,LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Key Person 1]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Key Person 2]
	,LTRIM(RTRIM(ISNULL(u3.FirstName + '' '','''')  + ISNULL(u3.LastName,''''))) AS [Key Person 3]
	,LTRIM(RTRIM(ISNULL(u4.FirstName + '' '','''')  + ISNULL(u4.LastName,''''))) AS [Key Person 4]
	,LTRIM(RTRIM(ISNULL(u5.FirstName + '' '','''')  + ISNULL(u5.LastName,''''))) AS [Key Person 5]
	,LTRIM(RTRIM(ISNULL(u6.FirstName + '' '','''')  + ISNULL(u6.LastName,''''))) AS [Key Person 6]
	,cam.CampaignName as [Campaign Name]
	,cam.CampaignID as [Campaign ID]
	,Case cam.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active]
	,cs.SegmentName as [Campaign Segment]
	,cs.PlanStart as [Campaign Segment Start Date]
	,cs.PlanComplete as [Campaign Segment Due Date]
	,cam.StartDate as [Campaign Start Date]
	,cam.EndDate as [Campaign End Date]
	,cas.Address1 as [Client Address 1]
	,cas.Address2 as [Client Address 2]
	,cas.Address3 as [Client Address 3]
	,cas.City as [Client City]
	,cas.Country as [Client Country]
	,cas.PostalCode as [Client Postal Code]
	,cas.State as [Client State]
	,cpt.TermsDescription as [Client Terms]
	,cct.CompanyTypeName as [Client Company Type]
	,pr.RequestID as [Project Request ID]
	,ISNULL(upr.UserName, pr.RequestedBy) as [Project Requested By]
	,prd.RequestName as [Project Request Type]
	,p.FlightStartDate as [Flight Start Date]
	,p.FlightEndDate as [Flight End Date]
	,Case When sp.ProjectNumber is null then sp.ProjectName else sp.ProjectNumber + '' - '' + sp.ProjectName end as [Source Project]
	,Case ISNULL(p.FlightInterval, 1) 
		When 1 then ''Daily''
		When 2 then ''Weekly''
		When 3 then ''Summary''
		else ''None''
		end as [Flight Interval]
	,rt.Title as [Retainer Name]
	,p.ClientNotes as [Client Notes]
	,p.ClientOpenTasks as [Client Open Tasks]
	,Case p.DoNotPostWIP WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Do Not Post WIP]
	,Case p.Template WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Template Project]
	,Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project]
	,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]
	-- Budgeted data
	,p.EstHours as [Original Budget Hours] -- [Estimate Hours]
	,p.EstLabor as  [Original Budget Labor Gross] -- [Estimate Labor]
	,p.BudgetLabor as [Original Budget Labor Net]
	,p.BudgetExpenses as [Original Budget Expense Net] -- [Estimate Expense Net]
	,p.EstExpenses as [Original Budget Expense Gross] -- [Estimate Expense Gross]
	,p.ApprovedCOHours as [CO Budget Hours] -- [Approved CO Hours]
	,p.ApprovedCOLabor as [CO Budget Labor Gross] -- [Approved CO Labor]
	,p.ApprovedCOBudgetLabor as [CO Budget Labor Net]
	,p.ApprovedCOBudgetExp as [CO Budget Expense Net]-- [Approved CO Expense Net]
	,p.ApprovedCOExpense as [CO Budget Expense Gross]-- [Approved CO Expense Gross]
	,p.EstHours + p.ApprovedCOHours as [Current Budget Hours] -- [Estimate Total Hours]
	,p.EstLabor + p.ApprovedCOLabor as [Current Budget Labor Gross] -- [Estimate Total Labor]
	,p.BudgetLabor + p.ApprovedCOBudgetLabor as [Current Budget Labor Net]
	,p.EstExpenses + p.ApprovedCOExpense as [Current Budget Expense Gross] --[Estimate Total Gross Expense]
	,p.BudgetExpenses + p.ApprovedCOBudgetExp as [Current Budget Expense Net] --[Estimate Total Net Expense]
	,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Current Total Budget wo Taxes] -- [Estimate Total]
	,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Current Total Budget] --New field
	,CASE 
		WHEN (p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense) = 0 THEN 1
		WHEN (ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherGross, 0) + ISNULL(roll.OpenOrderGross, 0) )  > 
				p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense THEN 3
		ELSE 1
		END AS FinancialStatusImage
	,CASE 
		WHEN (p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense) = 0 THEN ''GREEN''
		WHEN (ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherGross, 0) + ISNULL(roll.OpenOrderGross, 0) )  > 
				p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense THEN ''RED''
		WHEN (ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherGross, 0) + ISNULL(roll.OpenOrderGross, 0) ) / 
				(p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense) * 100 >= ISNULL(budg.Warning, (select Warning from DefaultWarning)) THEN ''YELLOW''
		ELSE ''GREEN''
		END AS [Financial Status]
	-- Actual data
	,ISNULL(roll.Hours, 0) as [Actual Hours]
	,ISNULL(roll.LaborGross, 0) as [Labor Gross] -- [Actual Labor]
	,ISNULL(roll.LaborNet, 0) as [Labor Net] --  [Actual Labor Cost]
	,ISNULL(roll.OpenOrderGross, 0) as [Open Orders Gross] 
	,ISNULL(roll.OpenOrderNet, 0) as [Open Orders Net] 
	,ISNULL(roll.OpenOrderUnbilled, 0) as [Open Orders Gross Unbilled]  
	,ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0) as [Total Costs Gross wo Orders] -- [Actual Billable Expense] 
    ,ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0) + ISNULL(roll.OrderPrebilled, 0)  as [Total Costs Gross] -- New field to match report
	,ISNULL(roll.MiscCostNet, 0) + ISNULL(roll.ExpReceiptNet, 0) + ISNULL(roll.VoucherNet, 0) as [Total Costs Net wo Orders] -- [Actual Net Expense]
	,ISNULL(roll.MiscCostNet, 0) + ISNULL(roll.ExpReceiptNet, 0) + ISNULL(roll.VoucherNet, 0) + ISNULL(roll.OpenOrderNet, 0) as [Total Costs Net] -- New field!!!
	,ISNULL(roll.LaborWriteOff, 0) + ISNULL(roll.MiscCostWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0) as [Transaction Writeoff Amount] -- No change, not in report
	,ISNULL(roll.BilledAmount, 0) as [Amount Billed]-- No change same as report
	,ISNULL(roll.BilledAmountNoTax, 0) as [Amount Billed wo Taxes]
	,ISNULL(roll.BilledAmountApproved, 0) as [Amount Billed Approved]
	,ISNULL(roll.AdvanceBilled, 0) as [Amount Advance Billed]-- No change same as report
	,ISNULL(roll.AdvanceBilledOpen, 0) as [Amount Advance Billed Open]
	,ISNULL(( 
		SELECT SUM(ISNULL(isum.Amount, 0) - ISNULL(i.AmountReceived, 0)  -- i.e. do not take isum.SalesTaxAmount 
				- ISNULL(i.WriteoffAmount, 0) - ISNULL(i.DiscountAmount, 0) ) 
		FROM (SELECT InvoiceKey, ProjectKey, SUM(Amount) as Amount from tInvoiceSummary (NOLOCK) WHERE ProjectKey = p.ProjectKey  group by InvoiceKey, ProjectKey)  as	isum 
		INNER JOIN tInvoice i (NOLOCK) ON isum.InvoiceKey = i.InvoiceKey 
		INNER JOIN	-- Starting Point: we need unique Adv Bill invoices with line for the project
					(SELECT isum.InvoiceKey
					, ISNULL(SUM(isum.Amount), 0) AS LineAmount -- might as well calc LineAmount here
					FROM  tInvoiceSummary isum (NOLOCK)
						INNER JOIN tInvoice i2 (NOLOCK) ON isum.InvoiceKey = i2.InvoiceKey 
					WHERE isum.ProjectKey =  p.ProjectKey
					AND   i2.AdvanceBill = 1
					GROUP BY isum.InvoiceKey 
					) AS inv ON i.InvoiceKey = inv.InvoiceKey
		WHERE i.AdvanceBill = 1 
		AND   isum.ProjectKey = p.ProjectKey 
	), 0) as [Open Amount of Adv Bill wo Tax] 
 	,ISNULL(( 
		SELECT SUM(isum.Amount) -- i.e. do not take isum.SalesTaxAmount 
		FROM tInvoiceSummary isum (NOLOCK)			 
		INNER JOIN tInvoice i (NOLOCK) ON isum.InvoiceKey = i.InvoiceKey 
		WHERE i.AdvanceBill = 1 
		AND   isum.ProjectKey = p.ProjectKey 
	), 0) as [Amount Advance Billed wo Tax] 
	,ISNULL(roll.LaborUnbilled, 0) + ISNULL(roll.MiscCostUnbilled, 0) + ISNULL(roll.ExpReceiptUnbilled, 0) + ISNULL(roll.VoucherUnbilled, 0) as [Total Gross Unbilled wo Orders] -- [Unbilled Total] 
	,ISNULL(roll.LaborUnbilled, 0) + ISNULL(roll.MiscCostUnbilled, 0) + ISNULL(roll.ExpReceiptUnbilled, 0) + ISNULL(roll.VoucherUnbilled, 0) + ISNULL(roll.OpenOrderUnbilled, 0) as [Total Gross Unbilled] -- New field

	,ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0) as [Total Gross wo Orders] --  [Actual Project Total]
	,ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0) + ISNULL(roll.OrderPrebilled, 0) + ISNULL(roll.OpenOrderUnbilled, 0) as [Total Gross]

	,ISNULL(roll.MiscCostGross, 0) as [Misc Cost Gross]
	,ISNULL(roll.MiscCostNet, 0) as [Misc Cost Net]
	,ISNULL(roll.ExpReceiptGross, 0) as [Expense Receipt Gross]
	,ISNULL(roll.VoucherGross, 0) as [Vendor Invoice Gross]
	,ISNULL(roll.VoucherNet, 0) as [Vendor Invoice Net]
	,ISNULL(roll.VoucherBilled, 0) as [Vendor Invoice Billed]
	,ROUND(ISNULL(ar.AmountReceived, 0), 2) AS [Amount Received]

	-- WriteOff data for Abelson Taylor
	,ISNULL(roll.MiscCostWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0) as [Expense Writeoff Amount] 
	,ISNULL(roll.LaborWriteOff, 0) as [Labor Writeoff Amount]  
	,ISNULL(roll.HoursWriteOff, 0) as [Hours Writeoff]
	,ISNULL(roll.HoursBilled, 0) as [Hours Billed]
	,ISNULL(roll.Hours, 0) - ISNULL(roll.HoursWriteOff, 0) as [Hours After Writeoff]
	,ISNULL(roll.LaborGross, 0) - ISNULL(roll.LaborWriteOff, 0) as [Labor Gross After Writeoff] 
	,ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0) 
		+ ISNULL(roll.OrderPrebilled, 0) + ISNULL(roll.OpenOrderUnbilled, 0)  -- Total Costs Gross w Orders
		- (ISNULL(roll.MiscCostWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0)) -- Expense Write Off
	as [Total Costs Gross After Writeoff w Open Orders]
	,ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0)   + ISNULL(roll.OrderPrebilled, 0) -- Total Costs Gross wo Orders
		- (ISNULL(roll.MiscCostWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0)) -- Expense Write Off
	as [Total Costs Gross After Writeoff wo Orders] 
	,ISNULL(roll.LaborGross, 0) + ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherOutsideCostsGross, 0) + ISNULL(roll.OrderPrebilled, 0) + ISNULL(roll.OpenOrderUnbilled, 0) 
		- (ISNULL(roll.LaborWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0)) -- Expense Write Off
	as [Total Gross After Writeoff]
	
	,(select Sum(tu.Hours) from	tTaskUser tu (NOLOCK) inner join tTask t (nolock) on tu.TaskKey = t.TaskKey Where t.ProjectKey = p.ProjectKey) As [Allocated Hours]
	,glc.GLCompanyKey
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,clGL.GLCompanyKey as [ClientGLCompanyKey]
	,clGL.GLCompanyID as [Default Client Company ID]
	,clGL.GLCompanyName as [Default Client Company Name]
	,cla.ClassID as [Class ID]
	,cla.ClassName as [Class Name]
	,o.OfficeID as [Office ID]
	,CASE p.GetRateFrom
		WHEN 5 THEN	trs.RateSheetName 
		ELSE NULL
	END	as [Service Rate Sheet]
	,tirs.RateSheetName as [Title Rate Sheet]
	,irs.RateSheetName as [Item Rate Sheet]
	,Case p.GetRateFrom When 2 then p.HourlyRate else 0 end as [Project Hourly Rate]
	,l.LeadID as [Opportunity ID]
	,l.Subject as [Opportunity Name]
	,loc.Outcome as [Opportunity Outcome]
	,ISNULL(p.CurrencyID, pref.CurrencyID) as [Currency]
	,(Select Max(WorkDate) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) as [Date of Last Time Entry]
	,Case When p.AutoIDTask = 1 then ''YES'' else ''NO'' end as [Auto ID Task]
 	,(Select ISNULL(SUM(tu.Hours), 0) from vTaskUserHour tu (nolock) where tu.ProjectKey = p.ProjectKey and tu.BucketStart > DATEADD(week, -1, CONVERT(SMALLDATETIME, (CONVERT(VARCHAR(10), GETDATE(), 101)), 101))) as [Future Allocated Hours]
	,LTRIM(RTRIM(ISNULL(bm.FirstName + '' '','''')  + ISNULL(bm.LastName,''''))) as [Billing Manager Name]
	,lo.LayoutName as [Layout Name]
	,CASE WHEN (SELECT COUNT(*) FROM tEstimate (nolock) WHERE ProjectKey = p.ProjectKey) > 0 THEN ''YES'' ELSE ''NO'' END AS [Has Estimate]  
 	,CASE WHEN (SELECT COUNT(*) FROM tSpecSheet (nolock) WHERE Entity = ''Project'' and EntityKey = p.ProjectKey) > 0 THEN ''YES'' ELSE ''NO'' END AS [Has Spec Sheet]   

	-- campaign summary 
	,vcs.BudgetHours as [Campaign Budget Hours] 
	,vcs.BudgetLabor as [Campaign Budget Labor] 
	,vcs.BudgetExpenseNet as [Campaign Budget Expense Net] 
	,vcs.BudgetExpenseGross as [Campaign Budget Expense Gross] 
	,vcs.ActualExpenseNet as [Campaign Actual Expense Net] 
	,vcs.ActualExpenseGross as [Campaign Actual Expense Gross] 
	,vcs.OpenOrdersNet as [Campaign Open Orders Net] 
	,vcs.OpenOrdersGross as [Campaign Open Orders Gross] 
	
	,vcs.CampaignCurrentTotalBudget as [Campaign Current Total Budget]
	,vcs.CampaignAmountBilled as [Campaign Amount Billed]
	,vcs.ProjectCurrentTotalBudgetContWithTax as [Project CurrentTotal Budget Cont With Tax]
	,vcs.ProjectCurrentTotalBudget as [Project Current Total Budget]
	,vcs.ProjectTotalGross as [Project Total Gross]
	,vcs.ProjectTotalGross as [Campaign Total Gross]
	,vcs.ProjectAmountBilled as [Project Amount Billed]
	,Substring((Select '', ''+ UserName  AS [text()]   
            From vUserName un (nolock)
            inner join tAssignment a (nolock) on a.UserKey = un.UserKey
			Where p.ProjectKey = a.ProjectKey
            ORDER BY un.UserName
            For XML PATH ('''')
        ), 2, 4000) as [Project Team]
	,Case ISNULL(p.FilesArchived, 0) WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Files Archived]
	,Case ISNULL(p.CampaignKey, 0)
		WHEN 0 THEN ''''
		ELSE case cam.BillBy
				when 1 then ''Project''
				when 2 then ''Campaign''
			 else ''''
			 end
	END as [Campaign Bill By]
	,p.ItemMarkup as [Purchasing Markup Rate]
	,p.IOCommission as [IO Commission Rate]
	,p.BCCommission as [BO Commission Rate]
	,cam.Description as [Campaign Description]
	,(Select count(*) from tBillingSchedule (nolock) Where tBillingSchedule.ProjectKey = p.ProjectKey) as [Billing Schedule Count]

	,splits.TotalPercentageSplit as [Total Percentage Split]
	,CASE 
			WHEN ISNULL(p.GLCompanySource,0) = 0 THEN ''Project'' 
			WHEN ISNULL(p.GLCompanySource,0) = 1 THEN ''Person'' 
			ELSE ''Project''
		END AS [Revenue Source]
	,Case when ISNULL(p.ScheduleLockedByKey, 0) > 1 then ''YES'' else ''NO'' end as [Locked Schedule]
           /*
             ,(Select ISNULL(Sum(ActualHours), 0) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) as [Actual Hours]
	,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) as [Actual Labor]
	,(Select ISNULL(Sum(ROUND(ActualHours * CostRate, 2)), 0) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) as [Actual Labor Cost]
	,(Select ISNULL(Sum(BillableCost), 0) from tMiscCost (nolock) Where tMiscCost.ProjectKey = p.ProjectKey) + 
	 (Select ISNULL(Sum(BillableCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ProjectKey = p.ProjectKey) + 
	 (Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ProjectKey = p.ProjectKey) as [Actual Billable Expense]
	,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey and WriteOff = 1) +
	 (Select ISNULL(Sum(BillableCost), 0) from tMiscCost (nolock) Where tMiscCost.ProjectKey = p.ProjectKey and WriteOff = 1) + 
	 (Select ISNULL(Sum(BillableCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ProjectKey = p.ProjectKey and WriteOff = 1) + 
	 (Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ProjectKey = p.ProjectKey and WriteOff = 1) as [Transaction Writeoff Amount]
	,(Select ISNULL(Sum(TotalAmount), 0) from tInvoiceLine (nolock) inner join tInvoice (nolock) on tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey Where tInvoice.AdvanceBill = 0 and tInvoiceLine.ProjectKey = p.ProjectKey) as [Amount Billed]
	,(Select ISNULL(Sum(TotalAmount), 0) from tInvoiceLine (nolock) inner join tInvoice (nolock) on tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey Where tInvoice.AdvanceBill = 1 and tInvoiceLine.ProjectKey = p.ProjectKey) as [Amount Advance Billed]
	,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) 
	  Where tTime.ProjectKey = p.ProjectKey and DateBilled is null) +
	 (Select ISNULL(Sum(BillableCost), 0) from tMiscCost (nolock) Where tMiscCost.ProjectKey = p.ProjectKey and DateBilled is null) + 
	 (Select ISNULL(Sum(BillableCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ProjectKey = p.ProjectKey and DateBilled is null) + 
	 (Select ISNULL(Sum(BillableCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ProjectKey = p.ProjectKey and DateBilled is null) as [Unbilled Total]
             */
	,CASE
		WHEN p.RetainerKey = NULL THEN ''N/A''
		WHEN p.RetainerKey IS NOT NULL AND ISNULL(rt.Active,0) = 1 THEN ''YES''
		WHEN p.RetainerKey IS NOT NULL AND ISNULL(rt.Active,0) = 0 THEN ''NO''
		ELSE ''N/A''
	END AS [Retainer Active]
	
	, Substring(
	(
		select '', '' + cl2.CustomerID  + '': '' + cast(cast(splitbill.PercentageSplit as decimal(24,2)) as varchar) + ''%''  AS [text()]
					FROM tProjectSplitBilling splitbill (nolock)
						inner join tCompany cl2 (nolock) on splitbill.ClientKey = cl2.CompanyKey
					WHERE splitbill.ProjectKey = p.ProjectKey
					ORDER BY cl2.CustomerID
					FOR XML PATH ('''')
	 ), 2, 5000) as [Split Billing]

	,isnull((
		select sum(cbcp.Percentage)
		from tCBCodePercent cbcp (nolock)
		where cbcp.Entity = ''tProject'' and cbcp.EntityKey = p.ProjectKey
	 ),0) as [Charge Code Total Percentage]
	 ,roll.ScheduleAdherance as [Schedule Adherance]
	 ,roll.EffortVariance as [Effort Variance]
	 ,roll.ProjectPerformance as [Project Performance]
	,roll.MiscCostBilled + roll.ExpReceiptBilled + roll.VoucherBilled + roll.OrderPrebilled as [Expense Billed]
	,Case p.OverrideScheduleOptions When 1 then ''YES'' else ''NO'' end as [Override Company Schedule Options]
	,atc.AvalaraTaxCode as [Avalara Tax Code]
	,atc.Description as [Avalara Tax Code Description]
	,case p.ExpensesNotIncluded when 1 then ''YES'' else ''NO'' end as [Expenses Are Not Included]
	,campam.UserName as [Campaign Account Manager]
	,Case ISNULL(p.ExcludeFromRM, 0) WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Exclude from Resource Manager]
	,paddr.AddressName as [Tax Address]
	,am.Email as [Project Account Manager Email]
	,campam.Email as [Campaign Account Manager Email]
	,al.ActionDate as [Project Made Live Date]
	,con.UserName as [Company Owner]
	,Case cl.RequireCommentsOnTime When 1 then ''YES'' else ''NO'' end as [Require Comments on Time Entries]
	,ps.ProjectStatusColor as [Project Status Color]
From
	tProject p with  (index=IX_tProject, nolock)
	inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	left outer join BudgetWarning budg (nolock) on p.CompanyKey = budg.EntityKey
	left outer join tCompany pc (nolock) on cl.ParentCompanyKey = pc.CompanyKey
	left outer join tClientDivision pcd (nolock) on cl.ParentCompanyDivisionKey = pcd.ClientDivisionKey
	left outer join tCampaign cam (nolock) on p.CampaignKey = cam.CampaignKey
	left outer join vUserName campam (nolock) on cam.AEKey = campam.UserKey
	left outer join tUser bu (nolock) on p.BillingContact = bu.UserKey
	left outer join tUser cu (nolock) on p.CreatedByKey = cu.UserKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
	left outer join tClientProduct cpr (nolock) on p.ClientProductKey = cpr.ClientProductKey
	left outer join tOffice o (nolock) on p.OfficeKey = o.OfficeKey
	left outer join tUser am (nolock) on p.AccountManager = am.UserKey
	left outer join tUser upm (nolock) on p.ProjectManager = upm.UserKey
	left outer join tUser csp (nolock) on cl.SalesPersonKey = csp.UserKey
	left outer join tUser clientam (nolock) on cl.AccountManagerKey = clientam.UserKey
	left outer join tUser u1 (nolock) on p.KeyPeople1 = u1.UserKey
	left outer join tUser u2 (nolock) on p.KeyPeople2 = u2.UserKey
	left outer join tUser u3 (nolock) on p.KeyPeople3 = u3.UserKey
	left outer join tUser u4 (nolock) on p.KeyPeople4 = u4.UserKey
	left outer join tUser u5 (nolock) on p.KeyPeople5 = u5.UserKey
	left outer join tUser u6 (nolock) on p.KeyPeople6 = u6.UserKey
	left outer join tRequest pr (nolock) on pr.RequestKey = p.RequestKey
	left outer join vUserName upr (nolock) on pr.RequestedByKey = upr.UserKey
	left outer join tRequestDef prd (nolock) on pr.RequestDefKey = prd.RequestDefKey
	left outer join tProjectRollup roll (nolock) on p.ProjectKey = roll.ProjectKey
	left outer join tClass cla (nolock) on p.ClassKey = cla.ClassKey
	left outer join tGLCompany glc (nolock) on p.GLCompanyKey = glc.GLCompanyKey
	left outer join tGLCompany clGL (nolock) on cl.GLCompanyKey = clGL.GLCompanyKey
	left outer join tTimeRateSheet trs (nolock) on p.TimeRateSheetKey = trs.TimeRateSheetKey
	left outer join tTitleRateSheet tirs (nolock) on p.TitleRateSheetKey = tirs.TitleRateSheetKey
	left outer join tItemRateSheet irs (nolock) on p.ItemRateSheetKey = irs.ItemRateSheetKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey
	left outer join tRetainer rt (nolock) on p.RetainerKey = rt.RetainerKey
	left outer join tTeam put (nolock) on p.TeamKey = put.TeamKey
	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 tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	left outer join tUser bm (nolock) on p.BillingManagerKey = bm.UserKey
	left outer join tUser bmc (nolock) on cl.BillingManagerKey = bmc.UserKey
	left outer join tLayout lo (nolock) on p.LayoutKey = lo.LayoutKey
	left outer join tAddress cas (nolock) on cl.DefaultAddressKey = cas.AddressKey
	left outer join tPaymentTerms cpt (nolock) on cl.PaymentTermsKey = cpt.PaymentTermsKey
	left outer join tCompanyType  cct (nolock) on cl.CompanyTypeKey = cct.CompanyTypeKey
	left outer join tProject sp (nolock) on p.SourceProjectKey = sp.ProjectKey
	left outer join vCampaignSummary vcs (nolock) on p.CampaignKey = vcs.CampaignKey
	left outer join tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey
	left outer join (
		SELECT ProjectKey, SUM(AmountReceived) AS AmountReceived
		FROM (
			-- need to have a line per invoice project check app
			SELECT
				i.InvoiceKey, i.InvoiceNumber, ins.ProjectKey, ca.Amount, i.InvoiceTotalAmount, ins.InvoiceProjectAmount,
				CASE i.InvoiceTotalAmount WHEN 0 THEN 0 ELSE ca.Amount * (CAST(ins.InvoiceProjectAmount AS float) / CAST(i.InvoiceTotalAmount AS float)) END AS AmountReceived
			FROM
				tCheckAppl ca (nolock)
				INNER JOIN tInvoice i (nolock) ON ca.InvoiceKey = i.InvoiceKey
				INNER JOIN (
					-- this is the root table to get to the project
					SELECT
						ins.InvoiceKey, ins.ProjectKey,
						SUM(ins.Amount) + SUM(ins.SalesTaxAmount) AS InvoiceProjectAmount
					FROM
						tInvoiceSummary ins (nolock)
					WHERE ins.ProjectKey IS NOT NULL
					GROUP BY ins.InvoiceKey, ins.ProjectKey -- 1 line per invoice and project
				) ins ON ca.InvoiceKey = ins.InvoiceKey
			) AS receipts 
			GROUP BY ProjectKey
		) AS ar ON p.ProjectKey = ar.ProjectKey

		left outer join (
			select sum(PercentageSplit) as TotalPercentageSplit
			,ProjectKey	
			from   tProjectSplitBilling (nolock)
			group by ProjectKey
			) as splits on p.ProjectKey = splits.ProjectKey
	left outer join tAvalaraTaxCode atc (NOLOCK) ON p.AvalaraTaxCodeKey = atc.AvalaraTaxCodeKey
	left outer join tPreference pref (nolock) on p.CompanyKey = pref.CompanyKey
	left outer join tProjectAddress pa (nolock) on p.ProjectKey = pa.ProjectKey
	left outer join tAddress paddr (nolock) on pa.AddressKey = paddr.AddressKey
	outer apply (
    select top 1 al.ActionDate
    from tActionLog al (nolock)
    where al.Entity = ''Project''
      and al.EntityKey = p.ProjectKey
      and al.Action = ''Project Made Live''
    order by al.ActionDate desc
) al
	LEFT OUTER JOIN vUserName con (nolock) on cl.ContactOwnerKey = con.UserKey
'
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
*/ 
	
	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
	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].[vReport_TaskAssignmentDetailWOrig]'
GO
IF OBJECT_ID(N'[dbo].[vReport_TaskAssignmentDetailWOrig]', 'V') IS NOT NULL
EXEC sp_executesql N'

ALTER VIEW [dbo].[vReport_TaskAssignmentDetailWOrig]  
AS  
  
/*  
|| When     Who Rel      What  
|| 01/20/26 CRG 26.02.15 Created as a copy of vReport_TaskAssignmentDetail, but also including fields from tTaskUserHourOrig
|| 05/05/26 CRG 26.06.14 (727946) Removed restriction that limited it to just detail tasks
*/   
  
Select  
  p.CompanyKey  
 ,p.GLCompanyKey  
 ,p.CustomFieldKey  
 ,u.CustomFieldKey as CustomFieldKey2  
 ,p.ProjectName as [Project Name]  
 ,p.ProjectNumber as [Project Number]  
 ,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]  
 ,cl.CompanyName as [Client Name]  
 ,cl.CustomerID as [Client ID]  
 ,p.ClientProjectNumber [Client Project Number]  
 ,ps.ProjectStatus as [Project Status]  
 ,pbs.ProjectBillingStatus as [Project Billing Status]  
 ,pt.ProjectTypeName as [Project Type]  
 ,pt.ProjectTypeColor as [Project Type Color]  
 ,p.StatusNotes as [Project Status Note]  
 ,p.DetailedNotes as [Project Status Description]  
 ,p.ProjectCloseDate as [Project Close Date]  
 ,Case p.Active When 1 then ''YES'' else ''NO'' end as [Active]  
 ,p.StartDate as [Project Start Date]  
 ,p.CompleteDate as [Project Due Date]  
  
 ,Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project]  
 ,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]  
 ,cp.CampaignName as [Campaign Name]  
 ,cp.CampaignID as [Campaign ID]  
 ,cs.SegmentName as [Campaign Segment]  
 ,cs.PlanStart as [Campaign Segment Start Date]  
 ,cs.PlanComplete as [Campaign Segment Due Date]  
 ,o.OfficeName as [Office]  
 ,o.OfficeColor as [Office Color]  
 ,t.TaskID as [Task ID]  
 ,t.TaskName as [Task Name]  
 ,t.Description as [Task Description]  
 ,tat.TaskAssignmentType as [Task Type]  
 ,Case ISNULL(t.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable]  
 ,Case ISNULL(t.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable 2]  
 ,t.PlanStart as [Plan Start Date]  
 ,t.PlanComplete as [Plan Completion Date]  
 ,t.ActStart as [Actual Start Date]  
 ,t.ActComplete as [Actual Completion Date]  
 ,t.PercComp as [Percentage Complete]  
 ,t.BaseStart as [Baseline Start Date]  
 ,t.BaseComplete as [Baseline Completion Date]  
 ,Case t.MoneyTask When 1 then ''YES'' else ''NO'' end as [Track Budgets]  
 ,Case t.ScheduleTask When 1 then ''YES'' else ''NO'' end as [Track Schedules]  
 ,t.EstHours as [Original Budget Hours]  
 ,t.EstLabor as [Original Budget Labor]  
 ,t.BudgetExpenses as [Original Budget Net Expense]  
 ,t.EstExpenses as [Original Budget Gross Expense]  
 ,t.ApprovedCOHours as [Approved Change Order Hours]  
 ,t.ApprovedCOLabor as [Approved Change Order Labor]  
 ,t.ApprovedCOExpense as [Approved Change Order Gross Expense]  
 ,Case t.PredecessorsComplete When 1 then ''YES'' else ''NO'' end as [Predecessors Completed]  
 ,Case t.ExcludeFromStatus When 1 then ''YES'' else ''NO'' end as [Exclude From Status]  
 ,ISNULL(lt.ActualTaskLaborTotal, 0) as [Actual Task Labor Total]  
 ,ISNULL(lt.ActualTaskLaborHours, 0) as [Actual Task Labor Hours]  
 ,ISNULL(alt.ActualTaskAssignmentLaborTotal, 0) as [Actual Task Assignment Labor Total]  
 ,ISNULL(alt.ActualTaskAssignmentLaborHours, 0) as [Actual Task Assignment Labor Hours]  
 ,ISNULL((Select Sum(ActualHours) from tTime (nolock) Where ISNULL(tTime.DetailTaskKey, tTime.TaskKey) = t.TaskKey and tTime.UserKey = tu.UserKey AND tTime.WorkDate BETWEEN bucket.BucketStart AND DATEADD(DAY, 6, bucket.BucketStart)), 0) as [Actual Task Assignment Week Labor Hours]  
 ,u.UserName AS [Assigned User]  
 ,taun.Description [Default Service]  
 ,taun.Title [Title]  
 ,glc.GLCompanyID AS [Default GLCompany ID]  
 ,glc.GLCompanyID + '' - '' + glc.GLCompanyName AS [Default GLCompany Full Name]  
 ,ISNULL(d.DepartmentName, sd.DepartmentName) as [User Department]  
 ,ISNULL(d.DepartmentColor, sd.DepartmentColor) as [User Department Color]  
 ,Case ISNULL(t.HideFromClient, 0) When 1 then ''YES'' else ''NO'' end as [Hide From Client]  
 ,t.TaskName as [Assignment Subject]  
 ,t.DueBy as [Due By]  
 ,CAST(t.Description as varchar(4000)) as [Description of Work]  
 ,tu.ActStart as [Assignment Actual Start Date]  
 ,tu.ActComplete as [Assignment Actual Completion Date]  
 ,ISNULL(tu.APlanStart, t.PlanStart) as [Assignment Plan Start Date]  
 ,ISNULL(tu.APlanComplete, t.PlanComplete) as [Assignment Plan Completion Date]  
 ,t.PlanDuration as [Assignment Duration]  
 ,t.DisplayOrder as [Assignment Work Order]  
 ,t.AssignedNames as [All Assigned People]  
 ,tu.PercComp as [Assignment Percentage Complete]  
 ,se.ServiceCode as [Service Code]
 ,se.Description as [Role]  
 ,se.Description as [Service]  
 ,se.ServiceColor as [Service Color]  
 ,wt.WorkTypeID as [Billing Item Code]
 ,wt.WorkTypeName as [Billing Item Name]
 ,t.Comments as [Assignment Comments]  
 ,t.UserChangedDate as [Date Task Assigned]  
 ,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Account Manager]  
 ,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]  
 ,tu.CompletedByDate as [Time Completed]  
 ,tu.Hours as [Allocated Hours]  
 ,LTRIM(RTRIM(ISNULL(tsu.FirstName + '' '','''')  + ISNULL(tsu.LastName,''''))) AS [Time Completed By]  
 ,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Billing Contact]  
 ,u3.UserName as [Key People 1]  
 ,u4.UserName as [Key People 2]  
 ,u5.UserName as [Key People 3]  
 ,u6.UserName as [Key People 4]  
 ,u7.UserName as [Key People 5]  
 ,u8.UserName as [Key People 6]  
 ,glcp.GLCompanyID as [Company ID]  
 ,glcp.GLCompanyName as [Company Name]  
 ,cla.ClassID as [Class ID]  
 ,cla.ClassName as [Class Name]  
 ,t.ProjectOrder as Row  
 ,CASE t.ScheduleTask  
  WHEN 1 THEN t.PlanDuration  
  ELSE NULL  
 END AS [Task Days]  
 ,tp.PriorityName AS [Task Priority]  
 ,st.TaskID as [Summary Task ID]  
 ,st.TaskName as [Summary Task Name]  
 ,Case ISNULL(st.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Summary Taxable]  
 ,Case ISNULL(st.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Summary Taxable 2]  
 ,p.ProjectKey
 ,t.TaskKey
 ,cd.DivisionID as [Client Division ID]  
    ,cd.DivisionName as [Client Division]  
    ,pc.ProductID as [Client Product ID]  
    ,pc.ProductName as [Client Product]  
 ,ts.SegmentName as [Timeline Segment]  
 ,ts.SegmentColor as [Timeline Segment Color]  
 ,team.TeamName as [Team Name]  
  
 ,Case When tu.ManualAdjustment = 1 then ''Manually Adjusted'' else ''Automatically Adjusted'' end as [Adjustment Type]  
 ,tuh.Hours AS [Week Hours]  
 ,tuho.Hours AS [Orig Week Hours]
 ,tuho.WeekStartHours AS [Week Start Hours]
 ,CASE  
  WHEN bucket.BucketStart < DATEADD(DAY, -6, GETDATE()) THEN 0 --If it''s a previous bucket, show 0 so that the numbers are not double dipped with the Actual Hours from the previous weeks  
  ELSE tuh.Hours  
 END AS [Week Hours Current And Future]  
 ,bucket.BucketStart as [Week Start Date]  
 ,ISNULL(tuh.AHourlyRate, 0) [Week Rate]  
 ,ISNULL(tuh.AHourlyRate, 0) * tuh.Hours as [Week Gross]  
 ,ISNULL(u.HourlyCost, 0) * tuh.Hours as [Week Net]  
 ,YEAR(bucket.BucketStart) as [Year]  
 ,Case When MONTH(bucket.BucketStart) = 1 then tuh.Hours else 0 end as [January Hours]  
 ,Case When MONTH(bucket.BucketStart) = 2 then tuh.Hours else 0 end as [February Hours]  
 ,Case When MONTH(bucket.BucketStart) = 3 then tuh.Hours else 0 end as [March Hours]  
 ,Case When MONTH(bucket.BucketStart) = 4 then tuh.Hours else 0 end as [April Hours]  
 ,Case When MONTH(bucket.BucketStart) = 5 then tuh.Hours else 0 end as [May Hours]  
 ,Case When MONTH(bucket.BucketStart) = 6 then tuh.Hours else 0 end as [June Hours]  
 ,Case When MONTH(bucket.BucketStart) = 7 then tuh.Hours else 0 end as [July Hours]  
 ,Case When MONTH(bucket.BucketStart) = 8 then tuh.Hours else 0 end as [August Hours]  
 ,Case When MONTH(bucket.BucketStart) = 9 then tuh.Hours else 0 end as [September Hours]  
 ,Case When MONTH(bucket.BucketStart) = 10 then tuh.Hours else 0 end as [October Hours]  
 ,Case When MONTH(bucket.BucketStart) = 11 then tuh.Hours else 0 end as [November Hours]  
 ,Case When MONTH(bucket.BucketStart) = 12 then tuh.Hours else 0 end as [December Hours]  

 ,Case When MONTH(bucket.BucketStart) = 1 then tuho.Hours else 0 end as [Orig January Hours]  
 ,Case When MONTH(bucket.BucketStart) = 2 then tuho.Hours else 0 end as [Orig February Hours]  
 ,Case When MONTH(bucket.BucketStart) = 3 then tuho.Hours else 0 end as [Orig March Hours]  
 ,Case When MONTH(bucket.BucketStart) = 4 then tuho.Hours else 0 end as [Orig April Hours]  
 ,Case When MONTH(bucket.BucketStart) = 5 then tuho.Hours else 0 end as [Orig May Hours]  
 ,Case When MONTH(bucket.BucketStart) = 6 then tuho.Hours else 0 end as [Orig June Hours]  
 ,Case When MONTH(bucket.BucketStart) = 7 then tuho.Hours else 0 end as [Orig July Hours]  
 ,Case When MONTH(bucket.BucketStart) = 8 then tuho.Hours else 0 end as [Orig August Hours]  
 ,Case When MONTH(bucket.BucketStart) = 9 then tuho.Hours else 0 end as [Orig September Hours]  
 ,Case When MONTH(bucket.BucketStart) = 10 then tuho.Hours else 0 end as [Orig October Hours]  
 ,Case When MONTH(bucket.BucketStart) = 11 then tuho.Hours else 0 end as [Orig November Hours]  
 ,Case When MONTH(bucket.BucketStart) = 12 then tuho.Hours else 0 end as [Orig December Hours]

 ,Case When MONTH(bucket.BucketStart) = 1 then tuho.WeekStartHours else 0 end as [Week Start January Hours]  
 ,Case When MONTH(bucket.BucketStart) = 2 then tuho.WeekStartHours else 0 end as [Week Start February Hours]  
 ,Case When MONTH(bucket.BucketStart) = 3 then tuho.WeekStartHours else 0 end as [Week Start March Hours]  
 ,Case When MONTH(bucket.BucketStart) = 4 then tuho.WeekStartHours else 0 end as [Week Start April Hours]  
 ,Case When MONTH(bucket.BucketStart) = 5 then tuho.WeekStartHours else 0 end as [Week Start May Hours]  
 ,Case When MONTH(bucket.BucketStart) = 6 then tuho.WeekStartHours else 0 end as [Week Start June Hours]  
 ,Case When MONTH(bucket.BucketStart) = 7 then tuho.WeekStartHours else 0 end as [Week Start July Hours]  
 ,Case When MONTH(bucket.BucketStart) = 8 then tuho.WeekStartHours else 0 end as [Week Start August Hours]  
 ,Case When MONTH(bucket.BucketStart) = 9 then tuho.WeekStartHours else 0 end as [Week Start September Hours]  
 ,Case When MONTH(bucket.BucketStart) = 10 then tuho.WeekStartHours else 0 end as [Week Start October Hours]  
 ,Case When MONTH(bucket.BucketStart) = 11 then tuho.WeekStartHours else 0 end as [Week Start November Hours]  
 ,Case When MONTH(bucket.BucketStart) = 12 then tuho.WeekStartHours else 0 end as [Week Start December Hours]

 ,Case t.TaskConstraint  
  When 0 then case when p.ScheduleDirection = 1 then ''As Soon As Possible'' else ''As Late as Possible'' end  
  When 1 then ''Must Start On''  
  When 2 then ''Must Finish On''  
  When 3 then ''Finish No Earlier Than''  
  When 4 then ''Finish No Later Than''  
  When 5 then ''Start No Earlier Than''  
  When 6 then ''Start No Later Than''  
  When 7 then ''Duration of Project''  
  else ''''  
 end as [Constraint]  
 ,msvn.UserName as [My Supervisor]  
 ,p.ClientNotes as [Project Client Notes]  
 ,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')  
  FROM  
   tTaskPredecessor tpi (nolock)  
   INNER JOIN tTask ti (nolock) ON tpi.PredecessorKey = ti.TaskKey  
  WHERE tpi.TaskKey = t.TaskKey  
  ORDER BY ti.TaskID  
     FOR XML PATH('''')) ,1,1,''''))), '''') AS [Predecessor]  
 ,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')  
  FROM  
   tTaskPredecessor tpi (nolock)  
   INNER JOIN tTask ti (nolock) ON tpi.TaskKey = ti.TaskKey  
  WHERE tpi.PredecessorKey = t.TaskKey  
  ORDER BY ti.TaskID  
     FOR XML PATH('''')) ,1,1,''''))), '''') AS [Successor]  
 ,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(tut.TeamName, '''')  
  FROM  
   tTeamUser tutu (nolock)  
   INNER JOIN tTeam tut (nolock) ON tutu.TeamKey = tut.TeamKey  
  WHERE tutu.UserKey = tu.UserKey  
  ORDER BY tut.TeamName  
     FOR XML PATH('''')) ,1,1,''''))), '''') AS [Team Names]  
 ,p.PercComp as [Project Percent Complete]  
 ,t.ProjectOrder as [Task Line Number]  
 ,Case tu.ManualAdjustment When 1 then ''YES'' else ''NO'' end as [Manually Adjusted Buckets]  
 ,tu.TaskUserKey
 ,tu.UserKey AS EmployeeKey -- keeps api consistent 
 ,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
 ,ISNULL(CASE p.GetRateFrom
		WHEN 2 THEN p.HourlyRate 
		WHEN 3 THEN u.HourlyRate
		WHEN 4 THEN 
			(SELECT 
					CASE
						WHEN u.RateLevel = 1
							THEN se.HourlyRate1
						WHEN u.RateLevel = 2
							THEN ISNULL(se.HourlyRate2,se.HourlyRate1)
						WHEN u.RateLevel = 3
							THEN ISNULL(se.HourlyRate3,se.HourlyRate1)
						WHEN u.RateLevel = 4
							THEN ISNULL(se.HourlyRate4,se.HourlyRate1)
						WHEN u.RateLevel = 5
							THEN ISNULL(se.HourlyRate5,se.HourlyRate1)
					END)
		WHEN 5 THEN 
			(SELECT 
					CASE
						WHEN u.RateLevel = 1
							THEN (SELECT HourlyRate1 FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 2
							THEN (SELECT ISNULL(HourlyRate2,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 3
							THEN (SELECT ISNULL(HourlyRate3,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 4
							THEN (SELECT ISNULL(HourlyRate4,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 5
							THEN (SELECT ISNULL(HourlyRate5,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
					END)
		WHEN 6 THEN t.HourlyRate
		WHEN 9 THEN (SELECT HourlyRate FROM tTitle (nolock) WHERE TitleKey = u.TitleKey)
		WHEN 10 THEN 
				CASE 
					WHEN ISNULL((SELECT HourlyRate FROM tTitleRateSheetDetail (nolock) WHERE TitleRateSheetKey = p.TitleRateSheetKey),'''') = ''''
						THEN (SELECT HourlyRate FROM tTitle (nolock) WHERE TitleKey = u.TitleKey)
					ELSE
						(SELECT HourlyRate FROM tTitleRateSheetDetail (nolock) WHERE TitleRateSheetKey = p.TitleRateSheetKey)
				END
	END, u.HourlyRate) AS [Billable Rate]
From  
 tProject p (nolock)  
 inner join tTask t with (nolock, index= tTask51) on p.ProjectKey = t.ProjectKey  
 left outer join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey 
 left outer join vTaskUserHourBucketStart bucket on tu.TaskUserKey = bucket.TaskUserKey
 left outer join vTaskUserHour tuh (nolock) on bucket.TaskUserKey = tuh.TaskUserKey and bucket.BucketStart = tuh.BucketStart
 left outer join tTaskUserHourOrig tuho (nolock) on bucket.TaskUserKey = tuho.TaskUserKey and bucket.BucketStart = tuho.BucketStart
 left outer join vUserName u on tu.UserKey = u.UserKey  
 left outer join tUser tsu (nolock) on tu.CompletedByKey = tsu.UserKey  
 inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey  
 left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey  
 left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey  
 left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey  
 left outer join tOffice o (nolock) on p.OfficeKey = o.OfficeKey  
 left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey  
 left outer join tUser u2 (nolock) on p.AccountManager = u2.UserKey  
 left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey  
 left outer join tTaskAssignmentType tat (nolock) on t.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey  
 left outer join vUserName u3 on p.KeyPeople1 = u3.UserKey  
 left outer join vUserName u4 on p.KeyPeople2 = u4.UserKey  
 left outer join vUserName u5 on p.KeyPeople3 = u5.UserKey  
 left outer join vUserName u6 on p.KeyPeople4 = u6.UserKey  
 left outer join vUserName u7 on p.KeyPeople5 = u7.UserKey  
 left outer join vUserName u8 on p.KeyPeople6 = u8.UserKey  
 left outer join vUserName taun (nolock) on tu.UserKey = taun.UserKey  
 left outer join vUserName msvn (nolock) on u.MySupervisorKey = msvn.UserKey  
 left outer join tClass cla (nolock) on p.ClassKey = cla.ClassKey  
 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 tDepartment d (nolock) on u.DepartmentKey = d.DepartmentKey  
 left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey  
 left outer join tService se (nolock) on tu.ServiceKey = se.ServiceKey  
 left outer join tWorkType wt (nolock) on se.WorkTypeKey = wt.WorkTypeKey
 left outer join tDepartment sd (nolock) on se.DepartmentKey = sd.DepartmentKey  
 left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey  
 left outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey  
 left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey  
    left outer join tClientProduct  pc (nolock) on p.ClientProductKey  = pc.ClientProductKey  
 left outer join tTimelineSegment ts (nolock) on t.TimelineSegmentKey = ts.TimelineSegmentKey  
 left outer join tTeam team on p.TeamKey =  team.TeamKey   
 left outer join tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey  
 left outer join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey  
 LEFT OUTER JOIN (  
     SELECT  ISNULL(DetailTaskKey, TaskKey) AS TaskKey, Sum(ActualHours) AS ActualTaskLaborHours, Sum(ActualHours * ActualRate) AS ActualTaskLaborTotal  
     FROM  tTimeRollupDetail (NOLOCK)   
     GROUP BY ISNULL(DetailTaskKey, TaskKey)   
     ) lt ON lt.TaskKey = t.TaskKey  
  
    LEFT OUTER JOIN (  
     SELECT  ISNULL(DetailTaskKey, TaskKey) AS TaskKey, UserKey, Sum(ActualHours) AS ActualTaskAssignmentLaborHours, Sum(ActualHours * ActualRate) AS ActualTaskAssignmentLaborTotal  
     FROM  tTimeRollupDetail (NOLOCK)  
     GROUP BY ISNULL(DetailTaskKey, TaskKey), UserKey  
     ) alt ON alt.TaskKey = t.TaskKey AND alt.UserKey = tu.UserKey  
  
'
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,    -- e.g. ''Project'', ''Opportunity'', ''Lead'', ''Client'',
                                                --      ''Invoice'', ''Voucher'', ''Activity'', ''Campaign'', etc.
                                                --      Full list comes from select distinct Entity from tActionLog.
    @EntityKey          int          = null,    -- Primary key of the entity (ProjectKey, OpportunityKey,
                                                --      LeadKey, ClientKey/CompanyKey, InvoiceKey, VoucherKey, etc.)
    @ProjectNumber      varchar(100) = null,    -- Legacy shortcut: equivalent to @Entity=''Project'' + project lookup
    @Username           varchar(500) = null,    -- Legacy: returns log for that user (acts on tActionLog.UserKey)
    @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.
||                            @ProjectNumber preserved as a legacy shortcut for @Entity=''Project''.
||                            @Username preserved as a legacy shortcut that filters by tActionLog.UserKey
||                            (returns actions taken BY that user across all entities).
||                            Entity-scoped access checks: ''Project'' enforces GL company + assignment security;
||                            other entities only require CompanyKey isolation.
*/

set nocount on

    -- Create temp table for error/warning messages
    select * into #errors from tAPIErrorTemplate where 1 = 2 

    declare @TargetUserKey          int
    declare @ProjectKey             int
    declare @ProjectGLCompanyKey    int
    declare @SecurityGroupKey       int
    declare @IsAdministrator        bit
    declare @RestrictToGLCompany    tinyint
    declare @CheckAssignment        tinyint
    declare @ErrorCount             int
    declare @UTCStartDate           datetime
    declare @UTCEndDate             datetime
    declare @EffectiveEntity        varchar(50)
    declare @EffectiveEntityKey     int

    -- ------------------------------------------------------------------
    -- 1. Defaults
    -- ------------------------------------------------------------------
    if @StartDate is null
        set @StartDate = DATEADD(YEAR, -1, 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)

    -- ------------------------------------------------------------------
    -- 2. 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

    -- ------------------------------------------------------------------
    -- 3. Resolve scope: @Entity / @EntityKey takes precedence.
    --    @ProjectNumber is a legacy shortcut for @Entity=''Project''.
    --    @Username is a separate path that filters by tActionLog.UserKey
    --      (actions taken BY a user, not actions ON an entity).
    -- ------------------------------------------------------------------
    set @EffectiveEntity    = @Entity
    set @EffectiveEntityKey = @EntityKey

    -- Legacy: translate @ProjectNumber → @Entity=''Project''
    if @EffectiveEntity is null
       and @ProjectNumber is not null
       and LTRIM(RTRIM(@ProjectNumber)) <> ''''
    begin
        select @ProjectKey           = ProjectKey,
               @ProjectGLCompanyKey  = GLCompanyKey
        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

        set @EffectiveEntity    = ''Project''
        set @EffectiveEntityKey = @ProjectKey
    end

    -- ------------------------------------------------------------------
    -- 4. Validate Entity + EntityKey when entity-scoped
    -- ------------------------------------------------------------------
    if @EffectiveEntity is not null and LTRIM(RTRIM(@EffectiveEntity)) <> ''''
    begin
        if @EffectiveEntityKey is null or @EffectiveEntityKey <= 0
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''REQUIRED_FIELD'',
                    ''entityKey is required when entity is supplied.'',
                    ''entityKey'')

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

            drop table #errors
            return -100
        end

        -- Entity-specific security
        if @EffectiveEntity = ''Project''
            and (@IsAdministrator = 0 or @IsAdministrator is null)
        begin
            -- Make sure we have GLCompanyKey for the project (may already be set via legacy path)
            if @ProjectGLCompanyKey is null
                select @ProjectGLCompanyKey = GLCompanyKey
                from tProject (nolock)
                where CompanyKey = @CompanyKey
                  and ProjectKey = @EffectiveEntityKey

            -- GL Company access
            select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
            from tPreference (nolock)
            where CompanyKey = @CompanyKey

            if @RestrictToGLCompany = 1
               and @ProjectGLCompanyKey is not null
               and not exists (
                   select 1
                   from tUserGLCompanyAccess (nolock)
                   where UserKey       = @UserKey
                     and GLCompanyKey  = @ProjectGLCompanyKey
               )
            begin
                insert into #errors (errorType, errorCode, errorMessage, fieldName)
                values (''error'', ''ACCESS_DENIED'',
                        ''User does not have access to this project''''s GL Company.'',
                        ''entityKey'')
            end

            -- Project assignment (skipped if user has prjAccessAny)
            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
               and not exists (
                   select 1 from tAssignment (nolock)
                   where ProjectKey = @EffectiveEntityKey
                     and UserKey    = @UserKey
               )
            begin
                insert into #errors (errorType, errorCode, errorMessage, fieldName)
                values (''error'', ''ACCESS_DENIED'',
                        ''User is not assigned to this project and does not have global project access.'',
                        ''entityKey'')
            end
        end

        -- Surface any access errors before querying
        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

        -- --------------------------------------------------------------
        -- 5a. Return warnings (none expected on entity path, but consistent)
        -- --------------------------------------------------------------
        select errorType, errorCode, errorMessage, fieldName
        from #errors where errorType = ''warning''

        -- --------------------------------------------------------------
        -- 5b. Return action log filtered by Entity + EntityKey
        -- --------------------------------------------------------------
        select top (@MaxRows)
               al.Entity              as entity,
               al.EntityKey           as entityKey,
               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
        from vActionLog al (nolock)
        where al.CompanyKey   = @CompanyKey
          and al.Entity       = @EffectiveEntity
          and al.EntityKey    = @EffectiveEntityKey
          and al.ActionDate  >= @UTCStartDate
          and al.ActionDate  <= @UTCEndDate
        order by al.ActionDate desc

        drop table #errors
        return 0
    end

    -- ------------------------------------------------------------------
    -- 6. User path (legacy): @Username → resolve UserKey → return actions
    --    taken BY that user (across all entities)
    -- ------------------------------------------------------------------
    set @TargetUserKey = @UserKey

    if @Username is not null and LTRIM(RTRIM(@Username)) <> ''''
    begin
        select top 1 @TargetUserKey = UserKey
        from tUser (nolock)
        where CompanyKey = @CompanyKey
          and Active     = 1
          and (
                UPPER(FirstName + '' '' + LastName) = UPPER(LTRIM(RTRIM(@Username)))
                or UPPER(Email)  = UPPER(LTRIM(RTRIM(@Username)))
                or UPPER(UserID) = UPPER(LTRIM(RTRIM(@Username)))
              )

        if @TargetUserKey is null
        begin
            set @TargetUserKey = @UserKey
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'',
                    ''User not found for Username: '' + @Username + '' — returning action log for the requesting user.'',
                    ''username'')
        end
    end

    -- Return warnings (non-fatal)
    select errorType, errorCode, errorMessage, fieldName
    from #errors where errorType = ''warning''

    -- Return action log for the resolved user
    select top (@MaxRows)
           al.Entity              as entity,
           al.EntityKey           as entityKey,
           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
    from vActionLog al (nolock)
    where al.CompanyKey   = @CompanyKey
      and al.UserKey      = @TargetUserKey
      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].[spRptInvoiceAging]'
GO
IF OBJECT_ID(N'[dbo].[spRptInvoiceAging]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[spRptInvoiceAging]
(
	@CompanyKey int,
	@AsOfDate smalldatetime,
	@ClientKey int,
	@ParentClientKey int,
	@ClassKey int,
	@ProjectKey int = null,       -- ProjectKey on header
	@PostStatus tinyint,
	@AdvBill tinyint,		      -- Include Unapplied Advanced Billings
	@Receipts tinyint,
	@AgingDateOption tinyint,
	@OlderThan smallint,
	@Days1 smallint,
	@Days2 smallint,
	@Days3 smallint,
	@SummaryOnly tinyint,         -- 0: Regular AR Statement or Aging; 1: Used by Running Balance statement to get the Aging totals.
	@GLCompanyKey int = NULL,     -- -1 All, 0 NULL, >0 valid GLCompany, -2 Using a GLCompanyKeys temp table
	@Invoices tinyint = 1,        -- Include Invoices
	@AdvBillSalesTax tinyint = 1,  -- Include Sales Taxes on Unapplied Advanced Billings
	@AdvBillMultiplier int = 1,
	@ARAccountKey int,
	@UserKey int = null,
	@AccountManager int = null,
	@CurrencyID varchar(10) = null, -- Null Home Currency, or a foreign currency
	@CustomizationBarbarian int = 0, -- requires customization barbGroup
	@ClientKeys varchar(400) = NULL,
	@LiabilityAccountKey int = NULL,
	@ExcludeRevInvoices tinyint = NULL
)
AS --Encrypt
SET NOCOUNT ON

 /*
  || When     Who Rel  What
  || 06/27/06 GHL 8.35 Added ProjectKey parameter and column to include projects 
  ||                   in Client statements. Also added Primary contact 
  ||                   (Bug 4969 McClain-Finlon)
  || 11/06/06 CRG 8.35 Added option for aging based on PostingDate.
  || 11/27/06 CRG 8.35 Added @SummaryOnly parameter to get the Aging totals.
  || 11/28/06 GWG 8.35 Removed the unapplied payment link to invoices to take into account all applications
  || 02/20/07 GHL 8.403 Filtering out now checks which are voided (Bug 8330)
  || 10/17/07 CRG 8.5  Added GLCompanyKey parameter, and OfficeName to the return data
  || 11/27/07 GHL 8.5  Removed alias in ORDER BY for SQL Server 2005
  || 12/13/07 GHL 8.5  Added fields required for AE view, move client key and other keys to top where clauses
  ||                   to reduce the number of records processed
  || 12/21/07 GHL 8.5  Removed needless join in initial queries to speed up perfo 
  || 01/17/08 GHL 8502 Requirements for Project Numbers has changed
  ||                   Old requirement:
  ||					-- when no project on header, look at invoice line or summary, if none display ''None'', else ''MULTI''  
  ||                   New requirement:
  ||                    -- display all projects for invoices 
  ||                         proj #1 - proj name 1
  ||                         proj #2 - proj name 2     
  || 01/23/08 GHL 8502 (19016) Removed sort by Office, because it is not showing in Client Statements 
  ||                   and sorting was confusing to user (Open Transaction mode)
  ||                   Also put back project on header for Client Statements  
  || 01/29/08 GHL 8503 (19362) Removed sort by Office in summary section because this is used in conjunction with
  ||                   spRptStatementRunningBalance and there is no office in Client Statement (Statement Period mode) 
  ||                   Added check of posted status in subqueries
  ||                   Added check of invoice posting date in open rec 
  ||                   Did not fix discrepancy with spRptStatementRunningBalance in the case of application to sales
  || 05/18/08 GWG 26882 Added a restrict for prepayments so that they do not get added back in on missing receipts
  || 06/09/08 GHL 8513   (25847) Taking input parameters in account for new AR aging summary
  || 07/01/08 GHL 8515   (29015) Added new parameter @AdvBillOnly so that we only take unapplied adv billings
  || 02/10/09 GHL 10.018 (37631) Changed logic for GLCompany to match change in the UI
  || 03/09/09 GHL 10.020 (48415) Added restriction on invoice posting date <= check posting date for ''Payment''
  ||                      Because if not, there are similar to prepayments
  || 03/16/09 RLB 10.021 (48967) added sorting by invoice number
  || 04/22/09 RLB 10.024 (51346) fixed when summary was checked and due date was aging option it was pulling invoice date is now pulling Due Date
  || 04/28/09 GHL/GWG 10.024 Added Invoices parameter. Added ''Rev AB'' type and removed the * -1 so advances show up positive
  || 06/12/09 GWG 10.025 Reversed the fix above from 5/18/2008 as it causes the aging to be off
  || 01/19/10 GHL 10.517 (72581) Added @AdvBillSalesTax param and associated queries
  || 05/05/10 GHL 10.522 (77192) Added @AdvBillMultiplier so that client statements show as negative
  || 06/03/10 GWG 10.530 Added in functions to Group invoices with the same invoice number together on the aging
  || 09/16/10 RLB 10.535 (61907) Added days for enhancement request
  || 01/28/12 RLB 10.552 (129693) Added AR Account filter for enhancement request
  || 04/16/12 GHL 10.555  Added UserKey for UserGLCompanyAccess
  || 08/28/12 GWG 10.559 Fixed a case where an applied receipt was showing up twice because it was applied to an invoice after the as of date.
  || 04/22/13 GHL 10.567 (175324) For unapplied receipts, I am making the distinction between payments and prepayments
  ||                     If the invoice in a prepayment is after the AsOfDate, the check should be considered unapplied
  ||                     so OpenAmount = Check Amount - sum(of prepayments) where invoice posting date <= AsOfDate 
  || 08/26/13 RLB 10.571 (185716) Adding filter for client Account mananger
  || 09/19/13 MFT 10.572 (190363) Added DivisionName.tClientDivision & ProductName.tClientProduct to final output
  || 11/14/13 GHL 10.574 (196587) Check is on 10/21/13 voided check is on 11/7/13. report run as of 10/31
  ||                     user expects to see check on the report but it is not. Changed query from ch.VoidCheckKey = 0
  ||                     to ch.VoidCheckKey = 0 Or void_ch.PostingDate > AsOfDate
  || 01/27/14 GHL 10.576 Added CurrencyID param + @MultiCurrency logic 
  || 03/11/14 RLB 10.578 (160899) Added Parent CompanyKey for enhancement
  || 05/09/14 GHL 10.580 If the report is grouped by project, make sure that there is no difference between NULL and 0
  ||                     The report uses ProjectKey as the group''s datafield 
  || 05/13/14 GHL 10.580 (215354) Filter out invoices which are over applied
  || 02/23/15 KMC 10.589 (247059) Added ISNULL check for the Account Manager to default it to the company record Account Manager
  || 03/11/15 GHL 10.590 (248945) Problem when the Advance Bill comes after the regular invoice, the RetainerAmount is not time sensitive
  ||                      For this reason, I recalculate the total adv bill amount with FromAB = 0 (instead of taking i.RetainerAmount) 
  ||                      And we need to add to the applied amount the total adv bill amount with FromAB = 1
  || 04/14/15 GHL 10.591 (253288) Deleting now advance bills where applied amount > invoice amount to correct bad data
  ||                      The data could not be corrected due to GL locking
  || 05/08/15 GHL 10.591 (255992) Because sometimes i.RetainerAmount <> Sum(tInvoiceAdvanceBill.Amount) decided to take RetainerAmount
  ||                      when dealing with old invoices
  || 05/19/15 GHL 10.592 (257181) Added ABS() function around checks for 253288 because Acosta Sales had negative advance bills
  || 11/10/15 WDF 10.598 (277170) Added field ClientName in Summary, ClientFullName2 in Non-Summary for grouping for Ableson
  || 01/14/16 GHL 10.600 (282860) When running the client statements, show advance bill reversals if they are fully paid
  || 02/09/15 WDF 10.601 (278464) Appended ProjectName to ProjectNumber
  || 03/24/15 WDF 10.602 (293952) Broke out ProjectName and ProjectNumber
  || 06/15/17 GHL 10.617 (349458) Broke up the initial query in multiple queries to speed perfo
  ||                     went from 1 min to 50 sec on the AU server at the cost of added complexity
  ||                     ...left initial query in case we want to rollup
  || 11/20/17 GHL 10.622 (368959) Added customization for the Barbarian Group
  || 06/10/19 GHL 19.700 (462782) Added negative entries for the invoice advance bill amounts applied from the AB side
  || 10/07/19 GHL 19.100 (480759) Found 2 issues with the Aging of the Advance Bills (@AdvBill = 1)
  ||                     1) The reversal of regular invoices was not picked up when the Adv Bill and Reg invoices were on same posting dates
  ||                     and that day was on @AsOfDate and the AB application was initiated from the Reg side (i.e FromAB = 0)
  ||                     2) Deducting sales taxes needs to consider when the AB application was initiated from the AB side (FromAB=1)   
  || 12/18/19 GHL 20.010 (492030) Added credits to invoices for Barbarian customization
  || 02/16/21 MFT 21.030 (548595) Added missing @ProjectKey to initial WHERE clause
  || 10/04/21 GHL 21.110 (559294) Added campaign full name on invoice headers
  || 12/10/21 GHL 21.120 (580312) Added missing RealInvoiceKey to cbre queries (was causing project col to be blank)
  || 08/31/22 GAR 22.090 (610432) Changing the ARAging report to use any of for the GL Company
  ||			 This involves still passing the GLCompanyKey in because this SP is used in several places
  ||			 If that value is -2, that indicates we are using the temp table of GLCompanyKeys
  || 06/12/23 RLB 23.070 (634098) Added PM options
  || 08/01/23 MFT 23.080 (647768) If there is a Campaign on the Invoice, and the Campaign has an Account Manager use that value rather than the Client AM
  || 10/31/24 GAR 24.120 (685733) Change the Client selection to be Any Of
  || 03/20/25 RLS 25.04.20 (695915) Added check for CampaignKeys
  || 04/11/25 AMP 25.05.18 (699569) Correction for displaying Project/Campaign Full Name or just the numbers
  || 06/18/25 AMP 25.06.15 (704250) Bug Fix that was introduced in 699569 (Fixed display of Project/Campaign Full Name)
  || 11/03/25 MFT 25.110 (711198) Revert 215354 (removing overapplied Invoices)
  || 12/01/25 MCM 26.01x (656423) Adding Liability Account Key
  || 01/30/26 RLB 26.03.15 (719429) Adding Parent Company view 
  || 02/16/26 RLB 26.03.15 (719429) fixed spelling errors
  || 05/19/26 AMP 26.05.19 (718179) Added @ExcludeRevInvoices to exclude regular invoices (AdvanceBill = 0)
 */
 
/* Tips to debug aging problems (discrepancies between balance sheet and open amount on the aging report)

The aging report must be run with ''Posted Transactions Only'' checked

1) Find the first day at which the discrepancy occurs 
2) Record the difference between the open amount on the aging report and the balance sheet
3) Try to find a GL transaction on that day with the ABS(Debit - Credit) = difference
4) If you find one, analyze possible causes
5) If you do not find one, unpost one transaction at a time and compare balance sheet and aging report after each unposting  
   until the discrepancy disappears. When found, analyze possible causes
*/

-- Create table rather than select into to reduce time locking tempdb, 17000 records my be read below
CREATE TABLE #ARAging
	(InvoiceKey INT NULL -- will hold InvoiceKey if Type = ''Invoice'', ''Credit'', ''Open AB'' CheckKey if Type = ''Payment'', ''Open Rec''
	,GLCompanyKey INT NULL
	,Type VARCHAR(50) NULL
	,Posted INT NULL
	,ClientKey INT NULL
	,LoggedCompanyKey INT NULL
	,InvoiceNumber VARCHAR(250) NULL
	,ClassKey INT NULL
	,ProjectKey INT NULL
	,ContactName VARCHAR(500) NULL
	,InvoiceDate DATETIME NULL
	,DueDate DATETIME NULL
	,PostingDate DATETIME NULL
	,BilledAmount MONEY NULL
	,AppliedAmount MONEY NULL
	,OfficeKey INT NULL
	,AccountManager INT NULL  -- AE on project on header
	,ProjectManager INT NULL  -- PM on project on header
	,RealInvoiceKey INT NULL
	,ParentCompanyKey INT NULL
	,Action INT NULL  -- to determine projects
	,AmountReceived MONEY NULL
	,ARAccountKey INT NULL -- added for issue 349548
	) 

-- check for the cbre customization
declare @Customizations varchar(2000), @RollUpMatching int
Select @Customizations = LOWER(ISNULL(Customizations, '''')) from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
Select @RollUpMatching = CHARINDEX(''cbre'', @Customizations)

Declare @RestrictToGLCompany int
Declare @MultiCurrency int
Declare @AllClients int

Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
      ,@MultiCurrency = ISNULL(MultiCurrency, 0)
	from tUser u (nolock)
	inner join tPreference p (nolock) on p.CompanyKey = ISNULL(u.OwnerCompanyKey, u.CompanyKey)
	Where u.UserKey = @UserKey

select @RestrictToGLCompany = isnull(@RestrictToGLCompany, 0)
       ,@MultiCurrency = isnull(@MultiCurrency, 0)

DECLARE	@HasGLCompanyKeys int
SET @HasGLCompanyKeys = 0
IF @GLCompanyKey = -2
BEGIN
	SELECT	@HasGLCompanyKeys = COUNT(*)
	FROM	#GLCompanyKeys

	IF @HasGLCompanyKeys = 0
		SET @GLCompanyKey = -1
END
ELSE
BEGIN
CREATE TABLE #GLCompanyKeys (GLCompanyKey INT NULL)
END

-- (695915) This temp table is already created in VB when called from the Client Statement Report.
-- We need to conditionally create it here in case this SP is being called from elsewhere.
IF ISNULL(object_id(''tempdb..#CampaignKeys''), 0) = 0
	CREATE TABLE #CampaignKeys (CampaignKey int NULL) 

DECLARE	@HasCampaignKeys int
DECLARE @CampCount int = 0

SET @HasCampaignKeys = NULL
SELECT	@CampCount = COUNT(*)
FROM	#CampaignKeys

IF @CampCount > 0
SELECT	@HasCampaignKeys = @CampCount

CREATE TABLE #clients (ClientKey INT null)

-- Allow All Clients
SELECT @AllClients = 0
IF ISNULL(@ClientKeys, '''') = '''' and @RestrictToGLCompany = 0
	SELECT @AllClients = 1

-- Restrict to Clients passed in
IF LEN(@ClientKeys) > 0
BEGIN
	INSERT INTO #clients	 
	SELECT value FROM dbo.fSplitVals(@ClientKeys, '','')
END

IF @Invoices = 1
BEGIN
  
	-- Find the open invoices less credits and payments

	-- This first query is optimized for IX_tInvoice_Statement
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager,RealInvoiceKey, ARAccountKey)
	select i.InvoiceKey, i.GLCompanyKey, ''Invoice'', i.Posted, i.ClientKey, @CompanyKey, null, null, i.ProjectKey, null, null, null, i.PostingDate
	,0, 0, null, null , null, i.InvoiceKey, i.ARAccountKey
	from tInvoice i (nolock)
	where i.CompanyKey = @CompanyKey 
	And	i.PostingDate <= @AsOfDate 
	And	i.InvoiceTotalAmount >= 0
	And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(ab.GLCompanyKey, 0)) ) -- changed 1/16 i.GLCompanyKey to ch.GLCompanyKey
	-- Reduce # of records upfront
	and (
			(ISNULL(@ClientKeys, '''') <> '''' and ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)
	And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And i.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)
	AND (ISNULL(@ExcludeRevInvoices, 0) = 0 OR ISNULL(i.AdvanceBill, 0) <> 0)

	-- get missing data from tInvoice using the small number of invoices in #ARAging
	update #ARAging
	set    #ARAging.InvoiceNumber = i.InvoiceNumber
	      ,#ARAging.ClassKey = i.ClassKey
		  ,#ARAging.OfficeKey = i.OfficeKey
		  ,#ARAging.InvoiceDate = i.InvoiceDate
		  ,#ARAging.DueDate = i.DueDate
		  ,#ARAging.ARAccountKey = i.ARAccountKey
		  ,#ARAging.ContactName = i.ContactName
	from tInvoice i (nolock)
	where #ARAging.InvoiceKey = i.InvoiceKey
	 
	if @ClassKey is not null
		delete #ARAging where isnull(ClassKey, 0) <> @ClassKey 
	if @ARAccountKey is not null
		delete #ARAging where isnull(ARAccountKey, 0) <> @ARAccountKey 
		
	update #ARAging
	set    #ARAging.AccountManager = p.AccountManager,
		   #ARAging.ProjectManager = p.ProjectManager
	from   tProject p (nolock)
	where  #ARAging.ProjectKey = p.ProjectKey

	update #ARAging
	set    #ARAging.AccountManager = c.AccountManagerKey
	from   tCompany c (nolock)
	where  #ARAging.ClientKey = c.CompanyKey
	and    #ARAging.AccountManager is null
	
	UPDATE #ARAging
	SET AccountManager = c.AEKey
	FROM
		#ARAging
		INNER JOIN tInvoice i (nolock) ON #ARAging.RealInvoiceKey = i.InvoiceKey
		INNER JOIN tCampaign c (nolock) ON i.CampaignKey = c.CampaignKey
	WHERE ISNULL(c.AEKey, 0) > 0
	
	update #ARAging
	set    #ARAging.ProjectManager = c.ProjectManagerKey
	from   tCompany c (nolock)
	where  #ARAging.ClientKey = c.CompanyKey
	and    #ARAging.ProjectManager is null

	if @AccountManager is not null
		delete #ARAging where isnull(AccountManager, 0) <> @AccountManager 

	update #ARAging 
	set    #ARAging.BilledAmount = case when i.InvoiceDate < ''05/08/2014'' then
			ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0)
		     else
			ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - ISNULL(i.WriteoffAmount, 0) -- - ISNULL(i.RetainerAmount, 0)
			-- recalc RetainerAmount for 248945
			- (select isnull(sum(iab.Amount), 0) from tInvoiceAdvanceBill iab (nolock) where iab.InvoiceKey = i.InvoiceKey and isnull(FromAB, 0) = 0 )
		end
	from  tInvoice i (nolock)
	where #ARAging.InvoiceKey = i.InvoiceKey 
	
	update #ARAging 
	set    #ARAging.AppliedAmount = (Select ISNULL(SUM(ca.Amount), 0)
			from tCheckAppl ca (nolock)
			inner join tCheck ch (nolock) on ch.CheckKey = ca.CheckKey
			Where ca.InvoiceKey = #ARAging.InvoiceKey and ch.PostingDate <= @AsOfDate
			and ch.Posted >= @PostStatus -- Added By Gil 1/29/08 to match spRptRunningBalance
			) + 
		 (Select ISNULL(Sum(Amount), 0) 
			from tInvoiceCredit ic (nolock) 
			inner join tInvoice cc (nolock) on cc.InvoiceKey = ic.CreditInvoiceKey
			Where ic.InvoiceKey = #ARAging.InvoiceKey AND
				cc.PostingDate <= @AsOfDate
			and cc.Posted >= @PostStatus -- Added By Gil 1/29/08	
				)
			-- Added for 248945
				+ 
		 (Select ISNULL(Sum(iab2.Amount), 0) 
			from tInvoiceAdvanceBill iab2 (nolock) 
			inner join tInvoice ab (nolock) on ab.InvoiceKey = iab2.AdvBillInvoiceKey
			Where iab2.InvoiceKey = #ARAging.InvoiceKey AND
				ab.PostingDate <= @AsOfDate
			and ab.Posted >= @PostStatus 	
			and isnull(iab2.FromAB, 0) = 1 
				) 

	/* this is the initial query we split like above, the list with subqueries is too large (150,000 recs) issue 349458
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, RealInvoiceKey)
	SELECT 
		i.InvoiceKey
		,i.GLCompanyKey
		,''Invoice''
		,i.Posted
		,i.ClientKey
		,@CompanyKey 
		,RTRIM(i.InvoiceNumber)
		,i.ClassKey
		,i.ProjectKey
		,i.ContactName
		,i.InvoiceDate
		,i.DueDate
		,i.PostingDate
		
	--	,ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - ISNULL(i.WriteoffAmount, 0) -- - ISNULL(i.RetainerAmount, 0)
	--	-- recalc RetainerAmount for 248945
	--	- (select isnull(sum(iab.Amount), 0) from tInvoiceAdvanceBill iab (nolock) where iab.InvoiceKey = i.InvoiceKey and isnull(FromAB, 0) = 0 )
	--	AS BilledAmount
	
		-- due to the fact that I have too many old invoices popping up, use RetainerAmount or recalculate (there is sometimes a discrepancy between RetainerAmount and SUM(IAB.Amount))
		,case when i.InvoiceDate < ''05/08/2014'' then
			ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0)
		     else
			ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - ISNULL(i.WriteoffAmount, 0) -- - ISNULL(i.RetainerAmount, 0)
			-- recalc RetainerAmount for 248945
			- (select isnull(sum(iab.Amount), 0) from tInvoiceAdvanceBill iab (nolock) where iab.InvoiceKey = i.InvoiceKey and isnull(FromAB, 0) = 0 )
		end as BilledAmount

		,(Select ISNULL(SUM(ca.Amount), 0)
			from tCheckAppl ca (nolock)
			inner join tCheck ch (nolock) on ch.CheckKey = ca.CheckKey
			Where ca.InvoiceKey = i.InvoiceKey and ch.PostingDate <= @AsOfDate
			and ch.Posted >= @PostStatus -- Added By Gil 1/29/08 to match spRptRunningBalance
			) + 
		 (Select ISNULL(Sum(Amount), 0) 
			from tInvoiceCredit ic (nolock) 
			inner join tInvoice cc (nolock) on cc.InvoiceKey = ic.CreditInvoiceKey
			Where ic.InvoiceKey = i.InvoiceKey AND
				cc.PostingDate <= @AsOfDate
			and cc.Posted >= @PostStatus -- Added By Gil 1/29/08	
				)
			-- Added for 248945
				+ 
		 (Select ISNULL(Sum(iab2.Amount), 0) 
			from tInvoiceAdvanceBill iab2 (nolock) 
			inner join tInvoice ab (nolock) on ab.InvoiceKey = iab2.AdvBillInvoiceKey
			Where iab2.InvoiceKey = i.InvoiceKey AND
				ab.PostingDate <= @AsOfDate
			and ab.Posted >= @PostStatus 	
			and isnull(iab2.FromAB, 0) = 1 
				) 
		as AppliedAmount
		,i.OfficeKey
		,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
		,i.InvoiceKey
	FROM tInvoice i (nolock)
		LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey 
		LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	Where
		i.CompanyKey = @CompanyKey 
	And	i.PostingDate <= @AsOfDate 
	And	i.InvoiceTotalAmount >= 0 
	--And	(@GLCompanyKey IS NULL OR ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey) 
	AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )
	And	(@ClientKey IS NULL OR i.ClientKey = @ClientKey)  -- Reduce # of records upfront
	And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And	(@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey) 
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	And i.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	*/

	/*
	Issue 462782 -- Explanations for the following enty

INV-25481  (AB invoice)
Internal-25481 (real invoice)

GL					DR			CR
INV-25481          1/15/19		1720			0
INV-25481          1/15/19		0			1000			From AB = 1
Internal-25481	   1/16/19		1000			0

AR Aging 1/15
					Billed Amount		Applied Amount
INV-25481          AB			-1000			0		Needed to add this
INV-25481          Invoice		1720			0

AR Aging 1/16
					Billed Amount		Applied Amount
INV-25481          Invoice		1720			0
Internal-25481	   Invoice		1000			1000
	*/

	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	Select
		 ab.InvoiceKey
	    ,ab.GLCompanyKey
		,''Advance Bill''
		,ab.Posted
		,ab.ClientKey
		,@CompanyKey
		,RTRIM(ab.InvoiceNumber)
		,ab.ClassKey
		,ab.ProjectKey
		,ab.ContactName
		,ab.InvoiceDate
		,ab.DueDate
		,ab.PostingDate
		,iab.Amount * -1
		,0
		,ab.OfficeKey
		,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
		,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
		,ab.InvoiceKey

	From tInvoice ab (nolock)
		inner join tInvoiceAdvanceBill iab (nolock) on iab.AdvBillInvoiceKey = ab.InvoiceKey
		inner join tCompany c (nolock) on ab.ClientKey = c.CompanyKey
		LEFT JOIN tProject p (nolock) ON ab.ProjectKey = p.ProjectKey
		inner join tInvoice i (nolock) on iab.InvoiceKey = i.InvoiceKey
	Where
		ab.CompanyKey = @CompanyKey
	And	ab.PostingDate <= @AsOfDate
	And ab.Posted >= @PostStatus 
	And NOT (i.PostingDate <= @AsOfDate And i.Posted >= @PostStatus)
	And isnull(iab.FromAB, 0) = 1
	AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(ab.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(ab.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(ab.GLCompanyKey, 0)) ) -- changed 1/16 i.GLCompanyKey to ch.GLCompanyKey

	-- Reduce # of records upfront
	and (
			(ISNULL(@ClientKeys, '''') <> '''' and ab.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR ab.ClientKey = @ClientKey))
		)

	And (@ParentClientKey IS NULL or (ab.ClientKey = @ParentClientKey or ab.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And	(@ClassKey IS NULL OR ab.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@ProjectKey IS NULL OR ab.ProjectKey = @ProjectKey) 
	And (@ARAccountKey IS NULL OR ISNULL(ab.ARAccountKey, 0) = @ARAccountKey)
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	AND (@MultiCurrency = 0
		OR isnull(ab.CurrencyID, '''') = isnull(@CurrencyID, '''') )	 


	-- Add Back any receipts applied to invoices later than the date window (step Invoice 2)
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	Select
		 ch.CheckKey
	    ,ch.GLCompanyKey
		,''Payment''
		,ch.Posted
		,ch.ClientKey
		,@CompanyKey
		,RTRIM(ch.ReferenceNumber)
		,ch.ClassKey
		,i.ProjectKey
		,i.ContactName
		,ch.CheckDate
		,ch.CheckDate
		,ch.PostingDate
		,ca.Amount * -1
		,0
		,i.OfficeKey
		,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
		,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
		,i.InvoiceKey
	From
		tCheck ch (nolock)
		inner join tCompany c (nolock) on ch.ClientKey = c.CompanyKey
		inner join tCheckAppl ca (nolock) on ch.CheckKey = ca.CheckKey
		inner join tInvoice i (nolock) on ca.InvoiceKey = i.InvoiceKey
		LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
	Where
		c.OwnerCompanyKey = @CompanyKey 
	And	i.PostingDate > @AsOfDate 
	And	ch.PostingDate <= @AsOfDate 
	And ca.Prepay = 0 -- you dont want the stuff applied as a prepayment as that should come off the other invoice.
	-- Removed the line below as this report can only be run for one section at a time now. the statement below causes the ar aging to be off
	--And i.PostingDate <= ch.PostingDate -- If the check posting date is before the invoice date, it is like a prepayment
	
	--And	(@GLCompanyKey IS NULL OR ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey) 
	AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(ch.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(ch.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(ch.GLCompanyKey, 0)) ) -- changed 1/16 i.GLCompanyKey to ch.GLCompanyKey

	-- Reduce # of records upfront
	and (
			(ISNULL(@ClientKeys, '''') <> '''' and ch.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR ch.ClientKey = @ClientKey))
		)

	And (@ParentClientKey IS NULL or (ch.ClientKey = @ParentClientKey or ch.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And	(@ClassKey IS NULL OR ch.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey) 
	And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey)
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	And ch.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
		OR isnull(ch.CurrencyID, '''') = isnull(@CurrencyID, '''') )
			
	-- Add in any credits that are not fully applied yet
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	Select
		i.InvoiceKey
		,i.GLCompanyKey
		,''Credit''
		,i.Posted
		,i.ClientKey
		,@CompanyKey
		,RTRIM(i.InvoiceNumber)
		,i.ClassKey
		,i.ProjectKey
		,i.ContactName
		,i.InvoiceDate
		,i.DueDate
		,i.PostingDate
		,ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0)
		,((Select ISNULL(Sum(Amount), 0) 
			from tCheckAppl ca (nolock) 
			inner join tCheck ch (nolock) on ch.CheckKey = ca.CheckKey
			Where ca.InvoiceKey = i.InvoiceKey AND
				ch.PostingDate <= @AsOfDate
			And ch.Posted >= @PostStatus	
			) +  -- Added by Gil
		 (Select ISNULL(Sum(Amount), 0) * -1 
			from tInvoiceCredit icd (nolock) 
			inner join tInvoice ic (nolock) on ic.InvoiceKey = icd.InvoiceKey
			Where icd.CreditInvoiceKey = i.InvoiceKey AND
				ic.PostingDate <= @AsOfDate
			And ic.Posted >= @PostStatus -- Added by Gil
				)) as AmountPaid
		,i.OfficeKey
		,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
		,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
		,i.InvoiceKey
	From
		tInvoice i (nolock) 
		LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
		LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	Where
		i.CompanyKey = @CompanyKey 
	And	i.PostingDate <= @AsOfDate 
	And	i.InvoiceTotalAmount < 0 
	--And	(@GLCompanyKey IS NULL OR ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey) 
	AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	-- Reduce # of records upfront
	and (
			(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)

	And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And	(@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey) 
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	And i.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)
END
	
if @AdvBill = 1 And @AdvBillSalesTax = 1
BEGIN
	-- Add in any unapplied advance billings
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey, AmountReceived)
	Select
		i.InvoiceKey
		,i.GLCompanyKey
		,''Open AB''
		,i.Posted
		,i.ClientKey
		,@CompanyKey
		,RTRIM(i.InvoiceNumber)
		,i.ClassKey
		,i.ProjectKey
		,i.ContactName
		,i.InvoiceDate
		,i.DueDate
		,i.PostingDate
		,(ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0))
		,(Select ISNULL(Sum(Amount), 0)
			from tInvoiceAdvanceBill abi (nolock) 
			inner join tInvoice inv (nolock) on abi.InvoiceKey = inv.InvoiceKey
			Where abi.AdvBillInvoiceKey = i.InvoiceKey and inv.PostingDate <= @AsOfDate
			--And inv.Posted >= @PostStatus -- removed for 480759
			And (
				-- added for 480759
				isnull(abi.FromAB, 0) = 1  -- if entered from the AB side, posting status will be checked in the where clause
				Or (isnull(abi.FromAB, 0) = 0 AND inv.Posted >= @PostStatus)  -- if entered from the Reg side, check posting status now
				)
			) as AmountPaid
		,i.OfficeKey
		,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
		,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
		,i.InvoiceKey
		,(Select ISNULL(Sum(Amount), 0) 
			from tCheckAppl ca (nolock) 
			inner join tCheck ch (nolock) on ch.CheckKey = ca.CheckKey
			Where ca.InvoiceKey = i.InvoiceKey AND
				ch.PostingDate <= @AsOfDate
			And ch.Posted >= @PostStatus	
			) as AmountReceived
	From
		tInvoice i (nolock) 
		LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
		LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	Where
		i.CompanyKey = @CompanyKey 
	And	i.PostingDate <= @AsOfDate 
	And	i.AdvanceBill = 1 	
	--And	(@GLCompanyKey IS NULL OR ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey) 
	AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	-- Reduce # of records upfront
	and (
			(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)

	And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And	(@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey) 
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	And i.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
    And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)

	-- issue 253288 this is a patch to fix a data corruption situation
	-- an advance bill rec was over applied
	DELETE #ARAging WHERE ABS(AppliedAmount) > ABS(BilledAmount)

	-- issue 282860: only show advance bill reversals if they are fully paid 
	if @AdvBillMultiplier = -1 -- this indicates that we run the client statements, not AR aging
		DELETE #ARAging WHERE Type = ''Open AB'' and BilledAmount != isnull(AmountReceived, 0)

	 -- also insert the real invoices where they have adv bills applied but after the date.
	 Insert Into #ARAging
	 (InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	 ,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	 
	 Select
	  i.InvoiceKey
	  ,i.GLCompanyKey
	  ,''Rev AB''
	  ,i.Posted
	  ,i.ClientKey
	  ,@CompanyKey
	  ,RTRIM(i.InvoiceNumber)
	  ,i.ClassKey
	  ,i.ProjectKey
	  ,i.ContactName
	  ,i.InvoiceDate
	  ,i.DueDate
	  ,i.PostingDate
	  ,0
	  ,abi.Amount
	  ,i.OfficeKey
	  ,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
	  ,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
	  ,i.InvoiceKey
	 From tInvoice i (nolock) 
	  inner join tInvoiceAdvanceBill abi (nolock) on i.InvoiceKey = abi.InvoiceKey
	  inner join tInvoice ab (nolock) on ab.InvoiceKey = abi.AdvBillInvoiceKey
	  LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
	  LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	 Where i.CompanyKey = @CompanyKey 
	  and ab.PostingDate > @AsOfDate 
	  and i.PostingDate <= @AsOfDate
	  AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	  --AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	  -- Reduce # of records upfront
	  and (
				(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
				or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
			)

	  And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	  And (@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	  And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	  And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	  And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey) 
	  And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	  And i.Posted >= @PostStatus
	  AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	  AND  isnull(abi.FromAB,0) = 0 
	  And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)

  -- 480759 reversals when the AB is not posted and the reg invoice is posted in the window 	
	Insert Into #ARAging
	 (InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	 ,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	 
	 Select
	  i.InvoiceKey
	  ,i.GLCompanyKey
	  ,''Rev AB''
	  ,i.Posted
	  ,i.ClientKey
	  ,@CompanyKey
	  ,RTRIM(i.InvoiceNumber)
	  ,i.ClassKey
	  ,i.ProjectKey
	  ,i.ContactName
	  ,i.InvoiceDate
	  ,i.DueDate
	  ,i.PostingDate
	  ,0
	  ,abi.Amount
	  ,i.OfficeKey
	  ,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
	  ,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
	  ,i.InvoiceKey
	 From tInvoice i (nolock) 
	  inner join tInvoiceAdvanceBill abi (nolock) on i.InvoiceKey = abi.InvoiceKey
	  inner join tInvoice ab (nolock) on ab.InvoiceKey = abi.AdvBillInvoiceKey
	  LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
	  LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	 Where i.CompanyKey = @CompanyKey 
	  and ab.PostingDate <= @AsOfDate 
	  and i.PostingDate <= @AsOfDate
	  AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	  --AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	  -- Reduce # of records upfront
	  and (
			(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)

	  And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	  And (@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	  And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	  And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	  And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey) 
	  And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	  And i.Posted >= @PostStatus
	  And ab.Posted = 0 -- The AB is unposted, it it was posted it will be accounted for earlier
	  AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	  AND  isnull(abi.FromAB,0) = 0 
	  And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)
  
END

if @AdvBill = 1 And @AdvBillSalesTax = 0
BEGIN
	-- Add in any unapplied advance billings
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	Select
		i.InvoiceKey
		,i.GLCompanyKey
		,''Open AB''
		,i.Posted
		,i.ClientKey
		,@CompanyKey
		,RTRIM(i.InvoiceNumber)
		,i.ClassKey
		,i.ProjectKey
		,i.ContactName
		,i.InvoiceDate
		,i.DueDate
		,i.PostingDate
		,(ISNULL(i.InvoiceTotalAmount, 0) - isnull(i.DiscountAmount, 0) - isnull(i.RetainerAmount, 0) - ISNULL(i.WriteoffAmount, 0))
		- isnull(i.SalesTaxAmount, 0) -- No Sales Taxes
		,ISNULL((
		    Select ISNULL(Sum(abi.Amount), 0)
			from tInvoiceAdvanceBill abi (nolock) 
			inner join tInvoice inv (nolock) on abi.InvoiceKey = inv.InvoiceKey
			Where abi.AdvBillInvoiceKey = i.InvoiceKey and inv.PostingDate <= @AsOfDate
			--And inv.Posted >= @PostStatus -- removed for 480759
			And (
				-- added for 480759
				isnull(abi.FromAB, 0) = 1  -- if entered from the AB side, posting status will be checked in the where clause
				Or (isnull(abi.FromAB, 0) = 0 AND inv.Posted >= @PostStatus)  -- if entered from the Reg side, check posting status now
				)
			), 0)
		 -- No Sales Taxes	 
		- ISNULL((
		    Select ISNULL(Sum(abit.Amount), 0)
			from tInvoiceAdvanceBillTax abit (nolock) 
			inner join tInvoiceAdvanceBill abi (nolock) on abit.AdvBillInvoiceKey = abi.AdvBillInvoiceKey and abit.InvoiceKey = abi.InvoiceKey   
			inner join tInvoice inv (nolock) on abit.InvoiceKey = inv.InvoiceKey
			Where abit.AdvBillInvoiceKey = i.InvoiceKey and inv.PostingDate <= @AsOfDate
			--And inv.Posted >= @PostStatus
			And (
				-- added for 480759
				isnull(abi.FromAB, 0) = 1  -- if entered from the AB side, posting status will be checked in the where clause
				Or (isnull(abi.FromAB, 0) = 0 AND inv.Posted >= @PostStatus)  -- if entered from the Reg side, check posting status now
				)
			), 0)
			 
			as AmountPaid
		,i.OfficeKey
		,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
		,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
		,i.InvoiceKey
	From
		tInvoice i (nolock) 
		LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
		LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	Where
		i.CompanyKey = @CompanyKey 
	And	i.PostingDate <= @AsOfDate 
	And	i.AdvanceBill = 1 	
	--And	(@GLCompanyKey IS NULL OR ISNULL(i.GLCompanyKey, 0) = @GLCompanyKey) 
	AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	-- Reduce # of records upfront
	  and (
			(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)

	And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	And	(@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey) 
	And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey)
	And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	And i.Posted >= @PostStatus	
	AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)

	-- issue 253288 this is a patch to fix a data corruption situation
	-- an advance bill rec was over applied
	DELETE #ARAging WHERE ABS(AppliedAmount) > ABS(BilledAmount)

	 -- also insert the real invoices where they have adv bills applied but after the date.
	 Insert Into #ARAging
	 (InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	 ,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	 
	 Select
	  i.InvoiceKey
	  ,i.GLCompanyKey
	  ,''Rev AB''
	  ,i.Posted
	  ,i.ClientKey
	  ,@CompanyKey
	  ,RTRIM(i.InvoiceNumber)
	  ,i.ClassKey
	  ,i.ProjectKey
	  ,i.ContactName
	  ,i.InvoiceDate
	  ,i.DueDate
	  ,i.PostingDate
	  ,0
	  ,abi.Amount
	   -- No Sales Taxes
	  - ISNULL((
		Select Sum(abit.Amount)
		From   tInvoiceAdvanceBillTax abit (nolock)
		Where  abit.InvoiceKey = i.InvoiceKey
		and    abit.AdvBillInvoiceKey = abi.AdvBillInvoiceKey
	   ),0)
	  ,i.OfficeKey
	  ,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
	  ,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
	  ,i.InvoiceKey
	 From tInvoice i (nolock) 
	  inner join tInvoiceAdvanceBill abi (nolock) on i.InvoiceKey = abi.InvoiceKey
	  inner join tInvoice ab (nolock) on ab.InvoiceKey = abi.AdvBillInvoiceKey
	  LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
	  LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	 Where i.CompanyKey = @CompanyKey 
	  and ab.PostingDate > @AsOfDate 
	  and i.PostingDate <= @AsOfDate
	  AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	  --AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	  -- Reduce # of records upfront
	  and (
			(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)

	  And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	  And (@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	  And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	  And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	  And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey)
	  And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager) 
	  And i.Posted >= @PostStatus
	  AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	  AND  isnull(abi.FromAB,0) = 0	-- because there is no reversal on the real invoice side when FromAB=1 (the reversal takes place with the AB invoice)
	  And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)

 -- 480759 reversals when the AB is not posted and the reg invoice is posted in the window 	
	Insert Into #ARAging
	 (InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	 ,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	 
	 Select
	  i.InvoiceKey
	  ,i.GLCompanyKey
	  ,''Rev AB''
	  ,i.Posted
	  ,i.ClientKey
	  ,@CompanyKey
	  ,RTRIM(i.InvoiceNumber)
	  ,i.ClassKey
	  ,i.ProjectKey
	  ,i.ContactName
	  ,i.InvoiceDate
	  ,i.DueDate
	  ,i.PostingDate
	  ,0
	  ,abi.Amount
	   -- No Sales Taxes
	  - ISNULL((
		Select Sum(abit.Amount)
		From   tInvoiceAdvanceBillTax abit (nolock)
		Where  abit.InvoiceKey = i.InvoiceKey
		and    abit.AdvBillInvoiceKey = abi.AdvBillInvoiceKey
	   ),0)
	  ,i.OfficeKey
	  ,ISNULL(p.AccountManager, c.AccountManagerKey) AS AccountManager
	  ,ISNULL(p.ProjectManager, c.ProjectManagerKey) AS ProjectManager
	  ,i.InvoiceKey
	 From tInvoice i (nolock) 
	  inner join tInvoiceAdvanceBill abi (nolock) on i.InvoiceKey = abi.InvoiceKey
	  inner join tInvoice ab (nolock) on ab.InvoiceKey = abi.AdvBillInvoiceKey
	  LEFT JOIN tProject p (nolock) ON i.ProjectKey = p.ProjectKey
	  LEFT JOIN tCompany c (nolock) on i.ClientKey = c.CompanyKey
	 Where i.CompanyKey = @CompanyKey 
	  and ab.PostingDate <= @AsOfDate 
	  and i.PostingDate <= @AsOfDate
	  AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(i.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

	  --AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(i.GLCompanyKey, 0)) )

	  -- Reduce # of records upfront
	  and (
			(ISNULL(@ClientKeys, '''') <> '''' and i.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR i.ClientKey = @ClientKey))
		)

	  And (@ParentClientKey IS NULL or (i.ClientKey = @ParentClientKey or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
	  And (@ClassKey IS NULL OR i.ClassKey = @ClassKey)  -- Reduce # of records upfront
	  And (@ProjectKey IS NULL OR i.ProjectKey = @ProjectKey)
	  And (@HasCampaignKeys IS NULL OR i.CampaignKey IN (Select CampaignKey from #CampaignKeys))
	  And (@ARAccountKey IS NULL OR ISNULL(i.ARAccountKey, 0) = @ARAccountKey) 
	  And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
	  And i.Posted >= @PostStatus
		And ab.Posted = 0 -- The AB is unposted, it it was posted it will be accounted for earlier
	  AND (@MultiCurrency = 0
		OR isnull(i.CurrencyID, '''') = isnull(@CurrencyID, '''') )
	  AND  isnull(abi.FromAB,0) = 0 
	  And (@LiabilityAccountKey IS NULL or i.LiabilityAccountKey = @LiabilityAccountKey)
 
END

if @Receipts = 1 And @ProjectKey is Null
BEGIN
	-- Add Back any unapplied receipts from the client
	
	Insert Into #ARAging
	(InvoiceKey, GLCompanyKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, ClassKey, ProjectKey, ContactName, InvoiceDate, DueDate, PostingDate
	,BilledAmount, AppliedAmount, OfficeKey, AccountManager, ProjectManager, RealInvoiceKey)
	Select
	 ch.CheckKey
	 ,ch.GLCompanyKey
	,''Open Rec''
	,ch.Posted
	,ch.ClientKey
	,@CompanyKey
	,RTRIM(ch.ReferenceNumber)
	,ch.ClassKey
	,null -- no project
	,NULL  -- No Contact
	,ch.CheckDate
	,ch.CheckDate
	,ch.PostingDate
	,ch.CheckAmount * -1
	-- Need to include all applications regardless of invoice or sales account to deal with items directly applied to sales on a mixed payment
	,ISNULL((
		Select SUM(ca.Amount) * -1
		from tCheckAppl ca (nolock)
		Where ca.CheckKey = ch.CheckKey
		And   ca.InvoiceKey IS NULL  -- This will create discrepancy with spRptStatementRunningBalance
		),0)
	-- Issue 175324: Because of step Invoice 2, I think that we have to differentiate between payments and prepayments
	+ ISNULL((
	    Select SUM(ca.Amount) * -1
		from tCheckAppl ca (nolock)
		inner join tInvoice inv (nolock) on inv.InvoiceKey = ca.InvoiceKey
		Where ca.CheckKey = ch.CheckKey
		And   inv.Posted >= @PostStatus
		And   isnull(ca.Prepay, 0) = 0 -- Added for 175324
		--And   inv.PostingDate <= @AsOfDate  Removed this date because we always add back receipt amts applied after the window
		),0)
	-- Added for 175324
	+ ISNULL((
	    Select SUM(ca.Amount) * -1
		from tCheckAppl ca (nolock)
		inner join tInvoice inv (nolock) on inv.InvoiceKey = ca.InvoiceKey
		Where ca.CheckKey = ch.CheckKey
		And   inv.Posted >= @PostStatus
		And   isnull(ca.Prepay, 0) =1
		And   inv.PostingDate <= @AsOfDate 
		),0)		
	,null -- OfficeKey
	,''''
	,''''
	,null -- null InvoiceKey because we could have several invoices applied to the check
From
	tCheck ch (nolock)
	Inner Join tCompany c (nolock) On ch.ClientKey = c.CompanyKey
	-- join with a possible voided check, make sure that CheckKey <> VoidCheckKey on the void
	left Join tCheck void_ch (nolock) on ch.CheckKey = void_ch.VoidCheckKey and void_ch.CheckKey <> void_ch.VoidCheckKey 
Where
	c.OwnerCompanyKey = @CompanyKey 
And	ch.PostingDate <= @AsOfDate 
And	(isnull(ch.VoidCheckKey, 0) = 0
	Or
	void_ch.PostingDate > @AsOfDate
	)
--And	(@GLCompanyKey IS NULL OR ISNULL(ch.GLCompanyKey, 0) = @GLCompanyKey)
AND (
		-- All companies
		(
		@HasGLCompanyKeys = 0 AND
			(
			@GLCompanyKey = -1 OR 
				( ISNULL(@GLCompanyKey, 0) = ISNULL(ch.GLCompanyKey, 0) )
			)
		)
		-- Or specific companies requested (Is Blank will be 0 in #GLCompanyKeys)
		OR ISNULL(ch.GLCompanyKey, 0) IN (SELECT GLCompanyKey FROM #GLCompanyKeys)	
		)

--AND (@GLCompanyKey = -1 Or (ISNULL(@GLCompanyKey, 0) = ISNULL(ch.GLCompanyKey, 0)) ) 

-- Reduce # of records upfront
	  and (
			(ISNULL(@ClientKeys, '''') <> '''' and ch.ClientKey in (select ClientKey from #clients)) -- If the user passed in multiple client keys.
			or (ISNULL(@ClientKeys, '''') = '''' and (@ClientKey IS NULL OR ch.ClientKey = @ClientKey))
		)

And (@ParentClientKey IS NULL or (ch.ClientKey = @ParentClientKey or ch.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey))) 
And	(@ClassKey IS NULL OR ch.ClassKey = @ClassKey)  -- Reduce # of records upfront
And (@AccountManager IS NULL OR c.AccountManagerKey = @AccountManager)
And ch.Posted >= @PostStatus	
AND (@MultiCurrency = 0
		OR isnull(ch.CurrencyID, '''') = isnull(@CurrencyID, '''') )


	
END
	
-- If the user selected ALL Companies and we restrict
-- we need to look up into tUserGLCompanyAccess
IF @GLCompanyKey =-1 AND @RestrictToGLCompany = 1
begin
	update #ARAging set GLCompanyKey = isnull(GLCompanyKey, 0)

	-- this does not delete null GLCompanyKey
	delete #ARAging
	where  GLCompanyKey not in (select GLCompanyKey from tUserGLCompanyAccess where UserKey = @UserKey) 
end

-- Only keep open amounts
DELETE #ARAging 
WHERE  #ARAging.BilledAmount - #ARAging.AppliedAmount = 0


-- Multiply by -1 or 1
-- For client statements where you want to show what the client owes us
-- Advance Bill should show as negative
-- Real invoices should show as positive
-- Otherwise they would both show as postive doubling in effect what the client owes

-- For AR Aging
-- Advance Bill should show as positive

UPDATE #ARAging
SET    BilledAmount = cast(@AdvBillMultiplier as money) * BilledAmount
		,AppliedAmount = cast(@AdvBillMultiplier as money) *  AppliedAmount
WHERE  Type = ''Open AB''	

-- adding in parent company keys
	update #ARAging
	set    #ARAging.ParentCompanyKey = c.CompanyKey
	from   tCompany c (nolock)
	where  #ARAging.ClientKey = c.CompanyKey
	and    isnull(c.ParentCompany, 0) = 1

		update #ARAging
	set    #ARAging.ParentCompanyKey = c.ParentCompanyKey
	from   tCompany c (nolock)
	where  #ARAging.ClientKey = c.CompanyKey
	and    ISNULL(c.ParentCompany, 0) = 0
	and    ISNULL(c.ParentCompanyKey, 0) > 0

IF @RollUpMatching > 0 
BEGIN
	Insert Into #ARAging
	(InvoiceKey, RealInvoiceKey, Type, Posted, ClientKey, LoggedCompanyKey, InvoiceNumber, InvoiceDate, DueDate, PostingDate, BilledAmount, AppliedAmount, Action)
	Select
	MAX(InvoiceKey),MAX(RealInvoiceKey), Type, MAX(Posted), ClientKey, LoggedCompanyKey, InvoiceNumber, MAX(InvoiceDate), MAX(DueDate), MAX(PostingDate), SUM(BilledAmount), SUM(AppliedAmount), 1
	
	From #ARAging
	Group By
	Type, ClientKey, LoggedCompanyKey, InvoiceNumber

	Delete #ARAging Where Action is null

END

-- If the report is grouped by project, make sure that there is no difference between NULL and 0 
update #ARAging  set ProjectKey = NULL where ProjectKey = 0



if @CustomizationBarbarian = 1
begin
	-- summary
	IF @SummaryOnly = 1
		select ''AR''									as APType
			  ,''Y3B2''								as AffiliateCompanyCode
			  ,''12010111''							as LocalGLAccountCode
			  ,''12010111''							as CheilGLAccountCode
			  ,c.CustomerID
			  ,''D''									as DebitCreditIndicator
			  ,''USD''								as TransactionCurrency
			  ,SUM(BilledAmount - AppliedAmount)	as AmountInTransactionCurrency
			  ,''USD''								as HoldingCompanyCurrency
			  ,SUM(BilledAmount - AppliedAmount)	as AmountInHoldingCompanyCurrency

		from  #ARAging 
				inner join tCompany c (NOLOCK) on #ARAging.ClientKey = c.CompanyKey 
		where  #ARAging.Type in (''Invoice'', ''Credit'')
		GROUP BY  #ARAging.ClientKey, c.CustomerID
		ORDER BY c.CustomerID
	ELSE
		select ''AR''									as APType
			  ,''Y3B2''								as AffiliateCompanyCode
			  ,''12010111''							as LocalGLAccountCode
			  ,''12010111''							as CheilGLAccountCode
			   ,c.CustomerID

			  -- detail part
			  ,left(#ARAging.InvoiceNumber, 18)		as DocumentNumber
			  ,''''									as LineItem -- I have no way to get this (need client invoice line)
			  ,convert(varchar(35),#ARAging.PostingDate, 112)	as PostingDate
			  ,convert(varchar(35),#ARAging.DueDate, 112)		as InvoiceDueDate
			   
			  ,''D''									as DebitCreditIndicator
			  ,''USD''								as TransactionCurrency
			  ,BilledAmount - AppliedAmount			as AmountInTransactionCurrency
			  ,''USD''								as HoldingCompanyCurrency
			  ,BilledAmount - AppliedAmount			as AmountInHoldingCompanyCurrency

			  ,''''									as Reference
			  ,''''									as [Text]

		from  #ARAging 
				inner join tCompany c (NOLOCK) on #ARAging.ClientKey = c.CompanyKey  
		where  #ARAging.Type in (''Invoice'', ''Credit'')
		ORDER BY c.CustomerID
end
else
begin
	-- @CustomizationBarbarian = 0

IF @SummaryOnly = 1
BEGIN
	
	IF @AgingDateOption = 1		-- Using InvoiceDate
	BEGIN
		IF @OlderThan > 0 --Remove records that are not older than @OlderThan
			DELETE	#ARAging
			WHERE	DATEDIFF(d, InvoiceDate, @AsOfDate) <= @OlderThan

		SELECT #ARAging.ClientKey
				,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName 
				,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName 
				,SUM(BilledAmount - AppliedAmount) as NetAmount
				,SUM(CASE WHEN DATEDIFF(d, InvoiceDate, @AsOfDate) <= @Days1 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period0
				,SUM(CASE WHEN DATEDIFF(d, InvoiceDate, @AsOfDate) > @Days1 and DATEDIFF(d, InvoiceDate, @AsOfDate) <= @Days2 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period1
				,SUM(CASE WHEN DATEDIFF(d, InvoiceDate, @AsOfDate) > @Days2 and DATEDIFF(d, InvoiceDate, @AsOfDate) <= @Days3 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period2
				,SUM(CASE WHEN DATEDIFF(d, InvoiceDate, @AsOfDate) > @Days3 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period3
		FROM	#ARAging 
		inner join tCompany cl (nolock) on #ARAging.ClientKey = cl.CompanyKey
		GROUP BY  #ARAging.ClientKey, RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')), cl.CompanyName
		ORDER BY  RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME''))

	END
	ELSE IF @AgingDateOption = 2		-- Using PostingDate
	BEGIN
		IF @OlderThan > 0 --Remove records that are not older than @OlderThan
			DELETE	#ARAging
			WHERE	DATEDIFF(d, PostingDate, @AsOfDate) <= @OlderThan
	
		SELECT #ARAging.ClientKey
				,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName 
				,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName 
				,SUM(BilledAmount - AppliedAmount) as NetAmount
				,SUM(CASE WHEN DATEDIFF(d, PostingDate, @AsOfDate) <= @Days1 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period0
				,SUM(CASE WHEN DATEDIFF(d, PostingDate, @AsOfDate) > @Days1 and DATEDIFF(d, PostingDate, @AsOfDate) <= @Days2 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period1
				,SUM(CASE WHEN DATEDIFF(d, PostingDate, @AsOfDate) > @Days2 and DATEDIFF(d, PostingDate, @AsOfDate) <= @Days3 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period2
				,SUM(CASE WHEN DATEDIFF(d, PostingDate, @AsOfDate) > @Days3 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period3
		FROM	#ARAging 
		inner join tCompany cl (nolock) on #ARAging.ClientKey = cl.CompanyKey
		GROUP BY  #ARAging.ClientKey, RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')), cl.CompanyName
		ORDER BY  RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME''))

	END
	ELSE		-- Using Due Date
	BEGIN
		IF @OlderThan > 0 --Remove records that are not older than @OlderThan
			DELETE	#ARAging
			WHERE	DATEDIFF(d, DueDate, @AsOfDate) <= @OlderThan

		SELECT #ARAging.ClientKey
				,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName 
				,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName 
				,SUM(BilledAmount - AppliedAmount) as NetAmount
				,SUM(CASE WHEN DATEDIFF(d, DueDate, @AsOfDate) <= @Days1 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period0
				,SUM(CASE WHEN DATEDIFF(d, DueDate, @AsOfDate) > @Days1 and DATEDIFF(d, DueDate, @AsOfDate) <= @Days2 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period1
				,SUM(CASE WHEN DATEDIFF(d, DueDate, @AsOfDate) > @Days2 and DATEDIFF(d, DueDate, @AsOfDate) <= @Days3 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period2
				,SUM(CASE WHEN DATEDIFF(d, DueDate, @AsOfDate) > @Days3 
					THEN BilledAmount - AppliedAmount ELSE 0 END) as Period3
		FROM	#ARAging 
		inner join tCompany cl (nolock) on #ARAging.ClientKey = cl.CompanyKey
		GROUP BY  #ARAging.ClientKey, RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')), cl.CompanyName
		ORDER BY  RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME''))
	END	
END
ELSE
BEGIN
	-- Detail mode

	IF @AgingDateOption = 1		-- Using InvoiceDate
	BEGIN
		IF @OlderThan > 0 --Remove records that are not older than @OlderThan
			DELETE	#ARAging
			WHERE	DATEDIFF(d, InvoiceDate, @AsOfDate) <= @OlderThan

		Select #ARAging.*
		,RTRIM(ISNULL(cl.CustomerID, ''NO ID'')) as ClientID
		,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName
		,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName 
		,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) + RTRIM(ISNULL('' - '' + cl.CustomerID, '''')) as ClientFullName2 
		,BilledAmount - AppliedAmount as NetAmount
		,CASE WHEN DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) <= @Days1 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period0
		,CASE WHEN DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) > @Days1 and DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) <= @Days2 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period1
		,CASE WHEN DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) > @Days2 and DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) <= @Days3 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period2
		,CASE WHEN DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) > @Days3 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period3
		,DATEDIFF(d, #ARAging.InvoiceDate, @AsOfDate) AS Days
		,BilledAmount - AppliedAmount as OpenAmount
		,c.CompanyName
		,ad.Address1
		,ad.Address2
		,ad.Address3
		,ad.City
		,ad.State
		,ad.PostalCode
		,ad.Country
		,cl.CompanyName as BCompanyName
		,case when cl.BillingAddressKey IS NOT NULL then bad.Address1
		else cad.Address1 end as BAddress1,	
		case when cl.BillingAddressKey IS NOT NULL then bad.Address2
		else cad.Address2 end as BAddress2,	
		case when cl.BillingAddressKey IS NOT NULL then bad.Address3
		else cad.Address3 end as BAddress3,
		case when cl.BillingAddressKey IS NOT NULL then bad.City
		else cad.City end as BCity,
		case when cl.BillingAddressKey IS NOT NULL then bad.State
		else cad.State end as BState,	
		case when cl.BillingAddressKey IS NOT NULL then bad.PostalCode
		else cad.PostalCode end as BPostalCode,
		case when cl.BillingAddressKey IS NOT NULL then bad.Country
		else cad.Country end as BCountry

		,ISNULL(o.OfficeName, ''NO OFFICE'') AS OfficeName
		,ISNULL(am.FirstName + '' '' + am.LastName, ''NO ACCOUNT MANAGER'') AS AccountManagerName 
		,ISNULL(pm.FirstName + '' '' + pm.LastName, ''NO PROJECT MANAGER'') AS ProjectManagerName
		,ISNULL(pc.CompanyName , ''NO PARENT COMPANY'') AS ParentCompanyName
		,p.ProjectNumber
		,CASE
			WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
				RTRIM(ISNULL(ca.CampaignID, ''''))
			ELSE
				RTRIM(ISNULL(p.ProjectNumber, ''''))
			END AS ProjCamp
		,CASE
			WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
				RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, ''''))
			ELSE
				RTRIM(ISNULL(p.ProjectNumber, '''')) + RTRIM(ISNULL('' - '' + p.ProjectName, '''')) 
			END AS ProjCampFullName
		,p.ProjectName
		,ISNULL(p.ProjectNumber, Null) + '' - '' + ISNULL(p.ProjectName, Null) AS ProjectFullName 
		,cp.ProductName
		,cd.DivisionName
		,RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, '''')) as CampaignFullName

		from #ARAging 
		inner join tCompany cl (nolock) on #ARAging.ClientKey = cl.CompanyKey
		inner join tCompany c (nolock) on #ARAging.LoggedCompanyKey = c.CompanyKey
		left outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
		left outer join tAddress cad (nolock) on cl.DefaultAddressKey = cad.AddressKey
		left outer join tAddress bad (nolock) on cl.BillingAddressKey = bad.AddressKey
		left outer join tOffice o (NOLOCK) on #ARAging.OfficeKey = o.OfficeKey 
		left outer join tUser am (NOLOCK) on #ARAging.AccountManager = am.UserKey
		left outer join tUser pm (NOLOCK) on #ARAging.ProjectManager = pm.UserKey
		left outer join tProject p (nolock) on #ARAging.ProjectKey = p.ProjectKey
		left outer join tCompany pc (nolock) on #ARAging.ParentCompanyKey = pc.CompanyKey
		LEFT JOIN tClientProduct cp (nolock) ON p.ClientProductKey = cp.ClientProductKey
		LEFT JOIN tClientDivision cd (nolock) ON p.ClientDivisionKey = cd.ClientDivisionKey
		LEFT JOIN tInvoice i (nolock) on #ARAging.RealInvoiceKey = i.InvoiceKey
		LEFT JOIN tCampaign ca (nolock) on i.CampaignKey = ca.CampaignKey

		Order By
			ISNULL(cl.CustomerID, ''NO ID''), #ARAging.DueDate, #ARAging.InvoiceNumber 
	END
	ELSE IF @AgingDateOption = 2		-- Using PostingDate
	BEGIN
		IF @OlderThan > 0 --Remove records that are not older than @OlderThan
			DELETE	#ARAging
			WHERE	DATEDIFF(d, PostingDate, @AsOfDate) <= @OlderThan

		Select #ARAging.*
		,RTRIM(ISNULL(cl.CustomerID, ''NO ID'')) as ClientID
		,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName
		,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName 
		,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) + RTRIM(ISNULL('' - '' + cl.CustomerID, '''')) as ClientFullName2 
		,BilledAmount - AppliedAmount as NetAmount
		,CASE WHEN DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) <= @Days1 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period0
		,CASE WHEN DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) > @Days1 and DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) <= @Days2 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period1
		,CASE WHEN DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) > @Days2 and DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) <= @Days3 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period2
		,CASE WHEN DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) > @Days3 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period3
		,DATEDIFF(d, #ARAging.PostingDate, @AsOfDate) AS Days
		,BilledAmount - AppliedAmount as OpenAmount
		,c.CompanyName
		,ad.Address1
		,ad.Address2
		,ad.Address3
		,ad.City
		,ad.State
		,ad.PostalCode
		,ad.Country
		,cl.CompanyName as BCompanyName
		,case when cl.BillingAddressKey IS NOT NULL then bad.Address1
		else cad.Address1 end as BAddress1,	
		case when cl.BillingAddressKey IS NOT NULL then bad.Address2
		else cad.Address2 end as BAddress2,	
		case when cl.BillingAddressKey IS NOT NULL then bad.Address3
		else cad.Address3 end as BAddress3,
		case when cl.BillingAddressKey IS NOT NULL then bad.City
		else cad.City end as BCity,
		case when cl.BillingAddressKey IS NOT NULL then bad.State
		else cad.State end as BState,	
		case when cl.BillingAddressKey IS NOT NULL then bad.PostalCode
		else cad.PostalCode end as BPostalCode,
		case when cl.BillingAddressKey IS NOT NULL then bad.Country
		else cad.Country end as BCountry

		,ISNULL(o.OfficeName, ''NO OFFICE'') AS OfficeName
		,ISNULL(am.FirstName + '' '' + am.LastName, ''NO ACCOUNT MANAGER'') AS AccountManagerName 
		,ISNULL(pm.FirstName + '' '' + pm.LastName, ''NO PROJECT MANAGER'') AS ProjectManagerName
		,ISNULL(pc.CompanyName , ''NO PARENT COMPANY'') AS ParentCompanyName
		,p.ProjectNumber
		,CASE
			WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
				RTRIM(ISNULL(ca.CampaignID, ''''))
			ELSE
				RTRIM(ISNULL(p.ProjectNumber, ''''))
			END AS ProjCamp
		,CASE
			WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
				RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, ''''))
			ELSE
				RTRIM(ISNULL(p.ProjectNumber, '''')) + RTRIM(ISNULL('' - '' + p.ProjectName, '''')) 
			END AS ProjCampFullName
		,p.ProjectName
		,ISNULL(p.ProjectNumber, Null) + '' - '' + ISNULL(p.ProjectName, Null) AS ProjectFullName 
		,cp.ProductName
		,cd.DivisionName
		,RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, '''')) as CampaignFullName

		from #ARAging 
		inner join tCompany cl (nolock) on #ARAging.ClientKey = cl.CompanyKey
		inner join tCompany c (nolock) on #ARAging.LoggedCompanyKey = c.CompanyKey
		left outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
		left outer join tAddress cad (nolock) on cl.DefaultAddressKey = cad.AddressKey
		left outer join tAddress bad (nolock) on cl.BillingAddressKey = bad.AddressKey
		left outer join tOffice o (nolock) on #ARAging.OfficeKey = o.OfficeKey
		left outer join tUser am (NOLOCK) on #ARAging.AccountManager = am.UserKey
		left outer join tUser pm (NOLOCK) on #ARAging.ProjectManager = pm.UserKey
		left outer join tProject p (nolock) on #ARAging.ProjectKey = p.ProjectKey
		left outer join tCompany pc (nolock) on #ARAging.ParentCompanyKey = pc.CompanyKey
		LEFT JOIN tClientProduct cp (nolock) ON p.ClientProductKey = cp.ClientProductKey
		LEFT JOIN tClientDivision cd (nolock) ON p.ClientDivisionKey = cd.ClientDivisionKey
		LEFT JOIN tInvoice i (nolock) on #ARAging.RealInvoiceKey = i.InvoiceKey
		LEFT JOIN tCampaign ca (nolock) on i.CampaignKey = ca.CampaignKey

		Order By
			ISNULL(cl.CustomerID, ''NO ID''), #ARAging.DueDate, #ARAging.InvoiceNumber
	END
	ELSE		-- Using Due Date
	BEGIN
		IF @OlderThan > 0 --Remove records that are not older than @OlderThan
			DELETE	#ARAging
			WHERE	DATEDIFF(d, DueDate, @AsOfDate) <= @OlderThan

		Select #ARAging.*
		,RTRIM(ISNULL(cl.CustomerID, ''NO ID'')) as ClientID
		,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) as ClientName
		,RTRIM(ISNULL(cl.CustomerID, '''')) + RTRIM(ISNULL('' - '' + cl.CompanyName, ''NO NAME'')) as ClientFullName 
		,RTRIM(ISNULL(cl.CompanyName, ''NO NAME'')) + RTRIM(ISNULL('' - '' + cl.CustomerID, '''')) as ClientFullName2 
		,BilledAmount - AppliedAmount as NetAmount
		,CASE WHEN DATEDIFF(d, #ARAging.DueDate, @AsOfDate) <= @Days1 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period0
		,CASE WHEN DATEDIFF(d, #ARAging.DueDate, @AsOfDate) > @Days1 and DATEDIFF(d, #ARAging.DueDate, @AsOfDate) <= @Days2 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period1
		,CASE WHEN DATEDIFF(d, #ARAging.DueDate, @AsOfDate) > @Days2 and DATEDIFF(d, #ARAging.DueDate, @AsOfDate) <= @Days3 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period2
		,CASE WHEN DATEDIFF(d, #ARAging.DueDate, @AsOfDate) > @Days3 
			THEN BilledAmount - AppliedAmount ELSE 0 END as Period3
		,DATEDIFF(d, #ARAging.DueDate, @AsOfDate) AS Days
		,BilledAmount - AppliedAmount as OpenAmount
		,c.CompanyName
		,ad.Address1
		,ad.Address2
		,ad.Address3
		,ad.City
		,ad.State
		,ad.PostalCode
		,ad.Country
		,cl.CompanyName as BCompanyName
		,case when cl.BillingAddressKey IS NOT NULL then bad.Address1
		else cad.Address1 end as BAddress1,	
		case when cl.BillingAddressKey IS NOT NULL then bad.Address2
		else cad.Address2 end as BAddress2,	
		case when cl.BillingAddressKey IS NOT NULL then bad.Address3
		else cad.Address3 end as BAddress3,
		case when cl.BillingAddressKey IS NOT NULL then bad.City
		else cad.City end as BCity,
		case when cl.BillingAddressKey IS NOT NULL then bad.State
		else cad.State end as BState,	
		case when cl.BillingAddressKey IS NOT NULL then bad.PostalCode
		else cad.PostalCode end as BPostalCode,
		case when cl.BillingAddressKey IS NOT NULL then bad.Country
		else cad.Country end as BCountry

		,ISNULL(o.OfficeName, ''NO OFFICE'') AS OfficeName
		,ISNULL(am.FirstName + '' '' + am.LastName, ''NO ACCOUNT MANAGER'') AS AccountManagerName 
		,ISNULL(pm.FirstName + '' '' + pm.LastName, ''NO PROJECT MANAGER'') AS ProjectManagerName
		,ISNULL(pc.CompanyName , ''NO PARENT COMPANY'') AS ParentCompanyName
		,p.ProjectNumber
		,CASE
			WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
				RTRIM(ISNULL(ca.CampaignID, ''''))
			ELSE
				RTRIM(ISNULL(p.ProjectNumber, ''''))
			END AS ProjCamp
		,CASE
			WHEN ISNULL(ca.CampaignKey, 0) > 0 THEN 
				RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, ''''))
			ELSE
				RTRIM(ISNULL(p.ProjectNumber, '''')) + RTRIM(ISNULL('' - '' + p.ProjectName, '''')) 
			END AS ProjCampFullName
		,p.ProjectName
		,ISNULL(p.ProjectNumber, Null) + '' - '' + ISNULL(p.ProjectName, Null) AS ProjectFullName 
		,cp.ProductName
		,cd.DivisionName
		,RTRIM(ISNULL(ca.CampaignID, '''')) + RTRIM(ISNULL('' - '' + ca.CampaignName, '''')) as CampaignFullName

		from #ARAging 
		inner join tCompany cl (nolock) on #ARAging.ClientKey = cl.CompanyKey
		inner join tCompany c (nolock) on #ARAging.LoggedCompanyKey = c.CompanyKey
		left outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
		left outer join tAddress cad (nolock) on cl.DefaultAddressKey = cad.AddressKey
		left outer join tAddress bad (nolock) on cl.BillingAddressKey = bad.AddressKey
		left outer join tOffice o (nolock) on #ARAging.OfficeKey = o.OfficeKey
		left outer join tUser am (NOLOCK) on #ARAging.AccountManager = am.UserKey
		left outer join tUser pm (NOLOCK) on #ARAging.ProjectManager = pm.UserKey
		left outer join tProject p (nolock) on #ARAging.ProjectKey = p.ProjectKey
		left outer join tCompany pc (nolock) on #ARAging.ParentCompanyKey = pc.CompanyKey
		LEFT JOIN tClientProduct cp (nolock) ON p.ClientProductKey = cp.ClientProductKey
		LEFT JOIN tClientDivision cd (nolock) ON p.ClientDivisionKey = cd.ClientDivisionKey
		LEFT JOIN tInvoice i (nolock) on #ARAging.RealInvoiceKey = i.InvoiceKey
		LEFT JOIN tCampaign ca (nolock) on i.CampaignKey = ca.CampaignKey

		Order By
			ISNULL(cl.CustomerID, ''NO ID''), #ARAging.DueDate, #ARAging.InvoiceNumber
	END

  END -- @SummaryMode = 0

END -- @CustomizationBarbarian = 0

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptTimeSuggestDaily]'
GO
IF OBJECT_ID(N'[dbo].[sptTimeSuggestDaily]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   PROCEDURE [dbo].[sptTimeSuggestDaily]
(
      @CompanyKey     int
    , @UserKey        int
    , @WorkDate       date
    , @TopN           int = 10
    , @Debug          bit = 0
    , @MinInc         decimal(6,2) = 0.25
    , @MaxCandidates  int = 150
    , @LookbackDays   int = 365
    , @BacktestMode   bit = 0
)
AS
/*  
|| When      Who Rel           What  
|| 04/14/25  QMD 26.06.14.0000 (724849) - Created proc  
*/ 

BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    ------------------------------------------------------------
    -- Guard rails
    ------------------------------------------------------------
    IF @TopN IS NULL OR @TopN < 1 SET @TopN = 10;
    IF @TopN > 50 SET @TopN = 50;

    IF @MinInc IS NULL OR @MinInc <= 0 SET @MinInc = 0.25;
    IF @MaxCandidates IS NULL OR @MaxCandidates < 10 SET @MaxCandidates = 150;
    IF @LookbackDays IS NULL OR @LookbackDays < 30 SET @LookbackDays = 365;

    DECLARE @FromDate date = DATEADD(day, -@LookbackDays, @WorkDate);

    -- Monday=1 .. Sunday=7
    DECLARE @Dow tinyint = ((DATEDIFF(day, ''19000101'', @WorkDate) % 7) + 1);

    ------------------------------------------------------------
    -- RIGHTS
    ------------------------------------------------------------
    DECLARE
          @RK_TimeCompletedTask     int = 90920
        , @RK_TimeAllServices       int = 100120
        , @RK_TimeAllTasks          int = 100130
        , @RK_TimeNoCompletedPreds  int = 100950;

    DECLARE
          @CanTimeCompletedTask    bit = 0
        , @CanTimeAllServices      bit = 0
        , @CanTimeAllTasks         bit = 0
        , @CanTimeNoCompletedPreds bit = 0;

    SELECT @CanTimeCompletedTask =
        CASE WHEN EXISTS
        (
            SELECT 1
            FROM dbo.tRightAssigned ra
            WHERE ra.RightKey = @RK_TimeCompletedTask
              AND ra.EntityKey = @UserKey
        ) THEN 1 ELSE 0 END;

    SELECT @CanTimeAllServices =
        CASE WHEN EXISTS
        (
            SELECT 1
            FROM dbo.tRightAssigned ra
            WHERE ra.RightKey = @RK_TimeAllServices
              AND ra.EntityKey = @UserKey
        ) THEN 1 ELSE 0 END;

    SELECT @CanTimeAllTasks =
        CASE WHEN EXISTS
        (
            SELECT 1
            FROM dbo.tRightAssigned ra
            WHERE ra.RightKey = @RK_TimeAllTasks
              AND ra.EntityKey = @UserKey
        ) THEN 1 ELSE 0 END;

    SELECT @CanTimeNoCompletedPreds =
        CASE WHEN EXISTS
        (
            SELECT 1
            FROM dbo.tRightAssigned ra
            WHERE ra.RightKey = @RK_TimeNoCompletedPreds
              AND ra.EntityKey = @UserKey
        ) THEN 1 ELSE 0 END;

    ------------------------------------------------------------
    -- RECENT typical daily hours
    ------------------------------------------------------------
    DECLARE @TypicalDaily decimal(12,2);

    ;WITH Daily AS
    (
        SELECT
              CAST(t.WorkDate AS date) AS WorkDate
            , CAST(SUM(CASE WHEN ISNULL(t.ActualHours, 0) > 0 THEN t.ActualHours ELSE 0 END) AS decimal(12,2)) AS DayHours
        FROM dbo.tTime t
        INNER JOIN dbo.tProject p
            ON p.ProjectKey = t.ProjectKey
           AND p.CompanyKey = t.CompanyKey
        INNER JOIN dbo.tTask tk
            ON tk.TaskKey = t.TaskKey
           AND tk.ProjectKey = t.ProjectKey
        INNER JOIN dbo.tService s
            ON s.ServiceKey = t.ServiceKey
           AND s.CompanyKey = t.CompanyKey
        WHERE t.CompanyKey = @CompanyKey
          AND t.UserKey = @UserKey
          AND t.WorkDate >= DATEADD(day, -90, @WorkDate)
          AND t.WorkDate <  @WorkDate
          AND ISNULL(p.Deleted,0) = 0
          AND ISNULL(p.Closed,0) = 0
          AND ISNULL(p.Active,1) = 1
          AND ISNULL(tk.NoTimeEntry,0) = 0
          AND ISNULL(s.Active,1) = 1
        GROUP BY CAST(t.WorkDate AS date)
    )
    SELECT @TypicalDaily = CAST(AVG(CAST(DayHours AS float)) AS decimal(12,2))
    FROM Daily;

    IF @TypicalDaily IS NULL SET @TypicalDaily = 8.00;

    ------------------------------------------------------------
    -- Hours already booked today
    ------------------------------------------------------------
    DECLARE @BookedToday decimal(12,2);

    IF @BacktestMode = 1
    BEGIN
        SET @BookedToday = 0;
    END
    ELSE
    BEGIN
        SELECT @BookedToday =
            CAST(SUM(CASE WHEN ISNULL(t.ActualHours,0) > 0 THEN t.ActualHours ELSE 0 END) AS decimal(12,2))
        FROM dbo.tTime t
        INNER JOIN dbo.tProject p
            ON p.ProjectKey = t.ProjectKey
           AND p.CompanyKey = t.CompanyKey
        INNER JOIN dbo.tTask tk
            ON tk.TaskKey = t.TaskKey
           AND tk.ProjectKey = t.ProjectKey
        INNER JOIN dbo.tService s
            ON s.ServiceKey = t.ServiceKey
           AND s.CompanyKey = t.CompanyKey
        WHERE t.CompanyKey = @CompanyKey
          AND t.UserKey = @UserKey
          AND CAST(t.WorkDate AS date) = @WorkDate
          AND ISNULL(p.Deleted,0) = 0
          AND ISNULL(p.Closed,0) = 0
          AND ISNULL(p.Active,1) = 1
          AND ISNULL(tk.NoTimeEntry,0) = 0
          AND ISNULL(s.Active,1) = 1;
    END

    IF @BookedToday IS NULL SET @BookedToday = 0;

    DECLARE @Remaining decimal(12,2) = @TypicalDaily - @BookedToday;
    IF @Remaining < 0 SET @Remaining = 0;

    ------------------------------------------------------------
    -- Stage 1: today rows
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#Today'') IS NOT NULL DROP TABLE #Today;
    CREATE TABLE #Today
    (
          ProjectKey   int NOT NULL
        , TaskKey      int NOT NULL
        , ServiceKey   int NOT NULL
        , HoursToday   decimal(12,2) NOT NULL
        , PRIMARY KEY (ProjectKey, TaskKey, ServiceKey)
    );

    IF @BacktestMode = 0
    BEGIN
        INSERT INTO #Today
        (
              ProjectKey
            , TaskKey
            , ServiceKey
            , HoursToday
        )
        SELECT
              t.ProjectKey
            , t.TaskKey
            , t.ServiceKey
            , CAST(SUM(CASE WHEN ISNULL(t.ActualHours,0) > 0 THEN t.ActualHours ELSE 0 END) AS decimal(12,2))
        FROM dbo.tTime t
        WHERE t.CompanyKey = @CompanyKey
          AND t.UserKey = @UserKey
          AND CAST(t.WorkDate AS date) = @WorkDate
        GROUP BY
              t.ProjectKey
            , t.TaskKey
            , t.ServiceKey;
    END

    ------------------------------------------------------------
    -- Stage 2: history base
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#Hist'') IS NOT NULL DROP TABLE #Hist;
    CREATE TABLE #Hist
    (
          CompanyKey    int NOT NULL
        , UserKey       int NOT NULL
        , ProjectKey    int NOT NULL
        , TaskKey       int NOT NULL
        , ServiceKey    int NOT NULL
        , WorkDate      date NOT NULL
        , Hours         decimal(12,2) NOT NULL
        , HistDow       tinyint NOT NULL
    );

    INSERT INTO #Hist
    (
          CompanyKey
        , UserKey
        , ProjectKey
        , TaskKey
        , ServiceKey
        , WorkDate
        , Hours
        , HistDow
    )
    SELECT
          t.CompanyKey
        , t.UserKey
        , t.ProjectKey
        , t.TaskKey
        , t.ServiceKey
        , CAST(t.WorkDate AS date)
        , CAST(t.ActualHours AS decimal(12,2))
        , CAST(((DATEDIFF(day, ''19000101'', CAST(t.WorkDate AS date)) % 7) + 1) AS tinyint)
    FROM dbo.tTime t
    INNER JOIN dbo.tProject p
        ON p.ProjectKey = t.ProjectKey
       AND p.CompanyKey = t.CompanyKey
    INNER JOIN dbo.tTask tk
        ON tk.TaskKey = t.TaskKey
       AND tk.ProjectKey = t.ProjectKey
    INNER JOIN dbo.tService s
        ON s.ServiceKey = t.ServiceKey
       AND s.CompanyKey = t.CompanyKey
    WHERE t.CompanyKey = @CompanyKey
      AND t.UserKey = @UserKey
      AND t.WorkDate >= @FromDate
      AND t.WorkDate <  @WorkDate
      AND ISNULL(t.ActualHours,0) > 0
      AND ISNULL(p.Deleted,0) = 0
      AND ISNULL(p.Closed,0) = 0
      AND ISNULL(p.Active,1) = 1
      AND ISNULL(tk.NoTimeEntry,0) = 0
      AND ISNULL(s.Active,1) = 1;

    ------------------------------------------------------------
    -- Stage 2B: USER WORK STYLE PROFILE
    ------------------------------------------------------------
    DECLARE
          @AvgProjectsPerDay decimal(9,4)
        , @AvgTasksPerDay    decimal(9,4)
        , @AvgEntrySize      decimal(9,4)
        , @ScatterScore      decimal(9,4)
        , @IsScatterUser     bit = 0;

    ;WITH DailyStats AS
    (
        SELECT
              h.WorkDate
            , COUNT(DISTINCT h.ProjectKey) AS ProjectCount
            , COUNT(DISTINCT h.TaskKey)    AS TaskCount
            , AVG(h.Hours)                 AS AvgEntrySize
        FROM #Hist h
        GROUP BY h.WorkDate
    )
    SELECT
          @AvgProjectsPerDay = AVG(CAST(ProjectCount AS decimal(9,4)))
        , @AvgTasksPerDay    = AVG(CAST(TaskCount AS decimal(9,4)))
        , @AvgEntrySize      = AVG(CAST(AvgEntrySize AS decimal(9,4)))
    FROM DailyStats;

    SET @ScatterScore =
          (ISNULL(@AvgProjectsPerDay,0) * 0.5)
        + (ISNULL(@AvgTasksPerDay,0) * 0.3)
        + (CASE WHEN ISNULL(@AvgEntrySize,0) <= 0.5 THEN 1 ELSE 0 END * 0.2);

    IF @ScatterScore >= 2.5
        SET @IsScatterUser = 1;

    ------------------------------------------------------------
    -- Stage 3: task candidate features from history
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#TaskHistFeatures'') IS NOT NULL DROP TABLE #TaskHistFeatures;
    CREATE TABLE #TaskHistFeatures
    (
          ProjectKey         int NOT NULL
        , TaskKey            int NOT NULL
        , ServiceKey         int NOT NULL
        , UsesLast7          int NOT NULL
        , UsesLast14         int NOT NULL
        , UsesLast30         int NOT NULL
        , UsesLast90         int NOT NULL
        , UsesLast365        int NOT NULL
        , LastUsedDate       date NULL
        , DaysSinceLastUse   int NULL
        , UsedSameDOW90      int NOT NULL
        , HoursToday         decimal(12,2) NOT NULL
        , AvgHours90         decimal(12,2) NULL
        , MedianHours90      decimal(12,2) NULL
        , UsedYesterday      bit NOT NULL
        , UsesLast3WorkDays  int NOT NULL
        , TaskRecencyScore   decimal(18,6) NOT NULL
        , TaskRepeatScore    decimal(18,6) NOT NULL
        , CandidateSource    varchar(20) NOT NULL
        , PRIMARY KEY (ProjectKey, TaskKey, ServiceKey)
    );

    ;WITH Agg AS
    (
        SELECT
              h.ProjectKey
            , h.TaskKey
            , h.ServiceKey
            , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -7,  @WorkDate) THEN 1 ELSE 0 END) AS UsesLast7
            , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -14, @WorkDate) THEN 1 ELSE 0 END) AS UsesLast14
            , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -30, @WorkDate) THEN 1 ELSE 0 END) AS UsesLast30
            , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -90, @WorkDate) THEN 1 ELSE 0 END) AS UsesLast90
            , COUNT(*) AS UsesLast365
            , MAX(h.WorkDate) AS LastUsedDate
            , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -90, @WorkDate) AND h.HistDow = @Dow THEN 1 ELSE 0 END) AS UsedSameDOW90
            , CAST(AVG(CASE WHEN h.WorkDate >= DATEADD(day, -90, @WorkDate) THEN CAST(h.Hours AS float) END) AS decimal(12,2)) AS AvgHours90
            , MAX(CASE WHEN h.WorkDate = DATEADD(day, -1, @WorkDate) THEN 1 ELSE 0 END) AS UsedYesterday
            , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -4, @WorkDate) THEN 1 ELSE 0 END) AS UsesLast3WorkDays
        FROM #Hist h
        GROUP BY
              h.ProjectKey
            , h.TaskKey
            , h.ServiceKey
    ),
    Med AS
    (
        SELECT DISTINCT
              h.ProjectKey
            , h.TaskKey
            , h.ServiceKey
            , CAST(
                PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY h.Hours)
                OVER (PARTITION BY h.ProjectKey, h.TaskKey, h.ServiceKey)
              AS decimal(12,2)) AS MedianHours90
        FROM #Hist h
        WHERE h.WorkDate >= DATEADD(day, -90, @WorkDate)
    )
    INSERT INTO #TaskHistFeatures
    (
          ProjectKey
        , TaskKey
        , ServiceKey
        , UsesLast7
        , UsesLast14
        , UsesLast30
        , UsesLast90
        , UsesLast365
        , LastUsedDate
        , DaysSinceLastUse
        , UsedSameDOW90
        , HoursToday
        , AvgHours90
        , MedianHours90
        , UsedYesterday
        , UsesLast3WorkDays
        , TaskRecencyScore
        , TaskRepeatScore
        , CandidateSource
    )
    SELECT TOP (@MaxCandidates)
          a.ProjectKey
        , a.TaskKey
        , a.ServiceKey
        , a.UsesLast7
        , a.UsesLast14
        , a.UsesLast30
        , a.UsesLast90
        , a.UsesLast365
        , a.LastUsedDate
        , DATEDIFF(day, a.LastUsedDate, @WorkDate) AS DaysSinceLastUse
        , a.UsedSameDOW90
        , ISNULL(t.HoursToday, 0.00) AS HoursToday
        , a.AvgHours90
        , m.MedianHours90
        , CAST(ISNULL(a.UsedYesterday, 0) AS bit) AS UsedYesterday
        , ISNULL(a.UsesLast3WorkDays, 0) AS UsesLast3WorkDays
        , CAST(
            CASE
                WHEN a.LastUsedDate IS NULL THEN 0.00
                WHEN DATEDIFF(day, a.LastUsedDate, @WorkDate) <= 1 THEN 1.00
                WHEN DATEDIFF(day, a.LastUsedDate, @WorkDate) <= 3 THEN 0.85
                WHEN DATEDIFF(day, a.LastUsedDate, @WorkDate) <= 7 THEN 0.70
                WHEN DATEDIFF(day, a.LastUsedDate, @WorkDate) <= 14 THEN 0.50
                WHEN DATEDIFF(day, a.LastUsedDate, @WorkDate) <= 30 THEN 0.25
                ELSE 0.05
            END
          AS decimal(18,6)) AS TaskRecencyScore
        , CAST(
              (0.50 * CASE
                          WHEN a.UsesLast7  >= 2 THEN 1.00
                          WHEN a.UsesLast7  = 1 THEN 0.70
                          ELSE 0.00
                      END)
            + (0.30 * CASE
                          WHEN a.UsesLast14 >= 4 THEN 1.00
                          WHEN a.UsesLast14 >= 2 THEN 0.70
                          WHEN a.UsesLast14 = 1 THEN 0.35
                          ELSE 0.00
                      END)
            + (0.20 * CASE
                          WHEN a.UsesLast30 >= 6 THEN 1.00
                          WHEN a.UsesLast30 >= 3 THEN 0.70
                          WHEN a.UsesLast30 >= 1 THEN 0.30
                          ELSE 0.00
                      END)
          AS decimal(18,6)) AS TaskRepeatScore
        , ''History''
    FROM Agg a
    LEFT JOIN Med m
        ON m.ProjectKey = a.ProjectKey
       AND m.TaskKey = a.TaskKey
       AND m.ServiceKey = a.ServiceKey
    LEFT JOIN #Today t
        ON t.ProjectKey = a.ProjectKey
       AND t.TaskKey = a.TaskKey
       AND t.ServiceKey = a.ServiceKey
    ORDER BY
          CASE WHEN ISNULL(t.HoursToday,0) > 0 THEN 1 ELSE 0 END DESC
        , a.UsesLast30 DESC
        , a.LastUsedDate DESC;

    ------------------------------------------------------------
    -- Stage 3B: assigned task seed
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#AssignedSeed'') IS NOT NULL DROP TABLE #AssignedSeed;
    CREATE TABLE #AssignedSeed
    (
          ProjectKey   int NOT NULL
        , TaskKey      int NOT NULL
        , ServiceKey   int NOT NULL
        , PRIMARY KEY (ProjectKey, TaskKey, ServiceKey)
    );

    INSERT INTO #AssignedSeed
    (
          ProjectKey
        , TaskKey
        , ServiceKey
    )
    SELECT DISTINCT
          tk.ProjectKey
        , ta.TaskKey
        , tk.ServiceKey
    FROM dbo.tTaskAssignment ta
    INNER JOIN dbo.tTask tk
        ON tk.TaskKey = ta.TaskKey
    INNER JOIN dbo.tProject p
        ON p.ProjectKey = tk.ProjectKey
       AND p.CompanyKey = @CompanyKey
    INNER JOIN dbo.tService s
        ON s.ServiceKey = tk.ServiceKey
       AND s.CompanyKey = @CompanyKey
    WHERE ta.UserKey = @UserKey
      AND tk.ServiceKey IS NOT NULL
      AND ISNULL(p.Deleted,0) = 0
      AND ISNULL(p.Closed,0) = 0
      AND ISNULL(p.Active,1) = 1
      AND ISNULL(tk.NoTimeEntry,0) = 0
      AND ISNULL(s.Active,1) = 1
      AND (@CanTimeCompletedTask = 1 OR tk.ActComplete IS NULL)
      AND (@CanTimeNoCompletedPreds = 1 OR ISNULL(tk.PredecessorsComplete,1) = 1);

    INSERT INTO #TaskHistFeatures
    (
          ProjectKey
        , TaskKey
        , ServiceKey
        , UsesLast7
        , UsesLast14
        , UsesLast30
        , UsesLast90
        , UsesLast365
        , LastUsedDate
        , DaysSinceLastUse
        , UsedSameDOW90
        , HoursToday
        , AvgHours90
        , MedianHours90
        , UsedYesterday
        , UsesLast3WorkDays
        , TaskRecencyScore
        , TaskRepeatScore
        , CandidateSource
    )
    SELECT
          a.ProjectKey
        , a.TaskKey
        , a.ServiceKey
        , 0
        , 0
        , 0
        , 0
        , 0
        , NULL
        , NULL
        , 0
        , ISNULL(t.HoursToday, 0.00)
        , NULL
        , NULL
        , CAST(0 AS bit)
        , 0
        , CAST(0.00 AS decimal(18,6))
        , CAST(0.00 AS decimal(18,6))
        , ''Assigned''
    FROM #AssignedSeed a
    LEFT JOIN #Today t
        ON t.ProjectKey = a.ProjectKey
       AND t.TaskKey = a.TaskKey
       AND t.ServiceKey = a.ServiceKey
    WHERE NOT EXISTS
    (
        SELECT 1
        FROM #TaskHistFeatures c
        WHERE c.ProjectKey = a.ProjectKey
          AND c.TaskKey = a.TaskKey
          AND c.ServiceKey = a.ServiceKey
    );

    ------------------------------------------------------------
    -- Stage 3C: project team lookup
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#ProjectTeam'') IS NOT NULL DROP TABLE #ProjectTeam;
    CREATE TABLE #ProjectTeam
    (
          ProjectKey int NOT NULL
        , UserKey    int NOT NULL
        , PRIMARY KEY (ProjectKey, UserKey)
    );

    INSERT INTO #ProjectTeam
    (
          ProjectKey
        , UserKey
    )
    SELECT DISTINCT
          a.ProjectKey
        , a.UserKey
    FROM dbo.tAssignment a
    WHERE a.UserKey = @UserKey;

    ------------------------------------------------------------
    -- Stage 3D: task dates
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#TaskDates'') IS NOT NULL DROP TABLE #TaskDates;
    CREATE TABLE #TaskDates
    (
          TaskKey             int NOT NULL
        , UserKey             int NOT NULL
        , EffectiveStartDate  date NULL
        , EffectiveEndDate    date NULL
        , TaskDateScore       decimal(9,6) NOT NULL
        , PRIMARY KEY (TaskKey, UserKey)
    );

    ;WITH DistinctTasks AS
    (
        SELECT DISTINCT c.TaskKey
        FROM #TaskHistFeatures c
    )
    INSERT INTO #TaskDates
    (
          TaskKey
        , UserKey
        , EffectiveStartDate
        , EffectiveEndDate
        , TaskDateScore
    )
    SELECT
          dt.TaskKey
        , @UserKey
        , CAST(
            COALESCE
            (
                ta.MinPlanStart,
                ta.MinMustStartOn,
                ta.MinBaseStart,
                ta.MinActStart,
                tk.PlanStart,
                tk.BaseStart,
                tk.ActStart
            ) AS date
          ) AS EffectiveStartDate
        , CAST(
            COALESCE
            (
                ta.MaxActComplete,
                ta.MaxPlanComplete,
                ta.MaxBaseComplete,
                tk.ActComplete,
                tk.PlanComplete,
                tk.BaseComplete
            ) AS date
          ) AS EffectiveEndDate
        , CAST(0.00 AS decimal(9,6)) AS TaskDateScore
    FROM DistinctTasks dt
    INNER JOIN dbo.tTask tk
        ON tk.TaskKey = dt.TaskKey
    OUTER APPLY
    (
        SELECT
              MIN(ta.PlanStart)    AS MinPlanStart
            , MIN(ta.MustStartOn)  AS MinMustStartOn
            , MIN(ta.BaseStart)    AS MinBaseStart
            , MIN(ta.ActStart)     AS MinActStart
            , MAX(ta.ActComplete)  AS MaxActComplete
            , MAX(ta.PlanComplete) AS MaxPlanComplete
            , MAX(ta.BaseComplete) AS MaxBaseComplete
        FROM dbo.tTaskAssignment ta
        WHERE ta.TaskKey = dt.TaskKey
          AND ta.UserKey = @UserKey
    ) ta;

    UPDATE td
       SET TaskDateScore =
            CAST(
                CASE
                    WHEN td.EffectiveStartDate IS NULL
                     AND td.EffectiveEndDate IS NULL
                        THEN 0.35

                    WHEN td.EffectiveStartDate IS NOT NULL
                     AND @WorkDate < DATEADD(day, -14, td.EffectiveStartDate)
                        THEN
                            CASE
                                WHEN DATEDIFF(day, @WorkDate, td.EffectiveStartDate) <= 30 THEN 0.35
                                WHEN DATEDIFF(day, @WorkDate, td.EffectiveStartDate) <= 60 THEN 0.10
                                ELSE 0.00
                            END

                    WHEN td.EffectiveEndDate IS NOT NULL
                     AND @WorkDate > DATEADD(day, 21, td.EffectiveEndDate)
                        THEN 0.15

                    WHEN @WorkDate BETWEEN DATEADD(day, -14, ISNULL(td.EffectiveStartDate, @WorkDate))
                                      AND DATEADD(day,  21, ISNULL(td.EffectiveEndDate, ISNULL(td.EffectiveStartDate, @WorkDate)))
                        THEN 1.00

                    ELSE 0.50
                END
            AS decimal(9,6))
    FROM #TaskDates td;

    ------------------------------------------------------------
    -- Stage 3E: task allocation lookup
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#TaskAlloc'') IS NOT NULL DROP TABLE #TaskAlloc;
    CREATE TABLE #TaskAlloc
    (
          TaskKey              int NOT NULL
        , TotalAllocatedHours  decimal(12,2) NULL
        , TotalActualHours     decimal(12,2) NULL
        , RemainingAllocHours  decimal(12,2) NULL
        , AllocationScore      decimal(9,6) NOT NULL
        , PRIMARY KEY (TaskKey)
    );

    ;WITH DistinctTasks AS
    (
        SELECT DISTINCT c.TaskKey
        FROM #TaskHistFeatures c
    )
    INSERT INTO #TaskAlloc
    (
          TaskKey
        , TotalAllocatedHours
        , TotalActualHours
        , RemainingAllocHours
        , AllocationScore
    )
    SELECT
          tk.TaskKey
        , CAST(ISNULL(tk.TotalAllocatedHours,0) AS decimal(12,2))
        , CAST(ISNULL(tk.TotalActualHours,0) AS decimal(12,2))
        , CAST(ISNULL(tk.TotalAllocatedHours,0) - ISNULL(tk.TotalActualHours,0) AS decimal(12,2))
        , CAST(
            CASE
                WHEN ISNULL(tk.AllowAllocatedHours,0) = 1
                 AND ISNULL(tk.TotalAllocatedHours,0) > 0
                 AND (ISNULL(tk.TotalAllocatedHours,0) - ISNULL(tk.TotalActualHours,0)) > 0
                    THEN 1.00
                WHEN ISNULL(tk.TotalAllocatedHours,0) > 0
                 AND (ISNULL(tk.TotalAllocatedHours,0) - ISNULL(tk.TotalActualHours,0)) > 0
                    THEN 0.90
                WHEN ISNULL(tk.TotalAllocatedHours,0) > 0
                    THEN 0.55
                WHEN ISNULL(tk.EstHours,0) > 0
                    THEN 0.35
                ELSE 0.00
            END
          AS decimal(9,6))
    FROM DistinctTasks dt
    INNER JOIN dbo.tTask tk
        ON tk.TaskKey = dt.TaskKey;

    ------------------------------------------------------------
    -- Stage 3F: project-level recurrence features
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#ProjectFeatures'') IS NOT NULL DROP TABLE #ProjectFeatures;
    CREATE TABLE #ProjectFeatures
    (
          ProjectKey             int NOT NULL PRIMARY KEY
        , ProjectUsesLast7       int NOT NULL
        , ProjectUsesLast14      int NOT NULL
        , ProjectUsesLast30      int NOT NULL
        , ProjectUsesLast90      int NOT NULL
        , ProjectLastUsedDate    date NULL
        , ProjectUsedSameDOW90   int NOT NULL
        , ProjectAvgHours90      decimal(12,2) NULL
        , ProjectRecencyScore    decimal(18,6) NOT NULL
        , ProjectRepeatScore     decimal(18,6) NOT NULL
    );

    INSERT INTO #ProjectFeatures
    (
          ProjectKey
        , ProjectUsesLast7
        , ProjectUsesLast14
        , ProjectUsesLast30
        , ProjectUsesLast90
        , ProjectLastUsedDate
        , ProjectUsedSameDOW90
        , ProjectAvgHours90
        , ProjectRecencyScore
        , ProjectRepeatScore
    )
    SELECT
          h.ProjectKey
        , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -7,  @WorkDate) THEN 1 ELSE 0 END)
        , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -14, @WorkDate) THEN 1 ELSE 0 END)
        , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -30, @WorkDate) THEN 1 ELSE 0 END)
        , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -90, @WorkDate) THEN 1 ELSE 0 END)
        , MAX(h.WorkDate)
        , SUM(CASE WHEN h.WorkDate >= DATEADD(day, -90, @WorkDate) AND h.HistDow = @Dow THEN 1 ELSE 0 END)
        , CAST(AVG(CASE WHEN h.WorkDate >= DATEADD(day, -90, @WorkDate) THEN CAST(h.Hours AS float) END) AS decimal(12,2))
        , CAST(
            CASE
                WHEN MAX(h.WorkDate) IS NULL THEN 0.00
                WHEN DATEDIFF(day, MAX(h.WorkDate), @WorkDate) <= 1 THEN 1.00
                WHEN DATEDIFF(day, MAX(h.WorkDate), @WorkDate) <= 3 THEN 0.85
                WHEN DATEDIFF(day, MAX(h.WorkDate), @WorkDate) <= 7 THEN 0.70
                WHEN DATEDIFF(day, MAX(h.WorkDate), @WorkDate) <= 14 THEN 0.50
                WHEN DATEDIFF(day, MAX(h.WorkDate), @WorkDate) <= 30 THEN 0.25
                ELSE 0.05
            END
          AS decimal(18,6))
        , CAST(
              (0.50 * CASE
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -7, @WorkDate) THEN 1 ELSE 0 END) >= 2 THEN 1.00
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -7, @WorkDate) THEN 1 ELSE 0 END) = 1 THEN 0.70
                          ELSE 0.00
                      END)
            + (0.30 * CASE
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -14, @WorkDate) THEN 1 ELSE 0 END) >= 4 THEN 1.00
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -14, @WorkDate) THEN 1 ELSE 0 END) >= 2 THEN 0.70
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -14, @WorkDate) THEN 1 ELSE 0 END) = 1 THEN 0.35
                          ELSE 0.00
                      END)
            + (0.20 * CASE
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -30, @WorkDate) THEN 1 ELSE 0 END) >= 6 THEN 1.00
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -30, @WorkDate) THEN 1 ELSE 0 END) >= 3 THEN 0.70
                          WHEN SUM(CASE WHEN h.WorkDate >= DATEADD(day, -30, @WorkDate) THEN 1 ELSE 0 END) >= 1 THEN 0.30
                          ELSE 0.00
                      END)
          AS decimal(18,6))
    FROM #Hist h
    GROUP BY h.ProjectKey;

    ------------------------------------------------------------
    -- Stage 4: project candidate pool
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#ProjectCandidates'') IS NOT NULL DROP TABLE #ProjectCandidates;
    CREATE TABLE #ProjectCandidates
    (
          ProjectKey             int NOT NULL PRIMARY KEY
        , ProjectUsesLast7       int NOT NULL
        , ProjectUsesLast14      int NOT NULL
        , ProjectUsesLast30      int NOT NULL
        , ProjectUsesLast90      int NOT NULL
        , ProjectLastUsedDate    date NULL
        , ProjectDaysSinceUse    int NULL
        , ProjectUsedSameDOW90   int NOT NULL
        , ProjectAvgHours90      decimal(12,2) NULL
        , IsProjectTeamMember    bit NOT NULL
        , ProjectRecencyScore    decimal(18,6) NOT NULL
        , ProjectRepeatScore     decimal(18,6) NOT NULL
        , ProjectScore           decimal(18,6) NOT NULL
        , ProjectTier            int NOT NULL
    );

    INSERT INTO #ProjectCandidates
    (
          ProjectKey
        , ProjectUsesLast7
        , ProjectUsesLast14
        , ProjectUsesLast30
        , ProjectUsesLast90
        , ProjectLastUsedDate
        , ProjectDaysSinceUse
        , ProjectUsedSameDOW90
        , ProjectAvgHours90
        , IsProjectTeamMember
        , ProjectRecencyScore
        , ProjectRepeatScore
        , ProjectScore
        , ProjectTier
    )
    SELECT
          p.ProjectKey
        , ISNULL(pf.ProjectUsesLast7,0)
        , ISNULL(pf.ProjectUsesLast14,0)
        , ISNULL(pf.ProjectUsesLast30,0)
        , ISNULL(pf.ProjectUsesLast90,0)
        , pf.ProjectLastUsedDate
        , CASE WHEN pf.ProjectLastUsedDate IS NULL THEN NULL ELSE DATEDIFF(day, pf.ProjectLastUsedDate, @WorkDate) END
        , ISNULL(pf.ProjectUsedSameDOW90,0)
        , pf.ProjectAvgHours90
        , CASE WHEN pt.ProjectKey IS NOT NULL THEN 1 ELSE 0 END
        , ISNULL(pf.ProjectRecencyScore,0.00)
        , ISNULL(pf.ProjectRepeatScore,0.00)
        , CAST(
              (0.45 * ISNULL(pf.ProjectRecencyScore,0.00))
            + (0.35 * ISNULL(pf.ProjectRepeatScore,0.00))
            + (0.20 * CASE
                          WHEN ISNULL(pf.ProjectUsedSameDOW90,0) >= 6 THEN 1.00
                          WHEN ISNULL(pf.ProjectUsedSameDOW90,0) >= 3 THEN 0.60
                          WHEN ISNULL(pf.ProjectUsedSameDOW90,0) >= 1 THEN 0.25
                          ELSE 0.00
                      END)
          AS decimal(18,6))
        , (
              CASE
                  WHEN pf.ProjectLastUsedDate IS NOT NULL AND DATEDIFF(day, pf.ProjectLastUsedDate, @WorkDate) <= 3 THEN 60
                  WHEN pf.ProjectLastUsedDate IS NOT NULL AND DATEDIFF(day, pf.ProjectLastUsedDate, @WorkDate) <= 7 THEN 35
                  WHEN pf.ProjectLastUsedDate IS NOT NULL AND DATEDIFF(day, pf.ProjectLastUsedDate, @WorkDate) <= 14 THEN 15
                  ELSE 0
              END
            + CASE
                  WHEN ISNULL(pf.ProjectUsesLast7,0)  >= 2 THEN 20
                  WHEN ISNULL(pf.ProjectUsesLast7,0)  = 1 THEN 10
                  ELSE 0
              END
            + CASE
                  WHEN ISNULL(pf.ProjectUsesLast14,0) >= 4 THEN 15
                  WHEN ISNULL(pf.ProjectUsesLast14,0) >= 2 THEN 10
                  WHEN ISNULL(pf.ProjectUsesLast14,0) = 1 THEN 5
                  ELSE 0
              END
            + CASE
                  WHEN ISNULL(pf.ProjectUsedSameDOW90,0) >= 3 THEN 15
                  WHEN ISNULL(pf.ProjectUsedSameDOW90,0) >= 1 THEN 5
                  ELSE 0
              END
            + CASE
                  WHEN pt.ProjectKey IS NOT NULL THEN 10
                  ELSE 0
              END
          )
    FROM dbo.tProject p
    LEFT JOIN #ProjectFeatures pf
        ON pf.ProjectKey = p.ProjectKey
    LEFT JOIN #ProjectTeam pt
        ON pt.ProjectKey = p.ProjectKey
       AND pt.UserKey = @UserKey
    WHERE p.CompanyKey = @CompanyKey
      AND ISNULL(p.Deleted,0) = 0
      AND ISNULL(p.Closed,0) = 0
      AND ISNULL(p.Active,1) = 1
      AND (
            pf.ProjectKey IS NOT NULL
            OR pt.ProjectKey IS NOT NULL
          );

    ------------------------------------------------------------
    -- Stage 5: join project candidates to task candidates
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#Eligible'') IS NOT NULL DROP TABLE #Eligible;
    CREATE TABLE #Eligible
    (
          ProjectKey             int NOT NULL
        , TaskKey                int NOT NULL
        , ServiceKey             int NOT NULL
        , UsesLast7              int NOT NULL
        , UsesLast14             int NOT NULL
        , UsesLast30             int NOT NULL
        , UsesLast90             int NOT NULL
        , UsesLast365            int NOT NULL
        , LastUsedDate           date NULL
        , DaysSinceLastUse       int NULL
        , UsedSameDOW90          int NOT NULL
        , HoursToday             decimal(12,2) NOT NULL
        , AvgHours90             decimal(12,2) NULL
        , MedianHours90          decimal(12,2) NULL
        , CandidateSource        varchar(20) NOT NULL
        , IsAssignedTask         bit NOT NULL
        , IsServiceAligned       bit NOT NULL
        , IsAssignedNewWork      bit NOT NULL
        , IsProjectTeamMember    bit NOT NULL
        , EffectiveStartDate     date NULL
        , EffectiveEndDate       date NULL
        , TaskDateScore          decimal(9,6) NOT NULL
        , TotalAllocatedHours    decimal(12,2) NULL
        , TotalActualHours       decimal(12,2) NULL
        , RemainingAllocHours    decimal(12,2) NULL
        , AllocationScore        decimal(9,6) NOT NULL
        , ProjectUsesLast7       int NOT NULL
        , ProjectUsesLast14      int NOT NULL
        , ProjectUsesLast30      int NOT NULL
        , ProjectUsesLast90      int NOT NULL
        , ProjectLastUsedDate    date NULL
        , ProjectDaysSinceUse    int NULL
        , ProjectUsedSameDOW90   int NOT NULL
        , ProjectAvgHours90      decimal(12,2) NULL
        , ProjectRecencyScore    decimal(18,6) NOT NULL
        , ProjectRepeatScore     decimal(18,6) NOT NULL
        , ProjectScore           decimal(18,6) NOT NULL
        , ProjectTier            int NOT NULL
        , TaskRecencyScore       decimal(18,6) NOT NULL
        , TaskRepeatScore        decimal(18,6) NOT NULL
        , TaskWithinProjectScore decimal(18,6) NOT NULL
        , UsedYesterday          bit NOT NULL
        , UsesLast3WorkDays      int NOT NULL
        , StaleTaskPenalty       decimal(18,6) NOT NULL
        , MomentumScore          decimal(18,6) NOT NULL
        , BusinessTier           int NOT NULL
        , PRIMARY KEY (ProjectKey, TaskKey, ServiceKey)
    );

    INSERT INTO #Eligible
    (
          ProjectKey
        , TaskKey
        , ServiceKey
        , UsesLast7
        , UsesLast14
        , UsesLast30
        , UsesLast90
        , UsesLast365
        , LastUsedDate
        , DaysSinceLastUse
        , UsedSameDOW90
        , HoursToday
        , AvgHours90
        , MedianHours90
        , CandidateSource
        , IsAssignedTask
        , IsServiceAligned
        , IsAssignedNewWork
        , IsProjectTeamMember
        , EffectiveStartDate
        , EffectiveEndDate
        , TaskDateScore
        , TotalAllocatedHours
        , TotalActualHours
        , RemainingAllocHours
        , AllocationScore
        , ProjectUsesLast7
        , ProjectUsesLast14
        , ProjectUsesLast30
        , ProjectUsesLast90
        , ProjectLastUsedDate
        , ProjectDaysSinceUse
        , ProjectUsedSameDOW90
        , ProjectAvgHours90
        , ProjectRecencyScore
        , ProjectRepeatScore
        , ProjectScore
        , ProjectTier
        , TaskRecencyScore
        , TaskRepeatScore
        , TaskWithinProjectScore
        , UsedYesterday
        , UsesLast3WorkDays
        , StaleTaskPenalty
        , MomentumScore
        , BusinessTier
    )
    SELECT
          c.ProjectKey
        , c.TaskKey
        , c.ServiceKey
        , c.UsesLast7
        , c.UsesLast14
        , c.UsesLast30
        , c.UsesLast90
        , c.UsesLast365
        , c.LastUsedDate
        , c.DaysSinceLastUse
        , c.UsedSameDOW90
        , c.HoursToday
        , c.AvgHours90
        , c.MedianHours90
        , c.CandidateSource

        , CASE
              WHEN EXISTS
              (
                  SELECT 1
                  FROM #AssignedSeed a
                  WHERE a.ProjectKey = c.ProjectKey
                    AND a.TaskKey = c.TaskKey
                    AND a.ServiceKey = c.ServiceKey
              ) THEN 1 ELSE 0
          END

        , CASE
              WHEN @CanTimeAllServices = 1 THEN 1
              WHEN tk.ServiceKey IS NULL THEN 1
              WHEN tk.ServiceKey = c.ServiceKey THEN 1
              ELSE 0
          END

        , CASE
              WHEN EXISTS
              (
                  SELECT 1
                  FROM #AssignedSeed a
                  WHERE a.ProjectKey = c.ProjectKey
                    AND a.TaskKey = c.TaskKey
                    AND a.ServiceKey = c.ServiceKey
              )
               AND ISNULL(c.UsesLast30,0) = 0
               AND ISNULL(c.HoursToday,0) = 0
              THEN 1 ELSE 0
          END

        , pc.IsProjectTeamMember
        , td.EffectiveStartDate
        , td.EffectiveEndDate
        , ISNULL(td.TaskDateScore, 0.35)
        , al.TotalAllocatedHours
        , al.TotalActualHours
        , al.RemainingAllocHours
        , ISNULL(al.AllocationScore, 0.00)
        , pc.ProjectUsesLast7
        , pc.ProjectUsesLast14
        , pc.ProjectUsesLast30
        , pc.ProjectUsesLast90
        , pc.ProjectLastUsedDate
        , pc.ProjectDaysSinceUse
        , pc.ProjectUsedSameDOW90
        , pc.ProjectAvgHours90
        , pc.ProjectRecencyScore
        , pc.ProjectRepeatScore
        , pc.ProjectScore
        , pc.ProjectTier
        , c.TaskRecencyScore
        , c.TaskRepeatScore

        , CAST(
              (0.35 * c.TaskRecencyScore)
            + (0.35 * c.TaskRepeatScore)
            + (0.15 * CASE
                          WHEN c.UsedSameDOW90 >= 6 THEN 1.0
                          WHEN c.UsedSameDOW90 >= 3 THEN 0.6
                          WHEN c.UsedSameDOW90 >= 1 THEN 0.3
                          ELSE 0.0
                      END)
            + (0.15 * CASE WHEN c.HoursToday > 0 THEN 1.0 ELSE 0.0 END)
          AS decimal(18,6))

        , c.UsedYesterday
        , c.UsesLast3WorkDays

        , CAST(
            CASE
                WHEN c.LastUsedDate IS NULL THEN 0.20
                WHEN c.DaysSinceLastUse > 21 AND c.UsesLast30 <= 1 THEN 0.35
                WHEN c.DaysSinceLastUse > 14 AND c.UsesLast30 <= 2 THEN 0.25
                WHEN c.DaysSinceLastUse > 10 AND c.TaskRecencyScore < 0.50 AND c.TaskRepeatScore < 0.40 THEN 0.18
                WHEN c.DaysSinceLastUse > 7 AND
                     (
                         (0.35 * c.TaskRecencyScore)
                       + (0.35 * c.TaskRepeatScore)
                       + (0.15 * CASE
                                     WHEN c.UsedSameDOW90 >= 6 THEN 1.0
                                     WHEN c.UsedSameDOW90 >= 3 THEN 0.6
                                     WHEN c.UsedSameDOW90 >= 1 THEN 0.3
                                     ELSE 0.0
                                 END)
                       + (0.15 * CASE WHEN c.HoursToday > 0 THEN 1.0 ELSE 0.0 END)
                     ) < 0.35
                    THEN 0.12
                ELSE 0.00
            END
          AS decimal(18,6))

        , CAST(
              (CASE WHEN c.UsedYesterday = 1 THEN 1.00 ELSE 0.00 END * 0.60)
            + (CASE
                  WHEN c.UsesLast3WorkDays >= 3 THEN 1.00
                  WHEN c.UsesLast3WorkDays = 2 THEN 0.70
                  WHEN c.UsesLast3WorkDays = 1 THEN 0.30
                  ELSE 0.00
               END * 0.40)
          AS decimal(18,6))

        , (
              CASE
                  WHEN EXISTS
                  (
                      SELECT 1
                      FROM #AssignedSeed a
                      WHERE a.ProjectKey = c.ProjectKey
                        AND a.TaskKey = c.TaskKey
                        AND a.ServiceKey = c.ServiceKey
                  ) THEN 100 ELSE 0
              END
            + CASE
                  WHEN @CanTimeAllServices = 1 THEN 20
                  WHEN tk.ServiceKey IS NULL THEN 20
                  WHEN tk.ServiceKey = c.ServiceKey THEN 20
                  ELSE 0
              END
            + CASE WHEN pc.IsProjectTeamMember = 1 THEN 35 ELSE 0 END
            + CASE
                  WHEN ISNULL(td.TaskDateScore,0.35) >= 0.90 THEN 30
                  WHEN ISNULL(td.TaskDateScore,0.35) >= 0.50 THEN 15
                  ELSE 0
              END
            + CASE
                  WHEN ISNULL(al.AllocationScore,0.00) >= 0.90 THEN 25
                  WHEN ISNULL(al.AllocationScore,0.00) >= 0.35 THEN 10
                  ELSE 0
              END
            + CASE
                  WHEN EXISTS
                  (
                      SELECT 1
                      FROM #AssignedSeed a
                      WHERE a.ProjectKey = c.ProjectKey
                        AND a.TaskKey = c.TaskKey
                        AND a.ServiceKey = c.ServiceKey
                  )
                   AND ISNULL(c.UsesLast30,0) = 0
                   AND ISNULL(c.HoursToday,0) = 0
                  THEN 10 ELSE 0
              END
          )
    FROM #TaskHistFeatures c
    INNER JOIN #ProjectCandidates pc
        ON pc.ProjectKey = c.ProjectKey
    INNER JOIN dbo.tProject p
        ON p.ProjectKey = c.ProjectKey
       AND p.CompanyKey = @CompanyKey
    INNER JOIN dbo.tTask tk
        ON tk.TaskKey = c.TaskKey
       AND tk.ProjectKey = c.ProjectKey
    INNER JOIN dbo.tService s
        ON s.ServiceKey = c.ServiceKey
       AND s.CompanyKey = @CompanyKey
    LEFT JOIN #TaskDates td
        ON td.TaskKey = c.TaskKey
       AND td.UserKey = @UserKey
    LEFT JOIN #TaskAlloc al
        ON al.TaskKey = c.TaskKey
    WHERE ISNULL(p.Deleted,0) = 0
      AND ISNULL(p.Closed,0) = 0
      AND ISNULL(p.Active,1) = 1
      AND ISNULL(tk.NoTimeEntry,0) = 0
      AND ISNULL(s.Active,1) = 1
      AND (@CanTimeCompletedTask = 1 OR tk.ActComplete IS NULL)
      AND (@CanTimeNoCompletedPreds = 1 OR ISNULL(tk.PredecessorsComplete,1) = 1)
      AND (
            @CanTimeAllServices = 1
            OR tk.ServiceKey IS NULL
            OR tk.ServiceKey = c.ServiceKey
          );

    ------------------------------------------------------------
    -- Stage 6: final scoring
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#Scored'') IS NOT NULL DROP TABLE #Scored;
    CREATE TABLE #Scored
    (
          RankNo                 int NULL
        , ProjectKey             int NOT NULL
        , TaskKey                int NOT NULL
        , ServiceKey             int NOT NULL
        , SuggestedHours         decimal(12,2) NOT NULL
        , Score                  decimal(18,6) NOT NULL
        , Confidence             decimal(9,6) NOT NULL
        , Reason1                varchar(200) NULL
        , Reason2                varchar(200) NULL
        , ProjectScore           decimal(18,6) NOT NULL
        , TaskWithinProjectScore decimal(18,6) NOT NULL
        , BusinessBoostScore     decimal(18,6) NOT NULL
        , FinalScore             decimal(18,6) NOT NULL
        , BusinessTier           int NOT NULL
        , ProjectTier            int NOT NULL
        , HoursToday             decimal(12,2) NOT NULL
        , UsesLast30             int NOT NULL
        , LastUsedDate           date NULL
        , ProjectUsesLast30      int NOT NULL
        , ProjectLastUsedDate    date NULL
        , PRIMARY KEY (ProjectKey, TaskKey, ServiceKey)
    );

    INSERT INTO #Scored
    (
          ProjectKey
        , TaskKey
        , ServiceKey
        , SuggestedHours
        , Score
        , Confidence
        , Reason1
        , Reason2
        , ProjectScore
        , TaskWithinProjectScore
        , BusinessBoostScore
        , FinalScore
        , BusinessTier
        , ProjectTier
        , HoursToday
        , UsesLast30
        , LastUsedDate
        , ProjectUsesLast30
        , ProjectLastUsedDate
    )
    SELECT
          e.ProjectKey
        , e.TaskKey
        , e.ServiceKey

        , CAST(ROUND(rs.RawSuggestedHours / @MinInc, 0) * @MinInc AS decimal(12,2))
        , CAST(rs.FinalScore AS decimal(18,6))
        , CAST(CASE WHEN rs.FinalScore > 1 THEN 1 WHEN rs.FinalScore < 0 THEN 0 ELSE rs.FinalScore END AS decimal(9,6))

        , CAST(
            CONCAT(
                ''Scatter='', @IsScatterUser,
                ''; Assign='', e.IsAssignedTask,
                ''; Team='', e.IsProjectTeamMember,
                ''; Service='', e.IsServiceAligned,
                ''; Mom='', CONVERT(varchar(20), e.MomentumScore),
                ''; Stale='', CONVERT(varchar(20), e.StaleTaskPenalty),
                ''; Gate='', CONVERT(varchar(20), rs.WeakTaskGate)
            ) AS varchar(200)
          )

        , CAST(
            CONCAT(
                ''TaskRec='', CONVERT(varchar(20), e.TaskRecencyScore),
                ''; TaskRep='', CONVERT(varchar(20), e.TaskRepeatScore),
                ''; ProjRec='', CONVERT(varchar(20), e.ProjectRecencyScore),
                ''; ProjRep='', CONVERT(varchar(20), e.ProjectRepeatScore),
                ''; PTier='', e.ProjectTier
            ) AS varchar(200)
          )

        , e.ProjectScore
        , e.TaskWithinProjectScore
        , rs.BusinessBoostScore
        , rs.FinalScore
        , e.BusinessTier
        , e.ProjectTier
        , e.HoursToday
        , e.UsesLast30
        , e.LastUsedDate
        , e.ProjectUsesLast30
        , e.ProjectLastUsedDate
    FROM #Eligible e
    CROSS APPLY
    (
        SELECT
              CAST(
                  (0.25 * CASE WHEN e.IsAssignedTask = 1 THEN 1.0 ELSE 0.0 END)
                + (0.10 * CASE WHEN e.IsServiceAligned = 1 THEN 1.0 ELSE 0.0 END)
                + (0.15 * CASE WHEN e.IsAssignedNewWork = 1 THEN 1.0 ELSE 0.0 END)
                + (0.15 * CASE WHEN e.IsProjectTeamMember = 1 THEN 1.0 ELSE 0.0 END)
                + (0.20 * e.TaskDateScore)
                + (0.15 * e.AllocationScore)
              AS decimal(18,6)
              ) AS BusinessBoostScore

            , CAST(
                CASE
                    WHEN e.TaskWithinProjectScore < 0.20
                     AND e.UsesLast30 <= 1
                     AND ISNULL(e.HoursToday,0) = 0
                     AND (e.LastUsedDate IS NULL OR DATEDIFF(day, e.LastUsedDate, @WorkDate) > 14)
                        THEN 0.20

                    WHEN e.TaskWithinProjectScore < 0.30
                     AND e.UsesLast30 <= 2
                     AND ISNULL(e.HoursToday,0) = 0
                     AND (e.LastUsedDate IS NULL OR DATEDIFF(day, e.LastUsedDate, @WorkDate) > 10)
                        THEN 0.45

                    ELSE 1.00
                END
              AS decimal(18,6)
              ) AS WeakTaskGate

            , CAST(
                CASE
                    WHEN @IsScatterUser = 1 THEN
                        (
                              (0.34 * e.ProjectScore)
                            + (0.34 * e.TaskWithinProjectScore)
                            + (0.18 *
                                  (
                                      (0.25 * CASE WHEN e.IsAssignedTask = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.10 * CASE WHEN e.IsServiceAligned = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.15 * CASE WHEN e.IsAssignedNewWork = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.15 * CASE WHEN e.IsProjectTeamMember = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.20 * e.TaskDateScore)
                                    + (0.15 * e.AllocationScore)
                                  )
                              )
                            + (0.14 * e.MomentumScore)
                        )
                        *
                        (CASE
                            WHEN e.TaskWithinProjectScore < 0.20
                             AND e.UsesLast30 <= 1
                             AND ISNULL(e.HoursToday,0) = 0
                             AND (e.LastUsedDate IS NULL OR DATEDIFF(day, e.LastUsedDate, @WorkDate) > 14)
                                THEN 0.20
                            WHEN e.TaskWithinProjectScore < 0.30
                             AND e.UsesLast30 <= 2
                             AND ISNULL(e.HoursToday,0) = 0
                             AND (e.LastUsedDate IS NULL OR DATEDIFF(day, e.LastUsedDate, @WorkDate) > 10)
                                THEN 0.45
                            ELSE 1.00
                         END)
                        - e.StaleTaskPenalty

                    ELSE
                        (
                              (0.22 * e.ProjectScore)
                            + (0.53 * e.TaskWithinProjectScore)
                            + (0.15 *
                                  (
                                      (0.25 * CASE WHEN e.IsAssignedTask = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.10 * CASE WHEN e.IsServiceAligned = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.15 * CASE WHEN e.IsAssignedNewWork = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.15 * CASE WHEN e.IsProjectTeamMember = 1 THEN 1.0 ELSE 0.0 END)
                                    + (0.20 * e.TaskDateScore)
                                    + (0.15 * e.AllocationScore)
                                  )
                              )
                            + (0.20 * e.MomentumScore)
                        )
                        *
                        (CASE
                            WHEN e.TaskWithinProjectScore < 0.20
                             AND e.UsesLast30 <= 1
                             AND ISNULL(e.HoursToday,0) = 0
                             AND (e.LastUsedDate IS NULL OR DATEDIFF(day, e.LastUsedDate, @WorkDate) > 14)
                                THEN 0.20
                            WHEN e.TaskWithinProjectScore < 0.30
                             AND e.UsesLast30 <= 2
                             AND ISNULL(e.HoursToday,0) = 0
                             AND (e.LastUsedDate IS NULL OR DATEDIFF(day, e.LastUsedDate, @WorkDate) > 10)
                                THEN 0.45
                            ELSE 1.00
                         END)
                        - e.StaleTaskPenalty
                END
              AS decimal(18,6)
              ) AS FinalScore

            , CAST(
                CASE
                    WHEN e.HoursToday > 0 THEN
                        CASE
                            WHEN @Remaining <= 0 THEN 0
                            ELSE
                                CASE
                                    WHEN (COALESCE(e.MedianHours90, e.AvgHours90, e.ProjectAvgHours90, 1.00) - e.HoursToday) < 0 THEN 0
                                    WHEN (COALESCE(e.MedianHours90, e.AvgHours90, e.ProjectAvgHours90, 1.00) - e.HoursToday) > @Remaining THEN @Remaining
                                    ELSE (COALESCE(e.MedianHours90, e.AvgHours90, e.ProjectAvgHours90, 1.00) - e.HoursToday)
                                END
                        END
                    ELSE
                        CASE
                            WHEN @Remaining <= 0 THEN 0
                            WHEN COALESCE(e.MedianHours90, e.AvgHours90, e.ProjectAvgHours90, 1.00) > @Remaining THEN @Remaining
                            ELSE COALESCE(e.MedianHours90, e.AvgHours90, e.ProjectAvgHours90, 1.00)
                        END
                END
              AS decimal(12,4)
              ) AS RawSuggestedHours
    ) rs;

    ------------------------------------------------------------
    -- Rank
    ------------------------------------------------------------
    ;WITH BaseRank AS
    (
        SELECT
              ROW_NUMBER() OVER
              (
                  PARTITION BY s.ProjectKey
                  ORDER BY
                        s.Score DESC
                      , s.TaskWithinProjectScore DESC
                      , s.ProjectScore DESC
                      , s.HoursToday DESC
                      , s.UsesLast30 DESC
                      , s.LastUsedDate DESC
                      , s.ProjectTier DESC
                      , s.BusinessTier DESC
              ) AS ProjectTaskRN
            , *
        FROM #Scored s
        WHERE s.SuggestedHours > 0 OR s.HoursToday > 0
    ),
    Ranked AS
    (
        SELECT
              ROW_NUMBER() OVER
              (
                  ORDER BY
                        CASE WHEN @IsScatterUser = 1 THEN ProjectTaskRN ELSE 1 END
                      , Score DESC
                      , TaskWithinProjectScore DESC
                      , ProjectScore DESC
                      , HoursToday DESC
                      , UsesLast30 DESC
                      , LastUsedDate DESC
                      , ProjectUsesLast30 DESC
                      , ProjectLastUsedDate DESC
                      , BusinessTier DESC
                      , ProjectTier DESC
              ) AS RN
            , *
        FROM BaseRank
    )
    UPDATE s
       SET RankNo = r.RN
    FROM #Scored s
    INNER JOIN Ranked r
        ON r.ProjectKey = s.ProjectKey
       AND r.TaskKey = s.TaskKey
       AND r.ServiceKey = s.ServiceKey;

    ------------------------------------------------------------
    -- Output
    ------------------------------------------------------------
    IF @Debug = 1
    BEGIN
        SELECT
              @TypicalDaily             AS TypicalDaily
            , @BookedToday              AS BookedToday
            , @Remaining                AS Remaining
            , @Dow                      AS TargetDOW
            , @CanTimeCompletedTask     AS CanTimeCompletedTask
            , @CanTimeAllServices       AS CanTimeAllServices
            , @CanTimeAllTasks          AS CanTimeAllTasks
            , @CanTimeNoCompletedPreds  AS CanTimeNoCompletedPreds
            , @AvgProjectsPerDay        AS AvgProjectsPerDay
            , @AvgTasksPerDay           AS AvgTasksPerDay
            , @AvgEntrySize             AS AvgEntrySize
            , @ScatterScore             AS ScatterScore
            , @IsScatterUser            AS IsScatterUser
            , @BacktestMode             AS BacktestMode;

        SELECT * FROM #Today ORDER BY HoursToday DESC;
        SELECT * FROM #TaskHistFeatures ORDER BY CandidateSource DESC, UsesLast30 DESC, LastUsedDate DESC;
        SELECT * FROM #AssignedSeed ORDER BY ProjectKey, TaskKey, ServiceKey;
        SELECT * FROM #ProjectTeam ORDER BY ProjectKey;
        SELECT * FROM #TaskDates ORDER BY TaskDateScore DESC, EffectiveStartDate, EffectiveEndDate;
        SELECT * FROM #TaskAlloc ORDER BY AllocationScore DESC, RemainingAllocHours DESC;
        SELECT * FROM #ProjectFeatures ORDER BY ProjectUsesLast30 DESC, ProjectLastUsedDate DESC;
        SELECT * FROM #ProjectCandidates ORDER BY ProjectTier DESC, ProjectScore DESC, ProjectUsesLast30 DESC, ProjectLastUsedDate DESC;
        SELECT * FROM #Eligible ORDER BY ProjectScore DESC, TaskWithinProjectScore DESC, MomentumScore DESC, BusinessTier DESC;
        SELECT * FROM #Scored ORDER BY RankNo, Score DESC, ProjectScore DESC, TaskWithinProjectScore DESC;
    END
    ELSE
    BEGIN
        SELECT TOP (@TopN)
              s.RankNo
            , s.ProjectKey
            , p.ProjectName
            , p.ProjectNumber
            , s.TaskKey
            , t.TaskName
            , t.TaskID
            , s.ServiceKey
            , sv.ServiceCode
            , sv.[Description] AS ServiceDescription
            , s.SuggestedHours
            , s.Score
            , s.Confidence
            , s.Reason1
            , s.Reason2
            , WorkDate = @WorkDate

            -- extra analysis columns
            , s.ProjectScore
            , s.TaskWithinProjectScore
            , s.BusinessTier
            , s.ProjectTier
            , s.HoursToday
            , s.UsesLast30
            , s.LastUsedDate
            , s.ProjectUsesLast30
            , s.ProjectLastUsedDate
        FROM #Scored s
        LEFT JOIN dbo.tProject p WITH (NOLOCK)
            ON p.ProjectKey = s.ProjectKey
        LEFT JOIN dbo.tTask t WITH (NOLOCK)
            ON t.TaskKey = s.TaskKey
        LEFT JOIN dbo.tService sv WITH (NOLOCK)
            ON sv.ServiceKey = s.ServiceKey
        WHERE s.RankNo IS NOT NULL
          AND ISNULL(s.SuggestedHours,0) > 0
        ORDER BY s.RankNo;
    END
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptTimeSuggestWeekly]'
GO
IF OBJECT_ID(N'[dbo].[sptTimeSuggestWeekly]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   PROCEDURE [dbo].[sptTimeSuggestWeekly]
(
      @CompanyKey     int
    , @UserKey        int
    , @WeekStartDate  date
    , @TopNPerDay     int = 5
    , @IncludeWeekend bit = 0
    , @MinInc         decimal(6,2) = 0.25
    , @MaxCandidates  int = 150
    , @LookbackDays   int = 365
    , @Debug          bit = 0
)
AS
/*  
|| When      Who Rel           What  
|| 04/14/25  QMD 26.06.14.0000 (724849) - Created proc  
*/  

BEGIN
    SET NOCOUNT ON;
    SET XACT_ABORT ON;

    IF @TopNPerDay IS NULL OR @TopNPerDay < 1 SET @TopNPerDay = 5;
    IF @TopNPerDay > 50 SET @TopNPerDay = 50;

    IF @MinInc IS NULL OR @MinInc <= 0 SET @MinInc = 0.25;
    IF @MaxCandidates IS NULL OR @MaxCandidates < 10 SET @MaxCandidates = 150;
    IF @LookbackDays IS NULL OR @LookbackDays < 30 SET @LookbackDays = 365;

    DECLARE @WeekEndDate date = DATEADD(day, 6, @WeekStartDate);

    ------------------------------------------------------------
    -- Days to process
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#Days'') IS NOT NULL DROP TABLE #Days;

    CREATE TABLE #Days
    (
          SeqNo    int IDENTITY(1,1) NOT NULL PRIMARY KEY
        , WorkDate date NOT NULL
    );

    INSERT INTO #Days (WorkDate)
    VALUES
          (@WeekStartDate)
        , (DATEADD(day, 1, @WeekStartDate))
        , (DATEADD(day, 2, @WeekStartDate))
        , (DATEADD(day, 3, @WeekStartDate))
        , (DATEADD(day, 4, @WeekStartDate));

    IF @IncludeWeekend = 1
    BEGIN
        INSERT INTO #Days (WorkDate)
        VALUES
              (DATEADD(day, 5, @WeekStartDate))
            , (DATEADD(day, 6, @WeekStartDate));
    END;

    ------------------------------------------------------------
    -- Combined weekly results
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#WeeklyOut'') IS NOT NULL DROP TABLE #WeeklyOut;

    CREATE TABLE #WeeklyOut
    (
          WorkDate               date NOT NULL
        , DayOfWeek              tinyint NOT NULL
        , RankNo                 int NOT NULL
        , ProjectKey             int NOT NULL
        , ProjectName            varchar(500) NULL
        , ProjectNumber          varchar(200) NULL
        , TaskKey                int NOT NULL
        , TaskName               varchar(200) NULL
        , TaskID                 varchar(50) NULL
        , ServiceKey             int NOT NULL
        , ServiceCode            varchar(50) NULL
        , ServiceDescription     varchar(500) NULL
        , SuggestedHours         decimal(12,2) NOT NULL
        , Score                  decimal(18,6) NOT NULL
        , Confidence             decimal(9,6) NOT NULL
        , Reason1                varchar(200) NULL
        , Reason2                varchar(200) NULL
        , ProjectScore           decimal(18,6) NULL
        , TaskWithinProjectScore decimal(18,6) NULL
        , BusinessTier           int NULL
        , ProjectTier            int NULL
        , HoursToday             decimal(12,2) NULL
        , UsesLast30             int NULL
        , LastUsedDate           date NULL
        , ProjectUsesLast30      int NULL
        , ProjectLastUsedDate    date NULL
    );

    ------------------------------------------------------------
    -- Must match sptTimeSuggestDaily output exactly
    ------------------------------------------------------------
    IF OBJECT_ID(''tempdb..#DailyResult'') IS NOT NULL DROP TABLE #DailyResult;

    CREATE TABLE #DailyResult
    (
          RankNo                 int NULL
        , ProjectKey             int NOT NULL
        , ProjectName            varchar(500) NULL
        , ProjectNumber          varchar(200) NULL
        , TaskKey                int NOT NULL
        , TaskName               varchar(200) NULL
        , TaskID                 varchar(50) NULL
        , ServiceKey             int NOT NULL
        , ServiceCode            varchar(50) NULL
        , ServiceDescription     varchar(500) NULL
        , SuggestedHours         decimal(12,2) NOT NULL
        , Score                  decimal(18,6) NOT NULL
        , Confidence             decimal(9,6) NOT NULL
        , Reason1                varchar(200) NULL
        , Reason2                varchar(200) NULL
        , WorkDate               date NOT NULL
        , ProjectScore           decimal(18,6) NULL
        , TaskWithinProjectScore decimal(18,6) NULL
        , BusinessTier           int NULL
        , ProjectTier            int NULL
        , HoursToday             decimal(12,2) NULL
        , UsesLast30             int NULL
        , LastUsedDate           date NULL
        , ProjectUsesLast30      int NULL
        , ProjectLastUsedDate    date NULL
    );

    ------------------------------------------------------------
    -- Loop days and call daily proc
    ------------------------------------------------------------
    DECLARE
          @WorkDate date
        , @DOW tinyint;

    DECLARE DayCursor CURSOR LOCAL FAST_FORWARD FOR
        SELECT WorkDate
        FROM #Days
        ORDER BY WorkDate;

    OPEN DayCursor;

    FETCH NEXT FROM DayCursor INTO @WorkDate;

    WHILE @@FETCH_STATUS = 0
    BEGIN
        DELETE FROM #DailyResult;

        INSERT INTO #DailyResult
        (
              RankNo
            , ProjectKey
            , ProjectName
            , ProjectNumber
            , TaskKey
            , TaskName
            , TaskID
            , ServiceKey
            , ServiceCode
            , ServiceDescription
            , SuggestedHours
            , Score
            , Confidence
            , Reason1
            , Reason2
            , WorkDate
            , ProjectScore
            , TaskWithinProjectScore
            , BusinessTier
            , ProjectTier
            , HoursToday
            , UsesLast30
            , LastUsedDate
            , ProjectUsesLast30
            , ProjectLastUsedDate
        )
        EXEC dbo.sptTimeSuggestDaily
              @CompanyKey    = @CompanyKey
            , @UserKey       = @UserKey
            , @WorkDate      = @WorkDate
            , @TopN          = @TopNPerDay
            , @Debug         = 0
            , @MinInc        = @MinInc
            , @MaxCandidates = @MaxCandidates
            , @LookbackDays  = @LookbackDays;

        SET @DOW = CAST(((DATEDIFF(day, ''19000101'', @WorkDate) % 7) + 1) AS tinyint);

        INSERT INTO #WeeklyOut
        (
              WorkDate
            , DayOfWeek
            , RankNo
            , ProjectKey
            , ProjectName
            , ProjectNumber
            , TaskKey
            , TaskName
            , TaskID
            , ServiceKey
            , ServiceCode
            , ServiceDescription
            , SuggestedHours
            , Score
            , Confidence
            , Reason1
            , Reason2
            , ProjectScore
            , TaskWithinProjectScore
            , BusinessTier
            , ProjectTier
            , HoursToday
            , UsesLast30
            , LastUsedDate
            , ProjectUsesLast30
            , ProjectLastUsedDate
        )
        SELECT
              @WorkDate
            , @DOW
            , ROW_NUMBER() OVER
              (
                  ORDER BY
                        ISNULL(dr.RankNo, 999999)
                      , dr.Score DESC
                      , dr.SuggestedHours DESC
                      , dr.ProjectKey
                      , dr.TaskKey
                      , dr.ServiceKey
              )
            , dr.ProjectKey
            , dr.ProjectName
            , dr.ProjectNumber
            , dr.TaskKey
            , dr.TaskName
            , dr.TaskID
            , dr.ServiceKey
            , dr.ServiceCode
            , dr.ServiceDescription
            , dr.SuggestedHours
            , dr.Score
            , dr.Confidence
            , dr.Reason1
            , dr.Reason2
            , dr.ProjectScore
            , dr.TaskWithinProjectScore
            , dr.BusinessTier
            , dr.ProjectTier
            , dr.HoursToday
            , dr.UsesLast30
            , dr.LastUsedDate
            , dr.ProjectUsesLast30
            , dr.ProjectLastUsedDate
        FROM #DailyResult dr
        WHERE ISNULL(dr.SuggestedHours, 0) > 0;

        FETCH NEXT FROM DayCursor INTO @WorkDate;
    END;

    CLOSE DayCursor;
    DEALLOCATE DayCursor;

    ------------------------------------------------------------
    -- Output
    ------------------------------------------------------------
    IF @Debug = 1
    BEGIN
        SELECT
              @WeekStartDate AS WeekStartDate
            , @WeekEndDate AS WeekEndDate
            , @TopNPerDay AS TopNPerDay
            , @IncludeWeekend AS IncludeWeekend
            , @MinInc AS MinInc
            , @MaxCandidates AS MaxCandidates
            , @LookbackDays AS LookbackDays;

        SELECT *
        FROM #WeeklyOut
        ORDER BY WorkDate, RankNo;
    END
    ELSE
    BEGIN
        ;WITH FirstWorkDate AS
        (
            SELECT
                  ProjectKey
                , TaskKey
                , ServiceKey
                , MIN(WorkDate) AS WorkDate
            FROM #WeeklyOut
            GROUP BY
                  ProjectKey
                , TaskKey
                , ServiceKey
        ),
        Pivoted AS
        (
            SELECT
                  ProjectKey
                , ProjectName
                , ProjectNumber
                , TaskKey
                , TaskID
                , TaskName
                , ServiceKey
                , ServiceCode
                , ServiceDescription

                , SUM(CASE WHEN DayOfWeek = 1 THEN SuggestedHours ELSE 0 END) AS MondayHours
                , SUM(CASE WHEN DayOfWeek = 2 THEN SuggestedHours ELSE 0 END) AS TuesdayHours
                , SUM(CASE WHEN DayOfWeek = 3 THEN SuggestedHours ELSE 0 END) AS WednesdayHours
                , SUM(CASE WHEN DayOfWeek = 4 THEN SuggestedHours ELSE 0 END) AS ThursdayHours
                , SUM(CASE WHEN DayOfWeek = 5 THEN SuggestedHours ELSE 0 END) AS FridayHours
                , SUM(CASE WHEN DayOfWeek = 6 THEN SuggestedHours ELSE 0 END) AS SaturdayHours
                , SUM(CASE WHEN DayOfWeek = 7 THEN SuggestedHours ELSE 0 END) AS SundayHours

                , MAX(Score) AS Score
                , MAX(Confidence) AS Confidence
                , MAX(ProjectScore) AS ProjectScore
                , MAX(TaskWithinProjectScore) AS TaskWithinProjectScore
                , MAX(BusinessTier) AS BusinessTier
                , MAX(ProjectTier) AS ProjectTier
                , MAX(UsesLast30) AS UsesLast30
                , MAX(LastUsedDate) AS LastUsedDate
                , MAX(ProjectUsesLast30) AS ProjectUsesLast30
                , MAX(ProjectLastUsedDate) AS ProjectLastUsedDate
            FROM #WeeklyOut
            GROUP BY
                  ProjectKey
                , ProjectName
                , ProjectNumber
                , TaskKey
                , TaskID
                , TaskName
                , ServiceKey
                , ServiceCode
                , ServiceDescription
        )
        SELECT
              f.WorkDate
            , p.*
        FROM FirstWorkDate f
        INNER JOIN Pivoted p
            ON p.ProjectKey = f.ProjectKey
           AND p.TaskKey = f.TaskKey
           AND p.ServiceKey = f.ServiceKey
        ORDER BY
              p.ProjectName
            , p.TaskName
            , p.ServiceCode;
    END;
END;'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spConvertDB2606]'
GO
IF OBJECT_ID(N'[dbo].[spConvertDB2606]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[spConvertDB2606]
AS

--Seed new AB prefix with existing Invoice prefix value
UPDATE tPreference
SET AdvBillPrefix = ARNumPrefix'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPreferenceUpdateApp]'
GO
IF OBJECT_ID(N'[dbo].[sptPreferenceUpdateApp]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[sptPreferenceUpdateApp]
 @CompanyKey int,
 @ProjectNumStyle smallint,
 @ProjectNumPrefix varchar(10),
 @NextProjectNum int,
 @ProjectNumPlaces int,
 @ProjectNumSep char(1),
 @ProjectNumSuffixFromProjectType tinyint,
 @ProjectNumPrefixUseYear tinyint,
 @CampaignNumStyle smallint,
 @CampaignNumPrefix varchar(10),
 @NextCampaignNum int,
 @CampaignNumPlaces int,
 @CampaignNumSep char(1),
 @CampaignNumPrefixUseYear tinyint,
 @PONumPrefix varchar(10),
 @NextPONum int,
 @PONumPlaces int,
 @IONumPrefix varchar(10),
 @NextIONum int,
 @IONumPlaces int,
 @BCNumPrefix varchar(10),
 @NextBCNum int,
 @BCNumPlaces int,
 @ARNumPrefix varchar(10),
 @AdvBillPrefix varchar(10),
 @NextARNum int,
 @ARNumPlaces int,
 @DefaultARApprover smallint,
 @DefaultARApproverKey int,
 @DefaultAPApprover smallint,
 @DefaultAPApproverKey int, 
 @ExpenseNumPrefix varchar(10),
 @NextExpenseNum int,
 @ExpenseNumPlaces int,
 @RequireRequest tinyint,
 @RequireProjectType tinyint,
 @RequireClientProjectNumber tinyint,
 @NotifyExpenseReport int,
 @GetRateFrom smallint,
 @TimeRateSheetKey int,
 @TitleRateSheetKey int,
 -- @HourlyRate money,
 @GetMarkupFrom money,
 @ItemRateSheetKey int,
 -- @ItemMarkup decimal(24,4),
 -- @IOCommission decimal(24,4),
 -- @BCCommission decimal(24,4),
 -- @GetItemRate tinyint,
 @DefaultPOType int,
 @DefaultPrintPOType int,
 @DefaultBCPOType int,
 @IOOrderDisplayMode smallint,
 @BCOrderDisplayMode smallint,
 @IOApprover int,
 @BCApprover int,
 @IOClientLink smallint,
 @BCClientLink smallint, 
 @PaymentTermsKey int,
 @SendAssignmentEmail tinyint,
 @AutoScheduleProjects tinyint,
 -- @RequireMasterTask tinyint,
 @DefaultARLineFormat smallint,
 @ShowCustomRptConditions tinyint,
 @SetInvoiceNumberOnApproval tinyint,
 @SyncDeletesContacts tinyint,
 @SyncDeleteEvents tinyint,
 @AutoApproveExternalOrders tinyint,
 @ActualDateUpdatesPlan tinyint,
 @UseMilitaryTime tinyint,
 @IOPrintClientOnOrder tinyint,
 @BCPrintClientOnOrder tinyint,
 @EstimateNumStyle smallint,
 @EstimateNumPrefix varchar(10),
 @NextEstimateNum int,
 @EstimateNumPlaces int,
 @EstimateNumSep char(1),
 @EstimateNumPrefixUseYear tinyint,
 @EstimateInternalApprovalDays int,
 @EstimateExternalApprovalDays int,
 @IOAllowChangesAfterClientInvoice tinyint,
 @BCAllowChangesAfterClientInvoice tinyint,
 @IOShowAdjustmentsAsSingleLine tinyint,
 @BCShowAdjustmentsAsSingleLine tinyint,
 @IOUseClientCosting tinyint,
 @BCUseClientCosting tinyint,
 @BCUseProductName tinyint,
 @EditVendorInvTax tinyint,
 @POUnitCostDecimalPlaces int,
 @POQtyDecimalPlaces int,
 -- @UseUnitRate tinyint,
 @AutoApproveExternalInvoices tinyint,
 @BCGeneratePrebilledRevisions tinyint,
 @IOGeneratePrebilledRevisions tinyint,
 @PrintTrafficOnBC tinyint,
 @UseExpenseTypeClassOnVoucher tinyint,
 @AutoGenVoucherFromER tinyint,
 @SplitBilling tinyint,
 @SplitBillingClientVisible tinyint,
 @DuplicateVendorInvoiceNbr tinyint,
 @UseCompanyFolders tinyint,
 @UseContactFolders tinyint,
 @UseLeadFolders tinyint,
 @UseActivityFolders tinyint,
 @UseOppFolders tinyint,
 @EmailsVisibleToClient tinyint,
 @RequireActivityType tinyint,
 @EmailsDefaultActivityTypeKey int,
 @DefaultActivityTypeKey int,
 @DefaultToDoTypeKey int,
 @AutoGenerateInvoiceOrderLines tinyint,
 @ShowServicesOnGrid tinyint,
 @ReqProjectOnTime tinyint,
 @ReqServiceOnTime tinyint,
 @EmailTimeSubmittal tinyint,
 @TimeSheetPeriod smallint,
 @StartTimeOn smallint,
 @AllowOverlap tinyint,
 @PrintAsGrid tinyint,
 @AllowCustomDates tinyint,
 @LateEnteredDays smallint,
 @LateEnteredHours smalldatetime,
 @DefaultAutoIDTask tinyint,
 -- @DefaultSimpleSchedule tinyint,
 @UseClearedDate tinyint,
 @RequireCommentsOnTime tinyint,
 -- @UnverifiedTimeOption smallint,
 @UseToDo tinyint,
 @UseTypeOnToDo tinyint,
 @UseStatusOnDeliverables tinyint,
 @UseToDoOnDeliverables tinyint,
 @UseStatusOnToDo tinyint, 
 @ActivityEmailSender tinyint,
 @UseSalesTaxOnExpenseReports tinyint,
 @TimerInterval tinyint,
 @TimerRounding tinyint,
 @CheckMethodKey int,
 @ClientReviewInstructions varchar(1000),
 @ClientReviewEnableRouting tinyint,
 @ClientReviewAllApprove tinyint,
 @ClientReviewDaysToApprove int,
 @InternalReviewInstructions varchar(1000),
 @InternalReviewEnableRouting tinyint,
 @InternalReviewAllApprove tinyint,
 @InternalReviewDaysToApprove int,
 @InternalReviewLoginRequired int,
 @InternalReviewSendReminder int,
 @InternalReviewPause int,
 @ClientReviewLoginRequired int,
 @ClientReviewSendReminder int,
 @ClientSeeInternalComments tinyint = 0,
 --@ShowInactiveInCriteria tinyint,
 @EmployeePrimaryContact tinyint,
 @EmployeePrimaryContactCampaign tinyint,
 @SendAllComments tinyint,
 -- @UseAdvProjectDiary tinyint,
 @POHeaderStandardTextKey int,
 @POFooterStandardTextKey int,
 @IOHeaderStandardTextKey int,
 @IOFooterStandardTextKey int,
 @BOHeaderStandardTextKey int,
 @BOFooterStandardTextKey int,
 @ShowActualHours tinyint,
 @CrossProjectPreds tinyint,
 @InternalReviewReminderType tinyint,
 @InternalReviewReminderInterval int,
 @ClientReviewReminderType tinyint,
 @ClientReviewReminderInterval int,
 @NoTimeBeforeGLCloseDate int,
 -- @DiaryFont varchar(100),
 -- @DiaryFontSize int,
 @EmailSubjectFormat int,
 @VendorInvoiceApproverNotification tinyint,
 @DFAUserID varchar(100) = NULL,
 @DFAPassword varchar(100) = NULL,
 @ClientInvoiceApproverNotification tinyint,
 -- @EmailFooter text,
 @OnlyOneApprovedEstimate tinyint,
 @CalendarNotificationsToOrganizer tinyint,
 @CalendarNotificationsToStaffOnly tinyint,
 @RequireCampaignProjectClientMatch tinyint,
 -- @IOShowPremiumsAsSingleLine tinyint,
 -- @IOHideUserDefined1 tinyint,
 -- @IOHideUserDefined2 tinyint,
 -- @IOHideUserDefined3 tinyint,
 -- @IOHideUserDefined4 tinyint,
 -- @IOHideUserDefined5 tinyint,
 -- @IOHideUserDefined6 tinyint,
 -- @ShowReviewsTab tinyint,
 @UseBillingTitles tinyint,
 @RequireProducts tinyint,
 @RequireDivisions tinyint,
 @RequireUniqueIDOnProdDiv tinyint,
 @DoNotCopySpecs tinyint,
 @CloseMonthBLInvoice tinyint = null,
 @UseWWP tinyint,
 @RequireLoginForCC tinyint,
 @PostCCWhenSentToVendor tinyint,
 @DefaultDepartmentFromUser tinyint,
 @UpdateActualsOnBWS tinyint,
 @DefaultEstType smallint,
 @PrintClient tinyint = null,
 @PrintDivision tinyint = null,
 @POPrintClientProjectNumber  tinyint = null,
 @RequestRejectReason tinyint = null,
 @UseMedia tinyint = 0,
 @ClientMessage varchar(1000),
 @SSOURLPrefix varchar(50) = NULL,
 @SSOIPURL varchar(max) = NULL,
 @SSOLogutRedirectURL varchar(max) = NULL,
 @SSORedirectURL varchar(max) = NULL,
 @SSOUserParms varchar(max) = NULL,
 @CreateClientVendorLogins tinyint,
 @SSOSecurityGroupKey INT,
 @AutoScheduleTaskEndDate tinyint,
 @TimesheetCertify tinyint,
 @CertifyMessage varchar(3000),
 @LDAPFirstNameAttr varchar(50) = NULL,
 @LDAPLastNameAttr varchar(50) = NULL,
 @LDAPEmailAttr varchar(50) = NULL,
 @LDAPPhoneAttr varchar(50) = NULL,
 @LDAPClientAttr varchar(50) = NULL,
 @LDAPSecurityGroupAttr varchar(50) = NULL,

 -- Daily Emails
 @MissingTime smalldatetime,
 @MissingTimeSheet smalldatetime,
 @MissingTimeSheetFreq smallint,
 @BudgetUpdate smalldatetime,
 @DeliverableStatus smalldatetime,
 @MissingApproval smalldatetime,
 @TaskReminder smalldatetime,
 @UnsubmittedTimeSheet smalldatetime,
 @UnsubmittedTimeSheetFreq smallint,
 @MyItemsToApprove smalldatetime = null,

 --Email Settings
 @PopServer varchar(250) = NULL,
 @PopUserID varchar(250) = NULL,
 @PopEmail varchar(250) = NULL,
 @PopPassword varchar(250) = NULL,
 @SystemEmail varchar(300) = NULL,
 @ForceSystemAsFrom tinyint = NULL,
 @PopUseSSL tinyint = NULL,
 @PopPort int = NULL,
 @EmailProtocol tinyint = NULL,
 @EmailFooter text = NULL,
 @EmailLinkExpirationDays INT = NULL,

 @VCardUserName varchar(50),
 @VCardCustomerID varchar(50),
 @VCardPassword varchar(50),

 @CCProcessor INT = NULL,
 @CCPartnerID VARCHAR(100) = NULL,
 @CCLoginID VARCHAR(100) = NULL,
 @CCPassword VARCHAR(100) = NULL,
 @CCCashAccountKey int = null,
 @DefaultAccountManager tinyint = NULL,
 @DefaultEstimateApprover INT = 1,
 @DefaultEstimateApproverKey int,
 @SMTPServer VARCHAR(100) = NULL,
 @SMTPPort INT = null,
 @SMTPUserID VARCHAR(100) = NULL,
 @SMTPPassword VARCHAR(200) = NULL,
 @SMTPSSL TINYINT = NULL,
 @SMTPAuthMethod VARCHAR(50) = NULL,
 @EstimateExternalLoginNotRequired TINYINT = NULL,
 @ReviewStepOptions TINYINT,
 @DefaultDetailsOnExpenseReceipt tinyint = 1,
 @RescheduleProjects smalldatetime,
 @SetTaxableOnInvoice TINYINT,
 @RequireLoginToAcceptMeeting tinyint = 1,
 @RequestExtendDueDate tinyint = 0,
 @SendNotifyWhenSent tinyint = 0,
 @OneProjectAllowedPerRequest tinyint = 0,
 @CopyDeliverables tinyint = 1,
 @CopyToDos tinyint = 1,
 @POHideApprovedBy tinyint = 0,
 @KeepEstimateRates tinyint = 0,
 @DefaultEmailInvoiceMessage varchar(max) = NULL,
 @DefaultEmailStatementMessage varchar(max) = NULL,
 @POHideVendorPaymentDetails tinyint = 0,
 @RFQStatusChangeToSentAfterPrint tinyint = 0,
 @APInvoiceToPostingDate tinyint,
 @ARInvoiceToPostingDate tinyint = 0,
 @UseDraftsWithConversations tinyint = 1,
 @TaskReminderSendOnWeekEnd tinyint = 1,
 @POApproverLowerLimit tinyint = 0,
 @RequireApprovalForSpecChanges tinyint = 0,
 @AutoRevisionSpecs tinyint = 0,
 @DefaultBillingMethod  tinyint = 1,
 @DefaultExpensesNotIncluded tinyint = 0,
 @UseTypeOnDeliverables tinyint = 0,
 @RequireTaskOnDeliverables tinyint = 0,
 @DefaultEstLaborTaxable tinyint = NULL,
 @ShowProjectManager tinyint = 0,
 @DefaultProjectManager tinyint = NULL,
 @StrataOrderAPISubscriptionKey varchar(200) = NULL,
 @StrataInvoiceAPISubscriptionKey varchar(200) = NULL,
 @StrataAPIApplicationKey varchar(500) = NULL,
 @POPrintClientEmail varchar(max) = NULL,
 @KeyPerson1 varchar(500) = NULL,
 @KeyPerson2 varchar(500) = NULL,
 @KeyPerson3 varchar(500) = NULL,
 @KeyPerson4 varchar(500) = NULL,
 @KeyPerson5 varchar(500) = NULL,
 @KeyPerson6 varchar(500) = NULL,
 @ShowOriginalPostLast tinyint = 0,
 @ShowToDoOriginalPostLast tinyint = 0,
 @LayoutFromGLCompany tinyint = 0,
 @RFQShowProjectNumber tinyint = 0,
 @RFQRequireAttOnReply tinyint = 0,
 @RequireTaskOnTodo tinyint = 0,
 @AutoRecalcLabor tinyint = 0, 
 @UseApprovalComments tinyint = 0,
 @RequireApprovalComments tinyint = 0,
 @UseRejectComments tinyint = 0,
 @RequireRejectComments tinyint = 0,
 @NotifyOnTaskChange tinyint = 0,
 @BlankOwnerOnTaskChange tinyint = 0,
 @RequireWriteOffReason tinyint = 0,
 @TermsDays int = 0,
 @TermsNet int = 0,
 @TermsPercent decimal(24,4) = 0,
 @EnableInvoiceEstimateLayouts tinyint = 0,
 @UseMinHoursOnStaffSchedule tinyint = 0,
 @UseTimeOnDeliverables tinyint = 0,
 @DefaultCampaignEstType smallint = 4,
 @IncludeInternalComments tinyint = 0,
 @SlackBotUserOAuthToken varchar(512) = NULL,
 @RequirePlanningProjectClientMatch tinyint = 1,
 @POCheckBudget tinyint = 0,
 @DisplayAssignedServicesOnly tinyint = 0,
 @ACHProcessor int = 0,
 @ACHLoginID varchar (50) = NULL,
 @ACHTransactionKey varchar(200) = NULL,
 @ACHKey varchar(50) = NULL,
 @ACHCashAccountKey int =0,
 @ClientPortalTitle varchar(250),
 @RequireDivisionsOpp tinyint = 0,
 @RequireProductsOpp tinyint = 0,
 @NotifyUsersWhenSentForReview tinyint = 1,
 @RestrictClientEmailed tinyint = 0,
 @NoTimeBeforeDate smalldatetime = NULL,
 @LDAPCountryAttr varchar(50) = NULL,
 @TrackOvertime tinyint = 0,
 @ToDoReminder smalldatetime = NULL,
 @ToDoReminderSendOnWeekEnd tinyint = 1,
 @AvalaraEnabled tinyint = 0,
 @AvalaraAccountID varchar(200) = NULL,
 @AvalaraLicenseKey varchar(200) = NULL,
 @AvalaraCompanyCode varchar(200) = NULL,
 @AvalaraDocRecordingDisabled tinyint = 0,
 @AvalaraLoggingEnabled tinyint = 0,
 @AvalaraSandboxEnabled tinyint = 0,
 @AvalaraDisableAutoCalculate tinyint = 0,
 @HideExpenseReportItems tinyint = 0,
 @SendIndividualApprovedEmails tinyint = 1,
 @DefaultCampaignBillBy smallint = 1,
 @DefaultDeliverableSortBy smallint = 0,
 @UseNewFileType tinyint = 1,
 @UseExistingFileType tinyint = 1,
 @UseUrlFileType tinyint = 1,
 @UseVimeoFileType tinyint = 1,
 @UseYouTubeFileType tinyint = 1,
 @UseAdvanceCommentsOnDeliverables tinyint = 0,
 @WeekendBucket tinyint = 0,
 @DefaultCampUseCampaignBudget tinyint = 0,
 @DefaultCampExpensesNotIncluded tinyint = 0,
 @ClientPortalShowProjectRequests tinyint = 0,
 @ProjectNumPrefixUseGLCompanyID tinyint = 0,
 @VoucherSuperApproverKey int = null,
 @VoucherSuperMinLevel decimal(18,2) = 0,
 @VoucherMaxAmount decimal(18,2) = 0,
 @DefaultCCReceiptMessage varchar(max) = NULL,
 @ClientInvLogoPos tinyint = 0,
 @WelcomeMessage nvarchar(max) = NULL,
 @FileLinkExpirationDays tinyint = 7,
 @OppProjectNonBillable tinyint = 1,
 @IOHideApprovedBy tinyint = 0,
 @IOHideAcceptedBy tinyint = 0,
 @IOHideSpaceClose tinyint = 0,
 @IOHideMaterialsDue tinyint = 0,
 @BCHideApprovedBy tinyint = 0,
 @BCHideAcceptedBy tinyint = 0,
 @BCRequireStations tinyint = 0,
 @IORequirePublications tinyint = 0,
 @LoadNext50Conversations tinyint = 1,
 @RequireCommentsOnExpenseReports tinyint = 0,
 @SendBWSNotifyEmail tinyint = 0,
 @SendCCApproverEmail tinyint = 0,
 @IOShowVendorInvoices tinyint = 0,
 @BCShowVendorInvoices tinyint = 0

AS --Encrypt

/*
|| When     Who Rel		What 
|| 01/10/16 MAS 10.6.1.2 Cloned from sptPreferenceUpdateNumberWJ for Platinum
|| 02/15/17 GAR 10.6.1.3 Added in DFAUserID and DFAPassword fields as well as Email Settings fields.  Also added Single Sign on fields.
|| 02/16/17 GAR 10.6.1.3 Added EmailLinkExpirationDays and CC and vCard info.
|| 03/16/17 MFT 10.6.1.4 Added DefaultAccountManager
|| 04/04/17 MAS 10.6.1.5 Added InternalReviewInstructions, InternalReviewLoginRequired, ClientReviewLoginRequired & ClientReviewInstructions
|| 04/06/17 MCM 10.6.1.5 Added ActivityEmailSender, AllowTransferDate,NoTimeBeforeGLCloseDate, NotifyExpenseReport, PostCCWhenSentToVendor,RequestRejectReason, RequireLoginForCC, SetInvoiceNumberOnApproval, SplitBilling, UseActivityFolders
|| 05/01/17 MAS 10.6.1.5 (343597) Added back exluded fields
|| 06/01/17 MAS 10.6.1.6 (347462) Added SSORedirectURL
|| 06/07/17 MAS 10.6.1.7 (348319) Added LDAPSecurityGroupAttr
|| 06/22/17 CRG 10.6.1.7 (351192) Added ClientSeeInternalComments
|| 07/19/17 GAR 10.6.1.8 Added UseMedia
|| 09/19/17 MAS 10.6.2.0 Always reset the VCardToken.  We will retrieve a new token when they access VCard (CSI).
|| 09/20/17 GHL 10.6.2.0 (295216) Added fields for timesheet tardiness in tTimeOption
||                        Renamed to LateEnteredDays/LateEnteredHours we are using 2 settings for timesheet and time
|| 09/25/17 MAS 10.6.2.0 Added CreateClientVendorLogins flag 
|| 10/26/17 GHL 10.6.2.1 (368187) Added @DefaultEstimateApprover for enhancement for Spark44
|| 12/01/17 DDM 18.1.0.0 Added SMTP Settings fields
|| 02/26/18 WDF 18.3.0.0 (387517) Added @SplitBillingClientVisible flagging whether Clients could see Split Billing on Requests
|| 04/16/18 RLB 18.5.0.0 (4319) Add for To Do. Added option on estimate to allow external approver to by pass login
|| 04/23/18 AMP 18.5.0.0 (395107) Added ReviewStepOptions column 
|| 05/03/18 GHL 18.5.0.0 (386867) Added @DefaultDetailsOnExpenseReceipt, if 1 defaults for office, class and dept are seeded automatically
||                       if 0, these fields remain blank, the user will manually set these fields 
|| 05/09/18 CRG 18.6.0.0 Added CrossProjectPreds
|| 06/07/18 RLB 18.7.0.0 Added Reschedule Projects
|| 06/15/18 GWG 18.7     Added WWP
|| 06/28/18 GHL 18.7     (401828) Added @SetTaxableOnInvoice to force Taxable1 and Taxable2 to 1 on client invoices
|| 07/06/18 GAR 18.8.0.0 (408569) Added RequireLoginToAcceptMeeting for the calendar
|| 08/13/18 RLB 18.9.0.0 (411588) Added RequestExtendDueDate
|| 08/21/18 AMP 18.9.0.0 (415365) Changes for the addition of a default Estimate Approver 
|| 09/19/18 RLB 18.9.1.0 (420581) added option to send deliverable notifications to notiy user list when roud is sent out of review
|| 09/27/18 GAR 18.9.1.0 (412560) Added OneProjectAllowedPerRequest for allowing only one project per project request
|| 10/10/18 RLB 18.9.2.0 (417883) Added new project option to copy deliverables set to checked by default
|| 10/10/18 GHL 18.9.2.0 (424709) Added @POShowApprovedBy to control the label ''Approved By'' when printing POs 
|| 10/11/18 RLS 18.9.2.0 (418150) Added @DoNotCopySpecs 
|| 10/12/18 MCM 18.9.2.0 (425718) They want to change it to be @POHideApproved by so it dafaults to show 
|| 10/31/18 GHL 18.9.2.0 (427056) Added KeepEstimateRates so that they can decide to keep the same rates when copying projects 
|| 12/03/18 RLB 18.9.3.0 (422479) Added Default Email Invoice Message option to client invoices
|| 12/10/18 AMP 18.9.1.0 (433593) Added @POHideVendorPaymentDetails to allow users to hide applied vendor invoice amounts when printing a PO
|| 12/27/18 MCM 19.1.0.0 (436163) Added @RFQStatusChangeToSentAfterPrint to allow users to close request for quote after printing it.
|| 02/14/19 RLS 19.0.3.0 (443784) Added @RequireActivityType
|| 02/25/19 GHL 19.0.3.0 (437273) Added @APInvoiceToPostingDate, if 1 the posting date follows the invoice date on the Add new vendor Invoice page
|| 02/26/19 GWG 19.0.3.0  Add use status on deliverables
|| 04/11/19 GAR 19.0.5.0 (454295) - Added @UseDraftsWithConversations column to use to control whether the Draft checkbox is shown in conversations
|| 04/12/19 MAS 19.0.5.0 (454561) Added @VCardCustomerID
|| 04/19/19 RLB 19.0.5.0 (454470) Added TaskReminderSendOnWeekEnd
|| 05/02/19 GHL 19.0.5.0 (454283) Added POApproverLowerLimit. When checked, the approver with the PO limit with the lowest limit greater than or equal
||                                to the order total will be chosen as the approver on the order
|| 05/06/19 GWG 19.0.5.0 Adding fields for change requests
|| 05/13/19 AMP 19.0.6.0 (455327) Added Default Billing Method
|| 05/28/19 AMP 19.0.6.0 (455327) Added Default Expenses Not Included for Fixed Fee
|| 05/21/19 GWG 19.0.6.0 Added UseTypeOnDeliverables
|| 05/29/19 AMP 19.0.6.0 (460062) Added Default Estimate Labor Taxable 
|| 06/05/19 RLB 19.0.7.0 (446229) Added Show Project Manager and Default Project Manager
|| 06/04/19 AMP 19.0.7.0 (451095) Added StrataAPISubscriptionKey & StrataAPIApplicationKey
|| 07/18/19 GAR 19.0.8.0 (454300) Added new project option to copy todos set to checked by default
|| 08/29/19 AMP 19.0.9.0 (475130) Added Include Ordered By Email Address
|| 10/15/19 GWG 19.1.1.0 Adding in saving of key people to tran pref
|| 12/10/19 GAR 20.0.1.0 (471119) Added @ShowOriginalPostLast
|| 01/20/20 MCM 20.0.2.0 (496634) Added @CCCashAccountKey
|| 01/23/20 RLB 20.0.2.0 (465885) Adding deliverable Final Review options
|| 01/27/20 GHL 20.0.2.0 (495024) Added LayoutFromGLCompany to get invoice templates/layouts from GL company
|| 01/30/20 RLB 20.0.2.0 (465885) removed my above change because it was not used
|| 03/23/20 MCM 20.0.4.0 (487717) Added RFQShowProjectNumber
|| 04/02/20 RLS 20.0.4.0 (498604) Added RequireTaskOnTodo
|| 04/21/20 AMP 20.0.7.0 (504921) Moved the ''Allow Entry of Transfer Date'' option to the GL Tracking Options screen under GL Settings
|| 04/27/20 AMP 20.0.7.0 (500949) Added Auto Recalculate Labor on Transfers
|| 07/16/20 AMP 20.1.0.0 (501889) Added UseApprovalComments,RequireApprovalComments,UseRejectComments,RequireRejectComments for Approval/Reject Comments Options
|| 10/01/20 AMP 20.1.1.0 (519925) Added @DefaultEmailStatementMessage for emailing Client Statements
|| 10/26/20 RLB 20.1.1.0 (534457)(534455) added deliverable options @NotifyOnTaskChange and @BlankOwnerOnTaskChange
|| 11/17/20 AMP 21.0.1.0 (533795) Added @RequireWriteOffReason this option is for both the Billing Worksheets and Project > Billing screens
|| 11/19/20 GHL 20.1.2.0 (536731) Added RFQRequireAttOnReply to require attachments on quote replies
|| 11/24/20 MCM 20.1.2.0 (537901) Added  @TermsDays, @TermsNet, and @TermsPercent for vendor defaults
|| 12/14/20 MFT 21.01.17 (530937) Added @EnableInvoiceEstimateLayouts
|| 01/05/21 RLB 21.02.14 (440997) Added option to use employee''s min hours on staff schedule and RM Screens
|| 03/24/21 RLB 21.04.18 (549892) Added Use time on deliverables option
|| 04/23/21 GHL 21.05.20 (555670) Added @APShowBankBalances to hide/show bank account balances in AP
|| 04/27/21 GHL 21.05.20 (555670) After review by QA, APShowBankBalances is a system setting now
|| 04/28/21 MFT 21.05.20 (523414) Unused preference UseAlternatePayer removal
|| 05/25/21 RLB 21.06.20 (558379) Added Default Campaign Estimate Type
||07/26/21  AMP 21.08.15.0000 (563516) Added Include Internal Comments
|| 08/18/21 RLB 21.09.19 (563856) added Items to Approve option
|| 08/20/21 GHL 21.09.19 (568295) Added @ARInvoiceToPostingDate to make it similar to @APInvoiceToPostingDate 
|| 09/01/21 GAR 21.????? (DEV2501) Added @SlackBotUserOAuthToken for use in the Slack integration
|| 09/28/21 RLB 21.10.17 (567353) added option RequirePlanningProjectClientMatch
|| 11/02/21 GHL 21.12.00 (574585) Added @POCheckBudget to prevent saving PO details if there is no budget
|| 11/08/21 RLB 21.12.00 (575829) Added @DisplayAssignedServicesOnly to only use assigned services in project assignment, reassign and today assignment views
|| 11/30/21 RLB 21.12.00 (568901) Added @ShowToDoOriginalPostLast
|| 12/20/21 WDF 22.01.16 (580569) Added @CalendarNotificationsToOrganizer
|| 01/27/22 MCM 22.02.00 (573522) Added @ACH fields
|| 02/02/22 RLB 22.03.20 (583935) Added Client Portal Title
|| 03/18/22 RLB 22.04.17 (588994) Added option to not require Product or division on Opp''s
|| 03/18/22 GAR 22.03.20 (592317) Removed @SlackBotUserOAuthToken - no reason for us to update this here
|| 03/22/22 RLB 22.04.17 (588307) Added option to not get notifications when project request is sent
|| 04/01/22 RLB 22.05.15 (586017) added client option Restrict Emailed on Client Created Conversations
|| 04/22/22 CRG 22.05.15 (574458) Added NoTimeBeforeDate
|| 05/06/22 RLS 22.05.15 (597823) Added check to see if the TimeSheetPeriod is changing from weekly (2) to daily (1)
|| 05/04/22 MAS 22.8.3.0 (584600) Added Country 
|| 07/18/22 GHL 22.0.8.0 (604153) Added TrackOvertime
|| 05/15/22 RLB 22.08.14 (598281) Added ToDoReminder and ToDoReminderSendOnWeekEnd options
|| 08/18/22 GAR 22.09.18 (609618) Added EmployeePrimaryContactCampaign
|| 09/02/22 KMC 22.10.16 Added Avalara setup fields
|| 10/21/22 AMP 22.11.20 (605726) Added HideExpenseReportItems
|| 01/13/23 RLB 23.02.19 (627271) added SendIndividualApprovedEmails
|| 04/04/23 CRG 23.05.14 (621941) Added DefaultCampaignBillBy
|| 04/04/23 RLB 23.08.20 (640897) Added DefaultDeliverableSortBy
|| 08/21/23 RLB 23.09.17 (648167) Added File Type Option for deliverables
|| 10/24/23 RLB 23.11.19 (651713) added option on deliverables UseAdvanceCommentsOnDeliverables
|| 11/28/23 CRG 23.12.17 (649537) Added WeekendBucket
|| 11/30/23 RLB 23.12.17 (649537) Added DefaultCampUseCampaignBudget and DefaultCampExpensesNotIncluded new campagin default options
|| 07/23/24 CRG 24.08.18 (674384) Added ClientPortalShowProjectRequests
|| 08/26/24 RLB 24.09.15 (679872) Added GL Company ID prefix options to project numbering
|| 09/30/24 MCM 24.11.x  (676228) Added Voucher Super User fields
|| 11/18/24 AMP 24.12.15 (672399) Added DefaultCCReceiptMessage
|| 01/14/25 AMP 25.02.16 (685907) Added ClientInvLogoPos - Allows position of logo to be set on the printed invoice
|| 02/14/25 RLS 25.03.16 (693193) Added @DefaultToDoTypeKey
|| 03/11/25 CRG 25.04.20 (687240) Added @WelcomeMessage
|| 03/12/25 GAR 25.04.20 (686404) Added @FileLinkExpirationDays
|| 03/12/25 RLB 25.06.15 (699515) Added @OppProjectNonBillable
|| 06/03/25 AMP 25.07.20 (699964) Added @IOHideApprovedBy,@IOHideAcceptedBy,@IOHideSpaceClose,@IOHideMaterialsDue,
                                        @BCHideApprovedBy,@BCHideAcceptedBy	
|| 11/21/25 RLB 25.12.14 (715936) Added @LoadNext50Conversations options
|| 12/18/25 GAR 25.12.14 (718010) Added @AvalaraDisableAutoCalculate for billing worksheets and estimates
|| 12/29/25 MCM 26.01.18 (694595) Added @BCRequireStations and @IORequirePublications for BO''s and IO''s
|| 01/27/26 RLS 26.02.15 (718020) Added @RequireCommentsOnExpenseReports
|| 01/28/26 AMP 26.02.15 (719805) Added @SendBWSNotifyEmail
|| 03/04/26 AMP 26.04.19 (722928) Added @SendCCApproverEmail
|| 03/11/26 AMP 26.04.19 (722287) Added @BCShowVendorInvoices and @IOShowVendorInvoices
|| 04/07/26 AMP 26.05.17 (718171) Added @AdvBillPrefix
*/

/*
 DECLARE @OldRequireMasterTask INT
 SELECT  @OldRequireMasterTask = RequireMasterTask FROM tPreference (NOLOCK) WHERE CompanyKey = @CompanyKey
 IF @OldRequireMasterTask = 0 AND @RequireMasterTask = 1
 BEGIN
	UPDATE tTask
	SET    tTask.MasterTaskKey = mt.MasterTaskKey
	FROM   tProject p (NOLOCK)
	      ,tMasterTask mt (NOLOCK)
	WHERE  p.ProjectKey = tTask.ProjectKey
	AND    p.CompanyKey = @CompanyKey
	AND    mt.CompanyKey = @CompanyKey
	AND    tTask.TrackBudget = 1
	AND    tTask.MasterTaskKey IS NULL
	AND    tTask.TaskID = mt.TaskID
 END
 */
 
UPDATE
	tPreference
SET
	ProjectNumStyle = @ProjectNumStyle,
	ProjectNumPrefix = @ProjectNumPrefix,
	NextProjectNum = @NextProjectNum,
	ProjectNumPlaces = @ProjectNumPlaces,
	ProjectNumSep = @ProjectNumSep,
	ProjectNumSuffixFromProjectType = @ProjectNumSuffixFromProjectType,
	ProjectNumPrefixUseYear = @ProjectNumPrefixUseYear,
	CampaignNumStyle = @CampaignNumStyle,
	CampaignNumPrefix = @CampaignNumPrefix,
	NextCampaignNum = @NextCampaignNum,
	CampaignNumPlaces = @CampaignNumPlaces,
	CampaignNumSep = @CampaignNumSep,
	CampaignNumPrefixUseYear = @CampaignNumPrefixUseYear,
	PONumPrefix = @PONumPrefix,
	NextPONum = @NextPONum,
	PONumPlaces = @PONumPlaces,
	IONumPrefix = @IONumPrefix,
	NextIONum = @NextIONum,
	IONumPlaces = @IONumPlaces,
	BCNumPrefix = @BCNumPrefix,
	NextBCNum = @NextBCNum,
	BCNumPlaces = @BCNumPlaces,
	ARNumPrefix = @ARNumPrefix,
	AdvBillPrefix = @AdvBillPrefix,
	NextARNum = @NextARNum,
	ARNumPlaces = @ARNumPlaces,
	DefaultARApprover = @DefaultARApprover,
	DefaultARApproverKey = @DefaultARApproverKey,
	DefaultAPApprover = @DefaultAPApprover,
	DefaultAPApproverKey = @DefaultAPApproverKey,
	ExpenseNumPrefix = @ExpenseNumPrefix,
	NextExpenseNum = @NextExpenseNum,
	ExpenseNumPlaces = @ExpenseNumPlaces,
	RequireRequest = @RequireRequest,
	RequireProjectType = @RequireProjectType,
	RequireClientProjectNumber = @RequireClientProjectNumber,
	NotifyExpenseReport = @NotifyExpenseReport, -- Missing from HTML
	GetRateFrom = @GetRateFrom,
	-- HourlyRate = 	@HourlyRate, -- Missing from HTML
	GetMarkupFrom =	@GetMarkupFrom,
	TimeRateSheetKey = @TimeRateSheetKey, 
	TitleRateSheetKey = @TitleRateSheetKey,
	ItemRateSheetKey = 	@ItemRateSheetKey,
	-- ItemMarkup =	@ItemMarkup, -- Missing from HTML
	-- IOCommission = @IOCommission, -- Missing from HTML
	-- BCCommission = @BCCommission, -- Missing from HTML
	-- GetItemRate = @GetItemRate, -- Missing from HTML
	DefaultPOType = @DefaultPOType,
	DefaultPrintPOType = @DefaultPrintPOType,
	DefaultBCPOType = @DefaultBCPOType,
	IOOrderDisplayMode = @IOOrderDisplayMode,
	BCOrderDisplayMode = @BCOrderDisplayMode,
	IOApprover = @IOApprover, 
	BCApprover = @BCApprover,
	IOClientLink = @IOClientLink,
	BCClientLink = @BCClientLink,
	PaymentTermsKey = @PaymentTermsKey,
	SendAssignmentEmail = @SendAssignmentEmail,
	AutoScheduleProjects = @AutoScheduleProjects,
	-- RequireMasterTask = @RequireMasterTask, -- Missing from HTML
	DefaultARLineFormat = @DefaultARLineFormat,
	ShowCustomRptConditions = @ShowCustomRptConditions,
    SetInvoiceNumberOnApproval = @SetInvoiceNumberOnApproval,-- Missing from HTML
	SyncDeletesContacts = @SyncDeletesContacts,
	SyncDeleteEvents = @SyncDeleteEvents,
	AutoApproveExternalOrders = @AutoApproveExternalOrders,
	ActualDateUpdatesPlan = @ActualDateUpdatesPlan,
	UseMilitaryTime = @UseMilitaryTime,
	IOPrintClientOnOrder = @IOPrintClientOnOrder,
	BCPrintClientOnOrder = @BCPrintClientOnOrder,
	EstimateNumStyle = @EstimateNumStyle,
	EstimateNumPrefix = @EstimateNumPrefix,
	NextEstimateNum = @NextEstimateNum,
	EstimateNumPlaces = @EstimateNumPlaces,
	EstimateNumSep = @EstimateNumSep,
	EstimateNumPrefixUseYear = @EstimateNumPrefixUseYear,  
	EstimateInternalApprovalDays = @EstimateInternalApprovalDays,  
	EstimateExternalApprovalDays = @EstimateExternalApprovalDays,  
	IOAllowChangesAfterClientInvoice = @IOAllowChangesAfterClientInvoice,
	BCAllowChangesAfterClientInvoice = @BCAllowChangesAfterClientInvoice, 
	IOShowAdjustmentsAsSingleLine = @IOShowAdjustmentsAsSingleLine,
	BCShowAdjustmentsAsSingleLine = @BCShowAdjustmentsAsSingleLine,
	IOUseClientCosting = @IOUseClientCosting,
	BCUseClientCosting = @BCUseClientCosting,
	BCUseProductName = @BCUseProductName,
	EditVendorInvTax = @EditVendorInvTax,
	POUnitCostDecimalPlaces = @POUnitCostDecimalPlaces,
	POQtyDecimalPlaces = @POQtyDecimalPlaces,
	-- UseUnitRate = @UseUnitRate, -- Missing from HTML
	AutoApproveExternalInvoices = @AutoApproveExternalInvoices,
	BCGeneratePrebilledRevisions = @BCGeneratePrebilledRevisions,
	IOGeneratePrebilledRevisions = @IOGeneratePrebilledRevisions,
	PrintTrafficOnBC = @PrintTrafficOnBC,
	UseExpenseTypeClassOnVoucher = @UseExpenseTypeClassOnVoucher,
	AutoGenVoucherFromER = @AutoGenVoucherFromER,
	SplitBilling = @SplitBilling, -- Missing from HTML
	SplitBillingClientVisible = @SplitBillingClientVisible,
	DuplicateVendorInvoiceNbr = @DuplicateVendorInvoiceNbr,
	UseCompanyFolders = @UseCompanyFolders,
	UseContactFolders = @UseContactFolders,
	UseLeadFolders = @UseLeadFolders,
	UseActivityFolders = @UseActivityFolders, -- Missing from HTML
	UseOppFolders = @UseOppFolders,
	EmailsVisibleToClient = @EmailsVisibleToClient,
	RequireActivityType = @RequireActivityType,
	EmailsDefaultActivityTypeKey = @EmailsDefaultActivityTypeKey,
	DefaultActivityTypeKey = @DefaultActivityTypeKey,
	DefaultToDoTypeKey = @DefaultToDoTypeKey,
	AutoGenerateInvoiceOrderLines = @AutoGenerateInvoiceOrderLines,
	DefaultAutoIDTask = @DefaultAutoIDTask, 
	-- DefaultSimpleSchedule = @DefaultSimpleSchedule, -- Missing from HTML
	UseClearedDate = @UseClearedDate,
	RequireCommentsOnTime = @RequireCommentsOnTime,
	-- UnverifiedTimeOption = @UnverifiedTimeOption, -- Missing from HTML
	UseToDo = @UseToDo,
	
	UseTypeOnToDo = @UseTypeOnToDo, 
	UseStatusOnDeliverables = @UseStatusOnDeliverables, -- Missing from HTML
	UseToDoOnDeliverables = @UseToDoOnDeliverables,
	UseTypeOnDeliverables = @UseTypeOnDeliverables,
	RequireTaskOnDeliverables = @RequireTaskOnDeliverables,
	UseStatusOnToDo = @UseStatusOnToDo,

	ActivityEmailSender = @ActivityEmailSender, -- Missing from HTML
	UseSalesTaxOnExpenseReports = @UseSalesTaxOnExpenseReports,
	TimerInterval = @TimerInterval,
	TimerRounding = @TimerRounding,
	CheckMethodKey = @CheckMethodKey,
	InternalReviewInstructions = @InternalReviewInstructions,
	InternalReviewEnableRouting = @InternalReviewEnableRouting,
	InternalReviewAllApprove = @InternalReviewAllApprove,
	InternalReviewDaysToApprove = @InternalReviewDaysToApprove,
	ClientReviewInstructions = @ClientReviewInstructions, 
	ClientReviewEnableRouting = @ClientReviewEnableRouting,
	ClientReviewAllApprove = @ClientReviewAllApprove,
	ClientReviewDaysToApprove = @ClientReviewDaysToApprove,
	InternalReviewLoginRequired = @InternalReviewLoginRequired,
	InternalReviewSendReminder = @InternalReviewSendReminder,
	InternalReviewPause = @InternalReviewPause,
	ClientReviewLoginRequired = @ClientReviewLoginRequired,
	ClientReviewSendReminder = @ClientReviewSendReminder,
	ClientSeeInternalComments = @ClientSeeInternalComments,
	--ShowInactiveInCriteria = @ShowInactiveInCriteria, 
	EmployeePrimaryContact = @EmployeePrimaryContact,
	EmployeePrimaryContactCampaign = @EmployeePrimaryContactCampaign,
	SendAllComments = @SendAllComments,
	-- UseAdvProjectDiary = @UseAdvProjectDiary, -- Missing from HTML
	POHeaderStandardTextKey = @POHeaderStandardTextKey,
	POFooterStandardTextKey = @POFooterStandardTextKey,
	IOHeaderStandardTextKey = @IOHeaderStandardTextKey,
	IOFooterStandardTextKey = @IOFooterStandardTextKey,
	BOHeaderStandardTextKey = @BOHeaderStandardTextKey,
	BOFooterStandardTextKey = @BOFooterStandardTextKey,
	ShowActualHours = @ShowActualHours,
	CrossProjectPreds = @CrossProjectPreds,
	InternalReviewReminderType = @InternalReviewReminderType, 
	InternalReviewReminderInterval = @InternalReviewReminderInterval,
	ClientReviewReminderType = @ClientReviewReminderType,
	ClientReviewReminderInterval = @ClientReviewReminderInterval,
	EmailTimeSubmittal = @EmailTimeSubmittal,
    NoTimeBeforeGLCloseDate = @NoTimeBeforeGLCloseDate, -- Missing from HTML
	-- ShowReviewsTab = @ShowReviewsTab, -- Missing from HTML
	-- DiaryFont = @DiaryFont, -- Missing from HTML
	-- DiaryFontSize = @DiaryFontSize, -- Missing from HTML
	EmailSubjectFormat = @EmailSubjectFormat,
	VendorInvoiceApproverNotification = @VendorInvoiceApproverNotification,
	DFAUserID = ISNULL(@DFAUserID, DFAUserID),
	DFAPassword = ISNULL(@DFAPassword, DFAPassword),
	ClientInvoiceApproverNotification = @ClientInvoiceApproverNotification,
	-- EmailFooter = @EmailFooter, -- Missing from HTML
	OnlyOneApprovedEstimate = @OnlyOneApprovedEstimate,
	CalendarNotificationsToOrganizer = @CalendarNotificationsToOrganizer,
	CalendarNotificationsToStaffOnly = @CalendarNotificationsToStaffOnly,
	RequireCampaignProjectClientMatch = @RequireCampaignProjectClientMatch, -- Missing from HTML
	-- IOShowPremiumsAsSingleLine = @IOShowPremiumsAsSingleLine, -- Missing from HTML
	-- IOHideUserDefined1 = @IOHideUserDefined1, -- Missing from HTML
	-- IOHideUserDefined2 = @IOHideUserDefined2, -- Missing from HTML
	-- IOHideUserDefined3 = @IOHideUserDefined3, -- Missing from HTML
	-- IOHideUserDefined4 = @IOHideUserDefined4, -- Missing from HTML
	-- IOHideUserDefined5 = @IOHideUserDefined5, -- Missing from HTML
	-- IOHideUserDefined6 = @IOHideUserDefined6, -- Missing from HTML
	CloseMonthBLInvoice = @CloseMonthBLInvoice,
	UseBillingTitles = @UseBillingTitles,
	RequireProducts = @RequireProducts,
	RequireDivisions = @RequireDivisions,
	RequireUniqueIDOnProdDiv = @RequireUniqueIDOnProdDiv, 
	DoNotCopySpecs = @DoNotCopySpecs, 
	UseWWP = @UseWWP, -- Missing from HTML
	RequireLoginForCC = @RequireLoginForCC, -- Missing from HTML
	PostCCWhenSentToVendor = @PostCCWhenSentToVendor, -- Missing from HTML
	--AllowTransferDate = @AllowTransferDate, -- Missing from HTML
	DefaultDepartmentFromUser = @DefaultDepartmentFromUser, -- Missing from HTML
	UpdateActualsOnBWS = @UpdateActualsOnBWS,
	DefaultEstType = isnull(@DefaultEstType, 2), -- 2=Task/Service by default
	PrintClient = @PrintClient,
	PrintDivision = @PrintDivision,
	POPrintClientProjectNumber = @POPrintClientProjectNumber,
	POPrintClientEmail = @POPrintClientEmail,
    RequestRejectReason = @RequestRejectReason, -- Missing from HTML
	VCardToken = NULL, -- Always reset the token.  We will retrieve a new token when they access VCard (CSI)
	UseMedia = @UseMedia,
	ClientMessage = @ClientMessage,
	SSOURLPrefix = ISNULL(@SSOURLPrefix, SSOURLPrefix),
	SSOIPURL = ISNULL(@SSOIPURL, SSOIPURL),
	SSOLogutRedirectURL = ISNULL(@SSOLogutRedirectURL, SSOLogutRedirectURL),
	SSORedirectURL = ISNULL(@SSORedirectURL, SSORedirectURL),
	SSOUserParms = ISNULL(@SSOUserParms, SSOUserParms),
	CreateClientVendorLogins = @CreateClientVendorLogins, 
	SSOSecurityGroupKey = @SSOSecurityGroupKey, 
	AutoScheduleTaskEndDate = @AutoScheduleTaskEndDate,
	TimesheetCertify = @TimesheetCertify,
	CertifyMessage = @CertifyMessage,
	LDAPFirstNameAttr =	 ISNULL(@LDAPFirstNameAttr, LDAPFirstNameAttr),
	LDAPLastNameAttr = ISNULL(@LDAPLastNameAttr, LDAPLastNameAttr),
	LDAPEmailAttr = ISNULL(@LDAPEmailAttr, LDAPEmailAttr),
	LDAPPhoneAttr = ISNULL(@LDAPPhoneAttr, LDAPPhoneAttr),
	LDAPClientAttr = ISNULL(@LDAPClientAttr, LDAPClientAttr),
	LDAPSecurityGroupAttr = ISNULL(@LDAPSecurityGroupAttr, LDAPSecurityGroupAttr),
	LDAPCountryAttr = ISNULL(@LDAPCountryAttr, LDAPCountryAttr),

	-- Daily Emails
	MissingTime = @MissingTime,
	MissingTimeSheet = @MissingTimeSheet,
	MissingTimeSheetFreq = @MissingTimeSheetFreq,
	BudgetUpdate = @BudgetUpdate,
	DeliverableStatus = @DeliverableStatus,
	MissingApproval = @MissingApproval,
	TaskReminder = @TaskReminder,
	UnsubmittedTimeSheet = @UnsubmittedTimeSheet,
	UnsubmittedTimeSheetFreq = @UnsubmittedTimeSheetFreq,
	MyItemsToApprove = @MyItemsToApprove,

	PopServer = ISNULL(@PopServer, PopServer),
	PopUserID = ISNULL(@PopUserID, PopUserID),
	PopEmail = ISNULL(@PopEmail, PopEmail),
	PopPassword = ISNULL(@PopPassword, PopPassword),
	SystemEmail = ISNULL(@SystemEmail, SystemEmail),
	ForceSystemAsFrom = ISNULL(@ForceSystemAsFrom, ForceSystemAsFrom),
	PopUseSSL = ISNULL(@PopUseSSL, PopUseSSL),
	PopPort = ISNULL(@PopPort, PopPort),
	EmailProtocol = ISNULL(@EmailProtocol, EmailProtocol),
	EmailFooter = ISNULL(@EmailFooter, EmailFooter),
	EmailLinkExpirationDays = ISNULL(@EmailLinkExpirationDays, EmailLinkExpirationDays),

	VCardUserName = @VCardUserName,
	VCardCustomerID = @VCardCustomerID,
	VCardPassword = @VCardPassword,

	CCProcessor = ISNULL(@CCProcessor, CCProcessor),
	CCPartnerID = ISNULL(@CCPartnerID, CCPartnerID),
	CCLoginID = ISNULL(@CCLoginID, CCLoginID),
	CCPassword = ISNULL(@CCPassword, CCPassword),
	CCCashAccountKey = @CCCashAccountKey,
	DefaultAccountManager = ISNULL(@DefaultAccountManager, DefaultAccountManager),
	DefaultEstimateApprover = @DefaultEstimateApprover,
	DefaultEstimateApproverKey = @DefaultEstimateApproverKey,
	SMTPServer = ISNULL(@SMTPServer,SMTPServer),
	SMTPPort = ISNULL(@SMTPPort,SMTPPort),
	SMTPUserID = ISNULL(@SMTPUserID,SMTPUserID),
	SMTPPassword = ISNULL(@SMTPPassword,SMTPPassword),
	SMTPSSL = ISNULL(@SMTPSSL,SMTPSSL),
	SMTPAuthMethod = ISNULL(@SMTPAuthMethod,SMTPAuthMethod),
	EstimateExternalLoginNotRequired = ISNULL(@EstimateExternalLoginNotRequired,EstimateExternalLoginNotRequired),
	ReviewStepOptions = @ReviewStepOptions,
	DefaultDetailsOnExpenseReceipt = @DefaultDetailsOnExpenseReceipt,
	RescheduleProjects = @RescheduleProjects,
	SetTaxableOnInvoice = @SetTaxableOnInvoice,
	RequireLoginToAcceptMeeting = @RequireLoginToAcceptMeeting,
	RequestExtendDueDate = @RequestExtendDueDate,
	SendNotifyWhenSent = @SendNotifyWhenSent,
	OneProjectAllowedPerRequest = @OneProjectAllowedPerRequest,
	CopyDeliverables = @CopyDeliverables,
	CopyToDos = @CopyToDos,
	POHideApprovedBy = @POHideApprovedBy,
	KeepEstimateRates = @KeepEstimateRates,
	DefaultEmailInvoiceMessage = @DefaultEmailInvoiceMessage,
	DefaultEmailStatementMessage = @DefaultEmailStatementMessage,
	POHideVendorPaymentDetails = @POHideVendorPaymentDetails,
	RFQStatusChangeToSentAfterPrint = @RFQStatusChangeToSentAfterPrint,
	RFQShowProjectNumber = @RFQShowProjectNumber, 
	RFQRequireAttOnReply = @RFQRequireAttOnReply,
	RequireTaskOnTodo = @RequireTaskOnTodo,
	APInvoiceToPostingDate = @APInvoiceToPostingDate,
	ARInvoiceToPostingDate = @ARInvoiceToPostingDate,
	UseDraftsWithConversations = @UseDraftsWithConversations,
	TaskReminderSendOnWeekEnd = @TaskReminderSendOnWeekEnd,
	POApproverLowerLimit = @POApproverLowerLimit,
	RequireApprovalForSpecChanges = @RequireApprovalForSpecChanges,
	AutoRevisionSpecs = @AutoRevisionSpecs,
	DefaultBillingMethod = @DefaultBillingMethod,
    DefaultExpensesNotIncluded = @DefaultExpensesNotIncluded,
    DefaultEstLaborTaxable=@DefaultEstLaborTaxable,
	ShowProjectManager = @ShowProjectManager,
	DefaultProjectManager = @DefaultProjectManager,
	StrataOrderAPISubscriptionKey = @StrataOrderAPISubscriptionKey,
	StrataInvoiceAPISubscriptionKey = @StrataInvoiceAPISubscriptionKey,
    StrataAPIApplicationKey = @StrataAPIApplicationKey,
	ShowOriginalPostLast = @ShowOriginalPostLast,
	LayoutFromGLCompany = @LayoutFromGLCompany,
	AutoRecalcLabor = @AutoRecalcLabor,
	UseApprovalComments = @UseApprovalComments,
	RequireApprovalComments = @RequireApprovalComments,
	UseRejectComments = @UseRejectComments,
	RequireRejectComments = @RequireRejectComments,
	NotifyOnTaskChange = @NotifyOnTaskChange,
	BlankOwnerOnTaskChange = @BlankOwnerOnTaskChange,
	RequireWriteOffReason = @RequireWriteOffReason,
	TermsDays = @TermsDays, 
	TermsNet = @TermsNet, 
	TermsPercent = @TermsPercent,
	EnableInvoiceEstimateLayouts = @EnableInvoiceEstimateLayouts,
	UseMinHoursOnStaffSchedule = @UseMinHoursOnStaffSchedule,
	UseTimeOnDeliverables = @UseTimeOnDeliverables,
	DefaultCampaignEstType = @DefaultCampaignEstType,
	IncludeInternalComments = @IncludeInternalComments,
	RequirePlanningProjectClientMatch = @RequirePlanningProjectClientMatch,
	POCheckBudget = @POCheckBudget,
	DisplayAssignedServicesOnly = @DisplayAssignedServicesOnly,
	ShowToDoOriginalPostLast = @ShowToDoOriginalPostLast,
	ACHProcessor = @ACHProcessor,
	ACHLoginID = @ACHLoginID,
	ACHTransactionKey = @ACHTransactionKey,
	ACHKey = @ACHKey,
	ACHCashAccountKey = @ACHCashAccountKey,
	ClientPortalTitle = @ClientPortalTitle,
	RequireDivisionsOpp = @RequireDivisionsOpp,
	RequireProductsOpp = @RequireProductsOpp,
	NotifyUsersWhenSentForReview = @NotifyUsersWhenSentForReview,
	RestrictClientEmailed = @RestrictClientEmailed,
	NoTimeBeforeDate = @NoTimeBeforeDate,
	TrackOvertime = @TrackOvertime,	
	ToDoReminder = @ToDoReminder,
	ToDoReminderSendOnWeekEnd =  @ToDoReminderSendOnWeekEnd,
	AvalaraEnabled = @AvalaraEnabled,
	AvalaraAccountID = @AvalaraAccountID,
	AvalaraLicenseKey = @AvalaraLicenseKey,
	AvalaraCompanyCode = @AvalaraCompanyCode,
	AvalaraDocRecordingDisabled = @AvalaraDocRecordingDisabled,
	AvalaraLoggingEnabled = @AvalaraLoggingEnabled,
	AvalaraSandboxEnabled = @AvalaraSandboxEnabled,
	AvalaraDisableAutoCalculate = @AvalaraDisableAutoCalculate,
	HideExpenseReportItems = @HideExpenseReportItems,
	SendIndividualApprovedEmails = @SendIndividualApprovedEmails,
	DefaultCampaignBillBy = @DefaultCampaignBillBy,
	DefaultDeliverableSortBy = @DefaultDeliverableSortBy,
	UseNewFileType = @UseNewFileType,
	UseExistingFileType = @UseExistingFileType,
	UseUrlFileType = @UseUrlFileType,
	UseVimeoFileType = @UseVimeoFileType,
	UseYouTubeFileType = @UseYouTubeFileType,
	UseAdvanceCommentsOnDeliverables = @UseAdvanceCommentsOnDeliverables,
	WeekendBucket = @WeekendBucket,
	DefaultCampUseCampaignBudget = @DefaultCampUseCampaignBudget,
	DefaultCampExpensesNotIncluded = @DefaultCampExpensesNotIncluded,
	ClientPortalShowProjectRequests = @ClientPortalShowProjectRequests,
	ProjectNumPrefixUseGLCompanyID = @ProjectNumPrefixUseGLCompanyID,
	VoucherSuperApproverKey = @VoucherSuperApproverKey,
	VoucherSuperMinLevel = @VoucherSuperMinLevel,
	VoucherMaxAmount = @VoucherMaxAmount,
	DefaultCCReceiptMessage = @DefaultCCReceiptMessage,
	ClientInvLogoPos = @ClientInvLogoPos,
	FileLinkExpirationDays = @FileLinkExpirationDays,
	OppProjectNonBillable = @OppProjectNonBillable,
	IOHideApprovedBy = @IOHideApprovedBy,
	IOHideAcceptedBy = @IOHideAcceptedBy,
	IOHideSpaceClose = @IOHideSpaceClose,
	IOHideMaterialsDue = @IOHideMaterialsDue,
	BCHideApprovedBy = @BCHideApprovedBy,
	BCHideAcceptedBy = @BCHideAcceptedBy,
	BCRequireStations = @BCRequireStations,
	IORequirePublications = @IORequirePublications,
	LoadNext50Conversations = @LoadNext50Conversations,
	RequireCommentsOnExpenseReports = @RequireCommentsOnExpenseReports,
	SendBWSNotifyEmail = @SendBWSNotifyEmail,
	SendCCApproverEmail = @SendCCApproverEmail,
	IOShowVendorInvoices = @IOShowVendorInvoices,
    BCShowVendorInvoices = @BCShowVendorInvoices

WHERE
	CompanyKey = @CompanyKey

-- (597823) Check to see if the TimeSheetPeriod has changed from weekly (2) to daily (1):
DECLARE @oldTimeSheetPeriod smallint
SELECT @oldTimeSheetPeriod = TimeSheetPeriod from tTimeOption where CompanyKey = @CompanyKey 

IF @oldTimeSheetPeriod = 2 AND @TimeSheetPeriod = 1 -- Going from weekly to daily. Need to zero out RequireMinHoursPerWeek and MinHoursPerWeek = 0 for their users who had this set
BEGIN
	CREATE TABLE #tUserKeys (UserKey int NULL)

	INSERT #tUserKeys(UserKey)
	SELECT up.UserKey
	FROM tUserPreference up
	INNER JOIN tUser u on up.UserKey = u.UserKey
	INNER JOIN tCompany c on u.CompanyKey = c.CompanyKey
	WHERE u.CompanyKey = @CompanyKey and ISNULL(up.RequireMinHoursPerWeek, 0) > 0

	UPDATE up SET RequireMinHoursPerWeek = 0, MinHoursPerWeek = 0
	FROM tUserPreference up
	INNER JOIN #tUserKeys on up.UserKey = #tUserKeys.UserKey
END

UPDATE
  tTimeOption
SET
  ShowServicesOnGrid = @ShowServicesOnGrid,
  ReqProjectOnTime = @ReqProjectOnTime,
  ReqServiceOnTime = @ReqServiceOnTime,
  TimeSheetPeriod = @TimeSheetPeriod, -- Missing from HTML
  StartTimeOn = @StartTimeOn, -- Missing from HTML
  AllowOverlap = @AllowOverlap, -- Missing from HTML
  PrintAsGrid = @PrintAsGrid, -- Missing from HTML
  AllowCustomDates = @AllowCustomDates, -- Missing from HTML
  LateEnteredDays = @LateEnteredDays,
  LateEnteredHours = @LateEnteredHours
WHERE
  CompanyKey = @CompanyKey 

IF EXISTS(
		SELECT NULL
		FROM	tPreferenceWelcome (nolock)
		WHERE	CompanyKey = @CompanyKey)
	UPDATE	tPreferenceWelcome
	SET		WelcomeMessage = @WelcomeMessage
	WHERE	CompanyKey = @CompanyKey
ELSE
	INSERT	tPreferenceWelcome
			(CompanyKey,
			WelcomeMessage)
	VALUES	(@CompanyKey,
			@WelcomeMessage)

delete tStringCompany Where CompanyKey = @CompanyKey and StringID like ''KeyUser%''
Insert tStringCompany (StringID, CompanyKey, StringSingular) Values (''KeyUser1'', @CompanyKey, @KeyPerson1)
Insert tStringCompany (StringID, CompanyKey, StringSingular) Values (''KeyUser2'', @CompanyKey, @KeyPerson2)
Insert tStringCompany (StringID, CompanyKey, StringSingular) Values (''KeyUser3'', @CompanyKey, @KeyPerson3)
Insert tStringCompany (StringID, CompanyKey, StringSingular) Values (''KeyUser4'', @CompanyKey, @KeyPerson4)
Insert tStringCompany (StringID, CompanyKey, StringSingular) Values (''KeyUser5'', @CompanyKey, @KeyPerson5)
Insert tStringCompany (StringID, CompanyKey, StringSingular) Values (''KeyUser6'', @CompanyKey, @KeyPerson6)

RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptActivityGetLastThreadUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptActivityGetLastThreadUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[sptActivityGetLastThreadUpdate]
	(
	@CompanyKey int,
	@EntityKey int
	)

AS --Encrypt

/*
|| When     Who Rel      What
|| 05/11/26	CRG 26.06.14 Created
*/

SELECT MAX(DateAdded) AS LastThreadUpdate
FROM tActivity (NOLOCK)
WHERE CompanyKey = @CompanyKey
AND RootActivityKey = @EntityKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPreferenceGetApp]'
GO
IF OBJECT_ID(N'[dbo].[sptPreferenceGetApp]', 'P') IS NOT NULL
EXEC sp_executesql N'


ALTER PROCEDURE [dbo].[sptPreferenceGetApp]
	@CompanyKey int,
	@UserKey int = null
AS --Encrypt

/*
|| When     Who Rel			What
|| 01/10/16 MAS 10.6.1.2	Cloned from sptPreferenceGetWJ for Platinum
|| 02/02/17 RLB 10.6.1.2    Added a project numbering style
|| 02/13/17 GAR 10.6.1.3    Added Mail Settings info for company connections admin page.  Also added single sign on info and DFA.
|| 02/16/17 GAR 10.6.1.3    Added EmailLinkExpirationDays, VCard, and CC info.
|| 02/20/17 GAR 10.6.1.3    Added API Access Token.
|| 02/23/17 KMC 10.6.1.3    Removed duplicate columns
|| 03/16/17 MAS 10.6.1.4    Added DefaultAPApprover & DefaultARApprover UserNames from vUserName 
|| 03/16/17 MFT 10.6.1.4    Added DefaultAccountManager
|| 04/04/17 MAS 10.6.1.5	Added InternalReviewInstructions, InternalReviewLoginRequired, ClientReviewLoginRequired & ClientReviewInstructions
|| 04/04/17 MAS 10.6.1.5	Added ShowInactiveInCriteria
|| 04/06/17 MCM 10.6.1.5    Added AllowTransferDate, NotifyExpenseReportName, PostCCWhenSentToVendor, SetInvoiceNumberOnApproval, SplitBilling
|| 05/01/17 MAS 10.6.1.5	(343597) Added p.*
|| 09/20/17 GHL 10.6.2.0    (295216) Added tTimeOption fields for timesheet tardiness. Renamed fields to LateEnteredDays/LateEnteredHours
|| 10/18/17 GWG 10.6.2.1    add in two new project numbering styles
|| 10/26/17 GHL 10.6.2.1    (368187) Added DefaultEstimateApproverName for enhancement for Spark44
|| 12/02/17	DDM 18.1.0	    Added new SMTP settings in Company Connections
|| 01/29/18	MAS 18.2.0	    Added TermsDescription
|| 04/04/18 GWG 18.4.0      Fix the email subject format to match the UI when defaulting
|| 08/03/18 RLS 18.8.0      (411237) Added 6 minutes as a timer interval option.
|| 08/21/18 AMP 18.9.0      (415365) Changes for the addition of a default Estimate Approver 
|| 02/21/19 AMP 19.0.3.0    (446692) Added the other type of DefaultEstTypeNames
|| 05/13/19 AMP 19.0.6.0    (455327) Added Default Billing Method Name
|| 05/28/19 AMP 19.0.6.0    (455327) Added Default Expenses Not Included for Fixed Fee
|| 05/29/19 AMP 19.0.6.0    (460062) Added Default Estimate Labor Taxable 
|| 09/24/19 MAS 19.1.0.0    (443765) Added Authorize.Net (beta) as a CCProcessor
|| 10/03/19 GAR 19.1.1.0    (482405) Timer interval 30 was incorrect.  Was showing ''15 Minutes''
|| 10/15/19 GWG 19.1.1.0    Adding in getting of key people to tran pref
|| 10/28/19 GAR 19.1.1.0    (473997) Added PM From Project option to DefaultEstimateApprover
|| 01/20/20 MCM 20.0.1.0    (496634) Added CCCAshAccountKey, CCCashAccountNumber 
|| 01/23/20 RLB 20.0.2.0    (465885) Adding deliverable Final Review options
|| 01/30/20 RLB 20.0.2.0    (465885) removed above change because it was not used
|| 01/19/21 AMP 21.02.14    (543392) Added PM From Project on Header to DefaultAPApproverName
|| 05/25/21 RLB 21.06.20    (558379) Added Default Campaign Estimate Type
|| 11/05/21 KMC 21.12.19    Added Office365EmailAuthorized and additional EmailProtocol entries
|| 01/31/22 MCM 22.02.x     (573522) Added ACH Fields
|| 08/17/23 AMP 23.09.17    (647294) Added TimeSheetPeriodDesc for Trans Pref logging
|| 08/26/24 RLS 24.09.15    (673662) Added ''BM From Project'' to DefaultEstimateApproverName
|| 10/03/24 MCM 24.11.x     (676228) Added VoucherSuperApproverName
|| 10/10/24 CRG 24.11.17    Fixed case of reference to vUserName because it was throwing an error on case sensitive servers
|| 02/27/25 KMC 25.04.20	(687086) Added fields for Google OAuth
|| 03/11/25 CRG 25.04.20    (687240) Added WelcomeMessage
|| 04/21/25 KMC 25.05.18    Added Office365SMTPAuthorized
|| 05/21/25 KMC 25.06.15    Added GoogleSMTPAuthorized
|| 04/21/26 RLS 26.05.17    (725399) Added Billing Manager to DefaultARApproverName
*/

DECLARE	@DefaultToDoStatusKey int,
		@DefaultToDoStatusName varchar(500)
			
SELECT	@DefaultToDoStatusKey = astat.ActivityStatusKey,
		@DefaultToDoStatusName = astat.StatusName
FROM	tActivityStatus astat (nolock)
WHERE	astat.CompanyKey = @CompanyKey
AND		astat.IsDefault = 1 and Entity = ''ToDo''


SELECT	 p.*
		,ioa.UserFullName as IOApproverName
		
		,CASE WHEN p.IOClientLink = 1 THEN ''Through Project'' ELSE ''Through Estimate'' END as IOClientLinkName
		
		,CASE WHEN p.BCClientLink = 1 THEN ''Through Project'' ELSE ''Through Estimate'' END as BCClientLinkName
		
		,boa.UserFullName as BCApproverName
		
		,CASE 
			WHEN ISNULL(CCProcessor,0) = 0 THEN ''No Credit Card Processing''
			WHEN ISNULL(CCProcessor,0) = 1 THEN ''Authorize.Net (beta)''
			WHEN ISNULL(CCProcessor,0) = 10 THEN ''Payflow Pro''
			ELSE ''No Credit Card Processing'' 
		END AS CCProcessorName
		
		,(Select ClassID from tClass (nolock) Where tClass.ClassKey = p.DefaultClassKey) AS DefaultClassID
		,(Select ClassName from tClass (nolock) Where tClass.ClassKey = p.DefaultClassKey) AS DefaultClassName

		,(Select RequireUserTimeDetails from tUser (nolock) where UserKey = @UserKey) as RequireUserTimeDetails
		,tTimeOption.ShowServicesOnGrid
		,tTimeOption.ReqProjectOnTime
		,tTimeOption.ReqServiceOnTime
		,tTimeOption.TimeSheetPeriod	
		,CASE 
			WHEN ISNULL(TimeSheetPeriod,0) = 1 THEN ''Daily''
			WHEN ISNULL(TimeSheetPeriod,0) = 2 THEN ''Weekly''			
		END AS TimeSheetPeriodDesc
		,tTimeOption.StartTimeOn
		,tTimeOption.AllowOverlap
		,tTimeOption.PrintAsGrid
		,tTimeOption.AllowCustomDates
		,isnull(tTimeOption.LateEnteredDays, 1) as LateEnteredDays
		,isnull(tTimeOption.LateEnteredHours, ''2017-09-20 08:30:00.000'') as LateEnteredHours -- we just need 08:30 
			
		,(Select CheckMethod from tCheckMethod (nolock) where tCheckMethod.CheckMethodKey = p.CheckMethodKey) as CheckMethod

		,tActivityType.TypeName as DefaultActivityTypeName

		,ea.TypeName as EmailsDefaultActivityTypeName

		,it.TypeName as DefaultToDoTypeName
		,@DefaultToDoStatusKey as DefaultToDoStatusKey
		,@DefaultToDoStatusName as DefaultToDoStatusName
		,sg.GroupName as GroupName

		,CASE 
			WHEN ISNULL(EmailSubjectFormat,0) = 0 THEN ''[Project Number and Name] Subject''
			WHEN ISNULL(EmailSubjectFormat,0) = 1 THEN ''[Project Number] Subject (Project Name)''
			ELSE ''Subject [Project Number and Name]'' 
		END AS EmailSubjectFormatName

		,CASE 
			WHEN ISNULL(GetRateFrom,0) = 1 THEN ''Client'' 
			WHEN ISNULL(GetRateFrom,0) = 2 THEN ''Project'' 
			WHEN ISNULL(GetRateFrom,0) = 3 THEN ''Project User'' 
			WHEN ISNULL(GetRateFrom,0) = 4 THEN ''Service'' 
			WHEN ISNULL(GetRateFrom,0) = 5 THEN ''Service Rate Sheet'' 
			WHEN ISNULL(GetRateFrom,0) = 6 THEN ''Task'' 
			WHEN ISNULL(GetRateFrom,0) = 9 THEN ''Billing Title'' 
			ELSE ''Billing Title Rate Sheet''
		END AS GetRateFromName

		,rts.RateSheetName as TimeRateSheetName
		,trs.RateSheetName as TitleRateSheetName

		,CASE 
			WHEN ISNULL(GetMarkupFrom,0) = 1 THEN ''Client'' 
			WHEN ISNULL(GetMarkupFrom,0) = 2 THEN ''Project'' 
			WHEN ISNULL(GetMarkupFrom,0) = 3 THEN ''Item'' 
			WHEN ISNULL(GetMarkupFrom,0) = 4 THEN ''Item Rate Sheet'' 
			ELSE ''Task''
		END AS GetMarkupFromName

		,irs.RateSheetName as ItemRateSheetName

		,CASE 
			WHEN ISNULL(ProjectNumStyle,0) = 1 THEN ''Prefix + Next Global Number'' 
			WHEN ISNULL(ProjectNumStyle,0) = 2 THEN ''Client ID + Next Number From client'' 
			WHEN ISNULL(ProjectNumStyle,0) = 3 THEN ''Prefix + Client ID + Next Number From client'' 
			WHEN ISNULL(ProjectNumStyle,0) = 4 THEN ''Prefix + Client ID + Next Global Number'' 
			WHEN ISNULL(ProjectNumStyle,0) = 5 THEN ''Office Prefix + Next Number from Office'' 
			WHEN ISNULL(ProjectNumStyle,0) = 6 THEN ''Project Type Prefix + Next Number from Type'' 
			WHEN ISNULL(ProjectNumStyle,0) = 7 THEN ''Client Division Prefix  + Next Number from Client Division'' 
			WHEN ISNULL(ProjectNumStyle,0) = 8 THEN ''Campaign ID + Next Number from Campaign'' 
			WHEN ISNULL(ProjectNumStyle,0) = 9 THEN ''Client ID + Next Global Number''
			WHEN ISNULL(ProjectNumStyle,0) = 10 THEN ''Next Global Number + Client ID''
			WHEN ISNULL(ProjectNumStyle,0) = 11 THEN ''Office Prefix + Client ID (or Division Prefix) + Next Number from Client (or Division)''
			ELSE ''Next Global Number + ClientID''
		END AS ProjectNumStyleName

		,CASE 
			WHEN ISNULL(CampaignNumStyle,0) = 1 THEN ''Prefix + Next Global Number'' 
			WHEN ISNULL(CampaignNumStyle,0) = 2 THEN ''Client ID + Next Number From client'' 
			WHEN ISNULL(CampaignNumStyle,0) = 3 THEN ''Prefix + Client ID + Next Number From client'' 
			ELSE ''Prefix + Client ID + Next Global Number'' 
		END AS CampaignNumStyleName

		,CASE 
			WHEN ISNULL(EstimateNumStyle,0) = 1 THEN ''Prefix + Next Global Number'' 
			ELSE ''Project Number As Prefix + Next Number By Project'' 
		END AS EstimateNumStyleName

		,CASE 
			WHEN ISNULL(TimerInterval,0) = 0 THEN ''No Rounding'' 
			WHEN ISNULL(TimerInterval,0) = 6 THEN ''6 Minutes'' 
			WHEN ISNULL(TimerInterval,0) = 15 THEN ''15 Minutes'' 
			WHEN ISNULL(TimerInterval,0) = 30 THEN ''30 Minutes'' 
		END AS TimerIntervalName

		,CASE 
			WHEN ISNULL(TimerRounding,0) = 0 THEN ''Up to the next interval'' 
			ELSE ''Down to the previous interval'' 
		END AS TimerRoundingName

		,CASE 
			WHEN ISNULL(InternalReviewReminderType,0) = 0 THEN ''Daily'' 
			ELSE ''Hourly'' 
		END AS InternalReviewReminderTypeName

		,CASE 
			WHEN ISNULL(ClientReviewReminderType,0) = 0 THEN ''Daily''
			ELSE ''Hourly'' 
		END AS ClientReviewReminderTypeName

		,ap.UserName AS DefaultAPApprover
		,CASE 
			WHEN ISNULL(DefaultAPApprover,0) = 0 THEN ''Person Entering the Invoice''
			WHEN ISNULL(DefaultAPApprover,0) = 1 THEN ''AE From Project on Header''
			WHEN ISNULL(DefaultAPApprover,0) = 2 THEN ''Automatically Approved''
		    WHEN ISNULL(DefaultAPApprover,0) = 4 THEN ''PM From Project on Header''
			ELSE ''Person Entered Below'' 
		END AS DefaultAPApproverName

		,ar.UserName AS DefaultARApprover
		,CASE 
			WHEN ISNULL(DefaultARApprover,0) = 0 THEN ''Person Entering the Invoice''
			WHEN ISNULL(DefaultARApprover,0) = 1 THEN ''AE From Project on Header''
			WHEN ISNULL(DefaultARApprover,0) = 2 THEN ''Automatically Approved''
			WHEN ISNULL(DefaultARApprover,0) = 4 THEN ''PM From Project on Header''
			WHEN ISNULL(DefaultARApprover,0) = 5 THEN ''BM From Project on Header''
			ELSE ''Person Entered Below'' 
		END AS DefaultARApproverName

		,CASE 
			WHEN ISNULL(DefaultEstimateApprover,0) = 0 THEN ''Person Entering the Estimate''
			WHEN ISNULL(DefaultEstimateApprover,0) = 1 THEN ''AE From Project''
			WHEN ISNULL(DefaultEstimateApprover,0) = 3 THEN ''PM From Project''
			WHEN ISNULL(DefaultEstimateApprover,0) = 4 THEN ''BM From Project''
			ELSE ''Person Entered Below'' 
		END AS DefaultEstimateApproverName

		,CASE 
			WHEN ISNULL(IOClientLink,1) = 1 THEN ''Through Project''
			ELSE ''Through Estimate'' 
		END AS IOClientLinkName

		,CASE 
			WHEN ISNULL(IOOrderDisplayMode,1) = 1 THEN ''Net Only''
			WHEN ISNULL(IOOrderDisplayMode,1) = 2 THEN ''Gross Only''
			ELSE ''Gross and Net'' 
		END AS IOOrderDisplayModeName

		,CASE 
			WHEN ISNULL(BCClientLink,1) = 1 THEN ''Through Project''
			ELSE ''Through Estimate'' 
		END AS BCClientLinkName

		,CASE 
			WHEN ISNULL(BCOrderDisplayMode,1) = 1 THEN ''Net Only''
			WHEN ISNULL(BCOrderDisplayMode,1) = 2 THEN ''Gross Only''
			ELSE ''Gross and Net'' 
		END AS BCOrderDisplayModeName

		,CASE 
			WHEN ISNULL(UseClearedDate,0) = 0 THEN ''Use Invoice Date''
			WHEN ISNULL(UseClearedDate,0) = 1 THEN ''Use Clear Date''
			ELSE ''Use Invoice Month'' 
		END AS UseClearedDateName

		,CASE 
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 0 THEN ''Daily''
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 1 THEN ''Sunday''
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 2 THEN ''Monday''
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 3 THEN ''Tuesday''
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 4 THEN ''Wednesday''
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 5 THEN ''Thursday''
			WHEN ISNULL(UnsubmittedTimeSheetFreq,0) = 6 THEN ''Friday''
			ELSE ''Saturday'' 
		END AS UnsubmittedTimeSheetFreqName

		,CASE 
			WHEN ISNULL(MissingTimeSheetFreq,0) = 0 THEN ''Daily''
			WHEN ISNULL(MissingTimeSheetFreq,0) = 1 THEN ''Sunday''
			WHEN ISNULL(MissingTimeSheetFreq,0) = 2 THEN ''Monday''
			WHEN ISNULL(MissingTimeSheetFreq,0) = 3 THEN ''Tuesday''
			WHEN ISNULL(MissingTimeSheetFreq,0) = 4 THEN ''Wednesday''
			WHEN ISNULL(MissingTimeSheetFreq,0) = 5 THEN ''Thursday''
			WHEN ISNULL(MissingTimeSheetFreq,0) = 6 THEN ''Friday''
			ELSE ''Saturday'' 
		END AS MissingTimeSheetFreqName			

		,CASE 
			WHEN ISNULL(DefaultEstType,0) = 1 THEN ''By Task Only''
			WHEN ISNULL(DefaultEstType,0) = 2 THEN ''By Task And Service''
			WHEN ISNULL(DefaultEstType,0) = 3 THEN ''By Task And Person''
			WHEN ISNULL(DefaultEstType,0) = 4 THEN ''By Service Only''
			WHEN ISNULL(DefaultEstType,0) = 5 THEN ''By Segment Service''
			WHEN ISNULL(DefaultEstType,0) = 6 THEN ''By Project''
			WHEN ISNULL(DefaultEstType,0) = 7 THEN ''By Title Only''
			WHEN ISNULL(DefaultEstType,0) = 8 THEN ''By Segment Title''
			ELSE '''' 
		END AS DefaultEstTypeName

		,CASE 
			WHEN ISNULL(DefaultCampaignEstType,0) = 4 THEN ''By Service Only''
			WHEN ISNULL(DefaultCampaignEstType,0) = 6 THEN ''By Project''
			WHEN ISNULL(DefaultCampaignEstType,0) = 7 THEN ''By Title Only''
			ELSE '''' 
		END AS DefaultCampaignEstTypeName

		,CASE 
			WHEN ISNULL(DefaultARLineFormat,0) = 0 THEN ''One Line Item''
			WHEN ISNULL(DefaultARLineFormat,0) = 1 THEN ''One Per Task''
			WHEN ISNULL(DefaultARLineFormat,0) = 2 THEN ''One Per Service''
			WHEN ISNULL(DefaultARLineFormat,0) = 3 THEN ''One Per Billing Item''
			WHEN ISNULL(DefaultARLineFormat,0) = 8 THEN ''One Per Billing Item and Item''
			WHEN ISNULL(DefaultARLineFormat,0) = 11 THEN ''One Per Title''
			WHEN ISNULL(DefaultARLineFormat,0) = 12 THEN ''One Per Title and Service''
			WHEN ISNULL(DefaultARLineFormat,0) = 13 THEN ''One Per Service and Title''
			WHEN ISNULL(DefaultARLineFormat,0) = 14 THEN ''One Per Service/Item''
			ELSE '''' 
		END
		AS DefaultARLineFormatName

		,ISNULL(pot.PurchaseOrderTypeName,'''') AS PurchaseOrderTypeName

		,ISNULL(ht.TextName,'''') AS POHeaderStandardTextName 

		,ISNULL(ft.TextName,'''') AS POFooterStandardTextName

		,ISNULL(ioot.PurchaseOrderTypeName,'''') AS DefaultPrintPOTypeName

		,ISNULL(ioht.TextName,'''') AS IOHeaderStandardTextName 

		,ISNULL(ioft.TextName,'''') AS IOFooterStandardTextName

		,ISNULL(bcot.PurchaseOrderTypeName,'''') AS DefaultBCPOTypeName

		,ISNULL(bcht.TextName,'''') AS BOHeaderStandardTextName 

		,ISNULL(bcft.TextName,'''') AS BOFooterStandardTextName

		,(Select StringSingular from tStringCompany (nolock) Where CompanyKey = @CompanyKey and StringID = ''KeyUser1'') as KeyPerson1
		,(Select StringSingular from tStringCompany (nolock) Where CompanyKey = @CompanyKey and StringID = ''KeyUser2'') as KeyPerson2
		,(Select StringSingular from tStringCompany (nolock) Where CompanyKey = @CompanyKey and StringID = ''KeyUser3'') as KeyPerson3
		,(Select StringSingular from tStringCompany (nolock) Where CompanyKey = @CompanyKey and StringID = ''KeyUser4'') as KeyPerson4
		,(Select StringSingular from tStringCompany (nolock) Where CompanyKey = @CompanyKey and StringID = ''KeyUser5'') as KeyPerson5
		,(Select StringSingular from tStringCompany (nolock) Where CompanyKey = @CompanyKey and StringID = ''KeyUser6'') as KeyPerson6

		,ar.UserFullName as DefaultARApproverFullName
		,ap.UserFullName as DefaultAPApproverFullName
		,e.UserFullName as DefaultEstimateApproverFullName

		,CASE 
			WHEN ISNULL(EmailProtocol,0) = 0 THEN ''Pop''
			WHEN ISNULL(EmailProtocol,0) = 1 THEN ''Imap''
			WHEN ISNULL(EmailProtocol,0) = 2 THEN ''Office 365 Pop OAuth''
			WHEN ISNULL(EmailProtocol,0) = 3 THEN ''Office 365 Imap OAuth''
			WHEN ISNULL(EmailProtocol,0) = 4 THEN ''Google Pop OAuth''
			WHEN ISNULL(EmailProtocol,0) = 5 THEN ''Google Imap OAuth''
		END AS EmailProtocolName
		,CASE
			WHEN ISNULL(Office365EmailAuthToken, '''') > '''' THEN 1
			ELSE 0
		END AS Office365EmailAuthorized
		,CASE
			WHEN ISNULL(GoogleEmailAuthToken, '''') > '''' THEN 1
			ELSE 0
		END AS GoogleEmailAuthorized
		,ne.UserName as NotifyExpenseReportName
		,su.UserName as VoucherSuperApproverName

		--SMTP Settings
		,ISNULL(p.SMTPServer, '''') SMTPServer,
		p.SMTPPort,
		ISNULL(p.SMTPUserID, '''') SMTPUserID,
		ISNULL(p.SMTPPassword,'''') SMTPPassword,
		ISNULL(p.SMTPSSL,0) SMTPSSL,
		ISNULL(p.SMTPAuthMethod,'''') SMTPAuthMethod,
		CASE
			WHEN ISNULL(Office365SMTPAuthToken, '''') > '''' THEN 1
			ELSE 0
		END AS Office365SMTPAuthorized,
		CASE
			WHEN ISNULL(GoogleSMTPAuthToken, '''') > '''' THEN 1
			ELSE 0
		END AS GoogleSMTPAuthorized,
		pt.TermsDescription	as TermsDescription
		,CASE 
			WHEN ISNULL(DefaultBillingMethod,0) = 1 THEN ''Time and Materials''
			WHEN ISNULL(DefaultBillingMethod,0) = 2 THEN ''Fixed Fee''
			WHEN ISNULL(DefaultBillingMethod,0) = 3 THEN ''Retainer''
			ELSE ''Time and Materials'' 
		END AS DefaultBillingMethodName,
		p.DefaultExpensesNotIncluded
		,CASE 
			WHEN DefaultEstLaborTaxable = -1 THEN ''Default from Template''''s Estimate''
			WHEN DefaultEstLaborTaxable = 0 THEN ''Not Taxable''
			WHEN DefaultEstLaborTaxable = 1 THEN ''Taxable By Task''
			WHEN DefaultEstLaborTaxable = 2 THEN ''Taxable By Project''
			WHEN DefaultEstLaborTaxable = 3 THEN ''Taxable By Service''
			WHEN DefaultEstLaborTaxable = 4 THEN ''Taxable By Title''
			ELSE ''Default from Template''''s Estimate'' 
		END AS EstimateLaborTaxableName
		, cgl.AccountNumber as CCCashAccountNumber
		, cgl.AccountName as CCCashAccountName
		, CASE 
			WHEN ISNULL(ACHProcessor,0) = 0 THEN ''No Credit Card Processing''
			WHEN ISNULL(ACHProcessor,0) = 1 THEN ''Authorize.Net (beta)''
		END as ACHProcessorName
		, achgl.AccountNumber as ACHCashAccountNumber
		, achgl.AccountName as ACHCashAccountName	
		,pw.WelcomeMessage
FROM tPreference p (NOLOCK) 
LEFT OUTER JOIN tTimeOption (nolock) on p.CompanyKey = tTimeOption.CompanyKey
LEFT OUTER JOIN tActivityType (nolock) on p.DefaultActivityTypeKey = tActivityType.ActivityTypeKey
LEFT OUTER JOIN tActivityType it (nolock) on p.DefaultToDoTypeKey = it.ActivityTypeKey
LEFT OUTER JOIN tActivityType ea (nolock) on p.EmailsDefaultActivityTypeKey = ea.ActivityTypeKey
LEFT OUTER JOIN tSecurityGroup sg (nolock) on p.SSOSecurityGroupKey = sg.SecurityGroupKey
LEFT OUTER JOIN tPurchaseOrderType pot (nolock) on p.DefaultPOType = pot.PurchaseOrderTypeKey
LEFT OUTER JOIN tStandardText ht (nolock) on p.POHeaderStandardTextKey = ht.StandardTextKey
LEFT OUTER JOIN tStandardText ft (nolock) on p.POFooterStandardTextKey = ft.StandardTextKey
LEFT OUTER JOIN tPurchaseOrderType ioot (nolock) on p.DefaultPrintPOType = ioot.PurchaseOrderTypeKey
LEFT OUTER JOIN tStandardText ioht (nolock) on p.IOHeaderStandardTextKey = ioht.StandardTextKey
LEFT OUTER JOIN tStandardText ioft (nolock) on p.IOFooterStandardTextKey = ioft.StandardTextKey
LEFT OUTER JOIN tPurchaseOrderType bcot (nolock) on p.DefaultBCPOType = bcot.PurchaseOrderTypeKey
LEFT OUTER JOIN tStandardText bcht (nolock) on p.BOHeaderStandardTextKey = bcht.StandardTextKey
LEFT OUTER JOIN tStandardText bcft (nolock) on p.BOFooterStandardTextKey = bcft.StandardTextKey
LEFT OUTER JOIN vUserName ar (nolock) on p.DefaultARApproverKey = ar.UserKey
LEFT OUTER JOIN vUserName ap (nolock) on p.DefaultAPApproverKey = ap.UserKey
LEFT OUTER JOIN vUserName e (nolock) on p.DefaultEstimateApproverKey = e.UserKey
LEFT OUTER JOIN vUserName ne (nolock) on p.NotifyExpenseReport = ne.UserKey
LEFT OUTER JOIN vUserName su (nolock) on p.VoucherSuperApproverKey = su.UserKey
LEFT OUTER JOIN tTimeRateSheet rts (nolock) on p.TimeRateSheetKey = rts.TimeRateSheetKey
LEFT OUTER JOIN tTitleRateSheet trs (nolock) on p.TitleRateSheetKey = trs.TitleRateSheetKey
LEFT OUTER JOIN tItemRateSheet irs (nolock) on p.ItemRateSheetKey = irs.ItemRateSheetKey
LEFT OUTER JOIN vUserName ioa (nolock) on p.IOApprover = ioa.UserKey
LEFT OUTER JOIN vUserName boa (nolock) on p.BCApprover = boa.UserKey
LEFT OUTER JOIN tPaymentTerms pt (nolock) on p.PaymentTermsKey = pt.PaymentTermsKey
LEFT OUTER JOIN tGLAccount cgl (nolock) on p.CCCashAccountKey = cgl.GLAccountKey
LEFT OUTER JOIN tGLAccount achgl (nolock) on p.ACHCashAccountKey = achgl.GLAccountKey
LEFT OUTER JOIN tPreferenceWelcome pw (nolock) on p.CompanyKey = pw.CompanyKey
WHERE p.CompanyKey = @CompanyKey

RETURN 1


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIAddUpdateToDo]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddUpdateToDo]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIAddUpdateToDo]
    (
        @CompanyKey         int,
        @UserKey            int,
        @ProjectNumber      nvarchar(100),
        @Subject            nvarchar(4000),
        @Notes              nvarchar(max)   = null,
        @ActivityDate       smalldatetime   = null,
        @Completed          tinyint         = 0,
        @AssignedUserName   varchar(100)    = null
    )

AS --Encrypt

/*
|| When      Who Rel        What
|| 04/30/26  GR  26.05.xx   Created - AI add/update ToDo activity by project number + subject match
|| 05/28/26  AI  26.05.28   spCheckAccess (tProject) replaces inline GL company + project assignment checks.
|| 05/28/26  CRG 26.06.14   Changed assigned user parm from key to text
*/

    select * into #errors from tAPIErrorTemplate where 1 = 2

    declare @SecurityGroupKey       int
    declare @IsAdministrator        bit
    declare @RestrictToGLCompany    int
    declare @CheckAssignment        int = 1
    declare @ProjectKey             int
    declare @GLCompanyKey           int
    declare @ActivityKey            int
    declare @ErrorCount             int
    declare @AssignedUserKey        int

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

    -- Required field validation
    if @ProjectNumber is null or LTRIM(RTRIM(@ProjectNumber)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''Project number is required.'', ''projectNumber'')

    if @Subject is null or LTRIM(RTRIM(@Subject)) = ''''
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''REQUIRED_FIELD'', ''Subject is required.'', ''subject'')

    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

    -- Security: prjEditToDos right required (administrators bypass)
    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     = ''prjEditToDos''
        )
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''error'', ''ACCESS_DENIED'', ''You do not have permission to add or edit To Dos.'', ''general'')

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

    -- Resolve project number to key
    select  @ProjectKey   = p.ProjectKey,
            @GLCompanyKey = p.GLCompanyKey
    from    tProject p (nolock)
    where   p.CompanyKey        = @CompanyKey
    and     p.ProjectNumber     = @ProjectNumber
    and     ISNULL(p.Deleted, 0) = 0

    if @ProjectKey is null
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''NOT_FOUND'', ''Project not found for the given project number.'', ''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) — replaces the
    -- inline GL company + project-assignment checks.
    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

    select @AssignedUserKey = MIN(UserKey) from tUser (nolock)
    where  CompanyKey = @CompanyKey
      and  (UPPER(Email) = UPPER(@AssignedUserName)
            or UPPER(UserID) = UPPER(@AssignedUserName)
            or UPPER(FirstName + '' '' + LastName) = UPPER(@AssignedUserName))

    -- Upsert: match on Subject + ProjectKey for ActivityEntity = ''ToDo''
    select  @ActivityKey = ActivityKey
    from    tActivity (nolock)
    where   CompanyKey       = @CompanyKey
    and     ProjectKey       = @ProjectKey
    and     Subject          = @Subject
    and     ActivityEntity   = ''ToDo''
    and     ParentActivityKey = 0

    if @ActivityKey is not null
    begin
        update  tActivity
        set     Notes           = @Notes,
				ActivityDate    = isnull(@ActivityDate, dbo.fFormatDateNoTime(getutcdate())),
                Completed       = @Completed,
                AssignedUserKey = @AssignedUserKey,
                DateUpdated     = dbo.fFormatDateNoTime(getutcdate()),
                UpdatedByKey    = @UserKey
        where   ActivityKey     = @ActivityKey
        and     CompanyKey      = @CompanyKey
        and     ActivityEntity  = ''ToDo''
    end
    else
    begin
        insert into tActivity
        (
            CompanyKey, ParentActivityKey, RootActivityKey,
            ActivityEntity, Subject, ProjectKey,
            AssignedUserKey, OriginatorUserKey, AddedByKey, UpdatedByKey,
            Notes, ActivityDate, Completed,
            GLCompanyKey,
            DateAdded, DateUpdated
        )
        values
        (
            @CompanyKey, 0, 0,
            ''ToDo'', @Subject, @ProjectKey,
            @AssignedUserKey, @UserKey, @UserKey, @UserKey,
            @Notes, isnull(@ActivityDate, dbo.fFormatDateNoTime(getutcdate())), ISNULL(@Completed, 0),
            @GLCompanyKey, 
            dbo.fFormatDateNoTime(getutcdate()), dbo.fFormatDateNoTime(getutcdate())
        )

        select @ActivityKey = SCOPE_IDENTITY()
    end

    -- Return warnings (if any) then result
    select  errorType, errorCode, errorMessage, fieldName
    from    #errors
    where   errorType = ''warning''

    select  @ActivityKey as activityKey,
            @ProjectKey  as projectKey,
            @Subject     as subject

    drop table #errors

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tEmailTemplateSection]'
GO
IF OBJECT_ID(N'[dbo].[tEmailTemplateSection]', 'U') IS NULL
CREATE TABLE [dbo].[tEmailTemplateSection]
(
[EmailTemplateSectionKey] [int] NOT NULL IDENTITY(1, 1),
[EmailTemplateKey] [int] NOT NULL,
[EmailTemplateSectionDefKey] [int] NOT NULL,
[DisplayOrder] [int] NOT NULL,
[PromptText] [varchar] (max) NULL,
[DateAdded] [smalldatetime] NOT NULL,
[DateUpdated] [smalldatetime] NOT NULL,
[SectionName] [varchar] (500) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tEmailTemplate]'
GO
IF OBJECT_ID(N'[dbo].[tEmailTemplate]', 'U') IS NULL
CREATE TABLE [dbo].[tEmailTemplate]
(
[EmailTemplateKey] [int] NOT NULL IDENTITY(1, 1),
[CompanyKey] [int] NOT NULL,
[EmailTemplateName] [varchar] (100) NOT NULL,
[Description] [varchar] (500) NULL,
[Entity] [varchar] (50) NULL,
[EntityType] [int] NULL,
[DateAdded] [smalldatetime] NOT NULL,
[DateUpdated] [smalldatetime] NOT NULL,
[Active] [int] NOT NULL CONSTRAINT [DF_tEmailTemplate_Active] DEFAULT ((0))
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tEmailTemplate] on [dbo].[tEmailTemplate]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tEmailTemplate]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tEmailTemplate]', 'U'))
ALTER TABLE [dbo].[tEmailTemplate] ADD CONSTRAINT [PK_tEmailTemplate] PRIMARY KEY CLUSTERED ([EmailTemplateKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptEmailTemplateDelete]
    @EmailTemplateKey  INT
AS --Encrypt

/*
|| When			Who Rel		What
|| 04/10/2026	MAS	??		Created	
*/

DELETE
FROM tEmailTemplateSection
WHERE EmailTemplateKey = @EmailTemplateKey;

DELETE
FROM tEmailTemplate
WHERE EmailTemplateKey = @EmailTemplateKey;

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIVoucherUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIVoucherUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   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
*/

    -- ----------------------------------------------------------------
    -- 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

    -- ----------------------------------------------------------------
    -- GL company restriction check
    -- For updates: check against the existing record''s GL company when
    -- the caller did not specify a new one
    -- ----------------------------------------------------------------
    Declare @GLCompanyKeyToCheck int
    Set @GLCompanyKeyToCheck = Case When @GLCompanyKey Is Not Null Then @GLCompanyKey
                                    Else @ExistingGLCompanyKey
                               End

    If @IsAdministrator = 0 And @RestrictToGLCompany = 1 And @GLCompanyKeyToCheck Is Not Null
    Begin
        If Not Exists (
            Select  1
            From    tUserGLCompanyAccess (nolock)
            Where   UserKey     = @UserKey
              And   GLCompanyKey = @GLCompanyKeyToCheck
        )
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'',
                    ''You do not have GL company access to this vendor invoice.'', ''glCompanyID'')
            Goto ReturnResult
        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].[sptPreferenceUpdateNumber]'
GO
IF OBJECT_ID(N'[dbo].[sptPreferenceUpdateNumber]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptPreferenceUpdateNumber]
 @CompanyKey int,
 @ProjectNumStyle smallint,
 @ProjectNumPrefix varchar(10),
 @NextProjectNum int,
 @ProjectNumPlaces int,
 @ProjectNumSep char(1),
 @ProjectNumPrefixUseYear tinyint,
 @PONumPrefix varchar(10),
 @NextPONum int,
 @PONumPlaces int,
 @IONumPrefix varchar(10),
 @NextIONum int,
 @IONumPlaces int,
 @BCNumPrefix varchar(10),
 @NextBCNum int,
 @BCNumPlaces int,
 @ARNumPrefix varchar(10),
 @AdvBillPrefix varchar(10),
 @NextARNum int,
 @ARNumPlaces int,
 @DefaultARApprover smallint,
 @DefaultARApproverKey int,
 @DefaultAPApprover smallint,
 @DefaultAPApproverKey int, 
 @ExpenseNumPrefix varchar(10),
 @NextExpenseNum int,
 @ExpenseNumPlaces int,
 @RequireRequest tinyint,
 @NotifyExpenseReport int,
 @GetRateFrom smallint,
 @TimeRateSheetKey int,
 @HourlyRate money,
 @GetMarkupFrom money,
 @ItemRateSheetKey int,
 @ItemMarkup decimal(24,4),
 @IOCommission decimal(24,4),
 @BCCommission decimal(24,4),
 @GetItemRate tinyint,
 @DefaultPOType int,
 @DefaultPrintPOType int,
 @DefaultBCPOType int,
 @IOOrderDisplayMode smallint,
 @BCOrderDisplayMode smallint,
 @IOApprover int,
 @BCApprover int,
 @IOClientLink smallint,
 @BCClientLink smallint, 
 @PaymentTermsKey int,
 @SendAssignmentEmail tinyint,
 @AutoScheduleProjects tinyint,
 @RequireMasterTask tinyint,
 @DefaultARLineFormat smallint,
 @ShowCustomRptConditions tinyint,
 @SetInvoiceNumberOnApproval tinyint,
 @SyncDeletesContacts tinyint,
 @SyncDeleteEvents tinyint,
 @AutoApproveExternalOrders tinyint,
 @ActualDateUpdatesPlan tinyint,
 @RequireTimeDetails tinyint,
 @UseMilitaryTime tinyint,
 @IOPrintClientOnOrder tinyint,
 @BCPrintClientOnOrder tinyint,
 @EstimateNumStyle smallint,
 @EstimateNumPrefix varchar(10),
 @NextEstimateNum int,
 @EstimateNumPlaces int,
 @EstimateNumSep char(1),
 @EstimateNumPrefixUseYear tinyint,
 @EstimateInternalApprovalDays int,
 @EstimateExternalApprovalDays int,
 @IOAllowChangesAfterClientInvoice tinyint,
 @BCAllowChangesAfterClientInvoice tinyint,
 @IOShowAdjustmentsAsSingleLine tinyint,
 @BCShowAdjustmentsAsSingleLine tinyint,
 @IOUseClientCosting tinyint,
 @BCUseClientCosting tinyint,
 @BCUseProductName tinyint,
 @EditVendorInvTax tinyint,
 @POUnitCostDecimalPlaces int,
 @POQtyDecimalPlaces int,
 @UseUnitRate tinyint,
 @AutoApproveExternalInvoices tinyint,
 @UseClearedDate tinyint,
 @BCGeneratePrebilledRevisions tinyint,
 @IOGeneratePrebilledRevisions tinyint,
 @PrintTrafficOnBC tinyint,
 @UseExpenseTypeClassOnVoucher tinyint,
 @AutoGenVoucherFromER tinyint,
 @SplitBilling tinyint,
 @DuplicateVendorInvoiceNbr tinyint,
 @UseCompanyFolders tinyint,
 @UseContactFolders tinyint,
 @UseLeadFolders tinyint,
 @UseActivityFolders tinyint,
 @UseOppFolders tinyint,
 @EmailsVisibleToClient tinyint,
 @EmailsDefaultActivityTypeKey int,
 @DefaultActivityTypeKey int,
 @AutoGenerateInvoiceOrderLines tinyint,
 @RequireCommentsOnTime tinyint = null,
 @CloseMonthBLInvoice tinyint = null,
 @PrintClient tinyint = null,
 @PrintDivision tinyint = null,
 @RequestRejectReason tinyint = null,
 @OneProjectAllowedPerRequest tinyint = 0
 
AS --Encrypt

  /*
  || When     Who Rel		What
  || 01/11/07 GHL 8.4		Added RequireMasterTask logic to limit problems with missing tTask.MasterTaskKey 
  || 05/07/07 CRG 8.4.3		(9061) Added UseExpenseTypeClassOnVoucher parameter
  || 09/05/07 GWG 8.5		Added the autogen parameter
  || 10/22/07 CRG 8.5		(13583) Added SplitBilling parameter
  || 06/03/08 RTC 8.5		Added DuplicateVendorInvoiceNbr
  || 04/03/09 GWG 10.5		Added Email codes
  || 05/29/09 RTC 10.5		Added AutoGenerateInvoiceOrderLines
  || 06/10/09 QMD 10.5		Added SyncDeleteEvent
  || 11/12/09 MAS 10.5.1.3  (68340)Added ClientCosting 
  || 11/12/09 MAS 10.5.1.7  (72080)Added BCUseProductName 
  || 03/26/10 MAS 10.5.2	(76058)Added UseClearedDate
  || 04/29/10 MAS 10.5.2.2  (78968)Added ReqCommentsOnTime
  || 08/31/10 RLB 10.5.3.4  (88154) Added @DefaultAPApprover 
  || 04/18/13 MAS 10.5.6.7  Removed EnableLogging
  || 06/14/14 PLC 10.5.8.1  Added CloseMOnthBLINvoice for strata
  || 12/30/15 GAR 10.5.9.9  Added pref to print or not print client and division on a PO.
  || 02/03/16 WDF 10.6.0.1 (288182) Added @RequestRejectReason
  || 09/27/18 GAR 18.9.1.0 (412560) Added OneProjectAllowedPerRequest for allowing only one project per project request
  || 05/05/26 MFT 26.0.5.0 (718171) Added AB prefix
  */
  
 DECLARE @OldRequireMasterTask INT
 SELECT  @OldRequireMasterTask = RequireMasterTask FROM tPreference (NOLOCK) WHERE CompanyKey = @CompanyKey
 IF @OldRequireMasterTask = 0 AND @RequireMasterTask = 1
 BEGIN
	UPDATE tTask
	SET    tTask.MasterTaskKey = mt.MasterTaskKey
	FROM   tProject p (NOLOCK)
	      ,tMasterTask mt (NOLOCK)
	WHERE  p.ProjectKey = tTask.ProjectKey
	AND    p.CompanyKey = @CompanyKey
	AND    mt.CompanyKey = @CompanyKey
	AND    tTask.TrackBudget = 1
	AND    tTask.MasterTaskKey IS NULL
	AND    tTask.TaskID = mt.TaskID
 END
 
 UPDATE
  tPreference
 SET
  ProjectNumStyle = @ProjectNumStyle,
  ProjectNumPrefix = @ProjectNumPrefix,
  NextProjectNum = @NextProjectNum,
  ProjectNumPlaces = @ProjectNumPlaces,
  ProjectNumSep = @ProjectNumSep,
  ProjectNumPrefixUseYear = @ProjectNumPrefixUseYear,
  PONumPrefix = @PONumPrefix,
  NextPONum = @NextPONum,
  PONumPlaces = @PONumPlaces,
  IONumPrefix = @IONumPrefix,
  NextIONum = @NextIONum,
  IONumPlaces = @IONumPlaces,
  BCNumPrefix = @BCNumPrefix,
  NextBCNum = @NextBCNum,
  BCNumPlaces = @BCNumPlaces,
  ARNumPrefix = @ARNumPrefix,
  AdvBillPrefix = @AdvBillPrefix,
  NextARNum = @NextARNum,
  ARNumPlaces = @ARNumPlaces,
  DefaultARApprover = @DefaultARApprover,
  DefaultARApproverKey = @DefaultARApproverKey,
  DefaultAPApprover = @DefaultAPApprover,
  DefaultAPApproverKey = @DefaultAPApproverKey,
  ExpenseNumPrefix = @ExpenseNumPrefix,
  NextExpenseNum = @NextExpenseNum,
  ExpenseNumPlaces = @ExpenseNumPlaces,
  RequireRequest = @RequireRequest,
  NotifyExpenseReport = @NotifyExpenseReport,
  GetRateFrom = @GetRateFrom,
  HourlyRate = 	@HourlyRate,
  GetMarkupFrom =	@GetMarkupFrom,
  TimeRateSheetKey = @TimeRateSheetKey,
  ItemRateSheetKey = 	@ItemRateSheetKey,
  ItemMarkup =	@ItemMarkup,
  IOCommission = @IOCommission,
  BCCommission = @BCCommission,
  GetItemRate = @GetItemRate,
  DefaultPOType = @DefaultPOType,
  DefaultPrintPOType = @DefaultPrintPOType,
  DefaultBCPOType = @DefaultBCPOType,
  IOOrderDisplayMode = @IOOrderDisplayMode,
  BCOrderDisplayMode = @BCOrderDisplayMode,
  IOApprover = @IOApprover,
  BCApprover = @BCApprover,
  IOClientLink = @IOClientLink,
  BCClientLink = @BCClientLink,
  PaymentTermsKey = @PaymentTermsKey,
  SendAssignmentEmail = @SendAssignmentEmail,
  AutoScheduleProjects = @AutoScheduleProjects,
  RequireMasterTask = @RequireMasterTask,
  DefaultARLineFormat = @DefaultARLineFormat,
  ShowCustomRptConditions = @ShowCustomRptConditions,
  SetInvoiceNumberOnApproval = @SetInvoiceNumberOnApproval,
  SyncDeletesContacts = @SyncDeletesContacts,
  SyncDeleteEvents = @SyncDeleteEvents,
  AutoApproveExternalOrders = @AutoApproveExternalOrders,
  ActualDateUpdatesPlan = @ActualDateUpdatesPlan,
  RequireTimeDetails = @RequireTimeDetails,	
  UseMilitaryTime = @UseMilitaryTime,
  IOPrintClientOnOrder = @IOPrintClientOnOrder,
  BCPrintClientOnOrder = @BCPrintClientOnOrder,
  EstimateNumStyle = @EstimateNumStyle,
  EstimateNumPrefix = @EstimateNumPrefix,
  NextEstimateNum = @NextEstimateNum,
  EstimateNumPlaces = @EstimateNumPlaces,
  EstimateNumSep = @EstimateNumSep,
  EstimateNumPrefixUseYear = @EstimateNumPrefixUseYear,  
  EstimateInternalApprovalDays = @EstimateInternalApprovalDays,  
  EstimateExternalApprovalDays = @EstimateExternalApprovalDays,  
  IOAllowChangesAfterClientInvoice = @IOAllowChangesAfterClientInvoice, 
  BCAllowChangesAfterClientInvoice = @BCAllowChangesAfterClientInvoice, 
  IOShowAdjustmentsAsSingleLine = @IOShowAdjustmentsAsSingleLine,
  BCShowAdjustmentsAsSingleLine = @BCShowAdjustmentsAsSingleLine,
  IOUseClientCosting = @IOUseClientCosting,
  BCUseClientCosting = @BCUseClientCosting,
  BCUseProductName = @BCUseProductName,
  EditVendorInvTax = @EditVendorInvTax,
  POUnitCostDecimalPlaces = @POUnitCostDecimalPlaces,
  POQtyDecimalPlaces = @POQtyDecimalPlaces,
  UseUnitRate = @UseUnitRate,
  AutoApproveExternalInvoices = @AutoApproveExternalInvoices,
  UseClearedDate = @UseClearedDate,
  BCGeneratePrebilledRevisions = @BCGeneratePrebilledRevisions,
  IOGeneratePrebilledRevisions = @IOGeneratePrebilledRevisions,
  PrintTrafficOnBC = @PrintTrafficOnBC,
  UseExpenseTypeClassOnVoucher = @UseExpenseTypeClassOnVoucher,
  AutoGenVoucherFromER = @AutoGenVoucherFromER,
  SplitBilling = @SplitBilling,
  DuplicateVendorInvoiceNbr = @DuplicateVendorInvoiceNbr,
  UseCompanyFolders = @UseCompanyFolders,
  UseContactFolders = @UseContactFolders,
  UseLeadFolders = @UseLeadFolders,
  UseActivityFolders = @UseActivityFolders,
  UseOppFolders = @UseOppFolders,
  EmailsVisibleToClient = @EmailsVisibleToClient,
  EmailsDefaultActivityTypeKey = @EmailsDefaultActivityTypeKey,
  DefaultActivityTypeKey = @DefaultActivityTypeKey,
  AutoGenerateInvoiceOrderLines = @AutoGenerateInvoiceOrderLines,
  RequireCommentsOnTime = @RequireCommentsOnTime,
  CloseMonthBLInvoice = isnull(CloseMonthBLInvoice,0),
  PrintClient = @PrintClient,
  PrintDivision = @PrintDivision,
  RequestRejectReason = @RequestRejectReason,
  OneProjectAllowedPerRequest = @OneProjectAllowedPerRequest
 WHERE
  CompanyKey = @CompanyKey 
 RETURN 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIVoucherDetailUpdate]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIVoucherDetailUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   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
*/

    -- ----------------------------------------------------------------
    -- 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

    -- ----------------------------------------------------------------
    -- GL company access check
    -- ----------------------------------------------------------------
    Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    From    tPreference (nolock)
    Where   CompanyKey = @CompanyKey

    If @IsAdministrator = 0 And @RestrictToGLCompany = 1 And @VoucherGLCompanyKey Is Not Null
    Begin
        If Not Exists (
            Select  1
            From    tUserGLCompanyAccess (nolock)
            Where   UserKey     = @UserKey
              And   GLCompanyKey = @VoucherGLCompanyKey
        )
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'',
                    ''You do not have GL company access to modify this vendor invoice.'', ''voucherKey'')
            Goto ReturnResult
        End
    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'Creating [dbo].[spApiAIPurchaseOrderGet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIPurchaseOrderGet]', 'P') IS NULL
EXEC sp_executesql N'
CREATE    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.
*/

    Declare @PurchaseOrderKey       int
    Declare @POStatus               smallint
    Declare @POGLCompanyKey         int
    Declare @RestrictToGLCompany    int

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- ----------------------------------------------------------------
    -- 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

    -- ----------------------------------------------------------------
    -- GL company access check — user must have access to the PO''s
    -- GL company when RestrictToGLCompany is enabled.
    -- ----------------------------------------------------------------
    Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
    From    tPreference (nolock)
    Where   CompanyKey = @CompanyKey

    If @RestrictToGLCompany = 1 And @POGLCompanyKey Is Not Null
    Begin
        If Not Exists (
            Select  1
            From    tUserGLCompanyAccess (nolock)
            Where   UserKey      = @UserKey
              And   GLCompanyKey = @POGLCompanyKey
        )
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'',
                    ''You do not have GL company access to purchase order '' + @PurchaseOrderNumber + ''.'',
                    ''orderNumber'')
            Goto ReturnResult
        End
    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'Creating [dbo].[spApiAIGetConversations]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetConversations]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[spApiAIGetConversations]
(
    @CompanyKey     int,
    @UserKey        int,
    @Entity         varchar(50)  = null,    -- REQUIRED. Caller-facing entity name: ''Project'', ''Company'',
                                            --   ''Voucher'', ''Invoice'', ''Campaign'', ''Contact'', 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''.
*/

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'')
    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

    -- ------------------------------------------------------------------
    -- 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  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.'',
                    ''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 is the exception (link ''tUser'' -> check
        --  ''tUser_Contact'').
        set @CheckEntity = @LinkEntity
        if @Entity = ''Contact''
            set @CheckEntity = ''tUser_Contact''

        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 inner join yields at most one row per activity.
    -- ------------------------------------------------------------------
    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)
    inner 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   (@StartDate is null or a.ActivityDate >= @StartDate)
      and   (@EndDate   is null or a.ActivityDate <= @EndDate)
    order by a.ActivityDate desc, a.ActivityKey desc

    drop table #errors
    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAISpecSheetGetList]'
GO
IF OBJECT_ID(N'[dbo].[spApiAISpecSheetGetList]', 'P') IS NULL
EXEC sp_executesql N'Create   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
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @CheckAssignment        int = 1
    Declare @GLCompanyKey           int
    Declare @EntityKey              int

    Select * Into #errors From tAPIErrorTemplate Where 1 = 2

    -- Validate required parameters
    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'')

    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

    -- Validate entity type
    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

    -- Load user security context
    Select  @SecurityGroupKey   = SecurityGroupKey,
            @IsAdministrator    = Administrator
    From    tUser (nolock)
    Where   UserKey     = @UserKey
    And     CompanyKey  = @CompanyKey

    -- -----------------------------------------------------------------------
    -- Project entity security
    -- -----------------------------------------------------------------------
    If @Entity = ''Project''
    Begin
        -- Resolve ProjectNumber to ProjectKey
        Select  @EntityKey    = ProjectKey,
                @GLCompanyKey = GLCompanyKey
        From    tProject (nolock)
        Where   CompanyKey    = @CompanyKey
        And     ProjectNumber = @EntityNumber

        If @EntityKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''Project not found.'', ''entityNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -101
        End

        -- GL company restriction
        If @IsAdministrator = 0
        Begin
            Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
            From   tPreference (nolock)
            Where  CompanyKey = @CompanyKey

            If @RestrictToGLCompany = 1
            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 access to this project.'', ''entityKey'')

                    Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                    Drop Table #errors
                    Return -103
                End
            End
        End

        -- Project assignment check
        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     = ''prjAccessAny''
            )
                Select @CheckAssignment = 0

            If @CheckAssignment = 1
            Begin
                If Not Exists (
                    Select 1
                    From   tAssignment (nolock)
                    Where  ProjectKey  = @EntityKey
                    And    UserKey     = @UserKey
                )
                Begin
                    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                    Values (''error'', ''ACCESS_DENIED'', ''You are not assigned to this project.'', ''entityKey'')

                    Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                    Drop Table #errors
                    Return -103
                End
            End
        End
    End

    -- -----------------------------------------------------------------------
    -- Lead / Leads entity
    -- -----------------------------------------------------------------------
    If @Entity In (''Lead'', ''Leads'')
    Begin
        Select  @EntityKey = LeadKey
        From    tLead (nolock)
        Where   CompanyKey = @CompanyKey
        And     LeadID     = TRY_CAST(@EntityNumber As int)

        If @EntityKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''Lead not found.'', ''entityNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -101
        End
    End

    -- -----------------------------------------------------------------------
    -- ProjectRequest entity
    -- -----------------------------------------------------------------------
    If @Entity = ''ProjectRequest''
    Begin
        Select  @EntityKey = RequestKey
        From    tRequest (nolock)
        Where   CompanyKey = @CompanyKey
        And     RequestID  = @EntityNumber

        If @EntityKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''Project request not found.'', ''entityNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -101
        End
    End

    -- -----------------------------------------------------------------------
    -- Campaign entity
    -- -----------------------------------------------------------------------
    If @Entity = ''Campaign''
    Begin
        Select  @EntityKey = CampaignKey
        From    tCampaign (nolock)
        Where   CompanyKey  = @CompanyKey
        And     CampaignID  = @EntityNumber

        If @EntityKey Is Null
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''NOT_FOUND'', ''Campaign not found.'', ''entityNumber'')

            Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
            Drop Table #errors
            Return -101
        End
    End

    -- Return spec sheets
    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
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spLoadStandardPreference]'
GO
IF OBJECT_ID(N'[dbo].[spLoadStandardPreference]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spLoadStandardPreference]
 @CompanyKey int,
 @ProjectNumStyle smallint,
 @ProjectNumPrefix varchar(10),
 @NextProjectNum int,
 @ProjectNumPlaces int,
 @ProjectNumSep char(1),
 @ProjectNumPrefixUseYear tinyint,
 @PONumPrefix varchar(10),
 @NextPONum int,
 @PONumPlaces int,
 @IONumPrefix varchar(10),
 @NextIONum int,
 @IONumPlaces int,
 @BCNumPrefix varchar(10),
 @NextBCNum int,
 @BCNumPlaces int,
 @ARNumPrefix varchar(10),
 @AdvBillPrefix varchar(10),
 @NextARNum int,
 @ARNumPlaces int,
 @DefaultARApprover smallint,
 @DefaultARApproverKey int,
 @DefaultAPApprover smallint,
 @DefaultAPApproverKey int, 
 @ExpenseNumPrefix varchar(10),
 @NextExpenseNum int,
 @ExpenseNumPlaces int,
 @RequireRequest tinyint,
 @NotifyExpenseReport int,
 @GetRateFrom smallint,
 @TimeRateSheetKey int,
 @HourlyRate money,
 @GetMarkupFrom money,
 @ItemRateSheetKey int,
 @ItemMarkup decimal(24,4),
 @IOCommission decimal(24,4),
 @BCCommission decimal(24,4),
 @GetItemRate tinyint,
 @DefaultPOType int,
 @DefaultPrintPOType int,
 @DefaultBCPOType int,
 @IOOrderDisplayMode smallint,
 @BCOrderDisplayMode smallint,
 @IOApprover int,
 @BCApprover int,
 @IOClientLink smallint,
 @BCClientLink smallint, 
 @PaymentTermsKey int,
 @SendAssignmentEmail tinyint,
 @AutoScheduleProjects tinyint,
 @RequireMasterTask tinyint,
 @DefaultARLineFormat smallint,
 @ShowCustomRptConditions tinyint,
 @SetInvoiceNumberOnApproval tinyint,
 @SyncDeletesContacts tinyint,
 @SyncDeleteEvents tinyint,
 @AutoApproveExternalOrders tinyint,
 @ActualDateUpdatesPlan tinyint,
 @RequireTimeDetails tinyint,
 @UseMilitaryTime tinyint,
 @IOPrintClientOnOrder tinyint,
 @BCPrintClientOnOrder tinyint,
 @EstimateNumStyle smallint,
 @EstimateNumPrefix varchar(10),
 @NextEstimateNum int,
 @EstimateNumPlaces int,
 @EstimateNumSep char(1),
 @EstimateNumPrefixUseYear tinyint,
 @EstimateInternalApprovalDays int,
 @EstimateExternalApprovalDays int,
 @IOAllowChangesAfterClientInvoice tinyint,
 @BCAllowChangesAfterClientInvoice tinyint,
 @IOShowAdjustmentsAsSingleLine tinyint,
 @BCShowAdjustmentsAsSingleLine tinyint,
 @IOUseClientCosting tinyint,
 @BCUseClientCosting tinyint,
 @BCUseProductName tinyint,
 @EditVendorInvTax tinyint,
 @POUnitCostDecimalPlaces int,
 @POQtyDecimalPlaces int,
 @UseUnitRate tinyint,
 @AutoApproveExternalInvoices tinyint,
 @UseClearedDate tinyint,
 @BCGeneratePrebilledRevisions tinyint,
 @IOGeneratePrebilledRevisions tinyint,
 @PrintTrafficOnBC tinyint,
 @UseExpenseTypeClassOnVoucher tinyint,
 @AutoGenVoucherFromER tinyint,
 @SplitBilling tinyint,
 @DuplicateVendorInvoiceNbr tinyint,
 @UseCompanyFolders tinyint,
 @UseContactFolders tinyint,
 @UseLeadFolders tinyint,
 @UseActivityFolders tinyint,
 @UseOppFolders tinyint,
 @EmailsVisibleToClient tinyint,
 @EmailsDefaultActivityTypeKey int,
 @DefaultActivityTypeKey int,
 @AutoGenerateInvoiceOrderLines tinyint,
 @RequireCommentsOnTime tinyint,
 @AutoScheduleTaskEndDate tinyint = 1,
 @UseToDo tinyint = 0,
 @EmailTimeSubmittal tinyint = 1 ,
 @NoTimeBeforeGLCloseDate tinyint = 1

AS --Encrypt

  /*
  || When     Who Rel		What
  || 06/04/07 GHL 10.530	(80920) Decided to have a wrapper for [sptPreferenceUpdateNumber] or [sptPreferenceUpdateNumberWMJ]
  ||                        1) If we add a field to tPreference, we can modify the call here (with a hardcoded value) 
  ||                        without having to modify load_standard.aspx
  ||                        2) After the table change is deployed we can refresh the data XML file and modify load_standard.aspx
  || 08/31/10 RLB 10.5.3.4 (88154) Changed to Default Voucher approval
  || 01/20/11 GHL 10.5.4.0 (101013) Added UseTasks, UseItems and related fields
  || 04/15/12 GWG 10.5.5.5 Added some missing fields due to update clash
  || 04/18/13 MAS 10.5.6.7 Removed EnableLogging
  || 01/02/14 RLB 10.5.7.5 (201290) Added companykey to update statement to just update that one company
  || 10/16/17 GHL 10.6.2.1 (367534) Added fields missing after Dave Arnold''s testing
  || 11/03/17 GHL 10.6.2.1 (367534) Set the Client Portal security group to Client
  || 08/19/19 GHL 19.0.9.0 (475467) Added protection against blank customizations
  || 05/05/26 MFT 26.0.5.0 (718171) Added AB prefix
  */
  
 exec sptPreferenceUpdateNumber @CompanyKey,
 @ProjectNumStyle,
 @ProjectNumPrefix,
 @NextProjectNum,
 @ProjectNumPlaces,
 @ProjectNumSep ,
 @ProjectNumPrefixUseYear,
 @PONumPrefix ,
 @NextPONum,
 @PONumPlaces,
 @IONumPrefix,
 @NextIONum,
 @IONumPlaces,
 @BCNumPrefix,
 @NextBCNum,
 @BCNumPlaces,
 @ARNumPrefix,
 @AdvBillPrefix,
 @NextARNum ,
 @ARNumPlaces ,
 @DefaultARApprover ,
 @DefaultARApproverKey ,
 @DefaultAPApprover,
 @DefaultAPApproverKey , 
 @ExpenseNumPrefix,
 @NextExpenseNum ,
 @ExpenseNumPlaces ,
 @RequireRequest ,
 @NotifyExpenseReport ,
 @GetRateFrom ,
 @TimeRateSheetKey ,
 @HourlyRate ,
 @GetMarkupFrom ,
 @ItemRateSheetKey ,
 @ItemMarkup ,
 @IOCommission ,
 @BCCommission ,
 @GetItemRate ,
 @DefaultPOType ,
 @DefaultPrintPOType ,
 @DefaultBCPOType ,
 @IOOrderDisplayMode ,
 @BCOrderDisplayMode ,
 @IOApprover ,
 @BCApprover ,
 @IOClientLink ,
 @BCClientLink , 
 @PaymentTermsKey ,
 @SendAssignmentEmail ,
 @AutoScheduleProjects ,
 @RequireMasterTask ,
 @DefaultARLineFormat ,
 @ShowCustomRptConditions ,
 @SetInvoiceNumberOnApproval ,
 @SyncDeletesContacts ,
 @SyncDeleteEvents ,
 @AutoApproveExternalOrders ,
 @ActualDateUpdatesPlan ,
 @RequireTimeDetails ,
 @UseMilitaryTime ,
 @IOPrintClientOnOrder ,
 @BCPrintClientOnOrder ,
 @EstimateNumStyle ,
 @EstimateNumPrefix ,
 @NextEstimateNum ,
 @EstimateNumPlaces ,
 @EstimateNumSep ,
 @EstimateNumPrefixUseYear ,
 @EstimateInternalApprovalDays ,
 @EstimateExternalApprovalDays ,
 @IOAllowChangesAfterClientInvoice ,
 @BCAllowChangesAfterClientInvoice ,
 @IOShowAdjustmentsAsSingleLine ,
 @BCShowAdjustmentsAsSingleLine ,
 @IOUseClientCosting ,
 @BCUseClientCosting ,
 @BCUseProductName ,
 @EditVendorInvTax ,
 @POUnitCostDecimalPlaces ,
 @POQtyDecimalPlaces ,
 @UseUnitRate ,
 @AutoApproveExternalInvoices ,
 @UseClearedDate ,
 @BCGeneratePrebilledRevisions ,
 @IOGeneratePrebilledRevisions ,
 @PrintTrafficOnBC ,
 @UseExpenseTypeClassOnVoucher ,
 @AutoGenVoucherFromER ,
 @SplitBilling ,
 @DuplicateVendorInvoiceNbr ,
 @UseCompanyFolders ,
 @UseContactFolders ,
 @UseLeadFolders ,
 @UseActivityFolders ,
 @UseOppFolders ,
 @EmailsVisibleToClient ,
 @EmailsDefaultActivityTypeKey ,
 @DefaultActivityTypeKey ,
 @AutoGenerateInvoiceOrderLines ,
 @RequireCommentsOnTime 
  
  
  declare @SSOSecurityGroupKey int
  select @SSOSecurityGroupKey = SecurityGroupKey
  from   tSecurityGroup (nolock)
  where  CompanyKey = @CompanyKey
  and    GroupName = ''Clients''

 update tPreference
 set	UseItems = 1,RequireItems = 1, DefaultExpenseAccountFromItem = 1
	   ,UseTasks = 1, RequireTasks = 0
       ,DefaultAutoIDTask = 1, UseToDo = @UseToDo
	   ,TimerInterval = 0,TimerRounding = 0 
	   ,AdvBillAccountOnly = 1
	   ,AccrueCostToItemExpenseAccount = 1
	   ,DefaultEstType = 2
	   ,AutoScheduleTaskEndDate = @AutoScheduleTaskEndDate
	   ,EmailTimeSubmittal = @EmailTimeSubmittal
	   ,NoTimeBeforeGLCloseDate = @NoTimeBeforeGLCloseDate
	   ,SSOSecurityGroupKey = @SSOSecurityGroupKey
	   ,Customizations = isnull(Customizations, '''')
where CompanyKey = @CompanyKey

 RETURN 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIExpenseEnvelopeGetList]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseEnvelopeGetList]', 'P') IS NULL
EXEC sp_executesql N'Create   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
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @TargetUserKey          int
    Declare @TargetGLCompanyKey     int
    Declare @StatusNum              smallint

    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

        -- GL company restriction: caller must have access to the target user''s GL company
        If @IsAdministrator = 0
        Begin
            Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
            From    tPreference (nolock)
            Where   CompanyKey = @CompanyKey

            If @RestrictToGLCompany = 1
            Begin
                If Not Exists (
                    Select  1
                    From    tUserGLCompanyAccess (nolock)
                    Where   UserKey         = @UserKey
                    And     GLCompanyKey    = @TargetGLCompanyKey
                )
                Begin
                    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                    Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company 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
        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'Creating [dbo].[spApiAIExpenseEnvelopeGet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseEnvelopeGet]', 'P') IS NULL
EXEC sp_executesql N'Create   PROCEDURE [dbo].[spApiAIExpenseEnvelopeGet]
    (
        @CompanyKey     int,
        @UserKey        int,
        @EnvelopeNumber varchar(100)
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/05/26  GRR 26.05.xx   Created
*/

    Declare @SecurityGroupKey       int
    Declare @IsAdministrator        bit
    Declare @RestrictToGLCompany    int
    Declare @ExpenseEnvelopeKey     int
    Declare @EnvelopeUserKey        int
    Declare @EnvelopeGLCompanyKey   int

    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

        -- GL company restriction: caller must have access to the envelope owner''s GL company
        If @IsAdministrator = 0
        Begin
            Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
            From    tPreference (nolock)
            Where   CompanyKey = @CompanyKey

            If @RestrictToGLCompany = 1
            Begin
                If Not Exists (
                    Select  1
                    From    tUserGLCompanyAccess (nolock)
                    Where   UserKey         = @UserKey
                    And     GLCompanyKey    = @EnvelopeGLCompanyKey
                )
                Begin
                    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                    Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company access to view this expense report.'', ''envelopeNumber'')

                    Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
                    Drop Table #errors
                    Return -103
                End
            End
        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'Creating [dbo].[spApiAIExpenseReceiptInsert]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseReceiptInsert]', 'P') IS NULL
EXEC sp_executesql N'CREATE 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
*/

    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

    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

                -- GL company restriction
                Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
                From    tPreference (nolock)
                Where   CompanyKey = @CompanyKey

                If @RestrictToGLCompany = 1
                Begin
                    If Not Exists (
                        Select  1
                        From    tUserGLCompanyAccess (nolock)
                        Where   UserKey         = @UserKey
                        And     GLCompanyKey    = @EnvelopeGLCompanyKey
                    )
                    Begin
                        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                        Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company access to add receipts 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
    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'Creating [dbo].[spApiAIExpenseEnvelopeSubmit]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIExpenseEnvelopeSubmit]', 'P') IS NULL
EXEC sp_executesql N'Create   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
*/

    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

    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

            -- GL company restriction: caller must have access to the envelope owner''s GL company
            Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
            From    tPreference (nolock)
            Where   CompanyKey = @CompanyKey

            If @RestrictToGLCompany = 1
            Begin
                If Not Exists (
                    Select  1
                    From    tUserGLCompanyAccess (nolock)
                    Where   UserKey      = @UserKey
                    And     GLCompanyKey = @EnvelopeGLCompanyKey
                )
                Begin
                    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
                    Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company access to submit 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

    -- 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'Creating [dbo].[spApiAIApproveItem]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIApproveItem]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[spApiAIApproveItem]
    (
        @CompanyKey         int,
        @UserKey            int,
        @EntityType         varchar(50),
        @EntityKey          int,
        @ApprovalComments   nvarchar(500) = null,
        @WithChanges        tinyint       = 0
    )
AS --Encrypt

/*
|| When      Who Rel       What
|| 05/08/26  GRR 26.06.x   Created — AI approve tool for all approvable entity types
*/

SET NOCOUNT ON

Select * Into #errors From tAPIErrorTemplate Where 1 = 2

Declare @Administrator      int
Declare @SecurityGroupKey   int
Declare @RestrictToGLCompany int
Declare @ApprovedReference  varchar(200)
Declare @StatusLabel        varchar(50)
Declare @Now                smalldatetime

Set @Now = GETUTCDATE()

Select  @Administrator    = ISNULL(Administrator, 0)
       ,@SecurityGroupKey = SecurityGroupKey
From tUser (nolock)
Where UserKey = @UserKey

Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
From tPreference (nolock)
Where CompanyKey = @CompanyKey

-- ============================================================
-- Parameter validation
-- ============================================================
If @EntityType Is Null Or Len(LTRIM(RTRIM(@EntityType))) = 0
Begin
    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
    Values (''error'', ''REQUIRED_FIELD'', ''entityType is required.'', ''entityType'')
End

If @EntityKey Is Null Or @EntityKey <= 0
Begin
    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
    Values (''error'', ''REQUIRED_FIELD'', ''entityKey must be a positive integer.'', ''entityKey'')
End

Declare @InitErrorCount int
Select @InitErrorCount = Count(*) From #errors Where errorType = ''error''
If @InitErrorCount > 0
Begin
    Select errorType, errorCode, errorMessage, fieldName From #errors Order By errorType Desc, fieldName
    Drop Table #errors
    Return -100
End


-- ============================================================
-- tExpenseEnvelope
-- ============================================================
If @EntityType = ''tExpenseEnvelope''
Begin
    Declare @EEApprover int, @EEStatus smallint, @EERef varchar(100)
    Select  @EEApprover = u.ExpenseApprover
           ,@EEStatus   = ee.Status
           ,@EERef      = LTRIM(RTRIM(ee.EnvelopeNumber))
    From tExpenseEnvelope ee (nolock)
    Inner Join tUser u (nolock) On ee.UserKey = u.UserKey
    Where ee.ExpenseEnvelopeKey = @EntityKey
      And ee.CompanyKey = @CompanyKey

    If @EERef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Expense envelope not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @EEStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Expense envelope must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And @EEApprover <> @UserKey
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You are not the assigned expense approver for this envelope.'', ''entityKey'')
        Goto ReturnResult
    End

    Exec sptExpenseEnvelopeApprove @EntityKey, @ApprovalComments
    Set @ApprovedReference = @EERef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tTimeSheet
-- ============================================================
Else If @EntityType = ''tTimeSheet''
Begin
    Declare @TSApprover int, @TSStatus smallint, @TSRef varchar(200)
    Select  @TSStatus   = ts.Status
           ,@TSRef      = u.FirstName + '' '' + u.LastName + '' ('' + Convert(varchar(20), ts.StartDate, 101) + '')''
           ,@TSApprover = u.TimeApprover
    From tTimeSheet ts (nolock)
    Inner Join tUser u (nolock) On ts.UserKey = u.UserKey
    Where ts.TimeSheetKey = @EntityKey
      And ts.CompanyKey = @CompanyKey

    If @TSRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Timesheet not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @TSStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Timesheet must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And @TSApprover <> @UserKey
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You are not the assigned time approver for this timesheet.'', ''entityKey'')
        Goto ReturnResult
    End

    Declare @TSReturn int
    Exec @TSReturn = sptTimeSheetUpdateStatus @UserKey, @EntityKey, 4, @ApprovalComments
    If @TSReturn < 0
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'',
                ''Timesheet could not be approved. It may have billed or posted time entries (code: ''
                + Convert(varchar(10), @TSReturn) + '').'',
                ''entityKey'')
        Goto ReturnResult
    End
    Set @ApprovedReference = @TSRef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tPurchaseOrder  (PO / IO / BC — all use same table)
-- ============================================================
Else If @EntityType = ''tPurchaseOrder''
Begin
    Declare @POStatus int, @PORef varchar(100), @POApprover int, @POGLCompany int
    Select  @POStatus   = po.Status
           ,@PORef      = po.PurchaseOrderNumber
           ,@POApprover = ISNULL(po.ApprovedByKey, 0)
           ,@POGLCompany = po.GLCompanyKey
    From tPurchaseOrder po (nolock)
    Where po.PurchaseOrderKey = @EntityKey
      And po.CompanyKey = @CompanyKey

    If @PORef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Purchase order not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @POStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Purchase order must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0
      And @POApprover <> 0
      And @POApprover <> @UserKey
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You are not the assigned approver for this purchase order.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And @RestrictToGLCompany = 1
      And Not Exists (Select 1 From tUserGLCompanyAccess (nolock)
                      Where UserKey = @UserKey And GLCompanyKey = @POGLCompany)
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company access to approve this purchase order.'', ''entityKey'')
        Goto ReturnResult
    End

    Update tPurchaseOrder
    Set Status          = 4,
        ApprovedByKey   = @UserKey,
        ApprovedDate    = GETUTCDATE(),
        ApprovalComments = @ApprovalComments
    Where PurchaseOrderKey = @EntityKey

    Set @ApprovedReference = @PORef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tVoucher  (Vendor Invoices — CreditCard = 0)
-- ============================================================
Else If @EntityType = ''tVoucher''
Begin
    Declare @VStatus int, @VRef varchar(100), @VApprover int, @VProjectKey int, @VGLCompany int
    Select  @VStatus    = v.Status
           ,@VRef       = v.InvoiceNumber
           ,@VApprover  = ISNULL(v.ApprovedByKey, 0)
           ,@VProjectKey = v.ProjectKey
           ,@VGLCompany  = v.GLCompanyKey
    From tVoucher v (nolock)
    Where v.VoucherKey = @EntityKey
      And v.CompanyKey = @CompanyKey
      And ISNULL(v.CreditCard, 0) = 0

    If @VRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Vendor invoice not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @VStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Vendor invoice must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0
    Begin
        Declare @CanApproveVoucher int
        Set @CanApproveVoucher = 0

        If @VApprover = @UserKey
            Set @CanApproveVoucher = 1
        Else If Exists (
            Select 1 From tRight r (nolock)
            Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
            Where ra.EntityKey = @SecurityGroupKey And ra.EntityType = ''Security Group''
              And r.RightID = ''purch_approvemyprojectvoucher''
        ) And @VProjectKey Is Not Null
          And Exists (
            Select 1 From tAssignment (nolock)
            Where UserKey = @UserKey And ProjectKey = @VProjectKey
        )
            Set @CanApproveVoucher = 1

        If @CanApproveVoucher = 0
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to approve this vendor invoice.'', ''entityKey'')
            Goto ReturnResult
        End

        If @RestrictToGLCompany = 1
          And Not Exists (Select 1 From tUserGLCompanyAccess (nolock)
                          Where UserKey = @UserKey And GLCompanyKey = @VGLCompany)
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company access to approve this vendor invoice.'', ''entityKey'')
            Goto ReturnResult
        End
    End

    Update tVoucher
    Set Status          = 4,
        ApprovedByKey   = @UserKey,
        ApprovedDate    = GETUTCDATE(),
        ApprovalComments = @ApprovalComments
    Where VoucherKey = @EntityKey

    Set @ApprovedReference = @VRef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tVoucherCC  (Credit Card Charges — CreditCard = 1)
-- ============================================================
Else If @EntityType = ''tVoucherCC''
Begin
    Declare @CCStatus int, @CCRef varchar(100), @CCApprover int
    Select  @CCStatus   = v.Status
           ,@CCRef      = v.InvoiceNumber
           ,@CCApprover = ISNULL(v.ApprovedByKey, 0)
    From tVoucher v (nolock)
    Where v.VoucherKey = @EntityKey
      And v.CompanyKey = @CompanyKey
      And ISNULL(v.CreditCard, 0) = 1

    If @CCRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Credit card charge not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @CCStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Credit card charge must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0
    Begin
        If Not Exists (
            Select 1 From tRight r (nolock)
            Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
            Where ra.EntityKey = @SecurityGroupKey And ra.EntityType = ''Security Group''
              And r.RightID = ''purch_approvecreditcardcharge''
        ) Or @CCApprover <> @UserKey
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to approve this credit card charge.'', ''entityKey'')
            Goto ReturnResult
        End
    End

    Update tVoucher
    Set Status          = 4,
        ApprovedByKey   = @UserKey,
        ApprovedDate    = GETUTCDATE(),
        ApprovalComments = @ApprovalComments
    Where VoucherKey = @EntityKey

    Set @ApprovedReference = @CCRef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tEstimate  (Estimates and Change Orders — same table, ChangeOrder flag differs)
-- ============================================================
Else If @EntityType = ''tEstimate''
Begin
    Declare @EstIntStatus  smallint, @EstExtStatus  smallint
    Declare @EstIntApprover int,     @EstExtApprover int
    Declare @EstRef varchar(200)
    Declare @EstApproveStage varchar(20)

    Select  @EstIntStatus   = e.InternalStatus
           ,@EstExtStatus   = e.ExternalStatus
           ,@EstIntApprover = e.InternalApprover
           ,@EstExtApprover = e.ExternalApprover
           ,@EstRef         = e.EstimateName
    From tEstimate e (nolock)
    Where e.EstimateKey = @EntityKey

    If @EstRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Estimate not found.'', ''entityKey'')
        Goto ReturnResult
    End

    -- Stage 1: internal approval (InternalStatus = 2)
    If @EstIntStatus = 2 And (@Administrator = 1 Or @EstIntApprover = @UserKey)
    Begin
        Update tEstimate
        Set InternalStatus   = 4,
            InternalApproval = GETUTCDATE(),
            InternalComments = @ApprovalComments
        Where EstimateKey = @EntityKey
        Set @EstApproveStage = ''Internal''
    End
    -- Stage 2: external approval (InternalStatus = 4, ExternalStatus = 2)
    Else If @EstIntStatus = 4 And @EstExtStatus = 2 And (@Administrator = 1 Or @EstExtApprover = @UserKey)
    Begin
        Update tEstimate
        Set ExternalStatus   = 4,
            ExternalApproval = GETUTCDATE(),
            ExternalComments = @ApprovalComments
        Where EstimateKey = @EntityKey
        Set @EstApproveStage = ''External''
    End
    Else If @EstIntStatus <> 2 And Not (@EstIntStatus = 4 And @EstExtStatus = 2)
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Estimate is not awaiting approval.'', ''entityKey'')
        Goto ReturnResult
    End
    Else
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You are not the assigned approver for this estimate.'', ''entityKey'')
        Goto ReturnResult
    End

    Set @ApprovedReference = @EstRef
    Set @StatusLabel = @EstApproveStage + '' Approved''
End


-- ============================================================
-- tReviewDeliverable  (Digital Art Proofs)
-- ============================================================
Else If @EntityType = ''tReviewDeliverable''
Begin
    Declare @RDStepKey int, @RDRef varchar(200)

    Select @RDRef = rd.DeliverableName
    From tReviewDeliverable rd (nolock)
    Where rd.ReviewDeliverableKey = @EntityKey

    If @RDRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Deliverable not found.'', ''entityKey'')
        Goto ReturnResult
    End

    Select Top 1 @RDStepKey = asu.ApprovalStepKey
    From tApprovalStepUser asu (nolock)
    Inner Join tApprovalStep a (nolock)    On asu.ApprovalStepKey = a.ApprovalStepKey
    Inner Join tReviewRound rr (nolock)   On rr.ReviewRoundKey = a.EntityKey And a.Entity = ''tReviewRound''
    Where rr.ReviewDeliverableKey = @EntityKey
      And asu.AssignedUserKey = @UserKey
      And asu.ActiveUser = 1
      And a.ActiveStep = 1

    -- Admins can approve even if not explicitly assigned
    If @RDStepKey Is Null And @Administrator = 1
        Select Top 1 @RDStepKey = a.ApprovalStepKey
        From tApprovalStep a (nolock)
        Inner Join tReviewRound rr (nolock) On rr.ReviewRoundKey = a.EntityKey And a.Entity = ''tReviewRound''
        Where rr.ReviewDeliverableKey = @EntityKey And a.ActiveStep = 1

    If @RDStepKey Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You are not an active approver for this deliverable, or it is not awaiting approval.'',
                ''entityKey'')
        Goto ReturnResult
    End

    Exec sptApprovalStepUserApprove @RDStepKey, @UserKey, @ApprovalComments, @Now, @WithChanges
    Set @ApprovedReference = @RDRef
    Set @StatusLabel = Case When @WithChanges = 1 Then ''Approved With Changes'' Else ''Approved'' End
End


-- ============================================================
-- tRequest  (Project Requests)
-- ============================================================
Else If @EntityType = ''tRequest''
Begin
    Declare @ReqStepKey int, @ReqRef varchar(100)

    Select @ReqRef = RequestID From tRequest (nolock)
    Where RequestKey = @EntityKey And CompanyKey = @CompanyKey

    If @ReqRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Project request not found.'', ''entityKey'')
        Goto ReturnResult
    End

    Select Top 1 @ReqStepKey = asu.ApprovalStepKey
    From tApprovalStep step (nolock)
    Inner Join tApprovalStepUser asu (nolock) On step.ApprovalStepKey = asu.ApprovalStepKey
    Where step.Entity = ''ProjectRequest''
      And step.EntityKey = @EntityKey
      And step.ActiveStep = 1
      And asu.AssignedUserKey = @UserKey
      And asu.ActiveUser = 1

    If @ReqStepKey Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You are not an active approver for this project request, or it is not awaiting approval.'',
                ''entityKey'')
        Goto ReturnResult
    End

    Exec sptApprovalStepUserApprove @ReqStepKey, @UserKey, @ApprovalComments, @Now, 0
    Set @ApprovedReference = @ReqRef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tChange  (Change Requests)
-- ============================================================
Else If @EntityType = ''tChange''
Begin
    Declare @CRStepKey int, @CRRef varchar(100)

    Select @CRRef = Convert(varchar(50), VersionNumber)
    From tChange (nolock)
    Where ChangeKey = @EntityKey And CompanyKey = @CompanyKey

    If @CRRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Change request not found.'', ''entityKey'')
        Goto ReturnResult
    End

    Select Top 1 @CRStepKey = asu.ApprovalStepKey
    From tApprovalStep step (nolock)
    Inner Join tApprovalStepUser asu (nolock) On step.ApprovalStepKey = asu.ApprovalStepKey
    Where step.Entity = ''tChange''
      And step.EntityKey = @EntityKey
      And step.ActiveStep = 1
      And asu.AssignedUserKey = @UserKey
      And asu.ActiveUser = 1

    If @CRStepKey Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You are not an active approver for this change request, or it is not awaiting approval.'',
                ''entityKey'')
        Goto ReturnResult
    End

    Exec sptApprovalStepUserApprove @CRStepKey, @UserKey, @ApprovalComments, @Now, 0
    Set @ApprovedReference = @CRRef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tBillingApprove  (Billing Worksheets — awaiting final approval, Status = 2)
-- ============================================================
Else If @EntityType = ''tBillingApprove''
Begin
    If @Administrator = 0 And Not Exists (
        Select 1 From tRight r (nolock)
        Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
        Where ra.EntityKey = @SecurityGroupKey And ra.EntityType = ''Security Group''
          And r.RightID = ''billingeditinvoice''
    )
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to approve billing worksheets.'', ''entityKey'')
        Goto ReturnResult
    End

    Declare @BAStatus int, @BARef varchar(100), @BAGLCompany int
    Select  @BAStatus   = b.Status
           ,@BARef      = Convert(varchar(50), b.BillingID)
           ,@BAGLCompany = b.GLCompanyKey
    From tBilling b (nolock)
    Where b.BillingKey = @EntityKey And b.CompanyKey = @CompanyKey

    If @BARef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Billing worksheet not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @BAStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Billing worksheet must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And @RestrictToGLCompany = 1
      And Not Exists (Select 1 From tUserGLCompanyAccess (nolock)
                      Where UserKey = @UserKey And GLCompanyKey = @BAGLCompany)
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You do not have GL company access to approve this billing worksheet.'', ''entityKey'')
        Goto ReturnResult
    End

    Update tBilling
    Set Status           = 4,
        ApprovalComments = @ApprovalComments,
        Approver         = @UserKey
    Where BillingKey = @EntityKey

    Set @ApprovedReference = @BARef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tBilling  (Billing Worksheets in Review — Status 1 or 3 → submit for approval)
-- ============================================================
Else If @EntityType = ''tBilling''
Begin
    Declare @BRStatus int, @BRRef varchar(100), @BRApprover int
    Select  @BRStatus   = b.Status
           ,@BRRef      = Convert(varchar(50), b.BillingID)
           ,@BRApprover = b.Approver
    From tBilling b (nolock)
    Where b.BillingKey = @EntityKey And b.CompanyKey = @CompanyKey

    If @BRRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Billing worksheet not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @BRStatus Not In (1, 3)
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Billing worksheet is not awaiting review (must be Unsubmitted or Rejected).'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And @BRApprover <> @UserKey
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You are not the assigned reviewer for this billing worksheet.'', ''entityKey'')
        Goto ReturnResult
    End

    Update tBilling
    Set Status           = 2,
        ApprovalComments = @ApprovalComments,
        DateReviewed     = GETUTCDATE()
    Where BillingKey = @EntityKey

    Set @ApprovedReference = @BRRef
    Set @StatusLabel = ''Submitted for Approval''
End


-- ============================================================
-- tJournalEntry
-- ============================================================
Else If @EntityType = ''tJournalEntry''
Begin
    Declare @JEStatus int, @JERef varchar(100), @JEApprover int
    Select  @JEStatus   = je.Status
           ,@JERef      = je.JournalNumber
           ,@JEApprover = ISNULL(je.ApprovedByKey, 0)
    From tJournalEntry je (nolock)
    Where je.JournalEntryKey = @EntityKey And je.CompanyKey = @CompanyKey

    If @JERef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Journal entry not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @JEStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Journal entry must be in Submitted status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0
    Begin
        Declare @CanApproveJE int
        Set @CanApproveJE = 0

        If @JEApprover = @UserKey
            Set @CanApproveJE = 1
        Else If Exists (
            Select 1 From tRight r (nolock)
            Inner Join tRightAssigned ra (nolock) On r.RightKey = ra.RightKey
            Where ra.EntityKey = @SecurityGroupKey And ra.EntityType = ''Security Group''
              And r.RightID = ''gl_postjournalentry''
        )
            Set @CanApproveJE = 1

        If @CanApproveJE = 0
        Begin
            Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
            Values (''error'', ''ACCESS_DENIED'', ''You do not have permission to approve this journal entry.'', ''entityKey'')
            Goto ReturnResult
        End
    End

    Update tJournalEntry
    Set Status           = 4,
        ApprovedByKey    = @UserKey,
        ApprovedDate     = GETUTCDATE(),
        ApprovalComments = @ApprovalComments
    Where JournalEntryKey = @EntityKey

    Set @ApprovedReference = @JERef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- tForecast  (Revenue Forecasts — marks account manager''s items as reviewed)
-- ============================================================
Else If @EntityType = ''tForecast''
Begin
    Declare @FCRef varchar(200)
    Select @FCRef = f.ForecastName
    From tForecast f (nolock)
    Where f.ForecastKey = @EntityKey

    If @FCRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Revenue forecast not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And Not Exists (
        Select 1 From tForecastDetail (nolock)
        Where ForecastKey = @EntityKey
          And AccountManagerKey = @UserKey
          And ISNULL(ReviewComplete, 0) = 2
    )
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'',
                ''You have no forecast items awaiting your review on this forecast.'',
                ''entityKey'')
        Goto ReturnResult
    End

    -- Mark all this account manager''s pending items as reviewed
    Update tForecastDetail
    Set ReviewComplete = 1
    Where ForecastKey = @EntityKey
      And AccountManagerKey = @UserKey
      And ISNULL(ReviewComplete, 0) = 2

    Set @ApprovedReference = @FCRef
    Set @StatusLabel = ''Reviewed''
End


-- ============================================================
-- tForm  (Tracking Forms — closes the form)
-- ============================================================
Else If @EntityType = ''tForm''
Begin
    Declare @FMRef varchar(200), @FMAssignedTo int, @FMDateClosed smalldatetime
    Select  @FMRef        = fd.FormName + '' #'' + Convert(varchar(10), fm.FormNumber)
           ,@FMAssignedTo = fm.AssignedTo
           ,@FMDateClosed = fm.DateClosed
    From tForm fm (nolock)
    Inner Join tFormDef fd (nolock) On fm.FormDefKey = fd.FormDefKey
    Where fm.FormKey = @EntityKey And fm.CompanyKey = @CompanyKey

    If @FMRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Tracking form not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @FMDateClosed Is Not Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''This tracking form is already closed.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And ISNULL(@FMAssignedTo, 0) <> @UserKey
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''This tracking form is not assigned to you.'', ''entityKey'')
        Goto ReturnResult
    End

    Update tForm
    Set DateClosed = GETUTCDATE()
    Where FormKey = @EntityKey

    Set @ApprovedReference = @FMRef
    Set @StatusLabel = ''Closed''
End


-- ============================================================
-- tInvoice  (Client Invoices)
-- ============================================================
Else If @EntityType = ''tInvoice''
Begin
    Declare @InvStatus int, @InvRef varchar(100), @InvApprover int
    Select  @InvStatus   = i.InvoiceStatus
           ,@InvRef      = i.InvoiceNumber
           ,@InvApprover = ISNULL(i.ApprovedByKey, 0)
    From tInvoice i (nolock)
    Where i.InvoiceKey = @EntityKey
      And i.CompanyKey = @CompanyKey

    If @InvRef Is Null
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''NOT_FOUND'', ''Invoice not found.'', ''entityKey'')
        Goto ReturnResult
    End

    If @InvStatus <> 2
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''INVALID_VALUE'', ''Invoice must be in Sent for Approval status to approve.'', ''entityKey'')
        Goto ReturnResult
    End

    If @Administrator = 0 And @InvApprover <> @UserKey
    Begin
        Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
        Values (''error'', ''ACCESS_DENIED'', ''You are not the assigned approver for this invoice.'', ''entityKey'')
        Goto ReturnResult
    End

    Update tInvoice
    Set InvoiceStatus    = 4,
        ApprovedByKey    = @UserKey,
        ApprovalComments = @ApprovalComments
    Where InvoiceKey = @EntityKey

    Set @ApprovedReference = @InvRef
    Set @StatusLabel = ''Approved''
End


-- ============================================================
-- Unknown entity type
-- ============================================================
Else
Begin
    Insert Into #errors (errorType, errorCode, errorMessage, fieldName)
    Values (''error'', ''INVALID_VALUE'',
            ''Unsupported entity type: '' + ISNULL(@EntityType, ''(null)'') + ''. ''
            + ''Supported types: tExpenseEnvelope, tTimeSheet, tPurchaseOrder, tVoucher, tVoucherCC, ''
            + ''tEstimate, tReviewDeliverable, tRequest, tChange, tBillingApprove, tBilling, ''
            + ''tJournalEntry, tForecast, tForm, tInvoice.'',
            ''entityType'')
End


-- ============================================================
-- Return results
-- ============================================================
ReturnResult:

    Declare @FinalErrorCount int
    Select @FinalErrorCount = Count(*) From #errors Where errorType = ''error''

    -- Result set 1: warnings (empty = clean success; rows = issues)
    Select errorType, errorCode, errorMessage, fieldName
    From #errors
    Order By errorType Desc, fieldName

    -- Result set 2: approval confirmation (only when no errors)
    If @FinalErrorCount = 0
        Select @EntityType  as entityType,
               @EntityKey   as entityKey,
               @ApprovedReference as reference,
               @StatusLabel as statusLabel

    Drop Table #errors

    If @FinalErrorCount > 0 Return -100
    Return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesCreateInvoice]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCreateInvoice]', 'P') IS NOT NULL
EXEC sp_executesql N'


ALTER PROCEDURE [dbo].[spFixedFeesCreateInvoice]
	(
	@Entity varchar(50) -- tCampaign, tMediaEstimate
	,@EntityKey int     -- CampaignKey, etc
	,@InvoiceBy varchar(20) -- OneLine, Segment, Item/Service, Project
	,@UserKey int
	,@InvoiceAmount money
	,@AdvanceBilling tinyint = 1
	,@DefaultClassKey int = Null
	,@EstimateKey int = Null
	,@DefaultDepartmentKey int = NULL
	,@AddProjectDescription tinyint = 0
	,@UpdateSchedule tinyint = 1
	,@AddTopLine tinyint = 0 -- Do we add a top line for the entity
	)

AS --Encrypt

  /*
  || When     Who Rel   What
  || 05/2/10 GHL 10.522 Creation for campaign FF billing
  ||                    Cloned fragments from following sps used in FF project billing:
  ||                    - sptInvoiceInsertProject
  ||                    - sptInvoiceInsertProjectOneLine
  ||                    - sptInvoiceLineProjectInsert  
  || 12/14/11 GHL 10.540 Made changes to support case InvoiceBy = Project
  ||                     Reviewed design because the Fixed Fee campaign grid show show projects only (i.e. no item/services)
  ||                     And this sp will call spFixedFeesCreateInvoiceLines to create lines for items/services 
  || 01/21/11 GHL 10.540 (101244) If AdvanceBilling = 1, do not show details under segments or projects
  ||                      else show details under segments or projects    
  || 02/08/11 GHL 10.540 (102053) Getting now GLCompanyKey from the client   
  || 05/27/11 GHL 10.544 (112126) Added AddProjectDescription to have the option to put the project desc on the lines 
  ||                      Note: when printing an invoice, there is already some logic to pull project description based 
  ||                      on line type.
  || 08/08/11 GHL 10.546  Added project rollup at the end of the stored proc
  || 10/21/11 GHL 10.549  (124337) When billing by project, added a check to make sure that all projects have the
  ||                      same GL company, if they have we take that company, if they dont, we error out 
  || 04/27/12 GHL 10.555  Made changes for ICT, lines may have a different GLCompanyKey now
  ||                      Also get GLCompanyKey from campaign rather than the client
  || 10/01/13 GHL 10.573  Added currency info when calling invoice insert
  || 01/03/14 WDF 10.576 (188500) Pass UserKey to sptInvoiceInsert
  || 04/23/15 GHL 10.591 (254451) Added setting of OfficeKey from the project
  || 09/18/15 GHL 10.596 (270676) Added missing param IsForRetainer when calling sptInvoiceInsert
  || 10/15/15 GHL 10.596 Just a line to redeploy the missing param IsForRetainer when calling sptInvoiceInsert
  || 10/13/16 GHL 10.609 Get CurrencyID from the campaign rather than the client. The currency on the client is more like a default
  || 10/02/17 GHL 10.621 (363756) Added default AR account from client
  || 06/27/18 GHL 18.700 (401828) Reading now tPreference.SetTaxableOnInvoice to force 1 line invoices to be taxable
  || 01/27/20 GHL 20.030 (495024) Get the invoice template from the GL company if tPreference.LayoutFromGLCompany = 1
  || 10/15/20 GHL 20.110 (533381) Take in account tCampaign.ExpensesNotIncluded, if 1 only pull labor (OneLine case)
  || 10/21/20 GHL 20.110 (533381) Added UpdateSchedule parameter so that we can update the billing schedule
  || 03/24/21 GHL 21.05.16 Corrected Taxable2 (should not be Taxable) for items/services
  || 05/27/21 GHL 21.06.20 (560012) Added the ability of a Top Line for the entity, this allow users to enter by service/items for taxes
  ||                       and rollup to top line 
  || 11/04/21 MCM 21.12.x (573760) Updated to pull the displayOption from the layout, if applicable
  || 03/18/22 GHL 22.04.17 (590582) Added support for tProject.SetTaxableOnInvoice
  || 10/05/22 MFT 22.10.0 (613293) Removed errant DisplayOption set
  || 02/07/23 GAR 23.03.19 (622546) Have Fixed Fee Campaign mass billing observe the default approver settings from trans pref / client invoice / default approver
  || 03/09/23 MFT 23.04.00 (629602) Respect the Layout Billing Item / Item values
  || 05/30/24 MCM 24.07.x  (651173) Added OfficeKey so the invoice is created with it for campaigns
  || 11/04/25 MCM 25.11.x (656423) Added Liability Account Key when calling sptInvoiceInsert
  || 05/14/26 RLS 26.06.14 (725399) Added IF @DefaultARApprover = 5
  */
  
	SET NOCOUNT ON
	

	if isnull(@EntityKey, 0) = 0
		return 0
		 
	/* Assume
	CREATE TABLE #line (
		Entity VARCHAR(50) NULL -- tCampaignSegment, tItem, tService 
	   ,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
		)
	*/
	
-- General vars
declare @NewInvoiceKey int	
declare @NewInvoiceLineKey int	
declare @CompanyKey int	
declare @ClientKey int
declare @BillingContact varchar(100)
declare @PrimaryContactKey int 
declare @DefaultSalesAccountKey int
declare @SalesAccountKey int
declare @RetVal int
declare @TodaysDate smalldatetime
declare @ARAccountKey int
declare @DefaultARAccountKey int
declare @AdvBillAccountKey int
declare @DueDate smalldatetime
declare @DueDays int
declare @UseGLCompany int
declare @GLCompanyKey int
declare @OfficeKey int
declare @LayoutKey int
declare @EntityName nvarchar(250)
declare @RequireClasses int
declare @MultipleSegments int
declare @SegmentKey int
declare @SetTaxableOnInvoice int
declare @LayoutFromGLCompany int
declare @InvoiceTemplateKey int, @SalesTaxKey int, @SalesTax2Key int, @PaymentTermsKey int
declare @DefaultARApprover int
declare @DefaultARApproverKey int
declare @LiabilityAccountKey int

-- vars for line info
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
declare @CurrencyID varchar(10)

-- vars for the tCampaign.ExpensesNotIncluded
declare @ExpensesNotIncluded int

-- need to know which sp is failing
declare @kErrMissingClass int				select @kErrMissingClass = -1
declare @kErrProjectDiffGLCompany int		select @kErrProjectDiffGLCompany = -2

declare @kErrInvoiceBase int				select @kErrInvoiceBase = -1000
declare @kErrInvoiceLineBase int			select @kErrInvoiceLineBase = -2000

declare @DisplayOption int 
declare @kDisplayOptionNoDetail int			select @kDisplayOptionNoDetail = 1
declare @kDisplayOptionSubItemDetail int	select @kDisplayOptionSubItemDetail = 2
declare @kDisplayOptionTransactions int		select @kDisplayOptionTransactions = 3

	if @Entity = ''tCampaign''
	begin
		select @CompanyKey = c.CompanyKey
		       ,@ClientKey = c.ClientKey
               ,@LayoutKey = c.LayoutKey
               ,@BillingContact = Left(u.FirstName + '' '' + u.LastName, 100)
			   ,@PrimaryContactKey = u.UserKey 
		       ,@EntityName = cast(c.CampaignName as nvarchar(100))
			   ,@MultipleSegments = isnull(c.MultipleSegments, 0)
			   ,@GLCompanyKey = c.GLCompanyKey
			   ,@CurrencyID = c.CurrencyID
			   ,@ExpensesNotIncluded = isnull(c.ExpensesNotIncluded,0) 
			   ,@OfficeKey = c.OfficeKey
		from   tCampaign c (nolock)
			left outer join tUser u (nolock) on c.ContactKey = u.UserKey
		where  c.CampaignKey = @EntityKey 
		
		-- no defaults for OfficeKey
	end

	Select @InvoiceTemplateKey = ISNULL(c.InvoiceTemplateKey, 0)
		 , @SalesTaxKey = c.SalesTaxKey
		 , @SalesTax2Key = c.SalesTax2Key
		 , @PaymentTermsKey = c.PaymentTermsKey
		 , @SalesAccountKey = ISNULL(c.DefaultSalesAccountKey, 0)
		 , @ARAccountKey = ISNULL(c.DefaultARAccountKey, 0)
	from tCompany c (nolock) 
	where c.CompanyKey = @ClientKey
	
	SELECT @UseGLCompany = ISNULL(pref.UseGLCompany, 0)
			,@DefaultARApprover    = ISNULL(DefaultARApprover, 0)
			,@DefaultARApproverKey = ISNULL(DefaultARApproverKey, 0)	
	FROM   tPreference pref (NOLOCK)  
	WHERE  pref.CompanyKey = @CompanyKey

	IF @UseGLCompany = 0
		SELECT @GLCompanyKey = null

	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 = DueDays
		FROM   tPaymentTerms (NOLOCK)
		WHERE  PaymentTermsKey = @PaymentTermsKey
		 	
		SELECT @DueDate = DATEADD(d, @DueDays, @TodaysDate) 	
	END
	ELSE
		SELECT @DueDate = @TodaysDate

	--get default AR and advanced billing account key
	select @DefaultARAccountKey = DefaultARAccountKey
			,@DefaultSalesAccountKey = DefaultSalesAccountKey
			,@AdvBillAccountKey = AdvBillAccountKey
			,@RequireClasses = isnull(RequireClasses, 1)
			,@SetTaxableOnInvoice = isnull(SetTaxableOnInvoice, 0)
			,@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 isnull(@SalesAccountKey,0) > 0
		Select @DefaultSalesAccountKey = @SalesAccountKey

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

	If @AdvanceBilling = 1 And isnull(@AdvBillAccountKey, 0) > 0
		Select @DefaultSalesAccountKey = @AdvBillAccountKey


	if @DefaultSalesAccountKey = 0
		select @DefaultSalesAccountKey = null
	if @DefaultClassKey = 0
		select @DefaultClassKey = null
	if @DefaultDepartmentKey = 0
		select @DefaultDepartmentKey = null
	if @AdvBillAccountKey = 0
		select @AdvBillAccountKey = null	

	if @InvoiceBy = ''Segment''
	begin
		if @AdvanceBilling = 1
			select @LineType = 2 -- We do not show detail lines, so the campaign segment is a detail line
		else
			-- Not an advance bill
			select @LineType = 1 -- We show detail lines, so the campaign segment is a summary line
		
		update #line
		set    #line.Entity = ''tCampaignSegment''
			  ,#line.EntityName = cs.SegmentName
			  ,#line.EntityDescription = cs.SegmentDescription
			  ,#line.LineKey = #line.LineOrder -- we do not have a LineKey yet, so set it to LineOrder
			  ,#line.ParentLineKey = 0 
			  ,#line.LineType = @LineType
	    from   tCampaignSegment cs (nolock)
	    where  #line.EntityKey = cs.CampaignSegmentKey
		and    cs.CampaignKey = @EntityKey

		-- now create the missing items/services
		select @LineKey = 0
		while (@AdvanceBilling = 0) -- only do this if this is NOT an advance billing
		begin
			select @LineKey = min(LineKey)
			from   #line
			where  LineKey > @LineKey
			and    Entity = ''tCampaignSegment''
 			 
			if @LineKey is null
				break
				
			select @LineEntityKey = EntityKey
			      ,@LineBillAmt = BillAmt
			from   #line 
			where  Entity = ''tCampaignSegment''
			and    LineKey = @LineKey

			-- CampaignKey = EntityKey, CampaignSegmentKey = @LineEntityKey, ProjectKey = 0, ParentLineKey = @LineKey
			-- these lines are still created in #line
			exec spFixedFeesCreateInvoiceLines @EntityKey, @LineEntityKey, 0, @LineKey, @LineBillAmt

			-- if no underlying line was created, this is a detail line, not a summary line
			if (select count(*) from #line where ParentLineKey = @LineKey and Entity <> ''tCampaignSegment'') = 0
				update #line set LineType = 2 where LineKey = @LineKey and Entity = ''tCampaignSegment''

		end


	end

	declare @GLCompanyCount int
	if @InvoiceBy = ''Project''
	begin
		if @AdvanceBilling = 1
			select @LineType = 2 -- We do not show detail lines, so the project is a detail line
		else
			-- Not an advance bill
			select @LineType = 1 -- We show detail lines, so the project is a summary line
		
		-- here we inserted all lines regardless of Selected status 
		-- so delete lines which are not selected 
		delete #line where Entity = ''tProject'' and Selected = 0


		-- determine if the projects have different GLCompanyKeys
		
		if @UseGLCompany = 1
		begin
			select @GLCompanyCount =  count(distinct isnull(p.GLCompanyKey, 0)) from tProject p (nolock)
			inner join #line b on b.Entity = ''tProject'' and b.EntityKey = p.ProjectKey

			-- return error if GL company count > 1 and this is an advance bill, we do not allow this
			if @GLCompanyCount > 1 And @AdvanceBilling = 1
				return @kErrProjectDiffGLCompany

			/* commented out because we get the GLCompany from the campaign now
			select @GLCompanyKey = GLCompanyKey from tProject p (nolock)
			inner join #line b on b.Entity = ''tProject'' and b.EntityKey = p.ProjectKey
			
			if @GLCompanyKey = 0
				select @GLCompanyKey = null
			*/
				
		end
		
		update #line 
		set    #line.Selected =0
		where  #line.Entity = ''tCampaignSegment''

		update #line 
		set    #line.Selected = 1
		where  #line.Entity = ''tCampaignSegment''
		and    exists (select 1 from #line b where b.Entity = ''tProject'' and b.ParentLineKey = #line.LineKey)     

		delete #line where Entity = ''tCampaignSegment'' and Selected = 0

		update #line
		set    #line.EntityName = cs.SegmentName
			  ,#line.EntityDescription = cs.SegmentDescription
			  ,#line.LineType = 1 -- Summary line
	    from   tCampaignSegment cs (nolock)
	    where  #line.EntityKey = cs.CampaignSegmentKey
		and    cs.CampaignKey = @EntityKey
		and    #line.Entity = ''tCampaignSegment''

		-- this is debatable, should we have an extra ''No Segment'' line when projects do not have segments
		update #line
		set    #line.EntityName = ''No Segment''
			  ,#line.LineType = 1 -- Summary line by default
	    from   #line (nolock)
	    where  #line.EntityKey = 0
		and    #line.Entity = ''tCampaignSegment''

		-- LineKey and ProjectKey should be set
		update #line
		set    #line.EntityName = p.ProjectNumber + '' - '' + p.ProjectName
		      ,#line.LineType = @LineType
			  ,#line.ProjectKey = #line.EntityKey -- was not set initially, must be set to be on the invoice line 
			  ,#line.EntityDescription = case when @AddProjectDescription = 1 then p.Description else null end
		from   tProject p (nolock)
	    where  #line.EntityKey = p.ProjectKey
		and    #line.Entity = ''tProject''
		
		-- now create the missing items/services
		select @LineKey = 0
		while (@AdvanceBilling = 0) -- only do this if this is NOT an advance billing
		begin
			select @LineKey = min(LineKey)
			from   #line
			where  LineKey > @LineKey
			and    Entity = ''tProject''
 			 
			if @LineKey is null
				break
				
			select @LineEntityKey = EntityKey
			      ,@LineBillAmt = BillAmt
			from   #line 
			where  Entity = ''tProject''
			and    LineKey = @LineKey

			-- CampaignKey = EntityKey, CampaignSegmentKey = 0, ProjectKey = @LineEntityKey, ParentLineKey = @LineKey
			-- these lines are still created in #line
			exec spFixedFeesCreateInvoiceLines @EntityKey, 0, @LineEntityKey, @LineKey, @LineBillAmt

			-- if no underlying line was created, this is a detail line, not a summary line
			if (select count(*) from #line where ParentLineKey = @LineKey) = 0
				update #line set LineType = 2 where LineKey = @LineKey and Entity = ''tProject''


			-- update the project key
			update #line set ProjectKey = @LineEntityKey where ParentLineKey = @LineKey

		end

	end
	
	-- only if 1 line or segment
	if @InvoiceBy in (''OneLine'')
	begin	
		If @DefaultClassKey is null and @RequireClasses = 1
			return @kErrMissingClass
	end
	
	--select * from #line

	-- validation and defaults 
	--if @InvoiceBy in ( ''Item/Service'')
	--begin
			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 = @DefaultClassKey
			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 @AdvanceBilling = 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	   


	--end
	--Set the AdvBillAcountKey
	 Set @LiabilityAccountKey = 
		Case 
			When @AdvanceBilling = 1 Then @AdvBillAccountKey
			Else NULL
		End;
	--select * from #line 
	--return 1
		
	exec @RetVal = sptInvoiceInsert
			@CompanyKey = @CompanyKey,
			@ClientKey = @ClientKey,
			@ContactName = @BillingContact,
			@PrimaryContactKey = @PrimaryContactKey,
			@AddressKey = NULL,
			@AdvanceBill = @AdvanceBilling,
			@InvoiceNumber = null,
			@InvoiceDate = @TodaysDate,
			@DueDate = @DueDate,
			@PostingDate = @TodaysDate,
			@TermsKey = @PaymentTermsKey,
			@ARAccountKey = @DefaultARAccountKey,
			@ClassKey = @DefaultClassKey,
			@ProjectKey = NULL,
			@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 = @OfficeKey,
			@OpeningTransaction = 0,
			@LayoutKey = @LayoutKey,
			@CurrencyID = @CurrencyID,
			@ExchangeRate = 1,
			@RequestExchangeRate = 1, -- get a new rate
			@IsForRetainer = 0,
			@LiabilityAccountKey = @LiabilityAccountKey, -- **NEW PARAMETER ADDED**
			@oIdentity = @NewInvoiceKey OUTPUT

		if @RetVal <> 1
			return @kErrInvoiceBase + @RetVal
			
		if @Entity = ''tCampaign''
			update tInvoice
			set    CampaignKey = @EntityKey
			where  InvoiceKey = @NewInvoiceKey		
			
		-- (622546 ) Update the approver based on the selection in trans pref / client invoices / default approver
		-- We only care about 1, 4, and 5 because the others are handled in sptInvoiceInsert from above
		if @Entity = ''tCampaign''
		begin
			Declare @AE int -- Account Manager
			Declare @PM int -- Project Manager
			Declare @BM int -- Billing Manager
			-- DefaultARApprover 
			-- 1 AE From campaign
			-- 4 PM From campaign
			-- 5 Billing Manager From Project

			-- If AE From campaign
			IF @DefaultARApprover = 1			
				begin
					Select @AE = ISNULL(AEKey, 0) from tCampaign (nolock) Where CampaignKey = @EntityKey
					if @AE = 0
						Select @AE = @UserKey

					update tInvoice
					set    ApprovedByKey = @AE
					where  InvoiceKey = @NewInvoiceKey	
				end
			-- If PM From campaign
			IF @DefaultARApprover = 4
				begin
					Select @PM = ISNULL(PMKey, 0) from tCampaign (nolock) Where CampaignKey = @EntityKey
					if @PM = 0
						Select @PM = @UserKey

					update tInvoice
					set    ApprovedByKey = @PM
					where  InvoiceKey = @NewInvoiceKey	
				end
			-- If Billing Manager From Project
			IF @DefaultARApprover = 5
				begin
					Select TOP 1 @BM = ISNULL(p.BillingManagerKey, 0)
					from #line l
					inner join tProject p (nolock) on l.ProjectKey = p.ProjectKey
					where ISNULL(p.BillingManagerKey, 0) > 0
					order by l.LineOrder

					if @BM = 0
						Select @BM = @UserKey

					update tInvoice
					set    ApprovedByKey = @BM
					where  InvoiceKey = @NewInvoiceKey	
				end
		end
			
		if @InvoiceBy = ''OneLine''
		begin
			if isnull(@ExpensesNotIncluded, 0) = 0
				select @LineEntity = null
					   ,@LineEntityKey = null
			else
			begin
				-- expenses are not included, this one line must be Labor
				select @LineEntity = ''tService''
					   ,@LineEntityKey = null
			end	
			
			--create single invoice line
			exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,NULL							-- ProjectKey
						  ,NULL							-- TaskKey
						  ,@EntityName					-- Line Subject
						  ,null                 		-- Line description
						  ,1                    		-- Bill From 
						  ,1							-- Quantity
						  ,@InvoiceAmount				-- Unit Amount
						  ,@InvoiceAmount				-- Line Amount
						  ,2							-- line type
						  ,0							-- parent line key
						  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
						  ,@DefaultClassKey             -- Class Key
						  ,0							-- Taxable
						  ,0							-- Taxable2
						  ,NULL							-- Work TypeKey
						  ,0							-- PostInDetail
						  ,@LineEntity					-- Entity
						  ,@LineEntityKey				-- EntityKey
						  ,@OfficeKey
						  ,@DefaultDepartmentKey
						  ,@NewInvoiceLineKey output
			if @RetVal <> 1 
			begin
				exec sptInvoiceDelete @NewInvoiceKey
				return @kErrInvoiceLineBase + @RetVal
			end

		end	
			

		if @InvoiceBy = ''Item/Service''
		begin
			declare @TopLineKey int
			select @TopLineKey = 0

			if @AddTopLine = 1
			begin
				--create single invoice line
				exec @RetVal = sptInvoiceLineInsertMassBilling
							   @NewInvoiceKey				-- Invoice Key
							  ,NULL							-- ProjectKey
							  ,NULL							-- TaskKey
							  ,@EntityName					-- Line Subject
							  ,null                 		-- Line description
							  ,1                    		-- Bill From 
							  ,1							-- Quantity
							  ,0							-- Unit Amount
							  ,0							-- Line Amount
							  ,1							-- line type
							  ,0							-- parent line key
							  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
							  ,@DefaultClassKey             -- Class Key
							  ,0							-- Taxable
							  ,0							-- Taxable2
							  ,NULL							-- Work TypeKey
							  ,0							-- PostInDetail
							  ,NULL							-- Entity
							  ,NULL							-- EntityKey
							  ,NULL							-- OfficeKey
							  ,NULL							-- DefaultDepartmentKey	
							  ,@TopLineKey output
				if @RetVal <> 1 
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return @kErrInvoiceLineBase + @RetVal
				end

				-- Update the display Option for top line
				if @LayoutKey > 0
					update tInvoiceLine
					set    tInvoiceLine.DisplayOption = ISNULL(lb.DisplayOption, 2) --1 No Detail, 2 Sub Item Details, 3 Transactions
					from   tLayoutBilling lb (nolock)
					where  lb.LayoutKey = @LayoutKey
					and    lb.Entity = ''tProject''
					and    tInvoiceLine.InvoiceLineKey = @TopLineKey

			end


			-- eliminate lines which are for the billing items, they are displayed, but we are going to recreate them
			 
			select @LineOrder = -1
			while (1=1)
			begin
				select @LineOrder = min(LineOrder)
				from   #line
				where  LineOrder > @LineOrder
				and    Entity <> ''tWorkType''

				if @LineOrder 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  LineOrder = @LineOrder
				
			--create invoice line
			exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,NULL							-- ProjectKey
						  ,NULL							-- TaskKey
						  ,@LineEntityName				-- Line Subject
						  ,null                 		-- Line description
						  ,1                    		-- Bill From 
						  ,1							-- Quantity
						  ,@LineBillAmt					-- Unit Amount
						  ,@LineBillAmt					-- Line Amount
						  ,2							-- line type
						  ,@TopLineKey					-- 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 @kErrInvoiceLineBase + @RetVal
				end				
			
				update #line 
				set    InvoiceLineKey = @NewInvoiceLineKey
				where  LineOrder = @LineOrder

			end

			-- can only do it here because it is a text
			update tInvoiceLine
			set    tInvoiceLine.LineDescription = #line.EntityDescription
			from   #line
			where  tInvoiceLine.InvoiceLineKey = #line.InvoiceLineKey  	
			and    tInvoiceLine.InvoiceKey = @NewInvoiceKey
			
			-- now perform the grouping by billing item, top of invoice or top line key, do not recalc invoice order
			exec sptInvoiceLineGroupFFByBillingItem @NewInvoiceKey, @TopLineKey, 0 		
		end

		declare @ProjectKey int
		declare @ParentLineKey int
		declare @ParentInvoiceLineKey int
		declare @GrandParentLineKey int

		if @InvoiceBy in ( ''Segment'', ''Project'')
		begin

			-- do segment first
			select @LineKey = -1
			while (1=1)
			begin
				select @LineKey = min(LineKey)
				from   #line
				where  LineKey > @LineKey
				and    Entity = ''tCampaignSegment''

				if @LineKey is null
					break
			
				select @LineEntity = Entity
				       ,@LineEntityKey = EntityKey
				       ,@LineEntityName = EntityName
					   ,@LineType = LineType
					   ,@LineBillAmt = BillAmt
				from   #line
				where  LineKey = @LineKey
				
				--create single invoice line  

				if @LineType = 1 
				begin
					-- summary
					exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,Null					        -- ProjectKey
						  ,NULL							-- TaskKey
						  ,@LineEntityName				-- Line Subject
						  ,null                 		-- Line description
						  ,1                    		-- Bill From 
						  ,0							-- Quantity
						  ,0					        -- Unit Amount
						  ,0					        -- Line Amount
						  ,1							-- line type
						  ,0							-- parent line key
						  ,null				            -- Default Sales AccountKey
						  ,null                         -- Class Key
						  ,0						    -- Taxable
						  ,0						    -- Taxable2
						  ,null							-- Work TypeKey -- will be updated by the grouping by bi
						  ,0							-- PostInDetail
						  ,null					        -- Entity
						  ,0				            -- EntityKey
						  ,null                         --@OfficeKey
						  ,null                        --@LineDepartmentKey
						  ,@NewInvoiceLineKey output
				end
				else
				begin
					-- detail line because there probably was no budget
					exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,NULL					-- ProjectKey
						  ,NULL							-- TaskKey
						  ,@LineEntityName				-- Line Subject
						  ,null                 		-- Line description
						  ,1                    		-- Bill From 
						  ,1							-- Quantity
						  ,@LineBillAmt					-- Unit Amount
						  ,@LineBillAmt					-- Line Amount
						  ,2							-- line type
						  ,0		                    -- parent line key
						  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
						  ,@DefaultClassKey             -- Class Key
						  ,0						    -- Taxable
						  ,0						    -- Taxable2
						  ,NULL							-- Work TypeKey -- will be updated by the grouping by bi
						  ,0							-- PostInDetail
						  ,@LineEntity					-- Entity
						  ,@LineEntityKey				-- EntityKey
						  ,null
						  ,null
						  ,@NewInvoiceLineKey output
				end -- Line Type

				if @RetVal <> 1 
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return @kErrInvoiceLineBase + @RetVal
				end				
			
				update #line 
				set    InvoiceLineKey = @NewInvoiceLineKey
				where  LineKey = @LineKey
					
			end -- segment loop

			IF @LayoutKey > 0
				SELECT @DisplayOption = DisplayOption
				FROM tLayoutBilling (nolock)
				WHERE
					LayoutKey = @LayoutKey AND
					Entity = ''tProject''
			ELSE
				IF @InvoiceBy = ''Project''
						SELECT @DisplayOption = @kDisplayOptionSubItemDetail
				ELSE
						-- by segment
						SELECT @DisplayOption = @kDisplayOptionNoDetail
			
			If @MultipleSegments = 1 
			update tInvoiceLine
			set    tInvoiceLine.LineDescription = #line.EntityDescription -- text field, cannot be in a variable
			      ,tInvoiceLine.CampaignSegmentKey = #line.EntityKey
				  ,tInvoiceLine.DisplayOption = @DisplayOption
			from   #line
			where  tInvoiceLine.InvoiceLineKey = #line.InvoiceLineKey  			
			and    #line.Entity = ''tCampaignSegment''
		    and    tInvoiceLine.InvoiceKey = @NewInvoiceKey
			

			-- next do projects
			select @LineKey = -1
			while (1=1)
			begin
				select @LineKey = min(LineKey)
				from   #line
				where  LineKey > @LineKey
				and    Entity = ''tProject''

				if @LineKey is null
					break
			
				select @LineEntity = Entity
				       ,@LineEntityKey = EntityKey
				       ,@LineEntityName = EntityName
					   ,@LineType = LineType
					   ,@LineBillAmt = BillAmt
					   ,@ParentLineKey = ParentLineKey
					   ,@ProjectKey = ProjectKey
				from   #line
				where  LineKey = @LineKey
				
				select @ParentLineKey = isnull(@ParentLineKey, 0)

				select @ParentInvoiceLineKey = InvoiceLineKey
				from   #line
				where  LineKey =@ParentLineKey

				select @ParentInvoiceLineKey = isnull(@ParentInvoiceLineKey, 0)
				
				SELECT @OfficeKey = OfficeKey FROM tProject (NOLOCK) WHERE ProjectKey = @ProjectKey

				--create single invoice line 

				If @LineType = 1
				begin
					-- summary
					exec @RetVal = sptInvoiceLineInsertMassBilling
						   @NewInvoiceKey				-- Invoice Key
						  ,@ProjectKey					-- ProjectKey
						  ,NULL							-- TaskKey
						  ,@LineEntityName				-- Line Subject
						  ,null                 		-- Line description
						  ,1                    		-- Bill From 
						  ,0							-- Quantity
						  ,0					        -- Unit Amount
						  ,0					        -- Line Amount
						  ,1							-- line type
						  ,@ParentInvoiceLineKey		-- parent line key
						  ,null				            -- Default Sales AccountKey
						  ,null                         -- Class Key
						  ,0						    -- Taxable
						  ,0						    -- Taxable2
						  ,null							-- Work TypeKey -- will be updated by the grouping by bi
						  ,0							-- PostInDetail
						  ,null					        -- Entity
						  ,0				            -- EntityKey
						  ,@OfficeKey
						  ,null                        --@LineDepartmentKey
						  ,@NewInvoiceLineKey output
				end
				else
				begin
					-- detail line because there probably was no budget
					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
						  ,@ParentInvoiceLineKey		-- parent line key
						  ,@DefaultSalesAccountKey		-- Default Sales AccountKey
						  ,@DefaultClassKey             -- Class Key
						  ,0						    -- Taxable
						  ,0						    -- Taxable2
						  ,NULL							-- Work TypeKey -- will be updated by the grouping by bi
						  ,0							-- PostInDetail
						  ,@LineEntity					-- Entity
						  ,@LineEntityKey				-- EntityKey
						  ,@OfficeKey
						  ,null
						  ,@NewInvoiceLineKey output
				end

				if @RetVal <> 1 
				begin
					exec sptInvoiceDelete @NewInvoiceKey
					return @kErrInvoiceLineBase + @RetVal
				end				
			
				update #line 
				set    InvoiceLineKey = @NewInvoiceLineKey
				where  LineKey = @LineKey
					
			end -- project loop
		
			-- only do this if by project
			if @InvoiceBy = ''Project''
			begin
				update tInvoiceLine
				set    tInvoiceLine.DisplayOption = @DisplayOption
				      ,tInvoiceLine.LineDescription = #line.EntityDescription
				from   #line
				where  tInvoiceLine.InvoiceLineKey = #line.InvoiceLineKey  			
				and    #line.Entity = ''tProject''
				and    tInvoiceLine.InvoiceKey = @NewInvoiceKey			
			end

			-- next do items and services
			select @LineKey = -1
			while (1=1)
			begin
				select @LineKey = min(LineKey)
				from   #line
				where  LineKey > @LineKey
				and    LineType = 2
				and    Entity in (''tItem'', ''tService'')

				if @LineKey is null
					break
			
				select @LineEntity = Entity
				       ,@LineEntityKey = EntityKey
				       ,@LineEntityName = EntityName
					   ,@LineBillAmt = BillAmt	
                       ,@LineAccountKey = EntityAccountKey 
                       ,@LineDepartmentKey = EntityDepartmentKey
                       ,@LineClassKey = EntityClassKey
                       ,@Taxable = Taxable
                       ,@Taxable2 = Taxable2
					   ,@ProjectKey = ProjectKey
					   ,@ParentLineKey = ParentLineKey
				from   #line
				where  LineKey = @LineKey
				
				if @InvoiceBy = ''Project''
				begin
					select @ParentInvoiceLineKey = InvoiceLineKey
						  ,@ProjectKey = EntityKey
					from   #line
					where  LineKey = @ParentLineKey
				
					SELECT @OfficeKey = OfficeKey FROM tProject (NOLOCK) WHERE ProjectKey = @ProjectKey
				END
				else
					select @ParentInvoiceLineKey = InvoiceLineKey
						  ,@ProjectKey = NULL
                          ,@OfficeKey = null
					from   #line
					where  LineKey = @ParentLineKey
				
				select @ParentInvoiceLineKey = isnull(@ParentInvoiceLineKey, 0)

				-- we will try to propagate the segment key down
				select @SegmentKey = 0
				
				if @MultipleSegments = 1
				begin
					if @InvoiceBy = ''Segment''
						select @SegmentKey = EntityKey
						from   #line
						where  LineKey = @ParentLineKey
					else
					begin
						select @GrandParentLineKey = ParentLineKey
						from   #line
						where  LineKey = @ParentLineKey

						select @SegmentKey = EntityKey
						from   #line
						where  LineKey = @GrandParentLineKey
					
					end
				end
				 
				--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
						  ,@ParentInvoiceLineKey		-- parent line key
						  ,@LineAccountKey				-- Default Sales AccountKey
						  ,@LineClassKey                -- Class Key
						  ,@Taxable						-- Taxable
						  ,@Taxable						-- 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 @kErrInvoiceLineBase + @RetVal
				end				
			
				-- do we need to propagate the segment key down?? 
				update #line 
				set    InvoiceLineKey = @NewInvoiceLineKey
				      ,GPFlag = @SegmentKey
				where  LineOrder = @LineOrder
					
			end

			-- propagate CampaignSegmentKey down the lines so that we can find out what is billed next time we bill 
			update tInvoiceLine
			set    tInvoiceLine.LineDescription = #line.EntityDescription
			      ,tInvoiceLine.CampaignSegmentKey = #line.GPFlag
			from   #line
			where  tInvoiceLine.InvoiceLineKey = #line.InvoiceLineKey  	
			and    #line.Entity in (''tItem'', ''tService'')
		    and    tInvoiceLine.InvoiceKey = @NewInvoiceKey



			-- now perform the grouping by billing item, do not recalc invoice order
			
			if @InvoiceBy = ''Segment'' and @AdvanceBilling = 0
			begin
				select @LineKey = -1
				while (1=1)
				begin
					select @LineKey = min(LineKey)
					from   #line
					where  Entity=''tCampaignSegment''
					and    LineKey > @LineKey

					if @LineKey is null
						break

					select @NewInvoiceLineKey = InvoiceLineKey from #line where LineKey = @LineKey

					exec sptInvoiceLineGroupFFByBillingItem @NewInvoiceKey, @NewInvoiceLineKey, 0 		
				
				end
			end

			if @InvoiceBy = ''Project'' and @AdvanceBilling = 0
			begin
				select @LineKey = -1
				while (1=1)
				begin
					select @LineKey = min(LineKey)
					from   #line
					where  Entity=''tProject''
					and    LineKey > @LineKey

					if @LineKey is null
						break

					select @NewInvoiceLineKey = InvoiceLineKey from #line where LineKey = @LineKey

					exec sptInvoiceLineGroupFFByBillingItem @NewInvoiceKey, @NewInvoiceLineKey, 0 		
				
				end
			end


		end

	If ISNULL(@EstimateKey, 0) > 0
		Update tInvoiceLine 
		Set EstimateKey = @EstimateKey
		Where InvoiceKey = @NewInvoiceKey
		
	-- This will force the Taxable fields if the pref or the project requires them
	exec sptInvoiceSetTaxable @NewInvoiceKey, @SetTaxableOnInvoice

	-- before we leave, recalc the amounts in the header  
	exec sptInvoiceRecalcAmounts @NewInvoiceKey 
	
	-- Calculate the line order and position
	exec sptInvoiceOrder @NewInvoiceKey, 0, 0, 0
	  	
    --select * from #line
	
	 -- also update the billing schedule
	 if @UpdateSchedule = 1 and @Entity = ''tCampaign''
		exec spFixedFeesCampaignUpdateBillingSchedule @NewInvoiceKey, @EntityKey, null

	-- now do rollups on projects
	exec sptProjectRollupUpdateEntity ''tInvoice'', @NewInvoiceKey, 0, 0
	
	return @NewInvoiceKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetARAging]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetARAging]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetARAging]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,        -- defaults to today (UTC)
    @ClientID           varchar(75) = null,        -- tCompany.CustomerID  (or CompanyName fallback)
    @ParentClientID     varchar(75) = null,        -- tCompany.CustomerID of the parent
    @ProjectID          varchar(50) = null,        -- tProject.ProjectNumber
    @GLCompanyID        varchar(50) = null,        -- tGLCompany.GLCompanyID
    @ARAccountID        varchar(100) = null,       -- tGLAccount.AccountNumber  (AccountType = 11)
    @AgingDateOption    tinyint     = 1,           -- 1=InvoiceDate, 2=PostingDate, 3=DueDate
    @Days1              smallint    = 30,
    @Days2              smallint    = 60,
    @Days3              smallint    = 90,
    @MinDaysOverdue     int         = null,        -- only return invoices at least this many days past the aging date
    @PostStatus         tinyint     = 0,           -- 0 includes unposted, 1 posted only
    @IncludeAdvBill     tinyint     = 0,           -- include unapplied advance billings
    @IncludeReceipts    tinyint     = 0,           -- include unapplied receipts
    @CurrencyID         varchar(10) = null,        -- filter to one currency when multi-currency
    @MaxRows            int         = 500,         -- pagination ceiling on the invoices result set
    @Cursor             int         = 0            -- row offset for pagination
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created â€” API-friendly wrapper around spRptInvoiceAging.
||                          Returns 4 result sets: warnings, meta, summary, invoices.
||                          All filters accept string IDs; resolved to keys internally.
*/

set nocount on

    declare @ClientKey          int
    declare @ParentClientKey    int
    declare @ProjectKey         int
    declare @GLCompanyKeyResolved int
    declare @ARAccountKey       int
    declare @SecurityGroupKey   int
    declare @IsAdministrator    bit
    declare @RestrictToGLCompany tinyint
    declare @MultiCurrency      tinyint
    declare @HomeCurrencyID     varchar(10)
    declare @EffectiveCurrencyID varchar(10)
    declare @CanRunARAging      bit
    declare @ErrorCount         int
    declare @GLCompanyKeyArg    int
    declare @WindowStart        datetime
    declare @RowCount           int
    declare @Truncated          tinyint
    declare @NextCursor         int
    declare @OlderThanArg       int

    -- Default AsOfDate to today (no time) if not supplied
    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())

    -- Default pagination args defensively
    if @MaxRows is null or @MaxRows <= 0 set @MaxRows = 500
    if @Cursor  is null or @Cursor  <  0 set @Cursor  = 0

    -- 30-day default lookback window for the meta block
    set @WindowStart = dateadd(day, -30, @AsOfDate)

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. 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

    -- ------------------------------------------------------------------
    -- 3. Right check: acct_ar_aging (admin bypass)
    -- ------------------------------------------------------------------
    set @CanRunARAging = 0
    if @IsAdministrator = 1
        set @CanRunARAging = 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_ar_aging''
    )
        set @CanRunARAging = 1

    if @CanRunARAging = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to run AR Aging.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. 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)

    -- Reset CurrencyID arg to null when multi-currency is off
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 5. Validate basic args
    -- ------------------------------------------------------------------
    if @AgingDateOption not in (1, 2, 3)
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''agingDateOption must be 1 (InvoiceDate), 2 (PostingDate), or 3 (DueDate).'', ''agingDateOption'')
    end

    if @Days1 <= 0 or @Days2 <= @Days1 or @Days3 <= @Days2
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''days1 < days2 < days3 must hold and all must be positive.'', ''days1'')
    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 -102
    end

    -- ------------------------------------------------------------------
    -- 6. Resolve string IDs â†’ keys (warn on miss; never silently match wrong row)
    -- ------------------------------------------------------------------
    if @ClientID is not null and LTRIM(RTRIM(@ClientID)) <> ''''
    begin
        select @ClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(CustomerID) = UPPER(@ClientID) or UPPER(CompanyName) = UPPER(@ClientID))

        if @ClientKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Client not found: '' + @ClientID + '' â€” no invoices will be returned.'', ''clientID'')
    end

    if @ParentClientID is not null and LTRIM(RTRIM(@ParentClientID)) <> ''''
    begin
        select @ParentClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(CustomerID) = UPPER(@ParentClientID) or UPPER(CompanyName) = UPPER(@ParentClientID))

        if @ParentClientKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Parent client not found: '' + @ParentClientID + '' â€” no invoices will be returned.'', ''parentClientID'')
    end

    if @ProjectID is not null and LTRIM(RTRIM(@ProjectID)) <> ''''
    begin
        select @ProjectKey = ProjectKey
        from tProject (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(ProjectNumber) = UPPER(@ProjectID)

        if @ProjectKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Project not found: '' + @ProjectID + '' â€” no invoices will be returned.'', ''projectID'')
    end

    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' â€” filter ignored.'', ''glCompanyID'')
    end

    if @ARAccountID is not null and LTRIM(RTRIM(@ARAccountID)) <> ''''
    begin
        select @ARAccountKey = GLAccountKey
        from tGLAccount (nolock)
        where CompanyKey  = @CompanyKey
          and AccountType = 11
          and UPPER(AccountNumber) = UPPER(@ARAccountID)

        if @ARAccountKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''AR Account not found: '' + @ARAccountID + '' â€” filter ignored.'', ''arAccountID'')
    end

    -- ------------------------------------------------------------------
    -- 7. Build #GLCompanyKeys for the aging engine
    --    Honors RestrictToGLCompany + tUserGLCompanyAccess for non-admins.
    -- ------------------------------------------------------------------
    create table #GLCompanyKeys (GLCompanyKey int null)

    if @IsAdministrator = 1 and @GLCompanyKeyResolved is null
    begin
        -- Admin, no filter: let spRptInvoiceAging return all companies
        set @GLCompanyKeyArg = -1
    end
    else if @IsAdministrator = 1 and @GLCompanyKeyResolved is not null
    begin
        -- Admin, single-company filter
        insert into #GLCompanyKeys (GLCompanyKey) values (@GLCompanyKeyResolved)
        set @GLCompanyKeyArg = -2
    end
    else if @RestrictToGLCompany = 0 and @GLCompanyKeyResolved is null
    begin
        -- Non-admin, no restriction, no filter
        set @GLCompanyKeyArg = -1
    end
    else if @RestrictToGLCompany = 0 and @GLCompanyKeyResolved is not null
    begin
        insert into #GLCompanyKeys (GLCompanyKey) values (@GLCompanyKeyResolved)
        set @GLCompanyKeyArg = -2
    end
    else
    begin
        -- Restricted user: intersect (user allowlist) with (optional filter)
        insert into #GLCompanyKeys (GLCompanyKey)
        select uga.GLCompanyKey
        from tUserGLCompanyAccess uga (nolock)
        where uga.UserKey = @UserKey
          and (@GLCompanyKeyResolved is null or uga.GLCompanyKey = @GLCompanyKeyResolved)

        if not exists (select 1 from #GLCompanyKeys)
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''ACCESS_DENIED'', ''User has no GL company access â€” empty result returned.'', ''glCompanyID'')
        end

        set @GLCompanyKeyArg = -2
    end

    -- ------------------------------------------------------------------
    -- 8. Run the canonical aging engine in SummaryOnly mode.
    --    Engine returns 8 columns per client: ClientKey, ClientFullName,
    --    ClientName, NetAmount, Period0..Period3. Period0 includes BOTH
    --    "not yet due" and "0..Days1 overdue" â€” they cannot be separated
    --    in this mode.
    -- ------------------------------------------------------------------
    create table #AgingByClient (
        ClientKey       int           null,
        ClientFullName  nvarchar(600) null,
        ClientName      nvarchar(500) null,
        NetAmount       money         null,
        Period0         money         null,
        Period1         money         null,
        Period2         money         null,
        Period3         money         null
    )

    set @OlderThanArg = ISNULL(@MinDaysOverdue, 0)

    insert into #AgingByClient (
        ClientKey, ClientFullName, ClientName, NetAmount,
        Period0, Period1, Period2, Period3
    )
    exec spRptInvoiceAging
         @CompanyKey            = @CompanyKey,
         @AsOfDate              = @AsOfDate,
         @ClientKey             = @ClientKey,
         @ParentClientKey       = @ParentClientKey,
         @ClassKey              = null,
         @ProjectKey            = @ProjectKey,
         @PostStatus            = @PostStatus,
         @AdvBill               = @IncludeAdvBill,
         @Receipts              = @IncludeReceipts,
         @AgingDateOption       = @AgingDateOption,
         @OlderThan             = @OlderThanArg,
         @Days1                 = @Days1,
         @Days2                 = @Days2,
         @Days3                 = @Days3,
         @SummaryOnly           = 1,
         @GLCompanyKey          = @GLCompanyKeyArg,
         @Invoices              = 1,
         @AdvBillSalesTax       = 1,
         @AdvBillMultiplier     = 1,
         @ARAccountKey          = @ARAccountKey,
         @UserKey               = @UserKey,
         @CurrencyID            = @CurrencyID

    -- Pull ClientID out of the engine''s "ID - Name" composite for the API contract
    update #AgingByClient
       set ClientName = ISNULL(c.CompanyName, ClientName)
      from #AgingByClient a
      left join tCompany c (nolock) on c.CompanyKey = a.ClientKey

    -- drop empty (fully paid) clients to keep output focused
    delete from #AgingByClient
    where ISNULL(NetAmount, 0) = 0

    select @RowCount = COUNT(*) from #AgingByClient
    if @RowCount > (@Cursor + @MaxRows)
    begin
        set @Truncated  = 1
        set @NextCursor = @Cursor + @MaxRows
    end
    else
    begin
        set @Truncated  = 0
        set @NextCursor = null
    end

    -- ------------------------------------------------------------------
    -- 10. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType  as errorType,
           errorCode  as errorCode,
           errorMessage as errorMessage,
           fieldName  as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 11. Result set 2: meta (single row)
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate,    126) + ''Z''                 as asOf,
        @CompanyKey                                                   as companyKey,
        ISNULL(@EffectiveCurrencyID, '''')                              as currency,
        convert(varchar(10), @WindowStart, 23)                        as windowStart,
        convert(varchar(10), @AsOfDate,    23)                        as windowEnd,
        cast(null as varchar(10))                                     as comparisonWindowStart,
        cast(null as varchar(10))                                     as comparisonWindowEnd,
        @RowCount                                                     as [rowCount],
        @Truncated                                                    as truncated,
        @NextCursor                                                   as nextCursor,
        @AgingDateOption                                              as agingDateOption,
        @Days1                                                        as days1,
        @Days2                                                        as days2,
        @Days3                                                        as days3

    -- ------------------------------------------------------------------
    -- 12. Result set 3: summary (one row per bucket, fixed order).
    --     Summary mode bundles "not yet due" into Period0, so the
    --     "current" bucket is not separately reported here.
    -- ------------------------------------------------------------------
    ;with buckets as (
        select 1 as ord, ''0-30'' as bucket,
               ''0â€“'' + cast(@Days1 as varchar(10)) + '' days (incl. not yet due)'' as label,
               ISNULL(SUM(Period0), 0) as openAmount,
               SUM(case when Period0 <> 0 then 1 else 0 end) as clientCount,
               ''green'' as severity
        from #AgingByClient
        union all
        select 2, ''31-60'', cast(@Days1 + 1 as varchar(10)) + ''â€“'' + cast(@Days2 as varchar(10)) + '' days'',
               ISNULL(SUM(Period1), 0),
               SUM(case when Period1 <> 0 then 1 else 0 end),
               ''yellow''
        from #AgingByClient
        union all
        select 3, ''61-90'', cast(@Days2 + 1 as varchar(10)) + ''â€“'' + cast(@Days3 as varchar(10)) + '' days'',
               ISNULL(SUM(Period2), 0),
               SUM(case when Period2 <> 0 then 1 else 0 end),
               ''red''
        from #AgingByClient
        union all
        select 4, ''90+'', cast(@Days3 + 1 as varchar(10)) + ''+ days'',
               ISNULL(SUM(Period3), 0),
               SUM(case when Period3 <> 0 then 1 else 0 end),
               ''red''
        from #AgingByClient
        union all
        select 5, ''total'', ''Total open'',
               ISNULL(SUM(NetAmount), 0),
               COUNT(*),
               cast(null as varchar(10))
        from #AgingByClient
    )
    select bucket                      as bucket,
           label                       as label,
           ROUND(openAmount, 2)        as openAmount,
           clientCount                 as clientCount,
           cast(null as money)         as priorOpenAmount,
           severity                    as severity
    from buckets
    order by ord

    -- ------------------------------------------------------------------
    -- 13. Result set 4: clients (paginated, one row per client)
    -- ------------------------------------------------------------------
    ;with ordered as (
        select
            ROW_NUMBER() over (
                order by
                    case
                        when ISNULL(Period2,0) + ISNULL(Period3,0) > 0 then 1   -- red
                        when ISNULL(Period1,0)                      > 0 then 2   -- yellow
                        else                                                3   -- green
                    end,
                    ISNULL(NetAmount,0) desc,
                    ClientName
            )                                       as rn,
            ClientKey, ClientName, NetAmount,
            Period0, Period1, Period2, Period3
        from #AgingByClient
    )
    select
        ClientKey                                                       as clientKey,
        ClientName                                                      as clientName,
        ROUND(ISNULL(Period0, 0), 2)                                    as bucket0_30,
        ROUND(ISNULL(Period1, 0), 2)                                    as bucket31_60,
        ROUND(ISNULL(Period2, 0), 2)                                    as bucket61_90,
        ROUND(ISNULL(Period3, 0), 2)                                    as bucket90Plus,
        ROUND(ISNULL(NetAmount, 0), 2)                                  as totalOpen,
        case
            when ISNULL(Period2,0) + ISNULL(Period3,0) > 0 then ''overdue_60plus''
            when ISNULL(Period1,0)                      > 0 then ''overdue_30plus''
            else                                                null
        end                                                             as flag,
        case
            when ISNULL(Period2,0) + ISNULL(Period3,0) > 0 then ''red''
            when ISNULL(Period1,0)                      > 0 then ''yellow''
            else                                                ''green''
        end                                                             as severity,
        @EffectiveCurrencyID                                            as currency
    from ordered
    where rn >  @Cursor
      and rn <= @Cursor + @MaxRows
    order by rn

    -- ------------------------------------------------------------------
    drop table #AgingByClient
    drop table #GLCompanyKeys
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetAPAging]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetAPAging]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetAPAging]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,        -- defaults to today (UTC)
    @VendorID           varchar(50) = null,        -- tCompany.VendorID  (or CompanyName fallback)
    @GLCompanyID        varchar(50) = null,        -- tGLCompany.GLCompanyID
    @APAccountID        varchar(100) = null,       -- tGLAccount.AccountNumber  (AccountType = 20)
    @AgingDateOption    tinyint     = 3,           -- 1=InvoiceDate, 2=PostingDate, 3=DueDate (AP default)
    @Days1              smallint    = 30,
    @Days2              smallint    = 60,
    @Days3              smallint    = 90,
    @MinDaysOverdue     int         = null,        -- only return vouchers at least this many days past the aging date
    @PostStatus         tinyint     = 0,           -- 0 includes unposted, 1 posted only
    @IncludePayments    tinyint     = 0,           -- 1 include unapplied payments
    @CurrencyID         varchar(10) = null,        -- filter to one currency when multi-currency
    @MaxRows            int         = 500,         -- pagination ceiling on the vendors result set
    @Cursor             int         = 0            -- row offset for pagination
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created Ã¢â‚¬â€ API-friendly wrapper around spRptVoucherAging.
||                          Returns 4 result sets: warnings, meta, summary, vendors.
||                          All filters accept string IDs; resolved to keys internally.
*/

set nocount on

    declare @VendorKey          int
    declare @GLCompanyKeyResolved int
    declare @APAccountKey       int
    declare @SecurityGroupKey   int
    declare @IsAdministrator    bit
    declare @RestrictToGLCompany tinyint
    declare @MultiCurrency      tinyint
    declare @HomeCurrencyID     varchar(10)
    declare @EffectiveCurrencyID varchar(10)
    declare @CanRunAPAging      bit
    declare @ErrorCount         int
    declare @GLCompanyKeyArg    int
    declare @WindowStart        datetime
    declare @RowCount           int
    declare @Truncated          tinyint
    declare @NextCursor         int

    -- Default AsOfDate to today (no time) if not supplied
    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())

    -- Default pagination args defensively
    if @MaxRows is null or @MaxRows <= 0 set @MaxRows = 500
    if @Cursor  is null or @Cursor  <  0 set @Cursor  = 0

    -- 30-day default lookback window for the meta block
    set @WindowStart = dateadd(day, -30, @AsOfDate)

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. 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

    -- ------------------------------------------------------------------
    -- 3. Right check: acct_ap_aging (admin bypass)
    -- ------------------------------------------------------------------
    set @CanRunAPAging = 0
    if @IsAdministrator = 1
        set @CanRunAPAging = 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_ap_aging''
    )
        set @CanRunAPAging = 1

    if @CanRunAPAging = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to run AP Aging.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. 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)

    -- Reset CurrencyID arg to null when multi-currency is off
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 5. Validate basic args
    -- ------------------------------------------------------------------
    if @AgingDateOption not in (1, 2, 3)
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''agingDateOption must be 1 (InvoiceDate), 2 (PostingDate), or 3 (DueDate).'', ''agingDateOption'')
    end

    if @Days1 <= 0 or @Days2 <= @Days1 or @Days3 <= @Days2
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''days1 < days2 < days3 must hold and all must be positive.'', ''days1'')
    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 -102
    end

    -- ------------------------------------------------------------------
    -- 6. Resolve string IDs Ã¢â€ â€™ keys (warn on miss; never silently match wrong row)
    -- ------------------------------------------------------------------
    if @VendorID is not null and LTRIM(RTRIM(@VendorID)) <> ''''
    begin
        select @VendorKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(VendorID) = UPPER(@VendorID) or UPPER(CompanyName) = UPPER(@VendorID))

        if @VendorKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Vendor not found: '' + @VendorID + '' Ã¢â‚¬â€ no vouchers will be returned.'', ''vendorID'')
    end

    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' Ã¢â‚¬â€ filter ignored.'', ''glCompanyID'')
    end

    if @APAccountID is not null and LTRIM(RTRIM(@APAccountID)) <> ''''
    begin
        select @APAccountKey = GLAccountKey
        from tGLAccount (nolock)
        where CompanyKey  = @CompanyKey
          and AccountType = 20
          and UPPER(AccountNumber) = UPPER(@APAccountID)

        if @APAccountKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''AP Account not found: '' + @APAccountID + '' Ã¢â‚¬â€ filter ignored.'', ''apAccountID'')
    end

    -- ------------------------------------------------------------------
    -- 7. Build #GLCompanyKeys for the aging engine
    --    Honors RestrictToGLCompany + tUserGLCompanyAccess for non-admins.
    -- ------------------------------------------------------------------
    create table #GLCompanyKeys (GLCompanyKey int null)

    if @IsAdministrator = 1 and @GLCompanyKeyResolved is null
    begin
        set @GLCompanyKeyArg = -1
    end
    else if @IsAdministrator = 1 and @GLCompanyKeyResolved is not null
    begin
        insert into #GLCompanyKeys (GLCompanyKey) values (@GLCompanyKeyResolved)
        set @GLCompanyKeyArg = -2
    end
    else if @RestrictToGLCompany = 0 and @GLCompanyKeyResolved is null
    begin
        set @GLCompanyKeyArg = -1
    end
    else if @RestrictToGLCompany = 0 and @GLCompanyKeyResolved is not null
    begin
        insert into #GLCompanyKeys (GLCompanyKey) values (@GLCompanyKeyResolved)
        set @GLCompanyKeyArg = -2
    end
    else
    begin
        -- Restricted user: intersect (user allowlist) with (optional filter)
        insert into #GLCompanyKeys (GLCompanyKey)
        select uga.GLCompanyKey
        from tUserGLCompanyAccess uga (nolock)
        where uga.UserKey = @UserKey
          and (@GLCompanyKeyResolved is null or uga.GLCompanyKey = @GLCompanyKeyResolved)

        if not exists (select 1 from #GLCompanyKeys)
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''ACCESS_DENIED'', ''User has no GL company access Ã¢â‚¬â€ empty result returned.'', ''glCompanyID'')
        end

        set @GLCompanyKeyArg = -2
    end

    -- ------------------------------------------------------------------
    -- 8. Run the canonical aging engine in SummaryOnly mode.
    --    Engine returns 7 columns per vendor: VendorKey, VendorFullName,
    --    NetAmount, Period0..Period3. Period0 includes BOTH "not yet due"
    --    and "0..Days1 overdue" Ã¢â‚¬â€ they cannot be separated in this mode.
    -- ------------------------------------------------------------------
    create table #AgingByVendor (
        VendorKey       int           null,
        VendorFullName  nvarchar(600) null,
        VendorName      nvarchar(500) null,
        NetAmount       money         null,
        Period0         money         null,
        Period1         money         null,
        Period2         money         null,
        Period3         money         null
    )

    insert into #AgingByVendor (
        VendorKey, VendorFullName, NetAmount,
        Period0, Period1, Period2, Period3
    )
    exec spRptVoucherAging
         @CompanyKey         = @CompanyKey,
         @AsOfDate           = @AsOfDate,
         @GLCompanyKey       = @GLCompanyKeyArg,
         @ClassKey           = null,
         @VendorKey          = @VendorKey,
         @PostStatus         = @PostStatus,
         @Payments           = @IncludePayments,
         @Days1              = @Days1,
         @Days2              = @Days2,
         @Days3              = @Days3,
         @AgingDateOption    = @AgingDateOption,
         @APAccountKey       = @APAccountKey,
         @SummaryOnly        = 1,
         @UserKey            = @UserKey,
         @CurrencyID         = @CurrencyID

    -- Resolve VendorName from the company table for the API contract
    update #AgingByVendor
       set VendorName = ISNULL(c.CompanyName, VendorFullName)
      from #AgingByVendor a
      left join tCompany c (nolock) on c.CompanyKey = a.VendorKey

    -- drop empty (fully paid) vendors to keep output focused
    delete from #AgingByVendor where ISNULL(NetAmount, 0) = 0

    -- Note: @MinDaysOverdue is honored inside the engine via @Days1..@Days3
    -- bucketing; we can''t post-filter per-voucher days from summary mode.

    select @RowCount = COUNT(*) from #AgingByVendor
    if @RowCount > (@Cursor + @MaxRows)
    begin
        set @Truncated  = 1
        set @NextCursor = @Cursor + @MaxRows
    end
    else
    begin
        set @Truncated  = 0
        set @NextCursor = null
    end

    -- ------------------------------------------------------------------
    -- 10. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType  as errorType,
           errorCode  as errorCode,
           errorMessage as errorMessage,
           fieldName  as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 11. Result set 2: meta (single row)
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate,    126) + ''Z''                 as asOf,
        @CompanyKey                                                   as companyKey,
        ISNULL(@EffectiveCurrencyID, '''')                              as currency,
        convert(varchar(10), @WindowStart, 23)                        as windowStart,
        convert(varchar(10), @AsOfDate,    23)                        as windowEnd,
        cast(null as varchar(10))                                     as comparisonWindowStart,
        cast(null as varchar(10))                                     as comparisonWindowEnd,
        @RowCount                                                     as [rowCount],
        @Truncated                                                    as truncated,
        @NextCursor                                                   as nextCursor,
        @AgingDateOption                                              as agingDateOption,
        @Days1                                                        as days1,
        @Days2                                                        as days2,
        @Days3                                                        as days3

    -- ------------------------------------------------------------------
    -- 12. Result set 3: summary (one row per bucket, fixed order).
    --     Summary mode bundles "not yet due" into Period0.
    -- ------------------------------------------------------------------
    ;with buckets as (
        select 1 as ord, ''0-30'' as bucket,
               ''0Ã¢â‚¬â€œ'' + cast(@Days1 as varchar(10)) + '' days (incl. not yet due)'' as label,
               ISNULL(SUM(Period0), 0) as openAmount,
               SUM(case when Period0 <> 0 then 1 else 0 end) as vendorCount,
               ''green'' as severity
        from #AgingByVendor
        union all
        select 2, ''31-60'', cast(@Days1 + 1 as varchar(10)) + ''Ã¢â‚¬â€œ'' + cast(@Days2 as varchar(10)) + '' days'',
               ISNULL(SUM(Period1), 0),
               SUM(case when Period1 <> 0 then 1 else 0 end),
               ''yellow''
        from #AgingByVendor
        union all
        select 3, ''61-90'', cast(@Days2 + 1 as varchar(10)) + ''Ã¢â‚¬â€œ'' + cast(@Days3 as varchar(10)) + '' days'',
               ISNULL(SUM(Period2), 0),
               SUM(case when Period2 <> 0 then 1 else 0 end),
               ''red''
        from #AgingByVendor
        union all
        select 4, ''90+'', cast(@Days3 + 1 as varchar(10)) + ''+ days'',
               ISNULL(SUM(Period3), 0),
               SUM(case when Period3 <> 0 then 1 else 0 end),
               ''red''
        from #AgingByVendor
        union all
        select 5, ''total'', ''Total open'',
               ISNULL(SUM(NetAmount), 0),
               COUNT(*),
               cast(null as varchar(10))
        from #AgingByVendor
    )
    select bucket                      as bucket,
           label                       as label,
           ROUND(openAmount, 2)        as openAmount,
           vendorCount                 as vendorCount,
           cast(null as money)         as priorOpenAmount,
           severity                    as severity
    from buckets
    order by ord

    -- ------------------------------------------------------------------
    -- 13. Result set 4: vendors (paginated, one row per vendor)
    -- ------------------------------------------------------------------
    ;with ordered as (
        select
            ROW_NUMBER() over (
                order by
                    case
                        when ISNULL(Period2,0) + ISNULL(Period3,0) > 0 then 1
                        when ISNULL(Period1,0)                      > 0 then 2
                        else                                                3
                    end,
                    ISNULL(NetAmount,0) desc,
                    VendorName
            )                                       as rn,
            VendorKey, VendorName, NetAmount,
            Period0, Period1, Period2, Period3
        from #AgingByVendor
    )
    select
        VendorKey                                                       as vendorKey,
        VendorName                                                      as vendorName,
        ROUND(ISNULL(Period0, 0), 2)                                    as bucket0_30,
        ROUND(ISNULL(Period1, 0), 2)                                    as bucket31_60,
        ROUND(ISNULL(Period2, 0), 2)                                    as bucket61_90,
        ROUND(ISNULL(Period3, 0), 2)                                    as bucket90Plus,
        ROUND(ISNULL(NetAmount, 0), 2)                                  as totalOpen,
        case
            when ISNULL(Period2,0) + ISNULL(Period3,0) > 0 then ''overdue_60plus''
            when ISNULL(Period1,0)                      > 0 then ''overdue_30plus''
            else                                                null
        end                                                             as flag,
        case
            when ISNULL(Period2,0) + ISNULL(Period3,0) > 0 then ''red''
            when ISNULL(Period1,0)                      > 0 then ''yellow''
            else                                                ''green''
        end                                                             as severity,
        @EffectiveCurrencyID                                            as currency
    from ordered
    where rn >  @Cursor
      and rn <= @Cursor + @MaxRows
    order by rn

    -- ------------------------------------------------------------------
    drop table #AgingByVendor
    drop table #GLCompanyKeys
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetOverdueInvoices]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetOverdueInvoices]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetOverdueInvoices]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,        -- defaults to today (UTC)
    @ClientID           varchar(75) = null,        -- tCompany.CustomerID (or CompanyName fallback)
    @ProjectID          varchar(50) = null,        -- tProject.ProjectNumber
    @GLCompanyID        varchar(50) = null,        -- tGLCompany.GLCompanyID
    @MinDaysOverdue     int         = 1,           -- only invoices past due by at least N days (1 = anything past due)
    @MaxDaysOverdue     int         = null,        -- optional cap (e.g. 60 = exclude very old write-offs)
    @MinOpenAmount      money       = null,        -- optional minimum exposure filter
    @CurrencyID         varchar(10) = null,        -- filter to one currency when multi-currency
    @PostStatus         tinyint     = 0,           -- 0 includes unposted, 1 posted only
    @MaxRows            int         = 100,         -- pagination ceiling — collections lists are short, default tighter than aging
    @Cursor             int         = 0            -- row offset for pagination
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — collections-prioritized overdue invoice list.
||                          Trusts tInvoice.AmountReceived + RetainerAmount for openAmount
||                          (path 1; does not subtract applied credits via tBillingPayment).
||                          v2: add payerProfile / avgPaymentLagDays via tBillingPayment → tCheck.
*/

set nocount on

    declare @ClientKey            int
    declare @ProjectKey           int
    declare @GLCompanyKeyResolved int
    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @MultiCurrency        tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @EffectiveCurrencyID  varchar(10)
    declare @CanRunCollections    bit
    declare @ErrorCount           int
    declare @RowCount             int
    declare @Truncated            tinyint
    declare @NextCursor           int

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())

    if @MaxRows is null or @MaxRows <= 0 set @MaxRows = 100
    if @Cursor  is null or @Cursor  <  0 set @Cursor  = 0
    if @MinDaysOverdue is null           set @MinDaysOverdue = 1

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. 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

    -- ------------------------------------------------------------------
    -- 3. Right check: acct_ar_aging covers collections (admin bypass)
    -- ------------------------------------------------------------------
    set @CanRunCollections = 0
    if @IsAdministrator = 1
        set @CanRunCollections = 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 (''acct_ar_aging'', ''acct_ar_invoicesummary'', ''billingviewclientinvoice'')
    )
        set @CanRunCollections = 1

    if @CanRunCollections = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view AR collections data.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. 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)
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 5. Resolve string IDs → keys
    -- ------------------------------------------------------------------
    if @ClientID is not null and LTRIM(RTRIM(@ClientID)) <> ''''
    begin
        select @ClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(CustomerID) = UPPER(@ClientID) or UPPER(CompanyName) = UPPER(@ClientID))

        if @ClientKey is null
        begin
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Client not found: '' + @ClientID + '' — empty result returned.'', ''clientID'')

            select errorType, errorCode, errorMessage, fieldName from #errors where errorType = ''warning''
            -- emit empty meta + empty invoices, then return cleanly
            select
                convert(varchar(19), @AsOfDate, 126) + ''Z'' as asOf,
                @CompanyKey                                as companyKey,
                ISNULL(@EffectiveCurrencyID, '''')           as currency,
                0 as [rowCount], cast(0 as bit) as truncated, cast(null as int) as nextCursor
            select top 0
                cast(null as int)            as invoiceKey
            drop table #errors
            return 0
        end
    end

    if @ProjectID is not null and LTRIM(RTRIM(@ProjectID)) <> ''''
    begin
        select @ProjectKey = ProjectKey
        from tProject (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(ProjectNumber) = UPPER(@ProjectID)

        if @ProjectKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Project not found: '' + @ProjectID + '' — filter ignored.'', ''projectID'')
    end

    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 6. Pull overdue invoices into temp staging (path 1 math)
    --     openAmount = InvoiceTotalAmount − AmountReceived − RetainerAmount
    --     filter: due date < AsOfDate AND openAmount > 0
    -- ------------------------------------------------------------------
    create table #Overdue (
        InvoiceKey            int            null,
        InvoiceNumber         varchar(35)    null,
        InvoiceDate           smalldatetime  null,
        DueDate               smalldatetime  null,
        PostingDate           smalldatetime  null,
        ClientKey             int            null,
        ClientID              varchar(75)    null,
        ClientName            nvarchar(200)  null,
        ContactName           varchar(100)   null,
        ProjectKey            int            null,
        ProjectNumber         varchar(50)    null,
        ProjectName           nvarchar(500)  null,
        AccountManagerKey     int            null,
        AccountManagerName    varchar(200)   null,
        ProjectManagerKey     int            null,
        ProjectManagerName    varchar(200)   null,
        GLCompanyKey          int            null,
        InvoiceTotalAmount    money          null,
        AmountReceived        money          null,
        RetainerAmount        money          null,
        OpenAmount            money          null,
        DaysOverdue           int            null,
        CurrencyID            varchar(10)    null,
        InvoiceStatus         smallint       null
    )

    insert into #Overdue (
        InvoiceKey, InvoiceNumber, InvoiceDate, DueDate, PostingDate,
        ClientKey, ClientID, ClientName, ContactName,
        ProjectKey, ProjectNumber, ProjectName,
        AccountManagerKey, AccountManagerName,
        ProjectManagerKey, ProjectManagerName,
        GLCompanyKey,
        InvoiceTotalAmount, AmountReceived, RetainerAmount, OpenAmount,
        DaysOverdue, CurrencyID, InvoiceStatus
    )
    select
        i.InvoiceKey,
        i.InvoiceNumber,
        i.InvoiceDate,
        i.DueDate,
        i.PostingDate,
        i.ClientKey,
        c.CustomerID,
        c.CompanyName,
        i.ContactName,
        i.ProjectKey,
        p.ProjectNumber,
        p.ProjectName,
        p.AccountManager,
        case when p.AccountManager is not null then am.FirstName + '' '' + am.LastName end,
        p.ProjectManager,
        case when p.ProjectManager is not null then pm.FirstName + '' '' + pm.LastName end,
        i.GLCompanyKey,
        i.InvoiceTotalAmount,
        ISNULL(i.AmountReceived, 0),
        ISNULL(i.RetainerAmount, 0),
        i.InvoiceTotalAmount - ISNULL(i.AmountReceived, 0) - ISNULL(i.RetainerAmount, 0),
        DATEDIFF(day, i.DueDate, @AsOfDate),
        i.CurrencyID,
        i.InvoiceStatus
    from tInvoice i (nolock)
    left join tCompany c (nolock) on i.ClientKey         = c.CompanyKey
    left join tProject p (nolock) on i.ProjectKey        = p.ProjectKey
    left join tUser   am (nolock) on p.AccountManager    = am.UserKey
    left join tUser   pm (nolock) on p.ProjectManager    = pm.UserKey
    where i.CompanyKey      = @CompanyKey
      and i.DueDate         < @AsOfDate
      and i.InvoiceDate    <= @AsOfDate
      and i.InvoiceStatus   = 4                                                                                  -- Approved
      and (i.InvoiceTotalAmount - ISNULL(i.AmountReceived, 0) - ISNULL(i.RetainerAmount, 0)) > 0
      and (@ClientKey            is null or i.ClientKey      = @ClientKey)
      and (@ProjectKey           is null or i.ProjectKey     = @ProjectKey)
      and (@GLCompanyKeyResolved is null or i.GLCompanyKey   = @GLCompanyKeyResolved)
      and (@CurrencyID           is null or ISNULL(i.CurrencyID, '''') = ISNULL(@CurrencyID, ''''))
      and (i.Posted >= @PostStatus)

    -- ------------------------------------------------------------------
    -- 7. GL company security (admin bypass; honors RestrictToGLCompany)
    -- ------------------------------------------------------------------
    if @IsAdministrator = 0 and @RestrictToGLCompany = 1
    begin
        delete from #Overdue
        where ISNULL(GLCompanyKey, 0) not in (
            select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey
        )
    end

    -- ------------------------------------------------------------------
    -- 8. Apply daysOverdue + openAmount range filters
    -- ------------------------------------------------------------------
    delete from #Overdue
    where DaysOverdue < @MinDaysOverdue
       or (@MaxDaysOverdue is not null and DaysOverdue > @MaxDaysOverdue)
       or (@MinOpenAmount  is not null and OpenAmount  < @MinOpenAmount)

    -- ------------------------------------------------------------------
    -- 9. Pagination
    -- ------------------------------------------------------------------
    select @RowCount = COUNT(*) from #Overdue
    if @RowCount > (@Cursor + @MaxRows)
    begin
        set @Truncated  = 1
        set @NextCursor = @Cursor + @MaxRows
    end
    else
    begin
        set @Truncated  = 0
        set @NextCursor = null
    end

    -- ------------------------------------------------------------------
    -- 10. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 11. Result set 2: meta (single row)
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate, 126) + ''Z''                        as asOf,
        @CompanyKey                                                       as companyKey,
        ISNULL(@EffectiveCurrencyID, '''')                                  as currency,
        convert(varchar(10), @AsOfDate, 23)                               as windowEnd,
        @RowCount                                                         as [rowCount],
        @Truncated                                                        as truncated,
        @NextCursor                                                       as nextCursor,
        @MinDaysOverdue                                                   as minDaysOverdue,
        @MaxDaysOverdue                                                   as maxDaysOverdue

    -- ------------------------------------------------------------------
    -- 12. Result set 3: invoices (paginated, prioritized for collections)
    --     Sort: severity desc → openAmount desc → daysOverdue desc
    --     Bucket cutoffs are the standard 30/60/90 boundaries.
    -- ------------------------------------------------------------------
    ;with ranked as (
        select
            ROW_NUMBER() over (
                order by
                    case
                        when DaysOverdue > 60 then 1   -- red
                        when DaysOverdue > 30 then 2   -- yellow
                        else                       3   -- green (1..30)
                    end,
                    OpenAmount  desc,
                    DaysOverdue desc
            )                                              as rn,
            InvoiceKey, InvoiceNumber, InvoiceDate, DueDate, PostingDate,
            ClientKey, ClientID, ClientName, ContactName,
            ProjectKey, ProjectNumber, ProjectName,
            AccountManagerKey, AccountManagerName,
            ProjectManagerKey, ProjectManagerName,
            GLCompanyKey,
            InvoiceTotalAmount, AmountReceived, RetainerAmount, OpenAmount,
            DaysOverdue, CurrencyID, InvoiceStatus
        from #Overdue
    )
    select
        InvoiceKey                                              as invoiceKey,
        InvoiceNumber                                           as invoiceNumber,
        convert(varchar(10), InvoiceDate, 23)                   as invoiceDate,
        convert(varchar(10), DueDate,     23)                   as dueDate,
        convert(varchar(10), PostingDate, 23)                   as postingDate,
        ClientKey                                               as clientKey,
        ClientID                                                as clientID,
        ClientName                                              as clientName,
        ContactName                                             as contactName,
        ProjectKey                                              as projectKey,
        ProjectNumber                                           as projectNumber,
        ProjectName                                             as projectName,
        AccountManagerKey                                       as accountManagerKey,
        AccountManagerName                                      as accountManagerName,
        ProjectManagerKey                                       as projectManagerKey,
        ProjectManagerName                                      as projectManagerName,
        GLCompanyKey                                            as glCompanyKey,
        ROUND(InvoiceTotalAmount, 2)                            as invoiceTotalAmount,
        ROUND(AmountReceived,     2)                            as amountReceived,
        ROUND(RetainerAmount,     2)                            as retainerAmount,
        ROUND(OpenAmount,         2)                            as openAmount,
        DaysOverdue                                             as daysOverdue,
        case
            when DaysOverdue <= 30 then ''0-30''
            when DaysOverdue <= 60 then ''31-60''
            when DaysOverdue <= 90 then ''61-90''
            else                        ''90+''
        end                                                     as bucket,
        case
            when DaysOverdue >  60 then ''overdue_60plus''
            when DaysOverdue >  30 then ''overdue_30plus''
            else                        ''overdue''
        end                                                     as flag,
        case
            when DaysOverdue >  60 then ''red''
            when DaysOverdue >  30 then ''yellow''
            else                        ''green''
        end                                                     as severity,
        CurrencyID                                              as currency
    from ranked
    where rn >  @Cursor
      and rn <= @Cursor + @MaxRows
    order by rn

    -- ------------------------------------------------------------------
    drop table #Overdue
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetCashPosition]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetCashPosition]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetCashPosition]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,        -- defaults to today (UTC)
    @PriorAsOfDate      datetime    = null,        -- optional explicit prior date
    @CompareDaysBack    int         = 7,           -- used when @PriorAsOfDate is null (default = WoW delta)
    @GLCompanyID        varchar(50) = null,        -- tGLCompany.GLCompanyID  (single)
    @IncludeInactive    bit         = 0,           -- default 0: only Active bank accounts
    @MinBalanceThreshold money      = 5000.00      -- balances at/below trigger yellow severity; <= 0 trigger red
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — current cash position summary across Bank accounts (AccountType=10).
||                          Computes balance at @AsOfDate AND at a prior date (default 7 days back) for WoW delta.
||                          Reports amounts in the main home currency (per tTransaction Debit/Credit convention,
||                          same as sptGLAccountGetBalance). Native-currency per-account display would require a
||                          more complex query — flagged as v2.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @CanSeeCash           bit
    declare @ErrorCount           int
    declare @GLCompanyKeyResolved int

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())

    if @CompareDaysBack is null or @CompareDaysBack < 0
        set @CompareDaysBack = 7

    if @PriorAsOfDate is null and @CompareDaysBack > 0
        set @PriorAsOfDate = dateadd(day, -@CompareDaysBack, @AsOfDate)

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. 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

    -- ------------------------------------------------------------------
    -- 3. Right check (any one of these gates a cash-position view).
    --    Admins bypass.
    -- ------------------------------------------------------------------
    set @CanSeeCash = 0
    if @IsAdministrator = 1
        set @CanSeeCash = 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 (''acct_gl_balsheet'', ''acct_gl_trailbal'', ''acct_gl_cashprojection'')
    )
        set @CanSeeCash = 1

    if @CanSeeCash = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view bank balances.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. Preferences
    -- ------------------------------------------------------------------
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0),
           @HomeCurrencyID      = CurrencyID
    from tPreference (nolock)
    where CompanyKey = @CompanyKey

    set @RestrictToGLCompany = ISNULL(@RestrictToGLCompany, 0)

    -- ------------------------------------------------------------------
    -- 5. Resolve GLCompanyID → key (optional)
    -- ------------------------------------------------------------------
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 6. List the Bank accounts (AccountType = 10) in scope
    -- ------------------------------------------------------------------
    create table #BankAccounts (
        GLAccountKey   int            null,
        AccountNumber  varchar(100)   null,
        AccountName    nvarchar(200)  null,
        DisplayOrder   int            null,
        CurrencyID     varchar(10)    null,
        CurrentBalance money          null,        -- as-of  @AsOfDate
        PriorBalance   money          null         -- as-of  @PriorAsOfDate
    )

    insert into #BankAccounts (GLAccountKey, AccountNumber, AccountName, DisplayOrder, CurrencyID)
    select gl.GLAccountKey, gl.AccountNumber, gl.AccountName, gl.DisplayOrder, gl.CurrencyID
    from tGLAccount gl (nolock)
    where gl.CompanyKey  = @CompanyKey
      and gl.AccountType = 10
      and (@IncludeInactive = 1 or gl.Active = 1)

    -- GL company security
    if @IsAdministrator = 0 and @RestrictToGLCompany = 1
    begin
        -- Bank accounts themselves don''t carry GLCompanyKey directly — restrict via the transactions:
        -- if the user can see none of the GL companies in which an account had activity, drop it.
        delete from #BankAccounts
        where GLAccountKey not in (
            select distinct t.GLAccountKey
            from tTransaction t (nolock)
            where t.CompanyKey   = @CompanyKey
              and t.GLAccountKey in (select GLAccountKey from #BankAccounts)
              and t.GLCompanyKey in (
                  select uglca.GLCompanyKey
                  from tUserGLCompanyAccess uglca (nolock)
                  where uglca.UserKey = @UserKey
              )
        )
    end

    -- ------------------------------------------------------------------
    -- 7. Compute balances (Debit − Credit; sign convention from sptGLAccountGetBalance)
    -- ------------------------------------------------------------------
    update b
       set b.CurrentBalance = ISNULL(c.bal, 0)
    from #BankAccounts b
    left join (
        select t.GLAccountKey, SUM(ISNULL(t.Debit, 0) - ISNULL(t.Credit, 0)) as bal
        from tTransaction t (nolock)
        where t.CompanyKey      = @CompanyKey
          and t.TransactionDate <= @AsOfDate
          and (@GLCompanyKeyResolved is null or t.GLCompanyKey = @GLCompanyKeyResolved)
        group by t.GLAccountKey
    ) c on b.GLAccountKey = c.GLAccountKey

    if @PriorAsOfDate is not null
    begin
        update b
           set b.PriorBalance = ISNULL(p.bal, 0)
        from #BankAccounts b
        left join (
            select t.GLAccountKey, SUM(ISNULL(t.Debit, 0) - ISNULL(t.Credit, 0)) as bal
            from tTransaction t (nolock)
            where t.CompanyKey      = @CompanyKey
              and t.TransactionDate <= @PriorAsOfDate
              and (@GLCompanyKeyResolved is null or t.GLCompanyKey = @GLCompanyKeyResolved)
            group by t.GLAccountKey
        ) p on b.GLAccountKey = p.GLAccountKey
    end

    -- ------------------------------------------------------------------
    -- 8. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 9. Result set 2: meta (single row, with rolled-up totals)
    -- ------------------------------------------------------------------
    declare @TotalCurrent money, @TotalPrior money, @AccountCount int
    select @TotalCurrent = ISNULL(SUM(CurrentBalance), 0),
           @TotalPrior   = ISNULL(SUM(PriorBalance),   0),
           @AccountCount = COUNT(*)
    from #BankAccounts

    select
        convert(varchar(19), @AsOfDate,      126) + ''Z''                   as asOf,
        @CompanyKey                                                       as companyKey,
        ISNULL(@HomeCurrencyID, '''')                                       as currency,
        convert(varchar(10), @AsOfDate,      23)                          as windowEnd,
        convert(varchar(10), @PriorAsOfDate, 23)                          as comparisonWindowEnd,
        @CompareDaysBack                                                  as compareDaysBack,
        @AccountCount                                                     as [rowCount],
        cast(0 as bit)                                                    as truncated,
        cast(null as int)                                                 as nextCursor,
        ROUND(@TotalCurrent, 2)                                           as totalBalance,
        case when @PriorAsOfDate is null then null else ROUND(@TotalPrior, 2) end as priorTotalBalance,
        case when @PriorAsOfDate is null then null else ROUND(@TotalCurrent - @TotalPrior, 2) end as totalDelta,
        case
            when @TotalCurrent <= 0                          then ''red''
            when @TotalCurrent <= @MinBalanceThreshold       then ''yellow''
            else                                                  ''green''
        end                                                               as totalSeverity

    -- ------------------------------------------------------------------
    -- 10. Result set 3: accounts (one row per bank account)
    -- ------------------------------------------------------------------
    select
        GLAccountKey                                                      as glAccountKey,
        AccountNumber                                                     as accountNumber,
        AccountName                                                       as accountName,
        ISNULL(CurrencyID, @HomeCurrencyID)                               as currency,
        ROUND(CurrentBalance, 2)                                          as balance,
        case when @PriorAsOfDate is null then null else ROUND(PriorBalance, 2) end as priorBalance,
        case when @PriorAsOfDate is null then null else ROUND(CurrentBalance - PriorBalance, 2) end as delta,
        case
            when CurrentBalance <= 0                          then ''red''
            when CurrentBalance <= @MinBalanceThreshold       then ''yellow''
            else                                                   ''green''
        end                                                               as severity,
        case
            when CurrentBalance <= 0                          then ''overdrawn''
            when CurrentBalance <= @MinBalanceThreshold       then ''low_balance''
            else                                                   null
        end                                                               as flag
    from #BankAccounts
    order by DisplayOrder, AccountNumber

    -- ------------------------------------------------------------------
    drop table #BankAccounts
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetCorporatePL]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetCorporatePL]', 'P') IS NULL
EXEC sp_executesql N'CREATE   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.
*/

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 ''OtherIncome''
            when 4 then ''Expense''
            when 5 then ''OtherExpense''
        end                                                               as accountType,
        case raw.MinorGroup
            when 1 then ''Income''
            when 2 then ''COGS''
            when 3 then ''OtherIncome''
            when 4 then ''Expense''
            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].[spRpt1099Form]'
GO
IF OBJECT_ID(N'[dbo].[spRpt1099Form]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spRpt1099Form]
(
	@CompanyKey int,
	@MinAmount money,
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@Form smallint,						-- 1: Misc, 2: Int, 3: NEC
	@VendorKey int,						-- 0 All, > 0 valid vendor
	@GLCompanyKey INT = -1,		-- -1 All, 0 Blank or NULL, >0 valid GLCompany
	@UserKey int = NULL,
	@1099Summary int = NULL,  --Summarize 1099 data for 1096 form
	@IncludeCCPayments int = NULL, --CC Payments get reported on 1099-K by CC company
	@ShowLast4DigitsEIN int = NULL --Option to hide all but the last four digits of EIN/SSN on the report

)

AS --Encrypt

/*
|| When     Who Rel      What
|| 12/7/06  CRG 8.4      Added the @VendorKey parameter.
|| 01/29/08 GHL 8.503    (20078 + 20133) Sort by VendorID. Take >= @MinAmount 
|| 10/27/08 GHL 10.011   (34982) Added GLCompanyKey param for 1099 reporting
|| 03/17/09 MFT 10.021   (40077) Added Exclude1099
|| 11/4/09  CRG 10.5.1.3 (67238) Added DBA
|| 1/28/10  CRG 10.5.1.7 (72919) Now including the Exclude1099 calculation in the HAVING clause
|| 11/4/10  RLB 10.5.3.7 Changes made for the added 1096 report
|| 11/28/11 MFT 10.5.5.0 For electronic file format: added GLCompanyKey to output
|| 01/11/12 RLB 10.5.5.2 (131060) Changes made because GLCompany can be null or 0
|| 04/13/12 GHL 10.555  Added UserKey for UserGLCompanyAccess
|| 05/11/12 GHL 10.556 (142929) Added 1099 logic for credit cards
|| 01/09/14 GHL 10.576 (202119) Credit cards are payments
|| 03/04/14 GHL 10.578 Added conversion to home currency
|| 03/24/14 RLB 10.578 (203504) Added Exclude1099 on CC to the voucher cc calculation
|| 01/29/15 MFT 10.588 (244173) Restriced Credit Card payments to BoughtFromKey = @VendorKey so CC data will respect @VendorKey param
|| 09/30/15 MFT 10.596 (245426) Added the FATCAFilingRequirement field
|| 01/27/17 MFT 10.612 (330149) Return DBA only if UseDBAForPayment is selected
|| 11/27/18 MFT 18.9.3 (432767) Added "dba/" prefix to DBA field per IRS example
|| 09/25/20 MFT 20.110 (528335) Changed @Form enum (removed 4), added @1099Summary instead of @FormOriginal
|| 10/15/20 MFT 20.110 (506409) Removed CC payments by default
|| 01/26/20 MFT 21.010 (545666) Put in override to use Vendor''s PaymentAddressKey over DefaultAddressKey
|| 06/23/21 MFT 21.060 (538227) Added options to exclude VCard & ACH Payments
|| 09/28/23 MCM 23.010 (628804) Added #PaymentTypes so we can search by paymentTypes
|| 11/29/23 RLB 23.120 (653809) use new UseDBAForPayment1099
|| 12/11/23 MFT 24.010 (657806) Add recipient Email and IDType to support CSV submission
|| 01/19/24 MFT 24.010 (662488) Changed IDType to text values
|| 04/29/24 AMP 26.05.17 (720478) Added option to show only last 4 digits of EIN/SSN
*/

-- CREATE TABLE #PaymentTypes (PaymentType int NULL)
Declare @HasPaymentTypes int
SET @HasPaymentTypes = 0
SELECT @HasPaymentTypes = Count(*)  From #PaymentTypes

Declare @RestrictToGLCompany int

Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
	from tUser u (nolock)
	inner join tPreference p (nolock) on p.CompanyKey = ISNULL(u.OwnerCompanyKey, u.CompanyKey)
	Where u.UserKey = @UserKey

select @RestrictToGLCompany = isnull(@RestrictToGLCompany, 0)

-- Step 1: get the payments by GLCompany/Vendor
create table #tmpPayment 
	(
	PaymentKey int
	,GLCompanyKey int null
	,VendorKey int null
	,PaymentAmount money null
	,Exclude1099 money null
	,ExchangeRate decimal(24, 7) null
	,GPFlag int null
	,PaymentType varchar(25) null
	)

-- Pass 1: Get the payments againt regular vouchers

insert #tmpPayment (PaymentKey, GLCompanyKey, VendorKey, PaymentAmount, Exclude1099, ExchangeRate, GPFlag, PaymentType)
SELECT
	p.PaymentKey
	,isnull(p.GLCompanyKey, 0)
	,p.VendorKey
	,p.PaymentAmount
	,(ISNULL((
		SELECT SUM(ISNULL(Exclude1099, 0)) FROM tPaymentDetail pd (nolock) WHERE pd.PaymentKey = p.PaymentKey
	),0))
	,p.ExchangeRate
	,0
	,''Payment''
FROM
	tPayment p (nolock)
	INNER JOIN tCompany c (nolock) ON p.VendorKey = c.CompanyKey
WHERE 
	p.PaymentDate >= @StartDate 
	AND p.PaymentDate <= @EndDate 
	AND c.Type1099 = @Form
	AND p.CompanyKey = @CompanyKey
	AND (p.VendorKey = @VendorKey OR @VendorKey = 0)
	AND (
			@HasPaymentTypes = 0
			OR
			ISNULL(p.PaymentType, 1) in (SELECT PaymentType from #PaymentTypes)
		)
	AND     (-- case when @GLCompanyKey = ALL
				(@GLCompanyKey = -1 AND 
					(
					@RestrictToGLCompany = 0 OR 
					(@RestrictToGLCompany = 1 AND p.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
					)
				)
			--case when @GLCompanyKey = X or Blank(0)
			 OR (@GLCompanyKey != -1 AND ISNULL(p.GLCompanyKey, 0) = @GLCompanyKey)
			)

-- Now remove the payments against credit cards
-- there is a special process by payment detail line for credit cards
update #tmpPayment
set    #tmpPayment.GPFlag = 1
from   tPayment p (nolock)
inner  join tPaymentDetail pd (nolock) on p.PaymentKey = pd.PaymentKey
inner  join tVoucher v (nolock) on pd.VoucherKey = v.VoucherKey
where  #tmpPayment.PaymentKey = p.PaymentKey
and    isnull(v.CreditCard, 0) = 1 

delete #tmpPayment where GPFlag = 1


-- Pass 2: add the payments against credit cards if specifially requested
IF @IncludeCCPayments = 1
	insert #tmpPayment (PaymentKey, GLCompanyKey, VendorKey, PaymentAmount, Exclude1099, ExchangeRate, PaymentType)
	select ccc.VoucherKey, 
		ccc.GLCompanyKey, 
		ccc.BoughtFromKey, 
		ccc.VoucherTotal,
		(
			(
					 (select ISNULL(sum (Exclude1099), 0) from tVoucherDetail vod (nolock) where vod.VoucherKey = ccc.VoucherKey) 
					 + 
					 (select ISNULL(sum (Exclude1099), 0) from tVoucherCC vcc (nolock) where vcc.VoucherCCKey = ccc.VoucherKey)
			)
		 ),
		ccc.ExchangeRate, 
		''Credit Card''
	from   tVoucher ccc (nolock)
	INNER JOIN tCompany c (nolock) ON ccc.BoughtFromKey = c.CompanyKey
	where isnull(ccc.CreditCard, 0) = 1
		AND ccc.InvoiceDate >= @StartDate 
		AND ccc.InvoiceDate <= @EndDate 
		AND c.Type1099 = @Form
		AND ccc.CompanyKey = @CompanyKey
		AND (ccc.BoughtFromKey = @VendorKey OR @VendorKey = 0)
		AND     (-- case when @GLCompanyKey = ALL
					(@GLCompanyKey = -1 AND 
						(
						@RestrictToGLCompany = 0 OR 
						(@RestrictToGLCompany = 1 AND ccc.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (NOLOCK) WHERE UserKey = @UserKey) )
						)
					)
				--case when @GLCompanyKey = X or Blank(0)
				 OR (@GLCompanyKey != -1 AND ISNULL(ccc.GLCompanyKey, 0) = @GLCompanyKey)
				)

update #tmpPayment 
	set PaymentAmount = isnull(PaymentAmount, 0) 
		, Exclude1099 = isnull(Exclude1099, 0)
		, ExchangeRate = isnull(ExchangeRate, 1)

update #tmpPayment
set PaymentAmount = round(PaymentAmount * ExchangeRate, 2)
   ,Exclude1099 = round(Exclude1099 * ExchangeRate, 2)

-- Step 2: get the data to display

	IF @1099Summary = 1 --Form 1096 (Summary of 1099 payments)
		BEGIN
			Select 
				SUM(PaymentAmount) as FormTotal
				,COUNT(DISTINCT VendorKey) as FormCount
				,@Form as FormType
			FROM (
					SELECT
						c.CompanyKey
						,c.CompanyName
						,c.VendorID
						,p.VendorKey
						,SUM(PaymentAmount - Exclude1099) AS PaymentAmount
						,ISNULL(p.GLCompanyKey, 0) AS GLCompanyKey
					FROM
						#tmpPayment p (nolock)
						INNER JOIN tCompany c (nolock) ON p.VendorKey = c.CompanyKey
					GROUP BY
						 c.CompanyKey
						,c.CompanyName
						,c.VendorID
						,p.VendorKey
						,ISNULL(p.GLCompanyKey, 0) 
					HAVING
						SUM(PaymentAmount - Exclude1099) >= @MinAmount
				) as FormData
		END

	ELSE
		SELECT
			 c.CompanyKey
			,c.CompanyName
			,c.VendorID
			,c.Type1099
			,CASE Type1099 WHEN 3 THEN ''SSN'' ELSE ''EIN'' END AS IDType
			,CASE @ShowLast4DigitsEIN WHEN 1 THEN ''*****'' + RIGHT(EINNumber, 4) ELSE EINNumber END AS EINNumber			
			,c.Box1099
			,ad.Address1
			,ad.Address2
			,ad.Address3
			,ad.City
			,ad.State
			,ad.PostalCode
			,ad.Country
			,c.Phone
			,u.Email
			,SUM(PaymentAmount -Exclude1099) AS PaymentAmount
			,CASE UseDBAForPayment1099 WHEN 1 THEN ''dba/ '' + ISNULL(c.DBA, '''') ELSE '''' END AS DBA
			,ISNULL(p.GLCompanyKey, 0) AS GLCompanyKey
			,FATCAFilingRequirement
		FROM 
			#tmpPayment p (nolock)
			INNER JOIN tCompany c (nolock) ON p.VendorKey = c.CompanyKey
			LEFT JOIN tAddress ad (nolock) ON ISNULL(c.PaymentAddressKey, c.DefaultAddressKey) = ad.AddressKey
			LEFT JOIN tUser u (nolock) ON c.PrimaryContact = u.UserKey
		GROUP BY
			 c.CompanyKey
			,c.CompanyName
			,c.VendorID
			,c.Type1099
			,CASE Type1099 WHEN 3 THEN 2 ELSE 1 END
			,CASE @ShowLast4DigitsEIN WHEN 1 THEN ''*****'' + RIGHT(EINNumber, 4) ELSE EINNumber END
			,c.StateEINNumber
			,c.Box1099
			,ad.Address1
			,ad.Address2
			,ad.Address3
			,ad.City
			,ad.State
			,ad.PostalCode
			,ad.Country
			,c.Phone
			,u.Email
			,CASE UseDBAForPayment1099 WHEN 1 THEN ''dba/ '' + ISNULL(c.DBA, '''') ELSE '''' END
			,ISNULL(p.GLCompanyKey, 0)
			,FATCAFilingRequirement
		HAVING
			SUM(PaymentAmount - Exclude1099) >= @MinAmount
		ORDER BY
			VendorID'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetCashForecast]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetCashForecast]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetCashForecast]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,         -- defaults today UTC
    @GLCompanyID        varchar(50) = null,
    @HorizonDays        int         = 90,
    @WindowDays         varchar(50) = ''30,60,90'',   -- comma-separated cumulative windows
    @DelayReceiptsBy    int         = null,         -- days to push AR receipt date past DueDate; null = derive from history
    @LagHistoryMonths   int         = 6,            -- months back to learn the global average lag
    @KnownObligations   nvarchar(max) = null,       -- JSON array: [{"date":"YYYY-MM-DD","amount":N,"description":"..."}]
    @ConfidenceBandPct  decimal(9,4) = 15.0,        -- band width as % of expected inflows
    @PostStatus         tinyint     = 1,            -- 1 = posted only (matches GL); 0 = include unposted
    @CurrencyID         varchar(10) = null
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — 30/60/90 forward cash forecast.
||                          Modeled on spRptCashProjection''s AR/AP/bank predicates but produces
||                          a per-window summary (vs. day/week/month bands), confidence bands,
||                          and a named-risk list. Caller-supplied knownObligations (payroll,
||                          rent, etc.) are folded into outflows as JSON-in.
||                          v1 lag model: single global offset (caller-supplied or derived
||                          from history). Per-customer lag is a future enhancement.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @MultiCurrency        tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @EffectiveCurrencyID  varchar(10)
    declare @CanRunForecast       bit
    declare @ErrorCount           int
    declare @GLCompanyKeyResolved int

    declare @StartingCash         money
    declare @MaxWindowEnd         datetime
    declare @AvgLagDays           int

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())
    if @HorizonDays is null or @HorizonDays <= 0
        set @HorizonDays = 90
    if @ConfidenceBandPct is null or @ConfidenceBandPct < 0
        set @ConfidenceBandPct = 15.0

    set @MaxWindowEnd = dateadd(day, @HorizonDays, @AsOfDate)

    -- ------------------------------------------------------------------
    -- 1. Errors staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Load caller 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
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Right check (admin bypass) — same as cash position / projection
    -- ------------------------------------------------------------------
    set @CanRunForecast = 0
    if @IsAdministrator = 1
        set @CanRunForecast = 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 (''acct_gl_cashprojection'', ''acct_gl_balsheet'', ''acct_gl_trailbal'')
    )
        set @CanRunForecast = 1

    if @CanRunForecast = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view cash projections.'', ''general'')

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

    -- ------------------------------------------------------------------
    -- 4. 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)
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 5. Resolve GL company filter
    -- ------------------------------------------------------------------
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 6. Parse @WindowDays into a list (1, 7, 14, 30, 60, 90 etc.)
    -- ------------------------------------------------------------------
    create table #Windows (
        windowDays int       null,
        windowEnd  datetime  null
    )

    insert into #Windows (windowDays, windowEnd)
    select cast(LTRIM(RTRIM(value)) as int),
           dateadd(day, cast(LTRIM(RTRIM(value)) as int), @AsOfDate)
    from dbo.fSplitVals(@WindowDays, '','')
    where ISNULL(LTRIM(RTRIM(value)), '''') <> ''''
      and cast(LTRIM(RTRIM(value)) as int) > 0
      and cast(LTRIM(RTRIM(value)) as int) <= @HorizonDays

    if not exists (select 1 from #Windows)
    begin
        insert into #Windows (windowDays, windowEnd) values (30, dateadd(day, 30, @AsOfDate))
        insert into #Windows (windowDays, windowEnd) values (60, dateadd(day, 60, @AsOfDate))
        insert into #Windows (windowDays, windowEnd) values (90, dateadd(day, 90, @AsOfDate))
    end

    -- ------------------------------------------------------------------
    -- 7. Starting cash = sum of all bank accounts (AccountType=10) at @AsOfDate
    --    Same convention as sptGLAccountGetBalance.
    -- ------------------------------------------------------------------
    select @StartingCash = ISNULL(SUM(ISNULL(t.Debit, 0) - ISNULL(t.Credit, 0)), 0)
    from tTransaction t (nolock)
    inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
                                     and gl.CompanyKey  = @CompanyKey
                                     and gl.AccountType = 10
                                     and gl.Active      = 1
    where t.CompanyKey      = @CompanyKey
      and t.TransactionDate <= @AsOfDate
      and (@GLCompanyKeyResolved is null or t.GLCompanyKey = @GLCompanyKeyResolved)
      and (
          @IsAdministrator = 1 or @RestrictToGLCompany = 0
          or t.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
      )

    -- ------------------------------------------------------------------
    -- 8. Derive global average payment lag from history if not supplied
    --    Lag = (CheckDate − DueDate of fully-applied invoices) averaged over @LagHistoryMonths.
    --    Approximation: average across paid invoices using AmountReceived as the signal.
    -- ------------------------------------------------------------------
    if @DelayReceiptsBy is null
    begin
        declare @LagStart datetime = dateadd(month, -ISNULL(@LagHistoryMonths, 6), @AsOfDate)

        ;with paid as (
            select i.InvoiceKey,
                   i.DueDate,
                   ch.CheckDate
            from tInvoice i (nolock)
            inner join tBillingPayment bp (nolock) on bp.Entity = ''tInvoice'' and bp.EntityKey = i.InvoiceKey
            inner join tCheck ch (nolock) on bp.BillingKey = ch.CheckKey
            where i.CompanyKey  = @CompanyKey
              and ch.CheckDate >= @LagStart
              and ch.CheckDate <= @AsOfDate
              and i.DueDate is not null
        )
        select @AvgLagDays = ISNULL(AVG(DATEDIFF(day, DueDate, CheckDate)), 0)
        from paid

        -- Clamp the derived lag to a sane range; if no history, fall back to 0
        if @AvgLagDays is null   set @AvgLagDays = 0
        if @AvgLagDays < -30     set @AvgLagDays = 0
        if @AvgLagDays > 90      set @AvgLagDays = 90

        set @DelayReceiptsBy = @AvgLagDays
    end
    else
        set @AvgLagDays = @DelayReceiptsBy

    -- ------------------------------------------------------------------
    -- 9. Expected inflows = open invoices with (DueDate + lag) within horizon
    -- ------------------------------------------------------------------
    create table #Inflows (
        InvoiceKey       int            null,
        ClientKey        int            null,
        ClientName       nvarchar(500)  null,
        InvoiceNumber    varchar(35)    null,
        DueDate          smalldatetime  null,
        ExpectedDate     smalldatetime  null,
        OpenAmount       money          null
    )

    insert into #Inflows (InvoiceKey, ClientKey, ClientName, InvoiceNumber, DueDate, ExpectedDate, OpenAmount)
    select
        i.InvoiceKey,
        i.ClientKey,
        c.CompanyName,
        i.InvoiceNumber,
        i.DueDate,
        dateadd(day, @DelayReceiptsBy, i.DueDate),
        i.InvoiceTotalAmount
            - ISNULL(i.DiscountAmount, 0)
            - ISNULL(i.AmountReceived, 0)
            - ISNULL(i.RetainerAmount, 0)
            - ISNULL(i.WriteoffAmount, 0)
    from tInvoice i (nolock)
    left join tCompany c (nolock) on i.ClientKey = c.CompanyKey
    where i.CompanyKey         = @CompanyKey
      and i.InvoiceStatus      = 4
      and i.Posted >= @PostStatus
      and i.InvoiceTotalAmount > 0                                           -- exclude credits (handled separately below)
      and dateadd(day, @DelayReceiptsBy, i.DueDate) <= @MaxWindowEnd
      and (i.InvoiceTotalAmount
            - ISNULL(i.DiscountAmount, 0)
            - ISNULL(i.AmountReceived, 0)
            - ISNULL(i.RetainerAmount, 0)
            - ISNULL(i.WriteoffAmount, 0)) > 0
      and (@GLCompanyKeyResolved is null or i.GLCompanyKey = @GLCompanyKeyResolved)
      and (@CurrencyID is null or ISNULL(i.CurrencyID, '''') = @CurrencyID)
      and (
          @IsAdministrator = 1 or @RestrictToGLCompany = 0
          or ISNULL(i.GLCompanyKey, 0) in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
      )

    -- ------------------------------------------------------------------
    -- 10. Expected outflows = open vouchers due in horizon
    -- ------------------------------------------------------------------
    create table #Outflows (
        Source           varchar(20)    null,      -- ''voucher'' | ''obligation''
        VoucherKey       int            null,
        VendorKey        int            null,
        VendorName       nvarchar(500)  null,
        DueDate          smalldatetime  null,
        OpenAmount       money          null,
        Description      nvarchar(500)  null
    )

    insert into #Outflows (Source, VoucherKey, VendorKey, VendorName, DueDate, OpenAmount, Description)
    select
        ''voucher'',
        v.VoucherKey,
        v.VendorKey,
        c.CompanyName,
        v.DueDate,
        v.VoucherTotal - ISNULL(v.AmountPaid, 0),
        case when v.VoucherID is not null then ''Voucher #'' + cast(v.VoucherID as varchar(20)) else ''Voucher '' + cast(v.VoucherKey as varchar(20)) end
    from tVoucher v (nolock)
    left join tCompany c (nolock) on v.VendorKey = c.CompanyKey
    where v.CompanyKey          = @CompanyKey
      and v.VoucherTotal  > 0
      and v.Posted >= @PostStatus
      and v.DueDate            <= @MaxWindowEnd
      and (v.VoucherTotal - ISNULL(v.AmountPaid, 0)) > 0
      and (@GLCompanyKeyResolved is null or v.GLCompanyKey = @GLCompanyKeyResolved)
      and (@CurrencyID is null or ISNULL(v.CurrencyID, '''') = @CurrencyID)
      and (
          @IsAdministrator = 1 or @RestrictToGLCompany = 0
          or ISNULL(v.GLCompanyKey, 0) in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
      )

    -- ------------------------------------------------------------------
    -- 11. Layer in caller-supplied known obligations (payroll, rent, etc.)
    --     JSON: [{"date":"YYYY-MM-DD","amount":N,"description":"..."}]
    -- ------------------------------------------------------------------
    if @KnownObligations is not null and LTRIM(RTRIM(@KnownObligations)) <> ''''
    begin
        begin try
            insert into #Outflows (Source, DueDate, OpenAmount, Description)
            select
                ''obligation'',
                try_cast(JSON_VALUE(o.value, ''$.date'')        as datetime),
                try_cast(JSON_VALUE(o.value, ''$.amount'')      as money),
                cast(JSON_VALUE(o.value, ''$.description'')     as nvarchar(500))
            from OPENJSON(@KnownObligations) o
            where try_cast(JSON_VALUE(o.value, ''$.date'')   as datetime) is not null
              and try_cast(JSON_VALUE(o.value, ''$.amount'') as money)    is not null
              and try_cast(JSON_VALUE(o.value, ''$.date'')   as datetime) <= @MaxWindowEnd
              and try_cast(JSON_VALUE(o.value, ''$.amount'') as money)     > 0
        end try
        begin catch
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''INVALID_VALUE'', ''knownObligations JSON could not be parsed — ignored.'', ''knownObligations'')
        end catch
    end

    -- ------------------------------------------------------------------
    -- 12. Per-window aggregates
    -- ------------------------------------------------------------------
    create table #WindowAgg (
        windowDays           int            null,
        windowEnd            datetime       null,
        expectedInflows      money          null,
        expectedOutflows     money          null,
        knownObligations     money          null,
        netChange            money          null,
        endingCash           money          null,
        endingCashLow        money          null,
        endingCashHigh       money          null,
        inflowCount          int            null,
        outflowCount         int            null,
        knownObligCount      int            null,
        severity             varchar(10)    null,
        flag                 varchar(20)    null
    )

    insert into #WindowAgg (windowDays, windowEnd, expectedInflows, expectedOutflows, knownObligations,
                            inflowCount, outflowCount, knownObligCount)
    select
        w.windowDays,
        w.windowEnd,
        ISNULL((select SUM(OpenAmount) from #Inflows  where ExpectedDate <= w.windowEnd), 0),
        ISNULL((select SUM(OpenAmount) from #Outflows where DueDate     <= w.windowEnd and Source = ''voucher''), 0),
        ISNULL((select SUM(OpenAmount) from #Outflows where DueDate     <= w.windowEnd and Source = ''obligation''), 0),
        ISNULL((select COUNT(*)        from #Inflows  where ExpectedDate <= w.windowEnd), 0),
        ISNULL((select COUNT(*)        from #Outflows where DueDate     <= w.windowEnd and Source = ''voucher''), 0),
        ISNULL((select COUNT(*)        from #Outflows where DueDate     <= w.windowEnd and Source = ''obligation''), 0)
    from #Windows w

    update #WindowAgg
    set netChange      = expectedInflows - expectedOutflows - knownObligations,
        endingCash     = @StartingCash + (expectedInflows - expectedOutflows - knownObligations),
        endingCashLow  = @StartingCash + (expectedInflows - expectedOutflows - knownObligations)
                         - (expectedInflows * @ConfidenceBandPct / 100.0),
        endingCashHigh = @StartingCash + (expectedInflows - expectedOutflows - knownObligations)
                         + (expectedInflows * @ConfidenceBandPct / 100.0)

    update #WindowAgg
    set flag =
            case
                when endingCashLow < 0                                            then ''negative_cash''
                when @StartingCash > 0 AND endingCashLow < @StartingCash * 0.25   then ''payroll_risk''
                when endingCash < @StartingCash * 0.5                             then ''tight''
                else                                                                   ''healthy''
            end,
        severity =
            case
                when endingCashLow < 0                                            then ''red''
                when @StartingCash > 0 AND endingCashLow < @StartingCash * 0.25   then ''red''
                when endingCash < @StartingCash * 0.5                             then ''yellow''
                else                                                                   ''green''
            end

    -- ------------------------------------------------------------------
    -- 13. Build top-N risks list
    --     Up to 8 entries surfaced as the "things to act on" list:
    --       - any window with negative_cash / payroll_risk severity
    --       - top 3 outflows by amount
    --       - top 3 inflows by amount (chase candidates)
    -- ------------------------------------------------------------------
    create table #Risks (
        riskType         varchar(40)    null,
        windowDays       int            null,
        counterpartyName nvarchar(500)  null,
        amount           money          null,
        description      nvarchar(500)  null,
        severity         varchar(10)    null,
        ord              int            null
    )

    insert into #Risks (riskType, windowDays, counterpartyName, amount, description, severity, ord)
    select
        flag,
        windowDays,
        null,
        ROUND(@StartingCash + netChange, 2),
        case flag
            when ''negative_cash'' then cast(windowDays as varchar(10)) + ''-day projection runs negative — low band $'' + cast(cast(endingCashLow as int) as varchar(20))
            when ''payroll_risk''  then cast(windowDays as varchar(10)) + ''-day cash drops below 25% of today (low band $'' + cast(cast(endingCashLow as int) as varchar(20)) + '')''
            else null
        end,
        severity,
        1
    from #WindowAgg
    where flag in (''negative_cash'', ''payroll_risk'')

    -- Top 3 expected outflows by amount
    insert into #Risks (riskType, windowDays, counterpartyName, amount, description, severity, ord)
    select top 3
        case when Source = ''obligation'' then ''known_obligation'' else ''large_payable'' end,
        DATEDIFF(day, @AsOfDate, DueDate),
        VendorName,
        ROUND(OpenAmount, 2),
        case when Source = ''obligation''
             then Description + '' lands '' + convert(varchar(10), DueDate, 23) + '' — $'' + cast(cast(OpenAmount as int) as varchar(20))
             else ISNULL(VendorName, ''Vendor'') + '' — '' + Description + '' due '' + convert(varchar(10), DueDate, 23) + '' ($'' + cast(cast(OpenAmount as int) as varchar(20)) + '')''
        end,
        case when OpenAmount > @StartingCash * 0.2 then ''red'' else ''yellow'' end,
        2
    from #Outflows
    order by OpenAmount desc

    -- Top 3 expected inflows by amount (chase candidates)
    insert into #Risks (riskType, windowDays, counterpartyName, amount, description, severity, ord)
    select top 3
        ''large_receivable'',
        DATEDIFF(day, @AsOfDate, ExpectedDate),
        ClientName,
        ROUND(OpenAmount, 2),
        ISNULL(ClientName, ''Client'') + '' invoice '' + ISNULL(InvoiceNumber, ''#'') + '' expected '' + convert(varchar(10), ExpectedDate, 23) + '' ($'' + cast(cast(OpenAmount as int) as varchar(20)) + '')'',
        ''green'',
        3
    from #Inflows
    order by OpenAmount desc

    -- ------------------------------------------------------------------
    -- 14. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 15. Result set 2: meta
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate, 126) + ''Z''                        as asOf,
        @CompanyKey                                                       as companyKey,
        ISNULL(@EffectiveCurrencyID, '''')                                  as currency,
        ROUND(@StartingCash, 2)                                           as startingCash,
        @HorizonDays                                                      as horizonDays,
        convert(varchar(10), @MaxWindowEnd, 23)                           as horizonEnd,
        @DelayReceiptsBy                                                  as lagAppliedDays,
        @AvgLagDays                                                       as derivedLagDays,
        @LagHistoryMonths                                                 as lagHistoryMonths,
        @ConfidenceBandPct                                                as confidenceBandPct,
        (select COUNT(*) from #Inflows)                                   as totalInflowCount,
        (select COUNT(*) from #Outflows where Source = ''voucher'')         as totalVoucherCount,
        (select COUNT(*) from #Outflows where Source = ''obligation'')      as totalObligationCount

    -- ------------------------------------------------------------------
    -- 16. Result set 3: windows
    -- ------------------------------------------------------------------
    select
        windowDays                                          as windowDays,
        convert(varchar(10), windowEnd, 23)                 as windowEnd,
        ROUND(@StartingCash,    2)                          as startingCash,
        ROUND(expectedInflows,  2)                          as expectedInflows,
        ROUND(expectedOutflows, 2)                          as expectedOutflows,
        ROUND(knownObligations, 2)                          as knownObligations,
        ROUND(netChange,        2)                          as netChange,
        ROUND(endingCash,       2)                          as endingCash,
        ROUND(endingCashLow,    2)                          as endingCashLow,
        ROUND(endingCashHigh,   2)                          as endingCashHigh,
        inflowCount                                         as inflowCount,
        outflowCount                                        as outflowCount,
        knownObligCount                                     as knownObligationsCount,
        flag                                                as flag,
        severity                                            as severity
    from #WindowAgg
    order by windowDays

    -- ------------------------------------------------------------------
    -- 17. Result set 4: risks (top items by impact)
    -- ------------------------------------------------------------------
    select top 8
        riskType                                            as riskType,
        windowDays                                          as windowDays,
        counterpartyName                                    as counterpartyName,
        ROUND(amount, 2)                                    as amount,
        description                                         as description,
        severity                                            as severity
    from #Risks
    order by
        case severity when ''red'' then 1 when ''yellow'' then 2 else 3 end,
        ord,
        amount desc

    -- ------------------------------------------------------------------
    drop table #Risks
    drop table #WindowAgg
    drop table #Outflows
    drop table #Inflows
    drop table #Windows
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetRevenueByItem]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetRevenueByItem]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetRevenueByItem]
(
    @CompanyKey         int,
    @UserKey            int,
    @StartDate          datetime    = null,
    @EndDate            datetime    = null,
    @PriorStartDate     datetime    = null,
    @PriorEndDate       datetime    = null,
    @AsOfDate           datetime    = null,
    @TrailingMonths     int         = 3,
    @IncludeComparison  bit         = 1,
    @ClientID           varchar(75) = null,
    @ProjectID          varchar(50) = null,
    @GLCompanyID        varchar(50) = null,
    @ItemType           varchar(20) = null,        -- ''LABOR'' | ''EXPRPT'' | ''MEDIA'' | ''VOUCHER'' | ''OPENORDER''
    @TopN               int         = 50,
    @MinRevenue         money       = null,
    @CurrencyID         varchar(10) = null
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — billed-revenue rollup by service / item over a trailing window.
||                          Source: vProjectTransPO (unifies labor + expense + media + voucher + open-order
||                          billable activity). Filter is DateBilled in window. Rows with
||                          InvoiceLineKey > 0 are on real invoices; InvoiceLineKey = 0 are fixed-fee
||                          "marked billed" rows — both are summed into revenue.
||                          Revenue GL account is resolved per Type: tService.GLAccountKey for LABOR,
||                          tItem.SalesAccountKey for everything else.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @MultiCurrency        tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @EffectiveCurrencyID  varchar(10)
    declare @CanReadRevenue       bit
    declare @ErrorCount           int

    declare @ClientKey            int
    declare @ProjectKey           int
    declare @GLCompanyKeyResolved int

    declare @TotalRevenue         money
    declare @PriorTotalRevenue    money
    declare @ItemCount            int

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())
    if @TrailingMonths is null or @TrailingMonths <= 0
        set @TrailingMonths = 3
    if @EndDate   is null set @EndDate   = @AsOfDate
    if @StartDate is null set @StartDate = dateadd(month, -@TrailingMonths, @EndDate)

    if @IncludeComparison = 1 and @PriorStartDate is null and @PriorEndDate is null
    begin
        set @PriorEndDate   = dateadd(day, -1, @StartDate)
        set @PriorStartDate = dateadd(month, -@TrailingMonths, @PriorEndDate)
    end

    if @TopN is null or @TopN <= 0 set @TopN = 50

    -- ------------------------------------------------------------------
    -- 1. Errors staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Load caller 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
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Right check: any revenue-related right (admin bypass)
    -- ------------------------------------------------------------------
    set @CanReadRevenue = 0
    if @IsAdministrator = 1
        set @CanReadRevenue = 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 (
              ''acct_ar_invoicesummary'',
              ''acct_ar_invoicelineitemsummary'',
              ''acct_ar_salesjournal'',
              ''acct_ar_aging'',
              ''acct_client_gl_pl_ytd''
          )
    )
        set @CanReadRevenue = 1

    if @CanReadRevenue = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view revenue data.'', ''general'')

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

    -- ------------------------------------------------------------------
    -- 4. Validate dates
    -- ------------------------------------------------------------------
    if @EndDate < @StartDate
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''endDate must be on or after startDate.'', ''endDate'')

    if (@PriorStartDate is null and @PriorEndDate is not null)
        or (@PriorStartDate is not null and @PriorEndDate is null)
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''priorStartDate and priorEndDate must be supplied together.'', ''priorStartDate'')

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

    -- ------------------------------------------------------------------
    -- 5. 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)
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 6. Resolve string IDs
    -- ------------------------------------------------------------------
    if @ClientID is not null and LTRIM(RTRIM(@ClientID)) <> ''''
    begin
        select @ClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(CustomerID) = UPPER(@ClientID) or UPPER(CompanyName) = UPPER(@ClientID))

        if @ClientKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Client not found: '' + @ClientID + '' — filter ignored.'', ''clientID'')
    end

    if @ProjectID is not null and LTRIM(RTRIM(@ProjectID)) <> ''''
    begin
        select @ProjectKey = ProjectKey
        from tProject (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(ProjectNumber) = UPPER(@ProjectID)

        if @ProjectKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Project not found: '' + @ProjectID + '' — filter ignored.'', ''projectID'')
    end

    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 7. Pull billed rows from vProjectTransPO into staging
    --    Filter: DateBilled in current OR prior window; InvoiceLineKey not null
    --    (InvoiceLineKey = 0 means fixed-fee marked billed — include).
    --    Multi-tenancy through tProject.ClientKey when ClientID filter is set.
    -- ------------------------------------------------------------------
    create table #Raw (
        ItemType         varchar(20)    null,
        ItemKey          int            null,
        ItemID           varchar(100)   null,
        ItemName         nvarchar(500)  null,
        ProjectKey       int            null,
        ClientKey        int            null,
        AmountBilled     money          null,
        DateBilled       datetime       null,
        InvoiceLineKey   int            null,
        CurrencyID       varchar(10)    null,
        GLCompanyKey     int            null
    )

    insert into #Raw (
        ItemType, ItemKey, ItemID, ItemName,
        ProjectKey, ClientKey,
        AmountBilled, DateBilled, InvoiceLineKey,
        CurrencyID, GLCompanyKey
    )
    select
        v.Type,
        v.ItemKey,
        v.ItemID,
        v.ItemName,
        v.ProjectKey,
        p.ClientKey,
        ISNULL(v.AmountBilled, 0),
        v.DateBilled,
        v.InvoiceLineKey,
        v.CurrencyID,
        v.GLCompanyKey
    from vProjectTransPO v
    left join tProject p (nolock) on v.ProjectKey = p.ProjectKey
    where v.CompanyKey       = @CompanyKey
      and v.InvoiceLineKey   is not null
      and v.DateBilled       is not null
      and ISNULL(v.AmountBilled, 0) <> 0
      and (
            (v.DateBilled between @StartDate      and @EndDate)
         or (@PriorStartDate is not null
             and v.DateBilled between @PriorStartDate and @PriorEndDate)
      )
      and (@ItemType            is null or v.Type         = @ItemType)
      and (@ClientKey           is null or p.ClientKey    = @ClientKey)
      and (@ProjectKey          is null or v.ProjectKey   = @ProjectKey)
      and (@GLCompanyKeyResolved is null or v.GLCompanyKey = @GLCompanyKeyResolved)
      and (@CurrencyID          is null or ISNULL(v.CurrencyID, '''') = @CurrencyID)
      and (
            @IsAdministrator = 1
            or @RestrictToGLCompany = 0
            or ISNULL(v.GLCompanyKey, 0) in (
                select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey
            )
      )

    -- ------------------------------------------------------------------
    -- 8. Aggregate per (ItemType, ItemKey) — resolve revenue GL account
    -- ------------------------------------------------------------------
    create table #Items (
        ItemType              varchar(20)    null,
        ItemKey               int            null,
        ItemID                varchar(100)   null,
        ItemName              nvarchar(500)  null,
        RevenueAccountKey     int            null,
        RevenueAccountNumber  varchar(100)   null,
        RevenueAccountName    nvarchar(200)  null,
        Revenue               money          null,
        PriorRevenue          money          null,
        TransactionCount      int            null,
        ProjectCount          int            null,
        ClientCount           int            null,
        InvoicedCount         int            null,    -- InvoiceLineKey > 0
        FixedFeeCount         int            null,    -- InvoiceLineKey = 0
        MixedCurrency         tinyint        null,
        Currency              varchar(10)    null
    )

    ;with grp as (
        select
            ItemType,
            ItemKey,
            MAX(ItemID)                                                        as ItemID,
            MAX(ItemName)                                                      as ItemName,
            SUM(case when DateBilled between @StartDate and @EndDate then AmountBilled else 0 end)              as Revenue,
            SUM(case when @PriorStartDate is not null
                      and DateBilled between @PriorStartDate and @PriorEndDate then AmountBilled else 0 end)    as PriorRevenue,
            COUNT(*)                                                           as TransactionCount,
            COUNT(distinct ProjectKey)                                         as ProjectCount,
            COUNT(distinct ClientKey)                                          as ClientCount,
            SUM(case when InvoiceLineKey > 0 then 1 else 0 end)                as InvoicedCount,
            SUM(case when InvoiceLineKey = 0 then 1 else 0 end)                as FixedFeeCount,
            case when COUNT(distinct ISNULL(CurrencyID, '''')) > 1 then 1 else 0 end                              as MixedCurrency,
            case when COUNT(distinct ISNULL(CurrencyID, '''')) = 1 then MAX(ISNULL(CurrencyID, '''')) else null end as Currency
        from #Raw
        where ItemKey is not null
        group by ItemType, ItemKey
    )
    insert into #Items
    select
        g.ItemType, g.ItemKey, g.ItemID, g.ItemName,
        ra.GLAccountKey,
        ra.AccountNumber,
        ra.AccountName,
        ROUND(g.Revenue,      2),
        ROUND(g.PriorRevenue, 2),
        g.TransactionCount, g.ProjectCount, g.ClientCount,
        g.InvoicedCount, g.FixedFeeCount,
        g.MixedCurrency, g.Currency
    from grp g
    left join tService   s  (nolock) on g.ItemType  = ''LABOR''  and g.ItemKey = s.ServiceKey
    left join tItem      i  (nolock) on g.ItemType <> ''LABOR''  and g.ItemKey = i.ItemKey
    left join tGLAccount ra (nolock) on COALESCE(s.GLAccountKey, i.SalesAccountKey) = ra.GLAccountKey
                                    and ra.CompanyKey = @CompanyKey

    -- Drop rows with zero current + zero prior (defensive)
    delete from #Items where ISNULL(Revenue, 0) = 0 and ISNULL(PriorRevenue, 0) = 0

    -- minRevenue filter applies to current-window revenue
    if @MinRevenue is not null
        delete from #Items where ISNULL(Revenue, 0) < @MinRevenue

    -- Mixed-currency warning
    if exists (select 1 from #Items where MixedCurrency = 1)
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''warning'', ''MIXED_CURRENCY'',
                ''One or more items have transactions in multiple currencies. Totals are native-summed without FX conversion.'',
                ''currencyID'')

    -- ------------------------------------------------------------------
    -- 9. Totals + median for "slow_mover" detection
    -- ------------------------------------------------------------------
    select @TotalRevenue      = ISNULL(SUM(Revenue),      0),
           @PriorTotalRevenue = ISNULL(SUM(PriorRevenue), 0),
           @ItemCount         = COUNT(*)
    from #Items
    where Revenue > 0

    -- ------------------------------------------------------------------
    -- 10. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType, errorCode, errorMessage, fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 11. Result set 2: meta
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate,       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,
        @TrailingMonths                                                   as trailingMonths,
        ROUND(@TotalRevenue,      2)                                      as totalRevenue,
        case when @PriorStartDate is null then null else ROUND(@PriorTotalRevenue, 2) end                       as priorTotalRevenue,
        case when @PriorStartDate is null then null else ROUND(@TotalRevenue - @PriorTotalRevenue, 2) end       as totalRevenueDelta,
        @ItemCount                                                        as itemCount,
        cast(0 as bit)                                                    as truncated,
        cast(null as int)                                                 as nextCursor

    -- ------------------------------------------------------------------
    -- 12. Result set 3: items (ranked, top N)
    --     severity / flag (first match wins):
    --       ''top_seller''  green  — rank in top 3 by revenue
    --       ''growing''     green  — comparison enabled AND revenueDelta > +20%
    --       ''declining''   yellow — comparison enabled AND revenueDelta < -15%
    --       ''slow_mover''  yellow — percentOfTotal < 1% AND in bottom quartile by rank
    --       null          green  — otherwise
    -- ------------------------------------------------------------------
    ;with ranked as (
        select
            ROW_NUMBER() over (order by Revenue desc, ItemName) as rn,
            COUNT(*) over ()                                    as totalRanked,
            ItemType, ItemKey, ItemID, ItemName,
            RevenueAccountKey, RevenueAccountNumber, RevenueAccountName,
            Revenue, PriorRevenue,
            TransactionCount, ProjectCount, ClientCount,
            InvoicedCount, FixedFeeCount,
            MixedCurrency, Currency,
            case when @TotalRevenue      > 0 then 100.0 * Revenue      / @TotalRevenue      else 0 end as PercentOfTotal,
            case when @PriorTotalRevenue > 0 then 100.0 * PriorRevenue / @PriorTotalRevenue else 0 end as PriorPercentOfTotal
        from #Items
        where Revenue > 0
    )
    select
        rn                                                                  as rank,
        ItemType                                                            as itemType,
        ItemKey                                                             as itemKey,
        ItemID                                                              as itemID,
        ItemName                                                            as itemName,
        RevenueAccountKey                                                   as revenueAccountKey,
        RevenueAccountNumber                                                as revenueAccountNumber,
        RevenueAccountName                                                  as revenueAccountName,
        ROUND(Revenue, 2)                                                   as revenue,
        case when @PriorStartDate is null then null else ROUND(PriorRevenue, 2) end                              as priorRevenue,
        case when @PriorStartDate is null then null else ROUND(Revenue - PriorRevenue, 2) end                    as revenueDelta,
        ROUND(PercentOfTotal, 2)                                            as percentOfTotal,
        case when @PriorStartDate is null then null else ROUND(PriorPercentOfTotal, 2) end                       as priorPercentOfTotal,
        case when @PriorStartDate is null then null else ROUND(PercentOfTotal - PriorPercentOfTotal, 2) end      as percentDelta,
        TransactionCount                                                    as transactionCount,
        ProjectCount                                                        as projectCount,
        ClientCount                                                         as clientCount,
        InvoicedCount                                                       as invoicedCount,
        FixedFeeCount                                                       as fixedFeeCount,
        case when MixedCurrency = 1 then null else Currency end             as currency,
        cast(MixedCurrency as bit)                                          as mixedCurrency,
        case
            when rn <= 3                                                          then ''top_seller''
            when @PriorStartDate is not null AND PriorRevenue > 0
                 AND (Revenue - PriorRevenue) / NULLIF(PriorRevenue, 0) >  0.20   then ''growing''
            when @PriorStartDate is not null AND PriorRevenue > 0
                 AND (Revenue - PriorRevenue) / NULLIF(PriorRevenue, 0) < -0.15   then ''declining''
            when PercentOfTotal < 1.0
                 AND rn > (totalRanked * 3 / 4)                                   then ''slow_mover''
            else null
        end                                                                 as flag,
        case
            when rn <= 3                                                          then ''green''
            when @PriorStartDate is not null AND PriorRevenue > 0
                 AND (Revenue - PriorRevenue) / NULLIF(PriorRevenue, 0) >  0.20   then ''green''
            when @PriorStartDate is not null AND PriorRevenue > 0
                 AND (Revenue - PriorRevenue) / NULLIF(PriorRevenue, 0) < -0.15   then ''yellow''
            when PercentOfTotal < 1.0
                 AND rn > (totalRanked * 3 / 4)                                   then ''yellow''
            else ''green''
        end                                                                 as severity
    from ranked
    where rn <= @TopN
    order by rn

    -- ------------------------------------------------------------------
    drop table #Items
    drop table #Raw
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetVendorPayments]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetVendorPayments]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetVendorPayments]
(
    @CompanyKey            int,
    @UserKey               int,
    @StartDate             datetime    = null,         -- defaults to Jan 1 of @AsOfDate''s year
    @EndDate               datetime    = null,         -- defaults to @AsOfDate
    @AsOfDate              datetime    = null,         -- defaults today; used for default window only
    @VendorID              varchar(50) = null,         -- tCompany.VendorID (single)
    @GLCompanyID           varchar(50) = null,
    @ContractorsOnly       bit         = 0,            -- 1 = only 1099-eligible payees (Type1099 <> 0)
    @AboveThresholdOnly    bit         = 0,            -- 1 = only payees with totalPaid >= @ThresholdAmount
    @ThresholdAmount       money       = 600.00,       -- IRS 1099 default
    @NearThresholdAmount   money       = 400.00,       -- "watch list" lower bound — 400-599 territory
    @PostedOnly            bit         = 1,            -- 1 = posted payments only
    @MaxRows               int         = 250,
    @Cursor                int         = 0
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — YTD vendor payment summary.
||                          Source: tPayment (AP cash disbursements). Includes employee expense
||                          reimbursements when those flow through tPayment (the standard path —
||                          envelope -> voucher -> payment).
||                          @ContractorsOnly narrows to 1099-eligible payees (tCompany.Type1099 <> 0)
||                          for tax-prep workflows. With the flag off, returns every payee paid in
||                          the window — useful for AP audit, cash-out summaries, and concentration
||                          analysis on the AP side.
||                          Voided payments are excluded by the standard pattern: VoidPaymentKey = 0
||                          OR the voiding entry posts after @EndDate (the original was valid during
||                          the window).
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @MultiCurrency        tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @EffectiveCurrencyID  varchar(10)
    declare @CanReadAP            bit
    declare @ErrorCount           int

    declare @VendorKey            int
    declare @GLCompanyKeyResolved int

    declare @RowCount             int
    declare @Truncated            tinyint
    declare @NextCursor           int
    declare @TotalPaid            money

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())
    if @EndDate is null
        set @EndDate = @AsOfDate
    if @StartDate is null
        -- Default: calendar YTD (1099s are calendar-year reporting regardless of fiscal year).
        set @StartDate = cast(cast(year(@AsOfDate) as varchar(4)) + ''-01-01'' as datetime)

    if @MaxRows is null or @MaxRows <= 0 set @MaxRows = 250
    if @Cursor  is null or @Cursor  <  0 set @Cursor  = 0

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Validate dates
    -- ------------------------------------------------------------------
    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 @NearThresholdAmount > @ThresholdAmount
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''nearThresholdAmount must be <= thresholdAmount.'', ''nearThresholdAmount'')
    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 (admin bypass): any AP-payments-related right
    -- ------------------------------------------------------------------
    set @CanReadAP = 0
    if @IsAdministrator = 1
        set @CanReadAP = 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 (
              ''acct_ap_payjournal'',     -- Cash Disbursements Journal
              ''acct_ap_listing'',         -- AP Listing
              ''acct_ap_aging'',           -- AP Account Aging
              ''acct_gl_trailbal''         -- Trial Balance covers vendor payments too
          )
    )
        set @CanReadAP = 1

    if @CanReadAP = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view vendor payment data.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 5. Bail on date validation
    -- ------------------------------------------------------------------
    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. Resolve string IDs → keys
    -- ------------------------------------------------------------------
    if @VendorID is not null and LTRIM(RTRIM(@VendorID)) <> ''''
    begin
        select @VendorKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(VendorID) = UPPER(@VendorID) or UPPER(CompanyName) = UPPER(@VendorID))

        if @VendorKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Vendor not found: '' + @VendorID + '' — filter ignored.'', ''vendorID'')
    end

    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 8. Aggregate payments per vendor over the window
    --    Void handling: include payment when not voided, OR when the
    --    voiding entry posted after the window''s end (original was valid
    --    during the window). Matches the convention in spRptInvoiceAging.
    -- ------------------------------------------------------------------
    create table #Vendors (
        VendorKey         int            null,
        VendorID          nvarchar(50)   null,
        VendorName        nvarchar(500)  null,
        Type1099          smallint       null,
        Box1099           varchar(10)    null,
        HasW9             bit            null,
        TotalPaid         money          null,
        PaymentCount      int            null,
        LastPaymentDate   smalldatetime  null,
        Flag              varchar(40)    null,
        Severity          varchar(10)    null
    )

    ;with pays as (
        select
            p.VendorKey,
            p.PaymentAmount,
            p.PaymentDate
        from tPayment p (nolock)
        left join tPayment v (nolock) on p.VoidPaymentKey = v.PaymentKey
                                     and v.CompanyKey     = @CompanyKey
        where p.CompanyKey   = @CompanyKey
          and p.PaymentDate >= @StartDate
          and p.PaymentDate <= @EndDate
          and (p.Posted >= @PostedOnly)
          and (
              ISNULL(p.VoidPaymentKey, 0) = 0
              or v.PaymentDate is null
              or v.PaymentDate > @EndDate
          )
          and (@VendorKey            is null or p.VendorKey    = @VendorKey)
          and (@GLCompanyKeyResolved is null or p.GLCompanyKey = @GLCompanyKeyResolved)
          and (
              @IsAdministrator = 1
              or @RestrictToGLCompany = 0
              or ISNULL(p.GLCompanyKey, 0) in (
                    select uglca.GLCompanyKey
                    from tUserGLCompanyAccess uglca (nolock)
                    where uglca.UserKey = @UserKey
                )
          )
    )
    insert into #Vendors (
        VendorKey, VendorID, VendorName, Type1099, Box1099, HasW9,
        TotalPaid, PaymentCount, LastPaymentDate
    )
    select
        pays.VendorKey,
        MAX(c.VendorID),
        MAX(c.CompanyName),
        MAX(ISNULL(c.Type1099, 0)),
        MAX(c.Box1099),
        cast(case when MAX(case when c.EINNumber is not null and LTRIM(RTRIM(c.EINNumber)) <> '''' then 1 else 0 end) = 1
                  then 1 else 0 end as bit),
        ROUND(SUM(pays.PaymentAmount), 2),
        COUNT(*),
        MAX(pays.PaymentDate)
    from pays
    left join tCompany c (nolock) on pays.VendorKey = c.CompanyKey
    group by pays.VendorKey

    -- ------------------------------------------------------------------
    -- 9. Apply contractor / threshold filters
    -- ------------------------------------------------------------------
    if @ContractorsOnly = 1
        delete from #Vendors where ISNULL(Type1099, 0) = 0

    if @AboveThresholdOnly = 1
        delete from #Vendors where ISNULL(TotalPaid, 0) < @ThresholdAmount

    -- Drop net-zero rows (paid + voided in window)
    delete from #Vendors where ISNULL(TotalPaid, 0) = 0 and ISNULL(PaymentCount, 0) <= 1

    -- ------------------------------------------------------------------
    -- 10. Compute flag / severity (1099 lens)
    --     Priority — first match wins, most actionable first:
    --       missing_w9_over_threshold  → contractor, paid >= threshold, no EIN  (red)
    --       missing_w9                 → contractor, paid > 0, no EIN           (yellow)
    --       over_1099_threshold        → contractor, paid >= threshold, has W9  (yellow)
    --       near_1099_threshold        → contractor, paid >= near threshold     (yellow)
    --       null                       → everyone else                          (green)
    --     Non-contractors (Type1099 = 0) never carry a flag — they''re routine AP.
    -- ------------------------------------------------------------------
    update #Vendors
    set Flag =
            case
                when ISNULL(Type1099, 0) = 0                                          then null
                when TotalPaid >= @ThresholdAmount     and HasW9 = 0                  then ''missing_w9_over_threshold''
                when TotalPaid >= @ThresholdAmount     and HasW9 = 1                  then ''over_1099_threshold''
                when TotalPaid >= @NearThresholdAmount and TotalPaid < @ThresholdAmount then ''near_1099_threshold''
                when TotalPaid > 0                     and HasW9 = 0                  then ''missing_w9''
                else                                                                       null
            end,
        Severity =
            case
                when ISNULL(Type1099, 0) = 0                                          then ''green''
                when TotalPaid >= @ThresholdAmount     and HasW9 = 0                  then ''red''
                when TotalPaid >= @ThresholdAmount     and HasW9 = 1                  then ''yellow''
                when TotalPaid >= @NearThresholdAmount and TotalPaid < @ThresholdAmount then ''yellow''
                when TotalPaid > 0                     and HasW9 = 0                  then ''yellow''
                else                                                                       ''green''
            end

    -- ------------------------------------------------------------------
    -- 11. Totals + pagination
    -- ------------------------------------------------------------------
    select @TotalPaid = ISNULL(SUM(TotalPaid), 0),
           @RowCount  = COUNT(*)
    from #Vendors

    if @RowCount > (@Cursor + @MaxRows)
    begin
        set @Truncated  = 1
        set @NextCursor = @Cursor + @MaxRows
    end
    else
    begin
        set @Truncated  = 0
        set @NextCursor = null
    end

    -- ------------------------------------------------------------------
    -- 12. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 13. Result set 2: meta (single row)
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate, 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,
        @RowCount                                                                   as [rowCount],
        @Truncated                                                                  as truncated,
        @NextCursor                                                                 as nextCursor,
        ROUND(@TotalPaid, 2)                                                        as totalPaid,
        cast(@ContractorsOnly as bit)                                               as contractorsOnly,
        @ThresholdAmount                                                            as thresholdAmount,
        @NearThresholdAmount                                                        as nearThresholdAmount,
        (select COUNT(*) from #Vendors where ISNULL(Type1099, 0) <> 0)              as contractorCount,
        (select COUNT(*) from #Vendors where ISNULL(Type1099, 0) <> 0 and TotalPaid >= @ThresholdAmount) as candidateCount1099,
        (select COUNT(*) from #Vendors where ISNULL(Type1099, 0) <> 0 and HasW9 = 0) as missingW9Count,
        (select COUNT(*) from #Vendors
            where ISNULL(Type1099, 0) <> 0
              and TotalPaid >= @NearThresholdAmount
              and TotalPaid <  @ThresholdAmount)                                    as nearThresholdCount

    -- ------------------------------------------------------------------
    -- 14. Result set 3: vendors (paginated, prioritized)
    --     Sort: severity desc → totalPaid desc → VendorName asc.
    -- ------------------------------------------------------------------
    ;with ordered as (
        select
            ROW_NUMBER() over (
                order by
                    case
                        when Severity = ''red''    then 1
                        when Severity = ''yellow'' then 2
                        else                          3
                    end,
                    TotalPaid desc,
                    VendorName
            )                                                          as rn,
            VendorKey, VendorID, VendorName, Type1099, Box1099, HasW9,
            TotalPaid, PaymentCount, LastPaymentDate, Flag, Severity
        from #Vendors
    )
    select
        VendorKey                                                                  as vendorKey,
        VendorID                                                                   as vendorID,
        VendorName                                                                 as vendorName,
        cast(case when ISNULL(Type1099, 0) <> 0 then 1 else 0 end as bit)          as is1099Eligible,
        Type1099                                                                   as type1099,
        Box1099                                                                    as box1099,
        HasW9                                                                      as hasW9,
        TotalPaid                                                                  as totalPaid,
        PaymentCount                                                               as paymentCount,
        convert(varchar(10), LastPaymentDate, 23)                                  as lastPaymentDate,
        Flag                                                                       as flag,
        Severity                                                                   as severity
    from ordered
    where rn >  @Cursor
      and rn <= @Cursor + @MaxRows
    order by rn

    -- ------------------------------------------------------------------
    drop table #Vendors
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetTransactionRegister]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetTransactionRegister]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetTransactionRegister]
(
    @CompanyKey         int,
    @UserKey            int,
    @StartDate          datetime,                       -- required: period start
    @EndDate            datetime,                       -- required: period end
    @GLAccountID        varchar(100) = null,            -- tGLAccount.AccountNumber (single)
    @AccountType        smallint     = null,            -- single AccountType filter (e.g. 41 Expense)
    @GLCompanyID        varchar(50)  = null,
    @ClientID           varchar(75)  = null,            -- tCompany.CustomerID
    @ProjectID          varchar(50)  = null,            -- tProject.ProjectNumber
    @Entity             varchar(50)  = null,            -- source-entity filter (''tInvoice'',''tVoucher'',''tCheck'',''tJournalEntry'',...)
    @MinAmount          money        = null,            -- |Debit|+|Credit| minimum
    @IncludeReversed    bit          = 1,               -- 0 = drop Reversed=1 rows
    @FlagsOnly          bit          = 0,               -- 1 = only rows with a non-null flag (close-of-month worklist)
    @CurrencyID         varchar(10)  = null,            -- filter to one currency when multi-currency
    @MaxRows            int          = 250,             -- pagination ceiling — transaction register can be huge
    @Cursor             int          = 0
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — full GL detail for a window with review flags.
||                          Source: tTransaction (every posted GL entry). Joins tGLAccount for
||                          account info; reads the polymorphic Entity/EntityKey + Reference for
||                          source-document context. Computes per-row review flags for month-end
||                          close worklists: reversed entries, manual JEs without memos, and
||                          name-based suspense/uncategorized detection.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @MultiCurrency        tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @EffectiveCurrencyID  varchar(10)
    declare @CanReadGL            bit
    declare @ErrorCount           int

    declare @GLAccountKey         int
    declare @GLCompanyKeyResolved int
    declare @ClientKey            int
    declare @ProjectKey           int

    declare @RowCount             int
    declare @Truncated            tinyint
    declare @NextCursor           int
    declare @TotalDebits          money
    declare @TotalCredits         money

    if @MaxRows is null or @MaxRows <= 0 set @MaxRows = 250
    if @Cursor  is null or @Cursor  <  0 set @Cursor  = 0

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Validate required inputs
    -- ------------------------------------------------------------------
    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'')

    -- ------------------------------------------------------------------
    -- 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: any GL-detail right (admin bypass)
    -- ------------------------------------------------------------------
    set @CanReadGL = 0
    if @IsAdministrator = 1
        set @CanReadGL = 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 (''acct_gl_trailbal'', ''acct_gl_balsheet'', ''acct_gl_pl_ytd'')
    )
        set @CanReadGL = 1

    if @CanReadGL = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view the GL transaction register.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 5. Bail on validation errors gathered earlier
    -- ------------------------------------------------------------------
    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)
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 7. Resolve string IDs → keys
    -- ------------------------------------------------------------------
    if @GLAccountID is not null and LTRIM(RTRIM(@GLAccountID)) <> ''''
    begin
        select @GLAccountKey = GLAccountKey
        from tGLAccount (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(AccountNumber) = UPPER(@GLAccountID)

        if @GLAccountKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Account not found: '' + @GLAccountID + '' — filter ignored.'', ''glAccountID'')
    end

    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    if @ClientID is not null and LTRIM(RTRIM(@ClientID)) <> ''''
    begin
        select @ClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(CustomerID) = UPPER(@ClientID) or UPPER(CompanyName) = UPPER(@ClientID))

        if @ClientKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Client not found: '' + @ClientID + '' — filter ignored.'', ''clientID'')
    end

    if @ProjectID is not null and LTRIM(RTRIM(@ProjectID)) <> ''''
    begin
        select @ProjectKey = ProjectKey
        from tProject (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(ProjectNumber) = UPPER(@ProjectID)

        if @ProjectKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Project not found: '' + @ProjectID + '' — filter ignored.'', ''projectID'')
    end

    -- ------------------------------------------------------------------
    -- 8. Pull the window into staging with computed flag / severity
    --    Sign-aware "amount" for display:  Debit > 0 ? +Debit : -Credit
    --    All home-currency totals come from HDebit/HCredit when populated,
    --    falling back to Debit/Credit (single-currency tenants).
    -- ------------------------------------------------------------------
    create table #Reg (
        TransactionKey   int            null,
        TransactionDate  smalldatetime  null,
        PostMonth        int            null,
        PostYear         int            null,
        Entity           varchar(50)    null,
        EntityKey        int            null,
        Reference        varchar(100)   null,
        Memo             nvarchar(500)  null,

        GLAccountKey     int            null,
        AccountNumber    varchar(100)   null,
        AccountName      nvarchar(200)  null,
        AccountType      smallint       null,

        GLCompanyKey     int            null,
        OfficeKey        int            null,
        ClassKey         int            null,
        DepartmentKey    int            null,
        ClientKey        int            null,
        ProjectKey       int            null,

        NativeDebit      money          null,
        NativeCredit     money          null,
        NativeAmount     money          null,
        HomeAmount       money          null,
        CurrencyID       varchar(10)    null,
        ExchangeRate     decimal(24,7)  null,

        Reversed         tinyint        null,
        Cleared          tinyint        null,

        Flag             varchar(40)    null,
        Severity         varchar(10)    null
    )

    insert into #Reg (
        TransactionKey, TransactionDate, PostMonth, PostYear, Entity, EntityKey, Reference, Memo,
        GLAccountKey, AccountNumber, AccountName, AccountType,
        GLCompanyKey, OfficeKey, ClassKey, DepartmentKey, ClientKey, ProjectKey,
        NativeDebit, NativeCredit, NativeAmount, HomeAmount,
        CurrencyID, ExchangeRate, Reversed, Cleared
    )
    select
        t.TransactionKey,
        t.TransactionDate,
        t.PostMonth,
        t.PostYear,
        t.Entity,
        t.EntityKey,
        t.Reference,
        t.Memo,

        t.GLAccountKey,
        gl.AccountNumber,
        gl.AccountName,
        gl.AccountType,

        t.GLCompanyKey,
        t.OfficeKey,
        t.ClassKey,
        t.DepartmentKey,
        t.ClientKey,
        t.ProjectKey,

        ISNULL(t.Debit,  0),
        ISNULL(t.Credit, 0),
        ISNULL(t.Debit,  0) - ISNULL(t.Credit, 0),                          -- native signed amount
        ISNULL(t.HDebit, ISNULL(t.Debit,  0))
          - ISNULL(t.HCredit, ISNULL(t.Credit, 0)),                         -- home-currency signed amount
        ISNULL(t.CurrencyID, @HomeCurrencyID),
        t.ExchangeRate,
        t.Reversed,
        t.Cleared
    from tTransaction t (nolock)
    left join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
                                    and gl.CompanyKey  = @CompanyKey
    where t.CompanyKey      = @CompanyKey
      and t.TransactionDate >= @StartDate
      and t.TransactionDate <= @EndDate
      and (@GLAccountKey          is null or t.GLAccountKey = @GLAccountKey)
      and (@AccountType           is null or gl.AccountType = @AccountType)
      and (@GLCompanyKeyResolved  is null or t.GLCompanyKey = @GLCompanyKeyResolved)
      and (@ClientKey             is null or t.ClientKey    = @ClientKey)
      and (@ProjectKey            is null or t.ProjectKey   = @ProjectKey)
      and (@Entity                is null or t.Entity       = @Entity)
      and (@IncludeReversed = 1   or  ISNULL(t.Reversed, 0) = 0)
      and (@CurrencyID            is null or ISNULL(t.CurrencyID, '''') = @CurrencyID)
      and (@MinAmount is null or
           ABS(ISNULL(t.Debit, 0)) + ABS(ISNULL(t.Credit, 0)) >= @MinAmount)
      and (
            @IsAdministrator = 1
            or @RestrictToGLCompany = 0
            or ISNULL(t.GLCompanyKey, 0) in (
                select uglca.GLCompanyKey
                from tUserGLCompanyAccess uglca (nolock)
                where uglca.UserKey = @UserKey
              )
      )

    -- ------------------------------------------------------------------
    -- 9. Compute review flags
    --    Flag priority (first match wins, most-actionable first):
    --      reversed       → Reversed = 1
    --      uncategorized  → account name/number matches a suspense pattern
    --      review_blank   → manual JE with empty memo + reference
    --      none           → null
    --    Severity:
    --      reversed       → red
    --      uncategorized  → yellow
    --      review_blank   → yellow
    --      otherwise      → green
    -- ------------------------------------------------------------------
    update #Reg
    set Flag =
            case
                when Reversed = 1                                                          then ''reversed''
                when UPPER(ISNULL(AccountName, ''''))   like ''%UNCATEGOR%''                   then ''uncategorized''
                when UPPER(ISNULL(AccountName, ''''))   like ''%SUSPENSE%''                    then ''uncategorized''
                when UPPER(ISNULL(AccountName, ''''))   like ''%ASK MY ACCOUNTANT%''           then ''uncategorized''
                when UPPER(ISNULL(AccountNumber, '''')) like ''%UNCAT%''                       then ''uncategorized''
                when Entity = ''tJournalEntry''
                 and (Memo is null or LTRIM(RTRIM(Memo)) = '''')
                 and (Reference is null or LTRIM(RTRIM(Reference)) = '''')                   then ''review_blank''
                else null
            end,
        Severity =
            case
                when Reversed = 1                                                          then ''red''
                when UPPER(ISNULL(AccountName, ''''))   like ''%UNCATEGOR%''                   then ''yellow''
                when UPPER(ISNULL(AccountName, ''''))   like ''%SUSPENSE%''                    then ''yellow''
                when UPPER(ISNULL(AccountName, ''''))   like ''%ASK MY ACCOUNTANT%''           then ''yellow''
                when UPPER(ISNULL(AccountNumber, '''')) like ''%UNCAT%''                       then ''yellow''
                when Entity = ''tJournalEntry''
                 and (Memo is null or LTRIM(RTRIM(Memo)) = '''')
                 and (Reference is null or LTRIM(RTRIM(Reference)) = '''')                   then ''yellow''
                else ''green''
            end

    if @FlagsOnly = 1
        delete from #Reg where Flag is null

    -- ------------------------------------------------------------------
    -- 10. Totals + pagination
    -- ------------------------------------------------------------------
    select @TotalDebits  = ISNULL(SUM(NativeDebit),  0),
           @TotalCredits = ISNULL(SUM(NativeCredit), 0),
           @RowCount     = COUNT(*)
    from #Reg

    if @RowCount > (@Cursor + @MaxRows)
    begin
        set @Truncated  = 1
        set @NextCursor = @Cursor + @MaxRows
    end
    else
    begin
        set @Truncated  = 0
        set @NextCursor = null
    end

    -- ------------------------------------------------------------------
    -- 11. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 12. 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,
        @RowCount                                                     as [rowCount],
        @Truncated                                                    as truncated,
        @NextCursor                                                   as nextCursor,
        ROUND(@TotalDebits,  2)                                       as totalDebits,
        ROUND(@TotalCredits, 2)                                       as totalCredits,
        ROUND(@TotalDebits - @TotalCredits, 2)                        as totalNet,
        (select COUNT(*) from #Reg where Flag = ''reversed'')           as reversedCount,
        (select COUNT(*) from #Reg where Flag = ''uncategorized'')      as uncategorizedCount,
        (select COUNT(*) from #Reg where Flag = ''review_blank'')       as reviewBlankCount

    -- ------------------------------------------------------------------
    -- 13. Result set 3: transactions (paginated)
    --     Sort: severity desc → TransactionDate desc → TransactionKey desc.
    --     The severity-first sort puts close-of-month worklist items on page 1.
    -- ------------------------------------------------------------------
    ;with ordered as (
        select
            ROW_NUMBER() over (
                order by
                    case
                        when Severity = ''red''    then 1
                        when Severity = ''yellow'' then 2
                        else                          3
                    end,
                    TransactionDate desc,
                    TransactionKey  desc
            )                                                          as rn,
            TransactionKey, TransactionDate, PostMonth, PostYear,
            Entity, EntityKey, Reference, Memo,
            GLAccountKey, AccountNumber, AccountName, AccountType,
            GLCompanyKey, OfficeKey, ClassKey, DepartmentKey, ClientKey, ProjectKey,
            NativeDebit, NativeCredit, NativeAmount, HomeAmount,
            CurrencyID, ExchangeRate, Reversed, Cleared, Flag, Severity
        from #Reg
    )
    select
        TransactionKey                                                 as transactionKey,
        convert(varchar(10), TransactionDate, 23)                      as transactionDate,
        PostMonth                                                      as postMonth,
        PostYear                                                       as postYear,
        Entity                                                         as entity,
        EntityKey                                                      as entityKey,
        Reference                                                      as reference,
        Memo                                                           as memo,
        GLAccountKey                                                   as glAccountKey,
        AccountNumber                                                  as accountNumber,
        AccountName                                                    as accountName,
        AccountType                                                    as accountType,
        GLCompanyKey                                                   as glCompanyKey,
        OfficeKey                                                      as officeKey,
        ClassKey                                                       as classKey,
        DepartmentKey                                                  as departmentKey,
        ClientKey                                                      as clientKey,
        ProjectKey                                                     as projectKey,
        ROUND(NativeDebit,  2)                                         as debit,
        ROUND(NativeCredit, 2)                                         as credit,
        ROUND(NativeAmount, 2)                                         as amount,
        ROUND(HomeAmount,   2)                                         as homeAmount,
        CurrencyID                                                     as currency,
        ExchangeRate                                                   as exchangeRate,
        cast(ISNULL(Reversed, 0) as bit)                               as reversed,
        cast(ISNULL(Cleared,  0) as bit)                               as cleared,
        Flag                                                           as flag,
        Severity                                                       as severity
    from ordered
    where rn >  @Cursor
      and rn <= @Cursor + @MaxRows
    order by rn

    -- ------------------------------------------------------------------
    drop table #Reg
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetCustomerConcentration]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetCustomerConcentration]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetCustomerConcentration]
(
    @CompanyKey                int,
    @UserKey                   int,
    @StartDate                 datetime    = null,        -- defaults to @AsOfDate − @TrailingMonths
    @EndDate                   datetime    = null,        -- defaults to @AsOfDate (today)
    @PriorStartDate            datetime    = null,        -- optional explicit prior-period start
    @PriorEndDate              datetime    = null,        -- optional explicit prior-period end
    @AsOfDate                  datetime    = null,        -- defaults today; only used to derive defaults above
    @TrailingMonths            int         = 12,          -- when @StartDate/@EndDate are null
    @IncludeComparison         bit         = 1,           -- 1 = compute prior trailing window automatically
    @GLCompanyID               varchar(50) = null,        -- tGLCompany.GLCompanyID
    @ParentClientID            varchar(75) = null,        -- when set, group children up under their parent
    @TopN                      int         = 50,          -- ceiling on the clients[] result set
    @MinPercent                decimal(9,4) = null,       -- only return clients at/above this % of total (e.g. 1.0)
    @RedThresholdPct           decimal(9,4) = 20.0,       -- per-client % at/above which severity=''red''
    @YellowThresholdPct        decimal(9,4) = 10.0,       -- per-client % at/above which severity=''yellow''
    @IncludeAdvanceBills       bit         = 0,           -- 0 = exclude AB invoices (recommended for revenue view)
    @PostedOnly                bit         = 1,           -- 1 = only posted invoices (matches GL revenue)
    @CurrencyID                varchar(10) = null         -- filter to one currency when multi-currency
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — billed-revenue concentration by client over a trailing window.
||                          Source: tInvoice (approved + optionally posted), excludes advance-bill rows
||                          by default. Computes per-client % of total, HHI for the book overall,
||                          and severity flags. Optional prior-trailing window for percent-delta trends.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @MultiCurrency        tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @EffectiveCurrencyID  varchar(10)
    declare @CanRunRevenueReport  bit
    declare @ErrorCount           int
    declare @GLCompanyKeyResolved int
    declare @ParentClientKey      int
    declare @TotalRevenue         money
    declare @PriorTotalRevenue    money
    declare @ClientCount          int
    declare @HHI                  decimal(20,4)
    declare @PriorHHI             decimal(20,4)

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())

    if @TrailingMonths is null or @TrailingMonths <= 0
        set @TrailingMonths = 12

    if @EndDate is null
        set @EndDate = @AsOfDate
    if @StartDate is null
        set @StartDate = dateadd(month, -@TrailingMonths, @EndDate)

    -- If comparison is on but explicit prior dates not provided, mirror the current window
    if @IncludeComparison = 1 and @PriorStartDate is null and @PriorEndDate is null
    begin
        set @PriorEndDate   = dateadd(day, -1, @StartDate)
        set @PriorStartDate = dateadd(month, -@TrailingMonths, @PriorEndDate)
    end

    if @TopN is null or @TopN <= 0 set @TopN = 50

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. 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

    -- ------------------------------------------------------------------
    -- 3. Right check: any AR/revenue-summary right (admin bypass)
    -- ------------------------------------------------------------------
    set @CanRunRevenueReport = 0
    if @IsAdministrator = 1
        set @CanRunRevenueReport = 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 (
              ''acct_ar_invoicesummary'',
              ''acct_ar_salesjournal'',
              ''acct_ar_aging'',
              ''acct_client_gl_pl_ytd''
          )
    )
        set @CanRunRevenueReport = 1

    if @CanRunRevenueReport = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view revenue summary data.'', ''general'')

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

        drop table #errors
        return -103
    end

    -- ------------------------------------------------------------------
    -- 4. Validate basic args
    -- ------------------------------------------------------------------
    if @EndDate < @StartDate
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''endDate must be on or after startDate.'', ''endDate'')

    if @PriorStartDate is not null and @PriorEndDate is not null and @PriorEndDate < @PriorStartDate
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''priorEndDate must be on or after priorStartDate.'', ''priorEndDate'')

    if (@PriorStartDate is null and @PriorEndDate is not null)
        or (@PriorStartDate is not null and @PriorEndDate is null)
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''priorStartDate and priorEndDate must be supplied together.'', ''priorStartDate'')

    if @RedThresholdPct < @YellowThresholdPct
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''INVALID_VALUE'', ''redThresholdPct must be >= yellowThresholdPct.'', ''redThresholdPct'')

    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

    -- ------------------------------------------------------------------
    -- 5. 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)
    if @MultiCurrency = 0 set @CurrencyID = null
    set @EffectiveCurrencyID = ISNULL(@CurrencyID, @HomeCurrencyID)

    -- ------------------------------------------------------------------
    -- 6. Resolve string IDs → keys
    -- ------------------------------------------------------------------
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    if @ParentClientID is not null and LTRIM(RTRIM(@ParentClientID)) <> ''''
    begin
        select @ParentClientKey = CompanyKey
        from tCompany (nolock)
        where OwnerCompanyKey = @CompanyKey
          and (UPPER(CustomerID) = UPPER(@ParentClientID) or UPPER(CompanyName) = UPPER(@ParentClientID))

        if @ParentClientKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Parent client not found: '' + @ParentClientID + '' — filter ignored.'', ''parentClientID'')
    end

    -- ------------------------------------------------------------------
    -- 7. Pull current-window revenue per client
    --    Rollup rule:
    --      - If @ParentClientKey is supplied, ONLY include children of that parent (+ the parent itself)
    --      - Otherwise, roll each client up to its ultimate parent (or itself if no parent)
    --    Multi-tenancy / GL company security mirrors the existing patterns.
    -- ------------------------------------------------------------------
    create table #Revenue (
        ClientKey         int            null,
        ClientID          varchar(75)    null,
        ClientName        nvarchar(500)  null,
        Revenue           money          null,
        PriorRevenue      money          null
    )

    ;with raw as (
        select
            -- Roll each row up to its parent when one exists, except when caller already
            -- narrowed to a parent (then keep child-grained inside that parent).
            case
                when @ParentClientKey is not null then i.ClientKey
                else                                   ISNULL(c.ParentCompanyKey, i.ClientKey)
            end as RollupClientKey,
            i.InvoiceTotalAmount,
            i.InvoiceDate,
            i.PostingDate,
            i.GLCompanyKey,
            i.Posted,
            i.AdvanceBill,
            i.InvoiceStatus,
            ISNULL(i.CurrencyID, '''') as CurrencyID
        from tInvoice i (nolock)
        left join tCompany c (nolock) on i.ClientKey = c.CompanyKey
        where i.CompanyKey       = @CompanyKey
          and i.InvoiceStatus    = 4                              -- Approved
          and (i.Posted >= @PostedOnly)
          and (@IncludeAdvanceBills = 1 or ISNULL(i.AdvanceBill, 0) = 0)
          and (@GLCompanyKeyResolved is null or i.GLCompanyKey = @GLCompanyKeyResolved)
          and (@CurrencyID is null or ISNULL(i.CurrencyID, '''') = @CurrencyID)
          and (
              @ParentClientKey is null
              or i.ClientKey = @ParentClientKey
              or i.ClientKey in (select CompanyKey from tCompany (nolock) where ParentCompanyKey = @ParentClientKey)
          )
          and (
              @IsAdministrator = 1
              or @RestrictToGLCompany = 0
              or ISNULL(i.GLCompanyKey, 0) in (
                    select uglca.GLCompanyKey
                    from tUserGLCompanyAccess uglca (nolock)
                    where uglca.UserKey = @UserKey
                )
          )
    )
    insert into #Revenue (ClientKey, ClientID, ClientName, Revenue, PriorRevenue)
    select
        raw.RollupClientKey,
        MAX(c.CustomerID),
        MAX(c.CompanyName),
        SUM(case when raw.InvoiceDate >= @StartDate and raw.InvoiceDate <= @EndDate then raw.InvoiceTotalAmount else 0 end),
        SUM(case
                when @PriorStartDate is not null
                 and raw.InvoiceDate >= @PriorStartDate
                 and raw.InvoiceDate <= @PriorEndDate
                then raw.InvoiceTotalAmount
                else 0
            end)
    from raw
    left join tCompany c (nolock) on raw.RollupClientKey = c.CompanyKey
    where (
        (raw.InvoiceDate >= @StartDate      and raw.InvoiceDate <= @EndDate)
     or (@PriorStartDate is not null
         and raw.InvoiceDate >= @PriorStartDate
         and raw.InvoiceDate <= @PriorEndDate)
    )
    group by raw.RollupClientKey

    -- Drop zero-revenue rows (a client that only had activity outside both windows)
    delete from #Revenue where ISNULL(Revenue, 0) = 0 and ISNULL(PriorRevenue, 0) = 0

    -- ------------------------------------------------------------------
    -- 8. Compute aggregates
    -- ------------------------------------------------------------------
    select @TotalRevenue      = ISNULL(SUM(Revenue),      0),
           @PriorTotalRevenue = ISNULL(SUM(PriorRevenue), 0),
           @ClientCount       = COUNT(*)
    from #Revenue
    where ISNULL(Revenue, 0) > 0

    -- HHI = sum of (pct^2). Use percent (0-100) so 1 client at 100% = 10000.
    if @TotalRevenue > 0
        select @HHI = ISNULL(SUM(POWER(100.0 * Revenue / @TotalRevenue, 2)), 0)
        from #Revenue where Revenue > 0
    else
        set @HHI = 0

    if @PriorTotalRevenue > 0
        select @PriorHHI = ISNULL(SUM(POWER(100.0 * PriorRevenue / @PriorTotalRevenue, 2)), 0)
        from #Revenue where PriorRevenue > 0
    else
        set @PriorHHI = 0

    -- ------------------------------------------------------------------
    -- 9. Result set 1: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 10. Result set 2: meta (single row, with rolled-up totals)
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate,       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,
        @TrailingMonths                                                   as trailingMonths,
        ROUND(@TotalRevenue,      2)                                      as totalRevenue,
        case when @PriorStartDate is null then null
             else ROUND(@PriorTotalRevenue, 2) end                        as priorTotalRevenue,
        case when @PriorStartDate is null then null
             else ROUND(@TotalRevenue - @PriorTotalRevenue, 2) end        as totalRevenueDelta,
        @ClientCount                                                      as clientCount,
        ROUND(@HHI, 2)                                                    as hhi,
        case when @PriorStartDate is null then null
             else ROUND(@PriorHHI, 2) end                                 as priorHHI,
        case
            when @HHI >= 2500 then ''high''
            when @HHI >= 1500 then ''moderate''
            else                   ''low''
        end                                                               as concentrationLevel,
        cast(0 as bit)                                                    as truncated,
        cast(null as int)                                                 as nextCursor

    -- ------------------------------------------------------------------
    -- 11. Result set 3: clients (ranked, top N)
    -- ------------------------------------------------------------------
    ;with ranked as (
        select
            ClientKey,
            ClientID,
            ClientName,
            ISNULL(Revenue,      0)                                            as Revenue,
            ISNULL(PriorRevenue, 0)                                            as PriorRevenue,
            case when @TotalRevenue      > 0 then 100.0 * Revenue      / @TotalRevenue      else 0 end as PercentOfTotal,
            case when @PriorTotalRevenue > 0 then 100.0 * PriorRevenue / @PriorTotalRevenue else 0 end as PriorPercentOfTotal
        from #Revenue
        where Revenue > 0
    ),
    rankedWithRn as (
        select *,
               ROW_NUMBER() over (order by Revenue desc, ClientName) as rn
        from ranked
        where (@MinPercent is null or PercentOfTotal >= @MinPercent)
    )
    select
        rn                                                            as rank,
        ClientKey                                                     as clientKey,
        ClientID                                                      as clientID,
        ClientName                                                    as clientName,
        ROUND(Revenue, 2)                                             as revenue,
        case when @PriorStartDate is null then null
             else ROUND(PriorRevenue, 2) end                          as priorRevenue,
        case when @PriorStartDate is null then null
             else ROUND(Revenue - PriorRevenue, 2) end                as revenueDelta,
        ROUND(PercentOfTotal, 2)                                      as percentOfTotal,
        case when @PriorStartDate is null then null
             else ROUND(PriorPercentOfTotal, 2) end                   as priorPercentOfTotal,
        case when @PriorStartDate is null then null
             else ROUND(PercentOfTotal - PriorPercentOfTotal, 2) end  as percentDelta,
        case
            when PercentOfTotal >= @RedThresholdPct    then ''red''
            when PercentOfTotal >= @YellowThresholdPct then ''yellow''
            else                                            ''green''
        end                                                           as severity,
        case
            when PercentOfTotal >= @RedThresholdPct                          then ''concentration_high''
            when PercentOfTotal >= @YellowThresholdPct                       then ''concentration_medium''
            when @PriorStartDate is not null
             and PercentOfTotal - PriorPercentOfTotal >= 5                   then ''concentration_growing''
            when @PriorStartDate is not null
             and PriorRevenue  > 0
             and Revenue       < (PriorRevenue * 0.7)                        then ''revenue_falling''
            else                                                                  null
        end                                                           as flag
    from rankedWithRn
    where rn <= @TopN
    order by rn

    -- ------------------------------------------------------------------
    drop table #Revenue
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetPipelineLeads]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetPipelineLeads]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetPipelineLeads]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,        -- defaults today UTC
    @LeadOwnerID        varchar(75) = null,        -- tUser.UserID or FullName; null = caller
    @GLCompanyID        varchar(50) = null,
    @StageID            varchar(50) = null,        -- tLeadStage match (name; tLeadStage has no ID column)
    @MinSaleAmount      money       = null,
    @MaxIdleDays        int         = null,        -- drop leads idle longer than N days
    @IncludeUnowned     bit         = 0,           -- include leads with no AccountManagerKey
    @TopN               int         = 25,
    @Cursor             int         = 0
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — pipeline scoring for the call-list / lead-triage workflow.
||                          Source: tLead with LastActivityKey-driven engagement signals.
||                          Default lead-owner scope is the caller; admins / unowned mode override.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @CanReadLeads         bit
    declare @ErrorCount           int

    declare @LeadOwnerKey         int
    declare @LeadOwnerName        nvarchar(200)
    declare @StageKey             int
    declare @GLCompanyKeyResolved int

    declare @MaxStageOrder        int
    declare @MaxSaleAmount        money
    declare @MedianSaleAmount     money

    declare @OpenCount            int
    declare @TotalOpenValue       money
    declare @TotalWeightedValue   money
    declare @StaleCount           int
    declare @SlippedCount         int
    declare @AverageScore         decimal(9,2)

    declare @RowCount             int
    declare @Truncated            tinyint
    declare @NextCursor           int

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())
    if @TopN  is null or @TopN  <= 0 set @TopN  = 25
    if @Cursor is null or @Cursor < 0 set @Cursor = 0

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Load caller 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
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Right check: useLeads (admin bypass)
    -- ------------------------------------------------------------------
    set @CanReadLeads = 0
    if @IsAdministrator = 1
        set @CanReadLeads = 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 (''useLeads'', ''cm_viewleads'')
    )
        set @CanReadLeads = 1

    if @CanReadLeads = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view leads.'', ''general'')

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

    -- ------------------------------------------------------------------
    -- 4. Preferences
    -- ------------------------------------------------------------------
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0),
           @HomeCurrencyID      = CurrencyID
    from tPreference (nolock)
    where CompanyKey = @CompanyKey

    set @RestrictToGLCompany = ISNULL(@RestrictToGLCompany, 0)

    -- ------------------------------------------------------------------
    -- 5. Resolve lead owner — default to caller
    --    Match on tUser.UserID, then FirstName + '' '' + LastName, then FullName
    -- ------------------------------------------------------------------
    if @LeadOwnerID is not null and LTRIM(RTRIM(@LeadOwnerID)) <> ''''
    begin
        select top 1 @LeadOwnerKey = UserKey,
                     @LeadOwnerName = FirstName + '' '' + LastName
        from tUser (nolock)
        where CompanyKey = @CompanyKey
          and (
              UPPER(UserID) = UPPER(@LeadOwnerID)
              or UPPER(FirstName + '' '' + LastName) = UPPER(@LeadOwnerID)
          )

        if @LeadOwnerKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Lead owner not found: '' + @LeadOwnerID + '' — filter ignored.'', ''leadOwnerID'')
    end
    else if @IncludeUnowned = 0
    begin
        -- Default to caller as owner
        set @LeadOwnerKey = @UserKey
        select @LeadOwnerName = FirstName + '' '' + LastName
        from tUser (nolock)
        where UserKey = @UserKey and CompanyKey = @CompanyKey
    end

    -- ------------------------------------------------------------------
    -- 6. Resolve stage filter (by name — tLeadStage has no ID column)
    -- ------------------------------------------------------------------
    if @StageID is not null and LTRIM(RTRIM(@StageID)) <> ''''
    begin
        select @StageKey = LeadStageKey
        from tLeadStage (nolock)
        where UPPER(LeadStageName) = UPPER(@StageID)
          and ISNULL(Active, 1) = 1

        if @StageKey is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''Lead stage not found: '' + @StageID + '' — filter ignored.'', ''stageID'')
    end

    -- ------------------------------------------------------------------
    -- 7. Resolve GL company filter
    -- ------------------------------------------------------------------
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey
          and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 8. Pull open leads into staging
    -- ------------------------------------------------------------------
    create table #Leads (
        LeadKey                  int            null,
        LeadSubject              nvarchar(200)  null,
        ContactCompanyKey        int            null,
        ContactCompanyName       nvarchar(500)  null,
        AccountManagerKey        int            null,
        OwnerName                varchar(200)   null,
        LeadStageKey             int            null,
        LeadStageName            varchar(200)   null,
        StageOrder               int            null,
        LeadStatusKey            int            null,
        LeadStatusName           varchar(200)   null,
        SaleAmount               money          null,
        Probability              int            null,
        WeightedAmount           money          null,
        EstCloseDate             smalldatetime  null,
        DaysToClose              int            null,
        DateAdded                smalldatetime  null,
        DaysSinceAdded           int            null,
        LastActivityDate         smalldatetime  null,
        DaysSinceLastActivity    int            null,
        LastActivityType         varchar(200)   null,
        Score                    decimal(6,2)   null,
        Severity                 varchar(10)    null,
        Flag                     varchar(20)    null
    )

    insert into #Leads (
        LeadKey, LeadSubject, ContactCompanyKey, ContactCompanyName,
        AccountManagerKey, OwnerName,
        LeadStageKey, LeadStageName, StageOrder,
        LeadStatusKey, LeadStatusName,
        SaleAmount, Probability, WeightedAmount,
        EstCloseDate, DaysToClose,
        DateAdded, DaysSinceAdded,
        LastActivityDate, DaysSinceLastActivity, LastActivityType
    )
    select
        l.LeadKey,
        l.Subject,
        l.ContactCompanyKey,
        cc.CompanyName,
        l.AccountManagerKey,
        case when l.AccountManagerKey is not null then am.FirstName + '' '' + am.LastName end,
        l.LeadStageKey,
        ls.LeadStageName,
        ls.DisplayOrder,
        l.LeadStatusKey,
        lst.LeadStatusName,
        ISNULL(l.SaleAmount, 0),
        ISNULL(l.Probability, 0),
        ROUND(ISNULL(l.SaleAmount, 0) * ISNULL(l.Probability, 0) / 100.0, 2),
        l.EstCloseDate,
        case when l.EstCloseDate is not null
             then DATEDIFF(day, @AsOfDate, l.EstCloseDate)
             else null end,
        l.DateAdded,
        case when l.DateAdded is not null
             then DATEDIFF(day, l.DateAdded, @AsOfDate)
             else null end,
        ISNULL(a.ActivityDate, l.DateAdded),
        case when ISNULL(a.ActivityDate, l.DateAdded) is not null
             then DATEDIFF(day, ISNULL(a.ActivityDate, l.DateAdded), @AsOfDate)
             else null end,
        at.TypeName
    from tLead l (nolock)
    inner join tLeadStatus  lst (nolock) on l.LeadStatusKey  = lst.LeadStatusKey
    left join  tLeadStage    ls (nolock) on l.LeadStageKey   = ls.LeadStageKey
    left join  tCompany      cc (nolock) on l.ContactCompanyKey = cc.CompanyKey
    left join  tUser         am (nolock) on l.AccountManagerKey = am.UserKey
    left join  tActivity      a (nolock) on l.LastActivityKey   = a.ActivityKey
    left join  tActivityType at (nolock) on a.ActivityTypeKey   = at.ActivityTypeKey
    where l.CompanyKey                  = @CompanyKey
      and ISNULL(lst.LeadStatusActive, 0) = 1
      and (
            @IncludeUnowned = 1
            or @LeadOwnerKey is null
            or l.AccountManagerKey = @LeadOwnerKey
      )
      and (@StageKey             is null or l.LeadStageKey  = @StageKey)
      and (@GLCompanyKeyResolved is null or l.GLCompanyKey  = @GLCompanyKeyResolved)
      and (@MinSaleAmount        is null or ISNULL(l.SaleAmount, 0) >= @MinSaleAmount)
      and (
            @IsAdministrator = 1
            or @RestrictToGLCompany = 0
            or ISNULL(l.GLCompanyKey, 0) in (
                select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey
            )
      )

    -- Apply MaxIdleDays after the insert so we keep "no-activity-ever" leads when caller didn''t ask
    if @MaxIdleDays is not null
        delete from #Leads where ISNULL(DaysSinceLastActivity, 99999) > @MaxIdleDays

    -- ------------------------------------------------------------------
    -- 9. Normalization values for scoring
    -- ------------------------------------------------------------------
    select @MaxStageOrder    = NULLIF(MAX(StageOrder), 0),
           @MaxSaleAmount    = NULLIF(MAX(SaleAmount), 0)
    from #Leads

    -- Median for "high value" comparison in the cold-lead flag
    select @MedianSaleAmount = ISNULL(
        (select top 1 SaleAmount
         from (select SaleAmount,
                      ROW_NUMBER() over (order by SaleAmount) as rn,
                      COUNT(*) over ()                       as ct
               from #Leads
               where SaleAmount > 0) m
         where rn = (ct + 1) / 2), 0)

    -- ------------------------------------------------------------------
    -- 10. Compute composite score (0-100, capped)
    --     engagement: 40 * max(0, 1 - daysSinceLastActivity / 30)
    --     stage:      30 * stageOrder / maxStageOrder
    --     value:      20 * ln(saleAmount+1) / ln(maxSaleAmount+1)
    --     urgency:    +10 if daysToClose between 0 and 30
    --     recency:    -10 if daysSinceLastActivity = 0  (already touched today)
    -- ------------------------------------------------------------------
    update #Leads
    set Score =
        cast(
            CASE WHEN ISNULL(DaysSinceLastActivity, 999) >= 30 THEN 0
                 WHEN ISNULL(DaysSinceLastActivity, 999) < 0   THEN 0
                 ELSE 40.0 * (1.0 - ISNULL(DaysSinceLastActivity, 30) / 30.0)
            END
            +
            CASE WHEN @MaxStageOrder is null OR @MaxStageOrder = 0 THEN 0
                 ELSE 30.0 * ISNULL(StageOrder, 0) / @MaxStageOrder
            END
            +
            CASE WHEN @MaxSaleAmount is null OR @MaxSaleAmount <= 0 OR ISNULL(SaleAmount, 0) <= 0 THEN 0
                 ELSE 20.0 * LOG(SaleAmount + 1.0) / LOG(@MaxSaleAmount + 1.0)
            END
            +
            CASE WHEN DaysToClose is not null AND DaysToClose between 0 and 30 THEN 10.0 ELSE 0 END
            -
            CASE WHEN DaysSinceLastActivity = 0 THEN 10.0 ELSE 0 END
        as decimal(6,2))

    -- Cap to [0, 100]
    update #Leads set Score = case when Score > 100 then 100 when Score < 0 then 0 else Score end

    -- ------------------------------------------------------------------
    -- 11. Compute severity + flag (first-match priority)
    --     red:    slipped (EstCloseDate < today, status open)
    --     red:    cold (idle > 30 days AND SaleAmount > median)
    --     yellow: stalled (idle > 7 days)
    --     yellow: due_soon (daysToClose <= 14)
    --     green:  hot (idle <= 3 AND probability >= 70)
    --     green:  null otherwise
    -- ------------------------------------------------------------------
    update #Leads
    set
        Flag =
            case
                when EstCloseDate is not null AND EstCloseDate < @AsOfDate                          then ''slipped''
                when ISNULL(DaysSinceLastActivity, 999) > 30 AND SaleAmount > @MedianSaleAmount     then ''cold''
                when ISNULL(DaysSinceLastActivity, 999) > 7                                          then ''stalled''
                when DaysToClose is not null AND DaysToClose between 0 and 14                        then ''due_soon''
                when ISNULL(DaysSinceLastActivity, 999) <= 3 AND ISNULL(Probability, 0) >= 70        then ''hot''
                else null
            end,
        Severity =
            case
                when EstCloseDate is not null AND EstCloseDate < @AsOfDate                          then ''red''
                when ISNULL(DaysSinceLastActivity, 999) > 30 AND SaleAmount > @MedianSaleAmount     then ''red''
                when ISNULL(DaysSinceLastActivity, 999) > 7                                          then ''yellow''
                when DaysToClose is not null AND DaysToClose between 0 and 14                        then ''yellow''
                else ''green''
            end

    -- ------------------------------------------------------------------
    -- 12. Aggregate meta counters + pagination
    -- ------------------------------------------------------------------
    select @OpenCount          = COUNT(*),
           @TotalOpenValue     = ISNULL(SUM(SaleAmount),     0),
           @TotalWeightedValue = ISNULL(SUM(WeightedAmount), 0),
           @StaleCount         = SUM(case when ISNULL(DaysSinceLastActivity, 999) > 14                       then 1 else 0 end),
           @SlippedCount       = SUM(case when EstCloseDate is not null and EstCloseDate < @AsOfDate         then 1 else 0 end),
           @AverageScore       = CAST(ISNULL(AVG(Score), 0) as decimal(9,2))
    from #Leads

    if @OpenCount > (@Cursor + @TopN)
    begin
        set @Truncated  = 1
        set @NextCursor = @Cursor + @TopN
    end
    else
    begin
        set @Truncated  = 0
        set @NextCursor = null
    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
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), @AsOfDate, 126) + ''Z''        as asOf,
        @CompanyKey                                       as companyKey,
        ISNULL(@HomeCurrencyID, '''')                       as currency,
        @LeadOwnerKey                                     as leadOwnerKey,
        @LeadOwnerName                                    as leadOwnerName,
        @OpenCount                                        as openCount,
        ROUND(@TotalOpenValue,     2)                     as totalOpenValue,
        ROUND(@TotalWeightedValue, 2)                     as totalWeightedValue,
        @AverageScore                                     as averageScore,
        @StaleCount                                       as staleCount,
        @SlippedCount                                     as slippedCount,
        @Truncated                                        as truncated,
        @NextCursor                                       as nextCursor

    -- ------------------------------------------------------------------
    -- 15. Result set 3: leads (sorted, paginated)
    -- ------------------------------------------------------------------
    ;with ranked as (
        select
            ROW_NUMBER() over (
                order by
                    case
                        when Severity = ''red''    then 1
                        when Severity = ''yellow'' then 2
                        else                          3
                    end,
                    Score desc,
                    case when EstCloseDate is null then 1 else 0 end,
                    EstCloseDate asc
            )                                                  as rn,
            LeadKey, LeadSubject, ContactCompanyKey, ContactCompanyName,
            AccountManagerKey, OwnerName,
            LeadStageKey, LeadStageName, LeadStatusKey, LeadStatusName,
            SaleAmount, Probability, WeightedAmount,
            EstCloseDate, DaysToClose,
            DateAdded, DaysSinceAdded,
            LastActivityDate, DaysSinceLastActivity, LastActivityType,
            Score, Severity, Flag
        from #Leads
    )
    select
        LeadKey                                                                  as leadKey,
        LeadSubject                                                              as leadSubject,
        ContactCompanyKey                                                        as contactCompanyKey,
        ContactCompanyName                                                       as contactCompanyName,
        AccountManagerKey                                                        as ownerUserKey,
        OwnerName                                                                as ownerName,
        LeadStageKey                                                             as stageKey,
        LeadStageName                                                            as stageName,
        LeadStatusKey                                                            as statusKey,
        LeadStatusName                                                           as statusName,
        ROUND(SaleAmount,     2)                                                 as saleAmount,
        Probability                                                              as probability,
        ROUND(WeightedAmount, 2)                                                 as weightedAmount,
        convert(varchar(10), EstCloseDate, 23)                                   as estCloseDate,
        DaysToClose                                                              as daysToClose,
        convert(varchar(10), DateAdded, 23)                                      as dateAdded,
        DaysSinceAdded                                                           as daysSinceAdded,
        convert(varchar(10), LastActivityDate, 23)                               as lastActivityDate,
        DaysSinceLastActivity                                                    as daysSinceLastActivity,
        LastActivityType                                                         as lastActivityType,
        Score                                                                    as score,
        Severity                                                                 as severity,
        Flag                                                                     as flag
    from ranked
    where rn >  @Cursor
      and rn <= @Cursor + @TopN
    order by rn

    -- ------------------------------------------------------------------
    drop table #Leads
    drop table #errors

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








  
ALTER VIEW [dbo].[vReport_TaskAssignmentDetail]  
AS  
  
/*  
|| When       Who Rel     What  
|| 06/01/2018 GWG 18.6.0  Created from vReport_TaskAssignment  
|| 07/18/18 RLS 18.8.0.0 (408867) Added Title and Default Service Description  
|| 11/05/18 RLS 18.9.3   (428022) Use tu.APlanStart and tu.APlanComplete if they''re populated  
|| 01/03/19 RLS 19.1.0.0 (437795) Added [Constraint]  
|| 01/25/19 GWG 19.0.2   (441880) Adding different text for the first constraint option based on direction  
|| 07/01/19 RLB 19.0.7.0 (467305) Adding Hide From Client yes/no field  
|| 07/29/19 RLB 19.0.8.0 (470152) Added Project Manager  
|| 01/14/20 RLB 20.0.2.0 (494049) Added My Superviser  
|| 01/16/20 GAR 20.0.2.0 (488883) Added Project Client Notes  
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format  
|| 10/30/20 CRG 20.1.1.0 (534905) Modified Assigned User to use vUserNam  
|| 12/28/21 GAR 22.01.16 (581427) Added fields ''Successor'' and ''Predecessor''  
|| 03/10/22 CRG 22.04.17 (590626) Added two new columns: ''Actual Task Assignment Week Labor Hours'' and ''Week Hours Current And Future''.  
||                                These columns will show the actual, and bucketed hours correctly per week based on the Bucket Start date.  
|| 07/02/22 WDF 22.07.17 (601359) Added [Planning Project], [Planning Project Number], [Planning Project Name] and [Planning Project Full Name]  
||                                modeled after vReport_Project  
|| 08/05/22 GAR 22.09.18 (607739) Added Campaign Segment Start Date and Due Date  
|| 11/11/22 RKB 22.12.18 (617899) add Team Names from the assigned task users  
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color, department and service  
|| 04/25/23 RLS 23.05.14 (631367) Added [Project Percent Complete]  
|| 05/08/23 CRG 23.06.18 (604775) Now using tTaskPriority  
|| 08/11/23 RLB 23.09.17 (648008) added project type color and timeline segment color  
|| 03/05/24 RLB 24.04.14 (665298) using new table tTimeRollupDetail for Actual Task Labor Total, Actual Task Labor Hours, Actual Task Assignment Labor Total,Actual Task Assignment Labor Hours fields to see if it speeds report up  
|| 03/15/24 GAR 23.04.14 (666856) Added [Task Line Number]  
|| 03/18/24 RLB 23.04.14 (667627) fxied the Index was fd which id not exist  
|| 02/11/25 QD  25.03.16 (694502) Performance Initiative: Moved the sub selects into left joins  
|| 02/28/25 CRG 25.03.16 (695455) Added [Manually Adjusted Buckets]  
|| 05/15/25 QMD 25.06.16 (701196) Added TaskKey
|| 06/05/25 QMD 25.07.20 (703561) Added TaskUserKey, EmployeeKey
|| 06/25/25 RLS 25.07.20 (702884) Added [Non Billable Project]
|| 08/28/25 GAR 25.09.21 (708828) Added Service Code, Billing Item Code, and Billing Item Name
|| 10/01/25 GAR 25.10.19 (710659) Added Billable Rate
|| 05/05/26 CRG 26.06.14 (727946) Removed restriction that limited it to just detail tasks
*/   
  
Select  
  p.CompanyKey  
 ,p.GLCompanyKey  
 ,p.CustomFieldKey  
 ,u.CustomFieldKey as CustomFieldKey2  
 ,p.ProjectName as [Project Name]  
 ,p.ProjectNumber as [Project Number]  
 ,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]  
 ,cl.CompanyName as [Client Name]  
 ,cl.CustomerID as [Client ID]  
 ,p.ClientProjectNumber [Client Project Number]  
 ,ps.ProjectStatus as [Project Status]  
 ,pbs.ProjectBillingStatus as [Project Billing Status]  
 ,pt.ProjectTypeName as [Project Type]  
 ,pt.ProjectTypeColor as [Project Type Color]  
 ,p.StatusNotes as [Project Status Note]  
 ,p.DetailedNotes as [Project Status Description]  
 ,p.ProjectCloseDate as [Project Close Date]  
 ,Case p.Active When 1 then ''YES'' else ''NO'' end as [Active]  
 ,p.StartDate as [Project Start Date]  
 ,p.CompleteDate as [Project Due Date]  
  
 ,Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project]  
 ,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]  
  
  
  
  
  
 ,cp.CampaignName as [Campaign Name]  
 ,cp.CampaignID as [Campaign ID]  
 ,cs.SegmentName as [Campaign Segment]  
 ,cs.PlanStart as [Campaign Segment Start Date]  
 ,cs.PlanComplete as [Campaign Segment Due Date]  
 ,o.OfficeName as [Office]  
 ,o.OfficeColor as [Office Color]  
 ,t.TaskID as [Task ID]  
 ,t.TaskName as [Task Name]  
 ,t.Description as [Task Description]  
 ,tat.TaskAssignmentType as [Task Type]  
 ,Case ISNULL(t.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable]  
 ,Case ISNULL(t.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Task Taxable 2]  
 ,t.PlanStart as [Plan Start Date]  
 ,t.PlanComplete as [Plan Completion Date]  
 ,t.ActStart as [Actual Start Date]  
 ,t.ActComplete as [Actual Completion Date]  
 ,t.PercComp as [Percentage Complete]  
 ,t.BaseStart as [Baseline Start Date]  
 ,t.BaseComplete as [Baseline Completion Date]  
 ,Case t.MoneyTask When 1 then ''YES'' else ''NO'' end as [Track Budgets]  
 ,Case t.ScheduleTask When 1 then ''YES'' else ''NO'' end as [Track Schedules]  
 ,t.EstHours as [Original Budget Hours]  
 ,t.EstLabor as [Original Budget Labor]  
 ,t.BudgetExpenses as [Original Budget Net Expense]  
 ,t.EstExpenses as [Original Budget Gross Expense]  
 ,t.ApprovedCOHours as [Approved Change Order Hours]  
 ,t.ApprovedCOLabor as [Approved Change Order Labor]  
 ,t.ApprovedCOExpense as [Approved Change Order Gross Expense]  
 ,Case t.PredecessorsComplete When 1 then ''YES'' else ''NO'' end as [Predecessors Completed]  
 ,Case t.ExcludeFromStatus When 1 then ''YES'' else ''NO'' end as [Exclude From Status]  
 ,ISNULL(lt.ActualTaskLaborTotal, 0) as [Actual Task Labor Total]  
 ,ISNULL(lt.ActualTaskLaborHours, 0) as [Actual Task Labor Hours]  
 ,ISNULL(alt.ActualTaskAssignmentLaborTotal, 0) as [Actual Task Assignment Labor Total]  
 ,ISNULL(alt.ActualTaskAssignmentLaborHours, 0) as [Actual Task Assignment Labor Hours]  
 ,ISNULL((Select Sum(ActualHours) from tTime (nolock) Where ISNULL(tTime.DetailTaskKey, tTime.TaskKey) = t.TaskKey and tTime.UserKey = tu.UserKey AND tTime.WorkDate BETWEEN tuh.BucketStart AND DATEADD(DAY, 6, tuh.BucketStart)), 0) as [Actual Task Assignment Week Labor Hours]  
 ,u.UserName AS [Assigned User]  
 ,taun.Description [Default Service]  
 ,taun.Title [Title]  
 ,glc.GLCompanyID AS [Default GLCompany ID]  
 ,glc.GLCompanyID + '' - '' + glc.GLCompanyName AS [Default GLCompany Full Name]  
 ,ISNULL(d.DepartmentName, sd.DepartmentName) as [User Department]  
 ,ISNULL(d.DepartmentColor, sd.DepartmentColor) as [User Department Color]  
 ,Case ISNULL(t.HideFromClient, 0) When 1 then ''YES'' else ''NO'' end as [Hide From Client]  
 ,t.TaskName as [Assignment Subject]  
 ,t.DueBy as [Due By]  
 ,CAST(t.Description as varchar(4000)) as [Description of Work]  
 ,tu.ActStart as [Assignment Actual Start Date]  
 ,tu.ActComplete as [Assignment Actual Completion Date]  
 ,ISNULL(tu.APlanStart, t.PlanStart) as [Assignment Plan Start Date]  
 ,ISNULL(tu.APlanComplete, t.PlanComplete) as [Assignment Plan Completion Date]  
 ,t.PlanDuration as [Assignment Duration]  
 ,t.DisplayOrder as [Assignment Work Order]  
 ,t.AssignedNames as [All Assigned People]  
 ,tu.PercComp as [Assignment Percentage Complete]  
 ,se.ServiceCode as [Service Code]
 ,se.Description as [Role]  
 ,se.Description as [Service]  
 ,se.ServiceColor as [Service Color]  
 ,wt.WorkTypeID as [Billing Item Code]
 ,wt.WorkTypeName as [Billing Item Name]
 ,t.Comments as [Assignment Comments]  
 ,t.UserChangedDate as [Date Task Assigned]  
 ,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Account Manager]  
 ,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]  
 ,tu.CompletedByDate as [Time Completed]  
 ,tu.Hours as [Allocated Hours]  
 ,LTRIM(RTRIM(ISNULL(tsu.FirstName + '' '','''')  + ISNULL(tsu.LastName,''''))) AS [Time Completed By]  
 ,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Billing Contact]  
 ,u3.UserName as [Key People 1]  
 ,u4.UserName as [Key People 2]  
 ,u5.UserName as [Key People 3]  
 ,u6.UserName as [Key People 4]  
 ,u7.UserName as [Key People 5]  
 ,u8.UserName as [Key People 6]  
 ,glcp.GLCompanyID as [Company ID]  
 ,glcp.GLCompanyName as [Company Name]  
 ,cla.ClassID as [Class ID]  
 ,cla.ClassName as [Class Name]  
 ,t.ProjectOrder as Row  
 ,CASE t.ScheduleTask  
  WHEN 1 THEN t.PlanDuration  
  ELSE NULL  
 END AS [Task Days]  
 ,tp.PriorityName AS [Task Priority]  
 ,st.TaskID as [Summary Task ID]  
 ,st.TaskName as [Summary Task Name]  
 ,Case ISNULL(st.Taxable, 0) When 1 then ''YES'' else ''NO'' end as [Summary Taxable]  
 ,Case ISNULL(st.Taxable2, 0) When 1 then ''YES'' else ''NO'' end as [Summary Taxable 2]  
 ,p.ProjectKey
 ,t.TaskKey
 ,cd.DivisionID as [Client Division ID]  
    ,cd.DivisionName as [Client Division]  
    ,pc.ProductID as [Client Product ID]  
    ,pc.ProductName as [Client Product]  
 ,ts.SegmentName as [Timeline Segment]  
 ,ts.SegmentColor as [Timeline Segment Color]  
 ,team.TeamName as [Team Name]  
  
 ,Case When tu.ManualAdjustment = 1 then ''Manually Adjusted'' else ''Automatically Adjusted'' end as [Adjustment Type]  
 ,tuh.Hours AS [Week Hours]  
 ,CASE  
  WHEN tuh.BucketStart < DATEADD(DAY, -6, GETDATE()) THEN 0 --If it''s a previous bucket, show 0 so that the numbers are not double dipped with the Actual Hours from the previous weeks  
  ELSE tuh.Hours  
 END AS [Week Hours Current And Future]  
 ,tuh.BucketStart as [Week Start Date]  
 ,ISNULL(tuh.AHourlyRate, 0) [Week Rate]  
 ,ISNULL(tuh.AHourlyRate, 0) * tuh.Hours as [Week Gross]  
 ,ISNULL(u.HourlyCost, 0) * tuh.Hours as [Week Net]  
 ,YEAR(tuh.BucketStart) as [Year]  
 ,Case When MONTH(tuh.BucketStart) = 1 then tuh.Hours else 0 end as [January Hours]  
 ,Case When MONTH(tuh.BucketStart) = 2 then tuh.Hours else 0 end as [February Hours]  
 ,Case When MONTH(tuh.BucketStart) = 3 then tuh.Hours else 0 end as [March Hours]  
 ,Case When MONTH(tuh.BucketStart) = 4 then tuh.Hours else 0 end as [April Hours]  
 ,Case When MONTH(tuh.BucketStart) = 5 then tuh.Hours else 0 end as [May Hours]  
 ,Case When MONTH(tuh.BucketStart) = 6 then tuh.Hours else 0 end as [June Hours]  
 ,Case When MONTH(tuh.BucketStart) = 7 then tuh.Hours else 0 end as [July Hours]  
 ,Case When MONTH(tuh.BucketStart) = 8 then tuh.Hours else 0 end as [August Hours]  
 ,Case When MONTH(tuh.BucketStart) = 9 then tuh.Hours else 0 end as [September Hours]  
 ,Case When MONTH(tuh.BucketStart) = 10 then tuh.Hours else 0 end as [October Hours]  
 ,Case When MONTH(tuh.BucketStart) = 11 then tuh.Hours else 0 end as [November Hours]  
 ,Case When MONTH(tuh.BucketStart) = 12 then tuh.Hours else 0 end as [December Hours]  
 ,Case t.TaskConstraint  
  When 0 then case when p.ScheduleDirection = 1 then ''As Soon As Possible'' else ''As Late as Possible'' end  
  When 1 then ''Must Start On''  
  When 2 then ''Must Finish On''  
  When 3 then ''Finish No Earlier Than''  
  When 4 then ''Finish No Later Than''  
  When 5 then ''Start No Earlier Than''  
  When 6 then ''Start No Later Than''  
  When 7 then ''Duration of Project''  
  else ''''  
 end as [Constraint]  
 ,msvn.UserName as [My Supervisor]  
 ,p.ClientNotes as [Project Client Notes]  
 ,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')  
  FROM  
   tTaskPredecessor tpi (nolock)  
   INNER JOIN tTask ti (nolock) ON tpi.PredecessorKey = ti.TaskKey  
  WHERE tpi.TaskKey = t.TaskKey  
  ORDER BY ti.TaskID  
     FOR XML PATH('''')) ,1,1,''''))), '''') AS [Predecessor]  
 ,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(ti.TaskID, '''') + '' - ''  + ISNULL(ti.TaskName,'''')  
  FROM  
   tTaskPredecessor tpi (nolock)  
   INNER JOIN tTask ti (nolock) ON tpi.TaskKey = ti.TaskKey  
  WHERE tpi.PredecessorKey = t.TaskKey  
  ORDER BY ti.TaskID  
     FOR XML PATH('''')) ,1,1,''''))), '''') AS [Successor]  
 ,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' +  ISNULL(tut.TeamName, '''')  
  FROM  
   tTeamUser tutu (nolock)  
   INNER JOIN tTeam tut (nolock) ON tutu.TeamKey = tut.TeamKey  
  WHERE tutu.UserKey = tu.UserKey  
  ORDER BY tut.TeamName  
     FOR XML PATH('''')) ,1,1,''''))), '''') AS [Team Names]  
 ,p.PercComp as [Project Percent Complete]  
 ,t.ProjectOrder as [Task Line Number]  
 ,Case tu.ManualAdjustment When 1 then ''YES'' else ''NO'' end as [Manually Adjusted Buckets]  
 ,tu.TaskUserKey
 ,tu.UserKey AS EmployeeKey -- keeps api consistent 
 ,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
 ,ISNULL(CASE p.GetRateFrom
		WHEN 2 THEN p.HourlyRate 
		WHEN 3 THEN u.HourlyRate
		WHEN 4 THEN 
			(SELECT 
					CASE
						WHEN u.RateLevel = 1
							THEN se.HourlyRate1
						WHEN u.RateLevel = 2
							THEN ISNULL(se.HourlyRate2,se.HourlyRate1)
						WHEN u.RateLevel = 3
							THEN ISNULL(se.HourlyRate3,se.HourlyRate1)
						WHEN u.RateLevel = 4
							THEN ISNULL(se.HourlyRate4,se.HourlyRate1)
						WHEN u.RateLevel = 5
							THEN ISNULL(se.HourlyRate5,se.HourlyRate1)
					END)
		WHEN 5 THEN 
			(SELECT 
					CASE
						WHEN u.RateLevel = 1
							THEN (SELECT HourlyRate1 FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 2
							THEN (SELECT ISNULL(HourlyRate2,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 3
							THEN (SELECT ISNULL(HourlyRate3,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 4
							THEN (SELECT ISNULL(HourlyRate4,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
						WHEN u.RateLevel = 5
							THEN (SELECT ISNULL(HourlyRate5,HourlyRate1) FROM tTimeRateSheetDetail (nolock) WHERE ServiceKey = se.ServiceKey AND TimeRateSheetKey = p.TimeRateSheetKey)
					END)
		WHEN 6 THEN t.HourlyRate
		WHEN 9 THEN (SELECT HourlyRate FROM tTitle (nolock) WHERE TitleKey = u.TitleKey)
		WHEN 10 THEN 
				CASE 
					WHEN ISNULL((SELECT HourlyRate FROM tTitleRateSheetDetail (nolock) WHERE TitleRateSheetKey = p.TitleRateSheetKey),'''') = ''''
						THEN (SELECT HourlyRate FROM tTitle (nolock) WHERE TitleKey = u.TitleKey)
					ELSE
						(SELECT HourlyRate FROM tTitleRateSheetDetail (nolock) WHERE TitleRateSheetKey = p.TitleRateSheetKey)
				END
	END, u.HourlyRate) AS [Billable Rate]
From  
 tProject p (nolock)  
 inner join tTask t with (nolock, index= tTask51) on p.ProjectKey = t.ProjectKey  
 left outer join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey  
 left outer join vTaskUserHour tuh (nolock) on tu.TaskUserKey = tuh.TaskUserKey  
 left outer join vUserName u on tu.UserKey = u.UserKey  
 left outer join tUser tsu (nolock) on tu.CompletedByKey = tsu.UserKey  
 inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey  
 left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey  
 left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey  
 left outer join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey  
 left outer join tOffice o (nolock) on p.OfficeKey = o.OfficeKey  
 left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey  
 left outer join tUser u2 (nolock) on p.AccountManager = u2.UserKey  
 left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey  
 left outer join tTaskAssignmentType tat (nolock) on t.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey  
 left outer join vUserName u3 on p.KeyPeople1 = u3.UserKey  
 left outer join vUserName u4 on p.KeyPeople2 = u4.UserKey  
 left outer join vUserName u5 on p.KeyPeople3 = u5.UserKey  
 left outer join vUserName u6 on p.KeyPeople4 = u6.UserKey  
 left outer join vUserName u7 on p.KeyPeople5 = u7.UserKey  
 left outer join vUserName u8 on p.KeyPeople6 = u8.UserKey  
 left outer join vUserName taun (nolock) on tu.UserKey = taun.UserKey  
 left outer join vUserName msvn (nolock) on u.MySupervisorKey = msvn.UserKey  
 left outer join tClass cla (nolock) on p.ClassKey = cla.ClassKey  
 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 tDepartment d (nolock) on u.DepartmentKey = d.DepartmentKey  
 left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey  
 left outer join tService se (nolock) on tu.ServiceKey = se.ServiceKey  
 left outer join tWorkType wt (nolock) on se.WorkTypeKey = wt.WorkTypeKey
 left outer join tDepartment sd (nolock) on se.DepartmentKey = sd.DepartmentKey  
 left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey  
 left outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey  
 left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey  
    left outer join tClientProduct  pc (nolock) on p.ClientProductKey  = pc.ClientProductKey  
 left outer join tTimelineSegment ts (nolock) on t.TimelineSegmentKey = ts.TimelineSegmentKey  
 left outer join tTeam team on p.TeamKey =  team.TeamKey   
 left outer join tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey  
 left outer join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey  
 LEFT OUTER JOIN (  
     SELECT  ISNULL(DetailTaskKey, TaskKey) AS TaskKey, Sum(ActualHours) AS ActualTaskLaborHours, Sum(ActualHours * ActualRate) AS ActualTaskLaborTotal  
     FROM  tTimeRollupDetail (NOLOCK)   
     GROUP BY ISNULL(DetailTaskKey, TaskKey)   
     ) lt ON lt.TaskKey = t.TaskKey  
  
    LEFT OUTER JOIN (  
     SELECT  ISNULL(DetailTaskKey, TaskKey) AS TaskKey, UserKey, Sum(ActualHours) AS ActualTaskAssignmentLaborHours, Sum(ActualHours * ActualRate) AS ActualTaskAssignmentLaborTotal  
     FROM  tTimeRollupDetail (NOLOCK)  
     GROUP BY ISNULL(DetailTaskKey, TaskKey), UserKey  
     ) alt ON alt.TaskKey = t.TaskKey AND alt.UserKey = tu.UserKey  
  
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetDashboard]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetDashboard]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[spApiAIGetDashboard]
(
    @CompanyKey         int,
    @UserKey            int,
    @AsOfDate           datetime    = null,       -- defaults today UTC
    @GLCompanyID        varchar(50) = null,       -- optional single GL company filter
    @PipelineWindowDays int         = 7,          -- "this period" window for new + closed-won counts
    @CashCompareDaysBack int        = 7,          -- WoW cash delta default
    @LowCashThreshold   money       = 25000.00    -- below this, cash severity = yellow
)
as --Encrypt

/*
|| When      Who Rel        What
|| 05/24/26  AI  26.05.24   Created — financial dashboard aggregator.
||                          Headlines-only view. Produces 10 result sets in one round trip:
||                          warnings, meta, cash, arSummary, arBuckets, arTopOverdue,
||                          apSummary, apBuckets, revenue, pipeline.
||                          For per-record drill-in callers must use the focused tools
||                          (get_ar_aging, get_overdue_invoices, get_corporate_pl, etc.).
||                          The handler additionally pulls a pending-approval count from
||                          spAppApprovalGetList and stitches it into the response.
*/

set nocount on

    declare @SecurityGroupKey     int
    declare @IsAdministrator      bit
    declare @RestrictToGLCompany  tinyint
    declare @HomeCurrencyID       varchar(10)
    declare @CanRunDashboard      bit
    declare @GLCompanyKeyResolved int

    -- Derived dates
    declare @EndDate           datetime,
            @MTDStart          datetime,
            @PriorMTDStart     datetime,
            @PriorMTDEnd       datetime,
            @YTDStart          datetime,
            @PriorYTDStart     datetime,
            @PriorYTDEnd       datetime,
            @CashPriorAsOf     datetime,
            @PipelineWindowStart datetime

    if @AsOfDate is null
        set @AsOfDate = dbo.fFormatDateNoTime(getutcdate())

    if @PipelineWindowDays is null or @PipelineWindowDays < 0
        set @PipelineWindowDays = 7
    if @CashCompareDaysBack is null or @CashCompareDaysBack < 0
        set @CashCompareDaysBack = 7

    set @EndDate             = @AsOfDate
    set @MTDStart            = dateadd(day, 1 - day(@AsOfDate), @AsOfDate)
    set @PriorMTDEnd         = dateadd(day, -1, @MTDStart)
    set @PriorMTDStart       = dateadd(day, 1 - day(@PriorMTDEnd), @PriorMTDEnd)
    set @YTDStart            = cast(cast(year(@AsOfDate) as varchar(4)) + ''-01-01'' as datetime)
    set @PriorYTDStart       = dateadd(year, -1, @YTDStart)
    set @PriorYTDEnd         = dateadd(year, -1, @AsOfDate)
    set @CashPriorAsOf       = dateadd(day, -@CashCompareDaysBack, @AsOfDate)
    set @PipelineWindowStart = dateadd(day, -@PipelineWindowDays, @AsOfDate)

    -- ------------------------------------------------------------------
    -- 1. Errors / warnings staging
    -- ------------------------------------------------------------------
    select * into #errors from tAPIErrorTemplate where 1 = 2

    -- ------------------------------------------------------------------
    -- 2. Load user
    -- ------------------------------------------------------------------
    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
        drop table #errors
        return -101
    end

    -- ------------------------------------------------------------------
    -- 3. Right check — permissive (any major financial right qualifies, plus useLeads for pipeline)
    -- ------------------------------------------------------------------
    set @CanRunDashboard = 0
    if @IsAdministrator = 1
        set @CanRunDashboard = 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 (
              ''acct_gl_balsheet'', ''acct_gl_trailbal'', ''acct_gl_pl_ytd'',
              ''acct_ar_aging'',    ''acct_ar_invoicesummary'', ''billingviewclientinvoice'',
              ''acct_ap_aging'',    ''acct_ap_payjournal''
          )
    )
        set @CanRunDashboard = 1

    if @CanRunDashboard = 0
    begin
        insert into #errors (errorType, errorCode, errorMessage, fieldName)
        values (''error'', ''ACCESS_DENIED'', ''User does not have permission to view the financial dashboard.'', ''general'')

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

    -- ------------------------------------------------------------------
    -- 4. Preferences
    -- ------------------------------------------------------------------
    select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0),
           @HomeCurrencyID      = CurrencyID
    from tPreference (nolock)
    where CompanyKey = @CompanyKey

    set @RestrictToGLCompany = ISNULL(@RestrictToGLCompany, 0)

    -- ------------------------------------------------------------------
    -- 5. Resolve GLCompanyID → key
    -- ------------------------------------------------------------------
    if @GLCompanyID is not null and LTRIM(RTRIM(@GLCompanyID)) <> ''''
    begin
        select @GLCompanyKeyResolved = GLCompanyKey
        from tGLCompany (nolock)
        where CompanyKey = @CompanyKey and UPPER(GLCompanyID) = UPPER(@GLCompanyID)

        if @GLCompanyKeyResolved is null
            insert into #errors (errorType, errorCode, errorMessage, fieldName)
            values (''warning'', ''NOT_FOUND'', ''GL Company not found: '' + @GLCompanyID + '' — filter ignored.'', ''glCompanyID'')
    end

    -- ------------------------------------------------------------------
    -- 6. Result set 0: warnings
    -- ------------------------------------------------------------------
    select errorType    as errorType,
           errorCode    as errorCode,
           errorMessage as errorMessage,
           fieldName    as fieldName
    from #errors
    where errorType = ''warning''

    -- ------------------------------------------------------------------
    -- 7. Result set 1: meta
    -- ------------------------------------------------------------------
    select
        convert(varchar(19), getutcdate(), 126) + ''Z''   as asOf,
        @CompanyKey                                     as companyKey,
        ISNULL(@HomeCurrencyID, '''')                     as currency,
        convert(varchar(10), @EndDate,         23)      as endDate,
        convert(varchar(10), @MTDStart,        23)      as mtdStart,
        convert(varchar(10), @PriorMTDStart,   23)      as priorMtdStart,
        convert(varchar(10), @PriorMTDEnd,     23)      as priorMtdEnd,
        convert(varchar(10), @YTDStart,        23)      as ytdStart,
        convert(varchar(10), @PriorYTDStart,   23)      as priorYtdStart,
        convert(varchar(10), @PriorYTDEnd,     23)      as priorYtdEnd,
        convert(varchar(10), @CashPriorAsOf,   23)      as cashPriorAsOf,
        @CashCompareDaysBack                            as cashCompareDaysBack,
        convert(varchar(10), @PipelineWindowStart, 23)  as pipelineWindowStart,
        @PipelineWindowDays                             as pipelineWindowDays

    -- ------------------------------------------------------------------
    -- 8. Result set 2: cash
    --     Bank balance = SUM(Debit - Credit) from tTransaction for AccountType=10.
    --     Match the sptGLAccountGetBalance convention.
    -- ------------------------------------------------------------------
    ;with bankAccts as (
        select gl.GLAccountKey
        from tGLAccount gl (nolock)
        where gl.CompanyKey  = @CompanyKey
          and gl.AccountType = 10
          and gl.Active      = 1
    ),
    balances as (
        select t.GLAccountKey,
               SUM(case when t.TransactionDate <= @EndDate
                        then ISNULL(t.Debit, 0) - ISNULL(t.Credit, 0) else 0 end) as CurrentBal,
               SUM(case when t.TransactionDate <= @CashPriorAsOf
                        then ISNULL(t.Debit, 0) - ISNULL(t.Credit, 0) else 0 end) as PriorBal
        from tTransaction t (nolock)
        where t.CompanyKey   = @CompanyKey
          and t.GLAccountKey in (select GLAccountKey from bankAccts)
          and (@GLCompanyKeyResolved is null or t.GLCompanyKey = @GLCompanyKeyResolved)
          and (
              @IsAdministrator = 1 or @RestrictToGLCompany = 0
              or t.GLCompanyKey in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
          )
        group by t.GLAccountKey
    )
    select
        ROUND(ISNULL(SUM(CurrentBal), 0), 2)                       as totalBalance,
        ROUND(ISNULL(SUM(PriorBal),   0), 2)                       as priorTotalBalance,
        ROUND(ISNULL(SUM(CurrentBal) - SUM(PriorBal), 0), 2)       as totalDelta,
        (select COUNT(*) from bankAccts)                           as accountCount,
        ISNULL(SUM(case when CurrentBal < 0 then 1 else 0 end), 0) as overdrawnCount,
        case
            when ISNULL(SUM(case when CurrentBal < 0 then 1 else 0 end), 0) > 0 then ''red''
            when ISNULL(SUM(CurrentBal), 0) < @LowCashThreshold              then ''yellow''
            else                                                                  ''green''
        end                                                        as severity
    from balances

    -- ------------------------------------------------------------------
    -- 9. AR — gather open invoices into a temp for reuse across RS 3-5
    -- ------------------------------------------------------------------
    create table #AR (
        InvoiceKey      int            null,
        InvoiceNumber   varchar(35)    null,
        ClientKey       int            null,
        ClientName      nvarchar(200)  null,
        DueDate         smalldatetime  null,
        OpenAmount      money          null,
        DaysOverdue     int            null,
        Bucket          varchar(10)    null
    )

    insert into #AR (InvoiceKey, InvoiceNumber, ClientKey, ClientName, DueDate, OpenAmount, DaysOverdue, Bucket)
    select
        i.InvoiceKey,
        i.InvoiceNumber,
        i.ClientKey,
        c.CompanyName,
        i.DueDate,
        i.InvoiceTotalAmount - ISNULL(i.AmountReceived, 0) - ISNULL(i.RetainerAmount, 0),
        case when i.DueDate >= @EndDate then 0 else DATEDIFF(day, i.DueDate, @EndDate) end,
        case
            when i.DueDate >= @EndDate                       then ''current''
            when DATEDIFF(day, i.DueDate, @EndDate) <= 30    then ''0-30''
            when DATEDIFF(day, i.DueDate, @EndDate) <= 60    then ''31-60''
            when DATEDIFF(day, i.DueDate, @EndDate) <= 90    then ''61-90''
            else                                                  ''90+''
        end
    from tInvoice i (nolock)
    left join tCompany c (nolock) on i.ClientKey = c.CompanyKey
    where i.CompanyKey      = @CompanyKey
      and i.InvoiceStatus   = 4
      and i.InvoiceDate    <= @EndDate
      and (i.InvoiceTotalAmount - ISNULL(i.AmountReceived, 0) - ISNULL(i.RetainerAmount, 0)) > 0
      and (@GLCompanyKeyResolved is null or i.GLCompanyKey = @GLCompanyKeyResolved)
      and (
          @IsAdministrator = 1 or @RestrictToGLCompany = 0
          or ISNULL(i.GLCompanyKey, 0) in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
      )

    -- ------------------------------------------------------------------
    -- 10. Result set 3: AR summary
    -- ------------------------------------------------------------------
    ;with arAgg as (
        select
            ISNULL(SUM(OpenAmount), 0)                                                  as totalOpen,
            ISNULL(SUM(case when DaysOverdue > 30 then OpenAmount else 0 end), 0)       as seriousOverdueAmount,
            ISNULL(SUM(case when DaysOverdue >  0 then OpenAmount else 0 end), 0)       as overdueAmount,
            COUNT(*)                                                                    as openInvoiceCount,
            SUM(case when DaysOverdue > 0 then 1 else 0 end)                            as overdueInvoiceCount
        from #AR
    )
    select
        ROUND(totalOpen,            2) as totalOpen,
        ROUND(overdueAmount,        2) as overdueAmount,
        ROUND(seriousOverdueAmount, 2) as seriousOverdueAmount,
        openInvoiceCount               as openInvoiceCount,
        overdueInvoiceCount            as overdueInvoiceCount,
        case
            when seriousOverdueAmount > 0 then ''red''
            when overdueAmount        > 0 then ''yellow''
            else                              ''green''
        end                            as severity
    from arAgg

    -- ------------------------------------------------------------------
    -- 11. Result set 4: AR buckets (always 5 rows in fixed order)
    -- ------------------------------------------------------------------
    ;with bucketDef as (
        select 1 ord, ''current'' bucket  union all
        select 2,     ''0-30''            union all
        select 3,     ''31-60''           union all
        select 4,     ''61-90''           union all
        select 5,     ''90+''
    )
    select
        b.bucket                                                            as bucket,
        ROUND(ISNULL(SUM(ar.OpenAmount), 0), 2)                             as openAmount,
        COUNT(ar.InvoiceKey)                                                as invoiceCount
    from bucketDef b
    left join #AR ar on ar.Bucket = b.bucket
    group by b.ord, b.bucket
    order by b.ord

    -- ------------------------------------------------------------------
    -- 12. Result set 5: AR top overdue (up to 5 invoices)
    -- ------------------------------------------------------------------
    select top 5
        InvoiceNumber                                                       as invoiceNumber,
        ClientKey                                                           as clientKey,
        ClientName                                                          as clientName,
        ROUND(OpenAmount, 2)                                                as openAmount,
        DaysOverdue                                                         as daysOverdue,
        Bucket                                                              as bucket
    from #AR
    where DaysOverdue > 0
    order by OpenAmount desc, DaysOverdue desc

    -- ------------------------------------------------------------------
    -- 13. AP — gather open vouchers into temp
    -- ------------------------------------------------------------------
    create table #AP (
        VoucherKey      int            null,
        VendorKey       int            null,
        DueDate         smalldatetime  null,
        OpenAmount      money          null,
        DaysOverdue     int            null,
        Bucket          varchar(10)    null
    )

    insert into #AP (VoucherKey, VendorKey, DueDate, OpenAmount, DaysOverdue, Bucket)
    select
        v.VoucherKey,
        v.VendorKey,
        v.DueDate,
        v.VoucherTotal - ISNULL(v.AmountPaid, 0),
        case when v.DueDate >= @EndDate then 0 else DATEDIFF(day, v.DueDate, @EndDate) end,
        case
            when v.DueDate >= @EndDate                       then ''current''
            when DATEDIFF(day, v.DueDate, @EndDate) <= 30    then ''0-30''
            when DATEDIFF(day, v.DueDate, @EndDate) <= 60    then ''31-60''
            when DATEDIFF(day, v.DueDate, @EndDate) <= 90    then ''61-90''
            else                                                  ''90+''
        end
    from tVoucher v (nolock)
    where v.CompanyKey       = @CompanyKey
      and v.InvoiceDate     <= @EndDate
      and (v.VoucherTotal - ISNULL(v.AmountPaid, 0)) > 0
      and (@GLCompanyKeyResolved is null or v.GLCompanyKey = @GLCompanyKeyResolved)
      and (
          @IsAdministrator = 1 or @RestrictToGLCompany = 0
          or ISNULL(v.GLCompanyKey, 0) in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
      )

    -- ------------------------------------------------------------------
    -- 14. Result set 6: AP summary
    -- ------------------------------------------------------------------
    ;with apAgg as (
        select
            ISNULL(SUM(OpenAmount), 0)                                                  as totalOwed,
            ISNULL(SUM(case when DaysOverdue > 30 then OpenAmount else 0 end), 0)       as seriousOverdueAmount,
            ISNULL(SUM(case when DaysOverdue >  0 then OpenAmount else 0 end), 0)       as overdueAmount,
            COUNT(*)                                                                    as openVoucherCount,
            SUM(case when DaysOverdue > 0 then 1 else 0 end)                            as overdueVoucherCount
        from #AP
    )
    select
        ROUND(totalOwed,            2) as totalOwed,
        ROUND(overdueAmount,        2) as overdueAmount,
        ROUND(seriousOverdueAmount, 2) as seriousOverdueAmount,
        openVoucherCount               as openVoucherCount,
        overdueVoucherCount            as overdueVoucherCount,
        case
            when seriousOverdueAmount > 0 then ''red''
            when overdueAmount        > 0 then ''yellow''
            else                              ''green''
        end                            as severity
    from apAgg

    -- ------------------------------------------------------------------
    -- 15. Result set 7: AP buckets
    -- ------------------------------------------------------------------
    ;with bucketDef as (
        select 1 ord, ''current'' bucket  union all
        select 2,     ''0-30''            union all
        select 3,     ''31-60''           union all
        select 4,     ''61-90''           union all
        select 5,     ''90+''
    )
    select
        b.bucket                                                            as bucket,
        ROUND(ISNULL(SUM(ap.OpenAmount), 0), 2)                             as openAmount,
        COUNT(ap.VoucherKey)                                                as voucherCount
    from bucketDef b
    left join #AP ap on ap.Bucket = b.bucket
    group by b.ord, b.bucket
    order by b.ord

    -- ------------------------------------------------------------------
    -- 16. Result set 8: revenue (MTD + YTD with prior-period comparison)
    --     Source: tInvoice Approved + Posted, AdvanceBill = 0
    -- ------------------------------------------------------------------
    ;with revAgg as (
        select
            SUM(case when i.InvoiceDate between @MTDStart      and @EndDate      then i.InvoiceTotalAmount else 0 end) as mtdRevenue,
            SUM(case when i.InvoiceDate between @PriorMTDStart and @PriorMTDEnd  then i.InvoiceTotalAmount else 0 end) as priorMtdRevenue,
            SUM(case when i.InvoiceDate between @YTDStart      and @EndDate      then i.InvoiceTotalAmount else 0 end) as ytdRevenue,
            SUM(case when i.InvoiceDate between @PriorYTDStart and @PriorYTDEnd  then i.InvoiceTotalAmount else 0 end) as priorYtdRevenue
        from tInvoice i (nolock)
        where i.CompanyKey       = @CompanyKey
          and i.InvoiceStatus    = 4
          and i.Posted           = 1
          and ISNULL(i.AdvanceBill, 0) = 0
          and i.InvoiceDate between @PriorYTDStart and @EndDate
          and (@GLCompanyKeyResolved is null or i.GLCompanyKey = @GLCompanyKeyResolved)
          and (
              @IsAdministrator = 1 or @RestrictToGLCompany = 0
              or ISNULL(i.GLCompanyKey, 0) in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)
          )
    )
    select
        ROUND(ISNULL(mtdRevenue,      0), 2)                                              as mtdRevenue,
        ROUND(ISNULL(priorMtdRevenue, 0), 2)                                              as priorMtdRevenue,
        ROUND(ISNULL(mtdRevenue, 0) - ISNULL(priorMtdRevenue, 0), 2)                      as mtdDelta,
        ROUND(ISNULL(ytdRevenue,      0), 2)                                              as ytdRevenue,
        ROUND(ISNULL(priorYtdRevenue, 0), 2)                                              as priorYtdRevenue,
        ROUND(ISNULL(ytdRevenue, 0) - ISNULL(priorYtdRevenue, 0), 2)                      as ytdDelta,
        case
            when ISNULL(priorMtdRevenue, 0) = 0                                              then ''green''
            when (ISNULL(mtdRevenue, 0) - ISNULL(priorMtdRevenue, 0)) / NULLIF(ISNULL(priorMtdRevenue, 0), 0) < -0.05 then ''red''
            when (ISNULL(mtdRevenue, 0) - ISNULL(priorMtdRevenue, 0)) < 0                    then ''yellow''
            else                                                                                  ''green''
        end                                                                               as severity
    from revAgg

    -- ------------------------------------------------------------------
    -- 17. Result set 9: pipeline (active leads + new + closed-won in window)
    -- ------------------------------------------------------------------
    ;with active as (
        select
            ISNULL(SUM(l.SaleAmount), 0)                                          as openTotal,
            ISNULL(SUM(l.SaleAmount * ISNULL(l.Probability, 0) / 100.0), 0)       as openWeighted,
            COUNT(*)                                                              as openCount
        from tLead l (nolock)
        inner join tLeadStatus ls (nolock) on l.LeadStatusKey = ls.LeadStatusKey
        where l.CompanyKey = @CompanyKey
          and ISNULL(ls.LeadStatusActive, 0) = 1
          and (@GLCompanyKeyResolved is null or l.GLCompanyKey = @GLCompanyKeyResolved)
    ),
    newWindow as (
        select COUNT(*) as newCount
        from tLead l (nolock)
        where l.CompanyKey = @CompanyKey
          and l.DateAdded between @PipelineWindowStart and @EndDate
          and (@GLCompanyKeyResolved is null or l.GLCompanyKey = @GLCompanyKeyResolved)
    ),
    closedWon as (
        select
            COUNT(*)                                          as closedWonCount,
            ISNULL(SUM(l.SaleAmount), 0)                      as closedWonAmount
        from tLead l (nolock)
        inner join tLeadStatus ls  (nolock) on l.LeadStatusKey  = ls.LeadStatusKey
        left  join tLeadOutcome lo (nolock) on l.LeadOutcomeKey = lo.LeadOutcomeKey
        where l.CompanyKey = @CompanyKey
          and ISNULL(ls.LeadStatusActive, 0) = 0
          and ISNULL(lo.PositiveOutcome,  0) = 1
          and l.ActualCloseDate between @PipelineWindowStart and @EndDate
          and (@GLCompanyKeyResolved is null or l.GLCompanyKey = @GLCompanyKeyResolved)
    )
    select
        ROUND(a.openTotal,       2)                                  as openTotal,
        ROUND(a.openWeighted,    2)                                  as openWeighted,
        a.openCount                                                  as openCount,
        n.newCount                                                   as newInWindow,
        cw.closedWonCount                                            as closedWonInWindow,
        ROUND(cw.closedWonAmount, 2)                                 as closedWonAmountInWindow,
        @PipelineWindowDays                                          as windowDays,
        case
            when a.openCount       = 0 then ''red''
            when cw.closedWonCount = 0 and n.newCount = 0 then ''yellow''
            else                            ''green''
        end                                                          as severity
    from active a
    cross join newWindow n
    cross join closedWon cw

    -- ------------------------------------------------------------------
    drop table #AP
    drop table #AR
    drop table #errors

    return 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateSectionUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateSectionUpdate]', 'P') IS NULL
EXEC sp_executesql N'

CREATE PROCEDURE [dbo].[sptEmailTemplateSectionUpdate]
	@CompanyKey int,
	@EmailTemplateKey int,
	@EmailTemplateSectionKey int = 0,
	@EmailTemplateSectionDefKey int = NULL,
	@SectionName nvarchar(500) = NULL,
	@PromptText nvarchar(max) = NULL,
	@DisplayOrder int = 0,
	@Active tinyint = 1
AS --Encrypt

  /*
  || When		Who		Rel     What
  || 04/10/2026	MAS	??		Created	
  */

-- Validate template belongs to company
IF NOT EXISTS (
	SELECT 1
	FROM tEmailTemplate (NOLOCK)
	WHERE EmailTemplateKey = @EmailTemplateKey
	  AND CompanyKey = @CompanyKey
)
	RETURN -1

IF @EmailTemplateSectionKey > 0
	BEGIN
		-- Update existing section (ensure it belongs to this template + company)
		UPDATE ets
		SET
			-- ets.EmailTemplateSectionDefKey = @EmailTemplateSectionDefKey,
			ets.SectionName = @SectionName,
			ets.PromptText = @PromptText,
			ets.DisplayOrder = @DisplayOrder,
			-- ets.Active = @Active,
			ets.DateUpdated = GETDATE()
		FROM tEmailTemplateSection ets
		JOIN tEmailTemplate et
			ON et.EmailTemplateKey = ets.EmailTemplateKey
		WHERE
			ets.EmailTemplateSectionKey = @EmailTemplateSectionKey
			AND ets.EmailTemplateKey = @EmailTemplateKey
			AND et.CompanyKey = @CompanyKey

		IF @@ROWCOUNT = 0
			RETURN -2

		RETURN @EmailTemplateSectionKey
	END
ELSE
	BEGIN
		IF @Active IS NULL
			SELECT @Active = 1

		INSERT tEmailTemplateSection
			(
			EmailTemplateKey,
			EmailTemplateSectionDefKey,
			SectionName,
			PromptText,
			DisplayOrder,
			--Active,
			DateAdded,
			DateUpdated
			)
		VALUES
			(
			@EmailTemplateKey,
			@EmailTemplateSectionDefKey,
			@SectionName,
			@PromptText,
			@DisplayOrder,
			--@Active,
			GETDATE(),
			GETDATE()
			)

		SELECT @EmailTemplateSectionKey = @@IDENTITY

		RETURN @EmailTemplateSectionKey
	END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateSectionDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateSectionDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptEmailTemplateSectionDelete]
    @CompanyKey        INT,
    @EmailTemplateSectionKey  INT
AS --Encrypt

/*
|| When			Who Rel		What
|| 04/10/2026	MAS	??		Created	
*/

BEGIN
    SET NOCOUNT ON;

    DELETE ets
    FROM tEmailTemplateSection ets
    INNER JOIN tEmailTemplate et 
        ON et.EmailTemplateKey = ets.EmailTemplateKey
    WHERE et.CompanyKey = @CompanyKey
      AND ets.EmailTemplateSectionKey = @EmailTemplateSectionKey;
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE Procedure [dbo].[sptEmailTemplateUpdate]
(
	@CompanyKey int,
	@EmailTemplateKey int = 0,
	@EmailTemplateName varchar(200),
	@Description varchar(200),
	@Active smallint
)

AS --Encrypt

/*
|| When		    Who Rel	    What
|| 04/10/2026	MAS	??		(729070) Created	
*/

IF @EmailTemplateKey > 0
	BEGIN
		UPDATE tEmailTemplate
		SET 
            EmailTemplateName = @EmailTemplateName,
			Description = @Description,
			Active = @Active,
            DateUpdated = GETDATE() -- Updates the timestamp on modification
		WHERE EmailTemplateKey = @EmailTemplateKey
		
		RETURN @EmailTemplateKey
	END
ELSE
	BEGIN
		IF @Active IS NULL
			SELECT @Active = 1

		INSERT tEmailTemplate
		(
			CompanyKey,
			EmailTemplateName,
			Description,
			DateAdded,
			DateUpdated,
			Active
		)
		VALUES
		(
			@CompanyKey,
			@EmailTemplateName,
			@Description,
			GETDATE(), -- Sets the creation date
			GETDATE(), -- Sets the initial update date
			@Active
		)
		
		SELECT @EmailTemplateKey = @@IDENTITY
        RETURN @EmailTemplateKey -- Good practice to return the new ID
	END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateGetList]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGetList]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptEmailTemplateGetList]
	@CompanyKey int,
	@IncludeInActive int = 0

AS --Encrypt  --Recompile

/*
|| When		    Who Rel	    What
|| 04/10/2026	MAS	??		Created	
*/

SELECT *
FROM tEmailTemplate
WHERE CompanyKey = @CompanyKey
-- If @IncludeInActive is true (1), it shows everything.
-- If @IncludeInActive is false (0), it only shows records where Active = 1.
AND (@IncludeInActive = 1 OR Active = 1)
ORDER By DateAdded 
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptRecurTranGenerateInvoice]'
GO
IF OBJECT_ID(N'[dbo].[sptRecurTranGenerateInvoice]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[sptRecurTranGenerateInvoice]
	(
	@CurrInvoiceKey int
	,@CompanyKey int
	,@NewInvoiceDate datetime	-- for invoice record
	,@CreateAsApproved int
	,@ProjectRollup int = 1
	
	,@RecurTranKey int
	,@NextDate datetime			-- for recur tran record
	,@NextNumberRemaining int	-- for recur tran record
	,@NewApproverKey int = 0
	)
AS --Encrypt

	SET NOCOUNT ON
	
  /*
  || When     Who Rel    What
  || 02/22/10 GHL 10.519 Creation for new recurring logic
  || 03/22/12 GWG 10.554 Added TargetGLCompanyKey to the copy
  || 09/19/13 MFT 10.572 (190447) Added	LayoutKey in INSERT statement
  || 09/27/13 GHL 10.572 Added currency info
  || 01/03/14 WDF 10.576 (188500) Added CreatedByKey, DateCreated to Insert tInvoice
  || 04/27/18 GHL 18.500 Set DateCreated = getdate()
  || 01/23/19 GHL 19.200 (441702) Added missing fields such as CampaignKey, RetainerKey, MediaEstimateKey, AlternatePayerKey, BillingGroupKey 
  || 02/27/19 MCM 19.300 (447674) Added error if project is closed
  || 11/04/20 RLB 20.1.2 (531678) added new approver option
  || 06/06/22 GHL 22.6.0 (451878) added GLC currency info
  || 03/10/26 MCM 26.03.x (724010) added LiabilityAccountKey
  || 04/21/26 AMP 26.05.17(718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
  */
  
	-- Constants
	declare @kErrInvoiceNotFound int		select @kErrInvoiceNotFound = 0
	declare @kErrValidateUseDetail int		select @kErrValidateUseDetail = -1
	declare @kErrGetTranNumber int			select @kErrGetTranNumber = -2
	declare @kErrUnexpected int				select @kErrUnexpected = -10
	declare @kErrProjectClosed int			select @kErrProjectClosed = -15

	if isnull(@CurrInvoiceKey, 0) <= 0
		return @kErrInvoiceNotFound

	-- Vars
	declare @RetVal int
	declare @Error int
	
	declare @NewInvoiceKey int
	declare @NewInvoiceLineKey int	
	declare @NewDueDate datetime
	declare @CurrInvoiceLineKey int	
	declare @CurrInvoiceDate datetime
	declare @CurrDueDate datetime
	declare @CurrDiffDays int
	declare @RecurringParentKey int

	-- Multi currency info
	declare @GLCompanyKey int
	declare @MultiCurrency int
	declare @HomeCurrencyID varchar(10)
	declare @CurrencyID varchar(10)
	declare @ExchangeRate decimal(24,7) 
	declare @RateHistory int
	declare @AdvanceBill int
	
	select 	@CurrInvoiceDate = i.InvoiceDate
			,@CurrDueDate = i.DueDate
			,@RecurringParentKey = i.RecurringParentKey
			,@GLCompanyKey = i.GLCompanyKey
			,@CurrencyID = i.CurrencyID
			,@HomeCurrencyID = pref.CurrencyID
			,@MultiCurrency = isnull(pref.MultiCurrency, 0)
			,@AdvanceBill = i.AdvanceBill
	from	tInvoice i (nolock)
		inner join tPreference pref (nolock) on i.CompanyKey = pref.CompanyKey
	where	i.InvoiceKey = @CurrInvoiceKey
	
	if @@ROWCOUNT = 0
		return @kErrInvoiceNotFound
	
	Select @CurrDiffDays = datediff(d, @CurrInvoiceDate, @CurrDueDate)
	Select @NewDueDate = dateadd(d, @CurrDiffDays, @NewInvoiceDate)
			
	-- perform validation, cannot be recurring if the invoice has transaction details
	If Exists(Select 1 from tInvoiceLine (NOLOCK) Where InvoiceKey = @CurrInvoiceKey and BillFrom = 2)
		return @kErrValidateUseDetail 	

	-- check to see if the project is closed
	if Exists (SELECT 1 from tInvoice i (NOLOCK) JOIN tProject p on i.ProjectKey = p.ProjectKey WHERE i.InvoiceKey = @CurrInvoiceKey AND p.Closed = 1)
		return @kErrProjectClosed
	
	-- logic for invoice number and approval
	declare @SetInvoiceNumberOnApproval int, @InvoiceNumberRequired int, @NextTranNo VARCHAR(100)
	  	
	Select @SetInvoiceNumberOnApproval = ISNULL(SetInvoiceNumberOnApproval, 0)
	from tPreference (NOLOCK) 
	Where CompanyKey = @CompanyKey

	-- Only case when Invoice Number is not required
	If @SetInvoiceNumberOnApproval = 1 And @CreateAsApproved = 0
		Select @InvoiceNumberRequired = 0
	Else
		Select @InvoiceNumberRequired = 1

	Begin Tran
	
	IF @InvoiceNumberRequired = 1
	 BEGIN					
		DECLARE @TranType varchar(10) = CASE @AdvanceBill WHEN 1 THEN ''AdvBill'' ELSE ''AR'' END
			EXEC spGetNextTranNo
				@CompanyKey,
				@TranType,
				@RetVal		      OUTPUT,
				@NextTranNo 	  OUTPUT	
		IF @RetVal <> 1
		Begin
			Rollback Tran
			RETURN @kErrGetTranNumber
		End
	END
	
	if isnull(@RecurringParentKey, 0) = 0
	begin
		Update tInvoice Set RecurringParentKey = @CurrInvoiceKey Where InvoiceKey = @CurrInvoiceKey
		if @@ERROR <> 0 
		begin
			rollback tran
			return @kErrUnexpected					   	
		end
	end
	

	select @ExchangeRate = 1

	if @MultiCurrency = 1 And  @CurrencyID is not null And @CurrencyID <> @HomeCurrencyID 
		exec sptCurrencyGetRate @CompanyKey, @GLCompanyKey, @CurrencyID, @NewInvoiceDate, @ExchangeRate output, @RateHistory output


	-- Invoice header
	INSERT tInvoice
	(
		CompanyKey,
		ClientKey,
		ContactName,
		BillingContactKey,
		AdvanceBill,
		InvoiceNumber,
		InvoiceDate,
		PostingDate,
		DueDate,
		RecurringParentKey,
		TermsKey,
		ARAccountKey,
		GLCompanyKey,
		OfficeKey,
		ClassKey,
		ProjectKey,
		RetainerAmount,
		WriteoffAmount,
		DiscountAmount,
		SalesTaxAmount,
		SalesTax1Amount,
		SalesTax2Amount,
		TotalNonTaxAmount,
		InvoiceTotalAmount,
		AmountReceived,
		HeaderComment,
		SalesTaxKey,
		SalesTax2Key,
		InvoiceStatus,
		ApprovedDate,
		ApprovedByKey,
		ApprovalComments,
		Posted,
		Downloaded,
		RetainerKey,
		InvoiceTemplateKey,
		LayoutKey,
		CampaignKey,
		MediaEstimateKey,
		AlternatePayerKey,
		BillingGroupKey,
		UserDefined1,
		UserDefined2,
		UserDefined3,
		UserDefined4,
		UserDefined5,
		UserDefined6,
		UserDefined7,
		UserDefined8,
		UserDefined9,
		UserDefined10,
		PrimaryContactKey,
		CurrencyID,
		ExchangeRate,
		CreatedByKey,
		DateCreated,
		GLCCurrencyID,
		GLCExchangeRate,
		LiabilityAccountKey
	)
	Select
		CompanyKey,
		ClientKey,
		ContactName,
		BillingContactKey,
		AdvanceBill,
		RTRIM(@NextTranNo),
		@NewInvoiceDate,
		@NewInvoiceDate,
		@NewDueDate,
		RecurringParentKey,
		TermsKey,
		ARAccountKey,
		GLCompanyKey,
		OfficeKey,
		ClassKey,
		ProjectKey,
		0,
		0,
		DiscountAmount,
		SalesTaxAmount,
		SalesTax1Amount,
		SalesTax2Amount,
		TotalNonTaxAmount,
		InvoiceTotalAmount,
		0,
		HeaderComment,
		SalesTaxKey,
		SalesTax2Key,
		case when @CreateAsApproved = 1 then 4 else 1 end, --InvoiceStatus
		case when @CreateAsApproved = 1 then dbo.fFormatDateNoTime(GETDATE()) else null end, --ApprovedDate,
		case when @NewApproverKey > 0 then @NewApproverKey else ApprovedByKey end,
		null, --ApprovalComments,
		0,
		0,
		RetainerKey,
		InvoiceTemplateKey,
		LayoutKey,
		CampaignKey,
		MediaEstimateKey,
		AlternatePayerKey,
		BillingGroupKey,
		UserDefined1,
		UserDefined2,
		UserDefined3,
		UserDefined4,
		UserDefined5,
		UserDefined6,
		UserDefined7,
		UserDefined8,
		UserDefined9,
		UserDefined10,
		PrimaryContactKey,
		CurrencyID,
		@ExchangeRate, -- new exchange rate for the day
		CreatedByKey,
		GETDATE(),
		GLCCurrencyID,
		GLCExchangeRate,
		LiabilityAccountKey
	From tInvoice (nolock) Where InvoiceKey = @CurrInvoiceKey
	
	select @Error = @@ERROR, @NewInvoiceKey = @@Identity
	
	if @Error <> 0 
	begin
		rollback tran
		return @kErrUnexpected				   	
	end
			
	-- Invoice lines
	exec @RetVal = sptInvoiceGenerateRecurringLines @CurrInvoiceKey, @NewInvoiceKey, 0 , 0
	if @RetVal <> 1 
	begin
		rollback tran
		return @kErrUnexpected				   	
	end
	
	-- Recur tran record, but check if it exists so that CMP can reuse
	if isnull(@RecurTranKey, 0) > 0
	begin		
		update tRecurTran
		set    NextDate = @NextDate, NumberRemaining = @NextNumberRemaining 
		where  RecurTranKey = @RecurTranKey
		
		if @@ERROR <> 0 
		begin
			rollback tran
			return @kErrUnexpected				   	
		end
	end		
			
	Commit Tran

	-- Rollups do not have to be in transaction
	
	exec sptInvoiceSummary @NewInvoiceKey	 
	
	If @ProjectRollup = 1
	begin
		-- Rollup for entity @InvoiceKey since same projects have been copied from that invoice to the other ones
		EXEC sptProjectRollupUpdateEntity ''tInvoice'', @CurrInvoiceKey
	end
	
	RETURN @NewInvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateGet]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGet]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptEmailTemplateGet]
	@CompanyKey int,
	@EmailTemplateKey int

AS --Encrypt

/*
|| When			Who Rel		What
|| 04/10/2026	MAS	??		Created	
*/

SELECT *
FROM tEmailTemplate (nolock)
WHERE CompanyKey = @CompanyKey
AND EmailTemplateKey = @EmailTemplateKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateSectionGetList]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateSectionGetList]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptEmailTemplateSectionGetList]
	@CompanyKey int,
	@EmailTemplateKey int

AS --Encrypt

/*
|| When			Who Rel		What
|| 04/10/2026	MAS	??		Created	
*/

SELECT ets.*
FROM tEmailTemplateSection ets WITH (NOLOCK)
JOIN tEmailTemplate et WITH (NOLOCK)
  ON et.EmailTemplateKey = ets.EmailTemplateKey
WHERE et.CompanyKey = @CompanyKey
  AND ets.EmailTemplateKey = @EmailTemplateKey
ORDER BY ets.DisplayOrder'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateGetProjectDetail]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGetProjectDetail]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptEmailTemplateGetProjectDetail]
    (
        @ProjectKey     int,
        @UserKey        int
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 04/16/26  AI  26.04.16   Created to support project_progress email template
|| 05/04/26  AI  26.xx.xx   Added project status name to result set
*/

Declare @CompanyKey             int
Declare @SecurityGroupKey       int
Declare @IsAdministrator        tinyint
Declare @CheckAssignment        int
Declare @RestrictToGLCompany    int

-- Derive CompanyKey from the project (also implicitly validates the project exists)
Select  @CompanyKey = CompanyKey
From    tProject (nolock)
Where   ProjectKey = @ProjectKey

If @CompanyKey Is Null
    Return

-- Get user security profile
Select  @SecurityGroupKey   = SecurityGroupKey,
        @IsAdministrator    = Administrator
From    tUser (nolock)
Where   UserKey    = @UserKey
And     CompanyKey = @CompanyKey

-- Project assignment check (administrators bypass)
If @IsAdministrator = 0
Begin
    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
    Begin
        If Not Exists (
            Select  1
            From    tAssignment (nolock)
            Where   ProjectKey = @ProjectKey
            And     UserKey    = @UserKey
        )
            Return
    End
End

-- GL Company security
Select  @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
From    tPreference (nolock)
Where   CompanyKey = @CompanyKey

Select  p.ProjectKey                                    as projectKey
        ,p.ProjectName                                  as projectName
        ,p.ProjectNumber                                as projectNumber
        ,p.PercComp                                     as percentComplete
        ,p.StartDate                                    as startDate
        ,p.CompleteDate                                 as completeDate
        ,p.StatusNotes                                  as statusNotes
        ,p.DetailedNotes                                as nextSteps
        ,p.ClientNotes                                  as clientNotes
        ,ps.ProjectStatus                               as statusName

        -- Completed: task is 100% done or has an actual complete date 
        ,(
            Select  Count(*)
            From    tTask t (nolock)
            Where   t.ProjectKey = @ProjectKey
            And     t.TaskType   = 2
            And     t.PercComp   = 100
        )                                               as completedTaskCount

        -- In Progress: started but not yet complete, and not overdue
        ,(
            Select  Count(*)
            From    tTask t (nolock)
            Where   t.ProjectKey  = @ProjectKey
            And     t.TaskType    = 2
            And     t.PercComp    > 0
            And     t.PercComp    < 100
            And     t.ActComplete Is Null
            And     (t.PlanComplete Is Null Or t.PlanComplete >= Cast(GetDate() As Date))
        )                                               as inProgressTaskCount

        -- Overdue: past planned completion date and not yet finished
        ,(
            Select  Count(*)
            From    tTask t (nolock)
            Where   t.ProjectKey  = @ProjectKey
            And     t.TaskType    = 2
            And     t.PercComp    < 100
            And     t.ActComplete Is Null
            And     t.PlanComplete < Cast(GetDate() As Date)
        )                                               as overdueTaskCount

From    tProject p (nolock)
Left Join tProjectStatus ps (nolock) On p.ProjectStatusKey = ps.ProjectStatusKey
Where   p.CompanyKey = @CompanyKey
And     p.ProjectKey = @ProjectKey
And     p.Deleted    = 0
And     (
            @RestrictToGLCompany = 0
            Or p.GLCompanyKey In (
                Select  GLCompanyKey
                From    tUserGLCompanyAccess (nolock)
                Where   UserKey = @UserKey
            )
        )

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateGetEvents]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGetEvents]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[sptEmailTemplateGetEvents]
(
    @ProjectKey int,
    @UserKey int
)
AS

-- Upcoming calendar events linked to this project
-- First leg: non-recurring events and first occurrence of recurring events (stored in tCalendar)
Select  cal.Subject                                     as eventName
        ,cal.EventStart                                 as eventDate
        ,cal.EventEnd                                   as eventEnd
        ,cal.Location                                   as location
        ,t.TaskName                                     as taskName
        ,t.TaskID                                       as taskID
        ,att.attendeeNames
From    tCalendar cal (nolock)
Left Outer Join tTask t (nolock) On t.TaskKey = cal.TaskKey
Cross Apply (
    Select STUFF((
        Select '', '' + u.FirstName + '' '' + u.LastName
        From   tCalendarAttendee ca (nolock)
        Join   tUser u (nolock) On u.UserKey = ca.EntityKey
        Where  ca.CalendarKey = cal.CalendarKey
        And    ca.Entity in (''Organizer'', ''Attendee'')
        For XML Path(''''), Type
    ).value(''.'', ''nvarchar(max)''), 1, 2, '''') as attendeeNames
) att
Where   cal.ProjectKey  = @ProjectKey
And     cal.EventStart  >= Cast(GetDate() As Date)

Union All

-- Second leg: subsequent occurrences of recurring events (stored in tCalendarCache)
Select  cal.Subject                                     as eventName
        ,cc.EventStart                                  as eventDate
        ,cc.EventEnd                                    as eventEnd
        ,cal.Location                                   as location
        ,t.TaskName                                     as taskName
        ,t.TaskID                                       as taskID
        ,att.attendeeNames
From    tCalendar cal (nolock)
Inner Join tCalendarCache cc (nolock) On cc.CalendarKey = cal.CalendarKey
Left Outer Join tTask t (nolock) On t.TaskKey = cal.TaskKey
Cross Apply (
    Select STUFF((
        Select '', '' + u.FirstName + '' '' + u.LastName
        From   tCalendarAttendee ca (nolock)
        Join   tUser u (nolock) On u.UserKey = ca.EntityKey
        Where  ca.CalendarKey = cal.CalendarKey
        And    ca.Entity  in (''Organizer'', ''Attendee'')
        For XML Path(''''), Type
    ).value(''.'', ''nvarchar(max)''), 1, 2, '''') as attendeeNames
) att
Where   cal.ProjectKey  = @ProjectKey
And     cc.EventStart   >= Cast(GetDate() As Date)

Order By eventDate'
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''
    )
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
*/

Declare @ProjectKey       int = null
Declare @ClientKey        int = null
Declare @ProjectTypeKey   int = null
Declare @ProjectStatusKey int = null
Declare @RestrictToGLCompany int, @CheckAssignment int, @SecurityGroupKey int

Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0) from tPreference (nolock) Where CompanyKey = @CompanyKey
Select @SecurityGroupKey = SecurityGroupKey from tUser (nolock) Where UserKey = @UserKey

-- Resolve project number â†’ project key
If @ProjectNumber is not null
    Select  @ProjectKey = ProjectKey
    From    tProject (nolock)
    Where   CompanyKey    = @CompanyKey
    and     ProjectNumber = @ProjectNumber

-- Resolve client: match CustomerID first, fall back to CompanyName
If @ClientID is not null
    Select  @ClientKey = CompanyKey
    From    tCompany (nolock)
    Where   OwnerCompanyKey = @CompanyKey
    and     (CustomerID = @ClientID or CompanyName = @ClientID)

-- Resolve project type: match ProjectTypeName
If @ProjectType is not null
    Select  @ProjectTypeKey = ProjectTypeKey
    From    tProjectType (nolock)
    Where   CompanyKey = @CompanyKey
    and     (ProjectTypeName = @ProjectType)

-- Resolve project status: match ProjectStatusID or ProjectStatus name
If @ProjectStatus is not null
    Select  @ProjectStatusKey = ProjectStatusKey
    From    tProjectStatus (nolock)
    Where   CompanyKey = @CompanyKey
    and     (ProjectStatusID = @ProjectStatus or ProjectStatus = @ProjectStatus)



-- -----------------------------------------------------------------------
-- Build #projectKeys: the set of ProjectKeys that satisfy all conditions
-- -----------------------------------------------------------------------
Create Table #projectKeys (ProjectKey int not null)

If @Filter = ''over_budget''
Begin
    -- Projects where actual gross costs exceed total budgeted gross
    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
    -- Projects whose due date has passed and are still open
    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
    -- Projects where (billed - actual cost) / budget < 10%
    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  -- margin below 10%
End
Else
Begin
    -- No filter: all open projects for the company (with optional param narrowing)
    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

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)


select @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'')
    
        select @CheckAssignment = 0

if @CheckAssignment = 1
    Delete #projectKeys Where ProjectKey not in (select ProjectKey from tAssignment Where UserKey = @UserKey)


-- -----------------------------------------------------------------------

Select
     pr.ProjectNumber                                                               as ProjectNumber
    ,ISNULL(pr.ProjectName, '''')                                                     as ProjectName
    ,pr.ProjectNumber + '' '' + ISNULL(pr.ProjectName, '''')                           as ProjectFullName
    ,ISNULL(pr.Description, '''')                                                     as Description

    -- Client / ownership
    ,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

    -- Status
    ,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

    -- Dates
    ,ISNULL(pr.StartDate, '''')                                                       as StartDate
    ,CASE
        WHEN YEAR(pr.CompleteDate) <= 1900 THEN NULL
        ELSE pr.CompleteDate
     END                                                                             as DueDate

    -- Budget (original + approved change orders)
    ,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

    -- Actuals (lifetime cumulative from rollup)
    ,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

    -- Billed / unbilled
    ,ISNULL(roll.BilledAmount, 0)                                                   as AmountBilled
    ,ISNULL(roll.LaborUnbilled, 0)
        + ISNULL(roll.MiscCostUnbilled, 0)
        + ISNULL(roll.ExpReceiptUnbilled, 0)
        + ISNULL(roll.VoucherUnbilled, 0)                                          as UnbilledTotal

    -- Margin: billed minus actual cost
    ,ISNULL(roll.BilledAmount, 0)
        - (ISNULL(roll.LaborNet, 0)
           + ISNULL(roll.MiscCostNet, 0)
           + ISNULL(roll.ExpReceiptNet, 0)
           + ISNULL(roll.VoucherNet, 0))                                           as Margin

    -- Budget remaining: budget gross minus actual gross
    ,(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

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

RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateGetTaskOverview]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGetTaskOverview]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[sptEmailTemplateGetTaskOverview]
(
    @ProjectKey     int,
    @StartDate      smalldatetime,
    @EndDate        smalldatetime
)
AS

-- ================================================
-- Result Set 1: Completed Tasks in the date window
-- ================================================
Select  t.TaskName                                          as taskName
        ,s.TaskName                                         as summaryTaskName
        ,t.PlanComplete                                     as dueDate
        ,t.ActComplete                                      as completedDate
        ,ISNULL(t.TotalAllocatedHours, 0)                   as allocatedHours
        ,ISNULL(t.TotalActualHours, 0)                      as actualHours
        ,STUFF((
            Select  '', '' + LEFT(ISNULL(u.FirstName,''''), 1) + LEFT(ISNULL(u.LastName,''''), 1)
            From    tTaskUser tu (nolock)
            Join    tUser u (nolock) On u.UserKey = tu.UserKey
            Where   tu.TaskKey = t.TaskKey
            For XML Path(''''), Type
        ).value(''.'', ''nvarchar(max)''), 1, 2, '''')            as assigneeInitials
From    tTask t (nolock)
Left Join tTask s (nolock) On s.TaskKey = t.SummaryTaskKey
Where   t.ProjectKey    = @ProjectKey
And     t.ActComplete   >= @StartDate
And     t.ActComplete   <= @EndDate
--And     t.TaskType      <> 2                                -- Exclude summary tasks
Order By t.ProjectOrder

-- ================================================
-- Result Set 2: Overdue Tasks 
-- (PlanComplete in window, not complete, past today)
-- ================================================
Select  t.TaskName                                          as taskName
        ,s.TaskName                                         as summaryTaskName
        ,t.PlanComplete                                     as dueDate
        ,ISNULL(t.TotalAllocatedHours, 0)                   as allocatedHours
        ,ISNULL(t.TotalActualHours, 0)                      as actualHours
        ,STUFF((
            Select  '', '' + LEFT(ISNULL(u.FirstName,''''), 1) + LEFT(ISNULL(u.LastName,''''), 1)
            From    tTaskUser tu (nolock)
            Join    tUser u (nolock) On u.UserKey = tu.UserKey
            Where   tu.TaskKey = t.TaskKey
            For XML Path(''''), Type
        ).value(''.'', ''nvarchar(max)''), 1, 2, '''')            as assigneeInitials
From    tTask t (nolock)
Left Join tTask s (nolock) On s.TaskKey = t.SummaryTaskKey
Where   t.ProjectKey    = @ProjectKey
And     t.PlanComplete  >= @StartDate
And     t.PlanComplete  <= @EndDate
And     t.ActComplete   Is Null                             -- Not completed
And     t.PlanComplete  < Cast(GetDate() As Date)           -- Past due
--And     t.TaskType      <> 2
Order By t.ProjectOrder

-- ================================================
-- Result Set 3: Upcoming Due Tasks
-- (PlanComplete in window, not complete, still ahead)
-- ================================================
Select  t.TaskName                                          as taskName
        ,s.TaskName                                         as summaryTaskName
        ,t.PlanComplete                                     as dueDate
        ,ISNULL(t.TotalAllocatedHours, 0)                   as allocatedHours
        ,ISNULL(t.TotalActualHours, 0)                      as actualHours
        ,STUFF((
            Select  '', '' + LEFT(ISNULL(u.FirstName,''''), 1) + LEFT(ISNULL(u.LastName,''''), 1)
            From    tTaskUser tu (nolock)
            Join    tUser u (nolock) On u.UserKey = tu.UserKey
            Where   tu.TaskKey = t.TaskKey
            For XML Path(''''), Type
        ).value(''.'', ''nvarchar(max)''), 1, 2, '''')            as assigneeInitials
From    tTask t (nolock)
Left Join tTask s (nolock) On s.TaskKey = t.SummaryTaskKey
Where   t.ProjectKey    = @ProjectKey
And     t.PlanComplete  >= @StartDate
And     t.PlanComplete  <= @EndDate
And     t.ActComplete   Is Null                             -- Not completed
And     t.PlanComplete  >= Cast(GetDate() As Date)          -- Still upcoming
--And     t.TaskType      <> 2
Order By t.ProjectOrder


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptEmailTemplateGetAssignments]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGetAssignments]', 'P') IS NULL
EXEC sp_executesql N'CREATE   Procedure [dbo].[sptEmailTemplateGetAssignments]
(
    @ProjectKey     int,
    @StartDate      smalldatetime,
    @EndDate        smalldatetime,
    @Type 	        varchar(20) = ''completed''
)
AS

if Lower(@Type) = ''completed''
BEGIN
    -- Completed tasks: completed in the date window
    Select  u.FirstName + '' '' + u.LastName                      as assigneeName
            ,t.TaskName                                         as taskName
            ,s.TaskName                                         as summaryTaskName
            ,t.PlanComplete                                     as plannedDueDate
            ,tu.ActComplete                                     as actualCompleteDate
            ,tu.Comments                                        as comments
    From    tTaskUser tu (nolock)
    Join    tTask t (nolock)     On t.TaskKey   = tu.TaskKey
    Join    tUser u (nolock)     On u.UserKey   = tu.UserKey
    Left Join tTask s (nolock)   On s.TaskKey   = t.SummaryTaskKey
    Where   t.ProjectKey        = @ProjectKey
    And     tu.ActComplete      >= @StartDate
    And     tu.ActComplete      <= @EndDate
    --And     t.TaskType          <> 2
    Order By u.LastName, u.FirstName, t.PlanComplete, t.TaskName
END

ELSE IF Lower(@Type) = ''overdue''   
BEGIN
    -- Overdue tasks: planned completion in the date window, not completed, past today
    Select  u.FirstName + '' '' + u.LastName                      as assigneeName
            ,t.TaskName                                         as taskName
            ,s.TaskName                                         as summaryTaskName
            ,t.PlanComplete                                     as plannedDueDate
            ,tu.ActComplete                                     as actualCompleteDate
            ,tu.Comments                                        as comments
    From    tTaskUser tu (nolock)
    Join    tTask t (nolock)     On t.TaskKey   = tu.TaskKey
    Join    tUser u (nolock)     On u.UserKey   = tu.UserKey
    Left Join tTask s (nolock)   On s.TaskKey   = t.SummaryTaskKey
    Where   t.ProjectKey        = @ProjectKey
    And     t.PlanComplete     >= @StartDate
    And     t.PlanComplete     <= @EndDate
    And     tu.ActComplete      Is Null
    --And     t.TaskType          <> 2
    Order By u.LastName, u.FirstName, t.PlanComplete, t.TaskName
END
'
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.
*/

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

-- 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

-- 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'Creating [dbo].[sptEmailTemplateSectionGet]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateSectionGet]', 'P') IS NULL
EXEC sp_executesql N'

CREATE PROCEDURE [dbo].[sptEmailTemplateSectionGet]
    @EmailTemplateSectionKey  INT
AS --Encrypt

/*
|| When			Who Rel		What
|| 04/10/2026	MAS	??		Created	
*/

BEGIN
    SET NOCOUNT ON;

    Select * FROM tEmailTemplateSection ets (nolock)
      Where ets.EmailTemplateSectionKey = @EmailTemplateSectionKey;
END
'
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
*/

Declare @TimeSheetKey   int       = null
Declare @CurrentStatus  smallint  = null
Declare @WorkDateDT     smalldatetime

Set @WorkDateDT = CAST(CAST(@WorkDate as date) as smalldatetime)

-- Find the timesheet for the given date — do NOT create a new one
Exec sptTimeSheetGetByDate
    @CompanyKey         = @CompanyKey,
    @UserKey            = @UserKey,
    @Date               = @WorkDateDT,
    @TimeSheetKey       = @TimeSheetKey OUTPUT,
    @CreateNewTimeSheet = 0

If @TimeSheetKey is null
Begin
    Select 0 as submitted, ''No timesheet found for the given date.'' as message
    Return
End

-- Read current status
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
    Return
End

-- Submit (Status 2 = Submitted)
Exec sptTimeSheetUpdateStatus
    @Approver       = @UserKey,
    @TimeSheetKey   = @TimeSheetKey,
    @Status         = 2,
    @SubmittedByKey = @UserKey

Select 1 as submitted, ''Timesheet submitted successfully.'' as message

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
 */

 /*
 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
				 from   #tProject b
				 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'Creating [dbo].[sptEmailTemplateGetDeliverables]'
GO
IF OBJECT_ID(N'[dbo].[sptEmailTemplateGetDeliverables]', 'P') IS NULL
EXEC sp_executesql N'CREATE   PROCEDURE [dbo].[sptEmailTemplateGetDeliverables]
    (
        @ProjectKey int
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 05/07/26  XXX 26.05.07   Created
*/

    Declare @CompanyKey int
    Declare @DefaultDeliverableStatusKey int
    Declare @DefaultStatusName nvarchar(500)

    Select  @CompanyKey = CompanyKey
    From    tProject (nolock)
    Where   ProjectKey = @ProjectKey

    Set @DefaultDeliverableStatusKey =
        (Select DeliverableStatusKey
         From   tDeliverableStatus (nolock)
         Where  CompanyKey = @CompanyKey
           And  DisplayOrder = (
                    Select  Min(DisplayOrder)
                    From    tDeliverableStatus (nolock)
                    Where   CompanyKey = @CompanyKey))

    Select  @DefaultStatusName = StatusName
    From    tDeliverableStatus (nolock)
    Where   DeliverableStatusKey = @DefaultDeliverableStatusKey

    Select  rd.DeliverableName as deliverableName
           ,ISNULL(s.StatusName, @DefaultStatusName) as deliverableStatus
           ,r.RoundName as roundName
           ,Case
                When r.Status = 5 Then Case r.ApprovedWithChanges When 1 Then ''Approved With Changes'' Else ''Approved'' End
                When r.Status = 4 Then ''Cancelled''
                When r.Status = 6 Then ''Paused''
                When r.Status = 3 Then ''Resubmit''
                When r.Status = 2 Then ''Not Sent''
                Else ''Unsubmitted''
            End as roundStatus
           ,(Select STUFF((
                Select  '', '' + RTRIM(LTRIM(ISNULL(u2.FirstName, '''') + '' '' + ISNULL(u2.LastName, '''')))
                From    tReviewDeliverableUsers rdu2 (nolock)
                Inner Join tUser u2 (nolock) On rdu2.UserKey = u2.UserKey
                Where   rdu2.ReviewDeliverableKey = rd.ReviewDeliverableKey
                Order By rdu2.DisplayOrder
                For XML PATH(''''), TYPE).value(''.'', ''nvarchar(max)''), 1, 2, '''')) as reviewerNames
    From    tReviewDeliverable rd (nolock)
    Left Outer Join tDeliverableStatus s (nolock) On ISNULL(rd.DeliverableStatusKey, @DefaultDeliverableStatusKey) = s.DeliverableStatusKey
    Left Outer Join tReviewRound r (nolock) On rd.ReviewDeliverableKey = r.ReviewDeliverableKey And r.LatestRound = 1
    Where   rd.ProjectKey = @ProjectKey
    Order By ISNULL(s.DisplayOrder, 0), rd.DeliverableName, r.RoundName
'
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
	*/

	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 @AdvBillAccountKey int
	declare @DefaultSalesAccountKey int
	declare @PostSalesUsingDetail int
	declare @SalesAccountKey int
	declare @RoundingError money
	declare @SetTaxableOnInvoice int
		
	declare @EntityName	VARCHAR(250)
	declare @LineOrder int

	-- 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)
		      ,@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
			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

				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

				-- 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].[sptInvoiceLineGetOrders]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceLineGetOrders]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptInvoiceLineGetOrders]
	(
		@InvoiceLineKey int,
		@Type smallint,
		@Percentage decimal(24,4)
	)

AS --Encrypt

/*  Who When        Rel       What
||  GHL 04/12/2006  8.3       Changed ISNULL(cm.StationID, c.VendorID) to cm.StationID
||                            United Concepts complained that it was showing wrong Publication or Station
||                            Also causing problems with the report''s groups and sorts
||  GHL 05/19/2006  8.4       Added Vendor info since Nerland did not like the change made in 83 
||  GHL 05/07/2008  8.510     (21995) Added Item for new grouping
||  MFT 01/21/2009  10.0.1.7  Added VendorNameID field (concatentation of VendorID and VendorName)
||  MFT 04/28/2010  10.5.2.2  Split out orders w/ vouchers into seperate unioned query
||  MFT 05/25/2010  10.5.3.0  Removed tVoucherDetail NULL requirment from "top" queries;
||                            Corrected "bottom" queries to match InvoiceLinkKey to tVoucherDetail
||  MFT 11/12/2012  10.5.6.2  Added pod.DetailOrderDate to the ORDER BY 2nd to CompanyMedia.Name 
||  WDF 08/14/2013  10.5.7.1  Added EstimateID
||  MFT 12/04/2013  10.5.7.5  Added pNet and pCommission (197741)
||  AMP 03/25/2021  21.05.16  (545972) Added First Start Date and Last End Date for Broadcast Orders
||  MFT 11/10/2023  23.12.0   (656090) Changed tVoucherDetail join to a derived grouping to eliminate dups;
||                            Fixed other derived join to eliminate SQL aggregate warning
|| AMP  01/09/2026 26.02.15   (712210) Added Media Plan ID - Media Plan Name for the BO/IO SubDetail 
|| AMP  04/24/2026 26.05.17   (726957) Added DetailOrderDateMonthName and DetailOrderDateMonthYear as grouping options for BO/IO
*/ 
declare @IOClientLink smallint
declare @BCClientLink smallint
declare @CompanyKey int

select @CompanyKey = co.CompanyKey
  from tCompany co (nolock) inner join tInvoice inv (nolock) on co.CompanyKey = inv.CompanyKey
       inner join tInvoiceLine invl (nolock) on inv.InvoiceKey = invl.InvoiceKey
 where invl.InvoiceLineKey = @InvoiceLineKey   
       
select @BCClientLink = isnull(BCClientLink,1),
       @IOClientLink = isnull(IOClientLink,1)
  from tPreference (nolock)
 where CompanyKey = @CompanyKey

Select @Percentage = @Percentage / 100

if (@Type = 1 and @IOClientLink = 2) or (@Type = 2 and @BCClientLink = 2) -- link to division & product via estimate
	Select
		pod.*,
		pod.Quantity * @Percentage as pQuantity,
		pod.UnitCost * @Percentage as pUnitCost,
		pod.AmountBilled * @Percentage as pAmountBilled,
		pod.TotalCost * @Percentage as pNet,
		(pod.AmountBilled * @Percentage) - (pod.TotalCost * @Percentage) as pCommission,
		po.PurchaseOrderNumber,
		po.PODate,
		cm.StationID as StationID,
		cm.Name as StationName,
		po.MediaEstimateKey,
		me.EstimateID,
		left(me.EstimateName,100) as EstimateName,
		cp.ClientProductKey,
		left(cp.ProductName,100) as ClientProduct,
		cd.ClientDivisionKey,
		left(cd.DivisionName,100) as ClientDivision,
		mm.MediaMarketKey,
		left(mm.MarketName,100) as MarketName,
		cm.CompanyMediaKey,
		c.CompanyName as VendorName,
		c.CompanyKey as VendorKey,
		c.VendorID as VendorID,
		ISNULL(c.VendorID + ''-'', '''') + ISNULL(c.CompanyName, '''') as VendorNameID,
		i.ItemName,
		i.ItemKey,
		pod1.FirstStartDate,
		pod1.LastStartDate,
		pod1.FirstEndDate, 
		pod1.LastEndDate,
		m.PlanID + ''-'' + m.PlanName as MediaPlanName,
		FORMAT(DetailOrderDate, ''MMMM'') as DetailOrderDateMonthName,
		FORMAT(DetailOrderDate, ''MMMM yyyy'') as DetailOrderDateMonthYear
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tClientProduct cp (nolock) on me.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on me.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
        left outer join tMediaPlanDetail mpd (NOLOCK) ON mpd.MediaPlanDetailKey = pod.MediaPlanDetailKey  
		left outer join tMediaPlanVendor mpv (NOLOCK) ON mpv.MediaPlanVendorKey = mpd.MediaPlanVendorKey
        left outer join tMediaPlan m (NOLOCK) ON mpv.MediaPlanKey = m.MediaPlanKey  
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		INNER JOIN (
			SELECT
				PurchaseOrderKey,
				MIN(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS FirstStartDate, MAX(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS LastStartDate,
				MIN(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) As FirstEndDate, MAX(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) AS LastEndDate
			FROM tPurchaseOrderDetail (nolock)
			GROUP BY PurchaseOrderKey
		) pod1 ON po.PurchaseOrderKey = pod1.PurchaseOrderKey
	Where
		pod.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type AND
		(pod.Quantity <> 0 or pod.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled 		
		
	UNION ALL
		
	Select
		pod.*,
		vd.Quantity * @Percentage as pQuantity,
		vd.UnitCost * @Percentage as pUnitCost,
		vd.AmountBilled * @Percentage as pAmountBilled,
		vd.TotalCost * @Percentage as pNet,
		(vd.AmountBilled * @Percentage) - (vd.TotalCost * @Percentage) as pCommission,
		po.PurchaseOrderNumber,
		po.PODate,
		cm.StationID as StationID,
		cm.Name as StationName,
		po.MediaEstimateKey,
		me.EstimateID,
		left(me.EstimateName,100) as EstimateName,
		cp.ClientProductKey,
		left(cp.ProductName,100) as ClientProduct,
		cd.ClientDivisionKey,
		left(cd.DivisionName,100) as ClientDivision,
		mm.MediaMarketKey,
		left(mm.MarketName,100) as MarketName,
		cm.CompanyMediaKey,
		c.CompanyName as VendorName,
		c.CompanyKey as VendorKey,
		c.VendorID as VendorID,
		ISNULL(c.VendorID + ''-'', '''') + ISNULL(c.CompanyName, '''') as VendorNameID,
		i.ItemName,
		i.ItemKey,
		pod1.FirstStartDate,
		pod1.LastStartDate,
		pod1.FirstEndDate, 
		pod1.LastEndDate,
		m.PlanID + ''-'' + m.PlanName as MediaPlanName,
		FORMAT(DetailOrderDate, ''MMMM'') as DetailOrderDateMonthName,
		FORMAT(DetailOrderDate, ''MMMM yyyy'') as DetailOrderDateMonthYear
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		INNER JOIN (
			SELECT
				InvoiceLineKey, PurchaseOrderDetailKey, UnitCost,
				SUM(Quantity) AS Quantity, SUM(TotalCost) AS TotalCost, SUM(AmountBilled) AS AmountBilled
			FROM tVoucherDetail (nolock)
			GROUP BY InvoiceLineKey, PurchaseOrderDetailKey, UnitCost
		) vd ON pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tClientProduct cp (nolock) on me.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on me.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tMediaPlanDetail mpd (NOLOCK) ON mpd.MediaPlanDetailKey = pod.MediaPlanDetailKey  
		left outer join tMediaPlanVendor mpv (NOLOCK) ON mpv.MediaPlanVendorKey = mpd.MediaPlanVendorKey
        left outer join tMediaPlan m (NOLOCK) ON mpv.MediaPlanKey = m.MediaPlanKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		INNER JOIN (
			SELECT
				PurchaseOrderKey,
				MIN(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS FirstStartDate, MAX(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS LastStartDate,
				MIN(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) As FirstEndDate, MAX(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) AS LastEndDate
			FROM tPurchaseOrderDetail (nolock)
			GROUP BY PurchaseOrderKey
		) pod1 ON po.PurchaseOrderKey = pod1.PurchaseOrderKey
	Where
		vd.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type
		and (vd.Quantity <> 0 or vd.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled 
	Order By cm.Name, pod.DetailOrderDate, po.PODate, po.PurchaseOrderNumber, pod.LineNumber

else  -- link to division & product via project

	Select
		pod.*,
		pod.Quantity * @Percentage as pQuantity,
		pod.UnitCost * @Percentage as pUnitCost,
		pod.AmountBilled * @Percentage as pAmountBilled,
		pod.TotalCost * @Percentage as pNet,
		(pod.AmountBilled * @Percentage) - (pod.TotalCost * @Percentage) as pCommission,
		po.PurchaseOrderNumber,
		po.PODate,
		cm.StationID as StationID,
		cm.Name as StationName,
		po.MediaEstimateKey,
		me.EstimateID,
		left(me.EstimateName,100) as EstimateName,
		cp.ClientProductKey,
		left(cp.ProductName,100) as ClientProduct,
		cd.ClientDivisionKey,
		left(cd.DivisionName,100) as ClientDivision,
		mm.MediaMarketKey,
		left(mm.MarketName,100) as MarketName,
		cm.CompanyMediaKey,
		c.CompanyName as VendorName,
		c.CompanyKey as VendorKey,
		c.VendorID as VendorID,
		ISNULL(c.VendorID + ''-'', '''') + ISNULL(c.CompanyName, '''') as VendorNameID,
		i.ItemName,
		i.ItemKey,
		pod1.FirstStartDate,
		pod1.LastStartDate,
		pod1.FirstEndDate, 
		pod1.LastEndDate,
		m.PlanID + ''-'' + m.PlanName as MediaPlanName,
		FORMAT(DetailOrderDate, ''MMMM'') as DetailOrderDateMonthName,
		FORMAT(DetailOrderDate, ''MMMM yyyy'') as DetailOrderDateMonthYear
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tProject pr (nolock) on pod.ProjectKey = pr.ProjectKey
		left outer join tClientProduct cp (nolock) on pr.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on pr.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tMediaPlanDetail mpd (NOLOCK) ON mpd.MediaPlanDetailKey = pod.MediaPlanDetailKey  
		left outer join tMediaPlanVendor mpv (NOLOCK) ON mpv.MediaPlanVendorKey = mpd.MediaPlanVendorKey
        left outer join tMediaPlan m (NOLOCK) ON mpv.MediaPlanKey = m.MediaPlanKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		INNER JOIN (
			SELECT
				PurchaseOrderKey,
				MIN(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS FirstStartDate, MAX(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS LastStartDate,
				MIN(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) As FirstEndDate, MAX(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) AS LastEndDate
			FROM tPurchaseOrderDetail (nolock)
			GROUP BY PurchaseOrderKey
		) pod1 ON po.PurchaseOrderKey = pod1.PurchaseOrderKey
	Where
		pod.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type AND
		(pod.Quantity <> 0 or pod.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled
				
	UNION ALL

	Select
		pod.*,
		vd.Quantity * @Percentage as pQuantity,
		vd.UnitCost * @Percentage as pUnitCost,
		vd.AmountBilled * @Percentage as pAmountBilled,
		vd.TotalCost * @Percentage as pNet,
		(vd.AmountBilled * @Percentage) - (vd.TotalCost * @Percentage) as pCommission,
		po.PurchaseOrderNumber,
		po.PODate,
		cm.StationID as StationID,
		cm.Name as StationName,
		po.MediaEstimateKey,
		me.EstimateID,
		left(me.EstimateName,100) as EstimateName,
		cp.ClientProductKey,
		left(cp.ProductName,100) as ClientProduct,
		cd.ClientDivisionKey,
		left(cd.DivisionName,100) as ClientDivision,
		mm.MediaMarketKey,
		left(mm.MarketName,100) as MarketName,
		cm.CompanyMediaKey,
		c.CompanyName as VendorName,
		c.CompanyKey as VendorKey,
		c.VendorID as VendorID,
		ISNULL(c.VendorID + ''-'', '''') + ISNULL(c.CompanyName, '''') as VendorNameID,
		i.ItemName,
		i.ItemKey,
		pod1.FirstStartDate,
		pod1.LastStartDate,
		pod1.FirstEndDate, 
		pod1.LastEndDate,
		m.PlanID + ''-'' + m.PlanName as MediaPlanName,
		FORMAT(DetailOrderDate, ''MMMM'') as DetailOrderDateMonthName,
		FORMAT(DetailOrderDate, ''MMMM yyyy'') as DetailOrderDateMonthYear
	From
		tPurchaseOrderDetail pod (nolock)
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		INNER JOIN (
			SELECT
				InvoiceLineKey, PurchaseOrderDetailKey, UnitCost,
				SUM(Quantity) AS Quantity, SUM(TotalCost) AS TotalCost, SUM(AmountBilled) AS AmountBilled
			FROM tVoucherDetail (nolock)
			GROUP BY InvoiceLineKey, PurchaseOrderDetailKey, UnitCost
		) vd ON pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tProject pr (nolock) on pod.ProjectKey = pr.ProjectKey
		left outer join tClientProduct cp (nolock) on pr.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on pr.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tMediaPlanDetail mpd (NOLOCK) ON mpd.MediaPlanDetailKey = pod.MediaPlanDetailKey  
		left outer join tMediaPlanVendor mpv (NOLOCK) ON mpv.MediaPlanVendorKey = mpd.MediaPlanVendorKey
        left outer join tMediaPlan m (NOLOCK) ON mpv.MediaPlanKey = m.MediaPlanKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		INNER JOIN (
			SELECT
				PurchaseOrderKey,
				MIN(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS FirstStartDate, MAX(ISNULL(DetailOrderDate, ''1900-01-01 00:00:00'')) AS LastStartDate,
				MIN(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) As FirstEndDate, MAX(ISNULL(DetailOrderEndDate, ''1900-01-01 00:00:00'')) AS LastEndDate
			FROM tPurchaseOrderDetail (nolock)
			GROUP BY PurchaseOrderKey
		) pod1 ON po.PurchaseOrderKey = pod1.PurchaseOrderKey
	Where
		vd.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type and
		(vd.Quantity <> 0 or vd.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled 
	Order By cm.Name, pod.DetailOrderDate, po.PODate, po.PurchaseOrderNumber, pod.LineNumber'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceSave]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceSave]', 'P') IS NOT NULL
EXEC sp_executesql N'


ALTER PROCEDURE [dbo].[sptInvoiceSave]
	@CompanyKey int,
	@InvoiceKey int,
	@InvoiceStatus smallint, -- just for the inserts
	@ClientKey int,
	@ContactName Varchar(100),
	@PrimaryContactKey int,
	@AddressKey int,
	@AdvanceBill tinyint,
	@InvoiceNumber varchar(35),
	@InvoiceDate smalldatetime,
	@DueDate smalldatetime,
	@PostingDate smalldatetime,
	@TermsKey int,
	@ARAccountKey int, 
	@ClassKey int,
	@ProjectKey int,
	@RetainerAmount money, 
	@WriteoffAmount money,
	@DiscountAmount money,
	@SalesTaxAmount money,
	@SalesTax1Amount money,
	@SalesTax2Amount money,
	@TotalNonTaxAmount money, 
	@InvoiceTotalAmount money,
	@AmountReceived money, 
	@HeaderComment nvarchar(max),
	@SalesTaxKey int,
	@SalesTax2Key int,
	@ApprovedByKey int,
	@InvoiceTemplateKey int,
	@UserDefined1 varchar(250),
	@UserDefined2 varchar(250),
	@UserDefined3 varchar(250),
	@UserDefined4 varchar(250),
	@UserDefined5 varchar(250),
	@UserDefined6 varchar(250),
	@UserDefined7 varchar(250),
	@UserDefined8 varchar(250),
	@UserDefined9 varchar(250),
	@UserDefined10 varchar(250),
	@Downloaded tinyint,
	@Printed tinyint,
	@ParentInvoice tinyint,
	@Emailed tinyint,
	@GLCompanyKey int,
	@OfficeKey int,
	@OpeningTransaction tinyint,
	@LayoutKey int,
	@CampaignKey int,
	@TransactionsUpdated int, -- Transactions have been changed on the UI
	@AlternatePayerKey int,
	@BillingGroupKey int,
	@CurrencyID varchar(10) = null,
    @ExchangeRate decimal(24,7) = 1, 
	@GLCExchangeRate decimal(24,7) = null, -- Rate to convert from CurrencyID to GLCCurrencyID (HC of the gl company) 
    @CreatedByKey int,
	@DeliveryDate smalldatetime = NULL,
	@oIdentity int output

AS --Encrypt

/*
|| When     Who Rel    What
|| 09/01/10 GHL 10.534 Creation for new flex invoice screen
|| 09/17/10 GHL 10.535 Added transactions and taxes
|| 09/21/10 GHL 10.535 Added summary tables
|| 10/07/10 GHL 10.536 Added prepayments
|| 10/08/10 GHL 10.536 Added credits
|| 10/14/10 GHL 10.536 Added adv bills
|| 10/21/10 GHL 10.537 Added validation of adv bills
|| 10/27/10 GHL 10.537 Added splits
|| 10/28/10 GHL 10.537 Added taxes for splits
|| 12/08/10 GHL 10.539 Added campaign key
|| 03/16/11 GHL 10.543 (106374) Project rollup on projects removed from lines
|| 05/25/11 GHL 10.544 (112509) If we are importing, rollup amounts to InvoiceTotalAmount and TotalNonTaxAmount
|| 09/26/11 GHL 10.548 Changed name of #tTransaction to #transaction because trigger tU_tInvoice
||                     references #tTransaction used in spGLPostInvoice with a different definition  
|| 11/11/11 GHL 10.550 (116847) Added precautionary checks before updating tInvoiceAdvanceBill and tInvoiceCredit
|| 12/12/11 GHL 10.550 (128535) Fixed bad join when updating tVoucherDetail records
|| 12/13/11 GHL 10.551 (128621) Added comparison of line.TotalAmount to sum(transactions.AmountBilled)
|| 01/26/12 GHL 10.551  Changed Billfrom to BillFrom
|| 02/24/12 GHL 10.552 (135120) Added recalc of AmountReceived on invoices involved with credits
|| 03/28/12 GHL 10.554 Added saving of TargetGLCompanyKey
|| 04/20/12 GHL 10.555 (140727) Added saving of billed item info
|| 05/22/12 GHL 10.556 (144399) Error out if SalesTaxKey = 0 and SalesTaxAmount <> 0
|| 07/20/12 GHL 10.558 (149227) If AddressKey = 0, set AddressKey = null. VB fixed but deployed SP to alleviate problem
|| 09/11/12 MFT 10.559 Added AlternatePayerKey param and header field
|| 09/20/12 GHL 10.560 (154851) Making sure now that a time entry or an expense is not added twice to a line
|| 09/27/12 GHL 10.560  Added Billing Group info for HMI request
|| 10/10/12 GHL 10.561 (156432) Added a patch to rollup the amounts from the lines to the header
||                     to prevent a company from having problems with a rollup problems in flex
|| 11/20/12 GHL 10.562 (160384) Added a patch to prevent BillFrom = 0 (should be 1 or 2)
|| 11/28/12 GHL 10.562 (160961) Added validation of lines project/company
||                     The project must have a gl comp = header gl comp or line gl comp
|| 02/07/13 GHL 10.564 (167883) Changed Entity to tPurchaseOrderDetail instead of PO
||                     when checking if a po detail is applied to a voucher detail
|| 03/20/13 GHL 10.566 (172334) prevent situation where the records exist in tInvoiceAdvanceBillTax but not in tInvoiceAdvanceBill
|| 05/14/13 GHL 10.567 (177926) Added checking of Line Type before inserting tInvoiceLineTax recs (summary lines should not have any)
|| 05/16/13 GHL 10.567 (178596) Added checking of LineType = 2 when rolling up amounts
|| 05/22/13 GHL 10.568 (179160) Make sure now that amounts on header/invoice are always rolledup from taxes for split invoices 
|| 06/05/13 GHL 10.568 (179672) Checking now if invoice is paid/posted before changing percentage split
|| 07/10/13 KMC 10.570 (183584) Changed the message being returned for duplicate invoice number to @kErrDupInvNumber
||                     from @kErrGetInvNumber
|| 09/12/13 GHL 10.572 (189382) Added checks of tax totals on the lines. Found on AU (Black Sheep) lines with
||                      SalesTaxAmount = 0 and SalesTax1Amount > 0
|| 09/24/13 GHL 10.572 (181928) Added logic for void invoice
|| 09/26/13 GHL 10.572 Added support for multi currency + validation of project currencies on lines and header (should be same)
|| 10/16/13 GHL 10.573 Added tougher check of tax totals on line. Found SalesTaxAmount > 0 and SalesTax1Amount = 0
||                     Now: SalesTaxAmount = SalesTax1Amount + SalesTax2Amount + other taxes
|| 11/07/13 GHL 10.574 pod.AccruedCost must be in HC
|| 01/03/14 WDF 10.576 (188500) Added CreatedByKey, DateCreated to Insert tInvoice
|| 01/17/14 GHL 10.576 Do not allow editing of credits from the regular side if foreign currency is used
||                     because of GL implications on the credit side
|| 02/21/14 GHL 10.577 AR Account must match currency on the header
|| 04/02/14 GHL 10.578  (174684) Allowing adv bill applications of posted regular invoices ( must repost)
|| 05/19/14 GHL 10.580  (216450) Allowing now ICT between regular invoices and adv bills
||                      Removed checks that prevented doing so. Cash basis posting seems OK
|| 08/18/14 GHL 10.582HF1 (226613) Rolled back 174684 because of new issues. Needs to be reviewed
|| 08/29/14 GHL 10.583  (226613) Saving now tInvoiceAdvanceBill.FromAB and allowing applic to posted real inv 
|| 03/09/15 GHL 10.591  Added setting of hours on invoice lines for Abelson taylor
|| 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
|| 08/22/17 GHL 10.619 (359617) Added error when the sales on a real invoice are over applied
|| 09/18/17 GHL 10.619 (363846) Rolledback 359617 because it affects credits 
|| 04/04/18 GHL 18.500 (394616) Removed error -17 because of issue at Altered Image. 
||                      Rolled back because I found out that the error was caused by a voucher detail linked to 3 expense receipts
|| 09/19/18 GHL 18.910 (421536) When removing an adv bill app, recalculate the RetainerAmount on the regular invoices
||                      Right now, it removes the reg invoice but does not recalc
|| 07/14/20 GHL 20.080 (451878) Added update of GLCExchangeRate for GL companies with different home currency
|| 12/11/20 MCM 21.010 (540453) Removed the check for @kErrLinesProjectGLCompany because the front end no longer does this check so the
||						API doesn''t need to either + nvarchar(max) HeaderComments
|| 10/20/21 MFT 21.110  (573836) Added DeliveryDate
|| 04/21/26 AMP 26.05.17(718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
*/

-- Constants
declare @kErrGetInvNumber int				select @kErrGetInvNumber = -1
declare @kErrDupInvNumber int				select @kErrDupInvNumber = -2
declare @kErrTransactionConflict int		select @kErrTransactionConflict = -3
declare @kErrTransactionHasVoucher int		select @kErrTransactionHasVoucher = -4
declare @kErrOverApplied int				select @kErrOverApplied = -5			-- for Advance bill applications
declare @kErrSalesOverApplied int			select @kErrSalesOverApplied = -26		-- for Advance bill applications

declare @kErrAdvBillSalesOverApplied int	select @kErrAdvBillSalesOverApplied = -6
declare @kErrAdvBillNoDeletePosted int      select @kErrAdvBillNoDeletePosted = -7
declare @kErrAdvBillNoChangePosted int      select @kErrAdvBillNoChangePosted = -8
declare @kErrAdvBillOverApplied int	        select @kErrAdvBillOverApplied = -9

declare @kErrChildDelete int                select @kErrChildDelete = -10
declare @kErrChildUpdate int                select @kErrChildUpdate = -19
declare @kErrParentHasAB int                select @kErrParentHasAB = -11
declare @kErrParentHasCredits int           select @kErrParentHasCredits = -12
declare @kErrParentHasReceipts int          select @kErrParentHasReceipts = -13

declare @kErrMissigTrans int				select @kErrMissigTrans = -14
declare @kErrMissingSalesTax int			select @kErrMissingSalesTax = -15
declare @kErrMissingSalesTax2 int			select @kErrMissingSalesTax2 = -16

declare @kErrTransactionDuplicates int		select @kErrTransactionDuplicates = -17
declare @kErrLinesProjectGLCompany int		select @kErrLinesProjectGLCompany = -18
declare @kErrLineTaxes int					select @kErrLineTaxes = -20
declare @kErrLinesProjectCurrency int		select @kErrLinesProjectCurrency = -23
declare @kErrLinesProjectClosed int			select @kErrLinesProjectClosed = -25

declare @kErrVoidPostingDateOrigAfter int	select @kErrVoidPostingDateOrigAfter = -21
declare @kErrVoidPostingDateVoidBefore int	select @kErrVoidPostingDateVoidBefore = -22
declare @kErrARAccountCurrency int			select @kErrARAccountCurrency = -24

-- next error is -27

declare @kErrUnexpected int					select @kErrUnexpected = -99


-- General vars + tPreference
DECLARE @AddMode int
       ,@RetVal	int
       ,@Error int
	   ,@NextTranNo VARCHAR(100)
	   ,@InvoiceNumberRequired INT
	   ,@SetInvoiceNumberOnApproval int
	   ,@Customizations varchar(2000)
       ,@UseGLCompany INT
	   ,@LoopInvoiceKey int
 	   ,@MultiCurrency int 
	   ,@UseBillingTitles int

Declare @CurAdvanceBill tinyint
		,@CurParentInvoice tinyint 
		,@CurRecurParent int
		,@ProjectGLCompanyKey INT
        ,@ParentInvoiceKey INT
        ,@CurSalesTaxKey INT
        ,@CurSalesTax2Key INT
        ,@CurPostingDate smalldatetime
		,@CurPosted int
		,@CurRetainerAmount money
		,@VoidInvoiceKey int

-- Mainly for the Import, error out if SalesTaxAmount > 0 and SalesTaxKey = 0
if isnull(@SalesTaxKey, 0) = 0 and exists (select 1 from #tInvoiceLine where SalesTax1Amount <> 0)
	return @kErrMissingSalesTax
if isnull(@SalesTax2Key, 0) = 0 and exists (select 1 from #tInvoiceLine where SalesTax2Amount <> 0)
	return @kErrMissingSalesTax2

-- issue 189382, validate strictly taxes now
-- SalesTaxAmount = SalesTax1Amount + SalesTax2Amount + other taxes
update #tInvoiceLine
	set    #tInvoiceLine.GPAmount = isnull((
		select sum(tax.SalesTaxAmount) from #tInvoiceLineTax tax
		where  tax.InvoiceLineKey = #tInvoiceLine.InvoiceLineKey
		), 0)
	where LineType = 2 -- detail

if exists (select 1 from  #tInvoiceLine 
	where LineType = 2 -- detail
	and   ABS(isnull(SalesTaxAmount, 0)) <>	ABS(isnull(SalesTax1Amount, 0) + isnull(SalesTax2Amount, 0) + isnull(GPAmount, 0) )
	)
	return @kErrLineTaxes

-- temporary patch, if Null invoice printing will get the client''s address
if @AddressKey = 0
	select @AddressKey = null

Select @UseGLCompany = ISNULL(UseGLCompany, 0)
      ,@Customizations = LOWER(ISNULL(Customizations, ''''))
	  ,@SetInvoiceNumberOnApproval = ISNULL(SetInvoiceNumberOnApproval, 0)
	  ,@MultiCurrency = isnull(MultiCurrency, 0)
	  ,@UseBillingTitles = isnull(UseBillingTitles, 0)
from tPreference (NOLOCK) 
Where CompanyKey = @CompanyKey

if CHARINDEX(''cbre'', @Customizations) = 0
	if exists(Select 1 from tInvoice (nolock) Where CompanyKey = @CompanyKey 
	and rtrim(ltrim(InvoiceNumber)) = @InvoiceNumber and InvoiceKey <> @InvoiceKey)
		return @kErrDupInvNumber

if isnull(@InvoiceKey, 0) <= 0
	select @AddMode = 1
else
	select @AddMode = 0

-- Patch for BillFrom = 0
if exists (select 1 from #tInvoiceLine where LineType = 2 and isnull(BillFrom, 0) not in (1,2))
begin
	update #tInvoiceLine
	set    #tInvoiceLine.BillFrom = 2 -- Use Transactions
	where  isnull(#tInvoiceLine.BillFrom, 0) not in (1,2)
	and    #tInvoiceLine.LineType = 2
	and    exists (select 1 from #transaction where #transaction.InvoiceLineKey = #tInvoiceLine.InvoiceLineKey) 

	update #tInvoiceLine
	set    #tInvoiceLine.BillFrom = 1 -- No Transactions
 	where  isnull(#tInvoiceLine.BillFrom, 0) not in (1,2)
	and    #tInvoiceLine.LineType = 2
	and    not exists (select 1 from #transaction where #transaction.InvoiceLineKey = #tInvoiceLine.InvoiceLineKey) 
end

select @InvoiceNumberRequired = 0
if @SetInvoiceNumberOnApproval = 1 And @InvoiceStatus = 4
	select @InvoiceNumberRequired = 1
if @SetInvoiceNumberOnApproval = 0
	select @InvoiceNumberRequired = 1

 IF @InvoiceNumberRequired = 1
 BEGIN			
	-- Get the next number
	IF @InvoiceNumber IS NULL OR @InvoiceNumber = ''''
	BEGIN
		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 @kErrGetInvNumber
	END
	ELSE
			SELECT @NextTranNo = @InvoiceNumber
END
ELSE
	-- Invoice Number not required
	-- Take null or what user gives us
	SELECT @NextTranNo = @InvoiceNumber
	

Select @CurAdvanceBill = AdvanceBill
     , @CurParentInvoice = ParentInvoice
     , @CurRecurParent = RecurringParentKey
     , @ParentInvoiceKey = ParentInvoiceKey 
     , @CurSalesTaxKey = SalesTaxKey
     , @CurSalesTax2Key = SalesTax2Key
	 , @CurPostingDate = PostingDate
	 , @CurPosted = Posted
	 , @CurRetainerAmount = RetainerAmount
	 , @VoidInvoiceKey = VoidInvoiceKey
	from tInvoice (nolock) Where InvoiceKey = @InvoiceKey

select @CurPosted = isnull(@CurPosted, 0)
       ,@ParentInvoiceKey = isnull(@ParentInvoiceKey, 0)

if @ParentInvoiceKey > 0
begin
	-- this is a split/child invoice
	-- reload the total amounts
	select @TotalNonTaxAmount = isnull(TotalNonTaxAmount, 0)
	      ,@SalesTaxAmount = isnull(SalesTaxAmount, 0) 
	from tInvoice (nolock) Where InvoiceKey = @InvoiceKey
	
	select @InvoiceTotalAmount = isnull(@TotalNonTaxAmount, 0) + isnull(@SalesTaxAmount, 0)
end
 

 -- Now multi currency 
if @MultiCurrency = 0
begin
	select @CurrencyID = null 
		  ,@ExchangeRate = 1
end
else 
begin
	if isnull(@ExchangeRate, 0) <=0
		select @ExchangeRate = 1

	if isnull(@CurrencyID, '''') = ''''
		select @CurrencyID = null -- no empty string
			  ,@ExchangeRate = 1

	-- Now AR account must be in same currency as the header
	declare @ARAccountCurrencyID varchar(10)
	select @ARAccountCurrencyID = CurrencyID from tGLAccount (nolock) where GLAccountKey = @ARAccountKey
	if isnull(@ARAccountCurrencyID, '''') <> isnull(@CurrencyID, '''')
		return @kErrARAccountCurrency
end

declare @GLCCurrencyID varchar(10)
declare @RateHistory int
if @MultiCurrency = 1
begin
	select @GLCCurrencyID = CurrencyID
	from   tGLCompany (nolock)
	where  GLCompanyKey = @GLCompanyKey 

	if @GLCExchangeRate is null
	begin
		if isnull(@GLCCurrencyID, '''') = ''''
			select @GLCExchangeRate = @ExchangeRate
		else
		begin
			exec sptCurrencyGetRateToCurrency @CompanyKey, @GLCompanyKey, @CurrencyID, @GLCCurrencyID, @InvoiceDate, @GLCExchangeRate output, @RateHistory output
		end
	end
end
select @GLCExchangeRate = isnull(@GLCExchangeRate, 1)


declare @SaveLines int
declare @SaveSplits int
declare @SaveCredits int
declare @SaveInvoiceTaxes int
declare @SavePrepayments int
declare @SaveAdvanceBills int

/*
* Validations and preprocessing
*/
declare @InvoiceOpenAmount as money
declare @IABAmount as money   -- sum of tInvoiceAdvanceBill.Amount
declare @IABTAmount as money  -- sum of tInvoiceAdvanceBillTax.Amount
declare @CreditAmount money


if @ParentInvoice = 1
	BEGIN
		if exists(Select 1 from #tAppl where Entity=''tInvoiceAdvanceBill'')
			return @kErrParentHasAB
			
		if exists(Select 1 from #tAppl where Entity=''tInvoiceCredit'')
			return @kErrParentHasCredits

		if exists(Select 1 from #tAppl where Entity=''tCheckAppl'')
			return @kErrParentHasReceipts
	
		if exists (select 1 from tCheckAppl (nolock) where InvoiceKey = @InvoiceKey and Prepay=0)
			return @kErrParentHasReceipts

	END


-- check if the posting date is before the date of the original invoice that was voided
declare @VoidInvoicePostingDate smalldatetime
If Isnull(@VoidInvoiceKey, 0) > 0 And Isnull(@VoidInvoiceKey, 0) <> @InvoiceKey 
Begin
	-- current invoice is the VOID invoice

	Select @VoidInvoicePostingDate = PostingDate -- orig
	From   tInvoice (nolock)
	Where  InvoiceKey = @VoidInvoiceKey
	
	If @VoidInvoicePostingDate Is Not Null
		If @PostingDate < @VoidInvoicePostingDate
			return @kErrVoidPostingDateVoidBefore
End

-- same check of the posting dates but seen from the other side (the VOID check)
If Isnull(@VoidInvoiceKey, 0) > 0 And Isnull(@VoidInvoiceKey, 0) = @InvoiceKey 
Begin
	-- current invoice is the ORIGINAL invoice

	Select @VoidInvoicePostingDate = PostingDate -- void
	From   tInvoice (nolock)
	Where  VoidInvoiceKey = @VoidInvoiceKey
	And    InvoiceKey <> @VoidInvoiceKey
	
	If @VoidInvoicePostingDate Is Not Null
		If @PostingDate > @VoidInvoicePostingDate
			return @kErrVoidPostingDateOrigAfter
End

/*
* ADVANCE BILLING VALIDATIONS OF CURRENT INVOICE
*/

if @ParentInvoice = 0
begin

	-- recalc @AmountReceived

	-- prepayments
	select @AmountReceived = sum(Amount) from #tAppl where Entity=''tCheckAppl''
	-- + payments
	if isnull(@InvoiceKey, 0) > 0
	select @AmountReceived = isnull(@AmountReceived, 0) +  sum(Amount) from tCheckAppl (nolock) where InvoiceKey = @InvoiceKey and Prepay = 0

	-- + credits
	if isnull(@InvoiceTotalAmount, 0) < 0 
		Select @CreditAmount = sum(Amount) * -1 from #tAppl where Entity=''tInvoiceCredit''
	else
		Select @CreditAmount = sum(Amount) from #tAppl where Entity=''tInvoiceCredit''

	select @AmountReceived = isnull(@AmountReceived, 0) + isnull(@CreditAmount, 0)
	
	-- recalc @RetainerAmount

	if @AdvanceBill = 0
	begin
		select @RetainerAmount = sum(Amount) from #tAppl where Entity=''tInvoiceAdvanceBill'' 

		select @InvoiceOpenAmount = isnull(@InvoiceTotalAmount, 0) -( isnull(@RetainerAmount, 0) + isnull(@AmountReceived, 0) + isnull(@WriteoffAmount, 0) 
		+ isnull(@DiscountAmount, 0)) 

		if @InvoiceTotalAmount >= 0 and @InvoiceOpenAmount <0
			return @kErrOverApplied
		if @InvoiceTotalAmount < 0 and @InvoiceOpenAmount >0
			return @kErrOverApplied

		-- For 226613 do not do because if FromAB = 1, there is no GL impact for this invoice 
		--if @CurPosted = 1 and isnull(@CurRetainerAmount, 0) <> isnull(@RetainerAmount, 0)
		--	return @kErrAdvBillNoChangePosted

		-- Added for 359617 (the total applied sales on the real invoice must also be checked, just like the adv bill)
		select @IABAmount = sum(Amount) from #tAppl where Entity=''tInvoiceAdvanceBill'' 
		select @IABTAmount = sum(Amount) from #tInvoiceAdvanceBillTax
	 
		--if Abs(isnull(@IABAmount, 0) - isnull(@IABTAmount, 0) ) > @TotalNonTaxAmount and @TotalNonTaxAmount > 0 -- also check that it is not a credit
		--	return @kErrSalesOverApplied
	end


	if @AdvanceBill = 1
	begin
		-- recalc IABAmount and IABTAmount

		select @IABAmount = sum(Amount) from #tAppl where Entity=''tInvoiceAdvanceBill'' 
		select @IABTAmount = sum(Amount) from #tInvoiceAdvanceBillTax
	
		select @InvoiceOpenAmount = isnull(@InvoiceTotalAmount, 0) -( isnull(@RetainerAmount, 0) + isnull(@AmountReceived, 0) + isnull(@WriteoffAmount, 0) 
		+ isnull(@DiscountAmount, 0)) 

		if @InvoiceTotalAmount >= 0 and @InvoiceOpenAmount <0
			return @kErrOverApplied
		if @InvoiceTotalAmount < 0 and @InvoiceOpenAmount >0
			return @kErrOverApplied

		if Abs(isnull(@IABAmount, 0)) > @InvoiceTotalAmount
			return @kErrAdvBillOverApplied
		  
		if Abs(isnull(@IABAmount, 0) - isnull(@IABTAmount, 0) ) > @TotalNonTaxAmount
			return @kErrAdvBillSalesOverApplied

	end

end -- ParentInvoice = 0
else
begin
	select @InvoiceTotalAmount = 0, @TotalNonTaxAmount = 0, @SalesTaxAmount = 0, @SalesTax1Amount = 0, @SalesTax2Amount = 0, @RetainerAmount = 0, @AmountReceived = 0 
end -- ParentInvoice = 1

/*
* Temp tables only used here
*/

create table #tInvoiceAdvanceBill (InvoiceAdvanceBillKey int null, InvoiceKey int null, AdvBillInvoiceKey int null
	, OldAmount money null, NewAmount money null
	, InvoiceTotalAmount money null, TotalNonTaxAmount money null
	, RetainerAmount money null, AmountReceived money null, DiscountAmount money null, WriteoffAmount money null 
	, IABAmount money null, IABTAmount money null 
	, Action varchar(20) null, Posted int null, UpdateFlag int null )

create table #recalcRetainerAmt(InvoiceKey int null, Posted int null)
create table #recalcAmtPaid(InvoiceKey int null)

create table #removedProjects(ProjectKey int null)
if isnull(@InvoiceKey, 0) > 0
begin
	insert #removedProjects (ProjectKey)
	select distinct ProjectKey 
	from tInvoiceLine (nolock) where InvoiceKey = @InvoiceKey

	delete #removedProjects
	where  ProjectKey  in (select ProjectKey from #tInvoiceLine)

end 

/*
* ADVANCE BILLING VALIDATIONS OF OTHER INVOICES
*/

-- Posted status on real invoices
-- I cannot rely on AdvanceBill because it could have changed, so check both sides

	insert #tInvoiceAdvanceBill (InvoiceAdvanceBillKey, InvoiceKey, AdvBillInvoiceKey, OldAmount, Action)
	select InvoiceAdvanceBillKey, InvoiceKey, AdvBillInvoiceKey, Amount, ''remove''
	from   tInvoiceAdvanceBill (nolock)
	where  InvoiceKey = @InvoiceKey

	if @@ROWCOUNT = 0
	insert #tInvoiceAdvanceBill (InvoiceAdvanceBillKey, InvoiceKey, AdvBillInvoiceKey, OldAmount, Action)
	select InvoiceAdvanceBillKey, InvoiceKey, AdvBillInvoiceKey, Amount, ''remove''
	from   tInvoiceAdvanceBill (nolock)
	where  AdvBillInvoiceKey = @InvoiceKey
 
 if @AdvanceBill = 1
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.Action = ''update''
		    ,#tInvoiceAdvanceBill.NewAmount = b.Amount
	from   #tAppl b
	where  b.Entity = ''tInvoiceAdvanceBill''
	and    #tInvoiceAdvanceBill.AdvBillInvoiceKey = @InvoiceKey
	and    #tInvoiceAdvanceBill.InvoiceKey = b.EntityKey
else
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.Action = ''update''
			,#tInvoiceAdvanceBill.NewAmount = b.Amount
	from   #tAppl b
	where  b.Entity = ''tInvoiceAdvanceBill''
	and    #tInvoiceAdvanceBill.InvoiceKey = @InvoiceKey
	and    #tInvoiceAdvanceBill.AdvBillInvoiceKey = b.EntityKey

	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.Action = ''update''
			,#tInvoiceAdvanceBill.NewAmount = b.Amount
	from   #tAppl b
	where  b.Entity = ''tInvoiceAdvanceBill''
	and    #tInvoiceAdvanceBill.InvoiceAdvanceBillKey = b.ApplKey
	 
	-- we cannot remove if the real invoice is posted, will not be tested below because of 174684
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.Posted = i.Posted 
	from   tInvoice i (nolock)
	where  #tInvoiceAdvanceBill.InvoiceKey = i.InvoiceKey
  
	-- we will have to recalc the retainer amounts on unposted invoices that we remove
	insert #recalcRetainerAmt (InvoiceKey)
	select InvoiceKey
	from   #tInvoiceAdvanceBill
	where  Action = ''remove''
	--and    Posted = 0 -- 421536 when removing a posted reg invoice on the AB invoice screen, the RetainerAmount is not recalculated, better to recalc even if posted 
	
	/* Allowing now posted invoices for 174684
	if exists (select 1 from #tInvoiceAdvanceBill where Posted = 1 and Action = ''remove'')
		return @kErrAdvBillNoDeletePosted 

	if exists (select 1 from #tInvoiceAdvanceBill where Posted = 1 and Action = ''update'' and isnull(OldAmount,0) <> isnull(NewAmount,0))
		return @kErrAdvBillNoChangePosted 
	*/

-- we are done with that table for now
truncate table #tInvoiceAdvanceBill

-- now check for over applications

if @AdvanceBill =  1
begin

	insert #tInvoiceAdvanceBill (InvoiceAdvanceBillKey, InvoiceKey, AdvBillInvoiceKey, NewAmount)
	select ApplKey, EntityKey, @InvoiceKey, Amount
	from   #tAppl
	where  Entity = ''tInvoiceAdvanceBill''
	and    Action = ''update''


	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.InvoiceTotalAmount = i.InvoiceTotalAmount
		 , #tInvoiceAdvanceBill.AmountReceived = i.AmountReceived
		 ,#tInvoiceAdvanceBill.DiscountAmount = i.DiscountAmount
		 ,#tInvoiceAdvanceBill.WriteoffAmount = i.WriteoffAmount
		 ,#tInvoiceAdvanceBill.Posted = i.Posted
		 ,#tInvoiceAdvanceBill.RetainerAmount = i.RetainerAmount
	from  tInvoice i (nolock)
	where #tInvoiceAdvanceBill.InvoiceKey = i.InvoiceKey -- real invoices

	
	-- Recalc RetainerAmount 
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.RetainerAmount = ISNULL((
	select Sum(b.Amount)
	from   tInvoiceAdvanceBill b (nolock)
	where  b.InvoiceKey = #tInvoiceAdvanceBill.InvoiceKey -- same invoice
	and    b.AdvBillInvoiceKey <> #tInvoiceAdvanceBill.AdvBillInvoiceKey -- but different AB invoice
	and    b.AdvBillInvoiceKey <> b.InvoiceKey -- filter out self appl 
	),0)

	-- and add the currently edited amount
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.RetainerAmount =  isnull(#tInvoiceAdvanceBill.RetainerAmount, 0) + isnull(#tInvoiceAdvanceBill.NewAmount, 0) 

	-- we will have to recalc the retainer amounts 
	insert #recalcRetainerAmt (InvoiceKey, Posted)
	select InvoiceKey, Posted
	from   #tInvoiceAdvanceBill
	
	if exists (select 1 from #tInvoiceAdvanceBill
			where Abs(InvoiceTotalAmount) < Abs(isnull(RetainerAmount, 0) + isnull(AmountReceived, 0) +
				                           isnull(DiscountAmount, 0) + isnull(WriteoffAmount, 0))
			) 
			return @kErrAdvBillOverApplied 

end

if @AdvanceBill = 0
begin
	insert #tInvoiceAdvanceBill (InvoiceAdvanceBillKey, InvoiceKey, AdvBillInvoiceKey, NewAmount)
	select ApplKey, @InvoiceKey, EntityKey, Amount
	from   #tAppl
	where  Entity = ''tInvoiceAdvanceBill''
	and    Action = ''update''

	-- get info from AB other invoices
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.InvoiceTotalAmount = i.InvoiceTotalAmount
		,#tInvoiceAdvanceBill.TotalNonTaxAmount = i.TotalNonTaxAmount
	from  tInvoice i (nolock)
	where #tInvoiceAdvanceBill.AdvBillInvoiceKey = i.InvoiceKey

	-- Recalc IABAmount
	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.IABAmount = ISNULL((
	select Sum(b.Amount)
	from   tInvoiceAdvanceBill b (nolock)
	where  b.AdvBillInvoiceKey = #tInvoiceAdvanceBill.AdvBillInvoiceKey -- same AB
	and    b.InvoiceKey <> #tInvoiceAdvanceBill.InvoiceKey -- but different real invoice
	and    b.AdvBillInvoiceKey <> b.InvoiceKey -- filter out self appl 
	),0)

	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.IABAmount =  isnull(#tInvoiceAdvanceBill.IABAmount, 0) + isnull(#tInvoiceAdvanceBill.NewAmount, 0) 


	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.IABTAmount = ISNULL((
	select Sum(b.Amount)
	from   tInvoiceAdvanceBillTax b (nolock)
	where  b.AdvBillInvoiceKey = #tInvoiceAdvanceBill.AdvBillInvoiceKey -- same AB
	and    b.InvoiceKey <> #tInvoiceAdvanceBill.InvoiceKey -- but different real invoice
	and    b.AdvBillInvoiceKey <> b.InvoiceKey -- filter out self appl 
	),0)

	update #tInvoiceAdvanceBill
	set    #tInvoiceAdvanceBill.IABTAmount = isnull(#tInvoiceAdvanceBill.IABTAmount, 0) + ISNULL((
	select Sum(b.Amount)
	from   #tInvoiceAdvanceBillTax b (nolock)
	where  b.AdvBillInvoiceKey = #tInvoiceAdvanceBill.AdvBillInvoiceKey -- same AB
	and    b.InvoiceKey = #tInvoiceAdvanceBill.InvoiceKey -- same real invoice
	and    b.AdvBillInvoiceKey <> b.InvoiceKey -- filter out self appl 
	),0)

	if exists (select 1
		from   #tInvoiceAdvanceBill
		where  Abs(isnull(#tInvoiceAdvanceBill.IABAmount, 0))  
			> Abs(isnull(#tInvoiceAdvanceBill.InvoiceTotalAmount, 0)) 
			) 
			return @kErrAdvBillOverApplied

	if exists (select 1
		from   #tInvoiceAdvanceBill
		where  Abs(isnull(#tInvoiceAdvanceBill.IABAmount, 0) - isnull(#tInvoiceAdvanceBill.IABTAmount, 0)) 
			> Abs(isnull(#tInvoiceAdvanceBill.TotalNonTaxAmount, 0)) 
			) 
			return @kErrAdvBillSalesOverApplied

end

/*
Line validation
*/

--if @UseGLCompany = 1 and exists (select 1 from #tInvoiceLine il
--			inner join tProject p (nolock) on il.ProjectKey = p.ProjectKey
--			where isnull(p.GLCompanyKey, 0) <> isnull(il.TargetGLCompanyKey, isnull(@GLCompanyKey, 0))
--			and   isnull(p.GLCompanyKey, 0) <> isnull(@GLCompanyKey, 0)
--			and   il.LineType = 2
--		  )
--		return @kErrLinesProjectGLCompany 

-- same type of check here for currencies
if @MultiCurrency = 1 and exists (select 1 from #tInvoiceLine il
			inner join tProject p (nolock) on il.ProjectKey = p.ProjectKey
			where isnull(p.CurrencyID, '''') <> isnull(@CurrencyID, '''')
			and   il.LineType = 2
		  )
		return @kErrLinesProjectCurrency 

if @AddMode = 0 and 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
			and  summ.InvoiceLineKey not in (select InvoiceLineKey from #tInvoiceLine)
		)
		return @kErrLinesProjectClosed
/*
* Transactions preprocessing
*/

if @TransactionsUpdated = 1
begin
	-- we cannot have several times the same transactions 
	if (select count(*) from #transaction)
		<>
		(select count(*) from 
			(
			select distinct Entity, EntityKey, TimeKey from #transaction
			) as trans
		)
		return  @kErrTransactionDuplicates
	
		
	if @AddMode = 0
	begin

		-- place in the same table the transactions we must remove (associated in DB with this invoice but no longer in our temp table)
		-- also get project key

		insert #transaction (Entity, EntityKey, Action, ProjectKey)
		select ''tMiscCost'', mc.MiscCostKey, ''remove'', mc.ProjectKey
		from   tMiscCost mc (nolock)
		inner join tInvoiceLine il (nolock) on mc.InvoiceLineKey = il.InvoiceLineKey
		where  il.InvoiceKey = @InvoiceKey
		and    mc.MiscCostKey not in (select EntityKey from #transaction where Entity = ''tMiscCost'')

		insert #transaction (Entity, EntityKey, Action, ProjectKey)
		select ''tVoucherDetail'', vd.VoucherDetailKey, ''remove'', vd.ProjectKey
		from   tVoucherDetail vd (nolock)
		inner join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
		where  il.InvoiceKey = @InvoiceKey
		and    vd.VoucherDetailKey not in (select EntityKey from #transaction where Entity = ''tVoucherDetail'')

		insert #transaction (Entity, EntityKey, Action, ProjectKey)
		select ''tPurchaseOrderDetail'', pod.PurchaseOrderDetailKey, ''remove'', pod.ProjectKey
		from   tPurchaseOrderDetail pod (nolock)
		inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
		where  il.InvoiceKey = @InvoiceKey
		and    pod.PurchaseOrderDetailKey not in (select EntityKey from #transaction where Entity = ''tPurchaseOrderDetail'')

		insert #transaction (Entity, EntityKey, Action, ProjectKey)
		select ''tExpenseReceipt'', er.ExpenseReceiptKey, ''remove'', er.ProjectKey
		from   tExpenseReceipt er (nolock)
		inner join tInvoiceLine il (nolock) on er.InvoiceLineKey = il.InvoiceLineKey
		where  il.InvoiceKey = @InvoiceKey
		and    er.ExpenseReceiptKey not in (select EntityKey from #transaction where Entity = ''tExpenseReceipt'')

		insert #transaction (Entity, TimeKey, Action, ProjectKey)
		select ''tTime'', t.TimeKey, ''remove'', t.ProjectKey
		from   tTime t (nolock)
		inner join tInvoiceLine il (nolock) on t.InvoiceLineKey = il.InvoiceLineKey
		where  il.InvoiceKey = @InvoiceKey
		and    t.TimeKey not in (select TimeKey from #transaction where Entity = ''tTime'')

		-- see sptInvoiceLineUpdateExpensesMultiple
		--If Expense Receipts linked to this invoice line are also linked to a voucher, mark as Unbilled
		/*
		UPDATE	tVoucherDetail
		SET		DateBilled = null,
				InvoiceLineKey = null
		FROM	tExpenseReceipt er (nolock)
		INNER JOIN #tInvoiceLineExpense b (nolock) ON er.ExpenseReceiptKey = b.EntityKey
		WHERE	er.VoucherDetailKey = tVoucherDetail.VoucherDetailKey
		AND		b.Entity = ''ER''
		AND		b.Action = 0
		*/

		insert #transaction (Entity, EntityKey, Action, ProjectKey)
		select ''tVoucherDetail'', er.VoucherDetailKey, ''remove'', vd.ProjectKey
		from   #transaction 
		inner join tExpenseReceipt er (nolock) on #transaction.Entity = ''tExpenseReceipt'' and #transaction.EntityKey = er.ExpenseReceiptKey  
		inner join tVoucherDetail vd (nolock) on er.VoucherDetailKey = vd.VoucherDetailKey
		where  #transaction.Action = ''remove''

		-- Clone of sptInvoiceLineUpdatePO    
		-- 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       
		UPDATE #transaction
		SET    #transaction.Action = ''has voucher''
		FROM   tVoucherDetail vd (NOLOCK)
			   ,tPurchaseOrderDetail pod (NOLOCK)
		WHERE  #transaction.Entity = ''tPurchaseOrderDetail''
		AND    #transaction.EntityKey = vd.PurchaseOrderDetailKey
		AND    #transaction.EntityKey = pod.PurchaseOrderDetailKey
		AND    #transaction.Action = ''remove''
		AND   ISNULL(pod.AccruedCost, 0) <> 0 -- Must have something to accrue
	end

	-- do we have conflicts? some transactions could be on a different invoice
	update #transaction
	set    #transaction.Action = ''conflict''
	from   tMiscCost mc (nolock)
	inner join tInvoiceLine il (nolock) on mc.InvoiceLineKey = il.InvoiceLineKey
	where  il.InvoiceKey <> isnull(@InvoiceKey, 0)
	and    #transaction.EntityKey = mc.MiscCostKey
	and    #transaction.Entity = ''tMiscCost''

	update #transaction
	set    #transaction.Action = ''conflict''
	from   tExpenseReceipt er (nolock)
	inner join tInvoiceLine il (nolock) on er.InvoiceLineKey = il.InvoiceLineKey
	where  il.InvoiceKey <> isnull(@InvoiceKey, 0)
	and    #transaction.EntityKey = er.ExpenseReceiptKey
	and    #transaction.Entity = ''tExpenseReceipt''

	update #transaction
	set    #transaction.Action = ''conflict''
	from   tVoucherDetail vd (nolock)
	inner join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
	where  il.InvoiceKey <> isnull(@InvoiceKey, 0)
	and    #transaction.EntityKey = vd.VoucherDetailKey
	and    #transaction.Entity = ''tVoucherDetail''

	update #transaction
	set    #transaction.Action = ''conflict''
	from   tPurchaseOrderDetail pod (nolock)
	inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
	where  il.InvoiceKey <> isnull(@InvoiceKey, 0)
	and    #transaction.EntityKey = pod.PurchaseOrderDetailKey
	and    #transaction.Entity = ''tPurchaseOrderDetail''

	update #transaction
	set    #transaction.Action = ''conflict''
	from   tTime t (nolock)
	inner join tInvoiceLine il (nolock) on t.InvoiceLineKey = il.InvoiceLineKey
	where  il.InvoiceKey <> isnull(@InvoiceKey, 0)
	and    #transaction.TimeKey = t.TimeKey
	and    #transaction.Entity = ''tTime''

	if exists (select 1 from #transaction where Action=''conflict'')
		return @kErrTransactionConflict 

	if exists (select 1 from #transaction where Action=''has voucher'')
		return @kErrTransactionHasVoucher


end

if @TransactionsUpdated = 1
begin
	-- compare the sum of the amounts on the trans and on the lines
	update #transaction
	set    #transaction.AmountBilled = ROUND(isnull(BilledHours, 0) * isnull(BilledRate, 0), 2) 
	where  Entity = ''tTime''

	update #tInvoiceLine
	set    #tInvoiceLine.GPAmount = isnull((
		select sum(trans.AmountBilled) from #transaction trans
		where  trans.InvoiceLineKey = #tInvoiceLine.InvoiceLineKey
		and    trans.Action = ''update''
		), 0)
	where LineType = 2 -- detail
	and BillFrom = 2 -- use trans

	if exists (select 1 from #tInvoiceLine 
		where LineType = 2 -- detail
		and   BillFrom = 2 -- use trans
		and   ROUND(GPAmount, 2) <> ROUND(TotalAmount, 2)
		) return @kErrMissigTrans

end

if @AddMode = 0 And (@ParentInvoice = 1 Or @CurParentInvoice = 1)
begin
	insert #tSplit (InvoiceKey, Action)
	select InvoiceKey, ''remove''
	from   tInvoice (nolock)
	where  ParentInvoiceKey = @InvoiceKey
	and    InvoiceKey not in (select InvoiceKey from #tSplit)
end

-- If there are splits to delete, do that here before we start the SQL transaction
declare @ErrChildDelete as integer
select @ErrChildDelete = 0

select @LoopInvoiceKey = -1
while (1=1)
begin
	select @LoopInvoiceKey = min(InvoiceKey)
	from   #tSplit
	where  InvoiceKey > @LoopInvoiceKey
	and    Action = ''remove''

	if @LoopInvoiceKey is null
		break

	exec @RetVal = sptInvoiceDelete @LoopInvoiceKey
	
	-- if error, abort
	if @RetVal < 0 
		select @ErrChildDelete = 1

end

if @ErrChildDelete = 1
	return @kErrChildDelete 

-- If there are splits to update, check if they are posted/paid before we start the SQL transaction
update #tSplit
set    UpdateFlag = 0
where  Action = ''update''

update #tSplit
set    #tSplit.UpdateFlag = 1
from   tInvoice i (nolock) 
where  #tSplit.InvoiceKey = i.InvoiceKey
and    (i.Posted = 1 or isnull(i.AmountReceived, 0) <> 0)
and    (isnull(#tSplit.PercentageSplit, 0) <>  isnull(i.PercentageSplit, 0))

if exists (select 1 from #tSplit where Action = ''update'' and UpdateFlag = 1)
	return @kErrChildUpdate 


/*
* DB inserts/updates start here
*/

begin tran

/*
* Header first
*/

if @AddMode = 0
begin

	 UPDATE
	  tInvoice
	 SET
		ContactName = @ContactName,
		PrimaryContactKey = @PrimaryContactKey,
		AddressKey = @AddressKey,
		InvoiceNumber = RTRIM(LTRIM(@NextTranNo)),
		AdvanceBill = @AdvanceBill,
		InvoiceDate = @InvoiceDate,
		DueDate = @DueDate,
		PostingDate = @PostingDate,
		TermsKey = @TermsKey,
		ARAccountKey = @ARAccountKey,
		ClassKey = @ClassKey,
		ProjectKey = @ProjectKey,
		RetainerAmount = @RetainerAmount, -- new
		WriteoffAmount = @WriteoffAmount,
		DiscountAmount = @DiscountAmount,
		SalesTaxAmount = @SalesTaxAmount, -- new
		SalesTax1Amount = @SalesTax1Amount,-- new
		SalesTax2Amount = @SalesTax2Amount,-- new
		TotalNonTaxAmount = @TotalNonTaxAmount, -- new
		InvoiceTotalAmount = @InvoiceTotalAmount, -- new
		AmountReceived = @AmountReceived, -- new
		HeaderComment = @HeaderComment,
		SalesTaxKey = @SalesTaxKey,
		SalesTax2Key = @SalesTax2Key,
		ApprovedByKey = @ApprovedByKey,
		InvoiceTemplateKey = @InvoiceTemplateKey,
		UserDefined1 = @UserDefined1,
		UserDefined2 = @UserDefined2,
		UserDefined3 = @UserDefined3,
		UserDefined4 = @UserDefined4,
		UserDefined5 = @UserDefined5,
		UserDefined6 = @UserDefined6,
		UserDefined7 = @UserDefined7,
		UserDefined8 = @UserDefined8,
		UserDefined9 = @UserDefined9,
		UserDefined10 = @UserDefined10,
		Downloaded = @Downloaded,
		Printed = @Printed,
		ParentInvoice = @ParentInvoice,
		Emailed = @Emailed,
		GLCompanyKey = @GLCompanyKey,
		OfficeKey = @OfficeKey,
		OpeningTransaction = @OpeningTransaction,
		LayoutKey = @LayoutKey,
		CampaignKey = @CampaignKey,
		AlternatePayerKey = @AlternatePayerKey,
		BillingGroupKey = @BillingGroupKey,
		CurrencyID = @CurrencyID,
		ExchangeRate = @ExchangeRate,
		GLCCurrencyID = @GLCCurrencyID,
		GLCExchangeRate = @GLCExchangeRate,
		DeliveryDate = @DeliveryDate
	 WHERE InvoiceKey = @InvoiceKey 

 	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end

end
  
else

begin
	 INSERT tInvoice
	  (
		CompanyKey,
		ClientKey,
		ContactName,
		PrimaryContactKey,
		AddressKey,
		AdvanceBill,
		InvoiceNumber,
		InvoiceDate,
		DueDate,
		PostingDate,
		TermsKey,
		ARAccountKey,
		ClassKey,
		ProjectKey,
	
		RetainerAmount, 
		WriteoffAmount,
		DiscountAmount,
		SalesTaxAmount,
		SalesTax1Amount,
		SalesTax2Amount,
		TotalNonTaxAmount, 
		InvoiceTotalAmount,
		AmountReceived, 
	
		InvoiceStatus,
		HeaderComment,
		SalesTaxKey,
		SalesTax2Key,
		InvoiceTemplateKey,
		ApprovedByKey,
		UserDefined1,
		UserDefined2,
		UserDefined3,
		UserDefined4,
		UserDefined5,
		UserDefined6,
		UserDefined7,
		UserDefined8,
		UserDefined9,
		UserDefined10,
		Downloaded,
		Printed,
		ParentInvoice,
		Emailed,
		GLCompanyKey,
		OfficeKey,
		OpeningTransaction,
		LayoutKey,
		CampaignKey,
		AlternatePayerKey,
		BillingGroupKey,
		CurrencyID,
		ExchangeRate,
		CreatedByKey,
		DateCreated,
		GLCCurrencyID,
		GLCExchangeRate,
		DeliveryDate
	  )
	 VALUES
	  (
		@CompanyKey,
		@ClientKey,
		@ContactName,
		@PrimaryContactKey,
		@AddressKey,
		@AdvanceBill,
		RTRIM(LTRIM(@NextTranNo)),
		@InvoiceDate,
		@DueDate,
		@PostingDate,
		@TermsKey,
		@ARAccountKey,
		@ClassKey,
		@ProjectKey,
	
		@RetainerAmount, 
		@WriteoffAmount,
		@DiscountAmount,
		@SalesTaxAmount,
		@SalesTax1Amount,
		@SalesTax2Amount,
		@TotalNonTaxAmount, 
		@InvoiceTotalAmount,
		@AmountReceived, 
	
		@InvoiceStatus,  
		@HeaderComment,
		@SalesTaxKey,
		@SalesTax2Key,
		@InvoiceTemplateKey,
		@ApprovedByKey,
		@UserDefined1,
		@UserDefined2,
		@UserDefined3,
		@UserDefined4,
		@UserDefined5,
		@UserDefined6,
		@UserDefined7,
		@UserDefined8,
		@UserDefined9,
		@UserDefined10,
		@Downloaded,
		@Printed,
		@ParentInvoice,
		@Emailed,
		@GLCompanyKey,
		@OfficeKey,
		@OpeningTransaction,
		@LayoutKey,
		@CampaignKey,
		@AlternatePayerKey,
		@BillingGroupKey,
		@CurrencyID,
		@ExchangeRate,
		@CreatedByKey,
		GETDATE(),
		@GLCCurrencyID,
		@GLCExchangeRate,
		@DeliveryDate
	  )

    SELECT @oIdentity = @@IDENTITY, @InvoiceKey = @@IDENTITY ,@Error = @@ERROR
 
	if @Error <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end

end

if @AddMode = 0
begin
	
	delete tInvoiceLine 
	where  tInvoiceLine.InvoiceKey = @InvoiceKey
	and    tInvoiceLine.InvoiceLineKey not in (select InvoiceLineKey from #tInvoiceLine where InvoiceLineKey > 0)
	
	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end
end

/*
* Then lines
*/

	-- No ICT if we are involved in Advance bills and split billing (removed for 216450)
	--if @AdvanceBill = 1
		--update #tInvoiceLine set TargetGLCompanyKey = null
	if @ParentInvoice = 1
		update #tInvoiceLine set TargetGLCompanyKey = null
	if @ParentInvoiceKey > 0
		update #tInvoiceLine set TargetGLCompanyKey = null
	--if exists (select 1 from #tAppl where Entity = ''tInvoiceAdvanceBill'')
		--update #tInvoiceLine set TargetGLCompanyKey = null
	
-- now we must insert lines in a loop
-- insert summary lines first by InvoiceOrder

	declare @OldKey int
	declare @NewKey int
    declare @InvoiceOrder int

	-- do we need to recalc the InvoiceOrder here?
	 
	select @InvoiceOrder = -1
	while (1=1)
	begin
		select @InvoiceOrder = Min(InvoiceOrder)
		from   #tInvoiceLine
		where  InvoiceLineKey <=0
		and    InvoiceOrder > @InvoiceOrder
		and    LineType = 1 -- summary

		if @InvoiceOrder is null
			break
		
		select @OldKey = InvoiceLineKey from #tInvoiceLine where InvoiceOrder = @InvoiceOrder

		insert tInvoiceLine (InvoiceKey, ProjectKey, TaskKey, LineType, LineSubject, LineDescription, BillFrom, PostSalesUsingDetail
		                     ,Quantity, UnitAmount, TotalAmount, SalesAccountKey, ClassKey
							 ,LineLevel, DisplayOrder, InvoiceOrder, ParentLineKey
							 ,Taxable, Taxable2, WorkTypeKey, Entity, EntityKey, RetainerKey, EstimateKey, OfficeKey, DepartmentKey
							 ,SalesTaxAmount, SalesTax1Amount, SalesTax2Amount, DisplayOption, CampaignSegmentKey, TargetGLCompanyKey)
		select @InvoiceKey, ProjectKey, TaskKey, LineType, LineSubject, LineDescription, BillFrom, PostSalesUsingDetail
		                     ,Quantity, UnitAmount, TotalAmount, SalesAccountKey, ClassKey
							 ,LineLevel, DisplayOrder, InvoiceOrder, ParentLineKey
							 ,Taxable, Taxable2, WorkTypeKey, Entity, EntityKey, RetainerKey, EstimateKey, OfficeKey, DepartmentKey
							 ,SalesTaxAmount, SalesTax1Amount, SalesTax2Amount, DisplayOption, CampaignSegmentKey, TargetGLCompanyKey
		from #tInvoiceLine
		where InvoiceLineKey = @OldKey

		select @Error = @@ERROR, @NewKey = @@IDENTITY

		if @Error <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end
		
		-- Always update the parent on the child lines as we create a parent
		update #tInvoiceLine set ParentLineKey = @NewKey where ParentLineKey = @OldKey

		insert #KeyMap (Entity, OldKey, NewKey)
		VALUES (''tInvoiceLine'', @OldKey, @NewKey)
	
	end

	
	
	select @OldKey = -10000
	while (1=1)
	begin
		select @OldKey = Min(InvoiceLineKey)
		from   #tInvoiceLine
		where  InvoiceLineKey <=0
		and    InvoiceLineKey > @OldKey
		and    LineType = 2 -- detail

		if @OldKey is null
			break
		
		insert tInvoiceLine (InvoiceKey, ProjectKey, TaskKey, LineType, LineSubject, LineDescription, BillFrom, PostSalesUsingDetail
		                     ,Quantity, UnitAmount, TotalAmount, SalesAccountKey, ClassKey
							 ,LineLevel, DisplayOrder, InvoiceOrder, ParentLineKey
							 ,Taxable, Taxable2, WorkTypeKey, Entity, EntityKey, RetainerKey, EstimateKey, OfficeKey, DepartmentKey
							 ,SalesTaxAmount, SalesTax1Amount, SalesTax2Amount, DisplayOption, CampaignSegmentKey,TargetGLCompanyKey)
		select @InvoiceKey, ProjectKey, TaskKey, LineType, LineSubject, LineDescription, BillFrom, PostSalesUsingDetail
		                     ,Quantity, UnitAmount, TotalAmount, SalesAccountKey, ClassKey
							 ,LineLevel, DisplayOrder, InvoiceOrder, ParentLineKey
							 ,Taxable, Taxable2, WorkTypeKey, Entity, EntityKey, RetainerKey, EstimateKey, OfficeKey, DepartmentKey
							 ,SalesTaxAmount, SalesTax1Amount, SalesTax2Amount, DisplayOption, CampaignSegmentKey, TargetGLCompanyKey
		from #tInvoiceLine
		where InvoiceLineKey = @OldKey


		select @Error = @@ERROR, @NewKey = @@IDENTITY

		if @Error <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end
		
		insert #KeyMap (Entity, OldKey, NewKey)
		VALUES (''tInvoiceLine'', @OldKey, @NewKey)
	
	end

if @AddMode = 0
begin
		
	update tInvoiceLine
		set tInvoiceLine.ProjectKey = b.ProjectKey
			,tInvoiceLine.TaskKey = b.TaskKey
			,tInvoiceLine.LineType = b.LineType
			,tInvoiceLine.LineSubject = b.LineSubject
			,tInvoiceLine.LineDescription = b.LineDescription
			,tInvoiceLine.BillFrom = b.BillFrom
			,tInvoiceLine.PostSalesUsingDetail = b.PostSalesUsingDetail
		    ,tInvoiceLine.Quantity = b.Quantity
			,tInvoiceLine.UnitAmount = b.UnitAmount
			,tInvoiceLine.TotalAmount = b.TotalAmount
			,tInvoiceLine.SalesAccountKey = b.SalesAccountKey
			,tInvoiceLine.ClassKey = b.ClassKey
			,tInvoiceLine.LineLevel = b.LineLevel
			,tInvoiceLine.DisplayOrder = b.DisplayOrder
			,tInvoiceLine.InvoiceOrder = b.InvoiceOrder
			,tInvoiceLine.ParentLineKey = b.ParentLineKey
			,tInvoiceLine.Taxable = b.Taxable
			,tInvoiceLine.Taxable2 = b.Taxable2
			,tInvoiceLine.WorkTypeKey = b.WorkTypeKey
			,tInvoiceLine.Entity = b.Entity
			,tInvoiceLine.EntityKey = b.EntityKey
			,tInvoiceLine.RetainerKey = b.RetainerKey
			,tInvoiceLine.EstimateKey = b.EstimateKey
			,tInvoiceLine.OfficeKey = b.OfficeKey
			,tInvoiceLine.DepartmentKey = b.DepartmentKey
			,tInvoiceLine.SalesTaxAmount = b.SalesTaxAmount
			,tInvoiceLine.SalesTax1Amount = b.SalesTax1Amount
			,tInvoiceLine.SalesTax2Amount = b.SalesTax2Amount
			,tInvoiceLine.DisplayOption = b.DisplayOption
			,tInvoiceLine.CampaignSegmentKey = b.CampaignSegmentKey
			,tInvoiceLine.TargetGLCompanyKey = b.TargetGLCompanyKey
	from #tInvoiceLine b
	where tInvoiceLine.InvoiceLineKey = b.InvoiceLineKey
	and   tInvoiceLine.InvoiceKey = @InvoiceKey
	and   tInvoiceLine.InvoiceLineKey > 0
	
	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end
	
end


/*
Prepayments
*/

if @AddMode = 0
begin
	
	delete tCheckAppl 
	where  tCheckAppl.InvoiceKey = @InvoiceKey
	and    tCheckAppl.Prepay = 1
	and    tCheckAppl.CheckApplKey not in (select ApplKey from #tAppl where Entity=''tCheckAppl'' and ApplKey > 0)
	
	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end
end

-- now we must insert prepayments in a loop

	select @OldKey = -10000
	while (1=1)
	begin
		select @OldKey = Min(ApplKey)
		from   #tAppl
		where  ApplKey <=0
		and    ApplKey > @OldKey
		and    Entity=''tCheckAppl''

		if @OldKey is null
			break
		
		INSERT tCheckAppl
			(
			CheckKey,
			InvoiceKey,
			SalesAccountKey,
			OfficeKey,
			DepartmentKey,
			ClassKey,
			Description,
			Amount,
			Prepay,
			SalesTaxKey
			)
		select EntityKey, @InvoiceKey, @ARAccountKey, null, null, @ClassKey, Description, Amount, 1, null
		from  #tAppl
		where ApplKey = @OldKey
		and   Entity=''tCheckAppl''

		select @Error = @@ERROR, @NewKey = @@IDENTITY

		if @Error <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end
		
		insert #KeyMap (Entity, OldKey, NewKey)
		VALUES (''tCheckAppl'', @OldKey, @NewKey)
	
	end

if @AddMode = 0
begin
		
	update tCheckAppl
		set tCheckAppl.Amount = b.Amount
			,tCheckAppl.Description = b.Description
			,tCheckAppl.SalesAccountKey = @ARAccountKey
			,tCheckAppl.ClassKey = @ClassKey	
	from #tAppl b
	where tCheckAppl.CheckApplKey = b.ApplKey
	and   tCheckAppl.InvoiceKey = @InvoiceKey
	and   b.ApplKey > 0
	and   b.Entity=''tCheckAppl''

	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end
	
end


/*
Credits
*/

declare @CanEditCredit int

if isnull(@CurrencyID, '''') = ''''
	select @CanEditCredit = 1
else
begin
	-- foreign currency used
	if @InvoiceTotalAmount < 0
		-- on the credit side we can edit
		select @CanEditCredit = 1
	else
		-- on the regular side, we cannot edit because of GL implications on the credit side
		select @CanEditCredit = 0
end
 
if @CanEditCredit = 1
begin
	if @AddMode = 0
	begin
	
		insert #recalcAmtPaid (InvoiceKey)
		select InvoiceKey
		from   tInvoiceCredit (nolock)
		where  CreditInvoiceKey = @InvoiceKey
	   
		insert #recalcAmtPaid (InvoiceKey)
		select CreditInvoiceKey
		from   tInvoiceCredit (nolock)
		where  InvoiceKey = @InvoiceKey
	
		-- with credits, InvoiceTotalAmount could fluctuate, <0 one time and >=0 another
		-- and we could have our invoice key = InvoiceKey OR = CreditInvoiceKey
		-- we must try to delete from both sides
		 
		delete tInvoiceCredit 
		where  tInvoiceCredit.InvoiceKey = @InvoiceKey
		and    tInvoiceCredit.InvoiceCreditKey not in (select ApplKey from #tAppl where Entity=''tInvoiceCredit'' and ApplKey > 0)
	
		if @@ERROR <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end

		delete tInvoiceCredit 
		where  tInvoiceCredit.CreditInvoiceKey = @InvoiceKey
		and    tInvoiceCredit.InvoiceCreditKey not in (select ApplKey from #tAppl where Entity=''tInvoiceCredit'' and ApplKey > 0)
	
		if @@ERROR <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end

	end

	-- now we must insert credits in a loop

		select @OldKey = -10000
		while (1=1)
		begin
			select @OldKey = Min(ApplKey)
			from   #tAppl
			where  ApplKey <=0
			and    ApplKey > @OldKey
			and    Entity=''tInvoiceCredit''

			if @OldKey is null
				break
		
			if @InvoiceTotalAmount < 0
			begin
				-- This invoice is credit invoice
				-- the others applied are regular invoices
				INSERT tInvoiceCredit
					(
					CreditInvoiceKey,
					InvoiceKey,
					Description,
					Amount
					)
				select @InvoiceKey, EntityKey, Description, Amount
				from  #tAppl
				where ApplKey = @OldKey
				and   Entity=''tInvoiceCredit''

				select @Error = @@ERROR, @NewKey = @@IDENTITY

				if @Error <> 0
				begin
					rollback tran
					return @kErrUnexpected
				end
			end
			else
			begin
				-- This invoice is a regular invoice
				-- the others applied are credit invoices

				INSERT tInvoiceCredit
					(
					CreditInvoiceKey,
					InvoiceKey,
					Description,
					Amount
					)
				select EntityKey, @InvoiceKey, Description, Amount
				from  #tAppl
				where ApplKey = @OldKey
				and   Entity=''tInvoiceCredit''

				select @Error = @@ERROR, @NewKey = @@IDENTITY

				if @Error <> 0
				begin
					rollback tran
					return @kErrUnexpected
				end
			end

			insert #KeyMap (Entity, OldKey, NewKey)
			VALUES (''tInvoiceCredit'', @OldKey, @NewKey)
	
		end

	if @AddMode = 0
	begin
		
		update tInvoiceCredit
			set tInvoiceCredit.Amount = b.Amount
				,tInvoiceCredit.Description = b.Description	
		from #tAppl b
		where tInvoiceCredit.InvoiceCreditKey = b.ApplKey
		and   b.ApplKey > 0
		and   b.Entity=''tInvoiceCredit''
		and   (tInvoiceCredit.InvoiceKey = @InvoiceKey OR tInvoiceCredit.CreditInvoiceKey = @InvoiceKey)

		if @@ERROR <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end
	
	end

	insert #recalcAmtPaid (InvoiceKey)
	select InvoiceKey
	from   tInvoiceCredit (nolock)
	where  CreditInvoiceKey = @InvoiceKey
	   
	insert #recalcAmtPaid (InvoiceKey)
	select CreditInvoiceKey
	from   tInvoiceCredit (nolock)
	where  InvoiceKey = @InvoiceKey

end -- can edit credit

/*
Advance Bills
*/


if @AddMode = 0
begin

	-- same precaution than with credits, delete from both sides
		
	delete tInvoiceAdvanceBill 
	where  tInvoiceAdvanceBill.InvoiceKey = @InvoiceKey
	and    tInvoiceAdvanceBill.InvoiceAdvanceBillKey not in (select ApplKey from #tAppl 
	where Entity=''tInvoiceAdvanceBill'' and ApplKey > 0 and Action=''update'')
	
	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end

	delete tInvoiceAdvanceBill 
	where  tInvoiceAdvanceBill.AdvBillInvoiceKey = @InvoiceKey
	and    tInvoiceAdvanceBill.InvoiceAdvanceBillKey not in (select ApplKey from #tAppl 
	where Entity=''tInvoiceAdvanceBill'' and ApplKey > 0 and Action=''update'')
	
	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end

end

-- now we must insert adv bills in a loop

	select @OldKey = -10000
	while (1=1)
	begin
		select @OldKey = Min(ApplKey)
		from   #tAppl
		where  ApplKey <=0
		and    ApplKey > @OldKey
		and    Entity=''tInvoiceAdvanceBill''
		and    Action=''update''

		if @OldKey is null
			break
		
		if @AdvanceBill = 1
			-- This invoice is advance invoice
			-- the others applied are regular invoices
			INSERT tInvoiceAdvanceBill
				(
				AdvBillInvoiceKey,
				InvoiceKey,
				Amount,
				FromAB
				)
			select @InvoiceKey, EntityKey, Amount, 1
			from  #tAppl
			where ApplKey = @OldKey
			and   Entity=''tInvoiceAdvanceBill''
			and   Action=''update''

		else
			-- This invoice is a regular invoice
			-- the others applied are advbill invoices

			INSERT tInvoiceAdvanceBill
				(
				AdvBillInvoiceKey,
				InvoiceKey,
				Amount,
				FromAB
				)
			select EntityKey, @InvoiceKey, Amount, 0
			from  #tAppl
			where ApplKey = @OldKey
			and   Entity=''tInvoiceAdvanceBill''
			and   Action=''update''

		select @Error = @@ERROR, @NewKey = @@IDENTITY

		if @Error <> 0
		begin
			rollback tran
			return @kErrUnexpected
		end
		
		insert #KeyMap (Entity, OldKey, NewKey)
		VALUES (''tInvoiceAdvanceBill'', @OldKey, @NewKey)
	
	end

if @AddMode = 0
begin
		
	update tInvoiceAdvanceBill
		set tInvoiceAdvanceBill.Amount = b.Amount
	from #tAppl b
	where tInvoiceAdvanceBill.InvoiceAdvanceBillKey = b.ApplKey
	and   b.ApplKey > 0
	and   b.Entity=''tInvoiceAdvanceBill''
	and   b.Action=''update''
	-- added 11/11/11 for issue 116847
	and   (tInvoiceAdvanceBill.InvoiceKey = @InvoiceKey OR tInvoiceAdvanceBill.AdvBillInvoiceKey = @InvoiceKey)

	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end
	
end



/*
* Invoice Advance Bill tax
*/

-- cleanup records, UI may leave records with Amount=0, no need to clutter db
delete #tInvoiceAdvanceBillTax where Amount = 0

if @AddMode = 0
begin
	-- delete everything
	delete tInvoiceAdvanceBillTax where InvoiceKey = @InvoiceKey

	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end

	delete tInvoiceAdvanceBillTax where AdvBillInvoiceKey = @InvoiceKey

	if @@ERROR <> 0
	begin
		rollback tran
		return @kErrUnexpected
	end

end

update #tInvoiceAdvanceBillTax set InvoiceKey = @InvoiceKey where isnull(InvoiceKey, 0) = 0
update #tInvoiceAdvanceBillTax set AdvBillInvoiceKey = @InvoiceKey where isnull(AdvBillInvoiceKey, 0) = 0

-- 172334 prevent situation where the records exist in tInvoiceAdvanceBillTax but not in tInvoiceAdvanceBill
delete #tInvoiceAdvanceBillTax
where  InvoiceKey not in (select InvoiceKey from tInvoiceAdvanceBill (nolock) )

delete #tInvoiceAdvanceBillTax
where  AdvBillInvoiceKey not in (select AdvBillInvoiceKey from tInvoiceAdvanceBill (nolock) )

insert tInvoiceAdvanceBillTax (InvoiceKey, AdvBillInvoiceKey, SalesTaxKey, Amount)
select InvoiceKey, AdvBillInvoiceKey, SalesTaxKey, Amount
from   #tInvoiceAdvanceBillTax

if @@ERROR <> 0
begin
	rollback tran
	return @kErrUnexpected
end

/*
* Invoiceline tax
*/

if @AddMode = 0
begin
	-- I remove everything and will remove the identity InvoiceLineTaxKey later

	if exists (select 1 from tInvoiceLineTax ilt (nolock)
		inner join tInvoiceLine il (nolock) on ilt.InvoiceLineKey = il.InvoiceLineKey
		where il.InvoiceKey =@InvoiceKey
		) 	
	delete tInvoiceLineTax
	from   tInvoiceLine il (nolock)
	where  tInvoiceLineTax.InvoiceLineKey = il.InvoiceLineKey 
	and    il.InvoiceKey = @InvoiceKey
	
	 IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
end


    update #tInvoiceLineTax
	set    #tInvoiceLineTax.NewInvoiceLineKey = b.NewKey
	from   #KeyMap b
	where  #tInvoiceLineTax.InvoiceLineKey = b.OldKey
	and    b.Entity = ''tInvoiceLine''

	delete #tInvoiceLineTax
	from   tInvoiceLine il (nolock)
	where  #tInvoiceLineTax.NewInvoiceLineKey = il.InvoiceLineKey 
	and    il.InvoiceKey = @InvoiceKey
	and    il.LineType = 1 -- if this is a summary line, do not take taxes  

	insert tInvoiceLineTax (InvoiceLineKey, SalesTaxKey, SalesTaxAmount)
	select NewInvoiceLineKey, SalesTaxKey, SalesTaxAmount
	from   #tInvoiceLineTax 

	 IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END

if @TransactionsUpdated = 1
begin
	-- now that invoice lines are processed, process the transactions
	update #transaction
	set    #transaction.NewInvoiceLineKey = b.NewKey
	from   #KeyMap b
	where  #transaction.InvoiceLineKey = b.OldKey
	and    b.Entity = ''tInvoiceLine''


	-- now transactions, tTime last

	if exists (select 1 from #transaction where Entity = ''tMiscCost'')
	begin
		UPDATE tMiscCost
		SET	   tMiscCost.AmountBilled     = CASE WHEN b.Action = ''update'' THEN b.AmountBilled ELSE 0 END
			   ,tMiscCost.InvoiceLineKey  = CASE WHEN b.Action = ''update'' THEN b.NewInvoiceLineKey ELSE NULL END
			   ,tMiscCost.DateBilled      = CASE WHEN b.Action = ''update'' THEN @PostingDate ELSE NULL END
			   ,tMiscCost.BilledItem   = CASE WHEN b.Action = ''update'' THEN 
						CASE WHEN b.BilledItem IS NULL THEN tMiscCost.ItemKey ELSE b.BilledItem END
						ELSE NULL END
			   ,tMiscCost.BilledComment   = CASE WHEN b.Action = ''update'' THEN b.BillingComments ELSE NULL END

		FROM   #transaction b
		WHERE  tMiscCost.MiscCostKey = b.EntityKey
		AND    b.Entity = ''tMiscCost'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tExpenseReceipt'')
	begin
		UPDATE tExpenseReceipt
		SET	   tExpenseReceipt.AmountBilled     = CASE WHEN b.Action = ''update'' THEN b.AmountBilled ELSE 0 END
			   ,tExpenseReceipt.InvoiceLineKey  = CASE WHEN b.Action = ''update'' THEN b.NewInvoiceLineKey ELSE NULL END
			   ,tExpenseReceipt.DateBilled      = CASE WHEN b.Action = ''update'' THEN @PostingDate ELSE NULL END
			   ,tExpenseReceipt.BilledItem   = CASE WHEN b.Action = ''update'' THEN 
						CASE WHEN b.BilledItem IS NULL THEN tExpenseReceipt.ItemKey ELSE b.BilledItem END
						ELSE NULL END
			   ,tExpenseReceipt.BilledComment   = CASE WHEN b.Action = ''update'' THEN b.BillingComments ELSE NULL END

		FROM   #transaction b
		WHERE  tExpenseReceipt.ExpenseReceiptKey = b.EntityKey
		AND    b.Entity = ''tExpenseReceipt'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tPurchaseOrderDetail'')
	begin
		UPDATE tPurchaseOrderDetail
		SET	   tPurchaseOrderDetail.AmountBilled     = CASE WHEN b.Action = ''update'' THEN b.AmountBilled ELSE 0 END
			   ,tPurchaseOrderDetail.InvoiceLineKey  = CASE WHEN b.Action = ''update'' THEN b.NewInvoiceLineKey ELSE NULL END
			   ,tPurchaseOrderDetail.DateBilled      = CASE WHEN b.Action = ''update'' THEN @PostingDate ELSE NULL END
		       ,tPurchaseOrderDetail.AccruedCost     = CASE WHEN b.Action = ''update'' THEN    
			                                                CASE WHEN po.BillAt < 2 THEN 
															ROUND(tPurchaseOrderDetail.TotalCost * isnull(po.ExchangeRate,1), 2)
				                                            ELSE 0 END
													   ELSE NULL END
			   ,tPurchaseOrderDetail.BilledItem   = CASE WHEN b.Action = ''update'' THEN 
						CASE WHEN b.BilledItem IS NULL THEN tPurchaseOrderDetail.ItemKey ELSE b.BilledItem END
						ELSE NULL END
			   ,tPurchaseOrderDetail.BilledComment   = CASE WHEN b.Action = ''update'' THEN b.BillingComments ELSE NULL END

		FROM   #transaction b
		      ,tPurchaseOrder po (nolock)
		WHERE  tPurchaseOrderDetail.PurchaseOrderDetailKey = b.EntityKey
		AND    b.Entity = ''tPurchaseOrderDetail'' 
		AND    tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tVoucherDetail'')
	begin
		UPDATE tVoucherDetail
		SET	   tVoucherDetail.AmountBilled     = CASE WHEN b.Action = ''update'' THEN b.AmountBilled ELSE 0 END
			   ,tVoucherDetail.InvoiceLineKey  = CASE WHEN b.Action = ''update'' THEN b.NewInvoiceLineKey ELSE NULL END
			   ,tVoucherDetail.DateBilled      = CASE WHEN b.Action = ''update'' THEN @PostingDate ELSE NULL END
			   ,tVoucherDetail.BilledItem   = CASE WHEN b.Action = ''update'' THEN 
						CASE WHEN b.BilledItem IS NULL THEN tVoucherDetail.ItemKey ELSE b.BilledItem END
						ELSE NULL END
			   ,tVoucherDetail.BilledComment   = CASE WHEN b.Action = ''update'' THEN b.BillingComments ELSE NULL END
		FROM   #transaction b
		WHERE  tVoucherDetail.VoucherDetailKey = b.EntityKey -- (128535)
		AND    b.Entity = ''tVoucherDetail'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tTime'')
	begin
		UPDATE tTime
		SET	   tTime.BilledHours     = CASE WHEN b.Action = ''update'' THEN b.BilledHours ELSE 0 END
			   ,tTime.BilledRate     = CASE WHEN b.Action = ''update'' THEN b.BilledRate ELSE 0 END
			   ,tTime.InvoiceLineKey  = CASE WHEN b.Action = ''update'' THEN b.NewInvoiceLineKey ELSE NULL END
			   ,tTime.DateBilled      = CASE WHEN b.Action = ''update'' THEN @PostingDate ELSE NULL END
			   ,tTime.BilledService   = CASE WHEN b.Action = ''update'' THEN 
						CASE WHEN b.BilledService IS NULL THEN tTime.ServiceKey ELSE b.BilledService END
						ELSE NULL END
			   ,tTime.BilledComment   = CASE WHEN b.Action = ''update'' THEN b.BillingComments ELSE NULL END
		FROM   #transaction b
		WHERE  tTime.TimeKey = b.TimeKey
		AND    b.Entity = ''tTime'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

end -- @TransactionsUpdated = 1

if @TransactionsUpdated = 0 and @PostingDate <> @CurPostingDate
begin
	if exists (select 1 from #transaction where Entity = ''tMiscCost'')
	begin
		UPDATE tMiscCost
		SET	   tMiscCost.DateBilled = @PostingDate
		FROM   #transaction b
		WHERE  tMiscCost.MiscCostKey = b.EntityKey
		AND    b.Entity = ''tMiscCost'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tExpenseReceipt'')
	begin
		UPDATE tExpenseReceipt
		SET	   tExpenseReceipt.DateBilled  = @PostingDate
		FROM   #transaction b
		WHERE  tExpenseReceipt.ExpenseReceiptKey = b.EntityKey
		AND    b.Entity = ''tExpenseReceipt'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tPurchaseOrderDetail'')
	begin
		UPDATE tPurchaseOrderDetail
		SET	   tPurchaseOrderDetail.DateBilled = @PostingDate
		FROM   #transaction b
		      ,tPurchaseOrder po (nolock)
		WHERE  tPurchaseOrderDetail.PurchaseOrderDetailKey = b.EntityKey
		AND    b.Entity = ''tPurchaseOrderDetail'' 
		AND    tPurchaseOrderDetail.PurchaseOrderKey = po.PurchaseOrderKey

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tVoucherDetail'')
	begin
		UPDATE tVoucherDetail
		SET	   tVoucherDetail.DateBilled = @PostingDate
		FROM   #transaction b
		WHERE  tVoucherDetail.VoucherDetailKey = b.EntityKey
		AND    b.Entity = ''tVoucherDetail'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

	if exists (select 1 from #transaction where Entity = ''tTime'')
	begin
		UPDATE tTime
		SET	   tTime.DateBilled = @PostingDate
		FROM   #transaction b
		WHERE  tTime.TimeKey = b.TimeKey
		AND    b.Entity = ''tTime'' 

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN @kErrUnexpected	
		END
	end

end -- @TransactionsUpdated = 0


commit tran


/*
* Split Billing
*/


update #tSplit
set    #tSplit.Action = ''insert'' 
where  #tSplit.InvoiceKey <= 0

update tInvoice
set    tInvoice.PercentageSplit = b.PercentageSplit
from   #tSplit b
where  tInvoice.ParentInvoiceKey = @InvoiceKey
and    tInvoice.InvoiceKey = b.InvoiceKey
and    b.Action = ''update''

declare @PercentageSplit decimal(24, 4)

select @LoopInvoiceKey = -1000
while (1=1)
begin
	select @LoopInvoiceKey = min(InvoiceKey)
	from   #tSplit
	where  InvoiceKey > @LoopInvoiceKey  
	and    Action = ''insert''

	if @LoopInvoiceKey is null
		break

	select @ClientKey = ClientKey
	      ,@PercentageSplit = PercentageSplit
	from   #tSplit
	where  InvoiceKey = @LoopInvoiceKey

	exec sptInvoiceInsertSplit @InvoiceKey, @ClientKey, @PercentageSplit

end

/*
* Updates of summary tables start here
*/

-- This should create the tInvoiceTax records and tInvoiceSummary
-- and also take care of the child invoices
declare @InvoiceTaxRecordsOnly int	select @InvoiceTaxRecordsOnly = 1

-- if are importing, recalc everything
if @InvoiceTotalAmount = 0 Or @TotalNonTaxAmount = 0
	select @InvoiceTaxRecordsOnly = 0

if isnull(@ParentInvoiceKey, 0) = 0
exec sptInvoiceRollupAmounts @InvoiceKey, @InvoiceTaxRecordsOnly

-- this is a patch for 156432
-- One company has problems with the rollup (they add transactions to a line and then delete them very quickly)
-- Could be some timing issue in the flex code (can''t be duplicated)
if @ParentInvoice = 0 And isnull(@ParentInvoiceKey, 0) = 0 And @CurPosted = 0
BEGIN			
	update tInvoice
	set    tInvoice.TotalNonTaxAmount = isnull((
			select SUM(il.TotalAmount)
			FROM    tInvoiceLine il (NOLOCK)
			where   il.InvoiceKey = tInvoice.InvoiceKey
			and     il.LineType = 2
			),0)
			,tInvoice.SalesTaxAmount = isnull((
			select SUM(il.SalesTaxAmount)
			FROM    tInvoiceLine il (NOLOCK)
			where   il.InvoiceKey = tInvoice.InvoiceKey
			and     il.LineType = 2
			),0)
			,tInvoice.SalesTax1Amount = isnull((
			select SUM(il.SalesTax1Amount)
			FROM    tInvoiceLine il (NOLOCK)
			where   il.InvoiceKey = tInvoice.InvoiceKey
			and     il.LineType = 2
			),0)
			,tInvoice.SalesTax2Amount = isnull((
			select SUM(il.SalesTax2Amount)
			FROM    tInvoiceLine il (NOLOCK)
			where   il.InvoiceKey = tInvoice.InvoiceKey
			and     il.LineType = 2
			),0)
	where   tInvoice.InvoiceKey = @InvoiceKey

	update tInvoice
	set    InvoiceTotalAmount = isnull(TotalNonTaxAmount, 0) + isnull(SalesTaxAmount, 0)
	where  InvoiceKey = @InvoiceKey

END

if isnull(@ParentInvoiceKey, 0) > 0
begin
	-- in case the user changes taxes on the header
	-- they have been recalced from the client side, so delete them here
	if isnull(@CurSalesTaxKey, 0) <> isnull(@SalesTaxKey, 0) OR isnull(@CurSalesTax2Key,0) <> isnull(@SalesTax2Key, 0)
	begin
		-- this will RELOAD tInvoiceTax from #tax, update invoice header amounts and call sptInvoiceSummary
		exec sptInvoiceTaxInsertMultiple @InvoiceKey, 0
	end
	else
	begin
		-- this will simply update tInvoiceTax amounts, update invoice header amounts and call sptInvoiceSummary
		exec sptInvoiceTaxInsertMultiple @InvoiceKey, 1
	end
end

-- If projects have been removed, we must recalc the billing info rollup
SELECT @ProjectKey = -1
WHILE (1=1)
BEGIN
	SELECT @ProjectKey = MIN(ProjectKey)
	FROM   #removedProjects
	WHERE  ProjectKey > @ProjectKey
	

	IF @ProjectKey IS NULL
		BREAK
			
	EXEC sptProjectRollupUpdate @ProjectKey, 6, 0, 0, 0, 0
END

if @TransactionsUpdated = 1
begin

	-- prepare temp for project rollup
	update #transaction set UpdateFlag = 0
	update #transaction 
	set    #transaction.UpdateFlag = 1
	where  #transaction.ProjectKey not in (select ProjectKey from tInvoiceSummary (nolock) where InvoiceKey = @InvoiceKey)
	and    #transaction.Action = ''remove''

	-- Project rollup (all trans, all types) for the transactions we removed...these projects are not in tInvoiceSummary
		SELECT @ProjectKey = -1
		WHILE (1=1)
		BEGIN
			SELECT @ProjectKey = MIN(ProjectKey)
			FROM   #transaction
			WHERE  ProjectKey > @ProjectKey
			AND    UpdateFlag = 1


			IF @ProjectKey IS NULL
				BREAK
			
			EXEC sptProjectRollupUpdate @ProjectKey, -1, 1, 1, 1, 1
		END

end

	-- now projects in tInvoiceSummary...are done off line after the update from flex
	-- by calling sptProjectRollupUpdateEntity

	-- now update DatePaid on vouchers
	declare @VouchersRecordsOnly int	select @VouchersRecordsOnly = 1
	exec sptInvoiceUpdateAmountPaid @InvoiceKey, @VouchersRecordsOnly 

	exec sptInvoiceLineSetHours @InvoiceKey
	if @ParentInvoiceKey > 0
		exec sptInvoiceLineSetHours @ParentInvoiceKey
	
	-- update the retainer amount on OTHER real invoices
	declare @Posted int
	select @LoopInvoiceKey = -1
	while (1=1)
	begin
		select @LoopInvoiceKey = min(InvoiceKey)
		from   #recalcRetainerAmt
		where  InvoiceKey > @LoopInvoiceKey

		if @LoopInvoiceKey is null
			break

		select @RetainerAmount =  Sum(Amount) from tInvoiceAdvanceBill (nolock) Where InvoiceKey = @LoopInvoiceKey and InvoiceKey <> AdvBillInvoiceKey

		Update tInvoice Set RetainerAmount = ISNULL(@RetainerAmount, 0) Where InvoiceKey = @LoopInvoiceKey

		exec sptInvoiceUpdateAmountPaid @LoopInvoiceKey
	end


	-- now recalc amount paid on invoices involved with credits
	select @LoopInvoiceKey = -1
	while (1=1)
	begin
		select @LoopInvoiceKey = min(InvoiceKey)
		from   #recalcAmtPaid
		where  InvoiceKey > @LoopInvoiceKey

		if @LoopInvoiceKey is null
			break

		exec sptInvoiceUpdateAmountPaid @LoopInvoiceKey

	end

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
*/

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].[sptCalendarScheduledReportSetReminderCache]'
GO
IF OBJECT_ID(N'[dbo].[sptCalendarScheduledReportSetReminderCache]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER Procedure [dbo].[sptCalendarScheduledReportSetReminderCache]

	(
		@CalendarKey int,
		@CompanyKey int
	)

AS --Encrypt

/*
|| When      Who Rel      What
|| 11/06/24  RLB 24.12.15 (684679) Added for enhancement will add to que but can only be done once a day since que has some protection from sending multiple times
|| 06/01/26 RLB 26.06.14 (729627) only try to add once then clear any next schedule date so they do not keep trying to send them
*/

Declare @NewSendTime as smalldatetime = GETUTCDATE()
Declare @NewEventStart as smalldatetime = GETUTCDATE()
Declare @NewEventStarEnd as smalldatetime = GETUTCDATE()

SELECT @NewSendTime = DATEADD(mi, 1,   @NewSendTime);
SELECT @NewEventStart = @NewSendTime;
SELECT @NewEventStarEnd = DATEADD(mi, 2,   @NewSendTime);
select @NewSendTime


insert tReminderCache(CalendarKey,CompanyKey,ActivityKey,UserKey,SendTime,IsReport,EventStart,EventEnd)
SELECT	@CalendarKey, @CompanyKey,0, 0,@NewSendTime, 1,@NewEventStart,@NewEventStarEnd

UPDATE tCalendar SET NextScheduleDate = null where CalendarKey = @CalendarKey

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

ALTER PROCEDURE [dbo].[sptCalendarScheduledReportUpdateNextScheduleDate]
	@CalendarKey int
AS --Encrypt

/*
|| When     Who Rel      What
|| 11/08/24 RLB 24.12.15 (684679) created to update NextScheduleDate on scheduled reports
|| 06/01/26 RLB 26.06.14 (729627) fix for monthly and yearly next date not set correctly for last week option
*/

Declare @Frequency varchar(50)
	,@Interval int
	,@ByMonthDay int
	,@Su tinyint
	,@Mo tinyint
	,@Tu tinyint
	,@We tinyint
	,@Th tinyint
	,@Fr tinyint
	,@Sa tinyint
	,@BySetPos int
	,@ByMonth int
	,@NextDate smalldatetime
	,@NextNextDate smalldatetime
	,@CurrentDatePart int
	,@SelectedDatePart int
	,@addDays int


select @NextDate = NextScheduleDate
		,@Interval = Interval
		,@Frequency = Freq
		,@ByMonthDay = ByMonthDay
		,@Su = Su
		,@Mo = Mo
		,@Tu = Tu
		,@We = We
		,@Th = Th
		,@Fr = Fr
		,@Sa = Sa
		,@BySetPos = BySetPos
		,@ByMonth = ByMonth
		,@SelectedDatePart = CASE
			WHEN Su = 1 then 1
			WHEN Mo = 1 then 2
			when Tu = 1 then 3
			when We = 1 then 4
			when Th = 1 then 5
			when Fr = 1 then 6
			when Sa = 1 then 7
			else 0
		end
	from tCalendar
	where CalendarKey = @CalendarKey

Select @NextNextDate = dbo.fFormatDateNoTime(GETDATE())    

if @Frequency = ''DAILY''
BEGIN
	if isnull(@Interval, 0) = 0 and @Mo = 1 and @Tu = 1 and @We = 1 and @Th = 1 and @Fr = 1
	begin
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)
		Select @CurrentDatePart = DATEPART(dw,@NextNextDate)
		if @CurrentDatePart = 1
			Select @NextNextDate = dateadd(d, 2,@NextNextDate)
		else if @CurrentDatePart = 2
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
		else if @CurrentDatePart = 3
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
		else if @CurrentDatePart = 4
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
		else if @CurrentDatePart = 5
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
		else if @CurrentDatePart = 6
			Select @NextNextDate = dateadd(d, 4,@NextNextDate)
		else if @CurrentDatePart = 7
			Select @NextNextDate = dateadd(d, 3,@NextNextDate)
	end
	else
	begin
		Select @NextNextDate = dateadd(d, @Interval,@NextNextDate)
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	end
END

if @Frequency = ''WEEKLY''
BEGIN
	select @addDays = 7 * @Interval
	Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
	SELECT @CurrentDatePart = DATEPART(dw,@NextNextDate)
	IF @Su = 1 and @CurrentDatePart = 1
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	else if @Mo = 1 and @CurrentDatePart < 3
		if @CurrentDatePart = 1
			Select @NextNextDate = dateadd(d, 2,@NextNextDate)
		else	
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	else if @Tu = 1 and @CurrentDatePart < 4
		if @CurrentDatePart = 1
			Select @NextNextDate = dateadd(d, 3,@NextNextDate)
		else if @CurrentDatePart = 2
			Select @NextNextDate = dateadd(d, 2,@NextNextDate)
		else if @CurrentDatePart = 3
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	else if @We = 1 and @CurrentDatePart < 5
		if @CurrentDatePart = 1
			Select @NextNextDate = dateadd(d, 4,@NextNextDate)
		else if @CurrentDatePart = 2
			Select @NextNextDate = dateadd(d, 3,@NextNextDate)
		else if @CurrentDatePart = 3
			Select @NextNextDate = dateadd(d, 2,@NextNextDate)
		else if @CurrentDatePart = 4
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	else if @Th = 1 and @CurrentDatePart < 6
		if @CurrentDatePart = 1
			Select @NextNextDate = dateadd(d, 5,@NextNextDate)
		else if @CurrentDatePart = 2
			Select @NextNextDate = dateadd(d, 4,@NextNextDate)
		else if @CurrentDatePart = 3
			Select @NextNextDate = dateadd(d, 3,@NextNextDate)
		else if @CurrentDatePart = 4
			Select @NextNextDate = dateadd(d, 2,@NextNextDate)
		else if @CurrentDatePart = 5
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	else if @Fr = 1 and @CurrentDatePart < 7
		if @CurrentDatePart = 1
			Select @NextNextDate = dateadd(d, 6,@NextNextDate)
		else if @CurrentDatePart = 2
			Select @NextNextDate = dateadd(d, 5,@NextNextDate)
		else if @CurrentDatePart = 3
			Select @NextNextDate = dateadd(d, 4,@NextNextDate)
		else if @CurrentDatePart = 4
			Select @NextNextDate = dateadd(d, 3,@NextNextDate)
		else if @CurrentDatePart = 5
			Select @NextNextDate = dateadd(d, 2,@NextNextDate)
		else if @CurrentDatePart = 6
			Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	else if @Sa = 1 and @CurrentDatePart = 7
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)	
END

if @Frequency = ''MONTHLY''
BEGIN
	IF @ByMonthDay > 0
	begin
		Select @NextNextDate = dateadd(m, @Interval,@NextNextDate)
		SELECT @NextNextDate = DATEFROMPARTS (DATEPART(YY,@NextNextDate), DATEPART(M,@NextNextDate), @ByMonthDay);
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)	
		end
	else
	begin
		Select @NextNextDate = dateadd(m, @Interval,@NextNextDate)
		SELECT @NextNextDate = DATEFROMPARTS (DATEPART(YY,@NextNextDate), DATEPART(M,@NextNextDate), 1);
		SELECT @CurrentDatePart = DATEPART(dw,@NextNextDate)
		if @CurrentDatePart <= @SelectedDatePart
		begin
			select @addDays = @SelectedDatePart - @CurrentDatePart
			Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
		end
		else
		begin
			select @addDays = @SelectedDatePart - @CurrentDatePart
			Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
			Select @NextNextDate = dateadd(d, 7,@NextNextDate)
		end
		
		if @BySetPos = -1
			select @addDays = -7
		else
			if @BySetPos = 1
				select @addDays = 0
			else
				select @addDays = 7 * (@BySetPos -1)

		Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	end
END

if @Frequency = ''YEARLY''
BEGIN
	IF @ByMonthDay > 0
	begin
	Select @NextNextDate = dateadd(YY, 1,@NextNextDate)
	SELECT @NextNextDate = DATEFROMPARTS (DATEPART(YY,@NextNextDate), @ByMonth, @ByMonthDay);
	Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	end
	else
	begin
		Select @NextNextDate = dateadd(YY, 1,@NextNextDate)
		SELECT @NextNextDate = DATEFROMPARTS (DATEPART(YY,@NextNextDate), @ByMonth, 1);
		SELECT @CurrentDatePart = DATEPART(dw,@NextNextDate)
	
		if @CurrentDatePart <= @SelectedDatePart
		begin
			select @addDays = @SelectedDatePart - @CurrentDatePart
			Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
		end
		else
		begin
			select @addDays = @SelectedDatePart - @CurrentDatePart
			Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
			Select @NextNextDate = dateadd(d, 7,@NextNextDate)
		end
		
		if @BySetPos = -1
			select @addDays = -7
		else
			if @BySetPos = 1
				select @addDays = 0
			else
				select @addDays = 7 * (@BySetPos -1)

		Select @NextNextDate = dateadd(d, @addDays,@NextNextDate)
		Select @NextNextDate = dateadd(d, 1,@NextNextDate)
	end
END


Select @NextDate = @NextNextDate 
	
UPDATE
	tCalendar
SET

	NextScheduleDate = @NextDate	
WHERE
	CalendarKey = @CalendarKey 

	
	
	RETURN @CalendarKey 





'
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
*/

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].[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.
*/

Declare @SecurityGroupKey int
Declare @IsAdministrator bit
Declare @TargetUserKey int

Select * into #errors From tAPIErrorTemplate Where 1 = 2

-- If a user name was provided, resolve it to a UserKey and check security
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

	-- Only chech security when viewing a different user''s calendar
	If @TargetUserKey <> @UserKey
	Begin
		Select @SecurityGroupKey = SecurityGroupKey,
			@IsAdministrator = Administrator
		From tUser (nolock)
		Where UserKey = @UserKey
			And CompanyKey = @CompanyKey

		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 = ''SecurityGroup''
				And ra.EntityKey = @SecurityGroupKey
				And r.RightID = ''admineditusercalendar''
			)
			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
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

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
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vListing_Request]'
GO
IF OBJECT_ID(N'[dbo].[vListing_Request]', 'V') IS NOT NULL
EXEC sp_executesql N'














ALTER View [dbo].[vListing_Request]

As

/*
|| When       Who Rel       What
|| 07/02/14   QMD 10.5.8.1  (220667) Added Date Cancelled and Date Sent for Approval
|| 07/21/14   GHL 10.5.8.2  (223349) Added Date Approved
|| 03/25/15   WDF 10.5.9.0  (250961) Added [Created By],[Created Date],[Updated By] and [Updated Date]
|| 05/13/15   WDF 10.5.9.2  (256578) Added [Reject Reason Name]
|| 11/01/17   GHL 10.6.2.2  (374562) Added OriginalDateSentForApproval for kohls enhancement
|| 05/21/18   WDF 18.6.0    (402084) Removed [Date Approved] logic from Select and placed it in a derived table
|| 05/22/18   GHL 18.6.0    (401883) Added separated status fields to help with performance issues at Kohls
|| 09/21/18   RLS 18.9.1    (421048) Added [Parent Company]
|| 10/24/19   RLS 19.1.1.0  (466765) Added [Attachments]
|| 11/14/19   GAR 19.1.2.0  (487821) Cast Project Description as VARCHAR(MAX) so it can be used in Where clause for views
|| 04/17/20   RLS 20.0.5.0  (509551) Added CampaignID, CampaignName and SegmentName
|| 07/09/20   GAR 20.0.8.0  (518830) Change Project Requested By field to grab the name based on the key instead of the text name
|| 09/02/20   RLB 20.1.0.0  (523772) making anything using user name common format
|| 11/03/20   GAR 20.1.1.0  (534898) Added account manager and project manager from the client
|| 12/30/20   GHL 21.01.24.0 (541935) Added Split Billing column to display the % per client of split billing
|| 01/12/23   GAR 23.02.19  (627108) Added Project Created
|| 09/05/24   RLS 24.10.20  (668040) Added r.Subject and r.RequestID for use in HideFields in views.xml
|| 05/27/26   RLB 26.06.14  (729321) Changed Date Approved to include step action 3 since approvals can now be on both
*/

Select 
	 r.RequestKey
	,r.CompanyKey
	,r.ClientKey
	,r.CustomFieldKey
	,r.Subject as [Project Name]
	,r.Subject -- Not aliased. Needed for HideFields
	,CAST(r.ProjectDescription AS VARCHAR(MAX)) as [Project Description]
	,r.ClientProjectNumber as [Client Project Number]
	,r.DueDate as [Project Due Date]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,pc.CompanyName as [Parent Company]
	,c.CustomerID + '' - '' + c.CompanyName as [Client ID and Name]
	,c.ParentCompanyKey
	,rd.RequestName as [Request Type]
	,r.RequestID as [Request ID]
	,r.RequestID -- Not aliased. Needed for HideFields
	,Case When r.DateCompleted is null then
		Case Status 
		When 1 then 
			Case r.Cancelled
				When 0 then ''Not Sent For Approval''
				When 1 then ''Cancelled''
				else ''Not Sent For Approval''
			end
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then ''Approved''
		end
	 else
		''Completed'' end as [Request Status]
	-- separated the [Request Status] because it degrades performance in the where clause  (401883)
	,case when r.DateCompleted is null then ''NO'' else ''YES'' end as Completed
	,case r.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]
	,Case r.Cancelled
				When 0 then ''NO'' 
				When 1 then ''YES''    
				else ''NO''
	end as Cancelled
	,Case When r.DateCompleted is null then
		Case Status 
			When 3 then rrr.ReasonName 
			else NULL 
		end
	 else
		NULL end as [Reject Reason Name]
	,r.DateAdded as [Date Added]
	,r.DateAdded as [Created Date]
	,r.DateCompleted as [Date Completed]
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Entered By]
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Created By]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Updated By]
	,r.DateUpdated as [Updated Date]
	,ISNULL(upr.UserName, r.RequestedBy) as [Requested By]
	,r.NotifyEmail as [Email to Notify]
	,r.DateCancelled as [Date Cancelled]
	,r.DateSentForApproval as [Date Sent For Approval]
	,isnull(r.OriginalDateSentForApproval, r.DateSentForApproval) as [Original Date Sent For Approval]
	,reqDt.DateApproved as [Date Approved]
	,(select count(*) from tAttachment a (nolock)
		where a.EntityKey = r.RequestKey and AssociatedEntity = ''ProjectRequest'') as [Attachments]
	,r.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign Name]
	,cs.SegmentName as [Campaign Segment]
	,pm_client.UserName as [Client Project Manager]
	,am_client.UserName as [Client Account Manager]
	, Substring(
	(
		select '', '' + cl2.CustomerID  + '': '' + cast(cast(splitbill.Split as decimal(24,2)) as varchar) + ''%''  AS [text()]
					FROM tRequestSplit splitbill (nolock)
						inner join tCompany cl2 (nolock) on splitbill.ClientKey = cl2.CompanyKey
					WHERE splitbill.RequestKey = r.RequestKey
					ORDER BY cl2.CustomerID
					FOR XML PATH ('''')
	 ), 2, 5000) as [Split Billing]
	 ,Case (SELECT COUNT(*) FROM tProject WHERE RequestKey = r.RequestKey)
				When 0 then ''NO''    
				else ''YES''
	end as [Project Created]

From
	tRequest r (nolock)
	inner join tRequestDef rd (nolock) on r.RequestDefKey = rd.RequestDefKey
	inner join (Select CompanyKey, RequestKey, Null as DateApproved
                  From tRequest (nolock) Where Status != 4
                UNION ALL
                Select CompanyKey, RequestKey, (Select MAX(asu.DateCompleted)
                                                  From tApprovalStepUser asu (nolock) inner join tApprovalStep astep (nolock) on astep.ApprovalStepKey = asu.ApprovalStepKey 
                                                 Where astep.Entity = ''ProjectRequest'' and astep.EntityKey = RequestKey and asu.Action = 1 and (astep.Action = 2 or astep.Action = 3)
                                               ) as DateApproved
                  From tRequest (nolock) Where Status = 4) AS reqDt on (r.CompanyKey = reqDt.CompanyKey and
                                                                        r.RequestKey = reqDt.RequestKey) 
	left outer join tCompany c (nolock) on r.ClientKey = c.CompanyKey
	left outer join tUser u (nolock) on r.EnteredByKey = u.UserKey
	left outer join tUser u2 (nolock) on r.UpdatedByKey = u2.UserKey
	left outer join tRequestRejectReason rrr (NOLOCK) ON r.RequestRejectReasonKey = rrr.RequestRejectReasonKey
	left outer join tCompany pc (nolock) on c.ParentCompanyKey = pc.CompanyKey
	left outer join tCampaign ca (nolock) on r.CampaignID = ca.CampaignID and r.CompanyKey = ca.CompanyKey 
	left outer join tCampaignSegment cs (nolock) on r.CampaignSegmentKey = cs.CampaignSegmentKey
	left outer join vUserName upr (nolock) on r.RequestedByKey = upr.UserKey
	left outer join vUserName pm_client (nolock) on c.ProjectManagerKey = pm_client.UserKey 
	left outer join vUserName am_client (nolock) on c.AccountManagerKey = am_client.UserKey 





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


ALTER VIEW [dbo].[vReport_Invoice]
AS

/*
|| When     Who Rel     What
|| 10/12/06 WES 8.3567  Added Amount Advance Billed, Estimate Total
|| 03/19/07 GHL 8.408   Added Emailed
|| 03/26/07 RTC 8.4.1   (7972) Added the client division and product from the invoice detail project.
|| 10/11/07 CRG 8.5     Added GLCompany, Department, Office
|| 11/7/07  CRG 8.5     (7962) Added Client Primary Contact Phone1, Phone2, and Email
|| 01/10/08 GWG 8.502   Fixed where invoice approver was comming from
|| 02/07/08 GHL 8.503  (20833) Added Date Paid field
|| 07/31/08 GHL 8.517  (31159) Added line project description
|| 03/17/09  RTC 10.5	  Removed user defined fields. 
|| 8/7/09   CRG 10.5.0.7 (58248) Added Company CustomFieldKey
|| 10/30/09 GWG 10.5.1.3 Added Task ID, Name and Description
|| 04/30/10 RLB 10.5.2.2 (63218)Added Parent Company Name
|| 06/15/10 GWG 10.5.3.2 Added the default client sales account for CBRE
|| 08/15/10 GWG 10.5.3.2 Added a union in to pull in child invoices (cbre)
|| 09/28/10 RLB 10.5.3.5 (91043) Added Opening Transaction to report
|| 11/2/10  RLB 10.5.3.7 (89210) Added line Sales Tax 1, 2 and Total
|| 11/5/10  GHL 10.5.3.7 (93868) Added Parent Invoice flag
|| 12/2/10  RLB 10.5.3.9 (95841) Added Project Billing Status
|| 12/3/10  RLB 10.5.3.9 (93868) fixed UNION
|| 02/17/11 RLB 10.5.4.1 (104102) added Line type, Item ID and Line Item Name
|| 02/22/11 RLB 10.5.4.1 (89417) added Tax 1 and 2 applied
|| 09/01.11 RLB 10.5.4.7 (119705) Added Gl Sales Account Number
|| 04/24/12 GHL 10.555   Added GLCompanyKey in order to map/restrict
|| 09/06/12 KMC 10.5.6.0 (151883) Added Billing Group Code
|| 10/17/12 GHL 10.5.6.0 (157258) Using now tBillingGroup to get Billing Group Code
||                        because of multiple billing worksheets associated to 1 invoice
||                        (happens when master billing ws used)
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey
|| 02/20/13 GHL 10.5.6.5 (169313) Advance Bill Unapplied = 0 for regular invoices
|| 01/03/14 WDF 10.5.7.6 (188500) Added CreatedByKey and DateCreated
|| 03/07/14 GHL 10.5.7.8  Added Currency + Exchange Rate
|| 07/16/14 GWG 10.5.8.2  Fixed join for header class
|| 11/24/14 GAR 10.5.8.6  (237300) Added company state.
|| 01/26/15 GHL 10.588 Added Billing Group Description for Abelson Taylor
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
|| 01/29/15 GHL 10.588 Added Billing Title for Abelson + Title Rate Sheet
|| 08/31/15 MCM 10.5.9.5 (267568) Updating the sales tax field to retun empty string instead of null
|| 12/30/15 WDF 10.5.9.9 (283249) Added ISNULL to HeaderComment
|| 02/10/16 WDF 10.6.0.1 (284808) Added [Line Retainer Name]
|| 08/09/16 KMC 10.6.0.6 (309861) Broke out AR Account Number and AR Account Name into their own fields instead of together in AR Account.  Still kept AR Account to not break existing reports.
|| 03/12/18 GHL 18.4.0.0 (390520) Check PostSalesUsingDetail before pulling SalesAccountNumber. If 1 return null because the account number should come from the item/detail
|| 04/12/18 GHL 18.5.0.0 (395899) When blanking the SalesAccountNumber, check that BillFrom = 2 (TM) and PostSalesUsingDetail = 1
||                        Also use same logic for the child invoices (part 2 of the UNION)
|| 08/20/18 GHL 18.9.0.0 (416014) When calculating [Date Paid], also take in account the receipts applied to the advance bills applied to the current invoice
|| 09/21/18 RLS 18.9.1.0 (418192) Added Client Account Manager 
|| 05/13/19 AMP 19.0.6.0 (453506) Added Client Active (yes/no)
|| 10/24/19 GAR 19.1.1.0 (466632) Display Campaign info on the dataset even if the line does not have a project on it, but the header has campaign info
|| 04/15/20 GAR 20.0.5.0 (510595) Added Posting Month
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 11/01/21 AMP 21.12.19 (574608) Added Parent Invoice Number
|| 08/03/22 GAR 22.09.18 (606205) Added campaign segment from the project
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color and Department
|| 06/12/23 RLB 23.07.16 (634098) Added Project manager options from company, project and campaign
|| 08/11/23 RLB 23.09.17 (648008) added project type color
|| 03/01/24 RLB 24.04.14 (665317) added Company Source from client
|| 10/25/24 GAR 24.11.17 (685481) Added Timeline Segment
|| 11/25/24 RLB 24.12.15 (688446) Added Current Labor Budget Gross from project header
|| 07/15/25 RLB 25.08.17 (705638) Added Estimate Total with Tax
|| 07/28/25 RLS 25.08.17 (705304) Added [Is an Active Client]
|| 04/07/26 AMP 26.05.17 (725534) Added Advance Bill Liability Account fields
|| 04/13/26 GAR 26.05.17 (726197) Added Project Address if it exists for Avalara
|| 05/27/26 RLS 26.06.14 (727104) Added CustomFieldKey4
*/

SELECT
	i.CompanyKey, 
	isnull(il.TargetGLCompanyKey, i.GLCompanyKey) as GLCompanyKey, 
	p.CustomFieldKey,
	c.CustomFieldKey AS CustomFieldKey2,
    bcu.CustomFieldKey AS CustomFieldKey3,
	ISNULL(cp.CustomFieldKey, icp.CustomFieldKey) AS CustomFieldKey4,
	cd.DivisionName as [Division Name],
	cd.DivisionID as [Division ID],
	pd.ProductName as [Product Name],
	pd.ProductID as [Product ID],
	i.InvoiceNumber AS [Invoice Number], 
	i.InvoiceDate AS [Invoice Date], 
	i.PostingDate as [Posting Date],
	DATENAME(Year, i.PostingDate) + ''_'' + RIGHT(''0'' + CAST(DATEPART(Month, i.PostingDate) AS VARCHAR(2)), 2) AS [Posting Month],
	i.DueDate AS [Due Date], 
	i.DateCreated AS [Date Created], 
	case i.AdvanceBill when 1 then ''YES'' else ''NO'' end as [Advance Billing Invoice],
	i.UserDefined1 as [Invoice User Defined 1],
	i.UserDefined2 as [Invoice User Defined 2],
	i.UserDefined3 as [Invoice User Defined 3],
	i.UserDefined4 as [Invoice User Defined 4],
	i.UserDefined5 as [Invoice User Defined 5],
	i.UserDefined6 as [Invoice User Defined 6],
	i.UserDefined7 as [Invoice User Defined 7],
	i.UserDefined8 as [Invoice User Defined 8],
	i.UserDefined9 as [Invoice User Defined 9],
	i.UserDefined10 as [Invoice User Defined 10],
	c.CompanyName AS [Client Name], 
	c.CustomerID AS [Client ID], 
	c.CustomerID + '' - '' + c.CompanyName AS [Client Full Name], 
	i.ContactName as [Bill To Contact],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Address1 ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Address1 ELSE ad.Address1 END
			end AS [Bill To Address1],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Address2 ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Address2 ELSE ad.Address2 END
			end AS [Bill To Address2],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Address3 ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Address3 ELSE ad.Address3 END
			end AS [Bill To Address3],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.City ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.City ELSE ad.City END
			end AS [Bill To City],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.State ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.State ELSE ad.State END
			end AS [Bill To State],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.PostalCode ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.PostalCode ELSE ad.PostalCode END
			end AS [Bill To Postal Code],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Country ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Country ELSE ad.Country END
			end AS [Bill To Country],
	pt.TermsDescription AS Terms, 
	glAR.AccountNumber AS [AR Account Number],
	glAR.AccountName AS [AR Account Name],
	glAR.AccountNumber + '' - '' + glAR.AccountName AS [AR Account], 
	glCL.AccountNumber + '' - '' + glCL.AccountName AS [Default Client Sales Account], 
	glLiab.AccountNumber AS [Advance Bill Liability Account Number],
	glLiab.AccountName AS [Advance Bill Liability Account Name],
	glLiab.AccountNumber + '' - '' + glLiab.AccountName AS [Advance Bill Liability Account],
	pr.ProjectNumber as [Project Number],
	pr.ProjectName as [Project Name], 
	pr.ProjectNumber + '' - '' + pr.ProjectName as [Project Full Name],
	pr.ClientProjectNumber as [Client Project Number],
	i.WriteoffAmount AS [Invoice Writeoff Amount], 
	i.RetainerAmount AS [Invoice Adv Bill Amount], 
	i.InvoiceTotalAmount as [Invoice Total With Tax],
	i.TotalNonTaxAmount as [Invoice Total No Tax],
	i.InvoiceTotalAmount - i.TotalNonTaxAmount as [Invoice Total Tax],
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.AmountReceived, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0) as [Amount Open],
    ISNULL(i.HeaderComment, '''') as [Invoice Comment], 
	i.ApprovalComments as [Approval Comments],
	cl2.ClassID as [Header Class ID],
	cl2.ClassName as [Header Class Name],
	case when i.AdvanceBill = 1 then
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where AdvBillInvoiceKey = i.InvoiceKey),0) 
	else 0 end as [Advance Bill Unapplied],
	ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where InvoiceKey = i.InvoiceKey),0) as [Applied Advance Billings],
	Case i.InvoiceStatus
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case i.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
		end as [Invoice Status],
	case il.BillFrom When 1 Then ''No Transactions'' else ''Transactions'' end as [Bill From],
	case i.Downloaded when 1 then ''YES'' else ''NO'' end as Downloaded, 
	case i.Posted when 1 then ''YES'' else ''NO'' end as Posted,
	case i.OpeningTransaction when 1 then ''YES'' else ''NO'' end as [Opening Transaction],
	case i.Printed when 1 then ''YES'' else ''NO'' end as Printed, 
	case i.Emailed when 1 then ''YES'' else ''NO'' end as Emailed, 
	case i.ParentInvoice when 1 then ''YES'' else ''NO'' end as [Parent Invoice], 
	il.LineSubject AS [Line Description], 
	il.LineDescription AS [Line Comments], 
	il.Quantity AS [Line Quantity], 
	il.UnitAmount AS [Line Unit Amount], 
	il.TotalAmount AS [Line Total Amount],
	case il.Taxable when 1 then ''YES'' else ''NO'' end as [Line Sales Tax 1 Applied],
	case il.Taxable2 when 1 then ''YES'' else ''NO'' end as [Line Sales Tax 2 Applied],
	il.SalesTax1Amount AS [Line Sales 1 Tax Amount],
	il.SalesTax2Amount AS [Line Sales 2 Tax Amount],
	il.SalesTaxAmount AS [Line Sales Tax Total Amount],
	case il.Entity
		when ''tItem'' then ''Item''
		when ''tService'' then ''Service''
		when ''tTitle'' then ''Title''
		end as [Line Type],
	case il.Entity
		When ''tItem'' then item.ItemID
		when ''tService'' then s.ServiceCode
		when ''tTitle'' then tt.TitleID
		End as [Line Item ID],
	case il.Entity
		When ''tItem'' then item.ItemName
		when ''tService'' then s.Description
		when ''tTitle'' then tt.TitleName
		End as [Line Item Name],
	cl.ClassID as [Line Class ID],
	cl.ClassName as [Line Class Name],
	bi.WorkTypeName as [Billing Item],
	LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager],
	LTRIM(RTRIM(ISNULL(cam.FirstName + '' '','''')  + ISNULL(cam.LastName,''''))) AS [Client Account Manager],
	case when il.PostSalesUsingDetail = 1 And il.BillFrom = 2 then null else glSales.AccountNumber + '' - '' + glSales.AccountName end AS [Sales GL Account],
	case when il.PostSalesUsingDetail = 1 And il.BillFrom = 2 then null else glSales.AccountNumber end AS [Sales GL Account Number],
	LTRIM(RTRIM(ISNULL(app.FirstName + '' '','''')  + ISNULL(app.LastName,''''))) AS [Invoice Approver],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Sales Person],
	p.ProjectNumber as [Line Project Number],
	p.ProjectName as [Line Project Name],
	p.ProjectNumber + '' - '' + p.ProjectName as [Line Project Full Name],
	p.ClientProjectNumber as [Line Client Project Number],
    CAST(p.Description as VARCHAR(4000)) as [Line Project Description],
	prt.ProjectTypeName as [Line Project Type],
	prt.ProjectTypeColor as [Line Project Type Color],
	pbs.ProjectBillingStatus as [Project Billing Status],
	ISNULL(cp.CampaignID, ISNULL(icp.CampaignID, '''')) as [Campaign ID],
	ISNULL(cp.CampaignName, ISNULL(icp.CampaignName, '''')) as [Campaign Name],
	cs.SegmentName as [Campaign Segment],
	ct.CompanyTypeName as [Company Type],
	i.ContactName as [Printed Name],
	LTRIM(RTRIM(ISNULL(cbk.FirstName + '' '','''')  + ISNULL(cbk.LastName,''''))) AS [Created By Name],
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Client Primary Contact],
	u.Phone1 as [Client Primary Contact Phone1],
	u.Phone2 as [Client Primary Contact Phone2],
	u.Email as [Client Primary Contact Email],
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Estimate Total],
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Estimate Total with Tax],
	p.EstLabor + p.ApprovedCOLabor as [Current Budget Labor Gross], -- [Estimate Total Labor]
	(Select ISNULL(Sum(TotalAmount), 0) from tInvoiceLine (nolock) inner join tInvoice (nolock) on tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey Where tInvoice.AdvanceBill = 1 and tInvoiceLine.ProjectKey = p.ProjectKey) as [Amount Advance Billed],
	isnull(glcT.GLCompanyID, glc.GLCompanyID) as [Company ID], 
	isnull(glcT.GLCompanyName, glc.GLCompanyName) as [Company Name], 
	pc.CompanyName as [Parent Company],
	o.OfficeID as [Office ID],
	o.OfficeName as [Office Name],
	o.OfficeColor as [Office Color],
	d.DepartmentName as Department,
	d.DepartmentColor as [Department Color],
	t.TaskID AS [Task ID],
	t.TaskName as [Task Name],
	t.Description as [Task Description],

	-- compare the check dates applied to the invoice AND the check dates applied to the advance bills applied to the invoice
	case when ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0) - ISNULL(i.AmountReceived, 0) <> 0 then null 
	     else 
			case when isnull(ca.CheckDate, ''1/1/1900'') > isnull(abca.CheckDate, ''1/1/1900'') then  ca.CheckDate
			     else abca.CheckDate -- if <= then take the date on the advance bill  
			end 
	end as [Date Paid],	

	bg.BillingGroupCode as [Billing Group Code],
	bg.Description as [Billing Group Description],
	p.ProjectKey,
	i.CurrencyID as [Currency],
	i.ExchangeRate as [Exchange Rate], 
	st1.SalesTaxID as [Sales Tax 1 Code],
	st2.SalesTaxID as [Sales Tax 2 Code],
	ISNULL(st1.SalesTaxName,'''') as [Sales Tax 1 Name],
	ISNULL(st2.SalesTaxName,'''') as [Sales Tax 2 Name],
	CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.State ELSE ad.State END
			AS [Company State],
	trs.RateSheetName as [Service Rate Sheet],
	irs.RateSheetName as [Item Rate Sheet],
	ttrs.RateSheetName as [Title Rate Sheet],
	ret.Title as [Line Retainer Name],
	case c.Active when 1 then ''YES'' else ''NO'' end as [Client Active],
	ISNULL(i2.InvoiceNumber,'''') AS [Parent Invoice Number],
	camp2pm.UserName AS [Campaign Project Manager],
	cpm.UserName AS [Client Project Manager],
	ppm.UserName AS [Project Manager],
	so.SourceName AS [Company Source],
	ts.SegmentName as [Timeline Segment],
	ts.SegmentColor as [Timeline Segment Color],
	case c.ActiveClient when 1 then ''YES'' else ''NO'' end as [Is an Active Client]
	,apa.Address1 AS [Project Tax Address1]
	,apa.Address2 AS [Project Tax Address2]
	,apa.Address3 AS [Project Tax Address3]
	,apa.City AS [Project Tax City]
	,apa.State AS [Project Tax State]
	,apa.PostalCode AS [Project Tax Postal Code]
	,apa.Country AS [Project Tax Country]
FROM 
	tInvoice i (nolock)
	INNER JOIN tInvoiceLine il (nolock)ON i.InvoiceKey = il.InvoiceKey  -- Regular Invoices
	INNER JOIN tCompany c (nolock) ON i.ClientKey = c.CompanyKey 
	LEFT OUTER JOIN tGLAccount glSales (nolock) ON il.SalesAccountKey = glSales.GLAccountKey
    LEFT OUTER JOIN tGLAccount glAR (nolock) ON i.ARAccountKey = glAR.GLAccountKey 
    LEFT OUTER JOIN tGLAccount glCL (nolock) ON c.DefaultSalesAccountKey = glCL.GLAccountKey 
	LEFT OUTER JOIN tGLAccount glLiab (nolock) ON i.LiabilityAccountKey = glLiab.GLAccountKey
	LEFT OUTER JOIN tPaymentTerms pt (nolock) ON i.TermsKey = pt.PaymentTermsKey
	LEFT OUTER JOIN tProject pr (nolock) ON i.ProjectKey = pr.ProjectKey
    LEFT OUTER JOIN tUser bcu (nolock) on pr.BillingContact = bcu.UserKey 
    LEFT OUTER JOIN tProject p (nolock) ON il.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
	LEFT OUTER JOIN tClientProduct pd (nolock) on p.ClientProductKey = pd.ClientProductKey
	LEFT OUTER JOIN tProjectType prt (nolock) on p.ProjectTypeKey = prt.ProjectTypeKey
	LEFT OUTER JOIN tUser am (nolock) on p.AccountManager = am.UserKey
	LEFT OUTER JOIN tUser cam (nolock) on c.AccountManagerKey = cam.UserKey
	LEFT OUTER JOIN tUser u (nolock) on i.PrimaryContactKey = u.UserKey
	LEFT OUTER JOIN tUser app (nolock) on i.ApprovedByKey = app.UserKey
	LEFT OUTER JOIN tUser cbk (nolock) on i.CreatedByKey = cbk.UserKey
	LEFT OUTER JOIN tUser sales (nolock) on c.SalesPersonKey = sales.UserKey
	LEFT OUTER JOIN tCompanyType ct (nolock) on c.CompanyTypeKey = ct.CompanyTypeKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
	LEFT OUTER JOIN tWorkType bi (nolock) on il.WorkTypeKey = bi.WorkTypeKey
	left outer join tClass cl (nolock) on il.ClassKey = cl.ClassKey
	left outer join tClass cl2 (nolock) on i.ClassKey = cl2.ClassKey
	Left outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
	Left outer join tAddress ab (nolock) on c.BillingAddressKey = ab.AddressKey
	Left outer join tAddress ib (nolock) on i.AddressKey = ib.AddressKey
	LEFT OUTER Join tTask t (nolock) on il.TaskKey = t.TaskKey
	left outer join tGLCompany glc (nolock) on i.GLCompanyKey = glc.GLCompanyKey
	left outer join tGLCompany glcT (nolock) on il.TargetGLCompanyKey = glcT.GLCompanyKey
	left outer join tOffice o (nolock) on il.OfficeKey = o.OfficeKey
	left outer join tDepartment d (nolock) on il.DepartmentKey = d.DepartmentKey
	left outer join tCompany pc (nolock) on c.ParentCompanyKey = pc.CompanyKey
	left outer join tProjectBillingStatus pbs (nolock) on ISNULL(p.ProjectBillingStatusKey, pr.ProjectBillingStatusKey) = pbs.ProjectBillingStatusKey
	left outer join tService s (nolock) on il.EntityKey = s.ServiceKey AND il.Entity = ''tService''
	left outer join tItem item (nolock) on il.EntityKey = item.ItemKey AND il.Entity = ''tItem''
	left outer join tTitle tt (nolock) on il.EntityKey = tt.TitleKey AND il.Entity = ''tTitle''
	left outer join tBillingGroup bg (nolock) on i.BillingGroupKey = bg.BillingGroupKey
	LEFT OUTER JOIN tSalesTax st1 (nolock) on i.SalesTaxKey = st1.SalesTaxKey
	LEFT OUTER JOIN tSalesTax st2 (nolock) on i.SalesTax2Key = st2.SalesTaxKey
	left outer join tTimeRateSheet trs (nolock) on p.TimeRateSheetKey = trs.TimeRateSheetKey
	left outer join tItemRateSheet irs (nolock) on p.ItemRateSheetKey = irs.ItemRateSheetKey
	left outer join tTitleRateSheet ttrs (nolock) on p.TitleRateSheetKey = ttrs.TitleRateSheetKey
	left outer join tRetainer ret (nolock) on il.RetainerKey = ret.RetainerKey
	left outer join tCampaign icp (nolock) on i.CampaignKey = icp.CampaignKey
	LEFT OUTER JOIN vUserName camp2pm (nolock) on icp.PMKey = camp2pm.UserKey
	LEFT OUTER JOIN vUserName cpm (nolock) on c.ProjectManagerKey = cpm.UserKey
	LEFT OUTER JOIN vUserName ppm (nolock) on p.ProjectManager = ppm.UserKey
	LEFT OUTER JOIN tProjectAddress padd (nolock) on p.ProjectKey = padd.ProjectKey
	LEFT OUTER JOIN tAddress apa (nolock) on padd.AddressKey = apa.AddressKey

	left outer join tInvoice i2 (nolock) on i.ParentInvoiceKey = i2.InvoiceKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	LEFT OUTER JOIN	tSource so (NOLOCK) on c.SourceKey = so.SourceKey
	left outer join tTimelineSegment ts (nolock) on t.TimelineSegmentKey = ts.TimelineSegmentKey

	-- derived tables to calculate the [Date Paid] field 
	left outer join (
	Select ca.InvoiceKey , Max(c.CheckDate) as CheckDate
	From   tCheck c (nolock)
	Inner Join tCheckAppl ca (nolock) on ca.CheckKey = c.CheckKey
	Inner Join tInvoice i2 (nolock) on ca.InvoiceKey = i2.InvoiceKey -- current invoice
	Group by ca.InvoiceKey
	) as ca on  ca.InvoiceKey = i.InvoiceKey

	left outer join (
	Select i3.InvoiceKey , Max(c.CheckDate) as CheckDate
	From   tCheck c (nolock)
	Inner Join tCheckAppl ca (nolock) on ca.CheckKey = c.CheckKey
	Inner join tInvoiceAdvanceBill iab (nolock) on ca.InvoiceKey = iab.AdvBillInvoiceKey  -- adv bill applied to the current invoice
	Inner Join tInvoice i3 (nolock) on iab.InvoiceKey = i3.InvoiceKey -- current invoice
	Group by i3.InvoiceKey
	) as abca on  abca.InvoiceKey = i.InvoiceKey

WHERE (il.LineType = 2)

UNION ALL

-- Child Invoices

SELECT
	i.CompanyKey, 
	i.GLCompanyKey, 
	p.CustomFieldKey,
	c.CustomFieldKey AS CustomFieldKey2,
    bcu.CustomFieldKey AS CustomFieldKey3,
	ISNULL(cp.CustomFieldKey, icp.CustomFieldKey) AS CustomFieldKey4,
	cd.DivisionName as [Division Name],
	cd.DivisionID as [Division ID],
	pd.ProductName as [Product Name],
	pd.ProductID as [Product ID],
	i.InvoiceNumber AS [Invoice Number], 
	i.InvoiceDate AS [Invoice Date], 
	i.PostingDate as [Posting Date],
	DATENAME(Year, i.PostingDate) + ''_'' + RIGHT(''0'' + CAST(DATEPART(Month, i.PostingDate) AS VARCHAR(2)), 2) AS [Posting Month],
	i.DueDate AS [Due Date], 
	i.DateCreated AS [Date Created], 
	case i.AdvanceBill when 1 then ''YES'' else ''NO'' end as [Advance Billing Invoice],
	i.UserDefined1 as [Invoice User Defined 1],
	i.UserDefined2 as [Invoice User Defined 2],
	i.UserDefined3 as [Invoice User Defined 3],
	i.UserDefined4 as [Invoice User Defined 4],
	i.UserDefined5 as [Invoice User Defined 5],
	i.UserDefined6 as [Invoice User Defined 6],
	i.UserDefined7 as [Invoice User Defined 7],
	i.UserDefined8 as [Invoice User Defined 8],
	i.UserDefined9 as [Invoice User Defined 9],
	i.UserDefined10 as [Invoice User Defined 10],
	c.CompanyName AS [Client Name], 
	c.CustomerID AS [Client ID], 
	c.CustomerID + '' - '' + c.CompanyName AS [Client Full Name], 
	i.ContactName as [Bill To Contact],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Address1 ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Address1 ELSE ad.Address1 END
			end AS [Bill To Address1],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Address2 ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Address2 ELSE ad.Address2 END
			end AS [Bill To Address2],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Address3 ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Address3 ELSE ad.Address3 END
			end AS [Bill To Address3],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.City ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.City ELSE ad.City END
			end AS [Bill To City],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.State ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.State ELSE ad.State END
			end AS [Bill To State],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.PostalCode ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.PostalCode ELSE ad.PostalCode END
			end AS [Bill To Postal Code],
	CASE WHEN i.AddressKey IS NOT NULL THEN ib.Country ELSE  
		CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.Country ELSE ad.Country END
			end AS [Bill To Country],
	pt.TermsDescription AS Terms, 
	glAR.AccountNumber AS [AR Account Number],
	glAR.AccountName AS [AR Account Name],
	glAR.AccountNumber + '' - '' + glAR.AccountName AS [AR Account], 
	glCL.AccountNumber + '' - '' + glCL.AccountName AS [Default Client Sales Account], 
	glLiab.AccountNumber AS [Advance Bill Liability Account Number],
	glLiab.AccountName AS [Advance Bill Liability Account Name],
	glLiab.AccountNumber + '' - '' + glLiab.AccountName AS [Advance Bill Liability Account],
	pr.ProjectNumber as [Project Number],
	pr.ProjectName as [Project Name], 
	pr.ProjectNumber + '' - '' + pr.ProjectName as [Project Full Name],
	pr.ClientProjectNumber as [Client Project Number],
	i.WriteoffAmount AS [Invoice Writeoff Amount], 
	i.RetainerAmount AS [Invoice Adv Bill Amount], 
	i.InvoiceTotalAmount as [Invoice Total With Tax],
	i.TotalNonTaxAmount as [Invoice Total No Tax],
	i.InvoiceTotalAmount - i.TotalNonTaxAmount as [Invoice Total Tax],
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.AmountReceived, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0) as [Amount Open],
    ISNULL(i.HeaderComment, '''') as [Invoice Comment], 
	i.ApprovalComments as [Approval Comments],
	cl2.ClassID as [Header Class ID],
	cl2.ClassName as [Header Class Name],
	case when i.AdvanceBill = 1 then
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where AdvBillInvoiceKey = i.InvoiceKey),0) 
	else 0 end as [Advance Bill Unapplied],
	ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where InvoiceKey = i.InvoiceKey),0) as [Applied Advance Billings],
	Case i.InvoiceStatus
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case i.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
		end as [Invoice Status],
	
	case il.BillFrom When 1 Then ''No Transactions'' else ''Transactions'' end as [Bill From],
	case i.Downloaded when 1 then ''YES'' else ''NO'' end as Downloaded, 
	case i.Posted when 1 then ''YES'' else ''NO'' end as Posted,
	case i.OpeningTransaction when 1 then ''YES'' else ''NO'' end as [Opening Transaction],
	case i.Printed when 1 then ''YES'' else ''NO'' end as Printed, 
	case i.Emailed when 1 then ''YES'' else ''NO'' end as Emailed, 
	case i.ParentInvoice when 1 then ''YES'' else ''NO'' end as [Parent Invoice], 
	il.LineSubject AS [Line Description], 
	il.LineDescription AS [Line Comments], 
	ROUND(il.Quantity * (i.PercentageSplit/100), 4) AS [Line Quantity], 
	il.UnitAmount AS [Line Unit Amount],
	ROUND(il.TotalAmount * (i.PercentageSplit/100), 2) AS [Line Total Amount],
	case il.Taxable when 1 then ''YES'' else ''NO'' end as [Line Sales Tax 1 Applied],
	case il.Taxable2 when 1 then ''YES'' else ''NO'' end as [Line Sales Tax 2 Applied],
	il.SalesTax1Amount AS [Line Sales 1 Tax Amount],
	il.SalesTax2Amount AS [Line Sales 2 Tax Amount], 
	il.SalesTaxAmount AS [Line Sales Tax Total Amount],
	case il.Entity
		when ''tItem'' then ''Item''
		when ''tService'' then ''Service''
		when ''tTitle'' then ''Title''
		end as [Line Type],
	case il.Entity
		When ''tItem'' then item.ItemID
		when ''tService'' then s.ServiceCode
		when ''tTitle'' then tt.TitleID
		End as [Line Item ID],
	case il.Entity
		When ''tItem'' then item.ItemName
		when ''tService'' then s.Description
		when ''tTitle'' then tt.TitleName
		End as [Line Item Name],
	cl.ClassID as [Line Class ID],
	cl.ClassName as [Line Class Name],
	bi.WorkTypeName as [Billing Item],
	LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager],
	LTRIM(RTRIM(ISNULL(cam.FirstName + '' '','''')  + ISNULL(cam.LastName,''''))) AS [Client Account Manager],
	case when il.PostSalesUsingDetail = 1 And il.BillFrom = 2 then null else glSales.AccountNumber + '' - '' + glSales.AccountName end AS [Sales GL Account],
	case when il.PostSalesUsingDetail = 1 And il.BillFrom = 2 then null else glSales.AccountNumber end AS [Sales GL Account Number],
	LTRIM(RTRIM(ISNULL(app.FirstName + '' '','''')  + ISNULL(app.LastName,''''))) AS [Invoice Approver],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Sales Person],
	p.ProjectNumber as [Line Project Number],
	p.ProjectName as [Line Project Name],
	p.ProjectNumber + '' - '' + p.ProjectName as [Line Project Full Name],
	p.ClientProjectNumber as [Line Client Project Number],
    CAST(p.Description as VARCHAR(4000)) as [Line Project Description],
	prt.ProjectTypeName as [Line Project Type],
	prt.ProjectTypeColor as [Line Project Type Color],
	pbs.ProjectBillingStatus as [Project Billing Status],
	ISNULL(cp.CampaignID, ISNULL(icp.CampaignID, '''')) as [Campaign ID],
	ISNULL(cp.CampaignName, ISNULL(icp.CampaignName, '''')) as [Campaign Name],
	cs.SegmentName as [Campaign Segment],
	ct.CompanyTypeName as [Company Type],
	i.ContactName as [Printed Name],
	LTRIM(RTRIM(ISNULL(cbk.FirstName + '' '','''')  + ISNULL(cbk.LastName,''''))) AS [Created By Name],
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Client Primary Contact],
	u.Phone1 as [Client Primary Contact Phone1],
	u.Phone2 as [Client Primary Contact Phone2],
	u.Email as [Client Primary Contact Email],
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Estimate Total],
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) as [Estimate Total with Tax],
	p.EstLabor + p.ApprovedCOLabor as [Current Budget Labor Gross], -- [Estimate Total Labor]
	(Select ISNULL(Sum(TotalAmount), 0) from tInvoiceLine (nolock) inner join tInvoice (nolock) on tInvoiceLine.InvoiceKey = tInvoice.InvoiceKey Where tInvoice.AdvanceBill = 1 and tInvoiceLine.ProjectKey = p.ProjectKey) as [Amount Advance Billed],
	glc.GLCompanyID as [Company ID],
	glc.GLCompanyName as [Company Name],
	pc.CompanyName as [Parent Company],
	o.OfficeID as [Office ID],
	o.OfficeName as [Office Name],
	o.OfficeColor as [Office Color],
	d.DepartmentName as Department,
	d.DepartmentColor as [Department Color],
	t.TaskID AS [Task ID],
	t.TaskName as [Task Name],
	t.Description as [Task Description],
	
	-- compare the check dates applied to the invoice AND the check dates applied to the advance bills applied to the invoice
	case when ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0) - ISNULL(i.AmountReceived, 0) <> 0 then null 
	     else 
			case when isnull(ca.CheckDate, ''1/1/1900'') > isnull(abca.CheckDate, ''1/1/1900'') then  ca.CheckDate
			     else abca.CheckDate -- if <= then take the date on the advance bill  
			end 
	end as [Date Paid],	

	bg.BillingGroupCode as [Billing Group Code],
	bg.Description as [Billing Group Description],
	p.ProjectKey,
	i.CurrencyID as [Currency],
	i.ExchangeRate as [Exchange Rate], 
	st1.SalesTaxID as [Sales Tax 1 Code],
	st2.SalesTaxID as [Sales Tax 2 Code],
	ISNULL(st1.SalesTaxName,'''') as [Sales Tax 1 Name],
	ISNULL(st2.SalesTaxName,'''') as [Sales Tax 2 Name],
	CASE WHEN c.BillingAddressKey IS NOT NULL THEN ab.State ELSE ad.State END
			AS [Company State],
	trs.RateSheetName as [Service Rate Sheet],
	irs.RateSheetName as [Item Rate Sheet],
	ttrs.RateSheetName as [Title Rate Sheet],
	ret.Title as [Line Retainer Name],
	case c.Active when 1 then ''YES'' else ''NO'' end as [Client Active],
	ISNULL(i2.InvoiceNumber,'''') AS [Parent Invoice Number],
	camp2pm.UserName AS [Campaign Project Manager],
	cpm.UserName AS [Client Project Manager],
	ppm.UserName AS [Project Project Manager],
	so.SourceName AS [Company Source],
	ts.SegmentName as [Timeline Segment],
	ts.SegmentColor as [Timeline Segment Color],
	case c.ActiveClient when 1 then ''YES'' else ''NO'' end as [Is an Active Client]
	,apa.Address1 AS [Project Tax Address1]
	,apa.Address2 AS [Project Tax Address2]
	,apa.Address3 AS [Project Tax Address3]
	,apa.City AS [Project Tax City]
	,apa.State AS [Project Tax State]
	,apa.PostalCode AS [Project Tax Postal Code]
	,apa.Country AS [Project Tax Country]
FROM 
	tInvoice i (nolock)
	INNER JOIN tInvoiceLine il (nolock)ON i.ParentInvoiceKey = il.InvoiceKey -- Child Invoices, must point to parent
	INNER JOIN tCompany c (nolock) ON i.ClientKey = c.CompanyKey 
	LEFT OUTER JOIN tGLAccount glSales (nolock) ON il.SalesAccountKey = glSales.GLAccountKey
    LEFT OUTER JOIN tGLAccount glAR (nolock) ON i.ARAccountKey = glAR.GLAccountKey 
    LEFT OUTER JOIN tGLAccount glCL (nolock) ON c.DefaultSalesAccountKey = glCL.GLAccountKey 
	LEFT OUTER JOIN tGLAccount glLiab (nolock) ON i.LiabilityAccountKey = glLiab.GLAccountKey
	LEFT OUTER JOIN tPaymentTerms pt (nolock) ON i.TermsKey = pt.PaymentTermsKey
	LEFT OUTER JOIN tProject pr (nolock) ON i.ProjectKey = pr.ProjectKey
    LEFT OUTER JOIN tUser bcu (nolock) on pr.BillingContact = bcu.UserKey 
    LEFT OUTER JOIN tProject p (nolock) ON il.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
	LEFT OUTER JOIN tClientProduct pd (nolock) on p.ClientProductKey = pd.ClientProductKey
	LEFT OUTER JOIN tProjectType prt (nolock) on p.ProjectTypeKey = prt.ProjectTypeKey
	LEFT OUTER JOIN tUser am (nolock) on p.AccountManager = am.UserKey
	LEFT OUTER JOIN tUser cam (nolock) on c.AccountManagerKey = cam.UserKey
	LEFT OUTER JOIN tUser u (nolock) on i.PrimaryContactKey = u.UserKey
	LEFT OUTER JOIN tUser app (nolock) on i.ApprovedByKey = app.UserKey
	LEFT OUTER JOIN tUser cbk (nolock) on i.CreatedByKey = cbk.UserKey
	LEFT OUTER JOIN tUser sales (nolock) on c.SalesPersonKey = sales.UserKey
	LEFT OUTER JOIN tCompanyType ct (nolock) on c.CompanyTypeKey = ct.CompanyTypeKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
	LEFT OUTER JOIN tWorkType bi (nolock) on il.WorkTypeKey = bi.WorkTypeKey
	left outer join tClass cl (nolock) on il.ClassKey = cl.ClassKey
	left outer join tClass cl2 (nolock) on i.ClassKey = cl2.ClassKey
	Left outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
	Left outer join tAddress ab (nolock) on c.BillingAddressKey = ab.AddressKey
	Left outer join tAddress ib (nolock) on i.AddressKey = ib.AddressKey
	LEFT OUTER Join tTask t (nolock) on il.TaskKey = t.TaskKey
	left outer join tGLCompany glc (nolock) on i.GLCompanyKey = glc.GLCompanyKey
	left outer join tOffice o (nolock) on il.OfficeKey = o.OfficeKey
	left outer join tDepartment d (nolock) on il.DepartmentKey = d.DepartmentKey
	left outer join tCompany pc (nolock) on c.ParentCompanyKey = pc.CompanyKey
	left outer join tProjectBillingStatus pbs (nolock) on ISNULL(p.ProjectBillingStatusKey, pr.ProjectBillingStatusKey) = pbs.ProjectBillingStatusKey
	left outer join tService s (nolock) on il.EntityKey = s.ServiceKey AND il.Entity = ''tService''
	left outer join tItem item (nolock) on il.EntityKey = item.ItemKey AND il.Entity = ''tItem''
	left outer join tTitle tt (nolock) on il.EntityKey = tt.TitleKey AND il.Entity = ''tTitle''
	left outer join tBillingGroup bg (nolock) on i.BillingGroupKey = bg.BillingGroupKey
	LEFT OUTER JOIN tSalesTax st1 (nolock) on i.SalesTaxKey = st1.SalesTaxKey
	LEFT OUTER JOIN tSalesTax st2 (nolock) on i.SalesTax2Key = st2.SalesTaxKey
	left outer join tTimeRateSheet trs (nolock) on p.TimeRateSheetKey = trs.TimeRateSheetKey
	left outer join tItemRateSheet irs (nolock) on p.ItemRateSheetKey = irs.ItemRateSheetKey
	left outer join tTitleRateSheet ttrs (nolock) on p.TitleRateSheetKey = ttrs.TitleRateSheetKey
	left outer join tRetainer ret (nolock) on il.RetainerKey = ret.RetainerKey
	left outer join tCampaign icp (nolock) on i.CampaignKey = icp.CampaignKey
	left outer join tInvoice i2 (nolock) on i.ParentInvoiceKey = i2.InvoiceKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey  
	LEFT OUTER JOIN vUserName camp2pm (nolock) on icp.PMKey = camp2pm.UserKey
	LEFT OUTER JOIN vUserName cpm (nolock) on c.ProjectManagerKey = cpm.UserKey
	LEFT OUTER JOIN vUserName ppm (nolock) on p.ProjectManager = ppm.UserKey
	LEFT OUTER JOIN	tSource so (NOLOCK) on c.SourceKey = so.SourceKey
	left outer join tTimelineSegment ts (nolock) on t.TimelineSegmentKey = ts.TimelineSegmentKey
	LEFT OUTER JOIN tProjectAddress padd (nolock) on p.ProjectKey = padd.ProjectKey
	LEFT OUTER JOIN tAddress apa (nolock) on padd.AddressKey = apa.AddressKey

	-- derived tables to calculate the [Date Paid] field 
	left outer join (
	Select ca.InvoiceKey , Max(c.CheckDate) as CheckDate
	From   tCheck c (nolock)
	Inner Join tCheckAppl ca (nolock) on ca.CheckKey = c.CheckKey
	Inner Join tInvoice i2 (nolock) on ca.InvoiceKey = i2.InvoiceKey -- current invoice
	Group by ca.InvoiceKey
	) as ca on  ca.InvoiceKey = i.InvoiceKey

	left outer join (
	Select i3.InvoiceKey , Max(c.CheckDate) as CheckDate
	From   tCheck c (nolock)
	Inner Join tCheckAppl ca (nolock) on ca.CheckKey = c.CheckKey
	Inner join tInvoiceAdvanceBill iab (nolock) on ca.InvoiceKey = iab.AdvBillInvoiceKey  -- adv bill applied to the current invoice
	Inner Join tInvoice i3 (nolock) on iab.InvoiceKey = i3.InvoiceKey -- current invoice
	Group by i3.InvoiceKey
	) as abca on  abca.InvoiceKey = i.InvoiceKey

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














ALTER VIEW [dbo].[vReport_Request]
As

/*
|| When      Who Rel      What
|| 10/29/12  CRG 10.5.6.1 (156391) Added ProjectKey
|| 06/13/13  WDF 10.5.6.9 (181051) Added ''Cancelled'' to Status Case Statement
|| 07/02/14  QMD 10.5.8.1 (220667) Added Date Cancelled and Date Sent for Approval
|| 07/21/14  GHL 10.5.8.2 (223349) Added Date Approved
|| 01/27/15  WDF 10.5.8.8 (Abelson Taylor) Added Division and Product
|| 11/16/16  WDF 10.6.1.0 (318451) Added [Date Updated]
|| 01/04/18  WDF 18.1.0   (379517) Added [Parent Company] 
|| 03/30/18  AMP 18.4.0   (393949) Added Request Key 
|| 05/22/18  GHL 18.6.0   (401883) Added separated status fields to help with performance issues at Kohls
||                        Moved DateApproved to derived table rather than subquery
|| 06/29/18  GHL 18.7.0   (408233) Changed inner join to outer join for DateApproved
|| 12/20/18  WDF 19.1.0   (436948) Change Company Inner Join to Left Join for ClientKey
|| 04/17/20  RLS 20.0.5.0 (509551) Added CampaignID, CampaignName and SegmentName
|| 07/09/20  GAR 20.0.8.0 (518830) Change Project Requested By field to grab the name based on the key instead of the text name
|| 09/02/20  RLB 20.1.0.0 (523772) making anything using user name common format
|| 10/13/20  RLS 20.1.1.0 (529272) Added [Date Rejected]
|| 10/13/20  QMD 20.1.1.0 (529272) Tagging on the same issue as Russ above. Removed the union for null values since it''s not needed.  That''s what a left join does.
|| 11/03/20  GAR 20.1.1.0 (534898) Added account manager and project manager from the client
|| 12/30/20  GHL 21.01.24.0 (541935) Added Split Billing column to display the % per client of split billing
|| 11/13/23  RLB 23.12.17 (654129) added Project Request Division and Product on the request
|| 05/27/26   RLB 26.06.14  (729321) Changed Date Approved to include step action 3 since approvals can now be on both
*/

Select 
	r.CompanyKey
	,r.CustomFieldKey
	,r.Subject as [Subject]
	,r.ProjectDescription as [Description]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' - '' + c.CompanyName as [Client ID and Name]
	,pc.CompanyName as [Parent Company]
	,rd.RequestName as [Request Type]
	,r.RequestID as [Request ID]
	,Case When r.DateCompleted is null then
		Case Status 
		When 1 then 
			Case r.Cancelled
				When 0 then ''Not Sent For Approval''
				When 1 then ''Cancelled''
				else ''Not Sent For Approval''
			end
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then ''Approved''
		end
	 else
		''Completed'' end as [Request Status]
	
	-- separated the [Request Status] because it degrades performance in the where clause  (401883)
	,case when r.DateCompleted is null then ''NO'' else ''YES'' end as Completed
	,case r.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]
	,Case r.Cancelled
				When 0 then ''NO'' 
				When 1 then ''YES''    
				else ''NO''
	end as Cancelled

	,r.DateAdded as [Date Added]
	,r.DateUpdated as [Date Updated]
	,r.DateCompleted as [Date Completed]
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Entered By]
	,ISNULL(upr.UserName, r.RequestedBy) as [Requested By]
	,r.NotifyEmail as [Email to Notify]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber as [Project Number]
	,p.ProjectKey
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cp.ProductID as [Client Product ID]
    ,cp.ProductName as [Client Product]
    ,prcd.DivisionName as [Project Request Division]
    ,prcp.ProductName as [Project Request Product]
	,r.DateCancelled as [Date Cancelled]
	,r.DateSentForApproval as [Date Sent For Approval]
	,maxdate.DateApproved as [Date Approved]
	,maxRejectDate.DateRejected as [Date Rejected]
	,r.RequestKey
	,r.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign Name]
	,cs.SegmentName as [Campaign Segment]
	,pm_client.UserName as [Client Project Manager]
	,am_client.UserName as [Client Account Manager]

	, Substring(
	(
		select '', '' + cl2.CustomerID  + '': '' + cast(cast(splitbill.Split as decimal(24,2)) as varchar) + ''%''  AS [text()]
					FROM tRequestSplit splitbill (nolock)
						inner join tCompany cl2 (nolock) on splitbill.ClientKey = cl2.CompanyKey
					WHERE splitbill.RequestKey = r.RequestKey
					ORDER BY cl2.CustomerID
					FOR XML PATH ('''')
	 ), 2, 5000) as [Split Billing]

From
	tRequest r (nolock)
	inner join tRequestDef rd (nolock) on r.RequestDefKey = rd.RequestDefKey
	left join tCompany c (nolock) on r.ClientKey = c.CompanyKey
	left join tCompany pc (nolock) on c.ParentCompanyKey = pc.CompanyKey
	left join tUser u (nolock) on r.EnteredByKey = u.UserKey
	left join tProject p (nolock) on r.RequestKey = p.RequestKey
	left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
    left outer join tClientProduct  cp (nolock) on p.ClientProductKey  = cp.ClientProductKey
	left outer join tClientDivision prcd (nolock) on r.ClientDivisionKey = prcd.ClientDivisionKey
    left outer join tClientProduct  prcp (nolock) on r.ClientProductKey  = prcp.ClientProductKey
	left outer join tCampaign ca (nolock) on r.CampaignID = ca.CampaignID and r.CompanyKey = ca.CompanyKey 
	left outer join tCampaignSegment cs (nolock) on r.CampaignSegmentKey = cs.CampaignSegmentKey
	left outer join vUserName upr (nolock) on r.RequestedByKey = upr.UserKey

	left outer join 
		(
		Select r.RequestKey, MAX(asu.DateCompleted)  as DateApproved
		From tApprovalStepUser asu (nolock) 
		inner join tApprovalStep astep (nolock) on astep.ApprovalStepKey = asu.ApprovalStepKey 
		inner join tRequest r (nolock) on astep.EntityKey = r.RequestKey 
		Where astep.Entity = ''ProjectRequest'' 
		and asu.Action = 1		-- Approved by User
		and (astep.Action = 2  OR astep.Action = 3) -- these steps have been combined
		and r.Status = 4
		group by r.RequestKey

		) as maxdate on maxdate.RequestKey = r.RequestKey

		-- Date Rejected
	left outer join 
		(
		Select r.RequestKey, MAX(asu.DateCompleted)  as DateRejected
		From tApprovalStepUser asu (nolock) 
		inner join tApprovalStep astep (nolock) on astep.ApprovalStepKey = asu.ApprovalStepKey 
		inner join tRequest r (nolock) on astep.EntityKey = r.RequestKey 
		Where astep.Entity = ''ProjectRequest'' 
		and asu.Action = 2		-- Rejected by User
		and astep.Action = 2	-- The action on the Approval Step is Approve, not Notify
		and r.Status = 3
		group by r.RequestKey

		) as maxRejectDate on maxRejectDate.RequestKey = r.RequestKey

	left outer join vUserName pm_client (nolock) on c.ProjectManagerKey = pm_client.UserKey 
	left outer join vUserName am_client (nolock) on c.AccountManagerKey = am_client.UserKey 


'
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

	-- Get the project key for the requested project
	DECLARE @ProjectKey int
	SELECT @ProjectKey = ProjectKey
	FROM tProject (nolock)
	WHERE CompanyKey = @CompanyKey
	AND UPPER(ProjectNumber) = UPPER(@ProjectNumber)

	IF @ProjectKey IS NULL
	BEGIN
		-- Project not found, return empty result
		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 1 = 0
		RETURN
	END

	-- Get user''s security group and administrator status
	DECLARE @SecurityGroupKey int
	DECLARE @IsAdministrator bit, @SuspendAdmin bit

	SELECT @SecurityGroupKey = SecurityGroupKey,
		   @IsAdministrator = Administrator,
		   @SuspendAdmin = ISNULL(SuspendAdmin, 0)
	FROM tUser (nolock)
	WHERE UserKey = @UserKey
	AND CompanyKey = @CompanyKey

	IF @SuspendAdmin = 1
		SELECT @IsAdministrator = 0

	-- Administrators can access all files
	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
		RETURN
	END

	-- Get all applicable security entries for this user
	DECLARE @ApplicableSecurity TABLE (
		ProjectKey int,
		Path varchar(500),
		PathUpper varchar(500),
		ViewFolder bit,
		Precedence int  -- 1 = most specific (path match), 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 
			-- Path-specific security (most specific)
			WHEN s.ProjectKey = @ProjectKey AND s.Path <> '''' THEN 1
			-- Project-level security (blank path)
			WHEN s.ProjectKey = @ProjectKey AND s.Path = '''' THEN 2
			-- Company-wide security
			WHEN s.ProjectKey = 0 THEN 3
			ELSE 4
		END as Precedence
	FROM tWebDavSecurity s (nolock)
	WHERE s.CompanyKey = @CompanyKey
	AND (
		-- Company-wide security (applies to all projects)
		s.ProjectKey = 0
		OR
		-- Project-specific security
		s.ProjectKey = @ProjectKey
	)
	AND (
		-- Direct user assignment
		(s.Entity = ''tUser'' AND s.EntityKey = @UserKey)
		OR
		-- Security group assignment
		(s.Entity = ''tSecurityGroup'' AND s.EntityKey = @SecurityGroupKey)
	)

	-- Return files based on hierarchical security evaluation
	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 (
		-- Find the most specific security entry that applies to this file
		SELECT TOP 1 1
		FROM @ApplicableSecurity sec
		WHERE 
			(
				-- Path-specific: exact match or parent path
				(sec.Precedence = 1 
				 AND (UPPER(ISNULL(f.Path, '''')) = sec.PathUpper
				      OR UPPER(ISNULL(f.Path, '''')) LIKE sec.PathUpper + ''/%''))
				OR
				-- Project-level: blank path (only if no path-specific exists)
				(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
				-- Company-wide: only if no path-specific or project-level exists
				(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  -- Must have ViewFolder permission
		ORDER BY sec.Precedence ASC
	)
	ORDER BY f.Path, f.LastModified DESC, f.FileKey DESC
'
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
)

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
*/

	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

	-- 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

	-- 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,
			DateUpdated
		)
		values
		(
			@ProjectKey,
			@TaskID,
			@TaskName,
			@Description,
			2,
			ISNULL(@ParentTaskKey, 0),
			@DisplayOrder,
			@ProjectOrder,
			@ServiceKey,
			@WorkTypeKey,
			@PlanStart,
			@PlanComplete,
			@PlanDuration,
			@TaskStatus,
			@Comments,
			1,
			1,
			0,
			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),
			DateUpdated = GETUTCDATE()
		where TaskKey = @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].[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
	*/

	/*
	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 @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

	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
	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
			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
		
		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
				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

				-- 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
  */

	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
			WHERE  ProjectKey = @ProjectKey and BillingKey = @BillingKey
	END

	-- or a campaign key
	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
		AND    b.BillingMethod = 2 -- FF

		IF @BillingKey is null
			break

		SELECT @CampaignKey = CampaignKey  from tBilling (nolock) where BillingKey = @BillingKey

		UPDATE tBillingSchedule
			SET    InvoiceKey = @NewInvoiceKey
			WHERE  CampaignKey = @CampaignKey and BillingKey = @BillingKey
	END

	RETURN @NewInvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceGenerateRecurring]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceGenerateRecurring]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptInvoiceGenerateRecurring]

	(
		@InvoiceKey int,
		@CompanyKey int,
		@RecurringInterval smallint,
		@RecurringCount int
	)

AS --Encrypt

  /*
  || When     Who Rel    What
  || 02/23/07 GHL 8.4    Added project rollup  
  || 03/29/07 CRG 8.4.1  (8730) Fixed DueDate calculation for quarterly recurring. 
  || 10/6/07  GWG 8.5    Added hooks for company,office and department 
  || 03/31/09 RLB 10.022 (49960) Added sptInvoiceRecalcAmounts to invoice creation loop so that recurring invoices hit tInvoiceSummary
  || 03/31/09 RLB 10.022 (50067) Added PrimaryContactKey to newly created Invoices since it was not being passed in before       
  || 02/12/10 GHL 10.518 (74670) Added tax info...also removed call to sptInvoiceRecalcAmount and added call to sptInvoiceSummary                    
  || 02/19/10 GHL 10.518 Reviewed capture of @@ERROR and @@IDENTITY
  || 09/19/13 MFT 10.572 (190447) Added	LayoutKey in INSERT statement
  || 01/03/14 WDF 10.576 (188500) Added CreatedByKey, DateCreated to Insert tInvoice
  || 08/03/20 GHL 20.090 (451878) Added new fields for GL companies and different currencies
  || 04/21/26 AMP 26.05.17 (718171) Added a check for Advance Bill -> Use Advance Bill Prefix set on preferences
 */
  	
if @RecurringCount = 0
	Return 1
	
If exists(Select 1 from tInvoice (nolock) Where InvoiceKey = @InvoiceKey and RecurringParentKey > 0)
	return -1

create table #newkeys (InvoiceKey int null)

Begin Transaction

Update tInvoice Set RecurringParentKey = @InvoiceKey Where InvoiceKey = @InvoiceKey
if @@ERROR <> 0 
begin
	rollback tran
	return -3
end

Declare @Loop int, @CurOrder int, @RetVal INTEGER, @NextTranNo VARCHAR(100), @NewKey int, @Error int
Declare @CurInvoiceDate smalldatetime, @CurDueDate smalldatetime, @InvoiceDate smalldatetime, @DueDate smalldatetime
Declare @AdvanceBill tinyint
Select @CurInvoiceDate = InvoiceDate, @CurDueDate = DueDate, @AdvanceBill = AdvanceBill from tInvoice (nolock) Where InvoiceKey = @InvoiceKey

Select @Loop = 0

While @Loop < @RecurringCount
BEGIN

	Select @Loop = @Loop + 1
	
 -- 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
		begin
			rollback tran
			return -3					   	
		end
		

	IF @RecurringInterval = 1
		SELECT @InvoiceDate = DATEADD(month, @Loop, @CurInvoiceDate), @DueDate = DATEADD(month, @Loop, @CurDueDate)
	if @@ERROR <> 0 
	begin
		rollback tran
		return -3					   	
	end
	
	IF @RecurringInterval = 2
		SELECT @InvoiceDate = DATEADD(month, 3 * @Loop, @CurInvoiceDate), @DueDate = DATEADD(month, 3 * @Loop, @CurDueDate)
	if @@ERROR <> 0 
	begin
		rollback tran
		return -3					   	
	end
	
	IF @RecurringInterval = 3
		SELECT @InvoiceDate = DATEADD(year, @Loop, @CurInvoiceDate), @DueDate = DATEADD(year, @Loop, @CurDueDate)
	if @@ERROR <> 0 
	begin
		rollback tran
		return -3					   	
	end

	INSERT tInvoice
	(
		CompanyKey,
		ClientKey,
		ContactName,
		BillingContactKey,
		AdvanceBill,
		InvoiceNumber,
		InvoiceDate,
		PostingDate,
		DueDate,
		RecurringParentKey,
		TermsKey,
		ARAccountKey,
		GLCompanyKey,
		OfficeKey,
		ClassKey,
		ProjectKey,
		RetainerAmount,
		WriteoffAmount,
		DiscountAmount,
		SalesTaxAmount,
		SalesTax1Amount,
		SalesTax2Amount,
		TotalNonTaxAmount,
		InvoiceTotalAmount,
		AmountReceived,
		HeaderComment,
		SalesTaxKey,
		SalesTax2Key,
		InvoiceStatus,
		ApprovedDate,
		ApprovedByKey,
		ApprovalComments,
		Posted,
		Downloaded,
		InvoiceTemplateKey,
		LayoutKey,
		UserDefined1,
		UserDefined2,
		UserDefined3,
		UserDefined4,
		UserDefined5,
		UserDefined6,
		UserDefined7,
		UserDefined8,
		UserDefined9,
		UserDefined10,
		PrimaryContactKey,
		CreatedByKey,
		DateCreated,

		CurrencyID,
		ExchangeRate,
		GLCCurrencyID,
		GLCExchangeRate
	)
	Select
		CompanyKey,
		ClientKey,
		ContactName,
		BillingContactKey,
		AdvanceBill,
		RTRIM(@NextTranNo),
		@InvoiceDate,
		@InvoiceDate,
		@DueDate,
		RecurringParentKey,
		TermsKey,
		ARAccountKey,
		GLCompanyKey,
		OfficeKey,
		ClassKey,
		ProjectKey,
		0,
		0,
		DiscountAmount,
		SalesTaxAmount,
		SalesTax1Amount,
		SalesTax2Amount,
		TotalNonTaxAmount,
		InvoiceTotalAmount,
		0,
		HeaderComment,
		SalesTaxKey,
		SalesTax2Key,
		InvoiceStatus,
		ApprovedDate,
		ApprovedByKey,
		ApprovalComments,
		0,
		0,
		InvoiceTemplateKey,
		LayoutKey,
		UserDefined1,
		UserDefined2,
		UserDefined3,
		UserDefined4,
		UserDefined5,
		UserDefined6,
		UserDefined7,
		UserDefined8,
		UserDefined9,
		UserDefined10,
		PrimaryContactKey,
		CreatedByKey,
		DateCreated,

		CurrencyID,
		ExchangeRate,
		GLCCurrencyID,
		GLCExchangeRate
	From tInvoice (nolock) Where InvoiceKey = @InvoiceKey
	
	select @Error = @@ERROR, @NewKey = @@Identity
	
	if @Error <> 0 
	begin
		rollback tran
		return -3					   	
	end
	
	Insert #newkeys (InvoiceKey) values (@NewKey)
		
	exec sptInvoiceGenerateRecurringLines @InvoiceKey, @NewKey, 0 , 0
	
	if @@ERROR <> 0 
	begin
		rollback tran
		return -3					   	
	end

	-- removed since the sales taxes are now copied from the original invoice 
	-- also some temp tables are created within a SQL tran which is not recommended	
    --EXEC sptInvoiceRecalcAmounts @NewKey

END	

Commit Transaction

select @NewKey = -1
while (1=1)
begin
	select @NewKey = min(InvoiceKey)
	from   #newkeys
	where  InvoiceKey > @NewKey
	
	if @NewKey is null
		break
		
	exec sptInvoiceSummary @NewKey	 
	
end

-- Rollup does not have to be in transaction
-- Rollup for entity @InvoiceKey since same projects have been copied from that invoice to the other ones
EXEC sptProjectRollupUpdateEntity ''tInvoice'', @InvoiceKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceGetForReportLayout]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceGetForReportLayout]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptInvoiceGetForReportLayout]
	@InvoiceKey int
AS

/*
|| When      Who Rel      What
|| 04/06/10  MFT 10.5.2.1 Created for new Invoice report from the Layout Designer
|| 05/25/10  MFT 10.5.3.0 Added tProject
|| 08/19/10  MFT 10.5.3.4 Added tProject for header fields, NULLed TotalAmount on summary lines, InvoiceOrder in ORDER BY
|| 08/24/10  MFT 10.5.3.4 Added AEName
|| 10/21/10  MFT 10.5.3.7 Suppressed LineProjectDescription & LineProjectNumber for all but LineLevel = 1, Added tCampaign & cm tables & fields
|| 10/25/10  MFT 10.5.3.7 Added tInvoiceSummary subqueries for Labor and Expense amounts on the line
|| 11/15/10  MFT 10.5.3.8 Wrapped RetainerAmount & AmountReceived in ISNULL
|| 11/19/10  MFT 10.5.3.8 Allowed LineProjectDescription & LineProjectNumber for LineLevel = 0 (LineLevel < 2), Added Client AM (clam)
|| 12/03/10  MFT 10.5.3.8 Added tUser as bc & Title as BillingContactTitle, ISNULL on DisplayOption
|| 12/10/10  MFT 10.5.3.9 Corrected get to account for split billing
|| 12/13/10  MFT 10.5.3.9 Added percentage split and SUM/GROUP BY to tax get
|| 01/06/11  MFT 10.5.3.9 Suppressed Quantity and UnitAmount with the same LineType rule as TotalAmount
|| 01/18/11  MFT 10.5.4.0 Made Taxable & Taxable2 display "*"
|| 01/26/11  MFT 10.5.4.0 Setup(!) custom field support
|| 03/16/11  MFT 10.5.4.1 Changed NULL reference tests to check for 0 key on ISNULL as this seems to be possible in some foreign keys
|| 06/07/11  GHL 10.5.4.5 Added logic for company address from the GL company
|| 06/08/11  GHL 10.5.4.5 Added CompanyName/Phone/Fax from Company OR GL Company
|| 08/17/11  MFT 10.5.4.7 Put LineProjectNumber & LineProjectDescription into main select to test for header.CampaignKey (119116)
|| 10/21/11  MFT 10.5.4.9 Added RetainerAmountSales and RetainerAmountTaxes
|| 12/20/11  MFT 10.5.5.1 Added TaskID to line
|| 02/14/12  MFT 10.5.5.2 Added AEEmail
|| 03/21/12  MFT 10.5.5.4 (137257) Added Other Invoice data
|| 04/27/12  MFT 10.5.5.5 Added @PreviousBalance
|| 06/21/12  MFT 10.5.5.7 Removed @PreviousBalance, adjusted calculation to account for AdvanceBill
|| 06/25/12  MFT 10.5.5.7 Added @BalanceForward
|| 07/06/12  MFT 10.5.5.7 Wrapped RetainerAmount & AmountReceived in ISNULL
|| 07/09/12  MFT 10.5.5.7 Calculated @OtherInvoicePaymentsReceived by @InvoiceDate; corrected AllInvoicesOpenAmount calculation
|| 07/10/12  GHL 10.5.5.8 (148091) Added BillingName
|| 07/16/12  MFT 10.5.5.8 Made Office Address the primary address
|| 08/13/12  MFT 10.5.5.8 Added logic to get @PreviousInvoiceKey and @LastInvoicePaymentsReceived, etc.
|| 09/25/12  MFT 10.5.6.0 Added ClientDivisionName and ClientProductName
|| 03/12/13  MFT 10.5.6.7 Added ParentCompany
|| 04/01/13  MFT 10.5.6.7 Added HeaderClientDivision and HeaderClientProduct
|| 08/08/13  MFT 10.5.7.1 Added EINNumber
|| 08/15/13  MFT 10.5.7.1 Added ClientEINNumber
|| 08/16/13  MFT 10.5.7.1 Added StateEINNumber
|| 07/16/14  WDF 10.5.8.2 If GLCompany, use GL EINNumber
|| 03/17/15  MFT 10.5.9.0 (238426) Added @tPreviousInvoiceTasks and PrevAmountBilled, TotalAmountBilled
|| 03/23/15  MFT 10.5.9.0 (238426) Added ProjectKey to the line
|| 03/24/15  MFT 10.5.9.0 (238426) Added PrevAmountBilledTotal, TotalAmountBilledTotal to header
|| 08/25/15  MFT 10.5.9.5 (258079) Put DivisionName & ProductName into main select to test for header.CampaignKey
|| 10/20/15  MFT 10.5.9.7 (274350) Added support for Custom Fields at the line level
|| 10/21/15  MFT 10.5.9.7 (275064) Added Billing Group fields
|| 11/03/15  MFT 10.5.9.8 (276598) Removed percentage split from tax get
|| 11/13/15  MFT 10.5.9.9 (278267) Changed tax joins to tInvoiceTax
|| 07/26/16  WDF 10.6.0.7 (307513) Added RetainerDescription
|| 08/05/16  MFT 10.6.0.6 (308522) Added @tPreviousInvoice to optimize @tPreviousInvoiceTasks query
|| 02/21/17  MFT 10.6.1.3 (329967) Added #cfCampaign - changed #cfHeader to #cfProjectHeader and #cfDetail to #cfProjectLine, rejiggered subqueries
|| 03/17/17  MFT 10.6.1.4 (337599) Changed FULL JOIN to cartesian product
|| 03/28/17  MFT 10.6.1.4 (338812) Changed cartesian product to dervied temp table join
|| 04/03/17  WDF 10.6.1.5 (337804) Join between #Header and InvoiceLine changed from header.InvoiceKey to header.ParentInvoiceKey
|| 10/09/18  MFT 18.9.2.0 (422647) Add SalesPerson
|| 10/10/18  MFT 18.9.2.0 Changed tUser joins to vUserName
|| 10/22/18  MFT 18.9.2.0 Added ISNULL protection on TotalAmountBilledTotal and PrevAmountBilledTotal
|| 11/09/18  MFT 18.9.3.0 (430458) Fixed LineProjectDescription and LineProjectNumber bug
|| 12/07/18  MFT 19.0.1.0 (434669) Changed the @tPreviousInvoiceTasks to reference ProjectKey rather than TaskKey
|| 12/11/18  MFT 19.0.1.1 (435516) Rollback changes from 430458
|| 01/17/19  MFT 19.0.2.0 (434669) Renamed @tPreviousInvoice to @tPreviousInvoiceLines for clarity and changed join to subquery
|| 03/08/19  MFT 19.0.3.0 (434669) Changed AllInvoicesOpenAmount to use the InvoiceOpenAmount calc rather than just InvoiceAmount
|| 09/09/19  MFT 19.1.0.0 (478110) Removed the ClientKey restriction from the @OtherInvoicePaymentsReceived query
|| 10/02/19  MFT 19.1.0.0 (481308) Changed final cartesian result to outer join to allow no line Invoice to print
|| 10/30/20  AMP 20.1.2.0 (468346) Added Project Account Manager Name & Email to the line level
|| 11/04/20  AMP 20.1.2.0 (526925) Added Billing Contact Email
|| 03/19/21  AMP 21.04.18 (545722) Added Client Default Address (no overrides)
|| 04/01/21  MFT 21.05.0  (452457) Added @tBudgetTask and PrevAmountBilledTask, etc. fields for Balance Forward by Task fields
|| 04/28/21  MFT 21.05.0  (537668) Added support for Retainer Custom Fields
|| 07/20/21  MFT 21.08.0  (559288) Added header level totals for Balance Forward by Task fields; fixed Budget query
|| 08/31/21  MFT 21.09.0  (566204) Added Original Budegt and Approved CO amounts
|| 10/20/21  MFT 21.11.0  (573836) Added DateCreated and DeliveryDate
|| 10/22/21  GHL 21.1200  (575185) Added logic for ChildTaxable field which indicates which line is taxable on the child invoice
|| 03/02/22  MFT 22.0300  (590414) Override tax amounts
|| 03/14/22  MFT 22.0.4.0 (578711) Added ClientCampaignNumber
|| 05/03/22  MFT 22.0.6.0 (595472) Added CurrencyID
|| 05/18/22  MFT 22.0.6.0 (598881) CAST BillingName as nvarchar(200) to allow extended characters in CompanyName to show. May be remvoed after field converted to nvarchar.
|| 05/27/22  MFT 22.0.6.0 (600921) Override CurrencyID with Home Currency
|| 07/08/22  MFT 22.0.7.0 (605606) Correct the CurrencyID override to exclude the Client Currency
|| 09/20/22  MFT 22.10.00 (577716) Add Service/Item balance forward
|| 10/25/22  RLS 22.11.20 (600017) Removed CAST to nvarchar on BillingName since the field itself is now nvarchar
|| 11/22/22  MFT 22.12.20 (620199) Fixed CurrentTotalBudget calc
|| 11/22/22  AMP 23.01.15 (619756) Added BillingContactPhone
|| 02/22/23  MFT 23.02.00 (631520) Added ISNULL override to ExpenseAmount and LaborAmount
|| 06/14/23  AMP 23.09.17 (636559) Added PMName and LinePMName to display Project Manager on the printed invoice
|| 06/16/23  AMP 23.10.15 (638321) Added Billing Name
|| 07/19/23  AMP 23.08.20 (605818) Added Total With Sales Tax; per MFT: only test for LineType (not value) on values to be rolled up in Invoice.vb
|| 07/25/23  GAR 23.??.?? (DEV2605) Added SalesTaxKey to the Other sales taxes select (will be used by Avalara)
|| 03/05/24  RLB 24.04.14 (664982) use try to use invoice label from time rate sheet if project has a time rate sheet and row is a service row
|| 06/13/24  MFT 24.07.00 (674763) Fix TotalAmountBilledTotal and PrevAmountBilledTotal join to tInvoice rather than tInvoiceLine, remove tax from total
|| 08/07/24  AMP 24.09.15 (673673) Added InvoiceDateMonthName for an available Invoice Header Fields
|| 09/17/24  AMP 24.10.20 (683335) Added an override to get the ClientProduct, and Division from the Campaign first and then the Project
|| 12/16/24  MFT 25.01.00 (686350) Revert service rate sheet labels
|| 03/03/25  AMP 25.04.20 (685884) Added the Project Campaign Segment Name to the Invoice Header Fields
|| 12/17/25  MFT 26.01.00 (711010) Added Client custom fields
|| 01/06/25  MFT 26.02.00 (718322) Added NetExpenseAmount
|| 04/23/26  AMP 26.04.19 (681623) Added TaxRemaining and TotalNonTaxRemaining
|| 04/29/26  AMP 26.05.17 (725287) Added Total Estimate and Remaining to Bill
|| 05/12/26  MFT 26.05.00 (728624) Fix divide by zero error and subquery group
*/

DECLARE
	@ParentInvoiceKey int,
	@PercentageSplit decimal(24, 4),
	@CampaignKey int,
	@ClientKey int,
	@OtherInvoicesAmountBilled money,
	@OtherInvoicePaymentsReceived money,
	@LastInvoicePaymentsReceived money,
	@OtherInvoicesOpenAmount money,
	@InvoiceDate datetime,
	@InvoiceNumber varchar(35),
	@BalanceForward money,
	@PreviousInvoiceKey int,
	@StartDate datetime,
	@LayoutKey int,
	@ProjectKey int

DECLARE @tPreviousInvoiceLines table (
	InvoiceLineKey int,
	InvoiceKey int,
	InvoiceDate datetime,
	InvoiceNumber varchar(35),
	PostingDate datetime,
	CampaignKey int,
	ProjectKey int,
	TaskKey int,
	TotalAmount money,
	AdvanceBill tinyint,
	InvoiceTotalAmount money
)

DECLARE @tPreviousInvoiceTasks table (
	TaskKey int,
	TotalAmount money
)
DECLARE @tPreviousInvoiceProjects table (
		ProjectKey int,
		TotalAmount money
)
DECLARE @tPreviousInvoiceItems table (
	ItemKey int,
	CampaignKey int,
	ProjectKey int,
	TotalAmount money
)
DECLARE @tPreviousInvoiceServices table (
	ServiceKey int,
	CampaignKey int,
	ProjectKey int,
	TotalAmount money
)
DECLARE @tCurrentInvoiceItems table (
	ItemKey int,
	CampaignKey int,
	ProjectKey int,
	TotalAmount money
)
DECLARE @tCurrentInvoiceServices table (
	ServiceKey int,
	CampaignKey int,
	ProjectKey int,
	TotalAmount money
)
DECLARE @tBudgetTask table (
	TaskKey int,
	OriginalLaborAmount money,
	OriginalExpenseAmount money,
	OriginalBudgetAmount money,
	ApprovedCOLabor money,
	ApprovedCOExpense money,
	ApprovedCOAmount money,
	CurrentLaborAmount money,
	CurrentExpenseAmount money,
	CurrentBudgetAmount money,
	RemainingAmount money
)
DECLARE @tBudgetItem table (
	ItemKey int,
	WorkTypeKey int,
	OriginalQty decimal (24, 4),
	OriginalNetAmount money,
	OriginalGrossAmount money,
	ApprovedCOQty decimal (24, 4),
	ApprovedCONet money,
	ApprovedCOGross money,
	CurrentQty decimal (24, 4),
	CurrentNetAmount money,
	CurrentGrossAmount money,
	PreviousAmountBilled money,
	CurrentBilled money,
	RemainingAmount money
)
DECLARE @tBudgetService table (
	ServiceKey int,
	WorkTypeKey int,
	OriginalHours money,
	OriginalLaborNet money,
	OriginalLaborGross money,
	ApprovedCOHours money,
	ApprovedCOLaborNet money,
	ApprovedCOLaborGross money,
	CurrentHours money,
	CurrentLaborNet money,
	CurrentLaborGross money,
	PreviousAmountBilled money,
	CurrentBilled money,
	RemainingAmount money
)

SELECT
	@ParentInvoiceKey = ISNULL(ParentInvoiceKey, @InvoiceKey),
	@PercentageSplit = ISNULL(PercentageSplit, 100),
	@CampaignKey = ISNULL(CampaignKey, 0),
	@ClientKey = ClientKey,
	@InvoiceDate = InvoiceDate,
	@InvoiceNumber = InvoiceNumber,
	@OtherInvoicesAmountBilled = 0,
	@OtherInvoicePaymentsReceived = 0,
	@LastInvoicePaymentsReceived = 0,
	@OtherInvoicesOpenAmount = 0,
	@BalanceForward = 0,
	@LayoutKey = LayoutKey,
	@ProjectKey = ProjectKey
FROM tInvoice (nolock)
WHERE InvoiceKey = @InvoiceKey

IF ISNULL(@ProjectKey, 0) = 0
	BEGIN
		PRINT ''ProjectKey not found on Invoice header''
		DECLARE @Projects int
		SELECT @Projects = COUNT(*)
		FROM tInvoiceLine (nolock)
		WHERE InvoiceKey = @InvoiceKey
		GROUP BY ProjectKey

		IF @Projects = 1
		SELECT TOP 1 @ProjectKey = ProjectKey
		FROM tInvoiceLine (nolock)
		WHERE InvoiceKey = @InvoiceKey
	END

INSERT INTO @tPreviousInvoiceLines
SELECT
	il.InvoiceLineKey,
	i.InvoiceKey,
	InvoiceDate,
	InvoiceNumber,
	PostingDate,
	i.CampaignKey,
	ISNULL(il.ProjectKey, i.ProjectKey),
	il.TaskKey,
	il.TotalAmount,
	AdvanceBill,
	InvoiceTotalAmount
FROM
	tInvoice i (nolock)
	INNER JOIN tInvoiceLine il (nolock) ON i.InvoiceKey = il.InvoiceKey
WHERE
	ClientKey = @ClientKey AND
	ISNULL(CampaignKey, 0) = @CampaignKey AND
	(
			InvoiceDate < @InvoiceDate OR
			(
				InvoiceDate = @InvoiceDate AND
				InvoiceNumber < @InvoiceNumber
			)
	)

INSERT INTO @tPreviousInvoiceTasks
SELECT TaskKey, SUM(TotalAmount)
FROM @tPreviousInvoiceLines	
GROUP BY TaskKey

INSERT INTO @tPreviousInvoiceProjects
SELECT ProjectKey, SUM(TotalAmount)
FROM @tPreviousInvoiceLines
WHERE AdvanceBill = 0 --Only include non-advance billings in the project total, as that''s how we calculate the percentage split for advance billings
GROUP BY ProjectKey

INSERT INTO @tPreviousInvoiceItems
SELECT ItemKey, CampaignKey, ProjectKey, SUM(Amount)
FROM (
	SELECT il.EntityKey AS ItemKey, pil.CampaignKey, pil.ProjectKey, pil.TotalAmount AS Amount
	FROM
		@tPreviousInvoiceLines pil
		INNER JOIN tInvoiceLine il (nolock) ON pil.InvoiceLineKey = il.InvoiceLineKey
	WHERE
		il.BillFrom = 1 AND --Not using transactions
		il.Entity = ''tItem''

	UNION ALL

	SELECT ins.EntityKey, pil.CampaignKey, pil.ProjectKey, ins.Amount
	FROM
		@tPreviousInvoiceLines pil
		INNER JOIN tInvoiceLine il (nolock) ON pil.InvoiceLineKey = il.InvoiceLineKey
		INNER JOIN tInvoiceSummary ins (nolock) ON pil.InvoiceLineKey = ins.InvoiceLineKey
	WHERE
		pil.ProjectKey = @ProjectKey AND
		il.BillFrom = 2 AND --Transactions
		ins.Entity = ''tItem''
) a
GROUP BY ItemKey, CampaignKey, ProjectKey

INSERT INTO @tCurrentInvoiceItems
SELECT ItemKey, CampaignKey, ProjectKey, SUM(Amount)
FROM (
	SELECT il.EntityKey AS ItemKey, i.CampaignKey, ISNULL(il.ProjectKey, i.ProjectKey) AS ProjectKey, il.TotalAmount AS Amount
	FROM
		tInvoiceLine il (nolock)
		INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
	WHERE
		il.InvoiceKey = @InvoiceKey AND
		il.BillFrom = 1 AND --Not using transactions
		il.Entity = ''tItem''

	UNION ALL

	SELECT ins.EntityKey, i.CampaignKey, ISNULL(il.ProjectKey, i.ProjectKey) AS ProjectKey, ins.Amount
	FROM
		tInvoiceLine il (nolock)
		INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
		INNER JOIN tInvoiceSummary ins (nolock) ON il.InvoiceLineKey = ins.InvoiceLineKey
	WHERE
		il.InvoiceKey = @InvoiceKey AND
		il.BillFrom = 2 AND --Transactions
		ins.Entity = ''tItem''
) a
GROUP BY ItemKey, CampaignKey, ProjectKey

INSERT INTO @tPreviousInvoiceServices
SELECT ServiceKey, CampaignKey, ProjectKey, SUM(Amount)
FROM (
	SELECT il.EntityKey AS ServiceKey, pil.CampaignKey, pil.ProjectKey, pil.TotalAmount AS Amount
	FROM
		@tPreviousInvoiceLines pil
		INNER JOIN tInvoiceLine il (nolock) ON pil.InvoiceLineKey = il.InvoiceLineKey
	WHERE
		il.BillFrom = 1 AND --Not using transactions
		il.Entity = ''tService''

	UNION ALL

	SELECT ins.EntityKey, pil.CampaignKey, pil.ProjectKey, ins.Amount
	FROM
		@tPreviousInvoiceLines pil
		INNER JOIN tInvoiceLine il (nolock) ON pil.InvoiceLineKey = il.InvoiceLineKey
		INNER JOIN tInvoiceSummary ins (nolock) ON pil.InvoiceLineKey = ins.InvoiceLineKey
	WHERE
		pil.ProjectKey = @ProjectKey AND
		il.BillFrom = 2 AND --Transactions
		ins.Entity = ''tService''
) a
GROUP BY ServiceKey, CampaignKey, ProjectKey

INSERT INTO @tCurrentInvoiceServices
SELECT ServiceKey, CampaignKey, ProjectKey, SUM(Amount)
FROM (
	SELECT il.EntityKey AS ServiceKey, i.CampaignKey, ISNULL(il.ProjectKey, i.ProjectKey) AS ProjectKey, il.TotalAmount AS Amount
	FROM
		tInvoiceLine il (nolock)
		INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
	WHERE
		il.InvoiceKey = @InvoiceKey AND
		il.BillFrom = 1 AND --Not using transactions
		il.Entity = ''tService''

	UNION ALL

	SELECT ins.EntityKey, i.CampaignKey, ISNULL(il.ProjectKey, i.ProjectKey) AS ProjectKey, ins.Amount
	FROM
		tInvoiceLine il (nolock)
		INNER JOIN tInvoice i (nolock) ON il.InvoiceKey = i.InvoiceKey
		INNER JOIN tInvoiceSummary ins (nolock) ON il.InvoiceLineKey = ins.InvoiceLineKey
	WHERE
		il.InvoiceKey = @InvoiceKey AND
		il.BillFrom = 2 AND --Transactions
		ins.Entity = ''tService''
) a
GROUP BY ServiceKey, CampaignKey, ProjectKey

INSERT INTO @tBudgetTask
SELECT
	t.TaskKey,
	SUM(t.EstLabor),
	SUM(t.EstExpenses),
	SUM(t.EstLabor) + SUM(t.EstExpenses),
	SUM(t.ApprovedCOLabor),
	SUM(t.ApprovedCOExpense),
	SUM(t.ApprovedCOExpense) + SUM(t.ApprovedCOLabor),	
	SUM(t.EstLabor) + SUM(t.ApprovedCOLabor),
	SUM(t.EstExpenses) + SUM(t.ApprovedCOExpense),
	SUM(t.EstLabor) + SUM(t.EstExpenses) + SUM(t.ApprovedCOExpense) + SUM(t.ApprovedCOLabor),	
	SUM(t.EstLabor) + SUM(t.EstExpenses) + SUM(t.ApprovedCOExpense) + SUM(t.ApprovedCOLabor) - SUM(ISNULL(pit.TotalAmount, 0)) - (SUM(il.TotalAmount) * (@PercentageSplit/100))
FROM
	tInvoiceLine il (nolock)
	INNER JOIN tTask t (nolock) ON il.TaskKey = t.TaskKey
	LEFT JOIN @tPreviousInvoiceTasks pit ON il.TaskKey = pit.TaskKey
WHERE
	il.InvoiceKey = @InvoiceKey
GROUP BY
	t.TaskKey

INSERT INTO @tBudgetItem
SELECT
	ISNULL(pei.EntityKey, ISNULL(cii.ItemKey, pii.ItemKey)),
	ISNULL(lb.ParentEntityKey, 0) AS WorkTypeKey,
	SUM(pei.Qty),
	SUM(pei.Net),
	SUM(pei.Gross),
	SUM(pei.COQty),
	SUM(pei.CONet),
	SUM(pei.COGross),
	SUM(pei.Qty) + SUM(pei.COQty),
	SUM(pei.Net) + SUM(pei.CONet),
	SUM(pei.Gross) + SUM(pei.COGross),
	SUM(ISNULL(pii.TotalAmount, 0)),
	(SUM(ISNULL(cii.TotalAmount, 0)) * (@PercentageSplit/100)),
	SUM(pei.Net) + SUM(pei.CONet) - SUM(ISNULL(pii.TotalAmount, 0)) - (SUM(ISNULL(cii.TotalAmount, 0)) * (@PercentageSplit/100)) --NET + CONET - PREVIOUS - (CURRENT * SPLIT %)
FROM
	(SELECT * FROM tProjectEstByItem (nolock) WHERE ProjectKey = @ProjectKey AND Entity = ''tItem'') pei
	FULL JOIN @tCurrentInvoiceItems cii ON pei.EntityKey = cii.ItemKey AND pei.Entity = ''tItem''
	FULL JOIN (SELECT * FROM @tPreviousInvoiceItems WHERE ISNULL(ProjectKey, 0) = @ProjectKey) pii ON pei.EntityKey = pii.ItemKey AND pei.Entity = ''tItem''
	LEFT JOIN tLayoutBilling lb (nolock) ON lb.Entity = ''tItem'' AND lb.ParentEntity = ''tWorkType'' AND lb.EntityKey = ISNULL(pei.EntityKey, ISNULL(cii.ItemKey, pii.ItemKey)) AND lb.LayoutKey = @LayoutKey
GROUP BY
	ISNULL(pei.EntityKey, ISNULL(cii.ItemKey, pii.ItemKey)),
	ISNULL(lb.ParentEntityKey, 0)

INSERT INTO @tBudgetService
SELECT
	ISNULL(pei.EntityKey, ISNULL(cis.ServiceKey, pis.ServiceKey)),
	ISNULL(lb.ParentEntityKey, 0) AS WorkTypeKey,
	SUM(pei.Qty),
	SUM(pei.Net),
	SUM(pei.Gross),
	SUM(pei.COQty),
	SUM(pei.CONet),
	SUM(pei.COGross),
	SUM(pei.Qty) + SUM(pei.COQty),
	SUM(pei.Net) + SUM(pei.CONet),
	SUM(pei.Gross) + SUM(pei.COGross),
	SUM(ISNULL(pis.TotalAmount, 0)),
	(SUM(ISNULL(cis.TotalAmount, 0)) * (@PercentageSplit/100)),
	SUM(pei.Net) + SUM(pei.CONet) - SUM(ISNULL(pis.TotalAmount, 0)) - (SUM(ISNULL(cis.TotalAmount, 0)) * (@PercentageSplit/100))
FROM
	(SELECT * FROM tProjectEstByItem (nolock) WHERE ProjectKey = @ProjectKey AND Entity = ''tService'') pei
	FULL JOIN @tCurrentInvoiceServices cis ON pei.EntityKey = cis.ServiceKey AND pei.Entity = ''tService''
	FULL JOIN (SELECT * FROM @tPreviousInvoiceServices WHERE ISNULL(ProjectKey, 0) = @ProjectKey) pis ON pei.EntityKey = pis.ServiceKey AND pei.Entity = ''tService''
	LEFT JOIN tLayoutBilling lb (nolock) ON lb.Entity = ''tService'' AND lb.ParentEntity = ''tWorkType'' AND lb.EntityKey = ISNULL(pei.EntityKey, ISNULL(cis.ServiceKey, pis.ServiceKey)) AND lb.LayoutKey = @LayoutKey
GROUP BY
	ISNULL(pei.EntityKey, ISNULL(cis.ServiceKey, pis.ServiceKey)),
	ISNULL(lb.ParentEntityKey, 0)

SELECT TOP 1
	@PreviousInvoiceKey = InvoiceKey,
	@StartDate = ISNULL(InvoiceDate, ''1900-01-01'')
FROM
	@tPreviousInvoiceLines
WHERE
	PostingDate <= @InvoiceDate
ORDER BY
	InvoiceDate DESC,
	InvoiceNumber DESC

SELECT
	@LastInvoicePaymentsReceived = ISNULL(SUM(ca.Amount), 0)
FROM
	tCheckAppl ca (nolock)
	INNER JOIN tCheck c (nolock) ON ca.CheckKey = c.CheckKey
	INNER JOIN tInvoice i (nolock) ON ca.InvoiceKey = i.InvoiceKey
WHERE
	c.ClientKey = @ClientKey AND
	c.PostingDate <= @InvoiceDate AND
	c.PostingDate >= @StartDate AND
	ISNULL(CampaignKey, 0) = @CampaignKey

--tInvoiceCredit NOT included here
SELECT
	@OtherInvoicePaymentsReceived = ISNULL(SUM(ca.Amount), 0)
FROM
	tCheckAppl ca (nolock)
	INNER JOIN tCheck c (nolock) ON ca.CheckKey = c.CheckKey
WHERE
--	c.ClientKey = @ClientKey AND
	c.PostingDate <= @InvoiceDate AND
	ca.InvoiceKey IN (SELECT InvoiceKey FROM @tPreviousInvoiceLines)

SELECT
	@OtherInvoicesAmountBilled = ISNULL(SUM(CASE AdvanceBill WHEN 1 THEN 0 ELSE TotalAmount END), 0),
	@OtherInvoicesOpenAmount = @OtherInvoicesAmountBilled - @OtherInvoicePaymentsReceived + @LastInvoicePaymentsReceived,
	@BalanceForward = @OtherInvoicesAmountBilled - @OtherInvoicePaymentsReceived
FROM
	@tPreviousInvoiceLines

--.NET created temp tables by standard code; need to change the CustomFieldKey col name to support additional (4th & 5th) CF tables
EXEC tempdb.sys.sp_rename ''#cfRetainer.CustomFieldKey'', ''RetainerCustomFieldKey'', ''COLUMN''
EXEC tempdb.sys.sp_rename ''#cfClient.CustomFieldKey'', ''ClientCustomFieldKey'', ''COLUMN''

--Calculate Tax Remaining
DECLARE @TaxRemaining AS money
SELECT @TaxRemaining = ISNULL(SUM(
	CASE
		WHEN ISNULL(i.InvoiceTotalAmount, 0) = 0 THEN it.SalesTaxAmount
		ELSE ROUND(it.SalesTaxAmount - (it.SalesTaxAmount * (i.AmountReceived / i.InvoiceTotalAmount)), 2)
	END), 0)
FROM
	tInvoiceTax it (nolock)
	INNER JOIN tInvoice i (nolock) ON it.InvoiceKey = i.InvoiceKey
WHERE it.InvoiceKey = @InvoiceKey

--Calculate Total Remaining
--Invoice Amount - The payments and credits
DECLARE @TotalNonTaxRemaining AS Money

SELECT @TotalNonTaxRemaining = ISNULL(InvoiceTotalAmount, 0) - ISNULL(WriteoffAmount, 0) - ISNULL(DiscountAmount, 0) - ISNULL(RetainerAmount, 0) - ISNULL(AmountReceived, 0)  - @TaxRemaining
FROM tInvoice (nolock)
WHERE InvoiceKey = @InvoiceKey

SELECT
	-- Company Address 1) on Office 2) on GL Company 3) Default Address on Company
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.Address1 ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.Address1 ELSE ca.Address1 END END AS CAddress1,
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.Address2 ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.Address2 ELSE ca.Address2 END END AS CAddress2,
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.Address3 ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.Address3 ELSE ca.Address3 END END AS CAddress3,
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.City ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.City ELSE ca.City END END AS CCity,
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.State ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.State ELSE ca.State END END AS CState,
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.PostalCode ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.PostalCode ELSE ca.PostalCode END END AS CPostalCode,
	CASE WHEN oa.AddressKey IS NOT NULL THEN oa.Country ELSE CASE WHEN glca.AddressKey IS NOT NULL THEN glca.Country ELSE ca.Country END END AS CCountry,
	CASE WHEN glc.GLCompanyKey IS NOT NULL THEN glc.PrintedName ELSE c.CompanyName END AS CompanyName,
	CASE WHEN glc.GLCompanyKey IS NOT NULL THEN glc.Phone ELSE c.Phone END AS Phone,
	CASE WHEN glc.GLCompanyKey IS NOT NULL THEN glc.Fax ELSE c.Fax END AS Fax,
	CASE WHEN glc.GLCompanyKey IS NOT NULL THEN glc.EINNumber ELSE c.EINNumber END AS EINNumber,
	c.StateEINNumber,
	ISNULL(cl.BillingName, cl.CompanyName) AS ClientName,	
	cl.CustomerID,
	cl.BillingName,
	cl.EINNumber AS ClientEINNumber,
	pc.CompanyName AS ParentCompany,
	-- Billing Address 1) On Invoice, 2) on Client Billing Address, 3) on Client Default Address
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.Address1
		ELSE
			CASE
				WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.Address1
				ELSE clda.Address1
			END
	END AS BAddress1,
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.Address2
		ELSE
			CASE
				WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.Address2
				ELSE clda.Address2
			END
	END AS BAddress2,
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.Address3
		ELSE
		CASE
			WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.Address3
			ELSE clda.Address3
		END
	END AS BAddress3,
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.City
		ELSE
			CASE
				WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.City
				ELSE clda.City
			END
	END AS BCity,
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.State
		ELSE
			CASE
				WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.State
				ELSE clda.State
			END
	END AS BState,
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.PostalCode
		ELSE
			CASE 
				WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.PostalCode
				ELSE clda.PostalCode
			END
	END AS BPostalCode,
	CASE
		WHEN ISNULL(i.AddressKey, 0) > 0 THEN ia.Country
		ELSE
			CASE 
				WHEN ISNULL(cl.BillingAddressKey, 0) > 0 THEN clba.Country
				ELSE clda.Country
			END
	END AS BCountry,

	--Client Default Address (no overrides)
	clda.Address1 AS CDAddress1,
	clda.Address2 AS CDAddress2,
	clda.Address3 AS CDAddress3,
	clda.City AS CDCity,
			clda.State AS CDState,
	clda.PostalCode AS CDPostalCode,
	clda.Country AS CDCountry,

	i.InvoiceKey,
	@ParentInvoiceKey AS ParentInvoiceKey,
	i.ContactName AS BillingContact,	
	bc.Email AS BillingContactEmail,
	bc.Title AS BillingContactTitle,
	bc.Phone1 AS BillingContactPhone,
	i.AdvanceBill,
	i.InvoiceNumber,
	i.InvoiceDate,
	DATENAME(month, i.InvoiceDate) AS InvoiceDateMonthName,
	i.DueDate,
	i.PostingDate,
	ISNULL(i.RetainerAmount, 0) AS RetainerAmount,
	ISNULL(i.RetainerAmount, 0) - ISNULL((SELECT SUM(iabt.Amount) FROM tInvoiceAdvanceBillTax iabt (nolock) WHERE iabt.InvoiceKey = i.InvoiceKey), 0) AS RetainerAmountSales,
	ISNULL((SELECT SUM(iabt.Amount) FROM tInvoiceAdvanceBillTax iabt (nolock) WHERE iabt.InvoiceKey = i.InvoiceKey), 0) AS RetainerAmountTaxes,
	i.WriteoffAmount,
	i.DiscountAmount,
	i.SalesTaxAmount AS SalesTaxAmount_ORIG,
	ISNULL((SELECT SUM(it.SalesTaxAmount) FROM tInvoiceTax it (nolock) WHERE it.InvoiceKey = @InvoiceKey), 0) AS SalesTaxAmount,
	i.SalesTax1Amount AS SalesTax1Amount_ORIG,
	ISNULL((SELECT SUM(it.SalesTaxAmount) FROM tInvoiceTax it (nolock) WHERE it.Type = 1 AND it.InvoiceKey = @InvoiceKey), 0) AS SalesTax1Amount,
	st1.SalesTaxID,
	st1.SalesTaxName,
	st1.Description AS SalesTaxDescription,
	st1.TaxRate,
	i.SalesTax2Amount AS SalesTax2Amount_ORIG,
	ISNULL((SELECT SUM(it.SalesTaxAmount) FROM tInvoiceTax it (nolock) WHERE it.Type = 2 AND it.InvoiceKey = @InvoiceKey), 0) AS SalesTax2Amount,
	st2.SalesTaxID AS SalesTax2ID,
	st2.SalesTaxName AS SalesTax2Name,
	st2.Description AS SalesTax2Description,
	st2.TaxRate AS Tax2Rate,
	i.TotalNonTaxAmount,
	i.InvoiceTotalAmount,
	ISNULL(i.AmountReceived, 0) AS AmountReceived,
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.DiscountAmount, 0) - ISNULL(i.RetainerAmount, 0) AS BilledAmount,
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.DiscountAmount, 0) - ISNULL(i.RetainerAmount, 0) - ISNULL(i.AmountReceived, 0) AS OpenAmount,
	ISNULL(p.CurrencyID, ISNULL(cp.CurrencyID, pf.CurrencyID)) AS CurrencyID,
	i.HeaderComment,
	i.ApprovedDate,
	i.DateCreated,
	i.DeliveryDate,
	i.ApprovedByKey,
	i.ApprovalComments,
	i.PercentageSplit,
	p.ProjectName AS HeaderProjectName,
	p.ProjectNumber AS HeaderProjectNumber,
	p.ClientProjectNumber AS HeaderClientProjectNumber,
	cd.DivisionName AS HeaderClientDivision,
	clp.ProductName AS HeaderClientProduct,
	p.Description AS HeaderProjectDescription,
	cs.SegmentName,
	CASE WHEN ISNULL(i.ProjectKey, 0) = 0 THEN CASE WHEN ISNULL(cp.CampaignKey, 0) = 0 THEN clam.UserName ELSE cm.UserName END ELSE am.UserName END AS AEName,
	CASE WHEN ISNULL(i.ProjectKey, 0) = 0 THEN CASE WHEN ISNULL(cp.CampaignKey, 0) = 0 THEN clam.Email ELSE cm.Email END ELSE am.Email END AS AEEmail,
	CASE WHEN ISNULL(i.ProjectKey, 0) = 0 THEN CASE WHEN ISNULL(cp.CampaignKey, 0) = 0 THEN clpm.UserName ELSE cm.UserName END ELSE pm.UserName END AS PMName,
	sm.UserName AS SalesPerson,
	cp.CampaignKey,
	cp.CampaignID,
	cp.CampaignName,
	cp.Description AS CampaignDesc,
	cp.Objective AS CampaignObjective,	
	cp.ClientCampaignNumber,
	cm.UserName AS CMName,
	pt.TermsDescription,
	@OtherInvoicesAmountBilled AS OtherInvoicesAmountBilled,
	@LastInvoicePaymentsReceived AS OtherInvoicePaymentsReceived,
	@OtherInvoicesOpenAmount AS OtherInvoicesOpenAmount,
	@BalanceForward AS BalanceForward,
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.WriteoffAmount, 0) - ISNULL(i.DiscountAmount, 0) - ISNULL(i.RetainerAmount, 0) - ISNULL(i.AmountReceived, 0) + @BalanceForward AS AllInvoicesOpenAmount,
	(SELECT ISNULL(SUM(pip.TotalAmount), 0) FROM @tPreviousInvoiceProjects pip INNER JOIN tInvoice i (nolock) ON pip.ProjectKey = i.ProjectKey WHERE i.InvoiceKey = @InvoiceKey) AS PrevAmountBilledTotal,
	(SELECT ISNULL(SUM(pip.TotalAmount), 0) FROM @tPreviousInvoiceProjects pip INNER JOIN tInvoice i (nolock) ON pip.ProjectKey = i.ProjectKey WHERE i.InvoiceKey = @InvoiceKey) + i.TotalNonTaxAmount AS TotalAmountBilledTotal,
	bg.BillingGroupCode,
	bg.Description AS BillingGroupDescription,
	bg.Comments AS BillingGroupComments,
	p.CustomFieldKey AS ProjectCustomFieldKey,
	cp.CustomFieldKey AS CampaignCustomFieldKey,
	cl.CustomFieldKey AS ClientCustomFieldKey,
	(SELECT ISNULL(SUM(pit.TotalAmount), 0) FROM @tPreviousInvoiceTasks pit INNER JOIN tInvoiceLine il (nolock) ON pit.TaskKey = il.TaskKey WHERE il.InvoiceKey = @InvoiceKey) AS TotalPrevAmountBilledTask,
	(SELECT ISNULL(SUM(pit.TotalAmount), 0) FROM @tPreviousInvoiceTasks pit INNER JOIN tInvoiceLine il (nolock) ON pit.TaskKey = il.TaskKey WHERE il.InvoiceKey = @InvoiceKey) + (SELECT ISNULL(SUM(TotalAmount) * (@PercentageSplit/100), 0) FROM tInvoiceLine WHERE InvoiceKey = @InvoiceKey) AS TotalAmountBilledTaskTotal,
	(SELECT ISNULL(SUM(CurrentBudgetAmount), 0) FROM @tBudgetTask) AS TotalTaskBudgetAmount,
	(SELECT ISNULL(SUM(RemainingAmount), 0) FROM @tBudgetTask) AS TotalRemainingAmountTask,
	(SELECT ISNULL(SUM(ApprovedCOAmount), 0) FROM @tBudgetTask) AS TotalApprovedCOAmountTask,
	(SELECT ISNULL(SUM(OriginalBudgetAmount), 0) FROM @tBudgetTask) AS TotalOriginalBudgetAmountTask,
	@TaxRemaining AS TaxRemaining,
	@TotalNonTaxRemaining AS TotalNonTaxRemaining,
	lp.EstimateTotal AS TotalEstimate,
	lp.EstimateTotal - (SELECT ISNULL(SUM(pip.TotalAmount), 0) FROM @tPreviousInvoiceProjects pip INNER JOIN tInvoice i (nolock) ON pip.ProjectKey = i.ProjectKey WHERE i.InvoiceKey = @InvoiceKey) - i.InvoiceTotalAmount AS RemainingToBill
INTO #header
FROM
	tInvoice i (nolock)
	INNER JOIN tCompany c (nolock)
		ON i.CompanyKey = c.CompanyKey
	INNER JOIN tCompany cl (nolock)
		ON i.ClientKey = cl.CompanyKey
	LEFT JOIN tCompany pc (nolock)
		ON cl.ParentCompanyKey = pc.CompanyKey
	LEFT JOIN tProject p (nolock)
		ON i.ProjectKey = p.ProjectKey
	LEFT JOIN tCampaignSegment cs (nolock)
		ON p.CampaignSegmentKey = cs.CampaignSegmentKey
	LEFT JOIN tPreference pf (nolock)
		ON p.CompanyKey = pf.CompanyKey
	LEFT JOIN tCampaign cp (nolock)
		ON i.CampaignKey = cp.CampaignKey
	LEFT JOIN tClientDivision cd (nolock)
		ON ISNULL(cp.ClientDivisionKey, p.ClientDivisionKey) = cd.ClientDivisionKey
	LEFT JOIN tClientProduct clp (nolock)
		ON ISNULL(cp.ClientProductKey, p.ClientProductKey) = clp.ClientProductKey
	LEFT JOIN vUserName am (nolock)
		ON p.AccountManager = am.UserKey
	LEFT JOIN vUserName pm (nolock)
		ON p.ProjectManager = pm.UserKey
	LEFT JOIN vUserName sm (nolock)
		ON cl.SalesPersonKey = sm.UserKey
	LEFT JOIN vUserName cm (nolock)
		ON cp.AEKey = cm.UserKey
	LEFT JOIN vUserName clam (nolock)
		ON cl.AccountManagerKey = clam.UserKey  
	LEFT JOIN vUserName clpm (nolock)
		ON cl.ProjectManagerKey = clpm.UserKey 
	LEFT JOIN tAddress ca (nolock)
		ON c.DefaultAddressKey = ca.AddressKey
	LEFT JOIN tAddress ia (nolock)
		ON i.AddressKey = ia.AddressKey
	LEFT JOIN tAddress clba (nolock)
		ON cl.BillingAddressKey = clba.AddressKey
	LEFT JOIN tAddress clda (nolock)
		ON cl.DefaultAddressKey = clda.AddressKey
	LEFT JOIN tGLCompany glc (nolock)
		ON i.GLCompanyKey = glc.GLCompanyKey
	LEFT JOIN tAddress glca (nolock)
		ON glc.AddressKey = glca.AddressKey
	LEFT JOIN tOffice o (nolock)
		ON i.OfficeKey = o.OfficeKey
	LEFT JOIN tAddress oa (nolock)
		ON o.AddressKey = oa.AddressKey
	LEFT JOIN tPaymentTerms pt (nolock)
		ON i.TermsKey = pt.PaymentTermsKey
	LEFT JOIN tSalesTax st1 (nolock)
		ON i.SalesTaxKey = st1.SalesTaxKey
	LEFT JOIN tSalesTax st2 (nolock)
		ON i.SalesTax2Key = st2.SalesTaxKey
	LEFT JOIN vUserName bc (nolock)
		ON i.PrimaryContactKey = bc.UserKey
	LEFT JOIN tBillingGroup bg (nolock)
		ON i.BillingGroupKey = bg.BillingGroupKey
	LEFT JOIN (SELECT SUM(Net) AS Net, InvoiceKey FROM vInvoiceExpenses GROUP BY InvoiceKey) ie
		ON i.InvoiceKey = ie.InvoiceKey
	LEFT JOIN (SELECT SUM(EstimateTotal) AS EstimateTotal, InvoiceKey FROM (
			SELECT DISTINCT il.ProjectKey, il.InvoiceKey
			FROM
				tProject p (nolock)
				INNER JOIN tInvoiceLine il (nolock) ON p.ProjectKey = il.ProjectKey
		) a
		INNER JOIN (
			SELECT SUM(p.EstExpenses + p.EstLabor) AS EstimateTotal, p.ProjectKey
			FROM tProject p (nolock)
			GROUP BY p.ProjectKey 
		) b ON a.ProjectKey = b.ProjectKey
		GROUP BY InvoiceKey
	) lp ON lp.InvoiceKey = i.InvoiceKey
WHERE
	i.InvoiceKey = @InvoiceKey

-- now determine if the child invoice lines are taxable
create table #lines (InvoiceLineKey int, ParentLineKey int, ChildTaxable int, ChildTaxable2 int)
create index idxline on #lines (InvoiceLineKey)
declare @IsChild int
select @IsChild = 0

if isnull(@ParentInvoiceKey, 0) > 0 and isnull(@ParentInvoiceKey, 0) <> isnull(@InvoiceKey, 0)
begin
	select @IsChild = 1

	insert #lines (InvoiceLineKey, ParentLineKey, ChildTaxable, ChildTaxable2)
	select InvoiceLineKey, ParentLineKey, 0, 0
	from   tInvoiceLine (nolock)
	where  InvoiceKey = @ParentInvoiceKey -- parent

	-- we have to rely on tInvoiceTax records
	update #lines
	set    #lines.ChildTaxable = 1
	from   tInvoiceTax it (nolock)
	where  it.InvoiceKey = @InvoiceKey -- child
	and    it.InvoiceLineKey = #lines.InvoiceLineKey
	and    it.SalesTaxAmount <> 0
	and    it.Type = 1

	update #lines
	set    #lines.ChildTaxable2 = 1
	from   tInvoiceTax it (nolock)
	where  it.InvoiceKey = @InvoiceKey -- child
	and    it.InvoiceLineKey = #lines.InvoiceLineKey
	and    it.SalesTaxAmount <> 0
	and    it.Type = 2

	-- now bubble up the Taxable flag to the summary lines 
	update #lines
	set    #lines.ChildTaxable = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable = 1

	update #lines
	set    #lines.ChildTaxable = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable = 1

	update #lines
	set    #lines.ChildTaxable = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable = 1

	update #lines
	set    #lines.ChildTaxable = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable = 1

	update #lines
	set    #lines.ChildTaxable = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable = 1

	-- tax 2

	update #lines
	set    #lines.ChildTaxable2 = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable2 = 1

	update #lines
	set    #lines.ChildTaxable2 = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable2 = 1

	update #lines
	set    #lines.ChildTaxable2 = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable2 = 1

	update #lines
	set    #lines.ChildTaxable = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable2 = 1

	update #lines
	set    #lines.ChildTaxable2 = 1
	from   #lines 
	inner join #lines child on child.ParentLineKey = #lines.InvoiceLineKey 
	where  child.ChildTaxable2 = 1

end


SELECT
	*,
	CASE WHEN (lines.LineLevel = 1 AND ISNULL(header.CampaignKey, 0) > 0) OR lines.LineLevel = 0 THEN lines.ProjectNumber ELSE '''' END AS LineProjectNumber,
	CASE WHEN (lines.LineLevel = 1 AND ISNULL(header.CampaignKey, 0) > 0) OR lines.LineLevel = 0 THEN lines.ProjectDescription ELSE '''' END AS LineProjectDescription,
	CASE WHEN (lines.LineLevel = 1 AND ISNULL(header.CampaignKey, 0) > 0) OR lines.LineLevel = 0 THEN lines.LineDivisionName ELSE '''' END AS DivisionName,
	CASE WHEN (lines.LineLevel = 1 AND ISNULL(header.CampaignKey, 0) > 0) OR lines.LineLevel = 0 THEN lines.LineProductName ELSE '''' END AS ProductName
FROM
	#header header
	LEFT JOIN
	(
		SELECT
			il.InvoiceKey AS LineInvoiceKey,
			il.InvoiceLineKey,
			il.LineType,
			il.LineSubject, 
			il.LineDescription,
			il.BillFrom,
			il.BilledTimeAmount,
			il.BilledExpenseAmount,
			il.ProjectKey,
			CASE WHEN il.LineType = 1 THEN NULL ELSE il.Quantity END AS Quantity,
			CASE WHEN il.LineType = 1 THEN NULL ELSE il.UnitAmount END AS UnitAmount,
			CASE WHEN il.LineType = 1 THEN NULL ELSE il.TotalAmount * (@PercentageSplit/100) END AS TotalAmount,
			il.PostSalesUsingDetail,
			il.InvoiceOrder,
			il.DisplayOrder,

			CASE WHEN il.LineType = 1 AND ISNULL(il.TotalAmount, 0) = 0 
			THEN '''' 
			ELSE 
				CASE WHEN @IsChild = 0 then CASE il.Taxable WHEN 1 THEN ''*'' ELSE '''' END
				     ELSE CASE l.ChildTaxable WHEN 1 THEN ''*'' ELSE '''' END 
					 END
			END AS Taxable,

			CASE WHEN il.LineType = 1 AND ISNULL(il.TotalAmount, 0) = 0 
			THEN '''' 
			ELSE 
				CASE WHEN @IsChild = 0 then CASE il.Taxable2 WHEN 1 THEN ''*'' ELSE '''' END
				     ELSE CASE l.ChildTaxable2 WHEN 1 THEN ''*'' ELSE '''' END 
					 END
			END AS Taxable2,

			/* to rollback original code
			CASE WHEN il.LineType = 1 AND ISNULL(il.TotalAmount, 0) = 0 THEN '''' ELSE CASE il.Taxable1 WHEN 1 THEN ''*'' ELSE '''' END END AS Taxable,
			CASE WHEN il.LineType = 1 AND ISNULL(il.TotalAmount, 0) = 0 THEN '''' ELSE CASE il.Taxable2 WHEN 1 THEN ''*'' ELSE '''' END END AS Taxable2,
			*/
			 il.LineLevel,			
			CASE WHEN il.LineType = 1 THEN NULL ELSE il.SalesTaxAmount * (@PercentageSplit/100) END AS LineSalesTaxAmount,
		    CASE WHEN il.LineType = 1 THEN NULL ELSE il.SalesTax1Amount * (@PercentageSplit/100) END AS LineSalesTax1Amount,
		    CASE WHEN il.LineType = 1 THEN NULL ELSE il.SalesTax2Amount * (@PercentageSplit/100) END AS LineSalesTax2Amount,
		    CASE WHEN il.LineType = 1 THEN NULL ELSE il.TotalAmount + isnull(il.SalesTaxAmount * (@PercentageSplit/100), 0.00) END AS TotalWithSalesTax,
		
			ISNULL(il.DisplayOption, CASE il.LineType WHEN 1 THEN 2 WHEN 2 THEN 1 END) AS DisplayOption,
			pl.ProjectName AS LineProjectName,
			pl.ProjectNumber,
	        pl.Description AS ProjectDescription,
			pl.ClientProjectNumber AS LineClientProjectNumber,
			am.UserName  AS LineAEName,
			pm.UserName  AS LinePMName,
			am.Email  AS LineAEEmail,			
			cd.DivisionName AS LineDivisionName,
			cp.ProductName AS LineProductName,
			rtn.Description AS RetainerDescription,
			t.TaskID,
			t.TaskKey,
			ISNULL(ise.ExpenseAmount * (@PercentageSplit/100), 0) AS ExpenseAmount,
			ISNULL(isl.LaborAmount * (@PercentageSplit/100), 0) AS LaborAmount,
			CASE WHEN il.LineType = 1 AND ISNULL(il.TotalAmount, 0) = 0 THEN NULL ELSE ISNULL(pip.TotalAmount, 0) END AS PrevAmountBilled,
			(ISNULL(pip.TotalAmount, 0) + (CASE WHEN il.LineType = 1 AND ISNULL(il.TotalAmount, 0) = 0 THEN CASE WHEN il.LineType = 1 THEN NULL ELSE 0 END ELSE il.TotalAmount * (@PercentageSplit/100) END)) AS TotalAmountBilled,
			CASE WHEN il.LineType = 1 THEN NULL ELSE ISNULL(pit.TotalAmount, 0) END AS PrevAmountBilledTask,
			CASE WHEN il.LineType = 1 THEN NULL ELSE ISNULL(pit.TotalAmount, 0) + (il.TotalAmount * (@PercentageSplit/100)) END AS TotalAmountBilledTask,
			CASE WHEN il.LineType = 1 THEN NULL ELSE ISNULL(bt.OriginalBudgetAmount, 0) END AS OriginalBudgetAmountTask,
			CASE WHEN il.LineType = 1 THEN NULL ELSE ISNULL(bt.ApprovedCOAmount, 0) END AS ApprovedCOAmountTask,
			CASE WHEN il.LineType = 1 THEN NULL ELSE ISNULL(bt.CurrentBudgetAmount, 0) END AS TaskBudgetAmount,
			CASE WHEN il.LineType = 1 THEN NULL ELSE ISNULL(bt.RemainingAmount, 0) END AS RemainingAmountTask,
			ISNULL(bt.CurrentExpenseAmount, 0) AS TaskExpenseAmount, --Not currently used
			ISNULL(bt.CurrentLaborAmount, 0) AS TaskLaborAmount, --Not currently used
			ISNULL(ie.Net, 0) AS NetExpenseAmount,
			cfd.*,
			cfr.*
		FROM
			tInvoiceLine il (nolock)
			LEFT JOIN (SELECT InvoiceLineKey, SUM(Amount) AS ExpenseAmount FROM tInvoiceSummary (nolock) WHERE Entity = ''tItem'' GROUP BY InvoiceLineKey) ise
				ON il.InvoiceLineKey = ise.InvoiceLineKey
			LEFT JOIN (SELECT InvoiceLineKey, SUM(Amount) AS LaborAmount FROM tInvoiceSummary (nolock) WHERE Entity = ''tService'' GROUP BY InvoiceLineKey) isl
				ON il.InvoiceLineKey = isl.InvoiceLineKey			
			LEFT JOIN tProject pl (nolock)
				ON il.ProjectKey = pl.ProjectKey
			LEFT JOIN vUserName am (nolock)
				ON pl.AccountManager = am.UserKey
			LEFT JOIN vUserName pm (nolock)
				ON pl.ProjectManager = pm.UserKey
			LEFT JOIN tTask t (nolock)
				ON il.TaskKey = t.TaskKey
			LEFT JOIN tClientDivision cd (nolock)
				ON pl.ClientDivisionKey = cd.ClientDivisionKey
			LEFT JOIN tClientProduct cp (nolock)
				ON pl.ClientProductKey = cp.ClientProductKey
			LEFT JOIN tRetainer rtn (nolock)
				ON il.RetainerKey = rtn.RetainerKey
			LEFT JOIN @tPreviousInvoiceProjects pip
				ON il.ProjectKey = pip.ProjectKey
			LEFT JOIN @tPreviousInvoiceTasks pit
				ON il.TaskKey = pit.TaskKey
			LEFT JOIN #cfProjectLine cfd (nolock)
				ON pl.CustomFieldKey = cfd.CustomFieldKey
			LEFT JOIN #cfRetainer cfr (nolock)
				ON rtn.CustomFieldKey = cfr.RetainerCustomFieldKey
			LEFT JOIN @tBudgetTask bt
				ON il.TaskKey = bt.TaskKey
			LEFT JOIN (SELECT SUM(Net) AS Net, InvoiceLineKey FROM vInvoiceExpenses GROUP BY InvoiceLineKey) ie
				ON il.InvoiceLineKey = ie.InvoiceLineKey
			LEFT JOIN #lines l ON il.InvoiceLineKey = l.InvoiceLineKey
		WHERE
			il.InvoiceKey = @ParentInvoiceKey
	) lines ON header.ParentInvoiceKey = lines.LineInvoiceKey
	LEFT JOIN #cfProjectHeader cfp (nolock)
		ON header.ProjectCustomFieldKey = cfp.CustomFieldKey
	LEFT JOIN #cfCampaign cfc (nolock)
		ON header.CampaignCustomFieldKey = cfc.CustomFieldKey
	LEFT JOIN #cfClient clfc (nolock)
		ON header.ClientCustomFieldKey = clfc.ClientCustomFieldKey
ORDER BY
	InvoiceOrder

--Other sales taxes
DECLARE @TaxAmtPaid AS money
SELECT @TaxAmtPaid = i.SalesTaxAmount - @TaxRemaining
FROM tInvoice i
WHERE InvoiceKey = @InvoiceKey

SELECT
	st.SalesTaxKey,
	it.InvoiceLineKey,
	st.SalesTaxName AS OtherSalesTaxName,
	st.SalesTaxID AS OtherSalesTaxID,
	st.TaxRate AS OtherTaxRate,
	st.Description AS OtherSalesTaxDescription,
	st.PiggyBackTax AS OtherPiggyBackTax,
	it.SalesTaxAmount AS OtherSalesTaxAmount,
	CASE ISNULL(i.SalesTaxAmount, 0) WHEN 0 THEN 0 ELSE ROUND(it.SalesTaxAmount / i.SalesTaxAmount * @TaxAmtPaid,2) END AS TaxPaid,
	CASE ISNULL(i.InvoiceTotalAmount, 0) WHEN 0 THEN 0 ELSE ROUND(it.SalesTaxAmount - (it.SalesTaxAmount * (i.AmountReceived / i.InvoiceTotalAmount)), 2) END AS TaxRemaining,
	it.Type
FROM
	tInvoiceTax it (nolock)
	INNER JOIN tSalesTax st (nolock)
		ON it.SalesTaxKey = st.SalesTaxKey
	INNER JOIN tInvoice i (nolock)
	    ON it.InvoiceKey = i.InvoiceKey
WHERE
	it.InvoiceKey = @InvoiceKey	
ORDER BY
	it.Type

SELECT
	''tItem'' AS Entity,
	bi.ItemKey AS EntityKey,
	bi.WorkTypeKey,
	i.ItemName AS ServiceItemName,
	bi.OriginalQty,
	bi.OriginalNetAmount,
	bi.OriginalGrossAmount,
	bi.ApprovedCOQty,
	bi.ApprovedCONet,
	bi.ApprovedCOGross,
	bi.CurrentQty,
	bi.CurrentNetAmount,
	ISNULL(bi.CurrentGrossAmount, 0.00) AS CurrentExpBudget,
	0.00 AS CurrentLaborBudget,
	ISNULL(bi.CurrentGrossAmount, 0.00) AS CurrentTotalBudget,
	ISNULL(bi.PreviousAmountBilled, 0.00) AS ServiceItemPreviousBilled,
	ISNULL(bi.CurrentBilled, 0.00) AS ServiceItemCurrentBilling,
	ISNULL(bi.PreviousAmountBilled, 0.00) + ISNULL(bi.CurrentBilled, 0.00) AS ServiceItemTotalBilled,
	ISNULL(bi.RemainingAmount, 0.00) AS RemainingAmount,
	lb.DisplayOption,
	lb.LayoutLevel,
	lb.LayoutOrder
FROM
	@tBudgetItem bi
	INNER JOIN tItem i (nolock) ON bi.ItemKey = i.ItemKey
	LEFT JOIN tLayoutBilling lb (nolock) ON bi.ItemKey = lb.EntityKey AND lb.Entity = ''tItem'' AND lb.LayoutKey = @LayoutKey
	
UNION

SELECT
	''tService'' AS Entity,
	bs.ServiceKey AS EntityKey,
	bs.WorkTypeKey,
	s.Description AS ServiceItemName,
	bs.OriginalHours,
	bs.OriginalLaborNet,
	bs.OriginalLaborGross,
	bs.ApprovedCOHours,
	bs.ApprovedCOLaborNet,
	bs.ApprovedCOLaborGross,
	bs.CurrentHours,
	bs.CurrentLaborNet,
	0.00,
	ISNULL(bs.CurrentLaborGross, 0.00),
	ISNULL(bs.CurrentLaborGross, 0.00),
	ISNULL(bs.PreviousAmountBilled, 0.00),
	ISNULL(bs.CurrentBilled, 0.00),
	ISNULL(bs.PreviousAmountBilled, 0.00) + ISNULL(bs.CurrentBilled, 0.00),
	ISNULL(bs.RemainingAmount, 0.00),
	lb.DisplayOption,
	lb.LayoutLevel,
	lb.LayoutOrder
FROM
	@tBudgetService bs
	INNER JOIN tService s (nolock) ON bs.ServiceKey = s.ServiceKey
	LEFT JOIN tLayoutBilling lb (nolock) ON bs.ServiceKey = lb.EntityKey AND lb.Entity = ''tService'' AND lb.LayoutKey = @LayoutKey

UNION

SELECT
	''tWorkType'' AS Entity,
	wt.WorkTypeKey AS EntityKey,
	0,
	wt.WorkTypeName,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	NULL,
	lb.DisplayOption,
	lb.LayoutLevel,
	lb.LayoutOrder
FROM
	tLayoutBilling lb (nolock)
	INNER JOIN tWorkType wt (nolock) ON lb.EntityKey = wt.WorkTypeKey AND lb.Entity = ''tWorkType'' AND lb.LayoutKey = @LayoutKey
WHERE wt.WorkTypeKey IN (
	SELECT WorkTypeKey
	FROM @tBudgetItem
	UNION
	SELECT WorkTypeKey
	FROM @tBudgetService
)

ORDER BY LayoutOrder
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceLineGetOrdersRollup]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceLineGetOrdersRollup]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptInvoiceLineGetOrdersRollup]
	(
		@InvoiceLineKey int,
		@Type smallint,
		@Percentage decimal(24,4)
	)

AS --Encrypt

/*  Who When        Rel     What
||  GHL 04/12/2006  8.3     Changed ISNULL(cm.StationID, c.VendorID) to cm.StationID
||                          United Concepts complained that it was showing wrong Publication or Station
||                          Also causing problems with the report''s groups and sorts
||  GHL 05/19/2006  8.4     Added Vendor info since Nerland did not like the change made in 83 
||  GHL 05/07/2008  8.510   (21995) Added Item as rollup
||  MFT 05/25/2010 10.5.3.0 Split out orders w/ vouchers into seperate unioned query
||  GWG 05/28/2010 10.5.3.0 Fixed query
||  MCM 06/10/2026 26.06.19 (730585) Added DetailOrderDate/DetailOrderEndDate to final SELECT statement required by VB report
*/
declare @Rollup INT
		,@Group1 INT
		,@Group2 INT
		,@Group3 INT
		,@Group4 INT
		,@Group5 INT

DECLARE @RollupGroupBy AS VARCHAR(1000)		-- For Group Bys
		,@Rollup1Where AS VARCHAR(1000)		-- For Where Clauses
		,@Rollup2Where AS VARCHAR(1000)
		,@Rollup3Where AS VARCHAR(1000)
		,@Rollup4Where AS VARCHAR(1000)
		,@Rollup5Where AS VARCHAR(1000)

DECLARE @SQL AS VARCHAR(1000)

IF @Type = 1
	-- IO
	SELECT @Rollup = IOHideDetails
			,@Group1 = IOGroup1 
			,@Group2 = IOGroup2
			,@Group3 = IOGroup3
			,@Group4 = IOGroup4
			,@Group5 = IOGroup5
	FROM    tInvoiceLine il (NOLOCK)
			INNER JOIN tInvoice i (NOLOCK) ON il.InvoiceKey = i.InvoiceKey
			LEFT OUTER JOIN tInvoiceTemplate it (NOLOCK) ON i.InvoiceTemplateKey = it.InvoiceTemplateKey
	WHERE   il.InvoiceLineKey = @InvoiceLineKey
ELSE
	-- BC					
	SELECT @Rollup = BCHideDetails 
			,@Group1 = BCGroup1 
			,@Group2 = BCGroup2
			,@Group3 = BCGroup3
			,@Group4 = BCGroup4
			,@Group5 = BCGroup5
	FROM    tInvoiceLine il (NOLOCK)
			INNER JOIN tInvoice i (NOLOCK) ON il.InvoiceKey = i.InvoiceKey
			LEFT OUTER JOIN tInvoiceTemplate it (NOLOCK) ON i.InvoiceTemplateKey = it.InvoiceTemplateKey
	WHERE   il.InvoiceLineKey = @InvoiceLineKey
	
SELECT @Rollup = ISNULL(@Rollup, 0)
		,@Group1 = ISNULL(@Group1, 0) 
		,@Group2 = ISNULL(@Group2, 0)
		,@Group3 = ISNULL(@Group3, 0)
		,@Group4 = ISNULL(@Group4, 0)
		,@Group5 = ISNULL(@Group5, 0)
				
IF @Rollup = 0
	RETURN 1		
	
declare @IOClientLink smallint
declare @BCClientLink smallint
declare @CompanyKey int

select @CompanyKey = co.CompanyKey
  from tCompany co (nolock) inner join tInvoice inv (nolock) on co.CompanyKey = inv.CompanyKey
       inner join tInvoiceLine invl (nolock) on inv.InvoiceKey = invl.InvoiceKey
 where invl.InvoiceLineKey = @InvoiceLineKey   
       
select @BCClientLink = isnull(BCClientLink,1),
       @IOClientLink = isnull(IOClientLink,1)
  from tPreference (nolock)
 where CompanyKey = @CompanyKey

Select @Percentage = @Percentage / 100

-- Temp table for the invoice lines
CREATE TABLE #IL (  pQuantity DECIMAL(24,4) NULL, pAmountBilled MONEY NULL
					,ClientDivision VARCHAR(100) NULL, ClientDivisionKey INT NULL 
					,ClientProduct VARCHAR(100) NULL, ClientProductKey INT NULL 
					,EstimateName VARCHAR(100) NULL, MediaEstimateKey INT NULL
					,MarketName VARCHAR(100) NULL, MediaMarketKey INT NULL
					,StationName VARCHAR(250) NULL, CompanyMediaKey INT NULL
					,VendorName VARCHAR(250) NULL, VendorKey INT NULL
					,ItemName VARCHAR(250) NULL, ItemKey INT NULL
					,PODate SMALLDATETIME NULL, PurchaseOrderNumber VARCHAR(30) NULL
					,LineNumber INT NULL
					)
					
-- Temp table for the rollups
CREATE TABLE #Rollup ( pQuantity DECIMAL(24,4) NULL, pAmountBilled MONEY NULL
					,ClientDivision VARCHAR(100) NULL, ClientDivisionKey INT NULL 
					,ClientProduct VARCHAR(100) NULL, ClientProductKey INT NULL 
					,EstimateName VARCHAR(100) NULL, MediaEstimateKey INT NULL
					,MarketName VARCHAR(100) NULL, MediaMarketKey INT NULL
					,StationName VARCHAR(250) NULL, CompanyMediaKey INT NULL
					,VendorName VARCHAR(250) NULL, VendorKey INT NULL
					,ItemName VARCHAR(250) NULL, ItemKey INT NULL
					,qRollup1 DECIMAL(24,4) NULL, aRollup1 MONEY NULL
					,qRollup2 DECIMAL(24,4) NULL, aRollup2 MONEY NULL
					,qRollup3 DECIMAL(24,4) NULL, aRollup3 MONEY NULL
					,qRollup4 DECIMAL(24,4) NULL, aRollup4 MONEY NULL
					,qRollup5 DECIMAL(24,4) NULL, aRollup5 MONEY NULL					
					)
					
					
if (@Type = 1 and @IOClientLink = 2) or (@Type = 2 and @BCClientLink = 2) -- link to division & product via estimate
BEGIN
	INSERT #IL
	Select
		ISNULL(pod.Quantity * @Percentage, 0) as pQuantity,
		ISNULL(pod.AmountBilled * @Percentage, 0) as pAmountBilled,
		left(cd.DivisionName,100) as ClientDivision, cd.ClientDivisionKey,
		left(cp.ProductName,100) as ClientProduct, cp.ClientProductKey,
		left(me.EstimateName,100) as EstimateName, po.MediaEstimateKey,
		left(mm.MarketName,100) as MarketName, mm.MediaMarketKey,
		cm.Name as StationName, cm.CompanyMediaKey,
		c.CompanyName as VendorName, c.CompanyKey,
		i.ItemName As ItemName, i.ItemKey,
		po.PODate, po.PurchaseOrderNumber,
		pod.LineNumber
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tClientProduct cp (nolock) on me.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on me.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	Where
		pod.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type
		and (pod.Quantity <> 0 or pod.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled 
	
	INSERT #IL
	Select
		ISNULL(vd.Quantity * @Percentage, 0) as pQuantity,
		ISNULL(vd.AmountBilled * @Percentage, 0) as pAmountBilled,
		left(cd.DivisionName,100) as ClientDivision, cd.ClientDivisionKey,
		left(cp.ProductName,100) as ClientProduct, cp.ClientProductKey,
		left(me.EstimateName,100) as EstimateName, po.MediaEstimateKey,
		left(mm.MarketName,100) as MarketName, mm.MediaMarketKey,
		cm.Name as StationName, cm.CompanyMediaKey,
		c.CompanyName as VendorName, c.CompanyKey,
		i.ItemName As ItemName, i.ItemKey,
		po.PODate, po.PurchaseOrderNumber,
		pod.LineNumber
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		inner join tVoucherDetail vd (nolock) on pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tClientProduct cp (nolock) on me.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on me.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	Where
		vd.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type
		and (vd.Quantity <> 0 or vd.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled 
	
	Order By cm.Name, po.PODate, po.PurchaseOrderNumber, pod.LineNumber
END
else  -- link to division & product via project
BEGIN
	INSERT #IL
	Select
		ISNULL(pod.Quantity * @Percentage, 0) as pQuantity,
		ISNULL(pod.AmountBilled * @Percentage, 0) as pAmountBilled,
		left(cd.DivisionName,100) as ClientDivision, cd.ClientDivisionKey,
		left(cp.ProductName,100) as ClientProduct,cp.ClientProductKey,
		left(me.EstimateName,100) as EstimateName,po.MediaEstimateKey,
		left(mm.MarketName,100) as MarketName,mm.MediaMarketKey,
		cm.Name as StationName, cm.CompanyMediaKey,
		c.CompanyName as VendorName, c.CompanyKey,
		i.ItemName As ItemName, i.ItemKey,
		po.PODate, po.PurchaseOrderNumber,
		pod.LineNumber
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tProject pr (nolock) on pod.ProjectKey = pr.ProjectKey
		left outer join tClientProduct cp (nolock) on pr.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on pr.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	Where
		pod.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type
		and (pod.Quantity <> 0 or pod.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled
	
	INSERT #IL
	Select
		ISNULL(vd.Quantity * @Percentage, 0) as pQuantity,
		ISNULL(vd.AmountBilled * @Percentage, 0) as pAmountBilled,
		left(cd.DivisionName,100) as ClientDivision, cd.ClientDivisionKey,
		left(cp.ProductName,100) as ClientProduct,cp.ClientProductKey,
		left(me.EstimateName,100) as EstimateName,po.MediaEstimateKey,
		left(mm.MarketName,100) as MarketName,mm.MediaMarketKey,
		cm.Name as StationName, cm.CompanyMediaKey,
		c.CompanyName as VendorName, c.CompanyKey,
		i.ItemName As ItemName, i.ItemKey,
		po.PODate, po.PurchaseOrderNumber,
		pod.LineNumber
	From
		tPurchaseOrderDetail pod (nolock) 
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		inner join tCompany c (nolock) on po.VendorKey = c.CompanyKey
		inner join tVoucherDetail vd (nolock) on pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
		left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
		left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
		left outer join tProject pr (nolock) on pod.ProjectKey = pr.ProjectKey
		left outer join tClientProduct cp (nolock) on pr.ClientProductKey = cp.ClientProductKey
		left outer join tClientDivision cd (nolock) on pr.ClientDivisionKey = cd.ClientDivisionKey
		left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	Where
		vd.InvoiceLineKey = @InvoiceLineKey and
		po.POKind = @Type
		and (vd.Quantity <> 0 or vd.AmountBilled <> 0) -- suppress lines with zero quantity and zero AmountBilled
	
	Order By cm.Name, po.PODate, po.PurchaseOrderNumber, pod.LineNumber
END

--SELECT * FROM #IL

SELECT @RollupGroupBy = ''0'' -- Just a marker for commas
IF @Rollup = 1
BEGIN
	IF @Group1 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup1Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group1 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup1Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group1 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup1Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group1 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup1Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''		
	IF @Group1 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup1Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group1 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup1Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group1 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup1Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''
		
END
IF @Rollup = 1
BEGIN
	IF @Group2 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup2Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group2 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup2Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group2 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup2Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group2 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup2Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''	
	IF @Group2 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup2Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group2 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup2Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group2 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup2Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END
IF @Rollup = 1
BEGIN
	IF @Group3 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup3Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group3 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup3Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group3 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup3Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group3 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup3Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''
	IF @Group3 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup3Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group3 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup3Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group3 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup3Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END
IF @Rollup = 1
BEGIN
	IF @Group4 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup4Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group4 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup4Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group4 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup4Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group4 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup4Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''
	IF @Group4 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup4Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group4 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup4Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group4 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup4Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END
IF @Rollup = 1
BEGIN
	IF @Group5 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup5Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group5 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup5Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group5 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup5Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group5 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup5Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''
	IF @Group5 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup5Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group5 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup5Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group5 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup5Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END

-- This way we can use as many ANDs in where clauses
SELECT @Rollup1Where = ISNULL(@Rollup1Where, '' 1 = 1 '')
		,@Rollup2Where = ISNULL(@Rollup2Where, '' 1 = 1 '')
		,@Rollup3Where = ISNULL(@Rollup3Where, '' 1 = 1 '')
		,@Rollup4Where = ISNULL(@Rollup4Where, '' 1 = 1 '')
		,@Rollup5Where = ISNULL(@Rollup5Where, '' 1 = 1 '')
				
SELECT @RollupGroupBy = REPLACE (@RollupGroupBy, ''0,'', '''') -- Remove marker
--SELECT @RollupGroupBy

SELECT @SQL = ''INSERT #Rollup ('' + @RollupGroupBy + '',pQuantity, pAmountBilled)''
SELECT @SQL = @SQL + '' SELECT '' + @RollupGroupBy + '', SUM(pQuantity), SUM(pAmountBilled) ''
SELECT @SQL = @SQL + '' FROM #IL ''
SELECT @SQL = @SQL + '' GROUP BY '' + @RollupGroupBy

--SELECT @SQL
EXEC (@SQL)

IF @Group1 > 0
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup1 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' ) ''	
	--SELECT @SQL
	EXEC (@SQL)
	
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup1 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' ) ''	
	EXEC (@SQL)
	
END

IF @Group2 > 0 
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup2 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)

	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup2 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)

END

IF @Group3 > 0
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup3 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)
	
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup3 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)
	
END


IF @Group4 > 0
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup4 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)

	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup4 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)

END

IF @Group5 > 0 
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup5 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup5Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)
	
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup5 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup5Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)	
END


-- DetailOrderDate and DetailOrderEndDate are not meaningful in rollup mode but are expected by VB report
SELECT #Rollup.*, CAST(NULL AS SMALLDATETIME) as DetailOrderDate, CAST(NULL AS SMALLDATETIME) as DetailOrderEndDate
FROM #Rollup

RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceLineGetCosts]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceLineGetCosts]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptInvoiceLineGetCosts]
(
	 @InvoiceLineKey int
	,@InvoiceKey int = null
)

as --Encrypt

/*
|| When     Who Rel    What
|| 05/24/06 GHL 8.3    Added field BillableCostOnLine to take in account the Prebill BillAt
||                     McClain reported that PO with BillAt=AtNet should bill at TotalCost not BillableCost  
|| 07/09/07 GHL 8.5    Added restriction on ER
|| 07/31/07 GHL 8.5    Removed ref to expense type
|| 08/02/07 GHL 8.5    Pulling now transactions only linked to the line (not all transactions for project)
|| 08/07/07 GHL 8.5    Added ProjectKey to facilitate project rollup in UI
|| 02/19/08 GHL 8.5    (21165) Added Expense receipt info for VI in Comments section now
|| 05/04/09 GHL 10.024 (52605) Getting now BillingComments from transaction BilledComment
||                    transaction BilledComment should be set when we generate the invoice 
||                    from a billing WS tBillingDetail.EditComents 
|| 09/15/09 GWG 10.510 Modified the transaction date for orders to pull the insertion date and start date for orders.
|| 04/30/10 GHL 10.522 Added InvoiceKey param to pull records for whole invoice
|| 11/16/10 GHL 10.538 Changed tMiscCost inner join tUser to left outer join because some misc costs have null EnteredBy 
|| 04/19/12 GHL 10.555 (140727) Added BilledItem info to edit on flex client edit screen
|| 06/01/12 GHL 10.556 Modified BillingComments like in sptInvoiceLineExpenseGetAll for consistency
|| 01/04/13 GHL 10.563 Added Order # for Vendor invoices to help debugging + added VI label to separate PO and VI #s (6/27/13)
|| 11/11/13 MFT 10.574 (196005) Altered VI label for clarity
|| 12/16/13 GHL 10.575 (199849) Altered VI label for even better clarity
|| 3/10/14  GHL 10.578 Change inner join with ERs to an outer join for companies that do not use items
|| 10/31/14 GHL 10.585 Added Worksheet ID for the new media screens
|| 05/19/16 GHL 10.604 Separated Project Number and Name for wjapp
|| 04/03/19 AMP 19.050 (437595) Added Vendor Name to the Expenses detail screen 
|| 06/12/19 MCM 19.070 (464959) Added Purchased from to the Expenses detail screen when it was bought with a credit card
|| 06/21/23 MAS 23.07.16 Removed old media references, tMediaWorksheet
|| 09/28/23 GAR 23.11.19 (DEV2605) Added ClientKey so we can do Avalara Tax Code hierarchy.
|| 09/05/24 AMP 24.10.20 (681249) Added ''Sales Account'' when drilling down on the Labor and Expense details on a client invoice line 
|| 03/02/26 RLB 26.04.19 (722093) added Variance Gross - Net
|| 03/11/26 AMP 26.05.17 (723108) Added the ParentKeyFld to be used as the link to the source transaction
|| 05/26/26 RLS 26.06.14 (729061) Added BilledVariance for invoice expense lines
*/
	
Declare @CompanyKey int

If isnull(@InvoiceKey, 0) = 0 
	Select @CompanyKey = CompanyKey 
	from   tInvoice i (nolock) 
	inner  join tInvoiceLine il (nolock) on i.InvoiceKey = il.InvoiceKey 
	where  il.InvoiceLineKey = @InvoiceLineKey
else
	Select @CompanyKey = CompanyKey 
	from   tInvoice (nolock)
	Where  InvoiceKey = @InvoiceKey

If isnull(@InvoiceKey, 0) = 0 
	-- pull costs for a single invoice line

	Select
		er.InvoiceLineKey
		,er.ProjectKey
		,er.TaskKey
		,''ER'' as Type
		,er.ExpenseReceiptKey as KeyFld
		,er.ExpenseEnvelopeKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,er.ActualQty as Quantity
		,er.ActualUnitCost as UnitCost
		,er.ActualCost as TotalCost
		,er.BillableCost as BillableCost
		,er.BillableCost as BillableCostOnLine
		,er.BillableCost - er.ActualCost as Variance
		,isnull(er.AmountBilled, 0) - isnull(er.ActualCost, 0) as BilledVariance
		,er.AmountBilled
		,er.Description as Description
		,er.ExpenseDate as TransactionDate
		,u.FirstName + '' '' + u.LastName as SourceName
		,'''' as ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,NULL AS Comments
		,CAST(ISNULL(er.BilledComment, er.Comments) as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(er.BilledItem, er.ItemKey) as BilledItem
		,case when er.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when er.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID  
		,NULL as VendorName
		,NULL as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tExpenseReceipt er (nolock)
		inner join tUser u (nolock) on er.UserKey = u.UserKey
		left outer join tItem i (nolock) on er.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on er.BilledItem = bi.ItemKey
		left outer join tProject p (nolock) on er.ProjectKey = p.ProjectKey
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		er.InvoiceLineKey = @InvoiceLineKey 

	Union ALL
	
	Select
		mc.InvoiceLineKey
		,mc.ProjectKey
		,mc.TaskKey
		,''MC'' as Type
		,mc.MiscCostKey as KeyFld
		,mc.MiscCostKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,mc.Quantity
		,mc.UnitCost
		,mc.TotalCost
		,mc.BillableCost
		,mc.BillableCost as BillableCostOnLine
		,mc.BillableCost - mc.TotalCost as Variance
		,isnull(mc.AmountBilled, 0) - isnull(mc.TotalCost, 0) as BilledVariance
		,mc.AmountBilled
		,mc.ShortDescription as Description
		,mc.ExpenseDate as TransactionDate
		,u.FirstName + '' '' + u.LastName as SourceName
		,'''' as ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,NULL AS Comments
		,CAST(ISNULL(mc.BilledComment, mc.LongDescription) as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(mc.BilledItem, mc.ItemKey) as BilledItem
		,case when mc.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when mc.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID
		,NULL as VendorName
		,NULL as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tMiscCost mc (nolock)
		left outer join tUser u (nolock) on mc.EnteredByKey = u.UserKey
		left outer join tItem i (nolock) on mc.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on mc.BilledItem = bi.ItemKey
		left outer join tProject p (nolock) on mc.ProjectKey = p.ProjectKey
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		mc.InvoiceLineKey = @InvoiceLineKey

	Union ALL
	
	Select
		vd.InvoiceLineKey
		,vd.ProjectKey
		,vd.TaskKey
		,''VO'' as Type
		,vd.VoucherDetailKey as KeyFld
		,vd.VoucherKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,vd.Quantity
		,vd.UnitCost
		,vd.TotalCost
		,vd.BillableCost
		,vd.BillableCost as BillableCostOnLine
		,vd.BillableCost - vd.TotalCost as Variance
		,isnull(vd.AmountBilled, 0) - isnull(vd.TotalCost, 0) as BilledVariance
		,vd.AmountBilled
		,vd.ShortDescription as Description
		,CASE WHEN er.ExpenseReceiptKey IS NULL THEN  v.InvoiceDate ELSE er.ExpenseDate END as TransactionDate
		,case when isnull(vd.PurchaseOrderDetailKey, 0) > 0 
			then 
				case when po.POKind = 0 then ''PO: '' + po.PurchaseOrderNumber + '' on VI: '' + v.InvoiceNumber 
				     when po.POKind = 1 then isnull(''IO: '' + po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
				     when po.POKind = 2 then isnull(''BO: '' + po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
 			         else isnull(po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
				end
			else ''VI: '' + v.InvoiceNumber
			end as SourceName
		
		,'''' as ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,CASE WHEN er.ExpenseReceiptKey IS NULL THEN c.CompanyName
		ELSE	'' -- Converted from expense receipt -- Person: '' + u.FirstName + '' '' + u.LastName  + '' Report: '' + rtrim(ee.EnvelopeNumber) + '' '' + er.Description
		END AS Comments
		,CAST(vd.BilledComment as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(vd.BilledItem, vd.ItemKey) as BilledItem
		,case when vd.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when vd.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID  
		,c.CompanyName as VendorName
		,ISNULL(v.BoughtFrom, '''') as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tVoucherDetail vd (nolock)
		inner join tVoucher v (nolock) on vd.VoucherKey = v.VoucherKey
		inner join tCompany c (nolock) on v.VendorKey = c.CompanyKey
		left outer join tItem i (nolock) on vd.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on vd.BilledItem = bi.ItemKey
		left outer join tProject p (nolock) on vd.ProjectKey = p.ProjectKey
		left outer join tExpenseReceipt er (nolock) on vd.VoucherDetailKey = er.VoucherDetailKey
		left outer join tExpenseEnvelope ee (nolock) on er.ExpenseEnvelopeKey = ee.ExpenseEnvelopeKey
		left outer join tUser u (nolock) on ee.UserKey = u.UserKey
		left outer join tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
		left outer join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey 
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 

	Where
		vd.InvoiceLineKey = @InvoiceLineKey
	
Union ALL
	
	Select
		pod.InvoiceLineKey
		,pod.ProjectKey
		,pod.TaskKey
		,''PO'' as Type
		,pod.PurchaseOrderDetailKey as KeyFld
		,pod.PurchaseOrderKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,pod.Quantity
		,pod.UnitCost
		,pod.TotalCost 
		,pod.BillableCost
		,CASE 
			WHEN po.BillAt = 0 THEN pod.BillableCost -- At Gross
			WHEN po.BillAt = 1 THEN pod.PTotalCost -- At Net
			WHEN po.BillAt = 2 THEN isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,0) -- At Commission
		END AS BillableCostOnLine
		,pod.BillableCost - pod.TotalCost as Variance
		,isnull(pod.AmountBilled, 0) - isnull(pod.TotalCost, 0) as BilledVariance
		,pod.AmountBilled
		,pod.ShortDescription as Description
		,(Case po.POKind 
			When 0 then po.PODate
			When 1 then pod.DetailOrderDate 
			When 2 then pod.DetailOrderDate end)
			as TransactionDate
		,(Case po.POKind 
			When 0 then ''PO: '' + po.PurchaseOrderNumber 
			When 1 then isnull(''IO: '' + po.PurchaseOrderNumber, '''')
			When 2 then isnull(''BO: '' + po.PurchaseOrderNumber, '''')
			Else isnull(po.PurchaseOrderNumber, '''')
			end)
			as SourceName
		,mrr.ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,NULL AS Comments
		,CAST(ISNULL(pod.BilledComment, pod.LongDescription) as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(pod.BilledItem, pod.ItemKey) as BilledItem
		,case when pod.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when pod.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID 
		,c.CompanyName as VendorName 
		,NULL as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tPurchaseOrderDetail pod (nolock)
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		left outer join tCompany c (nolock) on c.CompanyKey = po.VendorKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on pod.BilledItem = bi.ItemKey
		left outer join tMediaRevisionReason mrr (nolock) on pod.MediaRevisionReasonKey = mrr.MediaRevisionReasonKey
		left outer join tProject p (nolock) on pod.ProjectKey = p.ProjectKey	
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		pod.InvoiceLineKey = @InvoiceLineKey AND
		po.CompanyKey = @CompanyKey

else
	-- pull costs for the whole invoice

	Select
		er.InvoiceLineKey
		,er.ProjectKey
		,er.TaskKey
		,''ER'' as Type
		,er.ExpenseReceiptKey as KeyFld
		,er.ExpenseEnvelopeKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,er.ActualQty as Quantity
		,er.ActualUnitCost as UnitCost
		,er.ActualCost as TotalCost
		,er.BillableCost as BillableCost
		,er.BillableCost as BillableCostOnLine
		,er.BillableCost - er.ActualCost as Variance
		,isnull(er.AmountBilled, 0) - isnull(er.ActualCost, 0) as BilledVariance
		,er.AmountBilled
		,er.Description as Description
		,er.ExpenseDate as TransactionDate
		,u.FirstName + '' '' + u.LastName as SourceName
		,'''' as ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,NULL AS Comments
		,CAST(ISNULL(er.BilledComment, er.Comments) as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(er.BilledItem, er.ItemKey) as BilledItem
		,case when er.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when er.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID 
		,NULL as VendorName 
		,NULL as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tExpenseReceipt er (nolock)
		inner join tInvoiceLine il (nolock) on er.InvoiceLineKey = il.InvoiceLineKey
		inner join tUser u (nolock) on er.UserKey = u.UserKey
		left outer join tItem i (nolock) on er.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on er.BilledItem = bi.ItemKey
		left outer join tProject p (nolock) on er.ProjectKey = p.ProjectKey
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		il.InvoiceKey = @InvoiceKey 

	Union ALL
	
	Select
		mc.InvoiceLineKey
		,mc.ProjectKey
		,mc.TaskKey
		,''MC'' as Type
		,mc.MiscCostKey as KeyFld
		,mc.MiscCostKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,mc.Quantity
		,mc.UnitCost
		,mc.TotalCost
		,mc.BillableCost
		,mc.BillableCost as BillableCostOnLine
		,mc.BillableCost - mc.TotalCost as Variance
		,isnull(mc.AmountBilled, 0) - isnull(mc.TotalCost, 0) as BilledVariance
		,mc.AmountBilled
		,mc.ShortDescription as Description
		,mc.ExpenseDate as TransactionDate
		,u.FirstName + '' '' + u.LastName as SourceName
		,'''' as ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,NULL AS Comments
		,CAST(ISNULL(mc.BilledComment, mc.LongDescription) as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(mc.BilledItem, mc.ItemKey) as BilledItem
		,case when mc.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when mc.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID  
		,NULL as VendorName
		,NULL as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tMiscCost mc (nolock)
		inner join tInvoiceLine il (nolock) on mc.InvoiceLineKey = il.InvoiceLineKey
		left outer join tUser u (nolock) on mc.EnteredByKey = u.UserKey
		left outer join tItem i (nolock) on mc.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on mc.BilledItem = bi.ItemKey
		left outer join tProject p (nolock) on mc.ProjectKey = p.ProjectKey
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		il.InvoiceKey = @InvoiceKey

	Union ALL
	
	Select
		vd.InvoiceLineKey
		,vd.ProjectKey
		,vd.TaskKey
		,''VO'' as Type
		,vd.VoucherDetailKey as KeyFld
		,vd.VoucherKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,vd.Quantity
		,vd.UnitCost
		,vd.TotalCost
		,vd.BillableCost
		,vd.BillableCost as BillableCostOnLine
		,vd.BillableCost - vd.TotalCost as Variance
		,isnull(vd.AmountBilled, 0) - isnull(vd.TotalCost, 0) as BilledVariance
		,vd.AmountBilled
		,vd.ShortDescription as Description
		,CASE WHEN er.ExpenseReceiptKey IS NULL THEN  v.InvoiceDate ELSE er.ExpenseDate END as TransactionDate
		,case when isnull(vd.PurchaseOrderDetailKey, 0) > 0 
			then 
				case when po.POKind = 0 then isnull(''PO: '' + po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
				     when po.POKind = 1 then isnull(''IO: '' + po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
				     when po.POKind = 2 then isnull(''BO: '' + po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
			         else isnull(po.PurchaseOrderNumber, '''') + '' on VI: '' + v.InvoiceNumber
				end
			else ''VI: '' + v.InvoiceNumber
			end as SourceName
		
		,'''' as ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,CASE WHEN er.ExpenseReceiptKey IS NULL THEN c.CompanyName
		ELSE	'' -- Converted from expense receipt -- Person: '' + u.FirstName + '' '' + u.LastName  + '' Report: '' + rtrim(ee.EnvelopeNumber) + '' '' + er.Description
		END AS Comments
		,CAST(vd.BilledComment as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(vd.BilledItem, vd.ItemKey) as BilledItem
		,case when vd.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when vd.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID  
		,c.CompanyName as VendorName
		,ISNULL(v.BoughtFrom, '''') as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tVoucherDetail vd (nolock)
		inner join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
		inner join tVoucher v (nolock) on vd.VoucherKey = v.VoucherKey
		inner join tCompany c (nolock) on v.VendorKey = c.CompanyKey
		left outer join tItem i (nolock) on vd.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on vd.BilledItem = bi.ItemKey	
		left outer join tProject p (nolock) on vd.ProjectKey = p.ProjectKey
		left outer join tExpenseReceipt er (nolock) on vd.VoucherDetailKey = er.VoucherDetailKey
		left outer join tExpenseEnvelope ee (nolock) on er.ExpenseEnvelopeKey = ee.ExpenseEnvelopeKey
		left outer join tUser u (nolock) on ee.UserKey = u.UserKey
		left outer join tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
		left outer join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey 
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		il.InvoiceKey = @InvoiceKey
	
Union ALL
	
	Select
		pod.InvoiceLineKey
		,pod.ProjectKey
		,pod.TaskKey
		,''PO'' as Type
		,pod.PurchaseOrderDetailKey as KeyFld
		,pod.PurchaseOrderKey as ParentKeyFld
		,i.ItemID
		,i.ItemName
		,pod.Quantity
		,pod.UnitCost
		,pod.TotalCost
		,pod.BillableCost
		,CASE 
			WHEN po.BillAt = 0 THEN pod.BillableCost -- At Gross
			WHEN po.BillAt = 1 THEN pod.PTotalCost -- At Net
			WHEN po.BillAt = 2 THEN isnull(pod.BillableCost,0) - isnull(pod.PTotalCost,0) -- At Commission
		END AS BillableCostOnLine
		,pod.BillableCost - pod.TotalCost as Variance
		,isnull(pod.AmountBilled, 0) - isnull(pod.TotalCost, 0) as BilledVariance
		,pod.AmountBilled
		,pod.ShortDescription as Description
		,(Case po.POKind 
			When 0 then po.PODate
			When 1 then pod.DetailOrderDate 
			When 2 then pod.DetailOrderDate end)
			as TransactionDate
		,(Case po.POKind 
			When 0 then isnull(''PO: '' + po.PurchaseOrderNumber, '''') 
			When 1 then isnull(''IO: '' + po.PurchaseOrderNumber, '''')
			When 2 then isnull(''BO: '' + po.PurchaseOrderNumber, '''')
			Else isnull(po.PurchaseOrderNumber, '''')
			end)
			as SourceName
		,mrr.ReasonID		
		,isnull(p.ProjectNumber+'' - '','''') + isnull(left(p.ProjectName, 25),'''') as ProjectFullName
		,p.ProjectNumber
		,p.ProjectName
		,NULL AS Comments
		,CAST(ISNULL(pod.BilledComment, pod.LongDescription) as VARCHAR(6000)) as BillingComments
		,p.ClientKey

		-- for flex lookup
		,isnull(pod.BilledItem, pod.ItemKey) as BilledItem
		,case when pod.BilledItem is null then i.ItemName else bi.ItemName end as BilledItemName
		,case when pod.BilledItem is null then i.ItemID else bi.ItemID end as BilledItemID  
		,c.CompanyName as VendorName
		,NULL as PurchasedFrom
		,gla.AccountNumber + '' - '' + gla.AccountName as SalesAccount
	from
		tPurchaseOrderDetail pod (nolock) 
		inner join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
		inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
		left outer join tCompany c (nolock) on c.CompanyKey = po.VendorKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		left outer join tItem bi (nolock) on pod.BilledItem = bi.ItemKey
		left outer join tMediaRevisionReason mrr (nolock) on pod.MediaRevisionReasonKey = mrr.MediaRevisionReasonKey
		left outer join tProject p (nolock) on pod.ProjectKey = p.ProjectKey
		left outer join tGLAccount gla (nolock) on i.SalesAccountKey = gla.GLAccountKey 
	Where
		il.InvoiceKey = @InvoiceKey AND
		po.CompanyKey = @CompanyKey

'
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
 */

	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
			WHERE  ProjectKey = @ProjectKey and BillingKey = @BillingKey

	END

	-- or a campaign key
	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
		AND    b.BillingMethod = 2 -- FF

		IF @BillingKey is null
			break

		SELECT @CampaignKey = CampaignKey  from tBilling (nolock) where BillingKey = @BillingKey

		UPDATE tBillingSchedule
			SET    InvoiceKey = @NewInvoiceKey
			WHERE  CampaignKey = @CampaignKey and BillingKey = @BillingKey
	END

	RETURN @NewInvoiceKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPromptInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptPromptInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptPromptInsert]
	@UserKey int,
	@CompanyKey int,
	@EntityKey int,
	@Entity varchar(50),
	@PromptText varchar(MAX),
	@PromptTokenCount int = NULL,
	@ResponseTokenCount int = NULL,
	@Provider varchar(50) = NULL,
	@ResponseText varchar(MAX) = NULL
AS --Encrypt

/*
|| When     Who Rel      What
|| 09/04/25	MAS XX.X.X.X Created
*/

	DECLARE @MonthlyCount AS INT;
	DECLARE @MonthlyPromptTokenCount AS INT;
	DECLARE @MonthlyResponseTokenCount AS INT;
	DECLARE @YearMonth AS CHAR(7) = CONVERT(CHAR(7), GETDATE(), 120); -- Formats as YYYY-MM (example: 2025-09)
    
	DECLARE @ActionDate AS SMALLDATETIME;
    SET @ActionDate = GETUTCDATE();

    INSERT INTO dbo.tPrompt 
        (
        UserKey,
		CompanyKey,
		EntityKey,
		Entity,
        PromptText,
		PromptTokenCount,
		ResponseTokenCount,
		Provider,
		ResponseText,
        ActionDate
        )
    VALUES
        (
        @UserKey,
		@CompanyKey,
		@EntityKey,
		@Entity,
        @PromptText,
		@PromptTokenCount,
		@ResponseTokenCount,
		@Provider,
		@ResponseText,
        @ActionDate
        );

	-- Calculate counts for the current month
	SET @MonthlyCount = (
		SELECT COUNT(*)
		FROM tPrompt
		WHERE CompanyKey = @CompanyKey
			AND ActionDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0) -- Start of current month
			AND ActionDate < DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)) -- Start of next month
	);

	SET @MonthlyPromptTokenCount = (
		SELECT ISNULL(SUM(PromptTokenCount), 0)
		FROM tPrompt
		WHERE CompanyKey = @CompanyKey
			AND ActionDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
			AND ActionDate < DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
			AND PromptTokenCount IS NOT NULL
	);

	SET @MonthlyResponseTokenCount = (
		SELECT ISNULL(SUM(ResponseTokenCount), 0)
		FROM tPrompt
		WHERE CompanyKey = @CompanyKey
			AND ActionDate >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
			AND ActionDate < DATEADD(MONTH, 1, DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0))
			AND ResponseTokenCount IS NOT NULL
	);

	-- Update or insert into tPromptUsage
	IF EXISTS (
		SELECT 1
		FROM tPromptUsage
		WHERE CompanyKey = @CompanyKey
			AND YearMonth = @YearMonth
	)
	BEGIN
		-- Update existing record with new totals
		UPDATE tPromptUsage
		SET TotalCount = @MonthlyCount,
			PromptTokenCount = @MonthlyPromptTokenCount,
			ResponseTokenCount = @MonthlyResponseTokenCount
		WHERE CompanyKey = @CompanyKey
			AND YearMonth = @YearMonth;
	END
	ELSE
	BEGIN
		-- Insert new record for the month
		INSERT INTO tPromptUsage (CompanyKey, YearMonth, TotalCount, PromptTokenCount, ResponseTokenCount)
		VALUES (@CompanyKey, @YearMonth, @MonthlyCount, @MonthlyPromptTokenCount, @MonthlyResponseTokenCount);
	END

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

  /*
  || When     Who Rel    What
  || 07/10/15 GHL 10.594 Creation for WJAPP. This proc returns the default rates for the estimate  
  ||                     Contrary to sptEstimateGetRates and other sps that return the standard rates for the project, etc...
  ||                     This only returns the exact default rates in tEstimateService, tEstimateUser and tEstimateTitle
  || 07/15/16 GAR 10.606 (306889) - Added @kBySegmentService to the code where we add services to tEstimateService since we can estimate by campaigns now
  || 05/19/26 RLS 26.06.14 (727817) Added s.ServiceCode
  */

  -- 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
declare @kByProject int			    select @kByProject = 6
declare @kByTitleOnly int	        select @kByTitleOnly = 7
declare @kBySegmentTitle int	    select @kBySegmentTitle = 8

declare @CompanyKey int
declare @ProjectKey int
declare @CampaignKey int
declare @PullEstimateRates int
declare @EstType int
declare @UseTitle int

select  @EstType = EstType
      , @UseTitle = UseTitle 
     , @CompanyKey = CompanyKey
	  , @ProjectKey = ProjectKey
	 , @CampaignKey = CampaignKey
from tEstimate (nolock) 
where EstimateKey = @EstimateKey

-- if the estimate uses titles, even if the est type is by task/service, the rates come from the title, convert here
if isnull(@UseTitle, 0) = 1
	select @EstType = @kByTitleOnly

if @EstType = @kByTaskPerson
	select eu.*
	      ,eu.BillingRate as Rate
		  ,ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, '''') as EntityName
		  ,eu.UserKey as EntityKey
	from  tEstimateUser eu (nolock)
	inner join tUser u (nolock) on eu.UserKey = u.UserKey
	where eu.EstimateKey = @EstimateKey
	order by ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName, '''')

else if @EstType in ( @kByTaskService, @kByServiceOnly, @kBySegmentService)
	select es.*
		  ,s.Description as EntityName
		  ,es.ServiceKey as EntityKey
		  ,s.ServiceCode as ServiceCode
	from tEstimateService es (nolock)
		inner join tService s (nolock) on es.ServiceKey = s.ServiceKey
	where es.EstimateKey = @EstimateKey
	order by s.Description

else if @EstType = @kByTitleOnly
begin
	if isnull(@UseTitle, 0) = 0
	begin
		-- this is a true Title Only estimate, pull the recs in tEstimateTitle
		select et.*
			  ,t.TitleName as EntityName
			  ,et.TitleKey as EntityKey
		from tEstimateTitle et (nolock)
			inner join tTitle t (nolock) on et.TitleKey = t.TitleKey
		where et.EstimateKey = @EstimateKey
		order by t.TitleName
	end
	else	
	begin
		-- this is a Task & Service estimate, that uses titles, pull all the titles and override with tEstimateTitle
		-- the reason is that the number of titles is determined on a different screen (editLaborTitle.js) like levels 
		-- tEstimateTaskLaborTitle, not by tEstimateTitle

		select @PullEstimateRates = 1

		exec sptEstimateGetTitleRates @CompanyKey ,@EstimateKey ,@ProjectKey ,@CampaignKey, @PullEstimateRates 
	end
end	
	
		
		



	
	
	 


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

ALTER PROCEDURE [dbo].[sptInvoiceLineGetOrdersRollupSummary]
	(
		@InvoiceLineKey int,
		@Type smallint,
		@Percentage decimal(24,4)
	)
AS

/*  Who When        Rel     What
||  GHL 06/23/2006  8.35    Clone of sptInvoiceLineGetOrdersRollup for summary lines
||  GHL 05/07/2008  8.510   (21995) Added Item as rollup
||  GHL 10/07/20    20.110  (529627) Added purchase order number. Was missing for the sort when GroupByOrder = 1
||  MCM 06/10/26    26.06x  (730580) Added DetailOrderDate and DetailInvoiceDate to the return when GroupByOrder = 0
*/ 

declare @Rollup INT
		,@Group1 INT
		,@Group2 INT
		,@Group3 INT
		,@Group4 INT
		,@Group5 INT

declare @GroupByOrder smallint

DECLARE @RollupGroupBy AS VARCHAR(1000)		-- For Group Bys
		,@Rollup1Where AS VARCHAR(1000)		-- For Where Clauses
		,@Rollup2Where AS VARCHAR(1000)
		,@Rollup3Where AS VARCHAR(1000)
		,@Rollup4Where AS VARCHAR(1000)
		,@Rollup5Where AS VARCHAR(1000)

DECLARE @SQL AS VARCHAR(1000)

IF @Type = 1
	-- IO
	SELECT @Rollup = IOHideDetails
			,@Group1 = IOGroup1 
			,@Group2 = IOGroup2
			,@Group3 = IOGroup3
			,@Group4 = IOGroup4
			,@Group5 = IOGroup5
			,@GroupByOrder = IOGroupByOrder
	FROM    tInvoiceLine il (NOLOCK)
			INNER JOIN tInvoice i (NOLOCK) ON il.InvoiceKey = i.InvoiceKey
			LEFT OUTER JOIN tInvoiceTemplate it (NOLOCK) ON i.InvoiceTemplateKey = it.InvoiceTemplateKey
	WHERE   il.InvoiceLineKey = @InvoiceLineKey
ELSE
	-- BC					
	SELECT @Rollup = BCHideDetails 
			,@Group1 = BCGroup1 
			,@Group2 = BCGroup2
			,@Group3 = BCGroup3
			,@Group4 = BCGroup4
			,@Group5 = BCGroup5
			,@GroupByOrder = BCGroupByOrder
	FROM    tInvoiceLine il (NOLOCK)
			INNER JOIN tInvoice i (NOLOCK) ON il.InvoiceKey = i.InvoiceKey
			LEFT OUTER JOIN tInvoiceTemplate it (NOLOCK) ON i.InvoiceTemplateKey = it.InvoiceTemplateKey
	WHERE   il.InvoiceLineKey = @InvoiceLineKey
	
SELECT @Rollup = ISNULL(@Rollup, 0)
		,@Group1 = ISNULL(@Group1, 0) 
		,@Group2 = ISNULL(@Group2, 0)
		,@Group3 = ISNULL(@Group3, 0)
		,@Group4 = ISNULL(@Group4, 0)
		,@Group5 = ISNULL(@Group5, 0)
				
IF @Rollup = 0
	RETURN 1		
	
declare @IOClientLink smallint
declare @BCClientLink smallint
declare @CompanyKey int
declare @InvoiceKey int

select @CompanyKey = co.CompanyKey
       ,@InvoiceKey = invl.InvoiceKey
  from tCompany co (nolock) inner join tInvoice inv (nolock) on co.CompanyKey = inv.CompanyKey
       inner join tInvoiceLine invl (nolock) on inv.InvoiceKey = invl.InvoiceKey
 where invl.InvoiceLineKey = @InvoiceLineKey   
       
select @BCClientLink = isnull(BCClientLink,1),
       @IOClientLink = isnull(IOClientLink,1)
  from tPreference (nolock)
 where CompanyKey = @CompanyKey

Select @Percentage = @Percentage / 100


-- Temp table for the invoice lines
CREATE TABLE #IL (  pQuantity DECIMAL(24,4) NULL, pAmountBilled MONEY NULL
					,ClientDivision VARCHAR(100) NULL, ClientDivisionKey INT NULL 
					,ClientProduct VARCHAR(100) NULL, ClientProductKey INT NULL 
					,EstimateName VARCHAR(100) NULL, MediaEstimateKey INT NULL
					,MarketName VARCHAR(100) NULL, MediaMarketKey INT NULL
					,StationName VARCHAR(250) NULL, CompanyMediaKey INT NULL
					,VendorName VARCHAR(250) NULL, VendorKey INT NULL
					,ItemName VARCHAR(250) NULL, ItemKey INT NULL
					,PurchaseOrderNumber VARCHAR(250) NULL, PurchaseOrderKey int null
					)
					
-- Temp table for the rollups
CREATE TABLE #Rollup ( pQuantity DECIMAL(24,4) NULL, pAmountBilled MONEY NULL
					,ClientDivision VARCHAR(100) NULL, ClientDivisionKey INT NULL 
					,ClientProduct VARCHAR(100) NULL, ClientProductKey INT NULL 
					,EstimateName VARCHAR(100) NULL, MediaEstimateKey INT NULL
					,MarketName VARCHAR(100) NULL, MediaMarketKey INT NULL
					,StationName VARCHAR(250) NULL, CompanyMediaKey INT NULL
					,VendorName VARCHAR(250) NULL, VendorKey INT NULL
					,ItemName VARCHAR(250) NULL, ItemKey INT NULL
					,PurchaseOrderNumber VARCHAR(250) NULL, PurchaseOrderKey int null
					,qRollup1 DECIMAL(24,4) NULL, aRollup1 MONEY NULL
					,qRollup2 DECIMAL(24,4) NULL, aRollup2 MONEY NULL
					,qRollup3 DECIMAL(24,4) NULL, aRollup3 MONEY NULL
					,qRollup4 DECIMAL(24,4) NULL, aRollup4 MONEY NULL
					,qRollup5 DECIMAL(24,4) NULL, aRollup5 MONEY NULL					
					)

-- Fillup the temp tables recursively
EXEC sptInvoiceLineGetOrdersRollupRecursive @InvoiceKey, @InvoiceLineKey, @Type, @Percentage,
		@BCClientLink, @IOClientLink

-- if we group by order, all the other groups are ignored (529627)
if @GroupByOrder = 1
	select @Group1 = 0, @Group2 = 0, @Group3 = 0, @Group4 = 0, @Group5 = 0
		 

SELECT @RollupGroupBy = ''0'' -- Just a marker for commas
IF @Rollup = 1
BEGIN
	IF @Group1 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup1Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group1 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup1Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group1 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup1Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group1 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup1Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''		
	IF @Group1 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup1Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group1 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup1Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group1 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup1Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''
END
IF @Rollup = 1
BEGIN
	IF @Group2 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup2Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group2 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup2Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group2 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup2Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group2 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup2Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''	
	IF @Group2 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup2Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group2 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup2Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group2 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup2Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END
IF @Rollup = 1
BEGIN
	IF @Group3 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup3Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group3 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup3Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group3 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup3Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group3 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup3Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''
	IF @Group3 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup3Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group3 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup3Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group3 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup3Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END
IF @Rollup = 1
BEGIN
	IF @Group4 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup4Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group4 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup4Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group4 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup4Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group4 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup4Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''
	IF @Group4 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup4Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group4 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup4Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group4 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup4Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END
IF @Rollup = 1
BEGIN
	IF @Group5 = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientDivision, ClientDivisionKey''
			  ,@Rollup5Where = ''ISNULL(b.ClientDivisionKey, 0) = ISNULL(#Rollup.ClientDivisionKey, 0)''
	IF @Group5 = 2
		SELECT @RollupGroupBy = @RollupGroupBy + '',ClientProduct, ClientProductKey''
			  ,@Rollup5Where = ''ISNULL(b.ClientProductKey, 0) = ISNULL(#Rollup.ClientProductKey, 0)''
	IF @Group5 = 3
		SELECT @RollupGroupBy = @RollupGroupBy + '',EstimateName, MediaEstimateKey''
			  ,@Rollup5Where = ''ISNULL(b.MediaEstimateKey, 0) = ISNULL(#Rollup.MediaEstimateKey, 0)''
	IF @Group5 = 4
		SELECT @RollupGroupBy = @RollupGroupBy + '',MarketName, MediaMarketKey''
			  ,@Rollup5Where = ''ISNULL(b.MediaMarketKey, 0) = ISNULL(#Rollup.MediaMarketKey, 0)''
	IF @Group5 = 5
		SELECT @RollupGroupBy = @RollupGroupBy + '',StationName, CompanyMediaKey''		 		
			  ,@Rollup5Where = ''ISNULL(b.CompanyMediaKey, 0) = ISNULL(#Rollup.CompanyMediaKey, 0)''
	IF @Group5 = 6
		SELECT @RollupGroupBy = @RollupGroupBy + '',VendorName, VendorKey''		 		
			  ,@Rollup5Where = ''ISNULL(b.VendorKey, 0) = ISNULL(#Rollup.VendorKey, 0)''
	IF @Group5 = 7
		SELECT @RollupGroupBy = @RollupGroupBy + '',ItemName, ItemKey''		 		
			  ,@Rollup5Where = ''ISNULL(b.ItemKey, 0) = ISNULL(#Rollup.ItemKey, 0)''

END

-- for (529627)
IF @GroupByOrder = 1
		SELECT @RollupGroupBy = @RollupGroupBy + '',PurchaseOrderNumber, PurchaseOrderKey''
			  ,@Rollup1Where = ''ISNULL(b.PurchaseOrderKey, 0) = ISNULL(#Rollup.PurchaseOrderKey, 0)''

-- This way we can use as many ANDs in where clauses
SELECT @Rollup1Where = ISNULL(@Rollup1Where, '' 1 = 1 '')
		,@Rollup2Where = ISNULL(@Rollup2Where, '' 1 = 1 '')
		,@Rollup3Where = ISNULL(@Rollup3Where, '' 1 = 1 '')
		,@Rollup4Where = ISNULL(@Rollup4Where, '' 1 = 1 '')
		,@Rollup5Where = ISNULL(@Rollup5Where, '' 1 = 1 '')
				
SELECT @RollupGroupBy = REPLACE (@RollupGroupBy, ''0,'', '''') -- Remove marker
--SELECT @RollupGroupBy

SELECT @SQL = ''INSERT #Rollup ('' + @RollupGroupBy + '',pQuantity, pAmountBilled)''
SELECT @SQL = @SQL + '' SELECT '' + @RollupGroupBy + '', SUM(pQuantity), SUM(pAmountBilled) ''
SELECT @SQL = @SQL + '' FROM #IL ''
SELECT @SQL = @SQL + '' GROUP BY '' + @RollupGroupBy

--SELECT @SQL
EXEC (@SQL)

IF @Group1 > 0
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup1 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' ) ''	
	--SELECT @SQL
	EXEC (@SQL)
	
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup1 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' ) ''	
	EXEC (@SQL)
	
END

IF @Group2 > 0 
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup2 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)

	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup2 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)

END

IF @Group3 > 0
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup3 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)
	
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup3 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)
	
END


IF @Group4 > 0
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup4 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)

	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup4 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)

END

IF @Group5 > 0 
BEGIN
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.aRollup5 = (SELECT  SUM(b.pAmountBilled) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup5Where	
	SELECT @SQL = @SQL + '' ) ''
	--SELECT @SQL
	EXEC (@SQL)
	
	SELECT @SQL = '' UPDATE #Rollup SET #Rollup.qRollup5 = (SELECT  SUM(b.pQuantity) FROM #Rollup b ''
	SELECT @SQL = @SQL + '' WHERE ''
	SELECT @SQL = @SQL + @Rollup1Where
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup2Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup3Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup4Where	
	SELECT @SQL = @SQL + '' AND ''
	SELECT @SQL = @SQL + @Rollup5Where	
	SELECT @SQL = @SQL + '' ) ''
	EXEC (@SQL)	
END

IF @GroupByOrder = 0
	--added DetailOrderDate and DetailOrderEndDate as nulls for VB (730580) since they expect these columns to be there, even though they do not matter for rollups that are not grouped by order
	SELECT *, CAST(NULL AS SMALLDATETIME) as DetailOrderDate, CAST(NULL AS SMALLDATETIME) as DetailOrderEndDate FROM #Rollup
else
	-- these dates do not matter but are expected by VB (529627)
	SELECT #Rollup.*, po.PODate as DetailOrderDate, po.PODate as DetailOrderEndDate  
	FROM #Rollup
	INNER JOIN tPurchaseOrder po (nolock) on #Rollup.PurchaseOrderKey = po.PurchaseOrderKey

RETURN 1


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCompanyBackup]'
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
*/
/*
	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 ''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'Altering [dbo].[spCompanyDeleteAll]'
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
*/

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 ''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 index [IX_tApiLog_ActionDate] on [dbo].[tAPILog]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tApiLog_ActionDate' AND object_id = OBJECT_ID(N'[dbo].[tAPILog]'))
CREATE NONCLUSTERED INDEX [IX_tApiLog_ActionDate] ON [dbo].[tAPILog] ([ActionDate] DESC)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tCCEntry_1] on [dbo].[tCCEntry]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tCCEntry_1' AND object_id = OBJECT_ID(N'[dbo].[tCCEntry]'))
CREATE NONCLUSTERED INDEX [IX_tCCEntry_1] ON [dbo].[tCCEntry] ([CCVoucherKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tCCEntry_CompanyKey_Coverage] on [dbo].[tCCEntry]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tCCEntry_CompanyKey_Coverage' AND object_id = OBJECT_ID(N'[dbo].[tCCEntry]'))
CREATE NONCLUSTERED INDEX [IX_tCCEntry_CompanyKey_Coverage] ON [dbo].[tCCEntry] ([CompanyKey]) INCLUDE ([GLAccountKey], [CCVoucherKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tCCEntry_CompanyKey_GLAccountKey_TransactionDate] on [dbo].[tCCEntry]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tCCEntry_CompanyKey_GLAccountKey_TransactionDate' AND object_id = OBJECT_ID(N'[dbo].[tCCEntry]'))
CREATE NONCLUSTERED INDEX [IX_tCCEntry_CompanyKey_GLAccountKey_TransactionDate] ON [dbo].[tCCEntry] ([CompanyKey], [GLAccountKey], [TransactionPostedDate]) INCLUDE ([Amount], [CCVoucherKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tCCEntry_GLAccountKey] on [dbo].[tCCEntry]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tCCEntry_GLAccountKey' AND object_id = OBJECT_ID(N'[dbo].[tCCEntry]'))
CREATE NONCLUSTERED INDEX [IX_tCCEntry_GLAccountKey] ON [dbo].[tCCEntry] ([GLAccountKey]) INCLUDE ([ItemKey], [CCVoucherKey])
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
