SET NUMERIC_ROUNDABORT OFF
GO
SET ANSI_PADDING, ANSI_WARNINGS, CONCAT_NULL_YIELDS_NULL, ARITHABORT, QUOTED_IDENTIFIER, ANSI_NULLS ON
GO
SET XACT_ABORT ON
GO
SET TRANSACTION ISOLATION LEVEL Serializable
GO
BEGIN TRANSACTION
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [IX_tActivityEmail_UserKey] from [dbo].[tActivityEmail]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tActivityEmail_UserKey' AND object_id = OBJECT_ID(N'[dbo].[tActivityEmail]'))
DROP INDEX [IX_tActivityEmail_UserKey] ON [dbo].[tActivityEmail]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Dropping index [IX_tActivity_8] from [dbo].[tActivity]'
GO
IF EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tActivity_8' AND object_id = OBJECT_ID(N'[dbo].[tActivity]'))
DROP INDEX [IX_tActivity_8] ON [dbo].[tActivity]
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tProjectStatus]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tProjectStatus]', N'ProjectStatusColor') IS NULL
ALTER TABLE [dbo].[tProjectStatus] ADD[ProjectStatusColor] [varchar] (50) NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[tPurchaseOrderDetail]'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
IF COL_LENGTH(N'[dbo].[tPurchaseOrderDetail]', N'InteractiveAdUnitName') IS NULL
ALTER TABLE [dbo].[tPurchaseOrderDetail] ADD[InteractiveAdUnitName] [varchar] (100) NULL
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_Project]'
GO
IF OBJECT_ID(N'[dbo].[vReport_Project]', 'V') IS NOT NULL
EXEC sp_executesql N'




ALTER VIEW [dbo].[vReport_Project] 
AS 
/* 
|| When     Who Rel     What 
|| 10/12/06 WES 8.3567  Added Retainer Name 
|| 02/12/07 GWG 8.4004  Added Billing Contact email and phone 
|| 04/04/07 GWG 8.5     Added Client ID and full name 
|| 04/04/07 GHL 8.411   Using now tProjectRollup to improve performance 
|| 04/04/07 GHL 8.42    Added % Actual vs Budget Hours & Labor Gross 
|| 05/16/07 GHL  8.421  Added Percentage Complete 
|| 07/20/07 GWG 8.432   Modified the variances to include change orders 
|| 10/11/07 CRG 8.5     Added GLCompany and Class 
|| 11/07/07 GHL 8.5     Corrected  [Labor Variance Net] 
|| 11/08/07 GHL 8.5     Synch''ed names with flash reports 
|| 11/07/07 CRG 8.5     (9759) Added Actual Gross Total 
|| 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    (16801) Added Last Task Due Date 
|| 10/16/08 GHL 10.011 (34827)(36763) Removed Orders from Total Costs 
|| 02/03/09 MAS 10.0.1.8 (43997) Added the LaborUnbilled column 
|| 02/20/09 GHL 10.0.1.9 (44636) Added Open Amount of Adv Bill column 
|| 03/17/09 RTC 10.5	  Removed user defined fields. 
|| 05/15/09 GHL 10.0.1.5 (52321) Added Campaign summary data 
||                       Users can then compare project data vs campaign data   
|| 06/12/09 MAS 10.0.1.7 (54233) Added Campaign CustomField 
|| 07/09/09 GHL 10.504 (56867) Added Billed Amount without tax   
|| 09/15/09 GHL 10.510 (63067) Added Project Full Name 
|| 10/6/09  CRG 10.5.1.2 (64424) Added Parent Company Name and Parent Active 
|| 10/22/09 GHL 10.5.1.3 (66272) Added Adv Bill w/o Tax 
|| 11/04/09 GHL 10.5.1.3 (67443) Added Adv Bill Open 
|| 12/22/09 GHL 10.5.1.5  Added GetMarkupFrom 
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved 
|| 04/14/10 RLB 10.521  (40446) Added Company Type 
|| 07/30/10 RLB 10.533  Added Inside Cost Gross Unbilled and Outside Cost Gross Unbilled  
|| 02/01/11 RLB 10.541  Added campaign segment 
|| 04/07/11 RLB 10.543 (108045) Removed Project Short Name 
|| 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  
|| 03/07/12 GHL 10.554 (103259) Added [Opportunity Name] 
|| 04/24/12 GHL 10.555  Added GLCompanyKey in order to map/restrict 
|| 08/17/12 RLB 10.559 (151960) Added Billing Group Code 
|| 09/28/12 GHL 10.560 Getting now BillingGroupCode from tBillingGroup 
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey 
|| 11/07/12 KMC 10.562 (158998) Added DoNotPostWIP 
|| 03/06/13 GHL 10.566 (167702) Added Expense WO and Labor WO 
|| 04/09/13 GHL 10.566 (174154) Changed Open Order Unbilled to tProjectRollup.OpenOrderUnbilled 
||                      rather than OpenOrderGross 
|| 08/02/13 GHL 10.570 (185610) Added individual expense Gross amounts 
|| 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 
|| 01/27/15 WDF 10.588 (Abelson Taylor) Added Division and Product ID 
|| 01/26/15 GHL 10.588 Added Billing Group Description for Abelson Taylor 
|| 06/15/15 KMC 10.593 (259368) Added join to tSource to show the lead source the company was created from 
|| 01/28/16 MCM 10.600 (274838) Added Billing Manager 
|| 02/26/16 GHL 10.601 (290954) Added project currency 
|| 04/01/16 MCM 10.602 (274464) Added Total Gross - pulled from vListing_Project 
|| 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/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 
|| 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/14/17 MCM 10.619 (353717) Added CampaignCampaignCurrentTotalBudget and Project summary fields from vCampaignSummary
|| 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
|| 09/28/17 GWG 10.620 Added Allocated Hours
|| 06/05/18 GAR 18.6.0 (404485) Addded FilesArchived field.
|| 06/12/18 RLB 18.7.0 (403717)
|| 01/03/19 RLS 19.1.0 (435592) Added [Schedule Status Color]
|| 01/28/19 GWG 19.2.0 Added Month started and completed for graphing
|| 04/10/19 RLB 19.4.0 (453355) added project hourly rate 
|| 04/18/19 RLS 19.5.0 (452745) added [Purchasing Markup Rate], [IO Commission Rate], [BO Commission Rate]
|| 05/10/19 RLS 19.6.0 (454857) added [Campaign Advance Billed], [Campaign Advance Billed Open] and [Campaign Advance Billed Unapplied]
|| 05/13/19 AMP 19.0.6.0 (453506) Added Client Active (yes/no)
|| 07/24/19 GHL 19.080 (471535) Added OpenOrderUnbilled to [Total Gross Unbilled] (was same as [Total Gross Unbilled wo Orders]) 
|| 08/22/19 GAR 19.090 (474958) Added Project Manager
|| 09/16/19 GAR 19.100 (479426) Added campaign description
|| 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
|| 12/16/19 AMP 20.0.1.0 (490355) Added Last Billed Date field. This is the max date of the client invoices for that project
|| 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]
|| 08/17/20 GAR 20.0.9.0 (522505) Added [Retainer Active]
|| 08/20/20 RLS 20.0.9.0 (522471) Added [Date Sent For Approval] and [Requested By]
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 09/30/20 RLS 20.1.0.0 (531369) Changed ISNULL(roll.VoucherGross, 0) to ISNULL(roll.VoucherOutsideCostsGross, 0) in the calculation for the field [Total Costs Gross wo Orders]
|| 12/30/20 GHL 21.01.24.0 (541935) Added Split Billing column to display the % per client of split billing
|| 02/16/21 GAR 21.03.14 (547160) Added Planning Project Number, Name, Full Name
|| 02/26/21 GHL 21.03.14.0000 (550113) Fixed ambiguity with names like ''Project Amount Billed'' in the campaign summary by renaming them like ''Campaign Projects Amount Billed''
||                             and adding new field ''Project Amount Billed'' for the project only   
|| 07/29/21 AMP 21.08.15.0000 (565984) Added Client Account Manager
|| 07/30/21 GHL 21.08.15.0000 (566322) Added Charge Code Percentage for LLNL
|| 09/07/21 GAR 21.10.21.0000 (570680) Added CampaignKey for use in custom reports
|| 09/30/21 RLB 21.10.21 (572763) added Total Allocated Gross pulled from vTaskUserHour
|| 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
|| 06/14/22 RLS 22.07.17 (601560) Added [Last Date Worked]
|| 07/11/22 GAR 22.08.14 (605591) Added Account Team
|| 08/05/22 GAR 22.09.18 (607739) Added Campaign Segment Start Date and Due Date
|| 12/07/22 RLB 23.01.15 (622207) added Open Amount of Adv Bill wo Tax
|| 02/22/23 RLS 23.03.19 (631413) Added [Locked Schedule]
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color
|| 03/24/23 AMP 23.04.16 (635447) Added Current Budget Expense Net 
|| 04/17/23 MCM 23.05.x  (637872) Fix issue with "Open Amount of Adv Bill wo Tax" field because it''s wrong when multiple invoice lines in the t.InvoiceSummary table
|| 04/20/23 RLB 23.05.x  (633057) Added RemainingLaborBudget and RemainingExpenseBudget from projects page. total them for a new col called RemainingTotalBudget
|| 07/20/23 AMP 23.08.20 (646254) Added Last Task Actual Complete Date
|| 07/27/23 AMP 23.08.20 (647190) Added [Project Status ID]
|| 08/11/23 RLB 23.09.17 (648008) added project type color
|| 08/29/23 CRG 23.09.17 (643372) Modified [Last Task Actual Complete Date] to match the logic in the Project Dashboard scorecard
|| 05/09/24 GAR 24.06.16 (671523) Added OverrideScheduleOptions
|| 06/13/24 RLB 24.07.14 (663998) adding color field for Schedule_Status_Color
|| 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/10/24 RLS 25.02.16 (685555) Added [Outside Costs Gross]
|| 01/21/25 RLS 25.02.16 (687223) Added [Exclude from Resource Manager]
|| 02/24/25 RLS 25.03.16 (695376) Added [Payment Terms]
|| 08/13/25 RLS 25.09.14 (706655) Added OpenOrderNet to [Total Costs Net]
|| 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/03/26 AMP 26.03.15 (721175) Add Key Person 1-6 Email Address
|| 02/24/26 RLS 26.03.15 (720029) Added [Require Comments on Time Entries]
|| 03/31/26 GAR 26.04.19 (723332) Added ProjectStatusColor
*/ 
 
Select 
	 p.CompanyKey 
	,p.ProjectKey 
	,p.GLCompanyKey 
	,p.CustomFieldKey 
	,cp.CustomFieldKey as CustomFieldKey2 
	,cl.CustomFieldKey as CustomFieldKey3
	,rn.Title as [Retainer Name] 
	,p.ProjectName as [Project Name] 
	,p.ProjectNumber as [Project Number] 
    ,p.ProjectNumber + '' - '' + p.ProjectName as [Project Full Name] 
 	,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]
	,kp1.Email as [Key People 1 Email Address] 
	,kp2.Email as [Key People 2 Email Address] 
	,kp3.Email as [Key People 3 Email Address] 
	,kp4.Email as [Key People 4 Email Address] 
	,kp5.Email as [Key People 5 Email Address] 
	,kp6.Email as [Key People 6 Email Address] 
	,cl.CompanyName as [Client Name] 
	,cl.CustomerID as [Client ID] 
	,cl.CustomerID + '' - '' + cl.CompanyName as [Client Full Name] 
	,LTRIM(RTRIM(ISNULL(clientam.FirstName + '' '','''')  + ISNULL(clientam.LastName,''''))) AS [Client Account Manager]
	,case cl.Active when 1 then ''YES'' else ''NO'' end as [Client Active]
	,LTRIM(RTRIM(ISNULL(csp.FirstName + '' '','''')  + ISNULL(csp.LastName,''''))) AS [Client Sales Person] 
	,ct.CompanyTypeName as [Company Type] 
	,p.ClientProjectNumber [Client Project Number] 
	,Case When sp.ProjectNumber is null then sp.ProjectName else sp.ProjectNumber + '' - '' + sp.ProjectName end as [Source Project] 
	,bu.FirstName + '' '' + bu.LastName as [Client Billing Contact] 
	,bu.Email as [Client Billing Contact Email] 
	,bu.Phone1 as [Client Billing Contact Phone] 
	,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 Expense Rate From] 
	,Case p.BillingMethod  
		When 1 then ''Time and Materials'' 
		When 2 then ''Fixed Fee'' 
		When 3 then ''Retainer'' 
		end as [Billing Method] 
	,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] 
	,Case ISNULL(cp.MultipleSegments, 0) When 1 then ''YES'' else ''NO'' end as [Contains Segments] 
	,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.Description as [Project Description] 
	,p.ClientNotes as [Client Notes] 
	,Case p.Active When 1 then ''YES'' else ''NO'' end as [Active] 
	,p.StartDate as [Project Start 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.CompleteDate as [Project Due Date] 
	,(SELECT MAX(t.PlanComplete) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as [Last Task Due Date] 
	,lastTaskActComplete.LastActComplete as [Last Task Actual Complete Date]	
	,(SELECT MIN(t.PlanStart) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as [First Task Start Date] 
	,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] 
	,LTRIM(RTRIM(ISNULL(cu.FirstName + '' '','''')  + ISNULL(cu.LastName,''''))) AS [Created By] 
	,o.OfficeName as [Office] 
	,o.OfficeColor as [Office Color]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager] 
	,p.CampaignKey
	,cp.CampaignName as [Campaign Name] 
	,cp.CampaignID as [Campaign ID] 
	,cp.CampaignID + ''-'' + cp.CampaignName as [Campaign Full Name] 
	,cs.SegmentName as [Campaign Segment] 
	,cs.PlanStart as [Campaign Segment Start Date]
	,cs.PlanComplete as [Campaign Segment Due Date]
	,cp.StartDate as [Campaign Start Date] 
	,cp.EndDate as [Campaign End Date] 
	,pr.RequestID as [Project Request ID] 
	,Case p.DoNotPostWIP WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Do Not Post WIP] 
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager] 
 
	-- Budgeted data 
	,p.EstHours as [Original Budget Hours] -- [Estimate Hours] 
	,p.BudgetLabor as [Original Budget Labor Net] -- [Estimate Labor Net] 
	,p.EstLabor as [Original Budget Labor Gross] -- [Estimate Labor] 
	,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.ApprovedCOBudgetLabor as [CO Budget Labor Net] -- [Approved CO Labor Net] 
	,p.ApprovedCOLabor as [CO Budget Labor Gross] -- [Approved CO Labor] 
	,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.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] --[Total with Tax] 
	,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense - p.BudgetExpenses - p.BudgetLabor - p.ApprovedCOBudgetLabor - p.ApprovedCOBudgetExp  as [Estimate Profit] -- No change, not in report 
	,p.PercComp as [Percentage Complete]
	,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]
	-- Difference between CurrentBudgetLaborGross and TotalLaborGross
	,(p.EstLabor + p.ApprovedCOLabor) - ISNULL(roll.LaborGross, 0) as [Remaining Labor Budget]
	-- Difference between CurrentBudgetExpenseGross and TotalCostsGross
	,(p.EstExpenses + p.ApprovedCOExpense) - 
		(ISNULL(roll.MiscCostGross, 0) 
		+ ISNULL(roll.ExpReceiptGross, 0) 
		+ ISNULL(roll.OrderPrebilled, 0) 
		+ ISNULL(roll.VoucherOutsideCostsGross, 0)) as [Remaining Expense Budget]
	-- RemainingLaborBudget + RemainingExpenseBudget
	,((p.EstLabor + p.ApprovedCOLabor) - ISNULL(roll.LaborGross, 0))
		+
	 ((p.EstExpenses + p.ApprovedCOExpense) - 
		(ISNULL(roll.MiscCostGross, 0) 
		+ ISNULL(roll.ExpReceiptGross, 0) 
		+ ISNULL(roll.OrderPrebilled, 0) 
		+ ISNULL(roll.VoucherOutsideCostsGross, 0))) as [Remaining Total Budget]

 
	-- 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.LaborUnbilled, 0) as [Labor Unbilled] 
	,ISNULL(roll.VoucherUnbilled, 0) as [Outside Costs Gross Unbilled] 
	,ISNULL(roll.VoucherOutsideCostsGross, 0) as [Outside Costs Gross]


	,ISNULL(roll.MiscCostUnbilled, 0) + ISNULL(roll.ExpReceiptUnbilled, 0) as [Inside Costs 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.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherGross, 0) + ISNULL(roll.LaborGross, 0) as [Actual Gross Total] 
 
	,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.BilledAmount, 0) as [Amount Billed] -- No change same as report 
	,ISNULL(roll.HoursBilled, 0) as [Hours Billed]
	,ISNULL(roll.BilledAmountApproved, 0) as [Amount Billed Approved]  
	,ISNULL(roll.BilledAmountNoTax, 0) as [Amount Billed wo Tax]  
	,ISNULL(roll.AdvanceBilled, 0) as [Amount Advance Billed] -- No change same as report  
    ,ISNULL(roll.AdvanceBilledOpen, 0) as [Amount Advance Billed Open]   
	,ISNULL(roll.OpenOrderNet, 0) as [Open Orders Net] -- [Open Purchase Orders] 
	,ISNULL(roll.OpenOrderUnbilled, 0) as [Open Orders Gross Unbilled] -- New field!!!  
	,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) + ISNULL(roll.OrderPrebilled, 0) + ISNULL(roll.OpenOrderUnbilled, 0) as [Total Gross] 
 
	-- Comparisons 
	,ISNULL(roll.LaborNet, 0) - ISNULL(p.BudgetLabor, 0) - ISNULL(p.ApprovedCOBudgetLabor, 0) as [Labor Variance Net] 
	,ISNULL(roll.MiscCostNet, 0) + ISNULL(roll.ExpReceiptNet, 0) + ISNULL(roll.VoucherNet, 0) - ISNULL(p.BudgetExpenses, 0) - ISNULL(p.ApprovedCOBudgetExp, 0) as [Expense Variance Net] 
	,ISNULL(roll.LaborGross, 0) - ISNULL(p.EstLabor, 0) - ISNULL(p.ApprovedCOLabor, 0) as [Labor Variance Gross] 
	,ISNULL(roll.MiscCostGross, 0) + ISNULL(roll.ExpReceiptGross, 0) + ISNULL(roll.VoucherGross, 0) - ISNULL(p.EstExpenses, 0) - ISNULL(p.ApprovedCOExpense, 0) as  [Expense Variance Gross] 
 
	,ISNULL(roll.OpenOrderGross, 0) as [Open Orders Gross]  
	,ISNULL(roll.MiscCostGross, 0) as [Misc Cost Gross] 
	,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] 
 
	-- WriteOff data for Abelson Taylor 
	--Added in 2013  
	,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.MiscCostWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0) as [Expense Writeoff Amount]  
	,ISNULL(roll.LaborWriteOff, 0) as [Labor Writeoff Amount]   
	-- Added in 2016 
	,ISNULL(roll.HoursWriteOff, 0) as [Hours Writeoff] 
	,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] 
	,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 Open 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.MiscCostWriteOff, 0) + ISNULL(roll.ExpReceiptWriteOff, 0) + ISNULL(roll.VoucherWriteOff, 0)) -- Expense Write Off 
	as [Total Gross After Writeoff w Open Orders] 
 
 
	,CASE WHEN (p.EstHours + p.ApprovedCOHours) = 0 THEN ISNULL(roll.Hours, 0) * 100 ELSE ROUND(  (ISNULL(roll.Hours, 0) * 100) / (p.EstHours + p.ApprovedCOHours), 3) END as [Percent Actual vs Budget Hours]   
	,CASE WHEN (p.EstLabor + p.ApprovedCOLabor) = 0 THEN ISNULL(roll.LaborGross, 0) * 100 ELSE ROUND(  (ISNULL(roll.LaborGross, 0) * 100) / (p.EstLabor + p.ApprovedCOLabor), 3) END as [Percent Actual vs Budget Labor Gross]   
	,glc.GLCompanyID as [Company ID] 
	,glc.GLCompanyName as [Company Name] 
	,cla.ClassID as [Class ID] 
	,cla.ClassName as [Class Name] 
	,trs.RateSheetName as [Service Rate Sheet] 
	,tirs.RateSheetName as [Title Rate Sheet] 
    ,ISNULL(( 
		SELECT SUM(ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.AmountReceived, 0) 
				- ISNULL(i.WriteoffAmount, 0) - ISNULL(i.DiscountAmount, 0) ) 
		FROM tInvoice i (NOLOCK) 
		WHERE i.ProjectKey = p.ProjectKey 
		AND i.AdvanceBill = 1 
	),0) as [Open Amount of Adv Bill] 
 
	,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] 

	-- 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 [Campaign Projects Current Total Budget Cont With Tax]	-- 550113 changed Project to Campaign Projects
	,vcs.ProjectCurrentTotalBudget as [Campaign Projects Current Total Budget]							-- 550113 changed Project to Campaign Projects
	,vcs.ProjectTotalGross as [Campaign Projects Total Gross]											-- 550113 changed Project to Campaign Projects
	,vcs.ProjectAmountBilled as [Campaign Projects Amount Billed]										-- 550113 changed Project to Campaign Projects
 
	-- and created these 4 new ones with the old names (550113) for the project only
    ,ISNULL(p.EstLabor, 0) + ISNULL(p.EstExpenses, 0) + ISNULL(p.SalesTax, 0) + ISNULL(p.Contingency, 0) 
	+ ISNULL(p.ApprovedCOLabor, 0) + ISNULL(p.ApprovedCOExpense, 0) + ISNULL(p.ApprovedCOSalesTax, 0) AS [Project CurrentTotal Budget Cont With Tax] 
	,ISNULL(p.EstLabor, 0) + ISNULL(p.EstExpenses, 0) + ISNULL(p.ApprovedCOLabor, 0) + ISNULL(p.ApprovedCOExpense, 0) as [Project Current Total Budget]
	,roll.LaborGross + roll.MiscCostGross + roll.ExpReceiptGross + roll.OrderPrebilled + roll.VoucherOutsideCostsGross + roll.OpenOrderUnbilled as [Project Total Gross] 
	,roll.BilledAmount as [Project Amount Billed]	   	   	   

	,parentCompany.CompanyName as [Parent Company Name] 
	,pcd.DivisionName as [Parent Division Name] 
	,Case cp.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active] 
	,l.LeadID as [Opportunity ID]
	,l.Subject as [Opportunity Name] 
	,source.SourceName as [Company Source] 
	 
	, case when p.BillingManagerKey is null then LTRIM(RTRIM(ISNULL(bmc.FirstName + '' '','''')  + ISNULL(bmc.LastName,'''')))
	else LTRIM(RTRIM(ISNULL(bm.FirstName + '' '','''')  + ISNULL(bm.LastName,''''))) 
	end as [Billing Manager Name] 
 
	,p.CurrencyID as Currency 
	,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]   
	,(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]
	,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 p.FilesArchived WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Files Archived]
	,Case p.TaskStatus When 1 then ''Green'' When 2 then ''Yellow'' When 3 then ''Red'' else ''Green'' end as [Schedule Status Color]
	,Case p.TaskStatus When 1 then ''#16A765'' When 2 then ''#FBE983'' When 3 then ''#F83A22'' else ''#16A765'' end as [Schedule Status Color Field]
	,Case p.GetRateFrom When 2 then p.HourlyRate else 0 end as [Project Hourly Rate]
	,p.ItemMarkup as [Purchasing Markup Rate]
	,p.IOCommission as [IO Commission Rate]
	,p.BCCommission as [BO Commission Rate]
	,ISNULL(vab.InvoiceTotalAmount,0) as [Campaign Advance Billed]
	,ISNULL(vab.OpenAmount,0) as [Campaign Advance Billed Open]
	,ISNULL(vab.UnappliedAmount,0) as [Campaign Advance Billed Unapplied]
	,cp.Description AS [Campaign Description]
	,CASE 
			WHEN ISNULL(p.GLCompanySource,0) = 0 THEN ''Project'' 
			WHEN ISNULL(p.GLCompanySource,0) = 1 THEN ''Person'' 
			ELSE ''Project''
		END AS [Revenue Source]
	,pr.DateSentForApproval as [Date Sent For Approval]
	,pr.RequestedBy as [Requested By]
	,(SELECT MAX(ti.WorkDate) FROM tTime ti (NOLOCK) WHERE ti.ProjectKey = p.ProjectKey) as [Last Date Worked]
	,put.TeamName as [Account Team]	
	
/* 
	,(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(TotalCost), 0) from tMiscCost (nolock) Where tMiscCost.ProjectKey = p.ProjectKey) +  
	 (Select ISNULL(Sum(ActualCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ProjectKey = p.ProjectKey) +  
	 (Select ISNULL(Sum(TotalCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ProjectKey = p.ProjectKey) as [Actual Net 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 Sum(ISNULL(TotalCost, 0) - ISNULL(AppliedCost, 0)) from tPurchaseOrderDetail (nolock) inner join tPurchaseOrder (nolock) on tPurchaseOrderDetail.PurchaseOrderKey = tPurchaseOrder.PurchaseOrderKey 
		 Where tPurchaseOrderDetail.ProjectKey = p.ProjectKey and tPurchaseOrderDetail.Closed = 0) as [Open Purchase Orders] 
	,(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] 
	,(Select ISNULL(Sum(ROUND(ActualHours * CostRate, 2)), 0) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) - ISNULL(p.BudgetLabor, 0) as [Labor Variance Net] 
	,((Select ISNULL(Sum(TotalCost), 0) from tMiscCost (nolock) Where tMiscCost.ProjectKey = p.ProjectKey) +  
	 (Select ISNULL(Sum(ActualCost), 0) from tExpenseReceipt (nolock) Where tExpenseReceipt.ProjectKey = p.ProjectKey) +  
	 (Select ISNULL(Sum(TotalCost), 0) from tVoucherDetail (nolock) Where tVoucherDetail.ProjectKey = p.ProjectKey)) - ISNULL(p.BudgetExpenses, 0) as [Expense Variance Net] 
	,(Select ISNULL(Sum(ROUND(ActualHours * ActualRate, 2)), 0) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) - ISNULL(p.EstLabor, 0) as [Labor Variance Gross] 
	,((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)) - ISNULL(p.EstExpenses, 0) as [Expense Variance Gross] 
*/ 
    ,i.LastBilledDate AS [Last Billed Date]
	,splits.TotalPercentageSplit as [Total Percentage Split]
	,CASE
		WHEN p.RetainerKey = NULL THEN ''N/A''
		WHEN p.RetainerKey IS NOT NULL AND ISNULL(rn.Active,0) = 1 THEN ''YES''
		WHEN p.RetainerKey IS NOT NULL AND ISNULL(rn.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]
	 ,projectAllocated.ProjectGrossAllocated as [Total Allocated Gross]
	 
	 ,roll.ScheduleAdherance as [Schedule Adherance]
	 ,roll.EffortVariance as [Effort Variance]
	 ,roll.ProjectPerformance as [Project Performance]
	 ,Case when ISNULL(p.ScheduleLockedByKey, 0) > 1 then ''YES'' else ''NO'' end as [Locked Schedule]
	 ,gl.GLCompanyName as [GL Company]
	 ,Case p.OverrideScheduleOptions When 1 then ''YES'' else ''NO'' end as [Override Company Schedule Options]
	 ,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]
	 ,terms.TermsDescription as [Payment Terms]
	 ,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 (nolock) 
	inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey 
	left outer join tGLCompany gl (nolock) on p.GLCompanyKey = gl.GLCompanyKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey 
	left outer join tCompany parentCompany (nolock) on cl.ParentCompanyKey = parentCompany.CompanyKey 
	left outer join tClientDivision pcd (nolock) on cl.ParentCompanyDivisionKey = pcd.ClientDivisionKey 
	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 tUser csp (nolock) on cl.SalesPersonKey = csp.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 clientam (nolock) on cl.AccountManagerKey = clientam.UserKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey 
	left outer join vUserName campam (nolock) on cp.AEKey = campam.UserKey 
	left outer join tRequest pr (nolock) on pr.RequestKey = p.RequestKey 
	left outer join vUserName kp1 (nolock) on p.KeyPeople1 = kp1.UserKey 
	left outer join vUserName kp2 (nolock) on p.KeyPeople2 = kp2.UserKey 
	left outer join vUserName kp3 (nolock) on p.KeyPeople3 = kp3.UserKey 
	left outer join vUserName kp4 (nolock) on p.KeyPeople4 = kp4.UserKey 
	left outer join vUserName kp5 (nolock) on p.KeyPeople5 = kp5.UserKey 
	left outer join vUserName kp6 (nolock) on p.KeyPeople6 = kp6.UserKey 
	left outer join tRetainer rn (nolock) on p.RetainerKey = rn.RetainerKey 
	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 tTimeRateSheet trs (nolock) on p.TimeRateSheetKey = trs.TimeRateSheetKey 
	left outer join tTitleRateSheet tirs (nolock) on p.TitleRateSheetKey = tirs.TitleRateSheetKey 
    left outer join vCampaignSummary vcs (nolock) on p.CampaignKey = vcs.CampaignKey 
	left outer join tCompanyType ct (nolock) on cl.CompanyTypeKey = ct.CompanyTypeKey 
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey  
	left outer join tLead l (nolock) on p.LeadKey = l.LeadKey 
	left outer join tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey 
	left outer join tSource source (nolock) on cl.SourceKey = source.SourceKey 
	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 tProject sp (nolock) on p.SourceProjectKey = sp.ProjectKey 
	left outer join vCampaignAdvanceBilled vab (nolock) on cp.CampaignKey = vab.CampaignKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey 
	left outer join tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey
	left outer join tTeam put (nolock) on p.TeamKey = put.TeamKey
	left outer join tPaymentTerms terms (nolock) on cl.PaymentTermsKey = terms.PaymentTermsKey
	left outer join tActionLog al ON p.ProjectKey = al.EntityKey AND Action = ''Project Made Live''
	left outer join (
	                 SELECT MAX(InvoiceDate) AS LastBilledDate, ProjectKey
                     FROM (
					        SELECT InvoiceDate, ProjectKey
							FROM tInvoice i1 (nolock)
							UNION
							SELECT InvoiceDate, il.ProjectKey
							FROM
								tInvoice i2 (nolock)
								INNER JOIN tInvoiceLine il (nolock) ON i2.InvoiceKey = il.InvoiceKey
							) i3
					GROUP BY i3.ProjectKey
				   ) i ON p.ProjectKey = i.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 (
				select sum(ISNULL(tuh.AHourlyRate, 0) * tuh.Hours) as ProjectGrossAllocated, tuh.ProjectKey 
				from vTaskUserHour tuh (nolock)
				group by tuh.ProjectKey			
	) as projectAllocated on p. ProjectKey = projectAllocated.ProjectKey	

	LEFT OUTER JOIN (
				SELECT	MAX(ISNULL(lastTask.ActComplete, '''')) AS LastActComplete, lastTask.ProjectKey
				FROM	tTask lastTask (nolock)
				LEFT OUTER JOIN
						(SELECT COUNT(*) AS OpenTaskCount, openTasks.ProjectKey
						FROM	tTask openTasks 
						WHERE	openTasks.ScheduleTask = 1
						AND		openTasks.TaskType = 2
						AND		openTasks.ActComplete IS NULL
						GROUP BY openTasks.ProjectKey) pOpenTask ON lastTask.ProjectKey = pOpenTask.ProjectKey
				INNER JOIN tProject pLastTask (nolock) ON lastTask.ProjectKey = pLastTask.ProjectKey
				WHERE	pLastTask.Template <> 1
				AND		(pLastTask.Closed = 1 OR ISNULL(pOpenTask.OpenTaskCount, 0) = 0)
				AND		lastTask.ScheduleTask = 1
				AND		lastTask.TaskType = 2
				AND		lastTask.ActComplete IS NOT NULL
				GROUP BY lastTask.ProjectKey) lastTaskActComplete ON p.ProjectKey = lastTaskActComplete.ProjectKey
	LEFT OUTER JOIN vUserName con (nolock) on cl.ContactOwnerKey = con.UserKey


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoGetTask]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoGetTask]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptAutoGetTask]
(
	@TaskKey int,
	@ServiceKey int
)

as


Select 
	ProjectNumber + '' - '' + ProjectName as ProjectFullName, 
	ProjectName,
	ProjectNumber,
	p.Description,
	cl.CompanyName,
	ps.ProjectStatus,
	am.FirstName as AMFirstName,
	pm.FirstName as PMFirstName,
	bm.FirstName as BMFirstName,
	am.UserKey as AMUserKey,
	am.Email as AMEmail,
	pm.UserKey as PMUserKey,
	pm.Email as PMEmail,
	bm.UserKey as BMUserKey,
	bm.Email as BMEmail,
	t.TaskName,
	t.TaskID,
	st.TaskName as SummaryTaskName,
	st.TaskID as SummaryTaskID,
	(SELECT STUFF((
        SELECT '', '' + u.UserName
        FROM vUserName u WITH (NOLOCK)
        INNER JOIN tTaskUser tu WITH (NOLOCK) ON tu.UserKey = u.UserKey
        WHERE t.TaskKey = tu.TaskKey
        FOR XML PATH(''''), TYPE
    ).value(''.'', ''NVARCHAR(MAX)''), 1, 2, '''')
) AS AssignedTo

from tProject p (nolock)
inner join tTask t (nolock) on p.ProjectKey = t.ProjectKey
left outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey
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 tUser bm (nolock) on p.BillingManagerKey = bm.UserKey
left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
left outer join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey

Where t.TaskKey = @TaskKey

Declare @ProjectKey int
Select @ProjectKey = ProjectKey from tProject (nolock) Where ProjectKey = @ProjectKey

-- get the project team.
Select UserName, a.UserKey, Email From vUserName u
inner join tAssignment a on u.UserKey = a.UserKey
Where a.ProjectKey = @ProjectKey and Email is not null

-- get people assigned to a service.
if @ServiceKey is not null
	Select UserName, u.UserKey, Email From vUserName u (nolock)
	inner join tTaskUser tu (nolock) on u.UserKey = tu.UserKey
	Where tu.TaskKey = @TaskKey and tu.ServiceKey = @ServiceKey and Email is not null'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptVoucherDetailGetList]'
GO
IF OBJECT_ID(N'[dbo].[sptVoucherDetailGetList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptVoucherDetailGetList]
	@VoucherKey int

AS --Encrypt

/*
|| When     Who Rel     What
|| 02/19/08 GHL 8.5     (21547) Sorting now by VoucherDetailKey because users complain about change of
||                       position of the lines
|| 08/27/09 GHL 10.5    Added filter on TransferToKey NULL
|| 04/04/11 MFT 10.542  Added ProjectName, TaskName and ItemName
|| 08/11/11 GHL 10.547  Added CustomerID, ClientName + DepartmentName + OfficeID + OfficeName for flex lookups
|| 09/09/11 GHL 10.547  Added TotalCostWithTax for CreditCardEdit.mxml
|| 12/05/11 GHL 10.550  Added POKind to help out with the commissions/markups + PurchaseOrderKey
|| 12/08/11 GHL 10.550  Added PO info required for prebilled logic
|| 12/12/11 GHL 10.550  Corrected PO Cost fields 
|| 12/29/11 GHL 10.551  Added project costing info similarly to sptVoucherDetailGet for Flex app
|| 01/18/12 GHL 10.552  Added InvoiceNumber and BillingID and MarkedBilled to show on grids
|| 05/11/12 GHL 10.556  (142898) Added InvoiceNumber for the prebilled PO
|| 05/21/12 GHL 10.556  Addd Company ID/Name for TargetGLCompanyKey
|| 06/29/12 GHL 10.557  Added ProjectGLCompanyKey to help with validations
|| 09/22/12 GHL 10.560  (153619) Added po PODate pod DetailOrderDate and DetailOrderEndDate + pod BillableCost
||                      to show on voucher flex screen 
|| 12/14/12 GHL 10.563  Added Line + Adjustment field for POD flex lookup
|| 04/17/12 GHL 10.567  Added POLineAdjustment to help out with Media Accrued Order issues
|| 04/30/12 GHL 10.567  Added POLinkID to help out with Media Accrued Order issues
|| 10/15/13 GHL 10.573  Changes for GrossAmount
|| 10/30/13 GHL 10.573  Added AppliedPTotalCost = sum of vd.PTotalCost applied to a POD (needed for multi currency)  
|| 10/22/14 GHL 10.585 (228260) When closing, mark as billed, when opening, mark as unbilled
||                      For this reason, look at InvoiceLineKey to calculate POAmountBilled
|| 02/11/15 GHL 10.589  Added media worksheet info for the new media screens
|| 02/25/15 GHL 10.589  Added MORE media worksheet info for the new media screens
|| 10/20/15 GHL 10.597  (260241) order by display order (lines can be now rearranged by a display order)
|| 11/24/15 MCM 10.598  Added other tax so can display on the approval screen
|| 08/24/16 GHL 10.607  Returning now voucher exchange rate and PGrossAmount (gross in project currency) 
|| 09/02/16 GHL 10.607  Added GLCompanyKey from the header for the wjapp lookup
|| 09/14/16 GHL 10.608  Added WIP and Billed posting dates, AccruedCost for the new wjapp screen
|| 10/11/16 GHL 10.608  Added PurchaseOrderLineNumber for API
|| 01/23/19 GHL 19.200  (441872) Added Class Name to display on grid correctly
|| 12/27/19 MCM 20.010  (493821) On the DetailOrderDate, if no PO, then pull the source date from the voucherDetail
|| 01/08/20 GHL 20.020  Added MediaPlanVendorKey for drill down to the media plan vendor page
|| 04/03/20 GHL 20.040  (451878) Added the currency ID of the TargetGLCompanyKey
|| 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  
|| 07/07/22 GHL 22.08.00 (604152) Added support of custom fields ...returning FieldSetName
|| 06/21/23 MAS 23.07.16 Removed old media references, tMediaOrder, tMediaWorksheet
|| 06/04/24 MCM 24.07.14 (631574) added project expense active to determine if can void a voucher
|| 11/15/24 MFT 24.12.00 (687751) added UseMarkup
|| 05/07/26 MFT 26.070  (728174) Added table variable @tVoucherDetail to improve performance
*/

declare @GLCompanyKey int
declare @ExchangeRate decimal(24, 7) -- This is the vendor exchange rate

select @ExchangeRate = isnull(ExchangeRate, 1),  @GLCompanyKey = GLCompanyKey
from tVoucher (nolock) where VoucherKey = @VoucherKey

if @ExchangeRate <= 0
	select @ExchangeRate = 1

DECLARE @tVoucherDetail table (
		VoucherDetailKey int,
		TotalCost money,
		PurchaseOrderDetailKey int,
		PTotalCost money,
		PExchangeRate decimal(24, 7),
		GrossAmount money
	)
	
INSERT INTO @tVoucherDetail
SELECT
	vd.VoucherDetailKey,
	vd.TotalCost,
	vd.PurchaseOrderDetailKey,
	vd.PTotalCost,
	vd.PExchangeRate,
	vd.GrossAmount
FROM
	tVoucherDetail vd (nolock)
WHERE	VoucherKey = @VoucherKey

INSERT INTO @tVoucherDetail
SELECT
	vd.VoucherDetailKey,
	vd.TotalCost,
	vd.PurchaseOrderDetailKey,
	vd.PTotalCost,
	vd.PExchangeRate,
	vd.GrossAmount
FROM
	tVoucherDetail vd (nolock)
	INNER JOIN tPurchaseOrderDetail pod (nolock) ON vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
	INNER JOIN @tVoucherDetail vd2 ON pod.PurchaseOrderDetailKey = vd2.PurchaseOrderDetailKey
WHERE
	vd.VoucherDetailKey NOT IN (
		SELECT VoucherDetailKey FROM @tVoucherDetail
	)

SELECT vd.*
		,po.PurchaseOrderKey
		,po.PurchaseOrderNumber
		,po.POKind
		,po.PODate
		,pod.LineNumber AS POLineNumber
		,pod.LineNumber AS PurchaseOrderLineNumber
		,pod.AdjustmentNumber As POAdjustmentNumber
		,ISNULL(fs.FieldSetName, ''General'') AS FieldSetName
		,ISNULL(fs.FieldSetKey, 0) AS FieldSetKey 
		,ISNULL(pod.DetailOrderDate, vd.SourceDate) as DetailOrderDate
		,pod.DetailOrderEndDate
		,p.ProjectNumber
		,p.ProjectName
		,p.GetMarkupFrom
		,p.ItemRateSheetKey
		,p.GLCompanyKey as ProjectGLCompanyKey
		,ps.ExpenseActive as ProjectExpenseActive
		,t.TaskID
		,t.TaskName
		,gl.AccountNumber
		,gl.AccountName
		,cl.ClassID
		,cl.ClassName
		,i.ItemID
		,i.ItemName
		,i.UseMarkup
		
		,mrr.ReasonID 				
		,c.CustomerID
		,c.CompanyName as ClientName
		,d.DepartmentName
		,o.OfficeID
		,o.OfficeName

		,glc.GLCompanyID
		,glc.GLCompanyName
		,glc.CurrencyID as GLCCurrencyID

		,isnull(vd.TotalCost, 0) + isnull(vd.SalesTaxAmount, 0) as TotalCostWithTax

		-- POD info required for prebilled logic in Flex...similar to sptVoucherDetailGet
		,pod.TotalCost as POTotalCost
		,case when pod.InvoiceLineKey > 0 then pod.AmountBilled else 0 end as POAmountBilled
		,pod.BillableCost as POBillableCost
		,pod.AccruedCost

		,ISNULL((SELECT SUM(vd2.TotalCost)
						FROM @tVoucherDetail vd2
						WHERE vd2.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey -- same POD
						AND   vd2.VoucherDetailKey <> vd.VoucherDetailKey             -- but diff VD
						), 0) AS POOtherAppliedCost 

		-- this must be calculated in the project currency
		,ISNULL((SELECT SUM(
							case when isnull(vd2.PExchangeRate, 0) = 0
							then round((vd2.GrossAmount * @ExchangeRate), 2)
							else round((vd2.GrossAmount * @ExchangeRate) / vd2.PExchangeRate, 2)
						    end
							) 
			   			FROM @tVoucherDetail vd2
						WHERE vd2.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey -- same POD
						AND   vd2.VoucherDetailKey <> vd.VoucherDetailKey             -- but diff VD
						), 0) AS POOtherAppliedBillableCost 
		,ISNULL((SELECT SUM(vd2.PTotalCost) 
			   			FROM @tVoucherDetail vd2
						WHERE vd2.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey -- same POD
						AND   vd2.VoucherDetailKey <> vd.VoucherDetailKey             -- but diff VD
						), 0) AS POOtherAppliedPTotalCost 

		,inv.InvoiceKey
		,inv.InvoiceNumber as BilledInvoiceNumber
	    ,inv.Posted as BilledInvoicePosted
		,inv.PostingDate  as BilledInvoicePostingDate
			
		,case when isnull(inv.InvoiceKey, 0) = 0 then bill.BillingKey else 0 end as BillingKey
		,case when isnull(inv.InvoiceKey, 0) = 0 then 
			case when bill.BillingID is null then ''''
			else cast (bill.BillingID as varchar(50)) end  
		else '''' end as BillingID 
		,case when vd.InvoiceLineKey = 0 then 1 else 0 end as MarkedBilled  

		,pod_inv.InvoiceKey as PrebilledInvoiceKey
		,pod_inv.InvoiceNumber as PrebilledInvoiceNumber
	
		, po.PurchaseOrderNumber 
		+ '' '' + cast(pod.LineNumber as varchar(20)) 
		+ ''.'' + isnull(cast(pod.AdjustmentNumber as varchar(20)), ''0'') 
		as POLineAdjustment
		, pod.LinkID as POLinkID
		,isnull(po.BillAt, 0) as BillAt
		,case when po.BillAt = 0 then ''Gross''
			  when po.BillAt = 1 then ''Net''
			  when po.BillAt = 2 then ''Commission''
			  else ''''
		end as BillAtDescription
		,po.MediaWorksheetKey
		,po.InternalID
		,ISNULL(vd.SalesTaxAmount, 0) - ISNULL(vd.SalesTax1Amount, 0) - ISNULL(vd.SalesTax2Amount, 0)  as OtherTax

		,@ExchangeRate as VoucherExchangeRate
		,case when isnull(vd.PExchangeRate, 0) <= 0 then round((isnull(vd.GrossAmount, 0) * @ExchangeRate), 2)
		      else round((isnull(vd.GrossAmount, 0) * @ExchangeRate) / vd.PExchangeRate, 2)
		end as PGrossAmount -- Gross Amount expressed in project currency 
		
		,@GLCompanyKey as GLCompanyKey -- for the wjapp lookups

		,wpi.PostingDate as WIPInPostingDate
		,wpo.PostingDate as WIPOutPostingDate

		,mpd.SpotLinkID
		,mpd.MediaPlanDetailKey
		,mpd.MediaPlanVendorKey -- for drill down to the media plan vendor page
		,cm.StationID + ''-'' + cm.Name as PubName


FROM tVoucherDetail vd (NOLOCK)
	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 tProject p (NOLOCK) ON vd.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tProjectStatus ps (NOLOCK) on p.ProjectStatusKey = ps.ProjectStatusKey
	LEFT OUTER JOIN tTask t (NOLOCK) ON vd.TaskKey = t.TaskKey 
	LEFT OUTER JOIN tGLAccount gl (nolock) on vd.ExpenseAccountKey = gl.GLAccountKey
	LEFT OUTER JOIN tClass cl (nolock) on vd.ClassKey = cl.ClassKey	
	LEFT OUTER JOIN tItem i (nolock) on vd.ItemKey = i.ItemKey
	left outer join tMediaRevisionReason mrr (nolock) on pod.MediaRevisionReasonKey = mrr.MediaRevisionReasonKey
	left outer join tCompany c (nolock) on vd.ClientKey = c.CompanyKey		
	left outer join tDepartment d (nolock) on vd.DepartmentKey = d.DepartmentKey
	left outer join tOffice o (nolock) on vd.OfficeKey = o.OfficeKey
	left outer join tGLCompany glc (nolock) on vd.TargetGLCompanyKey = glc.GLCompanyKey 

	left outer join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
	left outer join tInvoice inv (nolock) on il.InvoiceKey = inv.InvoiceKey

	left outer join tInvoiceLine pod_il (nolock) on pod.InvoiceLineKey = pod_il.InvoiceLineKey
	left outer join tInvoice pod_inv (nolock) on pod_il.InvoiceKey = pod_inv.InvoiceKey

	left outer join (
		select max(b.BillingKey) as BillingKey, max(b.BillingID) as BillingID, vd2.VoucherDetailKey
		from   tBillingDetail bd (nolock)
		inner join tBilling b (nolock) on bd.BillingKey = b.BillingKey
		inner join tVoucherDetail vd2 (nolock) on bd.EntityKey = vd2.VoucherDetailKey
		where b.Status < 5 -- not invoiced
		and  bd.Entity = ''tVoucherDetail''
		and  vd2.VoucherKey = @VoucherKey
		group by vd2.VoucherDetailKey
	) as bill on bill.VoucherDetailKey = vd.VoucherDetailKey

	left outer join tWIPPosting wpi (nolock) on vd.WIPPostingInKey = wpi.WIPPostingKey
	left outer join tWIPPosting wpo (nolock) on vd.WIPPostingOutKey = wpo.WIPPostingKey

	left outer join tMediaPlanVoucherDetail mpvd (nolock) on vd.MediaPlanVoucherDetailKey = mpvd.MediaPlanVoucherDetailKey
	left outer join tMediaPlanDetail mpd (nolock) on mpvd.MediaPlanDetailKey = mpd.MediaPlanDetailKey  
	left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey

	left outer join tObjectFieldSet ofs (nolock) on vd.CustomFieldKey = ofs.ObjectFieldSetKey
	left outer join tFieldSet fs (nolock) on fs.FieldSetKey = ofs.FieldSetKey

WHERE vd.VoucherKey = @VoucherKey
AND   vd.TransferToKey IS NULL
ORDER BY vd.DisplayOrder, vd.VoucherDetailKey	

RETURN 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tAutoRuleTarget]'
GO
IF OBJECT_ID(N'[dbo].[tAutoRuleTarget]', 'U') IS NULL
CREATE TABLE [dbo].[tAutoRuleTarget]
(
[RuleKey] [int] NOT NULL,
[Entity] [varchar] (50) NOT NULL,
[EntityKey] [int] NOT NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tAutoRuleTarget] on [dbo].[tAutoRuleTarget]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tAutoRuleTarget]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tAutoRuleTarget]', 'U'))
ALTER TABLE [dbo].[tAutoRuleTarget] ADD CONSTRAINT [PK_tAutoRuleTarget] PRIMARY KEY CLUSTERED ([RuleKey], [Entity], [EntityKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tAutoRule]'
GO
IF OBJECT_ID(N'[dbo].[tAutoRule]', 'U') IS NULL
CREATE TABLE [dbo].[tAutoRule]
(
[RuleKey] [int] NOT NULL IDENTITY(1, 1),
[CompanyKey] [int] NOT NULL,
[Name] [varchar] (300) NOT NULL,
[Description] [varchar] (max) NULL,
[Scope] [varchar] (50) NULL,
[Active] [tinyint] NULL,
[IsDeleted] [tinyint] NULL,
[CreatedBy] [int] NOT NULL,
[DateCreated] [smalldatetime] NOT NULL CONSTRAINT [DF_tAutoRule_DateCreated] DEFAULT (getutcdate()),
[UpdatedBy] [int] NOT NULL,
[DateUpdated] [smalldatetime] NOT NULL CONSTRAINT [DF_tAutoRule_DateUpdated] DEFAULT (getutcdate()),
[Version] [int] NOT NULL,
[Private] [tinyint] NOT NULL CONSTRAINT [DF_tAutoRule_Private] DEFAULT ((0)),
[Event] [varchar] (50) NOT NULL,
[NextRunTime] [datetime] NULL,
[Options] [nvarchar] (max) NULL,
[Conditions] [nvarchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tAutoRule] on [dbo].[tAutoRule]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tAutoRule]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tAutoRule]', 'U'))
ALTER TABLE [dbo].[tAutoRule] ADD CONSTRAINT [PK_tAutoRule] PRIMARY KEY CLUSTERED ([RuleKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tAutoRule] on [dbo].[tAutoRule]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tAutoRule' AND object_id = OBJECT_ID(N'[dbo].[tAutoRule]'))
CREATE NONCLUSTERED INDEX [IX_tAutoRule] ON [dbo].[tAutoRule] ([CompanyKey]) INCLUDE ([Active], [IsDeleted])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tAutoAction]'
GO
IF OBJECT_ID(N'[dbo].[tAutoAction]', 'U') IS NULL
CREATE TABLE [dbo].[tAutoAction]
(
[ActionKey] [int] NOT NULL IDENTITY(1, 1),
[RuleKey] [int] NOT NULL,
[ActionType] [varchar] (50) NOT NULL,
[DisplayOrder] [int] NOT NULL,
[Options] [varchar] (max) NULL,
[ApiHookKey] [int] NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tAutoAction] on [dbo].[tAutoAction]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tAutoAction]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tAutoAction]', 'U'))
ALTER TABLE [dbo].[tAutoAction] ADD CONSTRAINT [PK_tAutoAction] PRIMARY KEY CLUSTERED ([ActionKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleTargetGetProjectRules]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleTargetGetProjectRules]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[sptAutoRuleTargetGetProjectRules]
	@ProjectKey int = NULL,
	@TaskKey int = NULL,
	@Event varchar(50)
AS
/*
|| When     Who Rel      What
|| 03/04/26 CRG 26.04.19 Created
*/

	DECLARE	@Scope varchar(50),
			@CompanyKey int,
			@ProjectTypeKey int,
			@ProjectStatusKey int,
			@ClientKey int,
			@CampaignKey int

	IF @TaskKey IS NOT NULL
		SELECT	@Scope = ''task'',
				@ProjectKey = ProjectKey
		FROM	tTask (nolock)
		WHERE	TaskKey = @TaskKey
	ELSE
		SELECT	@Scope = ''project''

	SELECT	@CompanyKey = CompanyKey,
			@ProjectTypeKey = ProjectTypeKey,
			@ProjectStatusKey = ProjectStatusKey,
			@ClientKey = ClientKey,
			@CampaignKey = CampaignKey
	FROM	tProject (nolock)
	WHERE	ProjectKey = @ProjectKey

	SELECT	r.RuleKey, ISNULL(rt.Entity, ''all'') AS Entity, ISNULL(rt.EntityKey, 0) AS EntityKey
	INTO	#Targets
	FROM	tAutoRule r (nolock)
	LEFT JOIN tAutoRuleTarget rt (nolock) ON r.RuleKey = rt.RuleKey
	WHERE	r.CompanyKey = @CompanyKey
	AND		r.Active = 1
	AND		ISNULL(r.IsDeleted, 0) = 0
	AND		r.Scope = @Scope
	AND		r.Event = @Event

	DELETE	#Targets
	WHERE	Entity = ''projectType''
	AND		EntityKey <> @ProjectTypeKey

	DELETE	#Targets
	WHERE	Entity = ''projectStatus''
	AND		EntityKey <> @ProjectStatusKey

	DELETE	#Targets
	WHERE	Entity = ''client''
	AND		EntityKey <> @ClientKey
	
	DELETE	#Targets
	WHERE	Entity = ''campaign''
	AND		EntityKey <> @CampaignKey

	DELETE	#Targets
	WHERE	Entity = ''project''
	AND		EntityKey <> @ProjectKey

	SELECT DISTINCT	r.*
	FROM	tAutoRule r (nolock)
	INNER JOIN #Targets t ON r.RuleKey = t.RuleKey
	ORDER BY r.RuleKey

	SELECT DISTINCT	a.*
	FROM	tAutoAction a (nolock)
	INNER JOIN #Targets t ON a.RuleKey = t.RuleKey
	ORDER BY a.RuleKey, a.DisplayOrder'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptProjectUpdateProjectDates]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectUpdateProjectDates]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[sptProjectUpdateProjectDates]
	@ProjectKey int,
	@StartDate smalldatetime = NULL,
	@CompleteDate smalldatetime = NULL
AS
/*
|| When      Who Rel      What
|| 03/10/26  CRG 25.04.19 Created
*/

	IF @StartDate IS NOT NULL
		UPDATE	tProject
		SET		StartDate = @StartDate
		WHERE	ProjectKey = @ProjectKey

	IF @CompleteDate IS NOT NULL
		UPDATE	tProject
		SET		CompleteDate = @CompleteDate
		WHERE	ProjectKey = @ProjectKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_Deliverables_By_Appover]'
GO
IF OBJECT_ID(N'[dbo].[vReport_Deliverables_By_Appover]', 'V') IS NOT NULL
EXEC sp_executesql N'

ALTER VIEW [dbo].[vReport_Deliverables_By_Appover]
AS

/*
|| When      Who Rel       What
|| 05/12/23  RLB 23.06.18  (633222) Created to display active approvers on active step on a round
|| 08/16/23  RLB 23.09.17 (648008) added type and status color
|| 04/20/26  RLB 26.05.17  (726348) Added Union since projectkey can mean project or campaign dependant on +- number
*/

SELECT asu.ApprovalStepUserKey
	,aps.ApprovalStepKey
	,asu.DateActivated as [Date Activated]
	,asu.DueDate as [Assigned User Due Date]
	,asu.Comments 
	,rd.ReviewDeliverableKey
	,rd.OwnerKey 
	,rd.CompanyKey	
	,rr.ReviewRoundKey
	,p.GLCompanyKey
	,p.ProjectKey
	,rd.Description AS [Description]
	,rd.DeliverableName AS [Deliverable Name]
	,p.ProjectNumber AS [Project Number]
	,p.ProjectName AS [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name]
	,aun.UserFullName as [Approver Name]
	,pm.UserFullName as [Project Manager]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' '' + c.CompanyName as [Client Full Name]
	,rr.RoundName AS [Current Round]
	,Case aps.EnableRouting
		WHEN 1 THEN ''In Order''
		WHEN 0 THEN ''Everyone''
	 END AS [Routing]
	,CASE aps.Internal 
		WHEN 1 THEN ''Internal''
		WHEN 0 THEN ''External''
	 END AS [Current Step]
	 ,CASE ISNULL(aps.Pause,0)
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Paused]
	 ,CASE aps.LoginRequired
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Login Required]
	 ,CASE aps.AllApprove
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Everyone Must Review]
	 ,CASE rd.Approved
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Approved]
	 ,rd.DueDate as [Deliverable Date Due]
	 ,rd.ApprovedDate as [Deliverable Date Approved]
	,rr.DateSent AS [Round Date Sent]
	,Case When aps.ActiveStep = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Reviewing'' end
	 Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		Else 
			Case 
				When rr.Status = 5 then case rr.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
				When rr.Status = 4 then ''Cancelled''  
				When rr.Status = 6 then ''Paused'' 
				When rr.Status = 3 then ''Resubmit''
				When rr.Status = 2 then ''Not Sent''
				When rr.Status IS NULL or rr.Status = 1 then ''Unsubmitted''
			End 
		End 
	 End as [Approval Status]
	,Case When aps.ActiveStep = 1 then aps.ApproverStatus 
	  Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		ELSE
			Case 
				When rr.Status = 5 then case rr.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
				When rr.Status = 4 then ''Cancelled''  
				When rr.Status = 6 then ''Paused'' 
				When rr.Status = 3 then ''Resubmit''
				When rr.Status = 2 then ''Not Sent''
				When rr.Status IS NULL or rr.Status = 1 then ''Unsubmitted''
			End 
		END
	End As [Approver Status]
	,am.UserFullName as [Account Manager]
	,do.UserFullName as [Deliverable Owner]
	,Case p.Active When 1 Then ''YES'' else ''NO'' end as [Active Project]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cp.ProductID as [Client Product ID]
    ,cp.ProductName as [Client Product]
	,rd.CustomFieldKey
	,p.CustomFieldKey as CustomFieldKey2 
	,ds.StatusName AS [Deliverable Status]
	,ds.StatusColor as [Deliverable_Status Color]
	,rd.DeliverableID AS [Deliverable ID]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign name]
	,dt.TypeName as [Deliverable Type]
	,dt.TypeColor as [Deliverable Type Color]
FROM tApprovalStepUser asu (NOLOCK)
INNER JOIN tApprovalStep aps (NOLOCK) on asu.ApprovalStepKey = aps.ApprovalStepKey and aps.Entity =''tReviewRound''
INNER JOIN tReviewRound rr (NOLOCK) on aps.EntityKey = rr.ReviewRoundKey
INNER JOIN tReviewDeliverable rd (NOLOCK) on rr.ReviewDeliverableKey = rd.ReviewDeliverableKey
left outer join tProject p (NOLOCK) ON rd.ProjectKey = p.ProjectKey
left outer join tCompany c (NOLOCK) on p.ClientKey = c.CompanyKey
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 tDeliverableStatus ds (nolock) on rd.DeliverableStatusKey = ds.DeliverableStatusKey
left outer join tDeliverableType dt (NOLOCK) on rd.DeliverableTypeKey = dt.DeliverableTypeKey
left outer join tCampaign ca (NOLOCK) on p.CampaignKey = ca.CampaignKey
left outer join vUserName aun (nolock) on asu.AssignedUserKey = aun.UserKey
left outer join vUserName pm (nolock) on p.ProjectManager = pm.UserKey
left outer join vUserName am (nolock) on p.AccountManager = am.UserKey
left outer join vUserName do (nolock) on rd.OwnerKey = do.UserKey
WHERE aps.ActiveStep = 1 
AND asu.ActiveUser = 1
and rd.ProjectKey > 0

UNION

SELECT asu.ApprovalStepUserKey
	,aps.ApprovalStepKey
	,asu.DateActivated as [Date Activated]
	,asu.DueDate as [Assigned User Due Date]
	,asu.Comments 
	,rd.ReviewDeliverableKey
	,rd.OwnerKey 
	,rd.CompanyKey	
	,rr.ReviewRoundKey
	,ca.GLCompanyKey
	,NULL
	,rd.Description AS [Description]
	,rd.DeliverableName AS [Deliverable Name]
	,'''' AS [Project Number]
	,'''' AS [Project Name]
	,'''' AS [Project Full Name]
	,aun.UserFullName as [Approver Name]
	,pm.UserFullName as [Project Manager]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' '' + c.CompanyName as [Client Full Name]
	,rr.RoundName AS [Current Round]
	,Case aps.EnableRouting
		WHEN 1 THEN ''In Order''
		WHEN 0 THEN ''Everyone''
	 END AS [Routing]
	,CASE aps.Internal 
		WHEN 1 THEN ''Internal''
		WHEN 0 THEN ''External''
	 END AS [Current Step]
	 ,CASE ISNULL(aps.Pause,0)
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Paused]
	 ,CASE aps.LoginRequired
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Login Required]
	 ,CASE aps.AllApprove
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Everyone Must Review]
	 ,CASE rd.Approved
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Approved]
	 ,rd.DueDate as [Deliverable Date Due]
	 ,rd.ApprovedDate as [Deliverable Date Approved]
	,rr.DateSent AS [Round Date Sent]
	,Case When aps.ActiveStep = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Reviewing'' end
	 Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		Else 
			Case 
				When rr.Status = 5 then case rr.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
				When rr.Status = 4 then ''Cancelled''  
				When rr.Status = 6 then ''Paused'' 
				When rr.Status = 3 then ''Resubmit''
				When rr.Status = 2 then ''Not Sent''
				When rr.Status IS NULL or rr.Status = 1 then ''Unsubmitted''
			End 
		End 
	 End as [Approval Status]
	,Case When aps.ActiveStep = 1 then aps.ApproverStatus 
	  Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		ELSE
			Case 
				When rr.Status = 5 then case rr.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
				When rr.Status = 4 then ''Cancelled''  
				When rr.Status = 6 then ''Paused'' 
				When rr.Status = 3 then ''Resubmit''
				When rr.Status = 2 then ''Not Sent''
				When rr.Status IS NULL or rr.Status = 1 then ''Unsubmitted''
			End 
		END
	End As [Approver Status]
	,am.UserFullName as [Account Manager]
	,do.UserFullName as [Deliverable Owner]
	,Case ca.Active When 1 Then ''YES'' else ''NO'' end as [Active Project]
	,'''' as [Client Division ID]
    ,'''' as [Client Division]
    ,'''' as [Client Product ID]
    ,'''' as [Client Product]
	,rd.CustomFieldKey
	,NULL as CustomFieldKey2 
	,ds.StatusName AS [Deliverable Status]
	,ds.StatusColor as [Deliverable_Status Color]
	,rd.DeliverableID AS [Deliverable ID]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign name]
	,dt.TypeName as [Deliverable Type]
	,dt.TypeColor as [Deliverable Type Color]
FROM tApprovalStepUser asu (NOLOCK)
INNER JOIN tApprovalStep aps (NOLOCK) on asu.ApprovalStepKey = aps.ApprovalStepKey and aps.Entity =''tReviewRound''
INNER JOIN tReviewRound rr (NOLOCK) on aps.EntityKey = rr.ReviewRoundKey
INNER JOIN tReviewDeliverable rd (NOLOCK) on rr.ReviewDeliverableKey = rd.ReviewDeliverableKey
left outer join tCampaign ca (NOLOCK) on ABS(rd.ProjectKey) = ca.CampaignKey
left outer join tCompany c (NOLOCK) on ca.ClientKey = c.CompanyKey
left outer join tDeliverableStatus ds (nolock) on rd.DeliverableStatusKey = ds.DeliverableStatusKey
left outer join tDeliverableType dt (NOLOCK) on rd.DeliverableTypeKey = dt.DeliverableTypeKey
left outer join vUserName aun (nolock) on asu.AssignedUserKey = aun.UserKey
left outer join vUserName pm (nolock) on ca.PMKey = pm.UserKey
left outer join vUserName am (nolock) on ca.AEKey = am.UserKey
left outer join vUserName do (nolock) on rd.OwnerKey = do.UserKey
WHERE aps.ActiveStep = 1 
AND asu.ActiveUser = 1
and rd.ProjectKey < 0




'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoActionUpdateApiHook]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoActionUpdateApiHook]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[sptAutoActionUpdateApiHook]
	@ActionKey int,
	@ApiHookKey int
AS
/*
|| When      Who Rel      What
|| 03/12/26  CRG 26.04.19 Created
*/

	UPDATE	tAutoAction
	SET		ApiHookKey = @ApiHookKey
	WHERE	ActionKey = @ActionKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tAutoEvent]'
GO
IF OBJECT_ID(N'[dbo].[tAutoEvent]', 'U') IS NULL
CREATE TABLE [dbo].[tAutoEvent]
(
[AutoEventKey] [int] NOT NULL IDENTITY(1, 1),
[RuleKey] [int] NOT NULL,
[EventDate] [datetime] NOT NULL CONSTRAINT [DF_tAutoEvent_EventDate] DEFAULT (sysutcdatetime()),
[CreatedByKey] [int] NOT NULL,
[Status] [varchar] (50) NULL,
[Errors] [varchar] (max) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tAutoEvent_1] on [dbo].[tAutoEvent]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tAutoEvent_1]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tAutoEvent]', 'U'))
ALTER TABLE [dbo].[tAutoEvent] ADD CONSTRAINT [PK_tAutoEvent_1] PRIMARY KEY CLUSTERED ([AutoEventKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoEventInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoEventInsert]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[sptAutoEventInsert]
	@RuleKey int,
	@UserKey int
AS

	INSERT	tAutoEvent
			(RuleKey,
			EventDate,
			CreatedByKey,
			Status)
	VALUES	(@RuleKey,
			GETUTCDATE(),
			@UserKey,
			''started'')

	RETURN @@IDENTITY
'
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

 */

-- 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_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_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"}
]''
	 , 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:"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].[spFixedFeesCampaignProjectList]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCampaignProjectList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spFixedFeesCampaignProjectList]
	(
	@CampaignKey int
	)
AS	--Encrypt

  /*
  || When     Who Rel		What
  || 12/02/10 GHL 10.539	Creation for campaign FF billing by project
  || 01/10/11 GHL 10.540	Instead of pulling all items/services for each project
  ||						Just display one line per project
  || 09/16/20 GHL 20.100	When calculating amount billed, exclude adv bill
  || 09/25/23 MFT 23.100	CAST Billed as decimal(24,4) to negate overflow error
  || 04/02/26 GAR 26.05.17	(722819) Added TotalGrossUnbilled
  */
  
	SET NOCOUNT ON
	
	declare @MultipleSegments int

	select @MultipleSegments = isnull(MultipleSegments, 0) 
	from   tCampaign (nolock)
	where  CampaignKey = @CampaignKey
	

	create table #project (
		ProjectKey int null
	    ,ProjectFullName varchar(1000) null

		,EstHours decimal(24, 4) null
		,EstLabor money null
		,EstExpenses money null

		,ActHours decimal(24, 4) null
		,ActLabor money null
		,ActExpenses money null

		,Billed money null
	
		,CampaignSegmentKey int null
		,DisplayOrder int identity(1,1)
		,TotalGrossUnbilled money null
		)

	-- First calculate budget and actual data
	insert #project (ProjectKey
		, ProjectFullName
		, EstHours
		, EstLabor
		, EstExpenses
		, CampaignSegmentKey
		)
	select ProjectKey, isnull(ProjectNumber, '''') + '' - '' + isnull(ProjectName, '''')
	    , isnull(EstHours, 0) + isnull(ApprovedCOHours, 0) 
		, isnull(EstLabor, 0) + isnull(ApprovedCOLabor, 0) 
		, isnull(EstExpenses, 0) + isnull(ApprovedCOExpense, 0) 
		, isnull(CampaignSegmentKey, 0)
	from   tProject (nolock)
	where  CampaignKey = @CampaignKey
	order by CampaignOrder, ProjectNumber

	update #project
	set				#project.ActHours = ISNULL((select sum(roll.Hours) 
					from tProjectRollup roll (nolock)
					Where roll.ProjectKey = #project.ProjectKey
					), 0) 
					
					,#project.ActLabor = ISNULL((select sum(roll.LaborGross) 
					from tProjectRollup roll (nolock)
					Where roll.ProjectKey = #project.ProjectKey
					), 0) 			

					,#project.ActExpenses = ISNULL((select sum(roll.ExpReceiptGross + roll.MiscCostGross + roll.VoucherGross + roll.OpenOrderGross) 
					from tProjectRollup roll (nolock)
					Where roll.ProjectKey = #project.ProjectKey
					), 0) 			

					,#project.Billed = ISNULL((SELECT SUM(CAST(isum.Amount AS decimal(24,4)))
						from tInvoiceSummary isum (NOLOCK)
						inner join tInvoice i (nolock) on isum.InvoiceKey = i.InvoiceKey
						WHERE isum.ProjectKey = #project.ProjectKey
						AND   i.AdvanceBill = 0
						), 0)

					,#project.TotalGrossUnbilled = ISNULL((select sum(roll.LaborUnbilled + roll.MiscCostUnbilled + roll.ExpReceiptUnbilled + roll.VoucherUnbilled + roll.OpenOrderUnbilled) 
					from tProjectRollup roll (nolock)
					Where roll.ProjectKey = #project.ProjectKey
					), 0) 	


	-- do not rely on display orders in db, create our own
	create table #segment (CampaignSegmentKey int null, SegmentName varchar(500) null, DisplayOrder int identity(1,1))  

	create table #line (
		Entity varchar(50) null
		,EntityKey int null
		,EntityName varchar(500) null
			
		,EstHours decimal(24, 4) null
		,EstLabor money null
		,EstExpenses money null
		,EstTotal money null

		,ActHours decimal(24, 4) null
		,ActLabor money null
		,ActExpenses money null
		,ActTotal money null

		,Billed money null
		,Remaining money null

		,LineKey INT IDENTITY(1,1)
		,ParentLineKey int null
		,DisplayOrder int null
		,TotalGrossUnbilled money null
		)

	if @MultipleSegments = 1
	begin
		if exists (select 1 from #project where CampaignSegmentKey = 0) 
		insert #segment (CampaignSegmentKey, SegmentName) values (0, ''No Segment'')

		insert #segment (CampaignSegmentKey, SegmentName)
		select CampaignSegmentKey, SegmentName
		from   tCampaignSegment (nolock)
		where  CampaignKey = @CampaignKey
		order  by DisplayOrder, SegmentName

		declare @DisplayOrder int
		declare @SegmentKey int
		declare @SegmentName varchar(500)
		declare @LineKey int

		select @DisplayOrder = -1
		while (1=1)
		begin
			select @DisplayOrder = min(DisplayOrder)
			from   #segment
			where  DisplayOrder > @DisplayOrder

			if @DisplayOrder is null
				break

			select @SegmentKey = CampaignSegmentKey
			      ,@SegmentName = SegmentName 
			from   #segment
			where  DisplayOrder = @DisplayOrder

			insert #line (Entity ,EntityKey ,EntityName ,ParentLineKey)
			select  ''tCampaignSegment'', @SegmentKey, @SegmentName, 0
			
			select @LineKey = LineKey from #line where Entity = ''tCampaignSegment'' and EntityKey = @SegmentKey
			 
			insert #line (Entity,EntityKey,EntityName ,EstHours ,EstLabor,EstExpenses,ActHours,ActLabor,ActExpenses,Billed,ParentLineKey,TotalGrossUnbilled)
			select ''tProject'', ProjectKey, ProjectFullName,EstHours ,EstLabor,EstExpenses,ActHours,ActLabor,ActExpenses,Billed, @LineKey, TotalGrossUnbilled
			from   #project
			where  CampaignSegmentKey =@SegmentKey
			order by DisplayOrder

		end
		
	end
	 
	if @MultipleSegments = 0
	begin
		insert #line (Entity,EntityKey,EntityName ,EstHours ,EstLabor,EstExpenses,ActHours,ActLabor,ActExpenses,Billed,ParentLineKey,TotalGrossUnbilled)
			select ''tProject'', ProjectKey, ProjectFullName,EstHours ,EstLabor,EstExpenses,ActHours,ActLabor,ActExpenses,Billed, 0,TotalGrossUnbilled
			from   #project
			order by DisplayOrder
	end

	--delete campaign segments without projects
	if @MultipleSegments = 1
		delete #line where #line.Entity = ''tCampaignSegment'' 
		and not exists (select 1 from #line b where b.Entity = ''tProject'' and b.ParentLineKey = #line.LineKey)  
			
	-- now manufacture a DisplayOrder, this is for the CMHierarchicalData
	declare @ProjectLineKey int

	if @MultipleSegments = 0
		update #line set DisplayOrder = LineKey

	if @MultipleSegments = 1
	begin
		-- do segments
		select @DisplayOrder = 1
		select @LineKey = -1
		while (1=1)
		begin
			select @LineKey = min(LineKey)
			from   #line
			where  ParentLineKey = 0
			and    LineKey > @LineKey

			if @LineKey is null
				break

			update #line set DisplayOrder = @DisplayOrder where LineKey = @LineKey
			set @DisplayOrder = @DisplayOrder + 1

		end

		-- do projects
		select @LineKey = -1
		while (1=1)
		begin
			select @LineKey = min(LineKey)
			from   #line
			where  ParentLineKey = 0
			and    LineKey > @LineKey

			if @LineKey is null
				break

			select @DisplayOrder = 1


			select @ProjectLineKey = -1
			while (1=1)
			begin
				select @ProjectLineKey = min(LineKey)
				from   #line
				where  ParentLineKey = @LineKey
				and    LineKey > @ProjectLineKey

				if @ProjectLineKey is null
					break

				update #line set DisplayOrder = @DisplayOrder where LineKey = @ProjectLineKey
				set @DisplayOrder = @DisplayOrder + 1

			end


		end

	end

	update #line 
	set    EstTotal = EstLabor + EstExpenses
	      ,ActTotal = ActLabor + ActExpenses  

	if @MultipleSegments = 1
		select * 
				,0 as [Percent]
				,0 as BillAmt
				,0 as Selected
				,LineKey as InvoiceOrder
				,case when Entity = ''tCampaignSegment'' then 1 else 2 end as LineType
				,case when Entity = ''tCampaignSegment'' then 0 else 1 end as LineLevel
		from #line
		order by LineKey
	else
		select * 
				,0 as [Percent]
				,0 as BillAmt
				,0 as Selected
				,LineKey as InvoiceOrder
				,2 as LineType
				,0 as LineLevel
		from #line
		order by LineKey
	

		 
	--select * from #project
	--select * from #segment
											
	RETURN 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spRptGLTrialBalanceCurrency]'
GO
IF OBJECT_ID(N'[dbo].[spRptGLTrialBalanceCurrency]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spRptGLTrialBalanceCurrency]
(
	@CompanyKey int,
	@AsOfDate smalldatetime,
	@CashBasis int = 0,
	@UserKey int = null,
	@RunInGLCHomeCurrency int = 0 -- 0 run in main home curr, 1 run in the home currency of the GL company
)

AS --Encrypt

/*
|| When      Who Rel     What
|| 03/03/14  GHL 10.577  Creation. Cloned spRptGLTrialBalance and modfied for multi currency (bank revaluation)
|| 03/11/14  GHL 10.578  Removed creation of rate tables, this is passed now from the UI
|| 03/20/14  GHL 10.578  Added Adv Bill account to revalue
|| 11/13/14  GHL 10.586  (236437) Fixed calc of RE amounts (was commented out by mistake)
|| 02/16/17  GHL 10.613  Instead of pulling transactions for the AdvBillAccountKey only, pull gl accounts
||                       where RevalueCurrency = 1 (adv bill + 2 prepayment accounts)
|| 04/09/18  GHL 18.500  (395225) After doing the currency revaluation, the threshold to determine adding or subtracting
||                       should be 20, not 11. Because this is what spRptBalanceSheetRevaluation does
|| 11/05/24  MCM 24.12x (673149) Added param @RunInGLCHomeCurrency to support GL comp with different currency
|| 02/27/26  AMP 6.03.15 (713493) Added ''Active'' flag to filter out the inactive/zero accounts
*/

-- Calculate the beginning of fiscal year
Declare @BeginningDate smalldatetime
Declare @FirstMonth int
Declare @FirstYear int
Declare @AdvBillAccountKey int -- we will revalue the adv bill account 
Declare @GLCHomeCurrencyID varchar(10) -- Home currency of the GL company
Declare @MainHomeCurrencyID varchar(10) -- Home currency of the main company
Declare @GLCompanyKey int

Select @FirstMonth = ISNULL(FirstMonth, 1) 
	,@AdvBillAccountKey = AdvBillAccountKey
	,@MainHomeCurrencyID = CurrencyID
from tPreference (nolock) Where CompanyKey = @CompanyKey

Select @FirstYear = Year(@AsOfDate)
if @FirstMonth > Month(@AsOfDate)
	Select @FirstYear = @FirstYear - 1
	
Select @BeginningDate = Cast(Cast(@FirstMonth as Varchar) + ''/1/'' + cast(@FirstYear as Varchar) as smalldatetime)

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)

--To allow sp to be called as a stand alone
IF OBJECT_ID(''tempdb..#GLCompanyKeys'') IS NULL
	BEGIN
		CREATE TABLE #GLCompanyKeys(GLCompanyKey int NOT NULL PRIMARY KEY)
	END
IF OBJECT_ID(''tempdb..#ClassKeys'') IS NULL
	BEGIN
		CREATE TABLE #ClassKeys(ClassKey int NOT NULL PRIMARY KEY)
	END

--If filtered in the UI, selected keys
--will be there, otherwise insert all
DECLARE @GLCount int
SELECT @GLCount = COUNT(*) FROM #GLCompanyKeys
IF @GLCount = 0
	BEGIN
		IF @RestrictToGLCompany = 0
			BEGIN
				INSERT INTO #GLCompanyKeys VALUES(0)
				INSERT INTO #GLCompanyKeys
				SELECT Distinct GLCompanyKey
				FROM tTransaction (nolock) 
				WHERE CompanyKey = @CompanyKey and GLCompanyKey is not null and GLCompanyKey <> 0
			END
		ELSE
			INSERT INTO #GLCompanyKeys
			SELECT GLCompanyKey
			FROM tUserGLCompanyAccess (nolock)
			WHERE UserKey = @UserKey
	END
DECLARE @ClassCount int
SELECT @ClassCount = COUNT(*) FROM #ClassKeys
IF @ClassCount = 0
	BEGIN
		INSERT INTO #ClassKeys VALUES(0)
		INSERT INTO #ClassKeys
		SELECT Distinct ClassKey
		FROM tTransaction (nolock)
		WHERE CompanyKey = @CompanyKey and ClassKey is not null and ClassKey <> 0
	END

Declare @GLAccountKey int
Declare @AccountNumber varchar(50)
Declare @AccountName varchar(100)
Declare @REAmountCR money
Declare @REAmountDB money
Declare @REAmountCR2 money
Declare @REAmountDB2 money
Declare @REDisplayOrder int


Create table #GLTran
(
	CompanyKey int,
	GLAccountKey int,
	GLCompanyKey int,
	TransactionDate smalldatetime,
	CurrencyID varchar(10) null,
	Debit money,
	Credit money,
	HDebit money null, -- in Home Currency
	HCredit money null,
	Revalue int null 
)

Create table #revalue
	(
	GLAccountKey int
	,TransactionDate smalldatetime null
	,CurrencyID varchar(10) null
 	,Debit money null -- in Transaction Currency
	,Credit money null
	,HDebit money null -- in Home Currency
	,HCredit money null
	)

-- bank accounts cannot be revalued transaction by transaction
-- they have to be revalued as a group, i.e. if I have 1000 EUR at 1.389128 it should be:
-- round(1000 * 1.389128, 2) = 1389.13 
-- not SUM(round(values, 1.389128, 2) which will be diff from 1389.13   
Create table #revalued
	(
	GLAccountKey int null
	,CurrencyID varchar(10) null
	,AccountType int null
	,OriginalHValue1 money null -- 1st period, original value
	,RevaluedHValue1 money null -- 1st period, revalued value
	,OriginalHValue money null  -- 2 periods
	,RevaluedHValue money null
	,RetainedEarning money null
	,CurrentEarning money null
	)

/* done in VB
create table #revaluerate(
		CurrencyID varchar(10) null
		,PreviousRate decimal(24,7) null
		,CurrentRate decimal(24,7) null
		)
*/

-- we use the GL company Debit and Credit if we have a single company with a diff home currency 
if @GLCount > 0 and @RunInGLCHomeCurrency = 1
begin
	select @GLCompanyKey = GLCompanyKey from #GLCompanyKeys
	select @GLCHomeCurrencyID = CurrencyID from tGLCompany (nolock) where GLCompanyKey = @GLCompanyKey
end

IF @CashBasis = 0
	INSERT	#GLTran (CompanyKey, GLAccountKey, GLCompanyKey, TransactionDate, CurrencyID, Debit, Credit, HDebit, HCredit)
	SELECT	CompanyKey, GLAccountKey, t.GLCompanyKey, TransactionDate, CurrencyID, Debit, Credit
	, case when @GLCHomeCurrencyID is null then HDebit else GLCDebit end
	, case when @GLCHomeCurrencyID is null then HCredit else GLCCredit end
	
	FROM	tTransaction t (nolock)
				INNER JOIN #GLCompanyKeys glc ON ISNULL(t.GLCompanyKey, 0) = glc.GLCompanyKey
				INNER JOIN #ClassKeys c ON ISNULL(t.ClassKey, 0) = c.ClassKey
	WHERE	CompanyKey = @CompanyKey
ELSE
	INSERT	#GLTran (CompanyKey, GLAccountKey, GLCompanyKey, TransactionDate, CurrencyID, Debit, Credit, HDebit, HCredit)
	SELECT	CompanyKey, GLAccountKey, t.GLCompanyKey, TransactionDate, CurrencyID, Debit, Credit
	, case when @GLCHomeCurrencyID is null then HDebit else GLCDebit end
	, case when @GLCHomeCurrencyID is null then HCredit else GLCCredit end
	FROM	tCashTransaction t (nolock)
				INNER JOIN #GLCompanyKeys glc ON ISNULL(t.GLCompanyKey, 0) = glc.GLCompanyKey
				INNER JOIN #ClassKeys c ON ISNULL(t.ClassKey, 0) = c.ClassKey
	WHERE	CompanyKey = @CompanyKey

-- we only revalue Bank Accounts (10) and Credit Card Accounts (23) + AP (11) and AR (20) accounts.
	update #GLTran
	set    Revalue = 0

	update #GLTran
	set    #GLTran.Revalue = 1
	from   tGLAccount gla (nolock) 
	where  #GLTran.GLAccountKey = gla.GLAccountKey
	and    gla.AccountType in (10, 11, 20, 23)
	and    gla.CurrencyID is not null
	and    #GLTran.CurrencyID is not null -- do not revalue the AR AP adjustments
	and    #GLTran.TransactionDate <= @AsOfDate -- only if Tran Date before or on Balance Date  

	/*
	update #GLTran
	set    #GLTran.Revalue = 1
	where  #GLTran.GLAccountKey = @AdvBillAccountKey
	and    #GLTran.CurrencyID is not null
	and    #GLTran.TransactionDate <= @AsOfDate -- only if Tran Date before or on Balance Date  
	*/

	update #GLTran
	set    #GLTran.Revalue = 1
	from   tGLAccount gla (nolock) 
	where  #GLTran.GLAccountKey = gla.GLAccountKey
	and    gla.AccountType < 32          -- Assets or Liabilities
	and    isnull(gla.RevalueCurrency, 0) = 1
	and    gla.Rollup = 0
	and    #GLTran.CurrencyID is not null				-- Adv Bill and Unapplied accounts could have any currency, just convert foreign currencies
	and    #GLTran.TransactionDate <= @AsOfDate		-- only if Tran Date before or on Balance Date  

	-- Also when we run the report in GLC home currency such as EUR, a currency like USD must be revalued
	if @GLCHomeCurrencyID is NOT null
	begin		
		update #GLTran
		set    #GLTran.Revalue = 1
				-- Also correct the blank currencies
		       ,#GLTran.CurrencyID = case when isnull(#GLTran.CurrencyID, '''') = '''' 
				then  @MainHomeCurrencyID else #GLTran.CurrencyID end
		from   tGLAccount gla (nolock) 
		where  #GLTran.GLAccountKey = gla.GLAccountKey
		and    gla.AccountType in (10, 11, 20, 23)          -- Bank account and AR AP CCs
		and    gla.CurrencyID is null	-- this must be null now	
		
		-- do not revalue the AR/AP adjustments where CurrencyID is null/ or Debit = 0 and Credit = 0
		and    not (#GLTran.Debit = 0 and #GLTran.Credit = 0)   	
		and    #GLTran.TransactionDate <= @AsOfDate		-- only if Tran Date before or on Balance Date  

		-- Adv Bill and Unapplied accounts could have any currency, just convert MAIN Home currency to @GLCHomeCurrencyID
		update #GLTran
		set    #GLTran.Revalue = 1
			-- Also correct the blank currencies
		       ,#GLTran.CurrencyID = case when isnull(#GLTran.CurrencyID, '''') = '''' 
				then  @MainHomeCurrencyID else #GLTran.CurrencyID end
		from   tGLAccount gla (nolock) 
		where  #GLTran.GLAccountKey = gla.GLAccountKey
		and    gla.AccountType < 32          -- Assets or Liabilities
		and    isnull(gla.RevalueCurrency, 0) = 1
		and    gla.Rollup = 0

		-- do not revalue the AR/AP adjustments where CurrencyID is null/ or Debit = 0 and Credit = 0
		and    not (#GLTran.Debit = 0 and #GLTran.Credit = 0)   	
		and    #GLTran.TransactionDate <= @AsOfDate		-- only if Tran Date before or on Balance Date  

	end


	/* Need to revalue if Tran Date <= Balance Date
	if Tran Date <= Beginning Date, there will be a retained earning and a current earning
	if Tran Date > Beginning Date, there will only be a current earning 

	if Tran Date > Balance Date, this is in the future, no need to revalue
	*/

	insert #revalue(GLAccountKey,TransactionDate,CurrencyID, Debit,Credit,HDebit ,HCredit)
	select GLAccountKey,TransactionDate,CurrencyID,Debit,Credit,HDebit ,HCredit
	from   #GLTran
	where  Revalue = 1

	exec spRptBalanceSheetRevaluation @CompanyKey, @BeginningDate, @AsOfDate

--select * from #GLTran
--select * from #revalue
--select * from #revalued
--return

declare @RevaluationCurrentEarning money
declare @RevaluationRetainedEarning money

select @RevaluationCurrentEarning = sum(CurrentEarning)
      ,@RevaluationRetainedEarning = sum(RetainedEarning) 
from #revalued 

-- Get the retained Earnings Account
Declare @REAccountKey int

if @CashBasis = 0
	Select @REAccountKey = GLAccountKey from tGLAccount (nolock) Where CompanyKey = @CompanyKey and AccountType = 32
else
	Select @REAccountKey = GLAccountKey from tGLAccount (nolock) Where CompanyKey = @CompanyKey and isnull(AccountTypeCash,AccountType) = 32

-- if there is no retained earnings account, create a virtual account
if @REAccountKey is null
	Select @GLAccountKey = -1, @AccountNumber = ''000'', @AccountName = ''Retained Earnings'', @REDisplayOrder = 999999
else
	Select @GLAccountKey = GLAccountKey, @AccountNumber = AccountNumber, @AccountName = AccountName, @REDisplayOrder = DisplayOrder from tGLAccount (nolock) Where GLAccountKey = @REAccountKey

-- Calculate the Retained Earnings Amount
-- Move prior net income over to retained earnings
if @CashBasis = 0
	Select @REAmountCR = ISNULL(SUM(HCredit), 0), @REAmountDB = ISNULL(SUM(HDebit), 0) 
		from #GLTran t (nolock) inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
		Where t.CompanyKey = @CompanyKey and AccountType in (31, 40, 41, 50, 51, 52) 
		and TransactionDate < @BeginningDate
		and t.Revalue = 0
else
	Select @REAmountCR = ISNULL(SUM(HCredit), 0), @REAmountDB = ISNULL(SUM(HDebit), 0) 
		from #GLTran t (nolock) inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
		Where t.CompanyKey = @CompanyKey and isnull(AccountTypeCash,AccountType) in (31, 40, 41, 50, 51, 52) 
		and TransactionDate < @BeginningDate
		and t.Revalue = 0

	-- Get any transactions posted directly to retained earnings
	If @REAccountKey is null
		Select @REAmountCR2 = 0, @REAmountDB2 = 0
	else	
		Select @REAmountCR2 = ISNULL(SUM(HCredit), 0), @REAmountDB2 = ISNULL(SUM(HDebit), 0)  
		from #GLTran t (nolock)
		Where t.GLAccountKey = @REAccountKey and TransactionDate <= @AsOfDate
		and t.Revalue = 0

		
--select * from 		#revalue
--select * from 		#revalued
--select * from #revaluerate
/*
select @RevaluationCurrentEarning as RevaluationCurrentEarning 
      ,@RevaluationRetainedEarning as RevaluationRetainedEarning
	  ,@REAmountDB + @REAmountDB2 as REAmountDB
	  ,@REAmountCR + @REAmountCR2 as REAmountCR
*/

Select @REAmountDB = @REAmountDB + @REAmountDB2 , @REAmountCR = @REAmountCR + @REAmountCR2 


declare @REBalance money
declare @UnrealizedBalance money

select @REBalance = @REAmountDB - @REAmountCR - isnull(@RevaluationRetainedEarning,0)
select @UnrealizedBalance = -@RevaluationCurrentEarning

create table #glacct (GLAccountKey int null, HDebit money null, HCredit money null, Amount money null, Revalued money null)
insert #glacct (GLAccountKey)
select GLAccountKey from tGLAccount (nolock) where CompanyKey = @CompanyKey and AccountType <= 30 and Rollup = 0

update #glacct
set    #glacct.HDebit = (select
	sum (#GLTran.HDebit)
	from #GLTran 
	where Revalue = 0 and #GLTran.TransactionDate <= @AsOfDate and #GLTran.GLAccountKey = #glacct.GLAccountKey)  

update #glacct
set    #glacct.HCredit = (select
	sum (#GLTran.HCredit)
	from #GLTran 
	where Revalue = 0 and #GLTran.TransactionDate <= @AsOfDate and #GLTran.GLAccountKey = #glacct.GLAccountKey)  

update #glacct
set Amount = isnull(HDebit, 0) - isnull(HCredit,0)

update #glacct
set    #glacct.Revalued = (select SUM(#revalued.RevaluedHValue)
from   #revalued
where  #revalued.GLAccountKey = #glacct.GLAccountKey 

)
-- when AccountType < 20, spRptBalanceSheetRevaluation takes Revalued = Debit - Credit
-- this is fine here
update #glacct
set Amount = isnull(Amount, 0) + isnull(Revalued, 0)
from tGLAccount gla (nolock) 
where #glacct.GLAccountKey = gla.GLAccountKey
and  AccountType < 20

-- when AccountType >=20, spRptBalanceSheetRevaluation takes Revalued = Credit - Debit
-- correct by subtracting the Revalued value
-- on the Trial Balance we always take Debit - Credit
update #glacct
set Amount = isnull(Amount, 0) - isnull(Revalued, 0)
from tGLAccount gla (nolock) 
where #glacct.GLAccountKey = gla.GLAccountKey
and  AccountType >= 20

/*
select * from #glacct where Amount <> 0

select b.AccountNumber, b.AccountType, a.* 
from #GLTran a
inner join tGLAccount b on a.GLAccountKey = b.GLAccountKey
*/


-- This summarizes all the do not close accounts.
if @CashBasis = 0
	-- Regular/Accrual GL
	Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,gl.AccountType
		,CASE WHEN ISNULL(#glacct.Amount, 0) > 0 THEN
			ISNULL(#glacct.Amount, 0) ELSE NULL END AS Debit
		,CASE WHEN ISNULL(#glacct.Amount, 0) > 0  THEN
			NULL ELSE -ISNULL(#glacct.Amount, 0)  END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join #glacct on gl.GLAccountKey = #glacct.GLAccountKey  
	Where
		gl.CompanyKey = @CompanyKey and
		gl.AccountType <= 30 and
		gl.Rollup = 0
	
		
Union ALL

Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,gl.AccountType
		,CASE WHEN ISNULL(SUM(t.HDebit), 0) - ISNULL(SUM(t.HCredit), 0) > 0 THEN
			ISNULL(SUM(t.HDebit), 0) - ISNULL(SUM(t.HCredit), 0) ELSE NULL END AS Debit
		,CASE WHEN ISNULL(SUM(t.HDebit), 0) - ISNULL(SUM(t.HCredit), 0) > 0 THEN
			NULL ELSE ISNULL(SUM(t.HCredit), 0) - ISNULL(SUM(t.HDebit), 0) END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join 
		(Select GLAccountKey, HDebit, HCredit From #GLTran (nolock) 
			Where TransactionDate <= @AsOfDate
			 and TransactionDate >= @BeginningDate) t on gl.GLAccountKey = t.GLAccountKey 
	Where
		gl.CompanyKey = @CompanyKey and
		gl.AccountType in (31, 40, 41, 50, 51, 52) and
		gl.Rollup = 0
	Group By gl.GLAccountKey ,gl.AccountNumber ,gl.AccountName,gl.AccountType,DisplayOrder, Active
		
-- Include the retained earnings account
Union ALL
	Select
		 @GLAccountKey
		,@AccountNumber
		,@AccountName
		,32
		,case when isnull(@REBalance, 0) > 0 then
			isnull(@REBalance, 0) else  NULL end AS Debit
		,case when isnull(@REBalance, 0) > 0 then
			null else -isnull(@REBalance, 0)  end AS Credit
		,@REDisplayOrder
		,1

Union ALL
	Select
		 -2
		,''''
		,''Unrealized Gains/Losses''
		,41
		,case when isnull(@UnrealizedBalance, 0) > 0 then
			isnull(@UnrealizedBalance, 0) else  NULL end AS Debit
		,case when isnull(@UnrealizedBalance, 0) > 0 then
			null else -isnull(@UnrealizedBalance, 0)  end AS Credit
		,999998
		,1
		
	ORDER BY DisplayOrder
		
ELSE
	-- Cash Basis GL

	Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,gl.AccountType
		,CASE WHEN ISNULL(#glacct.Amount, 0) > 0 THEN
			ISNULL(#glacct.Amount, 0) ELSE NULL END AS Debit
		,CASE WHEN ISNULL(#glacct.Amount, 0) > 0  THEN
			NULL ELSE -ISNULL(#glacct.Amount, 0)  END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join #glacct on gl.GLAccountKey = #glacct.GLAccountKey  
	Where
		gl.CompanyKey = @CompanyKey and
		gl.AccountType <= 30 and
		gl.Rollup = 0
	

Union ALL

Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,isnull(gl.AccountTypeCash, gl.AccountType) As AccountType
		,CASE WHEN ISNULL(SUM(t.HDebit), 0) - ISNULL(SUM(t.HCredit), 0) > 0 THEN
			ISNULL(SUM(t.HDebit), 0) - ISNULL(SUM(t.HCredit), 0) ELSE NULL END AS Debit
		,CASE WHEN ISNULL(SUM(t.HDebit), 0) - ISNULL(SUM(t.HCredit), 0) > 0 THEN
			NULL ELSE ISNULL(SUM(t.HCredit), 0) - ISNULL(SUM(t.HDebit), 0) END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join 
		(Select GLAccountKey, HDebit, HCredit From #GLTran (nolock) 
			Where TransactionDate <= @AsOfDate
			 and TransactionDate >= @BeginningDate) t on gl.GLAccountKey = t.GLAccountKey 
	Where
		gl.CompanyKey = @CompanyKey and
		isnull(gl.AccountTypeCash, gl.AccountType) in (31, 40, 41, 50, 51, 52) and
		gl.Rollup = 0
	Group By gl.GLAccountKey ,gl.AccountNumber ,gl.AccountName, isnull(gl.AccountTypeCash, gl.AccountType), DisplayOrder, Active
		
-- Include the retained earnings account
Union ALL
	Select
		 @GLAccountKey
		,@AccountNumber
		,@AccountName
		,32
		,case when isnull(@REBalance, 0) > 0 then
			isnull(@REBalance, 0) else  NULL end AS Debit
		,case when isnull(@REBalance, 0) > 0 then
			null else -isnull(@REBalance, 0)  end AS Credit
		,@REDisplayOrder
		,1
Union ALL
	Select
		 -2
		,''''
		,''Unrealized Gains/Losses''
		,41
		,case when isnull(@UnrealizedBalance, 0) > 0 then
			isnull(@UnrealizedBalance, 0) else  NULL end AS Debit
		,case when isnull(@UnrealizedBalance, 0) > 0 then
			null else -isnull(@UnrealizedBalance, 0)  end AS Credit
		,999998
		,1

	ORDER BY DisplayOrder
'
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
|| 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
*/


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 (128,  0, 0, ''automation'', ''Automation'', ''This will allow you to set up automation rules.'', '''')

-- Beta Items

INSERT tLab(LabKey, Beta, DisplayOrder, LabID, LabName, LabDescription, Customization) Values (123,  0, 1, ''newProjectDashboard'', ''New Project Dashboard (BETA)'', ''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'')



-- active plat betas   **************   Next Key: 130  *****************  exec spConvertAppSeed 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tAutoEventAction]'
GO
IF OBJECT_ID(N'[dbo].[tAutoEventAction]', 'U') IS NULL
CREATE TABLE [dbo].[tAutoEventAction]
(
[EventActionKey] [int] NOT NULL IDENTITY(1, 1),
[AutoEventKey] [int] NOT NULL,
[ActionKey] [int] NOT NULL,
[Status] [varchar] (50) NOT NULL,
[StartTime] [datetime] NULL,
[EndTime] [datetime] NULL,
[Errors] [varchar] (max) NULL,
[Results] [varchar] (max) NULL,
[ActionEntity] [varchar] (50) NULL,
[ActionEntityKey] [int] NULL,
[ActionOptions] [varchar] (max) NULL,
[ActionType] [varchar] (50) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tAutoEventAction] on [dbo].[tAutoEventAction]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tAutoEventAction]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tAutoEventAction]', 'U'))
ALTER TABLE [dbo].[tAutoEventAction] ADD CONSTRAINT [PK_tAutoEventAction] PRIMARY KEY CLUSTERED ([EventActionKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoEventActionInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoEventActionInsert]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[sptAutoEventActionInsert]
	@AutoEventKey int,
	@ActionKey int,
	@ActionEntity varchar(50),
	@ActionEntityKey int
AS

	INSERT	tAutoEventAction
			(AutoEventKey,
			ActionKey,
			ActionEntity,
			ActionEntityKey,
			ActionType,
			ActionOptions,
			Status,
			StartTime)
	SELECT	@AutoEventKey,
			ActionKey,
			@ActionEntity,
			@ActionEntityKey,
			ActionType,
			Options,
			''started'',
			GETUTCDATE()
	FROM	tAutoAction (nolock)
	WHERE	ActionKey = @ActionKey

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








ALTER VIEW [dbo].[vProjectTrans]
as

/*
|| When     Who Rel     What
|| 12/21/06 CRG 8.4     Added GLAccountKey
|| 07/10/07 QMD 8.5     Expense Type reference changed to tItem
|| 10/26/07 CRG 8.4.3.9 (14565) Modified to add a column for CostRate for use by vReport_Transactions_NetLabor
|| 11/07/07 CRG 8.5     (9205) Added ClassKey
|| 02/01/08 GHL 8.503   (20472) Added TranKey, UIDTranKey to join with expense receipts in vReport_Transactions
|| 04/10/08 GHL 8.508   (24671) Changed join type between tItem/tExpenseReceipt (case when no item)
|| 04/08/09 GHL 10.022  (50462) Added VendorKey  to add to vReport_Transactions
|| 04/24/09 MFT 10.024	(51139) Added DepartmentName to add to vReport_Transactions and vReport_Transactions_NetLabor
|| 04/28/09 GHL 10.024  (51139) Get department from the lines for misc cost and vouchers only 
|| 06/15/09 GHL 10.027  (54845) Added Transaction Number to get v.InvoiceNumber, ee.EnvelopeNumber + user
|| 09/11/09 GHL 10.5     Added TransferToKey 
|| 01/19/10 GHL 10.517  (72527) Added Billing Item info from service/item
||                       considered as defaults if there is no layout on the project 
|| 01/22/10 RLB 10.517  (72862) If no item on voucher line will pull lines expense account
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
|| 07/13/11 RLB 10.546  (114349) Added Sales Expense Account
|| 04/23/12 GHL 10.555  Added GLCompanyKey for map/restrict
||                       --> tTime/tExpenseReceipt
||							p.GLCompanySource = 0 then p.GLCompanyKey
||							p.GLCompanySource = 1 then u.GLCompanyKey
||							p.GLCompanySource is null i.e. no project then u.GLCompanyKey
||                       --> tMiscCost
||							p.GLCompanyKey
||                       --> tVoucherDetail
||							isnull(vd.TargetGLCompanyKey, v.GLCompanyKey)
|| 08/22/12 RLB 10.559  (151545) since labor TotalCost is gross going to add a new net field TotalCostNet
|| 01/29/15 GHL 10.588  Added titles for Abelson
|| 03/20/15 WDF 10.590 (AbelsonTaylor) Added AdjustmentType
|| 06/18/15 MCM 10.593 (260175) In the voucher section having it pull expense account from voucher first and items second
|| 04/12/16 MFT 10.603 (296036) Added WriteOffComment
|| 06/08/16 WDF 10.605 (303066) Added PurchasedFrom
|| 08/15/16 GWG 10.607 (310383) using isnull to get department from the time entry.
|| 08/20/16 GWG 10.607 Making department logic same as in time details dataset
|| 12/07/18 GHL 19.100 (424920) Added GrossAmount (mainly for VIs with prebilled POs applied, in that case 
||                      GrossAmount = 1000 and BillableCost = 0 )
|| 02/14/19 GHL 19.300 (445252) Removed LATIN1_GENERAL_ CI_AS collation, this creates conflicts when comparing to other strings 
||                      Other option could be to force it to COLLATE DATABASE_DEFAULT
|| 04/24/19 GWG 19.050  Distinguish between a voucher and a credit card in the type
|| 05/06/19 MCM 19.050 (449142) Adding unit Rate from the voucher detail
|| 05/13/19 GHL 19.0.6.0 (459967) Added Applied Order number
|| 07/19/19 AMP 19.0.8.0 (467528) Modified SalesAccountKey for ''Labor'' transaction type so that the Sales Account Number and Name will be displayed in the Project Cost Transactions dataset.
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 05/18/21 AMP 21.06.20.0000 (558708) Added currency field 
|| 12/20/21 GHL 22.01.16 (580428) Added WIP Anount
|| 02/28/22 RLS 22.03.20 (523772) Added data type specifier (N) to string literals
|| 11/29/22 RLS 22.12.18 (614994) Added TransactionApprovalDate
|| 05/30/23 RLS 23.16.18 (635138) Added TransactionPostingDate
|| 06/04/25 MCM 25.07.x  (700642) Added TransactionKey - type + underlying Key field
|| 09/04/25 RLS 25.09.21 (708615) Added PODCustomFieldKey
|| 04/28/26 RLS 26.05.17 (724768) Added Contractor
*/

Select
	N''LABOR'' as Type
	,ts.CompanyKey
	,case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey
	,t.TimeSheetKey as ParentKey
	,NULL as PODCustomFieldKey
	,t.ProjectKey
	,t.TaskKey
    ,t.ServiceKey as ItemKey
	,s.ServiceCode as ItemID
	,s.Description as ItemName
	,ActualHours as Quantity
	,ActualRate as UnitCost
	,ROUND(ActualHours * t.CostRate, 2) as TotalCostNet
	,ROUND(ActualHours * ActualRate, 2) as TotalCost
	,ROUND(ActualHours * ActualRate, 2) as BillableCost
	,ROUND(ActualHours * ActualRate, 2) as GrossAmount
	,ROUND(BilledHours * BilledRate, 2) as AmountBilled
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,'''')))  COLLATE DATABASE_DEFAULT as Description
	,t.WorkDate as TransactionDate
	,NULL as PurchasedFrom
	,t.InvoiceLineKey
	,t.WriteOff
	,ts.Status
	,WIPPostingInKey
	,WIPPostingOutKey
	,WIPAmount
	,t.OnHold
	,t.WriteOffReasonKey
	,t.WriteOffComment
	,t.Comments as Comments
	,ROUND(t.ActualRate * t.ActualHours, 2) - ISNULL(ROUND(t.BilledHours * t.BilledRate, 2), 0) as BilledDifference
	,NULL as GLAccountKey
	,s.GLAccountKey as SalesAccountKey
	,t.DateBilled
	,t.TransferComment
	,t.CostRate
	,s.ClassKey
	,t.TimeKey AS UIDTranKey
	,NULL AS TranKey
    ,NULL AS TranNumber
	,NULL AS VendorKey
	,case when t.DepartmentKey is not null then dt.DepartmentName 
		else case when isnull(pr.DefaultDepartmentFromUser, 0) = 1 then du.DepartmentName else ds.DepartmentName end end as DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,t.TransferToKey AS UIDTransferToKey
    ,NULL AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName) as WorkTypeName
    ,t.TransferInDate
    ,t.TransferOutDate
    ,t.TitleKey
    ,tt.TitleName
    ,tt.TitleID
    ,t.IsAdjustment as AdjustmentType
	,null as UnitRate
	,null as AppliedOrderNumber
	,t.CurrencyID
	,ts.DateApproved as TransactionApprovalDate
	,NULL as TransactionPostingDate
	,N''LABOR'' + Cast(t.TimeKey as varchar(100)) as TransactionKey
from 
	tTime t (nolock)
	inner join tUser u (nolock) on t.UserKey = u.UserKey
	inner join tTimeSheet ts (nolock) on t.TimeSheetKey = ts.TimeSheetKey
	inner join tPreference pr (nolock) on ts.CompanyKey = pr.CompanyKey
	left outer join tService s (nolock) on t.ServiceKey = s.ServiceKey
	left outer join tWorkType wt (nolock) on s.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on s.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = t.ProjectKey
	LEFT JOIN tDepartment dt (nolock) on t.DepartmentKey = dt.DepartmentKey
	LEFT JOIN tDepartment du (nolock) on u.DepartmentKey = du.DepartmentKey
	LEFT JOIN tDepartment ds (nolock) on s.DepartmentKey = ds.DepartmentKey

	left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
	left outer join tTitle tt (nolock) on t.TitleKey = tt.TitleKey
	
Union ALL

Select
	N''EXPRPT'' as Type
	,ee.CompanyKey
	,case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey
	,er.ExpenseEnvelopeKey as ParentKey
	,NULL as PODCustomFieldKey
	,er.ProjectKey
	,er.TaskKey
	,er.ItemKey 
	,i.ItemID
	,i.ItemName
	,er.ActualQty as Quantity
	,er.ActualUnitCost as UnitCost
	,er.ActualCost as TotalCostNet
	,er.ActualCost as TotalCost
	,er.BillableCost as BillableCost
	,er.GrossAmount
	,er.AmountBilled
	,er.Description COLLATE DATABASE_DEFAULT as Description
	,er.ExpenseDate as TransactionDate
	,NULL as PurchasedFrom
	,er.InvoiceLineKey
	,er.WriteOff
	,ee.Status
	,WIPPostingInKey
	,WIPPostingOutKey
	,WIPAmount
	,er.OnHold
	,er.WriteOffReasonKey
	,er.WriteOffComment
	,er.Comments as Comments
	,NULL
	,i.ExpenseAccountKey AS ExpenseGLAccountKey
	,i.SalesAccountKey
	,er.DateBilled
	,er.TransferComment
	,NULL
	,i.ClassKey
	,NULL AS UIDTranKey
	,er.ExpenseReceiptKey AS TranKey
    ,ee.EnvelopeNumber AS TranNumber
	,ee.VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
    ,NULL AS UIDTransferToKey
	,er.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,er.TransferInDate
    ,er.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
    ,null as TitleID
    ,er.AdjustmentType as AdjustmentType
	,null as UnitRate
	,null as AppliedOrderNumber
	,ee.CurrencyID
	,ee.DateApproved AS TransactionApprovalDate
	,NULL as TransactionPostingDate
	,N''EXPRPT'' + Cast(er.ExpenseReceiptKey as varchar(100)) as TransactionKey
from
	tExpenseReceipt er (nolock)
	inner join tExpenseEnvelope ee (nolock) on er.ExpenseEnvelopeKey = ee.ExpenseEnvelopeKey
	left outer join tItem i (nolock) on er.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = er.ProjectKey
	LEFT JOIN tDepartment d (nolock) on i.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on ee.UserKey = u.UserKey
    left outer join tProject p (nolock) on er.ProjectKey = p.ProjectKey
    
where   er.VoucherDetailKey is null

Union ALL

Select
	N''MISCCOST'' as Type
	,p.CompanyKey
	,p.GLCompanyKey
	,mc.MiscCostKey as ParentKey
	,NULL as PODCustomFieldKey
	,mc.ProjectKey
	,mc.TaskKey
	,mc.ItemKey 
	,i.ItemID
	,i.ItemName as ItemName
	,mc.Quantity
	,mc.UnitCost
	,mc.TotalCost as TotalCostNet
	,mc.TotalCost
	,mc.BillableCost
	,mc.BillableCost as GrossAmount
	,mc.AmountBilled
	,mc.ShortDescription COLLATE DATABASE_DEFAULT as Description
	,mc.ExpenseDate as TransactionDate
	,NULL as PurchasedFrom
	,mc.InvoiceLineKey
	,mc.WriteOff
	,4
	,WIPPostingInKey
	,WIPPostingOutKey
	,WIPAmount
	,mc.OnHold
	,mc.WriteOffReasonKey
	,mc.WriteOffComment
	,mc.LongDescription as Comments
	,NULL
	,i.ExpenseAccountKey
	,i.SalesAccountKey
	,mc.DateBilled
	,mc.TransferComment
	,NULL
	,mc.ClassKey
	,NULL AS UIDTranKey
	,mc.MiscCostKey AS TranKey
    ,null AS TranKey
	,NULL AS VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,NULL AS UIDTransferToKey
	,mc.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,mc.TransferInDate
    ,mc.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
	,null as TitleID
    ,mc.AdjustmentType as AdjustmentType
	,null as UnitRate
	,null as AppliedOrderNumber
	,mc.CurrencyID
	,NULL as TransactionApprovalDate
	,NULL as TransactionPostingDate
	,N''MISCCOST'' + Cast(mc.MiscCostKey as varchar(100)) as TransactionKey
from
	tMiscCost mc (nolock)
	inner join tProject p (nolock) on mc.ProjectKey = p.ProjectKey
	left outer join tItem i (nolock) on mc.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = mc.ProjectKey
	LEFT JOIN tDepartment d (nolock) on mc.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on mc.EnteredByKey = u.UserKey

Union ALL

Select
	case When v.CreditCard = 1 then N''CREDIT CARD'' else N''VOUCHER'' End as Type
	,v.CompanyKey
	,ISNULL(vd.TargetGLCompanyKey, v.GLCompanyKey) as GLCompanyKey
	,vd.VoucherKey as ParentKey
	,pod.CustomFieldKey as PODCustomFieldKey
	,vd.ProjectKey
	,vd.TaskKey
	,vd.ItemKey 
	,i.ItemID
	,i.ItemName as ItemName
	,vd.Quantity
	,vd.UnitCost
	,vd.TotalCost as TotalCostNet
	,vd.TotalCost
	,vd.BillableCost
	,vd.GrossAmount
	,vd.AmountBilled
	,vd.ShortDescription COLLATE DATABASE_DEFAULT as Description
	,v.InvoiceDate as TransactionDate
	,v.BoughtFrom as PurchasedFrom
	,vd.InvoiceLineKey
	,vd.WriteOff
	,v.Status
	,WIPPostingInKey
	,WIPPostingOutKey
	,WIPAmount
	,vd.OnHold
	,vd.WriteOffReasonKey
	,vd.WriteOffComment
	,vd.ShortDescription as Comments
	,NULL
	,vd.ExpenseAccountKey
	,i.SalesAccountKey
	,vd.DateBilled
	,vd.TransferComment
	,NULL
	,vd.ClassKey
	,NULL AS UIDTranKey
	,vd.VoucherDetailKey AS TranKey
    ,v.InvoiceNumber AS TranNumber
	,v.VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,NULL AS UIDTransferToKey
	,vd.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,vd.TransferInDate
    ,vd.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
	,null as TitleID
    ,vd.AdjustmentType as AdjustmentType
	,vd.UnitRate
	,po.PurchaseOrderNumber as AppliedOrderNumber
	,v.CurrencyID
	,v.ApprovedDate as TransactionApprovalDate
	,v.PostingDate AS TransactionPostingDate
	,case When v.CreditCard = 1 then N''CREDIT CARD'' else N''VOUCHER'' end + Cast(vd.VoucherDetailKey as varchar(100)) as TransactionKey
from
	tVoucherDetail vd (nolock)
	inner join tVoucher v (nolock) on vd.VoucherKey = v.VoucherKey
	left outer join tItem i (nolock) on vd.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = vd.ProjectKey
	LEFT JOIN tDepartment d (nolock) on vd.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on v.CreatedByKey = u.UserKey
	left outer join tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
	left outer join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey







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











ALTER VIEW [dbo].[vReport_Transactions_NetLabor]
AS

/*
|| When     Who Rel     What
|| 10/26/07 CRG 8.4.3.9 (14565) Created a copy of vReport_Transactions showing Net Labor amounts
|| 11/07/07 CRG 8.5     (9205) Modified to get Class from the Transactions rather than the Project.
|| 02/01/08 GHL 8.5     (20472) Added logic for expense receipts on voucher
|| 02/01/08 GHL 8.5     (20431) Changed TotalCost - Should be calculated at Net with Cost Rate
|| 04/23/09 MFT 10.024  (51485) Added Vendor Name, Total Labor Cost, Client Division, Client Product
|| 04/24/09 MFT 10.024	(51139) Added Transaction Department
|| 09/11/09 GHL 10.5     Added Transferred Out
|| 01/19/10 GHL 10.517  (72527) Added Billing Item info
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
|| 07/13/11 RLB 10.546  (114349) Added Sales Account
|| 07/27/11 RLB 10.546  (111324) Added Campaign Segment and other campaign fields that seem to be missing from this report
|| 09/21/11 RLB 10.548  (119193) Added Project Close Date 
|| 04/23/12 GHL 10.555   Added GLCompanyKey for map/restrict
|| 05/29/12 RLB 10.556  (143884) correctly pulling Total Labor Cost
|| 06/22/12 RLB 10.557  (146849) Added Transaction Month and year
|| 08/17/12 RLB 10.559 (151960) Added Billing Group Code
|| 08/22/12 RLB 10.559  (151545) pulling new TotalCostNet so that labor will be at cost like the expenses
|| 09/28/12 GHL 10.560 Getting now BillingGroupCode from tBillingGroup
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey
|| 11/15/12 GWG 10.5.6.2 Added transfer in out dates
|| 01/30/13 GHL 10.5.6.4 (166680) Added Billing Method
|| 11/06/14 WDF 10.5.8.6 (233050) Added Billing Manager
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
|| 01/28/15 GHL 10.5.8.8 Added title for Abelson
|| 03/20/15 WDF 10.5.9.0 (Abelson Taylor) Added AdjustmentType
|| 10/05/15 GHL 10.5.9.7 (272410) Added check of Write Off flag when pulling Write Off Date
|| 04/12/16 MFT 10.6.0.3 (296036) Added WriteOffComment
|| 06/08/16 WDF 10.6.0.5 (303066) Added PurchasedFrom
|| 07/12/16 WDF 10.6.0.6 (299976) Added Campaign Custom Fields
|| 08/16/16 KMC 10.6.0.7 (308209) Added [Parent Company Name] and [Parent Division Name] from the company page (Client Setup...Billing).
|| 02/08/17 WDF 10.6.1.3 (331895) Added [Project Description]
|| 05/20/17 GWG 10.6.1.5 Added project primary contact and email
|| 05/15/18 GWG 18.5.0.0 added campaign active
|| 08/15/18 WDF 18.9.0.0 (415376) Added [CustomFieldKey3]
|| 12/06/18 MFT 19.1.0.0 (434596) Wrapped LayoutKey in ISNULL
|| 05/13/19 GHL 19.0.6.0 (459967) Added Applied Order number
|| 07/18/19 GAR 19.0.8.0 (470619) Adding Project Manager
|| 07/29/19 WDF 19.0.8.0 (471596) Corrected alias of [Campaign Active] from cp to ca
|| 07/30/19 WDF 19.0.8.0 (472402) Corrected format of [Campaign Full Name] for linking in Report
|| 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
|| 12/19/19 GAR 20.0.1.0 (492042) Fixed project billing status - was pulling project status
|| 02/18/20 AMP 20.0.3.0 (500814) Added Client Project Number 
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 02/25/21 RLS 21.0.3.0 (549405) Added [Company Type]
|| 05/24/21 RLS 21.0.6.0 (559037) Added [Summary Task ID], [Summary Task Name] and [Summary Task Full Name]
|| 05/26/21 AMP 21.06.20 (558708) Added currency field 
|| 05/16/22 RLS 22.06.19 (596563) Added [Transaction Month Formatted]
|| 08/03/22 MFT 22.0.8.0 (607757) Added "s" to "Time and Material"
|| 11/29/22 RLS 22.12.18 (614994) Added TransactionApprovalDate
|| 01/17/23 RLB 23.02.19 (626523) added budget fields from vReport_Transactions
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color
|| 05/30/23 RLS 23.16.18 (635138) Added TransactionPostingDate
|| 08/11/23 RLB 23.09.17 (648008) added project type color
|| 09/30/24 RLS 24.10.20 (683085) Added [Transaction Status]
|| 09/04/25 RLS 25.09.21 (708615) Added PODCustomFieldKey
|| 09/29/25 MCM 25.10.x  (700642) Added TransactionKey 
|| 04/28/26 RLS 26.05.17 (724768) Added [Contractor]
*/

Select 
	p.CompanyKey
	,pt.GLCompanyKey
	,p.CustomFieldKey
	,ca.CustomFieldKey as [CustomFieldKey2]
	,cl.CustomFieldKey as [CustomFieldKey3]
	,pt.PODCustomFieldKey as [CustomFieldKey4]
	,p.ProjectNumber as [Project Number]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]
	,p.Description as [Project Description]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project Complete Date]
	,p.CreatedDate as [Project Creation Date]
	,p.ProjectCloseDate as [Project Close Date]
	,Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project]
	,bg.BillingGroupCode as [Billing Group Code]
 	,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]
	,ps.ProjectStatus as [Project Status]
	,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
	,Case p.BillingMethod When 1 then ''Time and Materials'' when 2 then ''Fixed Fee'' else ''Retainer'' end as [Billing Method]
	,cl.CustomerID as [Client ID]
	,cl.CompanyName as [Client Name]
	,cl.CustomerID + '' '' + cl.CompanyName as [Client Full Name]
	,t.TaskID as [Task ID]
	,t.TaskName as [Task Name]
	,o.OfficeName as [Office Name]
	,o.OfficeColor as [Office Color]
	,pty.ProjectTypeName as [Project Type]
	,pty.ProjectTypeColor as [Project Type Color]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager]
	,LTRIM(RTRIM(ISNULL(bm.FirstName + '' '','''')  + ISNULL(bm.LastName,''''))) AS [Billing Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
	,pt.TransactionDate
	,DATENAME(Month, pt.TransactionDate) as [Transaction Month]
	,RIGHT(''0'' + CAST(DATEPART(Month, pt.TransactionDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, pt.TransactionDate) AS [Transaction Month Formatted]
	,CAST(DATEPART(Year, pt.TransactionDate) AS VARCHAR(4)) as [Transaction Year]
	,pt.Type as [Transaction Type]
	,pt.ItemID as [Item ID]
	,pt.ItemName as [Item Name]
	,pt.Quantity
	,pt.PurchasedFrom as [Purchased From]

	,p.EstLabor + p.ApprovedCOLabor as [Current Budget Labor Gross]
	,p.EstLabor + p.EstExpenses + ISNULL(p.SalesTax, 0) + p.ApprovedCOLabor + p.ApprovedCOExpense + ISNULL(p.ApprovedCOSalesTax, 0) as [Current Total Budget]
	,p.EstLabor + p.EstExpenses + p.ApprovedCOLabor + p.ApprovedCOExpense as [Current Total Budget wo Tax]

	,p.ApprovedCOExpense as [CO Budget Expense Gross]
	,p.ApprovedCOBudgetExp as [CO Budget Expense Net]
	,p.ApprovedCOHours as [CO Budget Hours]
	,p.ApprovedCOLabor as [CO Labor Gross]
	,p.ApprovedCOBudgetLabor as [CO Budget Labor Net]

	,p.EstExpenses as [Original Budget Expense Gross]
	,p.BudgetExpenses as [Original Budget Expense Net]
	,p.EstHours as [Original Budget Hours]
	,p.EstLabor as [Original Budget Labor Gross]
	,p.BudgetLabor as [Original Budget Labor Net]

	, ISNULL(ca.EstExpenses, 0) + ISNULL(ca.ApprovedCOExpense, 0) as [Campaign Budget Expense Gross]
	, ISNULL(ca.BudgetExpenses, 0) + ISNULL(ca.ApprovedCOBudgetExp, 0) as [Campaign Budget Expense Net]
	, ISNULL(ca.EstHours, 0) + ISNULL(ca.ApprovedCOHours, 0) as [Campaign Budget Hours]
	, ISNULL(ca.EstLabor, 0) + ISNULL(ca.ApprovedCOLabor, 0) as [Campaign Budget Labor Gross]
	, ISNULL(ca.BudgetLabor, 0) + ISNULL(ca.ApprovedCOBudgetLabor, 0) as [Campaign Budget Labor Net]

	,CASE Type
		WHEN ''LABOR'' THEN pt.CostRate
		ELSE pt.UnitCost
	END as [Unit Cost]
	,CASE Type
		WHEN ''LABOR'' THEN ROUND(pt.Quantity * pt.CostRate, 2) 
		Else pt.TotalCost
	END as [Total Cost]
	,CASE pt.Type WHEN ''LABOR'' THEN ROUND(pt.Quantity * pt.CostRate, 2) ELSE 0 END AS [Total Labor Cost]
	,pt.BillableCost as [Billable Amount]
	,case when pt.WriteOff = 1 then pt.TotalCostNet else 0 end as [Write Off Total Cost]
	,case when pt.WriteOff = 1 then pt.BillableCost else 0 end as [Write Off Billable Amount]
	,pt.TransferComment as [Transfer Comment]
	,pt.Comments
	,Case pt.WriteOff When 1 then ''YES'' else ''NO'' end as [Write Off]
	,Case pt.OnHold When 1 then ''YES'' else ''NO'' end as [On Hold]
	,Case pt.Status 
		When 1 then ''Not Sent''
		When 2 then ''Sent for Approval''
		When 3 then ''Rejected''
		When 4 then ''Approved''
	end as [Approval Status]
	,wor.ReasonName as [Write Off Reason]
	,pt.WriteOffComment AS [Write Off Comment]
	,rn.Title as [Retainer Name]
	,pbs.ProjectBillingStatus as [Project Billing Status]
	,wpi.PostingDate as [WIP Posting In Date]
	,wpo.PostingDate as [WIP Posting Out Date]
	,gl.AccountNumber AS [Expense Account Number]
	,gl.AccountName AS [Expense Account Name]
	,gl2.AccountNumber AS [Sales Account Number]
	,gl2.AccountName AS [Sales Account Name]
	,case when pt.WriteOff = 1 then pt.DateBilled else null end as [Write Off Date]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,cla.ClassID as [Class ID]
	,cla.ClassName as [Class Name]
	,ca.CampaignName as [Campaign Name]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignID + '' - '' +  ca.CampaignName as [Campaign Full Name]
	,cs.SegmentName as [Campaign Segment]

	-- All these should change if there is a billed expense receipt  	
	,case when er.InvoiceLineKey > 0 then pt.Description + '' - Prebilled on expense report''  else pt.Description end as [Transaction Description] 
	,case when er.InvoiceLineKey > 0 then er.AmountBilled else pt.AmountBilled end as [Amount Billed] 
	,case when er.InvoiceLineKey > 0 then er.DateBilled else pt.DateBilled end as [Date Billed]
	,case when er.InvoiceLineKey > 0 then eri.InvoiceNumber else i.InvoiceNumber end as [Invoice Number]
	,case when er.InvoiceLineKey > 0 then eri.PostingDate else i.PostingDate end as  [Invoice Posting Date]
	,case when er.InvoiceLineKey > 0 then pt.BillableCost - er.AmountBilled else pt.BilledDifference end as [Billed Difference]	
	,CASE 
		WHEN ISNULL(er.InvoiceLineKey, -1) > 0 THEN ''YES''
		WHEN ISNULL(pt.InvoiceLineKey, -1) > 0 THEN ''YES''
		ELSE ''NO''
	END AS [Billed On Invoice]
	,CASE 
		WHEN ISNULL(er.InvoiceLineKey, -1) = 0 THEN ''YES''
		WHEN ISNULL(pt.InvoiceLineKey, -1) = 0 THEN ''YES''
		ELSE ''NO''
	END AS [Marked as Billed]
	,v.CompanyName as [Vendor Name]
	,v.VendorID + '' '' + v.CompanyName as [Vendor Full Name]
	,cv.DivisionID as [Client Division ID]
	,cv.DivisionName as [Client Division]
	,cp.ProductName as [Client Product]
    ,cp.ProductID as [Client Product ID]
	,pt.DepartmentName AS [Transaction Department]
    ,case when pt.UIDTransferToKey is not null then ''YES''
		  when pt.TransferToKey is not null then ''YES''
		  else ''NO''
	 end as [Transferred Out]
    ,pt.TransferInDate as [Transferred In Date]
    ,pt.TransferOutDate as [Transferred Out Date]
    ,case when ISNULL(p.LayoutKey, 0) = 0 then pt.WorkTypeID 
		  else 
              case when pt.Type = ''LABOR'' then wts.WorkTypeID else wt.WorkTypeID end 
     end as [Billing Item ID] 
    ,case when ISNULL(p.LayoutKey, 0) = 0 then pt.WorkTypeName 
		  else 
              case when pt.Type = ''LABOR'' then isnull(wtcusts.Subject, wts.WorkTypeName) else isnull(wtcust.Subject, wt.WorkTypeName) end 
     end as [Billing Item Name] 
	,p.ProjectKey
	,pt.TitleName as [Billing Title Name]
	,pt.TitleID as [Billing Title ID]
	,case when pt.AdjustmentType is null then null
	      when pt.AdjustmentType = 0 and pt.TransferOutDate is not null then ''Transfer''
	      when pt.AdjustmentType = 1 then ''Edited after Posting to WIP''
	      when pt.AdjustmentType = 2 then ''Title Adjustment''
	      when pt.AdjustmentType = 3 then ''Undo Writeoff after Posting out of WIP''
	      else null
	      end as [Adjustment Type]
	,parentCompany.CompanyName as [Parent Company Name]
	,pcd.DivisionName as [Parent Division Name]
	,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Project Primary Contact]
	,bc.Email as [Project Primary Contact Email] 
	,Case ca.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active]
	,Case p.Active When 1 then ''YES'' else ''NO'' end as [Project Active]
	,pt.AppliedOrderNumber as [Applied Order Number]
	,p.ClientProjectNumber as [Client Project Number]
	,ct.CompanyTypeName as [Company Type]
	,ISNULL(pt.CurrencyID, pref.CurrencyID) AS [Currency] --Get currency from the project transaction, if there is no currency set, use home currency from preferences	
	,st.TaskID as [Summary Task ID]
	,st.TaskName as [Summary Task Name]
	,ISNULL(st.TaskID + '' '', '''') + ISNULL(st.TaskName, '''') as [Summary Task Full Name]
	,pt.TransactionApprovalDate As [Transaction Approval Date]
	,pt.TransactionPostingDate as [Transaction Posting Date]
	,pt.TransactionKey
	,case
		when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status < 4 and isnull(pt.OnHold,0) = 0 then ''Unapproved'' 
		when pt.WriteOff = 1 then ''Write Offs'' 
		when pt.InvoiceLineKey > 0 then ''Invoiced''
		when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status = 4 and pt.WriteOff = 0 and pt.InvoiceLineKey is null and isnull(pt.OnHold,0) = 0 then ''Unbilled''
		when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status = 4 and pt.WriteOff = 0 and pt.InvoiceLineKey = 0 and isnull(pt.OnHold,0) = 0 then ''Marked As Billed''
		when isnull(pt.OnHold,0) = 1 then ''On Hold''
		when pt.TransferOutDate is not null and isnull(pt.AdjustmentType,0) = 0 then ''Transferred''
		when pt.TransferOutDate is not null and pt.AdjustmentType > 0 then ''Adjusted''
	end as [Transaction Status]
	,case when pt.Contractor = 1 then ''YES'' else ''NO'' end as [Contractor]
From vProjectTrans pt (nolock)
	inner join tProject p (nolock) on pt.ProjectKey = p.ProjectKey
	left outer join tPreference pref (nolock) on pref.CompanyKey = p.CompanyKey
	Left Outer join tTask t (nolock) on pt.TaskKey = t.TaskKey
	Left Outer Join tProjectType pty (nolock) on p.ProjectTypeKey = pty.ProjectTypeKey
	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 bm (nolock) on p.BillingManagerKey = bm.UserKey
	Left Outer Join tInvoiceLine il (nolock) on pt.InvoiceLineKey = il.InvoiceLineKey
	Left Outer Join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	left outer join tCompany parentCompany (nolock) on cl.ParentCompanyKey = parentCompany.CompanyKey
	left outer join tClientDivision pcd (nolock) on cl.ParentCompanyDivisionKey = pcd.ClientDivisionKey
	Left outer Join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	Left outer Join tWriteOffReason wor (nolock) on pt.WriteOffReasonKey = wor.WriteOffReasonKey
	left outer join vUserName kp1 (nolock) on p.KeyPeople1 = kp1.UserKey
	left outer join vUserName kp2 (nolock) on p.KeyPeople2 = kp2.UserKey
	left outer join vUserName kp3 (nolock) on p.KeyPeople3 = kp3.UserKey
	left outer join vUserName kp4 (nolock) on p.KeyPeople4 = kp4.UserKey
	left outer join vUserName kp5 (nolock) on p.KeyPeople5 = kp5.UserKey
	left outer join vUserName kp6 (nolock) on p.KeyPeople6 = kp6.UserKey
	left outer join tRetainer rn (nolock) on p.RetainerKey = rn.RetainerKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	left outer join tWIPPosting wpi (nolock) on pt.WIPPostingInKey = wpi.WIPPostingKey
	left outer join tWIPPosting wpo (nolock) on pt.WIPPostingOutKey = wpo.WIPPostingKey
	left outer join tGLAccount gl (nolock) on pt.GLAccountKey = gl.GLAccountKey
	left outer join tClass cla (nolock) on pt.ClassKey = cla.ClassKey
	left outer join tGLCompany glc (nolock) on pt.GLCompanyKey = glc.GLCompanyKey
	left outer join tGLAccount gl2 (nolock) on pt.SalesAccountKey = gl2.GLAccountKey
	left outer join tExpenseReceipt er (nolock) on pt.Type = ''VOUCHER'' AND pt.TranKey = er.VoucherDetailKey
	Left Outer Join tInvoiceLine eril (nolock) on er.InvoiceLineKey = eril.InvoiceLineKey
	Left Outer Join tInvoice eri (nolock) on eril.InvoiceKey =eri.InvoiceKey
	Left Outer Join tCampaign ca (nolock) on p.CampaignKey = ca.CampaignKey
	left outer join tCompany v (nolock) on pt.VendorKey = v.CompanyKey
	left outer join tClientDivision cv (nolock) on p.ClientDivisionKey = cv.ClientDivisionKey
	left outer join tClientProduct cp (nolock) on p.ClientProductKey = cp.ClientProductKey

    left outer join tLayoutBilling lb (nolock) on p.LayoutKey = lb.LayoutKey and lb.Entity = ''tItem'' and pt.Type <> ''LABOR'' and lb.EntityKey = pt.ItemKey
    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 tLayoutBilling lbs (nolock) on p.LayoutKey = lbs.LayoutKey and lbs.Entity = ''tService'' and pt.Type = ''LABOR'' and lbs.EntityKey = pt.ItemKey
    left outer join tWorkType wts (nolock) on lbs.ParentEntityKey = wts.WorkTypeKey and lbs.ParentEntity = ''tWorkType''
    left outer join tWorkTypeCustom wtcusts (nolock) on lbs.ParentEntityKey = wtcusts.WorkTypeKey and wtcusts.Entity = ''tProject'' and wtcusts.EntityKey = p.ProjectKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	left outer join tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey 
	left outer join tCompanyType ct (nolock) on cl.CompanyTypeKey = ct.CompanyTypeKey
	left outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoEventActionUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoEventActionUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE procedure [dbo].[sptAutoEventActionUpdate]
	@EventActionKey int,
	@Errors varchar(max),
	@Results varchar(max)
AS
	UPDATE	tAutoEventAction
	SET		Status = CASE
				WHEN ISNULL(@Errors, '''') = '''' THEN ''completed'' 
				ELSE ''error''
			END,
			Errors = @Errors,
			Results = @Results,
			EndTime = GETUTCDATE()
	WHERE	EventActionKey = @EventActionKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_Transactions]'
GO
IF OBJECT_ID(N'[dbo].[vReport_Transactions]', 'V') IS NOT NULL
EXEC sp_executesql N'









ALTER VIEW [dbo].[vReport_Transactions]
AS

/*
|| When     Who Rel     What
|| 10/11/06 WES 8.3567  Added Date Billed
|| 10/12/06 WES 8.3567  Added Retainer Name
|| 10/13/06 WES 8.3567  Added Project Billing Status
|| 10/16/06 WES 8.3567  Added Posting Date
|| 12/18/06 GWG 8.4     Added WIP Posting Dates
|| 12/21/06 CRG 8.4     Added Billed On Invoice, Invoice Posting Date, Expense Account Number, Expense Account Name
|| 02/26/07 BSH 8.4     Added WriteOff Date, Cost and Billable Amount
|| 10/11/07 CRG 8.5     Added GLCompany, Class
|| 11/07/07 CRG 8.5     (9205) Modified to get Class from the Transactions rather than the Project.
|| 11/07/07 CRG 8.5     (9581) Added Marked as Billed
|| 02/01/08 GHL 8.5     (20472) Added logic for expense receipts on voucher
|| 03/04/08 GWG 8.5     (22285) Changed Writeoff amount to be sensitive to the write off field
|| 03/08/08 GWG 8.5     (22734) Added Campaign Name
|| 04/02/09 RLB 10.02.2 (50160) Fixed project billing status it was not pulling data correctly
|| 04/08/09 GHL 10.022  (50462) Added Vendor Name and Total Labor Cost
|| 04/14/09 GHL 10.023  (51139) Added Client Division/Client Product 
|| 04/14/09 GHL 10.023  (51139) Added Company Type/Last Task Due Date
|| 04/24/09 MFT 10.024	(51139) Added Transaction Department
|| 06/15/09 GHL 10.027  (54845) Added Transaction Number to get v.InvoiceNumber, ee.EnvelopeNumber + user
|| 09/11/09 GHL 10.5     Added Transferred Out
|| 01/19/10 GHL 10.517  (72527) Added Billing Item info
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
|| 07/13/11 RLB 10.546  (114349) Added Sales Account
|| 07/27/11 RLB 10.546  (111324) Added Campaign Segment
|| 09/20/11 RLB 10.548  (121590) Removed Total Labor Cost column per Mikes request
|| 09/21/11 RLB 10.548  (119193) Added Project Close Date
|| 06/22/12 RLB 10.557  (146849) Added Transaction Month and year
|| 08/17/12 RLB 10.559 (151960) Added Billing Group Code
|| 09/28/12 GHL 10.560 Getting now BillingGroupCode from tBillingGroup
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey
|| 11/15/12 GWG 10.5.6.2 Added transfer in out dates
|| 01/30/13 GHL 10.5.6.4 (166680) Added Billing Method
|| 04/22/14 WDF 10.5.7.9 (219319) Added Posted to WIP
|| 11/06/14 WDF 10.5.8.6 (233050) Added Billing Manager
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
|| 01/28/15 GHL 10.5.8.8 Added title for Abelson
|| 03/20/15 WDF 10.5.9.0 (Abelson Taylor) Added AdjustmentType
|| 04/30/15 GHL 10.5.9.1 (253984) Added 20 project and campaign budget fields  (enhancement for Concentrix)
|| 10/05/15 GHL 10.5.9.7 (272410) Added check of Write Off flag when pulling Write Off Date
|| 04/12/16 MFT 10.6.0.3 (296036) Added WriteOffComment
|| 06/08/16 WDF 10.6.0.5 (303066) Added PurchasedFrom
|| 07/12/16 WDF 10.6.0.6 (299976) Added Campaign Custom Fields
|| 08/16/16 KMC 10.6.0.7 (308209) Added [Parent Company Name] and [Parent Division Name] from the company page (Client Setup...Billing).
|| 02/08/17 WDF 10.6.1.3 (331895) Added [Project Description]
|| 05/20/17 GWG 10.6.1.5 Added project primary contact and email
|| 05/15/18 GWG 18.5.0.0 added campaign active
|| 08/15/18 WDF 18.9.0.0 (415376) Added [CustomFieldKey3]
|| 12/06/18 MFT 19.1.0.0 (434596) Wrapped LayoutKey in ISNULL
|| 12/07/18 GHL 19.1.0.0 (424920) Added [Gross Amount] = GrossAmount (mainly for VIs with prebilled POs applied 
||                        , in that case GrossAmount = 1000 and BillableCost = 0 )
|| 05/06/19 MCM 19.0.5.0 (449142) Adding unit Rate from the voucher detail
|| 05/13/19 GHL 19.0.6.0 (459967) Added Applied Order number
|| 07/09/19 RLS 19.0.8.0 (468625) Added [Summary Task ID], [Summary Task Name] and [Summary Task Full Name]
|| 07/18/19 GAR 19.0.8.0 (470619) Adding Project Manager
|| 07/29/19 WDF 19.0.8.0 (471596) Corrected alias of [Campaign Active] from cp to ca
|| 07/30/19 WDF 19.0.8.0 (472402) Corrected format of [Campaign Full Name] for linking in Report
|| 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
|| 02/18/20 AMP 20.0.3.0 (500814) Added Client Project Number 
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 05/18/21 AMP 21.06.20.0000 (558708) Added currency field 
|| 11/11/21 GHL 21.12.19.0000 (570243) Added UIDTranKey so that can be used for service updates, and Transaction Status
|| 12/20/21 GHL 22.01.16 (580428) Added WIP Anount
|| 01/13/22 MCM 22.02.X  (583929) For the client Full Name, added an isNull around the client ID, for opportunities before the client Key is set.
|| 05/16/22 RLS 22.06.19 (596563) Added [Transaction Month Formatted]
|| 08/03/22 MFT 22.0.8.0 (607757) Added "s" to "Time and Material"
|| 11/29/22 RLS 22.12.18 (614994) Added TransactionApprovalDate
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color
|| 05/30/23 RLS 23.16.18 (635138) Added TransactionPostingDate
|| 08/11/23 RLB 23.09.17 (648008) added project type color
|| 06/04/25 MCM 25.07.x  (700642) Added TransactionKey - type + underlying Key field
|| 09/04/25 RLS 25.09.21 (708615) Added PODCustomFieldKey
|| 09/08/25 MCM 25.09.x  (710678) Updated logic for "Marked as Billed" for expense reports where they''ve been converted to vouchers
|| 04/28/26 RLS 26.05.17 (724768) Added [Contractor]
*/

Select 
	p.CompanyKey
	,pt.GLCompanyKey
	,p.CustomFieldKey
	,ca.CustomFieldKey as [CustomFieldKey2]
	,cl.CustomFieldKey as [CustomFieldKey3]
	,pt.PODCustomFieldKey as [CustomFieldKey4]
	,p.ProjectNumber as [Project Number]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]
	,p.Description as [Project Description]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project Complete Date]
	,p.CreatedDate as [Project Creation Date]
	,p.ProjectCloseDate as [Project Close Date]

	,p.EstExpenses + p.ApprovedCOExpense as [Current Budget Expense Gross]
	,p.EstHours + p.ApprovedCOHours as [Current Budget Hours]
	,p.EstLabor + p.ApprovedCOLabor as [Current Budget Labor Gross]
	,p.EstLabor + p.EstExpenses + ISNULL(p.SalesTax, 0) + p.ApprovedCOLabor + p.ApprovedCOExpense + ISNULL(p.ApprovedCOSalesTax, 0) as [Current Total Budget]
	,p.EstLabor + p.EstExpenses + p.ApprovedCOLabor + p.ApprovedCOExpense as [Current Total Budget wo Tax]

	,p.ApprovedCOExpense as [CO Budget Expense Gross]
	,p.ApprovedCOBudgetExp as [CO Budget Expense Net]
	,p.ApprovedCOHours as [CO Budget Hours]
	,p.ApprovedCOLabor as [CO Labor Gross]
	,p.ApprovedCOBudgetLabor as [CO Budget Labor Net]

	,p.EstExpenses as [Original Budget Expense Gross]
	,p.BudgetExpenses as [Original Budget Expense Net]
	,p.EstHours as [Original Budget Hours]
	,p.EstLabor as [Original Budget Labor Gross]
	,p.BudgetLabor as [Original Budget Labor Net]
	,Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project]

	, ISNULL(ca.EstExpenses, 0) + ISNULL(ca.ApprovedCOExpense, 0) as [Campaign Budget Expense Gross]
	, ISNULL(ca.BudgetExpenses, 0) + ISNULL(ca.ApprovedCOBudgetExp, 0) as [Campaign Budget Expense Net]
	, ISNULL(ca.EstHours, 0) + ISNULL(ca.ApprovedCOHours, 0) as [Campaign Budget Hours]
	, ISNULL(ca.EstLabor, 0) + ISNULL(ca.ApprovedCOLabor, 0) as [Campaign Budget Labor Gross]
	, ISNULL(ca.BudgetLabor, 0) + ISNULL(ca.ApprovedCOBudgetLabor, 0) as [Campaign Budget Labor Net]
	
	,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Project Primary Contact]
	,bc.Email as [Project Primary Contact Email] 
	,bg.BillingGroupCode as [Billing Group Code]
 	,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]
	,ps.ProjectStatus as [Project Status]
	,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
	,Case p.BillingMethod When 1 then ''Time and Materials'' when 2 then ''Fixed Fee'' else ''Retainer'' end as [Billing Method]
	,cl.CustomerID as [Client ID]
	,cl.CompanyName as [Client Name]
	,LTRIM(RTRIM(ISNULL(cl.CustomerID + '' '', ''''))) + cl.CompanyName as [Client Full Name]
	,t.TaskID as [Task ID]
	,t.TaskName as [Task Name]
	,o.OfficeName as [Office Name]
	,o.OfficeColor as [Office Color]
	,pty.ProjectTypeName as [Project Type]
	,pty.ProjectTypeColor as [Project Type Color]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager]
	,LTRIM(RTRIM(ISNULL(bm.FirstName + '' '','''')  + ISNULL(bm.LastName,''''))) AS [Billing Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
	,pt.TransactionDate
	,DATENAME(Month, pt.TransactionDate) as [Transaction Month]
	,RIGHT(''0'' + CAST(DATEPART(Month, pt.TransactionDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, pt.TransactionDate) AS [Transaction Month Formatted]
	,CAST(DATEPART(Year, pt.TransactionDate) AS VARCHAR(4)) as [Transaction Year]
	,pt.Type as [Transaction Type]
	,pt.PurchasedFrom as [Purchased From]
	,pt.ItemID as [Item ID]
	,pt.ItemName as [Item Name]
	,pt.Quantity
	,pt.UnitCost as [Unit Cost]
	,pt.TotalCost as [Total Cost]
	,pt.BillableCost as [Billable Amount]
	,pt.GrossAmount as [Gross Amount]
	,case when pt.WriteOff = 1 then pt.TotalCost else 0 end as [Write Off Total Cost]
	,case when pt.WriteOff = 1 then pt.BillableCost else 0 end as [Write Off Billable Amount]
	,pt.TransferComment as [Transfer Comment]
	,pt.Comments
	,Case pt.WriteOff When 1 then ''YES'' else ''NO'' end as [Write Off]
	,Case pt.OnHold When 1 then ''YES'' else ''NO'' end as [On Hold]
	,Case pt.Status 
		When 1 then ''Not Sent''
		When 2 then ''Sent for Approval''
		When 3 then ''Rejected''
		When 4 then ''Approved''
	end as [Approval Status]
	,wor.ReasonName as [Write Off Reason]
	,pt.WriteOffComment AS [Write Off Comment]
	,rn.Title as [Retainer Name]
	,pbs.ProjectBillingStatus as [Project Billing Status]
	,wpi.PostingDate as [WIP Posting In Date]
	,wpo.PostingDate as [WIP Posting Out Date]
	,gl.AccountNumber AS [Expense Account Number]
	,gl.AccountName AS [Expense Account Name]
	,gl2.AccountNumber AS [Sales Account Number]
	,gl2.AccountName AS [Sales Account Name]
	,case when pt.WriteOff = 1 then pt.DateBilled else null end as [Write Off Date]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,cla.ClassID as [Class ID]
	,cla.ClassName as [Class Name]
	,ca.CampaignName as [Campaign Name]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignID + '' - '' +  ca.CampaignName as [Campaign Full Name]
	,cs.SegmentName as [Campaign Segment]

	-- All these should change if there is a billed expense receipt  	
	,case when er.InvoiceLineKey > 0 then pt.Description + '' - Prebilled on expense report''  else pt.Description end as [Transaction Description] 
	,case when er.InvoiceLineKey > 0 then er.AmountBilled else pt.AmountBilled end as [Amount Billed] 
    ,case when er.InvoiceLineKey > 0 then
		case when isnull(eri.InvoiceStatus, 0) = 4 then er.AmountBilled else 0 end
    else
		case when isnull(i.InvoiceStatus, 0) = 4 then pt.AmountBilled else 0 end
	end as [Amount Billed Approved]
	,case when er.InvoiceLineKey > 0 then er.DateBilled else pt.DateBilled end as [Date Billed]
	,case when er.InvoiceLineKey > 0 then eri.InvoiceNumber else i.InvoiceNumber end as [Invoice Number]
	,case when er.InvoiceLineKey > 0 then eri.PostingDate else i.PostingDate end as  [Invoice Posting Date]
	,case when er.InvoiceLineKey > 0 then pt.BillableCost - er.AmountBilled else pt.BilledDifference end as [Billed Difference]	
	,CASE 
		WHEN ISNULL(er.InvoiceLineKey, -1) > 0 THEN ''YES''
		WHEN ISNULL(pt.InvoiceLineKey, -1) > 0 THEN ''YES''
		ELSE ''NO''
	END AS [Billed On Invoice]
	,CASE 
		WHEN ISNULL(er.InvoiceLineKey, -1) = 0 AND ISNULL(er.VoucherDetailKey, 0) = 0 THEN ''YES''
		WHEN ISNULL(pt.InvoiceLineKey, -1) = 0 THEN ''YES''
		ELSE ''NO''
	END AS [Marked as Billed]
	,v.CompanyName as [Vendor Name]
	,v.VendorID + '' '' + v.CompanyName as [Vendor Full Name]
	,cv.DivisionName as [Client Division]
	,cv.DivisionID as [Client Division ID]
	,cp.ProductName as [Client Product]
	,cp.ProductID as [Client Product ID]
	,ct.CompanyTypeName as [Company Type]
	,(SELECT MAX(t2.PlanComplete) FROM tTask t2 (NOLOCK) WHERE t2.ProjectKey = p.ProjectKey) as [Last Task Due Date]
	,pt.DepartmentName AS [Transaction Department]
    ,pt.TranNumber AS [Transaction Number]
    ,pt.EnteredByUser AS [Entered By]
    ,case when pt.UIDTransferToKey is not null then ''YES''
          when pt.TransferToKey is not null then ''YES''
          else ''NO''
     end as [Transferred Out]
    ,pt.TransferInDate as [Transferred In Date]
    ,pt.TransferOutDate as [Transferred Out Date]
    ,case when ISNULL(p.LayoutKey, 0) = 0 then pt.WorkTypeID 
		  else 
              case when pt.Type = ''LABOR'' then wts.WorkTypeID else wt.WorkTypeID end 
     end as [Billing Item ID] 
    ,case when ISNULL(p.LayoutKey, 0) = 0 then pt.WorkTypeName 
		  else 
              case when pt.Type = ''LABOR'' then isnull(wtcusts.Subject, wts.WorkTypeName) else isnull(wtcust.Subject, wt.WorkTypeName) end 
     end as [Billing Item Name]
	,Case p.DoNotPostWIP WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Do Not Post WIP]
    ,p.ProjectKey
    ,pt.TitleName as [Billing Title Name]
    ,pt.TitleID as [Billing Title ID]
	,case when pt.AdjustmentType is null then null
	      when pt.AdjustmentType = 0 and pt.TransferOutDate is not null then ''Transfer''
	      when pt.AdjustmentType = 1 then ''Edited after Posting to WIP''
	      when pt.AdjustmentType = 2 then ''Title Adjustment''
	      when pt.AdjustmentType = 3 then ''Undo Writeoff after Posting out of WIP''
	      else null
	      end as [Adjustment Type]
	,parentCompany.CompanyName as [Parent Company Name]
	,pcd.DivisionName as [Parent Division Name]
	,Case ca.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active]
	,Case p.Active When 1 then ''YES'' else ''NO'' end as [Project Active]
	,pt.UnitRate as [Unit Rate]
	,pt.AppliedOrderNumber as [Applied Order Number] 
	,st.TaskID as [Summary Task ID]
	,st.TaskName as [Summary Task Name]
	,ISNULL(st.TaskID + '' '', '''') + ISNULL(st.TaskName, '''') as [Summary Task Full Name]
	,p.ClientProjectNumber as [Client Project Number]	
	,ISNULL(pt.CurrencyID, pref.CurrencyID) AS [Currency]
	,pt.UIDTranKey -- This is TimeKey used for service updates

	,case
		when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status < 4 and isnull(pt.OnHold,0) = 0 then ''Unapproved'' 
		--when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status = 4 and pt.WriteOff = 1 then ''Write Off'' 
		when pt.WriteOff = 1 then ''Write Offs'' 
		when pt.InvoiceLineKey > 0 then ''Invoiced''
		when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status = 4 and pt.WriteOff = 0 and pt.InvoiceLineKey is null and isnull(pt.OnHold,0) = 0 then ''Unbilled''
		when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status = 4 and pt.WriteOff = 0 and pt.InvoiceLineKey = 0 and isnull(pt.OnHold,0) = 0 then ''Marked As Billed''
		--when pt.TransferToKey is null and pt.UIDTransferToKey is null and isnull(pt.OnHold,0) = 1 then ''On Hold''
		when isnull(pt.OnHold,0) = 1 then ''On Hold''
		when pt.TransferOutDate is not null and isnull(pt.AdjustmentType,0) = 0 then ''Transferred''
		when pt.TransferOutDate is not null and pt.AdjustmentType > 0 then ''Adjusted''
	end as [Transaction Status]

	,pt.WIPAmount as [WIP Amount]
	,pt.TransactionApprovalDate As [Transaction Approval Date]
	,pt.TransactionPostingDate as [Transaction Posting Date]
	,pt.TransactionKey
	,case when pt.Contractor = 1 then ''YES'' else ''NO'' end as [Contractor]

From vProjectTrans pt (nolock)
	inner join tProject p (nolock) on pt.ProjectKey = p.ProjectKey
	left outer join tPreference pref (nolock) on pref.CompanyKey = p.CompanyKey
	Left Outer join tTask t (nolock) on pt.TaskKey = t.TaskKey
	Left Outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey 
	Left Outer Join tProjectType pty (nolock) on p.ProjectTypeKey = pty.ProjectTypeKey
	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 bm (nolock) on p.BillingManagerKey = bm.UserKey
	Left Outer Join tInvoiceLine il (nolock) on pt.InvoiceLineKey = il.InvoiceLineKey
	Left Outer Join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	left outer join tCompany parentCompany (nolock) on cl.ParentCompanyKey = parentCompany.CompanyKey
	left outer join tClientDivision pcd (nolock) on cl.ParentCompanyDivisionKey = pcd.ClientDivisionKey
	Left outer Join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	Left outer Join tWriteOffReason wor (nolock) on pt.WriteOffReasonKey = wor.WriteOffReasonKey
	left outer join vUserName kp1 (nolock) on p.KeyPeople1 = kp1.UserKey
	left outer join vUserName kp2 (nolock) on p.KeyPeople2 = kp2.UserKey
	left outer join vUserName kp3 (nolock) on p.KeyPeople3 = kp3.UserKey
	left outer join vUserName kp4 (nolock) on p.KeyPeople4 = kp4.UserKey
	left outer join vUserName kp5 (nolock) on p.KeyPeople5 = kp5.UserKey
	left outer join vUserName kp6 (nolock) on p.KeyPeople6 = kp6.UserKey
	left outer join tRetainer rn (nolock) on p.RetainerKey = rn.RetainerKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	left outer join tWIPPosting wpi (nolock) on pt.WIPPostingInKey = wpi.WIPPostingKey
	left outer join tWIPPosting wpo (nolock) on pt.WIPPostingOutKey = wpo.WIPPostingKey
	left outer join tGLAccount gl (nolock) on pt.GLAccountKey = gl.GLAccountKey
	left outer join tGLAccount gl2 (nolock) on pt.SalesAccountKey = gl2.GLAccountKey
	left outer join tClass cla (nolock) on pt.ClassKey = cla.ClassKey
	left outer join tGLCompany glc (nolock) on pt.GLCompanyKey = glc.GLCompanyKey
	left outer join tExpenseReceipt er (nolock) on pt.Type = ''VOUCHER'' AND pt.TranKey = er.VoucherDetailKey
	Left Outer Join tInvoiceLine eril (nolock) on er.InvoiceLineKey = eril.InvoiceLineKey
	Left Outer Join tInvoice eri (nolock) on eril.InvoiceKey =eri.InvoiceKey
	Left Outer Join tCampaign ca (nolock) on p.CampaignKey = ca.CampaignKey
	left outer join tCompany v (nolock) on pt.VendorKey = v.CompanyKey
	left outer join tClientDivision cv (nolock) on p.ClientDivisionKey = cv.ClientDivisionKey
    left outer join tClientProduct cp (nolock) on p.ClientProductKey = cp.ClientProductKey
    left outer join tCompanyType ct (nolock) on cl.CompanyTypeKey = ct.CompanyTypeKey

    left outer join tLayoutBilling lb (nolock) on p.LayoutKey = lb.LayoutKey and lb.Entity = ''tItem'' and pt.Type <> ''LABOR'' and lb.EntityKey = pt.ItemKey
    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 tLayoutBilling lbs (nolock) on p.LayoutKey = lbs.LayoutKey and lbs.Entity = ''tService'' and pt.Type = ''LABOR'' and lbs.EntityKey = pt.ItemKey
    left outer join tWorkType wts (nolock) on lbs.ParentEntityKey = wts.WorkTypeKey and lbs.ParentEntity = ''tWorkType''
    left outer join tWorkTypeCustom wtcusts (nolock) on lbs.ParentEntityKey = wtcusts.WorkTypeKey and wtcusts.Entity = ''tProject'' and wtcusts.EntityKey = p.ProjectKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	left outer join tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoEventUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoEventUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE procedure [dbo].[sptAutoEventUpdate]
	@AutoEventKey int,
	@Errors varchar(max)
AS

	UPDATE	tAutoEvent
	SET		Status = CASE
				WHEN ISNULL(@Errors, '''') = '''' THEN ''completed'' 
				ELSE ''error''
			END,
			Errors = @Errors
	WHERE	AutoEventKey = @AutoEventKey'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vListing_Company]'
GO
IF OBJECT_ID(N'[dbo].[vListing_Company]', 'V') IS NOT NULL
EXEC sp_executesql N'









ALTER VIEW [dbo].[vListing_Company]
AS  

/*
  || When     Who Rel     What
  || 10/16/06 WES 8.3567  Added Comments field
  || 10/16/06 WES 8.3567  Added Date Added field
  || 03/27/07 RTC 8.4.1   (7434) Added Invoice Template, Default Billing Method, One Invoice Per,
                          One Line Per, Default Terms, Estimate Template, Get Rate From Labor, Get Rate From Expenses,
 						  Item Rate Sheet, Item Markup, Prebill Insertions At, Prebill Broadcast At
  || 05/07/07 CRG 8.4.3   (9029) Added Sales Tax 1 and Sales Tax 2
  || 10/4/07  GWG 8.4.3   Added Labor Rate Sheet, modified name of item rate sheet to expense rate sheet
  || 11/06/07 CRG 8.5     (13138) Added Account Team
  || 02/08/08 CRG 1.0.0.0 Added Created By, Date Updated, Last Modified By
  || 02/29/08 CRG 1.0.0.0 Added ASC_Selected
  || 03/27/08 GWG 8.5     Added Vendor Discount Percent and days
  || 07/29/08 GHL 1.0.0.5 Added CMFolderKey since it affects the rights
  || 02/09/09 GWG 10.5	  Made cmfolderkey force to 0 so that a no folder check can be made.
  || 03/11/09 MAS 10.5	  Added Last and Next Activity columns, renamed columns, removed user_defined columns.
  || 04/03/09 GWG 10.5    Minor fixes to views
  || 04/29/09 RLB 10.024  (50919) Pulling just date on b.DateAdded
  || 04/30/09 CRG 10.500  Added Next/Last Activity Types, Days Since Last Activity, and No Activity Since
  || 9/22/09  CRG 10.511  (63789) Added new options for DefaultARLineFormat
  || 09/24/09 RLB 10.511  (63767) wrapped c.Type1099 in isnull was not displaying no in listing when it was null
  || 01/19/10 RLB 10.517  (72560) Added Over Head Client to the listing
  || 06/11/10 GWG 10.531  (82828) Fixed the Date converted. should come from the primary cont. not acct manager.
  || 07/09/10 RLB 10.532  (82828) changed Date Converted to the Companies Date Converted.
  || 10/06/10 RLB 10.536   added Primary Contact Phone 1 and 2
  || 11/1/10  RLB 10.537  (89516) Added DBA for voucher listing
  || 03/30/12 RLB 10.554  (138232) Added Default Expense Account
  || 05/03/12 RLB 10.555  (126104) Added Default Sales Account
  || 12/07/12 WDF 10.563  (161600) Added Default GL Company
  || 02/13/13 WDF 10.565  (168570) [Last Modified By] using the wrong alias of [Created By]
  || 03/25/13 WDF 10.566  (172384) Added [Account Manager Active]
  || 06/28/13 GHL 10.569  (182649) Added [Vendor Accepts Credit Cards]
  || 02/13/14 WDF 10.577  (206358) Added [One Payment Per Invoice] and [Print DBA On Check]
  || 04/09/14 GHL 10.579  Added CurrencyID
  || 07/18/14 WDF 10.582  Added IO/BC Commission 
  || 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
  || 11/17/14 GAR 10.586  (236376) Added option 9 to [One Line Item Per] because it wasn''t being populated in 
  ||					  the companies listing screen when that option was chosen.
  || 01/28/15 GHL 10.588  Added new Line Formats for Abelson Taylor
  || 01/30/15 WDF 10.588  (244159) Added Billing Name and Email Invoices To
  || 02/10/15 KMC 10.589  (245859) Added Default AP Account
  || 02/11/15 KMC 10.589  (245859) Added Vendor Sales Tax 1 and Vendor Sales Tax 2
  || 03/05/15 GWG 10.590  Added Credit Card info
  || 05/05/15 KMC 10.591  (252479) Added masking of EINNumber on tCompany
  || 05/14/15 QMD 10.592  (256902) Tweaked ein masking slightly
  || 07/01/15 WDF 10.593  (262005) Added Payment Address
  || 09/27/15 GWG 10.5.9.6 change next and last act date to DateModified
  || 11/11/15 GWG 10.5.9.7 Revert the next last act date change
  || 01/13/16 WDF 10.6.0.0 (285154) Added [On Hold]
  || 01/28/16 MCM 10.6.0.0 (274838) Added Billing Manager
  || 03/18/16 WDF 10.6.0.0 (293854) Added [Default Layout Name]
  || 12/19/16 MAS 10.6.0.0 (322283) Added [Vendor Accepts VCards]
  || 08/02/17 WDF 10.6.1.8 (357243) Added [Default Office]
  || 02/19/18 GAR 18.3.0.0  (373196) Added No Folder as NULL option to aid in searching
  || 06/19/18 GHL 18.7.0.0 (406799) Added One Line Per (Fixed Fee) or FF line format
  || 07/25/18 RLB 18.8.0   (401369) Added Default Project Hourly Rate
  || 10/08/18 GHL 18.920   (349590) Added Labor Taxable
  || 11/02/18 WDF 19.2.0   (401369) Changed ''One Line Item Per (Fixed Fee)'' to ''One Line Item Per Fixed Fee'' because
                                    it was being translated to ''One Line Item Per _x0028_Fixed Fee_x0029_'' in Flash
                                    and causes all data from the following fields to be pulled into that field in Platinum.
  || 12/03/18 MCM 19.1.0   (432358) Removed "Vendor Credit Cards Accepted" since duplicate of "Accepts Credit Cards".  Also Changed from "Vendor Accepts VCards" to "Accepts VPay"
  || 04/02/19 RLB 19.0.4.0 (453535) added Date Added With Time since date add is stripped of time for filtering
  || 06/03/19 AMP 19.0.7.0 (463228) Added Default AR Account
  || 06/06/19 RLB 19.0.7.0 (446229) Adding Project Manager
  || 07/19/19 GAR 19.0.8.0 (470896) Adding NextProjectNum
  || 01/03/20 GAR 20.0.2.0 (493902) Added Primary Contact Email 
  || 01/16/20 AMP 20.0.2.0 (495449) Added Credit Card Exp Date column
  || 02/25/20 MCM 20.0.3.0 (502409) Updated logic of "Client Rate" column.  Only return value if get rate from = project (ie 2).  
  || 03/18/20 AMP 20.0.4.0 (507139) Added "Allow Credit Card Payments Online"
  || 04/08/20 MCM 20.0.5.0 (509727) Added "ACH Enabled"
  || 05/01/20 RLB 20.0.6.0 (513837) wrapped primary contact fist and last names
  || 06/16/20 MCM 20.0.7.0 (519216) Added IsNull around first and last name of "Email Invoices To"
  || 06/23/20 RLS 20.6.0.0  (517148) Added TwitterID
  || 08/18/20 MCM 20.0.9.0 (475239) Added companymetrics fields
  || 08/24/20 RLS 20.0.9.0 (522703) Added [Next Campaign Number]
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 09/25/20 MFT 20.1.1.0 (528335) Added NEC to Type1099 enum
  || 01/26/21 AMP 22.02.14 (544997) Added Default Approver Person
  || 12/20/21 MCM 22.02.14 (581037) Added ACH Email 
  || 01/27/22 GHL 22.02.20 (564369) Added Active Client and Active Vendor new fields
  || 09/16/22 GAR 22.10.16 (612270) Added GL Company Access Restrictions
  || 05/12/23 AMP 23.06.18 (629929) Added "Allow ACH Payments Online"
  || 06/14/23 GAR 23.07.16 (632579) Added Do not use for Projects or Project Requests
  || 11/29/23 RLB 23.12.17 (653809) added UseDBAForPayment1099 
  || 01/16/24 RLS 24.02.18 (659920) Added [Bank Account Type]
  || 09/05/24 GAR 24.10.20 (682270) Added Avalara Tax Code and Description
  || 09/11/24 GAR 24.10.20 (682936) Added Avalara Tax Exempt Reason
  || 02/24/26 RLS 26.03.15 (720029) Added [Require Comments on Time Entries]
  || 04/14/26 RLS 26.05.17 (602837) Changed the logic for [One Line Item Per] to be consistant with billing.clients.edit
*/

SELECT
	c.OwnerCompanyKey AS OwnerCompanyKey,  
	c.CompanyKey,  
	c.Vendor,  
	c.BillableClient,   
	c.CustomFieldKey,  
	c.ContactOwnerKey,
	ISNULL(c.CMFolderKey, 0) AS CMFolderKey,
	c.CompanyKey AS ContactCompanyKey,  --Needed for defaulting information into activity
	c.PrimaryContact,
	c.CompanyName,
	LTRIM(RTRIM(ISNULL(pct.FirstName + '' '','''')  + ISNULL(pct.LastName,''''))) AS ContactName,
	c.CompanyName AS [Company Name],
	c.DBA AS [DBA],   
	c.VendorID AS [Vendor ID],   
	c.CustomerID AS [Client ID], 
	LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Email Invoices To],
	ad.Address1 AS [Mailing Address1],   
	ad.Address2 AS [Mailing Address2],   
	ad.Address3 AS [Mailing Address3],   
	ad.City AS [Mailing City],   
	ad.State AS [Mailing State],   
	ad.PostalCode AS [Mailing Postal Code],   
	ad.Country AS [Mailing Country],   
	CASE
		WHEN c.ParentCompany = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Parent Company],  
	pc.CompanyName AS [Parent Company Name],  
	CASE
		WHEN c.Vendor = 1 THEN ''YES''
		ELSE ''NO'' 
	END AS [Is a Vendor],   
	CASE 
		WHEN c.BillableClient = 1 THEN ''YES'' 
		ELSE ''NO'' 
	END AS [Is a Client],   
	CASE 
		WHEN c.GetRateFrom <> 2 then 0
		ELSE c.HourlyRate 
	END AS [Client Rate],   
	c.BillingName AS [Billing Name],
	ab.Address1 AS [Billing Address1],   
	ab.Address2 AS [Billing Address2],   
	ab.Address3 AS [Billing Address3],   
	ab.City AS [Billing City],   
	ab.State AS [Billing State],   
	ab.PostalCode AS [Billing Postal Code],   
	ab.Country AS [Billing Country],   
	c.WebSite AS [Web Site],   
	c.Phone AS [Main Phone],   
	c.Fax AS [Main Fax],   
	o.OfficeName as [Default Office],   
	CASE
		WHEN c.Active = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Active],
	CASE
		WHEN isnull(c.BillableClient,0) = 1 and isnull(c.ActiveClient,0) = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Active Client],
	CASE
		WHEN isnull(c.Vendor,0) = 1 and isnull(c.ActiveVendor,0) = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Active Vendor],    
	CASE c.Type1099 
		WHEN 1 THEN ''MISC''
		WHEN 2 THEN ''INT''
		WHEN 3 THEN ''NEC''
	END AS [Form 1099 Type],
	CASE isnull(c.Type1099, 0)
		WHEN 0 THEN ''NO''
		ELSE ''YES''
	END AS [Is 1099],  
	c.Box1099 AS [Form 1099 Box],  	
	CASE
		WHEN LEN(c.EINNumber) >= 3 THEN ''*********'' + SUBSTRING(c.EINNumber, LEN(c.EINNumber) - 2, 3)
		ELSE c.EINNumber
	END AS [EIN Number],
	ct.CompanyTypeName AS [Company Type],  
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Account Manager Full Name],
	CASE u.Active
		WHEN 1 THEN ''YES''
		ELSE ''NO'' 
	END AS [Account Manager Active],  
	LTRIM(RTRIM(ISNULL(upm.FirstName + '' '','''')  + ISNULL(upm.LastName,''''))) AS [Project Manager Full Name],
	CASE upm.Active
		WHEN 1 THEN ''YES''
		ELSE ''NO'' 
	END AS [Project Manager Active],  
	LTRIM(RTRIM(ISNULL(pct.FirstName + '' '','''')  + ISNULL(pct.LastName,''''))) AS [Primary Contact Name], 
	pct.Phone1 AS [Primary Contact Phone 1],
	pct.Phone2 AS [Primary Contact Phone 2],
	LTRIM(RTRIM(ISNULL(owner.FirstName + '' '','''')  + ISNULL(owner.LastName,''''))) AS  [Company Owner],
	c.Comments,
	c.DateConverted AS [Date Converted],
	Cast(Cast(Month(c.DateAdded) AS VARCHAR) + ''/'' + Cast(Day(c.DateAdded) AS VARCHAR) + ''/'' + Cast(Year(c.DateAdded) AS VARCHAR) AS SMALLDATETIME) AS [Date Added],
	c.DateAdded AS [Date Added With Time],
	it.TemplateName AS [Invoice Template],
	glc.GLCompanyName AS [Default Company],
	CASE c.DefaultBillingMethod
		WHEN 1 THEN ''Time and Materials''
		WHEN 2 THEN ''Fixed Fee''
		WHEN 3 THEN ''Retainer''
	END AS [Default Billing Method],
	CASE c.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 [One Invoice Per],

	CASE c.DefaultARLineFormat
	WHEN -1 THEN ''''
	WHEN 8 THEN ''Project then Billing Item and Item''
	WHEN 11 THEN CASE WHEN ISNULL(pref.UseBillingTitles, 0) = 1 THEN ''Title'' ELSE '''' END
	WHEN 12 THEN CASE WHEN ISNULL(pref.UseBillingTitles, 0) = 1 THEN ''Title and Service'' ELSE '''' END
	WHEN 13 THEN CASE WHEN ISNULL(pref.UseBillingTitles, 0) = 1 THEN ''Service and Title'' ELSE '''' END
	WHEN 0 THEN CASE WHEN c.OneInvoicePer = 0 THEN ''Invoice'' ELSE ''Project'' END
	WHEN 1 THEN CASE WHEN c.OneInvoicePer = 0 THEN ''Task'' ELSE ''Project and Task'' END
	WHEN 2 THEN CASE WHEN ISNULL(c.LayoutKey, 0) = 0 THEN ''Service'' ELSE ''Project and Service'' END
	WHEN 14 THEN CASE WHEN ISNULL(c.LayoutKey, 0) = 0 THEN ''Service/Item'' ELSE ''Project and Service/Item'' END
	WHEN 3 THEN CASE WHEN ISNULL(c.LayoutKey, 0) = 0 THEN ''Billing Item'' ELSE '''' END
	WHEN 9 THEN CASE WHEN c.OneInvoicePer = 0 OR ISNULL(c.LayoutKey, 0) <> 0 THEN ''Billing Item and Item'' ELSE '''' END
	ELSE ''''
END AS [One Line Item Per],

	 CASE c.DefaultFFLineFormat
			WHEN -1 THEN ''''
			WHEN 0 THEN ''One Line''
			WHEN 1 THEN ''Task''
			WHEN 2 THEN ''Service/Item''
			WHEN 3 THEN ''Billing Item''
			WHEN 4 THEN ''Billing Item and Item''
		 END AS [One Line Item Per Fixed Fee],
	CASE
		WHEN c.OnePaymentPerVoucher = 1 THEN ''YES'' 
		ELSE ''NO'' 
	END AS [One Payment Per Invoice], 
	CASE
		WHEN c.UseDBAForPayment = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Print DBA On Check], 
	CASE
		WHEN c.UseDBAForPayment1099 = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Print DBA On 1099], 
	pt.TermsDescription AS [Billing Terms],
	et.TemplateName AS [Estimate Template],
	CASE c.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 [Labor Get Rate From],
	CASE c.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 [Purchasing Get Rate From],
	rs.RateSheetName AS [Expense Rate Sheet],
	srs.RateSheetName AS [Labor Rate Sheet],
	tirs.RateSheetName AS [Title Rate Sheet],
	c.ItemMarkup AS [Purchasing Markup],
	c.IOCommission AS [IO Commission Percent], 
	c.BCCommission AS [BC Commission Percent],
	Case c.GetRateFrom When 2 then c.HourlyRate else 0 end AS [Default Project Hourly Rate],
	CASE c.IOBillAt
		WHEN 0 THEN ''Gross''
		WHEN 1 THEN ''Net''
		WHEN 2 THEN ''Commission Only''
	END AS [Prebill Insertions At],
	CASE c.BCBillAt
		WHEN 0 THEN ''Gross''
		WHEN 1 THEN ''Net''
		WHEN 2 THEN ''Commission Only''
	END AS [Prebill Broadcast At],
	st1.SalesTaxName AS [Sales Tax 1],
	st2.SalesTaxName AS [Sales Tax 2],
	gla.AccountNumber + '' - '' + gla.AccountName AS [Default Expense Account],
	gla2.AccountNumber + '' - '' + gla2.AccountName AS [Default Sales Account],
	t.TeamName AS [Account Team],
	LTRIM(RTRIM(ISNULL(cb.FirstName + '' '','''')  + ISNULL(cb.LastName,''''))) AS [Created By],
	c.DateUpdated AS [Date Updated],
	LTRIM(RTRIM(ISNULL(mb.FirstName + '' '','''')  + ISNULL(mb.LastName,''''))) [Last Modified By],
	0 AS ASC_Selected,
	c.TermsPercent AS [Vendor Discount Percent],
	c.TermsDays AS [Vendor Discount Days],
	c.TermsNet AS [Vendor Days Net Due],
	CASE
		WHEN c.Overhead = 1 THEN ''YES''
		ELSE ''NO''
	END AS [OverHead Client], 
	CASE
		WHEN c.OverheadVendor = 1 THEN ''YES''
		ELSE ''NO''
	END AS [OverHead Vendor], 
	CASE
		WHEN c.CCAccepted = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Accepts Credit Cards],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Salesperson Name],
	so.SourceName AS [Company Source],
	ISNULL(folder.FolderName, ''No Folder'') AS [Folder],
	-- WWP
	CASE c.WWPCurrentLevel 
		WHEN 2 THEN ''2 - Contemplating''
		WHEN 3 THEN ''3 - Planning''
		WHEN 4 THEN ''4 - Action''
		ELSE ''1 - Unaware'' 
	END AS [WWP Current Level],
	lastActivity.ActivityDate AS [Last Activity Date],
	lastActivity.Subject AS [Last Activity Subject],
	ISNULL(lau.FirstName,'''') + '' '' + ISNULL(lau.LastName,'''') AS [Last Activity Assigned To],
	nextActivity.ActivityDate AS [Next Activity Date],
	nextActivity.Subject AS [Next Activity Subject],
	ISNULL(nau.FirstName,'''') + '' '' + ISNULL(nau.LastName,'''') AS [Next Activity Assigned To],
	atNext.TypeName AS [Next Activity Type],
	atLast.TypeName AS [Last Activity Type],
	DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) AS [Days Since Last Activity],
	CASE
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 90 THEN ''90 Days''
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 60 THEN ''60 Days''
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 30 THEN ''30 Days''
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 7 THEN ''7 Days''
		ELSE NULL
	END AS [No Activity Since],
	c.CurrencyID AS [Currency],
	gla3.AccountNumber + '' - '' + gla3.AccountName AS [Default AP Account],
	gla4.AccountNumber + '' - '' + gla4.AccountName AS [Default AR Account],
	vst1.SalesTaxName AS [Vendor Sales Tax 1],
	vst2.SalesTaxName AS [Vendor Sales Tax 2],
	glcc.AccountNumber AS [Credit Card Used],
	c.EmailACHToAddress as [Email ACH to Address],
	c.EmailCCToAddress AS [Email Card Info To],
	ap.Address1 AS [Payment Address1],   
	ap.Address2 AS [Payment Address2],   
	ap.Address3 AS [Payment Address3],   
	ap.City AS [Payment City],   
	ap.State AS [Payment State],   
	ap.PostalCode AS [Payment Postal Code],   
	ap.Country AS [Payment Country],
	CASE ISNULL(c.OnHold, 0)
		WHEN 1 THEN ''YES''
		ELSE ''NO''
	END AS [On Hold],
	LTRIM(RTRIM(ISNULL(bm.FirstName + '' '','''')  + ISNULL(bm.LastName,''''))) AS [Billing Manager Name],
	lo.LayoutName as [Default Layout Name],
	CASE
		WHEN c.VCardAccepted = 1 THEN ''YES''
		ELSE ''NO''
	END AS [Accepts VPay]
	,case c.EstimateLaborTaxable
		When 0 Then ''Not Taxable''
		When 1 then ''Taxable By Task''
		When 2 then ''Taxable By Project'' 
		When 3 then ''Taxable By Service'' 
		When 4 then ''Taxable By Title'' 
	end as [Estimate Labor Taxable],
	c.NextProjectNum As [Next Project Number],
	pct.Email AS [Primary Contact Email],
	c.ExpMonth + ''/'' + c.ExpYear AS [Credit Card Exp Date],
	CASE WHEN c.CCReceipts = 1 THEN ''YES'' ELSE ''NO'' END AS [Allow Credit Card Payments Online],	
	CASE WHEN c.ACHReceipts = 1 THEN ''YES'' ELSE ''NO'' END AS [Allow ACH Payments Online],
	CASE ISNULL(c.ACHEnabled, 0)
		WHEN 1 THEN ''YES''
		ELSE ''NO''
	END AS [ACH Enabled],
	c.TwitterID as [Twitter ID],
	--Client data
	cm.ARAmt as [AR Amount],
	cm.IncomeAmount as [Income Amount],
	CASE ISNULL(cm.IncomeAmount, 0)
		WHEN 0 THEN 0
		ELSE cm.ARAmt / (cm.IncomeAmount / 365) 
	end as [Collection Period]
	,CASE 
		WHEN c.DoNotUse = 1 THEN ''YES'' 
		ELSE ''NO'' 
	END AS [Do not use for Projects or Project Requests]
	--vendor data
	,cm.TotalPurchases as [Total Purchases]
	,cm.YearPurchases as [Purchases this year]
	,cm.UnpaidBalance as [Unpaid Balance]
	,cm.ExpenseAmt as [Expense Amount]
	,cm.APAmt as [AP Amount]
	,CASE ISNULL(cm.ExpenseAmt, 0)
		WHEN 0 THEN 0
		ELSE cm.APAmt / (cm.ExpenseAmt / 365) 
	end as [Payment Period]
	,c.NextCampaignNum As [Next Campaign Number]
	,LTRIM(RTRIM(ISNULL(defaultAPApprover.FirstName + '' '','''')  + ISNULL(defaultAPApprover.LastName,''''))) AS [Default Approver Person]
	,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' + GLCompanyName 
              FROM tGLCompany glc (NOLOCK)
			  INNER JOIN tGLCompanyAccess glca (NOLOCK) ON glc.GLCompanyKey = glca.GLCompanyKey AND glca.Entity = ''tCompany''
		      WHERE glca.EntityKey = c.CompanyKey
			  ORDER BY glc.GLCompanyName
              FOR XML PATH('''')) ,1,1,''''))), '''') AS [Access Restrictions]
	,ba.BankAccountType as [Bank Account Type]
	,atc.AvalaraTaxCode as [Avalara Tax Code]
	,atc.Description as [Avalara Tax Code Description]
	,c.AvalaraTaxExemptReason as [Avalara Tax Exempt Reason]
	,Case c.RequireCommentsOnTime When 1 then ''YES'' else ''NO'' end as [Require Comments on Time Entries]
FROM tCompany c (NOLOCK)  
	LEFT OUTER JOIN tCompanyType ct (NOLOCK) ON c.CompanyTypeKey = ct.CompanyTypeKey  
	LEFT OUTER JOIN tCompany pc (NOLOCK) ON c.ParentCompanyKey = pc.CompanyKey  
	LEFT OUTER JOIN tUser u (NOLOCK) ON c.AccountManagerKey = u.UserKey 
	LEFT OUTER JOIN tUser upm (NOLOCK) ON c.ProjectManagerKey = upm.UserKey       
	LEFT OUTER JOIN tUser pct (NOLOCK) ON c.PrimaryContact = pct.UserKey  
	LEFT OUTER JOIN tUser owner (NOLOCK) ON c.ContactOwnerKey = owner.UserKey  
	LEFT OUTER JOIN tUser cb (NOLOCK) ON c.CreatedBy = cb.UserKey
	LEFT OUTER JOIN tUser mb (NOLOCK) ON c.ModifiedBy = mb.UserKey
	LEFT OUTER JOIN tUser bc (NOLOCK) ON c.BillingEmailContact = bc.UserKey
	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 ap (NOLOCK) ON c.PaymentAddressKey = ap.AddressKey
	LEFT OUTER JOIN tInvoiceTemplate it (NOLOCK) ON c.InvoiceTemplateKey = it.InvoiceTemplateKey
	LEFT OUTER JOIN tEstimateTemplate et (NOLOCK) ON c.EstimateTemplateKey = et.EstimateTemplateKey
	LEFT OUTER JOIN tPaymentTerms pt (NOLOCK) ON c.PaymentTermsKey = pt.PaymentTermsKey
	LEFT OUTER JOIN tItemRateSheet rs (NOLOCK) ON c.ItemRateSheetKey = rs.ItemRateSheetKey
	LEFT OUTER JOIN tTimeRateSheet srs (NOLOCK) ON c.TimeRateSheetKey = srs.TimeRateSheetKey
	LEFT OUTER JOIN tTitleRateSheet tirs (NOLOCK) ON c.TitleRateSheetKey = tirs.TitleRateSheetKey
	LEFT OUTER JOIN tSalesTax st1 (NOLOCK) ON c.SalesTaxKey = st1.SalesTaxKey
	LEFT OUTER JOIN tSalesTax st2 (NOLOCK) ON c.SalesTax2Key = st2.SalesTaxKey
	LEFT OUTER JOIN tSalesTax vst1 (NOLOCK) ON c.VendorSalesTaxKey = vst1.SalesTaxKey
	LEFT OUTER JOIN tSalesTax vst2 (NOLOCK) ON c.VendorSalesTax2Key = vst2.SalesTaxKey
	LEFT OUTER JOIN tTeam t (nolock) ON c.DefaultTeamKey = t.TeamKey
	LEFT OUTER JOIN tActivity lastActivity (NOLOCK) ON c.LastActivityKey = lastActivity.ActivityKey
	LEFT OUTER JOIN tUser lau (NOLOCK) ON lastActivity.AssignedUserKey = lau.UserKey
	LEFT OUTER JOIN tActivity nextActivity (NOLOCK) ON c.NextActivityKey = nextActivity.ActivityKey
	LEFT OUTER JOIN tUser nau (NOLOCK) ON nextActivity.AssignedUserKey = nau.UserKey
	LEFT OUTER JOIN tUser sales (NOLOCK) ON c.SalesPersonKey = sales.UserKey
	LEFT OUTER JOIN tCMFolder folder (NOLOCK) ON c.CMFolderKey = folder.CMFolderKey
	LEFT OUTER JOIN	tSource so (NOLOCK) on c.SourceKey = so.SourceKey
	LEFT OUTER JOIN tActivityType atNext (NOLOCK) ON nextActivity.ActivityTypeKey = atNext.ActivityTypeKey
	LEFT OUTER JOIN tActivityType atLast (NOLOCK) ON lastActivity.ActivityTypeKey = atLast.ActivityTypeKey
	LEFT OUTER JOIN tGLAccount gla (NOLOCK) ON c.DefaultExpenseAccountKey = gla.GLAccountKey
	LEFT OUTER JOIN tGLAccount gla2 (NOLOCK) ON c.DefaultSalesAccountKey = gla2.GLAccountKey
	LEFT OUTER JOIN tGLCompany glc (NOLOCK) ON c.GLCompanyKey = glc.GLCompanyKey
	LEFT OUTER JOIN tGLAccount gla3 (NOLOCK) ON c.DefaultAPAccountKey = gla3.GLAccountKey
	LEFT OUTER JOIN tGLAccount gla4 (NOLOCK) ON c.DefaultARAccountKey = gla4.GLAccountKey
	LEFT OUTER JOIN tGLAccount glcc (nolock) on c.CCAccountKey = glcc.GLAccountKey
	LEFT OUTER JOIN tUser bm (NOLOCK) on c.BillingManagerKey = bm.UserKey
	LEFT OUTER JOIN tLayout lo (NOLOCK) on c.LayoutKey = lo.LayoutKey
	LEFT OUTER JOIN tOffice o (NOLOCK) on c.OfficeKey = o.OfficeKey
	LEFT OUTER JOIN tCompanyMetrics cm (NOLOCK) on c.CompanyKey = cm.CompanyKey
	LEFT OUTER JOIN tUser defaultAPApprover (NOLOCK) ON c.DefaultAPApproverKey = defaultAPApprover.UserKey 
	LEFT OUTER JOIN tBankAccountType ba (NOLOCK) on c.BankAccountTypeKey = ba.BankAccountTypeKey
	LEFT OUTER JOIN tAvalaraTaxCode atc (NOLOCK) ON c.AvalaraTaxCodeKey = atc.AvalaraTaxCodeKey
	LEFT OUTER JOIN tPreference pref (NOLOCK) ON pref.CompanyKey = ISNULL(c.OwnerCompanyKey, c.CompanyKey)



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tAPIErrorTemplate]'
GO
IF OBJECT_ID(N'[dbo].[tAPIErrorTemplate]', 'U') IS NULL
CREATE TABLE [dbo].[tAPIErrorTemplate]
(
[errorType] [varchar] (10) NULL,
[errorCode] [varchar] (50) NULL,
[errorMessage] [varchar] (500) NULL,
[fieldName] [varchar] (100) NULL
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIAddUpdateProject]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddUpdateProject]', 'P') IS NULL
EXEC sp_executesql N'-- Created by GitHub Copilot in SSMS - review carefully before executing

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

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

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

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

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

        -- Administrators bypass all security checks
        if @IsAdministrator <> 1
        begin
            DECLARE @HasAccess int
            select @HasAccess = 0

            -- Check GL Company security
            if @RestrictToGLCompany = 1
            begin
                if exists (
                    select 1
                    from tProject p (nolock)
                    where p.ProjectKey = @ExistingProjectKey
                      and p.GLCompanyKey in (
                          select GLCompanyKey
                          from tUserGLCompanyAccess (nolock)
                          where UserKey = @UserKey
                      )
                )
                    select @HasAccess = 1
                else
                begin
                    insert into #errors (errorType, errorCode, errorMessage, fieldName)
                    values (''error'', ''ACCESS_DENIED'', ''You do not have access to projects in this GL Company.'', ''projectNumber'')

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

                    drop table #errors
                    return -103
                end
            end
            else
                select @HasAccess = 1

            -- Check project assignment (if user doesn''t have prjAccessAny right)
            if @HasAccess = 1
            begin
                select @CheckAssignment = 1

                -- Check if user has prjAccessAny right
                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 user needs to be assigned, verify assignment
                if @CheckAssignment = 1
                begin
                    if not exists (
                        select 1
                        from tAssignment (nolock)
                        where ProjectKey = @ExistingProjectKey
                          and UserKey = @UserKey
                    )
                    begin
                        insert into #errors (errorType, errorCode, errorMessage, fieldName)
                        values (''error'', ''ACCESS_DENIED'', ''You are not assigned to this project and do not have rights to update it.'', ''projectNumber'')

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

                        drop table #errors
                        return -103
                    end
                end
            end
        end
    end
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

-- ========================================
-- 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
                EXEC sptActionLogInsert
                    @Entity = ''Project'',
                    @EntityKey = @NewProjectKey,
                    @CompanyKey = @CompanyKey,
                    @ProjectKey = @NewProjectKey,
                    @Action = ''Field Changed'',
                    @ActionDate = null, -- Will default to getutcdate() in the SP
                    @ActionBy = NULL, -- Will be auto-populated from @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
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'Creating [dbo].[spConvertDB2605]'
GO
IF OBJECT_ID(N'[dbo].[spConvertDB2605]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROC [dbo].[spConvertDB2605]
AS
	
	-- new right delete for all add/edit purchase order users for issue 722428
DECLARE @DeletePurchaseOrderKey INT = 60101 --new delete right(purch_deletepo)
INSERT INTO tRightAssigned (EntityType, EntityKey, RightKey)
SELECT EntityType, EntityKey, @DeletePurchaseOrderKey 
FROM tRightAssigned
WHERE RightKey = 60100 -- existing right (purch_editpo)

--Move enabled labs to customizations------------------------------------------
UPDATE p
SET
	Customizations = ISNULL(p.Customizations, '''') + CASE WHEN LEN(ISNULL(p.Customizations, '''')) > 0 THEN ''|'' ELSE '''' END + l.LabID
		COLLATE SQL_Latin1_General_CP1_CI_AS
FROM
	tLabCompany lc (nolock)
	INNER JOIN tLab l (nolock) ON lc.LabKey = l.LabKey
	INNER JOIN tPreference p (nolock) ON lc.CompanyKey = p.CompanyKey
WHERE lc.LabKey = 102

UPDATE p
SET
	Customizations = ISNULL(p.Customizations, '''') + CASE WHEN LEN(ISNULL(p.Customizations, '''')) > 0 THEN ''|'' ELSE '''' END + l.LabID
		COLLATE SQL_Latin1_General_CP1_CI_AS
FROM
	tLabCompany lc (nolock)
	INNER JOIN tLab l (nolock) ON lc.LabKey = l.LabKey
	INNER JOIN tPreference p (nolock) ON lc.CompanyKey = p.CompanyKey
WHERE lc.LabKey = 121

DELETE tLabCompany
WHERE LabKey IN (102,121,65)'
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
    */
    
    -- =================================================================
    -- 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);

    SELECT
        @CompanyKey = CompanyKey,
        @GLAccountKey = GLAccountKey,
        @PayeeName = PayeeName,
        @NormalizedPayeeName = NormalizedPayeeName,
        @OriginalMemo = OriginalMemo,
        @NormalizedMemo = NormalizedMemo,
        @Amount = Amount
    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

    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;

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

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

        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;

        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
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptImportExportSeedApiDoco]'
GO
IF OBJECT_ID(N'[dbo].[sptImportExportSeedApiDoco]', 'P') IS NOT NULL
EXEC sp_executesql N'




ALTER PROCEDURE [dbo].[sptImportExportSeedApiDoco]

AS
/*
 exec sptImportExportSeedApiDoco
|| When			Who Rel      What

|| 01/05/24     AMP 24.01.21 (636149) Modified the Credit Card Charge for Item - If the pref is required the field will be displayed in the required field list on the import screen, also made Net Cost always a required field
|| 01/19/24     CRG 24.02.19 (655377) Added Weekly Hours to the Task Import
|| 02/21/24     CRG 24.03.17 (664040) Added CalendarApprover to the Employee Import
|| 02/21/24     RLB 24.03.17 (664982) adding Invoice Label
|| 03/20/24     MCM 24.04.xx (658620) Adding Hourly Cost for Service Rate Sheet
|| 04/05/24     MCM 24.05.19 (669368) Adding get by id for station and publication and searhFor PO and IO
|| 04/24/24		MCM 24.05.19 (670663) Adding currencyID to the glAccounts import
|| 08/08/24		MCM 24.09.x  (676638) Adding Retainer custom field entity
|| 08/20/24		MCM 24.09.x  (681078) Adding GL Company Exchange rate to the JE detail api
|| 08/21/24     GAR 24.10.x  (680406) Adding Avalara Tax Code to Services
|| 10/09/24     GAR 24.11.x  (684268) Adding a new endpoint for updating staff rates on projects
|| 11/19/24		MCM 24.12.x  (688332) Fixing the startdate and endDate for the timesheet to be header
|| 12/09/24     MCM 25.01.x  (682120) Added toCurrencyID to the Currency import
|| 12/17/24     MCM 24.17.x  (689256) Updated the GLCompanyKey to be GLCompanyID
|| 12/18/24		MCM 25.01.x  (689448) Added notes to the todo import
|| 01/10/25		MCM 25.02.x  (688779) Added additional fiels for the view import
|| 03/04/25		MCM 25.04.x  (694525) Added custom fields to the activities import
|| 03/06/25		MCM 25.04.x  (692694) Added split billing to the project import
|| 04/16/25	    MCM 25.05.x  (696669) Added ability to update Credit Card Connector (Transactions aka ccEntry)
|| 05/14/25		MCM 25.06.x  (701811) Added the GL CompanyKey to the credit card connector
|| 05/30/25		MCM 25.06.x	 (702845) Added conversation search by projectNumber
|| 06/25/25		MCM 25.07.x  (700522) Added GL Budget export view
|| 07/11/25     MCM 25.08.x  (700243) Added HeaderID for PO, IO, BO
|| 08/11/25     MCM 25.09.x  (706891) Added ProjectColor to the Client import
|| 08/12/25		MCM 25.09.x  (705830) Added AssignedUserID to the todo import
|| 09/04/25     MCM 25.10.x  (709191) Added Address Name to client/company/vendor import
|| 10/07/25		MCM 25.11.x  (711735) Added Avalara Tax Code to project import
|| 10/10/25		MCM 25.11.x  (710932) Updated ToDo to allow updates and added completed field
|| 10/10/25		MCM 25.11.x  (709479) Updated timesheets with complete and reject options.
|| 12/31/25		MCM 26.01.x  (694595) Added Publication ID and Staion ID as conditionally required using SystemSettingFieldName
|| 01/14/26		MCM 26.02.x  (719575) Added Request ID to the Campaign import
|| 01/27/26		MCM 26.02.x  (719809) Added sendNotifications to the Task Import
|| 03/12/26		MCM 26.04.x  (723933) Added billable to the IO import
|| 03/18/26		MCM 26.04.x  (724666) Removed duplicate columns in the viewKey section
|| 03/24/26		MCM 26.04.x  (638176) Added Billing Schedule items
|| 04/14/26		MCM 26.05.x  (725995) Added comments to the credit card charge import
|| 04/21/26     GAR 26.05.x  (726790) Change the glCompanyKey in the Conversations import to glCompanyID
*/
BEGIN
/*************************************************************************************************************************
tImportExport and tImportExportDetail
**************************************************************************************************************************/
delete tImportExport
delete tImportExportDetail

DECLARE @ActivityKey int = 39
DECLARE @ActivityTypeKey int = 49
DECLARE @AddressKey int = 79
DECLARE @AvalaraTaxCodeKey int = 126
DECLARE @BillingGroupKey int = 61
DECLARE @BillingScheduleKey int = 135
DECLARE @BOKey int = 77
DECLARE @CampaignKey int = 124
DECLARE @ClientKey int = 71
DECLARE @ClientPaymentsKey int = 19  --To be deprecated 1/1/2020... Use Receipts instead
DECLARE @CompanyKey int = 37
DECLARE @ContactKey int = 1
DECLARE @ConversationKey int = 116
DECLARE @ConversationSearchKey int = 131
DECLARE @CreditCardCharge int = 57
DECLARE @CreditCardConnector int = 62
DECLARE @CurrencyRateKey int = 63
DECLARE @DeliverableKey int = 80
DECLARE @EmployeeKey int = 3
DECLARE @EstimateKey int = 16
DECLARE @ExpenseReportKey int = 22
DECLARE @GLAccountKey int = 6
DECLARE @GLBudget int = 60
DECLARE @InvoiceKey int = 11
DECLARE @ItemRateSheetKey int = 59
DECLARE @IOKey int = 34
DECLARE @JEKey int = 24
DECLARE @LeadKey int = 36
DECLARE @MediaPlanKey int select @MediaPlanKey = 111
DECLARE @MediaPlanReleaseKey int select @MediaPlanReleaseKey = 113
DECLARE @MediaPlanVoucherKey int select @MediaPlanVoucherKey = 112
DECLARE @OpportunitiesKey int = 38
DECLARE @POKey int = 18
DECLARE @ProjectKey int = 13
DECLARE @ProjectStaffRatesKey int = 127
DECLARE @ProjectStatusCodeKey int = 27
DECLARE @ProjectRequestKey int = 76
DECLARE @PublicationKey int = 120
DECLARE @ReceiptsKey int = 115
DECLARE @ReportKey int =  109
DECLARE @RetainerKey int = 118
DECLARE @ServiceRateSheetKey int = 58
DECLARE @StationKey int = 122
DECLARE @TaskKey int = 69
DECLARE @TimeSheetKey int = 21
DECLARE @TimeSheetTimeKey int = 107
DECLARE @TimeSheetCompleteKey int = 132
DECLARE @TimeSheetRejectKey int = 133
DECLARE @TimeKey int = 72
DECLARE @ToDoKey int = 84
DECLARE @VendorKey int = 70
DECLARE @VendorPaymentKey int = 20
DECLARE @ViewKey int = 78
DECLARE @VoucherKey int = 12



INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ContactKey, N''Contacts'', N''contacts'', NULL, NULL, N''Contact'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@EmployeeKey, N''Employees'', N''employees'', NULL, NULL, N''Employees'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (4, N''Expense Report Items'', N''expensereportitems'', NULL, NULL, NULL, N''vExport_ExpenseReportItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (5, N''Purchase Items'', N''purchaseitem'', NULL, NULL, NULL, N''vExport_PurchaseItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@GLAccountKey, N''GL Accounts'', N''glaccounts'', NULL, NULL, NULL, N''vExport_GLAccount'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (7, N''Payment Terms'', N''paymentterms'', NULL, NULL, NULL, N''tPaymentTerms'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (8, N''Sales Tax'', N''salestaxrates'', NULL, NULL, NULL, N''vExport_SalesTax'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (9, N''Services'', N''services'', NULL, NULL, NULL, N''vExport_Service'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (10, N''Billing Items'', N''billingitems'', NULL, NULL, NULL, N''vExport_WorkType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@InvoiceKey, N''Client Invoices'', N''invoices'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@VoucherKey, N''Vendor Invoices'', N''vouchers'', 1, N''details'', N''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectKey, N''Projects'', N''projects'', NULL, NULL, N''Project'', ''vExport_Project'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (16, N''Estimates'', N''estimates'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@POKey, N''Purchase Orders'', N''purchaseorders'', 1, N''details'', N''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ClientPaymentsKey, N''Client Payments'', N''clientpayments'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@VendorPaymentKey, N''Vendor Payments'', N''vendorpayments'', 1, N''details'',  NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@TimeSheetKey, N''Timesheets'', N''timesheets'', 1, N''time'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ExpenseReportKey, N''Expense Reports'', N''expensereports'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (23, N''Misc Project Costs'', N''misccosts'', NULL, NULL, NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@JEKey, N''Journal Entries'', N''journalentries'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (25, N''Project Types'', N''projecttypes'', NULL, NULL, NULL, N''tProjectType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectStatusCodeKey, N''Project Status'', N''projectstatuscodes'', NULL, NULL, NULL, N''tProjectStatus'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (28, N''Departments'', N''departments'', NULL, NULL, NULL, N''tDepartment'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (29, N''Project Billing Status'', N''projectbillingcodes'', NULL, NULL, NULL, N''tProjectBillingStatus'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (31, N''Broadcast Items'', N''broadcastitems'', NULL, NULL, NULL, N''vExport_BroadcastItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (32, N''Print Items'', N''printitems'', NULL, NULL, NULL, N''vExport_PrintItem'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (33, N''GL Companies'', N''glcompanies'', NULL, NULL, NULL, N''vExport_GLCompany'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@IOKey, N''Insertion Orders'', N''insertionorders'', 1, N''details'', N''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@LeadKey, N''Leads'', N''leads'', NULL, NULL, N''Company|Contact|Lead'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CompanyKey, N''Companies'', N''companies'', NULL, NULL, N''Company'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@OpportunitiesKey, N''Opportunities'', N''opportunities'', NULL, NULL, N''Lead'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ActivityKey, N''Activities'', N''activities'', NULL, NULL, ''Activity'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (40, N''Report Groups'', N''reportgroups'', NULL, NULL, NULL, N''tReportGroup'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (41, N''Opportunity Stages'', N''opportunitystages'', NULL, NULL, NULL, N''tLeadStage'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (42, N''Opportunity Status'', N''opportunitystatus'', NULL, NULL, NULL, N''tLeadStatus'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (43, N''Opportunity Outcome'', N''opportunityoutcome'', NULL, NULL, NULL, N''tLeadOutcome'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (44, N''Company Types'', N''companytypes'', NULL, NULL, NULL, N''tCompanyType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (45, N''Meeting Types'', N''calendartypes'', NULL, NULL, NULL, N''tCalendarType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (46, N''Calendar Resources'', N''calendarresources'', NULL, NULL, NULL, N''tCalendarResource'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (48, N''Sources'', N''sources'', NULL, NULL, NULL, N''tSource'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ActivityTypeKey, N''Conversation Types'', N''activitytypes'', NULL, NULL, NULL, N''tActivityType'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (50, N''Payment Methods'', N''paymentmethods'', NULL, NULL, NULL, N''tCheckMethod'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (51, N''Write Off Reasons'', N''writeoffreasons'', NULL, NULL, NULL, N''tWriteOffReason'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (52, N''Standard Text'', N''standardtext'', NULL, NULL, NULL, N''tStandardText'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (53, N''Media Markets'', N''mediamarkets'', NULL, NULL, NULL, N''tMediaMarket'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (54, N''GL Classes'', N''glclasses'', NULL, NULL, NULL, N''vExport_GLClass'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (55, N''Offices'', N''offices'', NULL, NULL, NULL, N''tOffice'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (56, N''Teams'', N''teams'', NULL, NULL, NULL, N''vExport_Team'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CreditCardCharge, N''Credit Card Charges'', N''creditcardcharges'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ServiceRateSheetKey, N''Service Rate Sheets'', N''serviceratesheets'', 1, N''details'', NULL, N''vExport_ServiceRateSheet'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ItemRateSheetKey, N''Item Rate Sheets'', N''itemratesheets'', 1, N''details'', NULL, N''vExport_ItemRateSheet'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@GLBudget, N''Financial Budgets'', N''financialbudgets'', 1, N''details'', NULL, N''vExport_GLFinancialBudget'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@BillingGroupKey, N''Billing Groups'', N''billinggroups'', NULL, NULL, NULL, N''vExport_BillingGroup'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CreditCardConnector, N''Credit Card Connector'', N''creditcardtransactions'', NULL, NULL, NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CurrencyRateKey, N''Currency Rates'', N''currencyrates'', NULL, NULL, NULL, N''vExport_CurrencyRate'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [Condition]) VALUES (64, N''Titles'', N''titles'', NULL, NULL, NULL, N''vExport_Title'', 1, NULL, 1, 1, 0, 0, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [Condition]) VALUES (65, N''Title Rate Sheets'', N''titleratesheets'', 1, N''details'', NULL, N''vExport_TitleRateSheet'', 1, NULL, 1, 1, 0, 0, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (67, N''Request Reject Reasons'', N''requestrejectreasons'', NULL, NULL, NULL, N''tRequestRejectReason'', 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@TaskKey, N''Tasks'', N''tasks'', 1, N''assignments'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@VendorKey, N''Vendors'', N''vendors'', NULL, NULL, N''Company'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ClientKey, N''Clients'', N''clients'', NULL, NULL, N''Company'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@TimeKey, N''Time'', N''time'', NULL, NULL, NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (73, N''Project Spec Sheets'', N''projectspecsheets'', NULL, NULL, N''Spec'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (74, N''Request Spec Sheets'', N''requestspecsheets'', NULL, NULL, N''Spec'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (75, N''Labor Budgets'', N''laborbudgets'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectRequestKey, N''Project Request'', N''projectrequests'', NULL, NULL, N''RequestDef'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@BOKey, N''Broadcast Orders'', N''broadcastorders'', 1, N''details'', ''PO_Header|PO_Detail'', NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ViewKey, N''View'', N''view'', NULL, Null, NULL, NULL, 1, ''Used to import data into the tReport table'', 0, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@AddressKey, N''Address'', N''address'', NULL, Null, NULL, NULL,1, ''Used to add an address to a company, vendor, or client'', 0, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@DeliverableKey, N''Deliverables'', N''deliverables'', NULL, Null, N''Deliverable|DeliverableType'', NULL,1, NULL, 0, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ToDoKey, N''To Do'', N''todos'', NULL, Null, N''To Do'', NULL,1, NULL, 1, 0, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ProjectStaffRatesKey, N''Project Staff Rates'', N''projectstaffrates'', NULL, Null, N''Project Staff Rates'', NULL,1, ''Used to update the staff rates on a project when the Get Rate From is Project User'', 1, 0, 1, 0)
--Just for API doco
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (100, N''Opportunities/List'', N''opportunities/list'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (101, N''Activities/Search'', N''activities/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (102, N''Companies/Search'', N''companies/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (103, N''Contacts/Search'', N''contacts/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (104, N''Employees/Search'', N''employees/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
--INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (105, N''JournalEntries/Search'', N''journalentries/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (106, N''Leads/Search'', N''leads/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@TimeSheetTimeKey, N''Timesheets/Time'', N''timesheets/time'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (108, N''Vendors/Search'', N''vendors/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@ReportKey, N''Reports'', N''reports'', NULL, Null, NULL, NULL,1 ,'''' , 1, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@MediaPlanKey, N''Media Plans'', N''mediaplans'', 1, ''details'', NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@MediaPlanVoucherKey, N''Media Plan Vendor Invoices'', N''mediaplanvouchers'', 1, ''details'', NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@ReceiptsKey, N''Receipts'', N''receipts'', 1, N''details'', NULL, NULL, 1, NULL, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@MediaPlanReleaseKey, N''Media Plan Release'', N''mediaplanrelease'', NULL, Null, NULL, NULL,1 ,'''' , 0, 0, 1, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@RetainerKey, N''Retainer'', N''retainer'', NULL, Null, N''Retainer'', NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@PublicationKey, N''Publication'', N''publications'', NULL, Null, NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@StationKey, N''Station'', N''stations'', NULL, Null, NULL, NULL,1 ,'''' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@CampaignKey, N''Campaign'', N''campaigns'', 1, N''details'', ''Campaign'', NULL,1 ,'''' , 1, 1, 1, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@ConversationKey, N''Conversation'', N''conversations'', NULL, Null, ''Activity'', NULL,1 ,''Used for import conversations.'' , 1, 1, 1, 0, 0)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@ConversationSearchKey, N''Conversations/Search'', N''Conversations/search'', NULL, Null, NULL, NULL,1, '''', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly], [Condition]) VALUES (@AvalaraTaxCodeKey, N''AvalaraTaxCodes'', NULL, NULL, Null, NULL, ''tAvalaraTaxCode'', 1 ,''Used for importing and exporting Avalara Tax Codes.'' , 0, 0, 0, 0, 1, N''System.hasCustomization(''''avalara'''')'')
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@TimeSheetCompleteKey, N''Timesheets/Complete'', N''timesheets/complete'', NULL, Null, NULL, NULL,1, ''Used for submitting/approving the timesheet.  If user has right to approve it will be approved, otherwise, it will be submitted'', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete], [DocumentationOnly]) VALUES (@TimeSheetRejectKey, N''Timesheets/Reject'', N''timesheets/reject'', NULL, Null, NULL, NULL,1, ''Used for reject a timesheet.'', 0, 0, 0, 0, 1)
INSERT [dbo].[tImportExport] ([ImportExportKey], [ImportExportID], [Endpoint], [IsParentChild], [ChildNode], [CustomFieldEntity], [TableName], [Active], [Description], [Get], [Post], [Put], [Delete]) VALUES (@BillingScheduleKey, N''Billing Schedule'', N''billingSchedule'', NULL, Null, NULL, NULL,1, ''Billing Schedule for a specified Project/Campaign'', 1, 1, 1, 0)

SET IDENTITY_INSERT [dbo].[tImportExportDetail] ON 

--Activities
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7745, @ActivityKey, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7746, @ActivityKey, N''Activity Date'', N''activityDate'', NULL, NULL, N''Activity Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7747, @ActivityKey, N''Completed'', N''completed'', NULL, NULL, N''Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7748, @ActivityKey, N''Date Completed'', N''dateCompleted'', NULL, NULL, N''Date Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7749, @ActivityKey, N''Assigned To'', N''assignedUser'', NULL, NULL, N''Assigned To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7750, @ActivityKey, N''Private'', N''private'', NULL, NULL, N''Private'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7751, @ActivityKey, N''Folder'', N''cMFolderKey'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7752, @ActivityKey, N''Activity Type'', N''activityTypeKey'', NULL, NULL, N''Activity Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7753, @ActivityKey, N''Notes'', N''notes'', NULL, NULL, N''Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7754, @ActivityKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7755, @ActivityKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7756, @ActivityKey, N''Contact'', N''linkedContact'', NULL, NULL, N''Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7757, @ActivityKey, N''Company'', N''linkedCompany'', NULL, NULL, N''Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7758, @ActivityKey, N''Opportunity'', N''linkedLead'', NULL, NULL, N''Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7759, @ActivityKey, N''Lead'', N''linkedUserLead'', NULL, NULL, N''Lead'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7760, @ActivityKey, N''Start Time'', N''startTime'', NULL, NULL, N''Start Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7761, @ActivityKey, N''End Time'', N''endTime'', NULL, NULL, N''End Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7762, @ActivityKey, N''Reminder (minutes)'', N''reminderMinutes'', NULL, NULL, N''Reminder (minutes)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7763, @ActivityKey, N''Priority'', N''priority'', NULL, NULL, N''Priority'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7764, @ActivityKey, N''Originator'', N''originatorUserKey'', NULL, NULL, N''Originator'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7765, @ActivityKey, N''Visible To Client'', N''visibleToClient'', NULL, NULL, N''Visible To Client'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7766, @ActivityKey, N''View As'', N''activityEntity'', NULL, NULL, N''View As'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7767, @ActivityKey, N''Outcome'', N''outcome'', NULL, NULL, N''Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7768, @ActivityKey, N''GL Company'', N''glCompanyKey'', NULL, NULL, N''GL Company, Required if GL Company is required '', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
--Activity aka Conversation Types
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7769, @ActivityTypeKey, N''Type Name'', N''typeName'', NULL, N''TypeName'', N''Type Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7770, @ActivityTypeKey, N''Display Color'', N''typeColor'', NULL, N''TypeColor'', N''Display Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7771, @ActivityTypeKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7772, @ActivityTypeKey, N''Auto Roll Date'', N''autoRollDate'', NULL, N''AutoRollDate'', N''Auto Roll Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Address
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79001, @AddressKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79002, @AddressKey, N''Company Key'', N''companyKey'', NULL, NULL, N''Company Key'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79003, @AddressKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79004, @AddressKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79005, @AddressKey, N''Address Name'', N''addressName'', NULL, NULL, N''Address Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79006, @AddressKey, N''Address 1'', N''address1'', NULL, NULL, N''Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79007, @AddressKey, N''Address 2'', N''address2'', NULL, NULL, N''Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79008, @AddressKey, N''Address 3'', N''address3'', NULL, NULL, N''CAddress 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79009, @AddressKey, N''City'', N''city'', NULL, NULL, N''City'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79010, @AddressKey, N''State'', N''state'', NULL, NULL, N''State'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79011, @AddressKey, N''Postal Code'', N''postalCode'', NULL, NULL, N''Postal Code'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (79012, @AddressKey, N''Country'', N''country'', NULL, NULL, N''Country'', NULL, Null, NULL, NULL, NULL, NULL, NULL)
--Billing Group
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7773, @BillingGroupKey, N''Billing Group Code'', N''billingGroupCode'', NULL, N''BillingGroupCode'', N''Billing Group Code'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7774, @BillingGroupKey, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7775, @BillingGroupKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7776, @BillingGroupKey, N''Comments'', N''comments'', NULL, N''Comments'', N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7777, @BillingGroupKey, N''GLCompany'', N''glCompanyKey'', NULL, N''GLCompanyID'', N''GLCompany, required if GL Company is required'', NULL, 2, N''GLCompanyID'', NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
-- Billing Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7778, 10, N''ID'', N''workTypeID'', NULL, N''WorkTypeID'', N''ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7779, 10, N''Name'', N''workTypeName'', NULL, N''WorkTypeName'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7780, 10, N''Standard Price'', N''standardPrice'', NULL, N''StandardPrice'', N''Standard Price'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7781, 10, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7782, 10, N''Sales Account Number'', N''glAccountNumber'', NULL, N''GLAccountNumber'', N''Sales Account Number'', NULL, NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7783, 10, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7784, 10, N''Department'', N''departmentID'', NULL, N''DepartmentName'', N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7785, 10, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7786, 10, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7787, 10, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7788, 10, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID'', NULL, NULL, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (788800, 10, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')

-- Billing Schedule
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135001, @BillingScheduleKey, N''Project Number'', N''projectNumber'', NULL, N''Project Number'', N''Project Number'', NULL, 1, NULL, NULl, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135002, @BillingScheduleKey, N''Date to Bill'', N''nextBillDate'', NULL, N''Next Bill Date'', N''Date To Bill'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135003, @BillingScheduleKey, N''Task ID'', N''taskID'', NULL, N''Task ID'', N''Set Date to bill when this task is complete'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135004, @BillingScheduleKey, N''Billing Comments'', N''comments'', NULL, N''Billing Comments'', N''Billing Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135005, @BillingScheduleKey, N''Percent Budget'', N''percentBudget'', NULL, N''Percent Budget'', N''Percent of Budget to Bill'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135006, @BillingScheduleKey, N''Dollar Amount'', N''dollarAmount'', NULL, N''Dollar Amount'', N''Dollar Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135007, @BillingScheduleKey, N''Advance Bill'', N''advanceBill'', NULL, N''Advance Bill'', N''Advance Bill'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (135008, @BillingScheduleKey, N''Campaign ID'', N''campaignID'', NULL, N''Campaign ID'', N''Campaign ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)

-- Broadcast Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7789, 31, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7790, 31, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7791, 31, N''Commission'', N''markup'', NULL, N''Markup'', N''Commission'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7792, 31, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7793, 31, N''Billing Item ID'', N''workType'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7794, 31, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department, required if departments are required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7795, 31, N''Expense Account Number'', N''expenseAccount'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7796, 31, N''Sales Account Number'', N''salesAccount'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7797, 31, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7798, 31, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7799, 31, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7800, 31, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID, required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (780100, 31, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')
--Calendar Resource
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7801, 46, N''Resource Name'', N''resourceName'', NULL, N''ResourceName'', N''Resource Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
-- Meeting aka Calendar Types
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7802, 45, N''Type Name'', N''typeName'', NULL, NULL, N''Type Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7803, 45, N''Type Color'', N''typeColor'', NULL, NULL, N''Type Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7804, 45, N''Display Order'', N''displayOrder'', NULL, NULL, N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Campaigns
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124001, @CampaignKey, N''Campaign ID'', N''campaignID'', NULL, NULL, N''Campaign ID'', N''header'', 0, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124002, @CampaignKey, N''Campaign Name'', N''campaignName'', NULL, NULL, N''Campaign Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124003, @CampaignKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124004, @CampaignKey, N''Description'', N''description'', NULL, NULL, N''description'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124005, @CampaignKey, N''objective'', N''objective'', NULL, NULL, N''objective'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124006, @CampaignKey, N''Start Date'', N''startDate'', NULL, NULL, N''Start Date'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124007, @CampaignKey, N''End Date'', N''endDate'', NULL, NULL, N''End Date'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124008, @CampaignKey, N''Account Manager'', N''accountManager'', NULL, NULL, N''Account Manager'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124009, @CampaignKey, N''Active'', N''active'', NULL, NULL, N''Active'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124010, @CampaignKey, N''Get Actuals By'', N''getActualsBy'', NULL, NULL, N''Get Actuals By'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124011, @CampaignKey, N''Layout'', N''layout'', NULL, NULL, N''Layout'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124012, @CampaignKey, N''multipleSegments;
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124013, @CampaignKey, N''Bill By'', N''billBy'', NULL, NULL, N''Bill By'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124014, @CampaignKey, N''One Line Per'', N''oneLinePer'', NULL, NULL, N''One Line Per'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124015, @CampaignKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124016, @CampaignKey, N''GL Company'', N''gLCompany'', NULL, NULL, N''GL Company'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124017, @CampaignKey, N''Client Division'', N''clientDivision'', NULL, NULL, N''clientDivision'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124018, @CampaignKey, N''Client Product'', N''clientProduct'', NULL, NULL, N''Client Product'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124019, @CampaignKey, N''Next Project Number'', N''nextProjectNum'', NULL, NULL, N''Next Project Number'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124020, @CampaignKey, N''Currency ID'', N''currencyID'', NULL, NULL, N''currency ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124021, @CampaignKey, N''Opportunity ID'', N''opportunityID'', NULL, NULL, N''Opportunity ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124022, @CampaignKey, N''Project Manager'', N''projectManager'', NULL, NULL, N''Project Manager'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124023, @CampaignKey, N''Use Campaign Budget'', N''useCampaignBudget'', NULL, NULL, N''Use Campaign Budget Manager'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124024, @CampaignKey, N''Expenses Not Included'', N''expensesNotIncluded'', NULL, NULL, N''Expenses Not Included'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124025, @CampaignKey, N''Bill by Percentage of'', N''billByFF'', NULL, NULL, N''Bill by Percentage of'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124030, @CampaignKey, N''Segment Name'', N''segmentName'', NULL, NULL, N''Segment Name'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124031, @CampaignKey, N''Segment Description'', N''segmentDescription'', NULL, NULL, N''segment Description'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124032, @CampaignKey, N''Segment Plan Start Date'', N''segmentPlanStartDate'', NULL, NULL, N''segment Plan Start Date'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124033, @CampaignKey, N''Segment Plan End Date'', N''segmentPlanEndDate'', NULL, NULL, N''segment Plan End Date'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124034, @CampaignKey, N''Segment Action'', N''action'', NULL, NULL, N''Segment Action - a/u/d for Add, Updated, or Delete to segment'', N''detail'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124040, @CampaignKey, N''Copy Campaign ID'', N''copyCampaignID'', NULL, NULL, N''Copy Campaign ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124041, @CampaignKey, N''Copy Projects'', N''copyProjects'', NULL, NULL, N''Copy Projects (yes/no) when copying a campaign'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124042, @CampaignKey, N''Copy Estimates'', N''copyEstimates'', NULL, NULL, N''Copy Estimates (yes/no) when copying a campaign'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124043, @CampaignKey, N''Client Campaign Number'', N''clientCampaignNumber'', NULL, NULL, N''Client Campaign Number'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (124045, @CampaignKey, N''Campaign Request ID'', N''requestID'', NULL, NULL, N''Campaign Request ID'', N''header'', 0, NULL, NULL, NULL, NULL, NULL)

-- Client Receipts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7805, @ClientPaymentsKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7806, @ClientPaymentsKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7807, @ClientPaymentsKey, N''Check Amount'', N''checkAmount'', NULL, NULL, N''Check Amount'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7808, @ClientPaymentsKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7809, @ClientPaymentsKey, N''Reference Number'', N''referenceNumber'', NULL, NULL, N''Reference Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7810, @ClientPaymentsKey, N''Payment Method'', N''paymentMethod'', NULL, NULL, N''Payment Method'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7811, @ClientPaymentsKey, N''Receipt Date'', N''checkDate'', NULL, NULL, N''Receipt Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7812, @ClientPaymentsKey, N''Deposit ID'', N''depositID'', NULL, NULL, N''Deposit ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7813, @ClientPaymentsKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7814, @ClientPaymentsKey, N''Cash Account Number'', N''cashAccountNumber'', NULL, NULL, N''Cash Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7815, @ClientPaymentsKey, N''Unapplied Payment Account Number'', N''prepayAccountNumber'', NULL, NULL, N''Unapplied Payment Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7816, @ClientPaymentsKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7817, @ClientPaymentsKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7818, @ClientPaymentsKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7819, @ClientPaymentsKey, N''GL Account'', N''glAccount'', NULL, NULL, N''GL Account'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7820, @ClientPaymentsKey, N''Description (Line)'', N''description'', NULL, NULL, N''Description (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7821, @ClientPaymentsKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7822, @ClientPaymentsKey, N''Department'', N''department'', NULL, NULL, N''Department. Required if Department is required.'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7823, @ClientPaymentsKey, N''Amount Applied'', N''amount'', NULL, NULL, N''Amount Applied'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7824, @ClientPaymentsKey, N''Office'', N''office'', NULL, NULL, N''Office. Required if Office ie required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7825, @ClientPaymentsKey, N''Target GL Company'', N''targetGLCompany'', NULL, NULL, N''Target GL Company. Required if GL Company is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7826, @ClientPaymentsKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7827, @ClientPaymentsKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7828, @ClientPaymentsKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7829, @ClientPaymentsKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
-- Clients
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7830, @ClientKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7831, @ClientKey, N''Primary Contact'', N''primaryContact'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7832, @ClientKey, N''Company Source'', N''companySource'', NULL, NULL, N''Company Source'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7833, @ClientKey, N''Company Type'', N''companyType'', NULL, NULL, N''Company Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7834, @ClientKey, N''Billing Manager'', N''billingManager'', NULL, NULL, N''Billing Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7835, @ClientKey, N''Phone'', N''phone'', NULL, NULL, N''Phone'', NULL, NULL, NULL, 4, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7836, @ClientKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7837, @ClientKey, N''Web Site'', N''website'', NULL, NULL, N''Web Site'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7838, @ClientKey, N''Twitter ID'', N''twitterID'', NULL, NULL, N''Twitter ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7839, @ClientKey, N''Company Address 1'', N''address1'', NULL, NULL, N''Company Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7840, @ClientKey, N''Company Address 2'', N''address2'', NULL, NULL, N''Company Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7841, @ClientKey, N''Company Address 3'', N''address3'', NULL, NULL, N''Company Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7842, @ClientKey, N''Company City'', N''city'', NULL, NULL, N''Company City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7843, @ClientKey, N''Company State'', N''state'', NULL, NULL, N''Company State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7844, @ClientKey, N''Company Postal Code'', N''postalCode'', NULL, NULL, N''Company Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7845, @ClientKey, N''Company Country'', N''country'', NULL, NULL, N''Company Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7846, @ClientKey, N''Company Owner'', N''companyOwner'', NULL, NULL, N''Company Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7847, @ClientKey, N''Account Manager'', N''accountManager'', NULL, NULL, N''Account Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7848, @ClientKey, N''Sales Person'', N''salesPerson'', NULL, NULL, N''Sales Person'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7849, @ClientKey, N''Folder'', N''folderName'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7850, @ClientKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7851, @ClientKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7852, @ClientKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7853, @ClientKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7854, @ClientKey, N''Is a Billable Client'', N''billableClient'', NULL, NULL, N''Is a Billable *[MediaPrint6]'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7855, @ClientKey, N''Client ID'', N''customerID'', NULL, NULL, N''Client ID. Required if Billable client is true'', NULL, 2, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7856, @ClientKey, N''Overhead'', N''overhead'', NULL, NULL, N''Overhead'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7857, @ClientKey, N''Is a Parent Company'', N''parentCompany'', NULL, NULL, N''Is a Parent Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7858, @ClientKey, N''Parent Company'', N''parentCompanyName'', NULL, NULL, N''Parent Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7859, @ClientKey, N''Downloaded'', N''clientDownloaded'', NULL, NULL, N''Downloaded'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7860, @ClientKey, N''Divisions'', N''divisions'', NULL, NULL, N''Divisions'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7861, @ClientKey, N''Products'', N''products'', NULL, NULL, N''Products'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7862, @ClientKey, N''Next Project Number'', N''nextProjectNum'', NULL, NULL, N''Next Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7863, @ClientKey, N''Next Campaign Number'', N''nextCampaignNum'', NULL, NULL, N''Next Campaign Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7864, @ClientKey, N''Default Sales Tax ID 1'', N''salesTaxID'', NULL, NULL, N''Default Sales Tax ID 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7865, @ClientKey, N''Default Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Default Sales Tax ID 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7866, @ClientKey, N''Default Sales GL Account Number'', N''defaultSalesAccount'', NULL, NULL, N''Default Sales GL Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7867, @ClientKey, N''Default AR Account Number'', N''defaultARAccount'', NULL, NULL, N''Default AR Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7868, @ClientKey, N''Invoice Template'', N''invoiceTemplate'', NULL, NULL, N''Invoice Template'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7869, @ClientKey, N''Layouts'', N''layout'', NULL, NULL, N''Default Invoice Layout'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7870, @ClientKey, N''Default Billing Method'', N''defaultBillingMethod'', NULL, NULL, N''Default Billing Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7871, @ClientKey, N''Expenses Not Included'', N''defaultExpensesNotIncluded'', NULL, NULL, N''Expenses Not Included'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7872, @ClientKey, N''Default Retainer'', N''defaultRetainer'', NULL, NULL, N''Default Retainer'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7873, @ClientKey, N''One Invoice Per'', N''oneInvoicePer'', NULL, NULL, N''One Invoice Per, possible values Project, Client, Parent Client, Division, Product, Campaign'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7874, @ClientKey, N''One Line Item Per'', N''defaultARLineFormat'', NULL, NULL, N''One Line Item Per'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7875, @ClientKey, N''Default Terms'', N''paymentTerms'', NULL, NULL, N''Default Terms'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7876, @ClientKey, N''Estimate Template'', N''estimateTemplate'', NULL, NULL, N''Estimate Template'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7877, @ClientKey, N''Card Holders Name'', N''cardHolderName'', NULL, NULL, N''Card Holders Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7878, @ClientKey, N''CC Number'', N''ccNumber'', NULL, NULL, N''CC Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7879, @ClientKey, N''CC Exp Month'', N''expMonth'', NULL, NULL, N''CC Exp Month'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7880, @ClientKey, N''CC Exp Year'', N''expYear'', NULL, NULL, N''CC Exp Year'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7881, @ClientKey, N''CC Verification Code'', N''cVV'', NULL, NULL, N''CC Verification Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7882, @ClientKey, N''Default Company GL'', N''glCompany'', NULL, NULL, N''Default Company GL'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7883, @ClientKey, N''Account Team'', N''defaultTeam'', NULL, NULL, N''Account Team'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7884, @ClientKey, N''Get Rate From'', N''getRateFrom'', NULL, NULL, N''Get Rate From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7885, @ClientKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7886, @ClientKey, N''Rate Sheet'', N''timeRateSheet'', NULL, NULL, N''Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7887, @ClientKey, N''Get Markup From'', N''getMarkupFrom'', NULL, NULL, N''Get Markup From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7888, @ClientKey, N''Markup Pct'', N''itemMarkup'', NULL, NULL, N''Markup Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7889, @ClientKey, N''IO Commission Pct'', N''ioCommission'', NULL, NULL, N''IO Commission Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7890, @ClientKey, N''BC Commission Pct'', N''bcCommission'', NULL, NULL, N''BC Commission Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7891, @ClientKey, N''Default Item Rate Sheet'', N''itemRateSheet'', NULL, NULL, N''Default Item Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7892, @ClientKey, N''Prebill Insertions At'', N''ioBillAt'', NULL, NULL, N''Prebill Insertions At'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7893, @ClientKey, N''Prebill Broadcast At'', N''bcBillAt'', NULL, NULL, N''Prebill Broadcast At'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7894, @ClientKey, N''Default Office'', N''office'', NULL, NULL, N''Default Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7895, @ClientKey, N''Lock Get Labor Rate'', N''lockLaborRate'', NULL, NULL, N''Lock Get Labor Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7896, @ClientKey, N''Lock Get Markup From'', N''lockMarkupFrom'', NULL, NULL, N''Lock Get Markup From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7897, @ClientKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7898, @ClientKey, N''Title Rate Sheet'', N''titleRateSheet'', NULL, NULL, N''Title Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71001, @ClientKey, N''Billing Address Name'', N''billingAddressName'', NULL, NULL, N''Billing Address Name.  Used to populate the Billing Address on the Billing Details'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71002, @ClientKey, N''Email Invoices To'', N''billingEmailContact'', NULL, NULL, N''Email Invoices To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71003, @ClientKey, N''Billing Name'', N''billingName'', NULL, NULL, N''Billing Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71004, @ClientKey, N''EIN Number'', N''einNumber'', NULL, NULL, N''EIN'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71005, @ClientKey, N''Estimate Labor Taxable'', N''estimateLaborTaxable'', NULL, NULL, N''Estimate Labor Taxable'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71006, @ClientKey, N''Project Manager'', N''projectManager'', NULL, NULL, N''Project Manager'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.ShowProjectManager == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71007, @ClientKey, N''One Line Item Per (Fixed Fee)'', N''defaultFFLineFormat'', NULL, NULL, N''One Line Item Per (Fixed Fee)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71008, @ClientKey, N''CC Receipts'', N''ccReceipts'', NULL, NULL, N''Allow Credit Card Payments Online'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71009, @ClientKey, N''ACH Receipts'', N''achReceipts'', NULL, NULL, N''Allow ACH Payments Online'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71010, @ClientKey, N''Primary Contact First Name'', N''primaryContactFirstName'', NULL, NULL, N''Primary Contact First Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71011, @ClientKey, N''Primary Contact Last Name'', N''primaryContactLastName'', NULL, NULL, N''Primary Contact Last Namee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71012, @ClientKey, N''Primary Contact Email'', N''primaryContactEmail'', NULL, NULL, N''Primary Contact Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71013, @ClientKey, N''Billing Contact First Name'', N''billingContactFirstName'', NULL, NULL, N''Billing Contact First Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71014, @ClientKey, N''Billing Contact Last Name'', N''billingContactLastName'', NULL, NULL, N''Billing Contact Last Namee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71015, @ClientKey, N''Billing Contact Email'', N''billingContactEmail'', NULL, NULL, N''Billing Contact Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71016, @ClientKey, N''Project Color'', N''projectColor'', NULL, NULL, N''Project Color in hex format (#FF0000)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (71017, @ClientKey, N''Company Address Name'', N''addressName'', NULL, NULL, N''Company Address Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Companies
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7899, @CompanyKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 1, NULL, 2, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7900, @CompanyKey, N''Primary Contact'', N''primaryContact'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7901, @CompanyKey, N''Source'', N''companySource'', NULL, NULL, N''Source'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7902, @CompanyKey, N''Company Type'', N''companyType'', NULL, NULL, N''Company Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7903, @CompanyKey, N''Main Phone'', N''phone'', NULL, NULL, N''Main Phone'', NULL, NULL, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7904, @CompanyKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7905, @CompanyKey, N''WebSite'', N''website'', NULL, NULL, N''WebSite'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7906, @CompanyKey, N''Company Address 1'', N''address1'', NULL, NULL, N''Company Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7907, @CompanyKey, N''Company Address 2'', N''address2'', NULL, NULL, N''Company Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7908, @CompanyKey, N''Company Address 3'', N''address3'', NULL, NULL, N''Company Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7909, @CompanyKey, N''Company City'', N''city'', NULL, NULL, N''Company City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7910, @CompanyKey, N''Company State'', N''state'', NULL, NULL, N''Company State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7911, @CompanyKey, N''Company Postal Code'', N''postalCode'', NULL, NULL, N''Company Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7912, @CompanyKey, N''Company Country'', N''country'', NULL, NULL, N''Company Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7913, @CompanyKey, N''Company Owner'', N''companyOwner'', NULL, NULL, N''Company Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7914, @CompanyKey, N''Account Manager'', N''accountManager'', NULL, NULL, N''Account Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7915, @CompanyKey, N''Sales Person'', N''salesPerson'', NULL, NULL, N''Sales Person'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7916, @CompanyKey, N''Folder'', N''folderName'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7917, @CompanyKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7918, @CompanyKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7919, @CompanyKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7920, @CompanyKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7921, @CompanyKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7922, @CompanyKey, N''Title Rate Sheet'', N''titleRateSheet'', NULL, NULL, N''Title Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3701, @CompanyKey, N''Project Manager'', N''projectManager'', NULL, NULL, N''Project Manager'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.ShowProjectManager == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3702, @CompanyKey, N''Primary Contact First Name'', N''primaryContactFirstName'', NULL, NULL, N''Primary Contact First Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3703, @CompanyKey, N''Primary Contact Last Name'', N''primaryContactLastName'', NULL, NULL, N''Primary Contact Last Namee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3704, @CompanyKey, N''Primary Contact Email'', N''primaryContactEmail'', NULL, NULL, N''Primary Contact Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3705, @CompanyKey, N''Company Address Name'', N''addressName'', NULL, NULL, N''Company Address Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Company Type
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7923, 44, N''Company Type Name'', N''companyTypeName'', NULL, N''CompanyTypeName'', N''Company Type Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
--Contacts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7924, @ContactKey, N''Salutation'', N''salutation'', NULL, NULL, N''Salutation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7925, @ContactKey, N''First Name'', N''firstName'', NULL, NULL, N''First Name'', NULL, 1, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7926, @ContactKey, N''Middle Name'', N''middleName'', NULL, NULL, N''Middle Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7927, @ContactKey, N''Last Name'', N''lastName'', NULL, NULL, N''Last Name'', NULL, 1, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7928, @ContactKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7929, @ContactKey, N''Linked Company'', N''linkedCompanyName'', NULL, NULL, N''Linked Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7930, @ContactKey, N''Company Name'', N''userCompanyName'', NULL, NULL, N''Company Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7931, @ContactKey, N''Primary Contact'', N''primaryContact'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7932, @ContactKey, N''Twitter ID'', N''twitterID'', NULL, NULL, N''Twitter ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7933, @ContactKey, N''LinkedIn URL'', N''linkedInUrl'', NULL, NULL, N''LinkedIn URL'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7934, @ContactKey, N''Phone 1'', N''phone1'', NULL, NULL, N''Phone 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7935, @ContactKey, N''Phone 2'', N''phone2'', NULL, NULL, N''Phone 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7936, @ContactKey, N''Cell'', N''cell'', NULL, NULL, N''Cell'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7937, @ContactKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7938, @ContactKey, N''Phone Other'', N''pager'', NULL, NULL, N''Phone Other'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7939, @ContactKey, N''Email Address'', N''email'', NULL, NULL, N''Email Address'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7940, @ContactKey, N''Personal Work Address 1'', N''workAddress1'', NULL, NULL, N''Personal Work Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7941, @ContactKey, N''Personal Work Address 2'', N''workAddress2'', NULL, NULL, N''Personal Work Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7942, @ContactKey, N''Personal Work Address 3'', N''workAddress3'', NULL, NULL, N''Personal Work Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7943, @ContactKey, N''Personal Work City'', N''workCity'', NULL, NULL, N''Personal Work City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7944, @ContactKey, N''Personal Work State'', N''workState'', NULL, NULL, N''Personal Work State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7945, @ContactKey, N''Personal Work Postal Code'', N''workPostalCode'', NULL, NULL, N''Personal Work Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7946, @ContactKey, N''Personal Work Country'', N''workCountry'', NULL, NULL, N''Personal Work Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7947, @ContactKey, N''Home Address 1'', N''homeAddress1'', NULL, NULL, N''Home Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7948, @ContactKey, N''Home Address 2'', N''homeAddress2'', NULL, NULL, N''Home Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7949, @ContactKey, N''Home Address 3'', N''homeAddress3'', NULL, NULL, N''Home Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7950, @ContactKey, N''Home City'', N''homeCity'', NULL, NULL, N''Home City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7951, @ContactKey, N''Home State'', N''homeState'', NULL, NULL, N''Home State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7952, @ContactKey, N''Home Postal Code'', N''homePostalCode'', NULL, NULL, N''Home Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7953, @ContactKey, N''Home Country'', N''homeCountry'', NULL, NULL, N''Home Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7954, @ContactKey, N''Other Address 1'', N''otherAddress1'', NULL, NULL, N''Other Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7955, @ContactKey, N''Other Address 2'', N''otherAddress2'', NULL, NULL, N''Other Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7956, @ContactKey, N''Other Address 3'', N''otherAddress3'', NULL, NULL, N''Other Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7957, @ContactKey, N''Other City'', N''otherCity'', NULL, NULL, N''Other City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7958, @ContactKey, N''Other State'', N''otherState'', NULL, NULL, N''Other State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7959, @ContactKey, N''Other Postal Code'', N''otherPostalCode'', NULL, NULL, N''Other Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7960, @ContactKey, N''Other Country'', N''otherCountry'', NULL, NULL, N''Other Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7961, @ContactKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7962, @ContactKey, N''Date of Hire'', N''dateHired'', NULL, NULL, N''Date of Hire'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7963, @ContactKey, N''Department'', N''department'', NULL, NULL, N''Department'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7964, @ContactKey, N''Reports To'', N''reportsToName'', NULL, NULL, N''Reports To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7965, @ContactKey, N''Assistant'', N''assistant'', NULL, NULL, N''Assistant'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7966, @ContactKey, N''Assistant Phone'', N''assistantPhone'', NULL, NULL, N''Assistant Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7967, @ContactKey, N''Assistant Email'', N''assistantEmail'', NULL, NULL, N''Assistant Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7968, @ContactKey, N''Birthday'', N''birthday'', NULL, NULL, N''Birthday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7969, @ContactKey, N''Spouse/Partner'', N''spouseName'', NULL, NULL, N''Spouse/Partner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7970, @ContactKey, N''Children'', N''children'', NULL, NULL, N''Children'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7971, @ContactKey, N''Anniversary'', N''anniversary'', NULL, NULL, N''Anniversary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7972, @ContactKey, N''Hobbies'', N''hobbies'', NULL, NULL, N''Hobbies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7973, @ContactKey, N''Marketing Groups'', N''marketingLists'', NULL, NULL, N''Marketing Groups'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7974, @ContactKey, N''Preferred Contact Method'', N''contactMethod'', NULL, NULL, N''Preferred Contact Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7975, @ContactKey, N''Do Not Call'', N''doNotCall'', NULL, NULL, N''Do Not Call'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7976, @ContactKey, N''Do Not Email'', N''doNotEmail'', NULL, NULL, N''Do Not Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7977, @ContactKey, N''Do Not Mail'', N''doNotMail'', NULL, NULL, N''Do Not Mail'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7978, @ContactKey, N''Do Not Fax'', N''doNotFax'', NULL, NULL, N''Do Not Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7979, @ContactKey, N''Default GL Company'', N''glCompany'', NULL, NULL, N''Default GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7980, @ContactKey, N''Services'', N''services'', NULL, NULL, N''Services'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7981, @ContactKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7982, @ContactKey, N''Billing Title ID'', N''titleID'', NULL, NULL, N''Billing Title ID'', NULL, NULL, N''BillingTitleID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7983, @ContactKey, N''Invoice Email Name'', N''invoiceEmailName'', NULL, NULL, N''Invoice Email Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7984, @ContactKey, N''Invoice Email Address'', N''invoiceEmailAddress'', NULL, NULL, N''Invoice Email Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7985, @ContactKey, N''System ID'', N''systemID'', NULL, NULL, N''System ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7986, @ContactKey, N''Contact Owner'', N''contactOwner'', NULL, NULL, N''Contact Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7987, @ContactKey, N''Folder'', N''folder'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7988, @ContactKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7989, @ContactKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7990, @ContactKey, N''Password'', N''newPassword'', NULL, NULL, N''Password'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7991, @ContactKey, N''Security Group'', N''securityGroup'', NULL, NULL, N''Security Group'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7992, @ContactKey, N''Free Login'', N''clientVendorLogin'', NULL, NULL, N''Free Login'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7993, @ContactKey, N''Timezone Index'', N''timeZoneIndex'', NULL, NULL, N''Timezone Index'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7994, @ContactKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7995, @ContactKey, N''Role'', N''userRole'', NULL, NULL, N''Role'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyroles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7996, @ContactKey, N''Skills'', N''skills'', NULL, NULL, N''Skills'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyskills'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (100, @ContactKey, N''Division'', N''clientDivision'', NULL, NULL, N''Division'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (101, @ContactKey, N''Product'', N''clientProduct'', NULL, NULL, N''Product'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (102, @ContactKey, N''Invoice Exclude Attachments'', N''invoiceExcludeAttachment'', NULL, NULL, N''Invoice Exclude Attachments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (103, @ContactKey, N''Do Not Use SSO Auth'', N''doNotUseSSO'', NULL, NULL, N''Do Not Use SAML/SSO Authentication'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Credit Card Charges
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7997, @CreditCardCharge, N''Credit Card Account'', N''aPAccountNumber'', NULL, NULL, N''Credit Card Account'', N''header'', 1, N''Credit Card Account'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7998, @CreditCardCharge, N''Reference Number'', N''invoiceNumber'', NULL, NULL, N''Reference Number'', N''header'', NULL, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7999, @CreditCardCharge, N''Charge Date'', N''invoiceDate'', NULL, NULL, N''Charge Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8000, @CreditCardCharge, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8001, @CreditCardCharge, N''Purchased By'', N''boughtBy'', NULL, NULL, N''Purchased By'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8002, @CreditCardCharge, N''Purchased From'', N''boughtFromID'', NULL, NULL, N''Purchased From'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8003, @CreditCardCharge, N''Approved By'', N''approvedBy'', NULL, NULL, N''Approved By'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8004, @CreditCardCharge, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8007, @CreditCardCharge, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8008, @CreditCardCharge, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8009, @CreditCardCharge, N''Overhead Charge'', N''voucherType'', NULL, NULL, N''Overhead Charge'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8010, @CreditCardCharge, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8011, @CreditCardCharge, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8012, @CreditCardCharge, N''Office'', N''officeID'', NULL, NULL, N''Office. Required if office is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition],[SystemSettingFieldName]) VALUES (8013, @CreditCardCharge, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if item is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL, N''RequireItems'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8014, @CreditCardCharge, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8015, @CreditCardCharge, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8016, @CreditCardCharge, N''Unit Description'', N''unitDescription'', NULL, NULL, N''Unit Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8017, @CreditCardCharge, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8018, @CreditCardCharge, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8019, @CreditCardCharge, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8020, @CreditCardCharge, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8021, @CreditCardCharge, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8022, @CreditCardCharge, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8023, @CreditCardCharge, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8024, @CreditCardCharge, N''Expense Account'', N''expenseAccountNumber'', NULL, NULL, N''Expense Account. Required if GL Acounts are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8025, @CreditCardCharge, N''Department'', N''departmentID'', NULL, NULL, N''Department. Required if Departments are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8026, @CreditCardCharge, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8027, @CreditCardCharge, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57002, @CreditCardCharge, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57003, @CreditCardCharge, N''Sales Tax 2 ID'', N''salesTax2ID'', NULL, NULL, N''Sales Tax 2 ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57004, @CreditCardCharge, N''Sales Tax Amount (line)'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57005, @CreditCardCharge, N''Sales Tax Amount 2 (line)'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2 (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8028, @CreditCardCharge, N''Taxable (line)'', N''taxable'', NULL, NULL, N''Taxable (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8029, @CreditCardCharge, N''Taxable 2 (line)'', N''taxable2'', NULL, NULL, N''Taxable 2 (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8030, @CreditCardCharge, N''Line Description'', N''shortDescription'', NULL, NULL, N''Line Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8031, @CreditCardCharge, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8032, @CreditCardCharge, N''Project Exchange Rate (Line)'', N''pExchangeRateLine'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8033, @CreditCardCharge, N''Class ID'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'',  N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57001, @CreditCardCharge, N''Exclude from 1099'', N''exclude1099'', NULL, NULL, N''Exclude from 1099 Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL,NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57006, @CreditCardCharge, N''Class ID (Line)'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'',  N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57007, @CreditCardCharge, N''Voucher Invoice Number (Line)'', N''voucherInvoiceNumber'', NULL, NULL, N''Voucher Invoice Number (Line)'',  N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57008, @CreditCardCharge, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57009, @CreditCardCharge, N''Vendor ID (Line)'', N''vendorID'', NULL, NULL, N''Vendor ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57010, @CreditCardCharge, N''Markup From Project (Line)'', N''markupFromProject'', NULL, NULL, N''Markup from Project (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57011, @CreditCardCharge, N''Target GL Company (Line)'', N''targetGLCompanyID'', NULL, NULL, N''Target GL Copmpany ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57012, @CreditCardCharge, N''Office (Line)'', N''officeID'', NULL, NULL, N''Office (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57013, @CreditCardCharge, N''Amount to Bill'', N''amountToBill'', NULL, NULL, N''Amount to Bill'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57014, @CreditCardCharge, N''GL Company Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57015, @CreditCardCharge, N''Invoice Exchange Rate'', N''invoiceExchangeRate'', NULL, NULL, N''Invoice Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57016, @CreditCardCharge, N''Net Cost (HC)'', N''hcTotalCost'', NULL, NULL, N''Net Cost (Home Currency)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57017, @CreditCardCharge, N''Project Currency ID'', N''pCurrencyID'', NULL, NULL, N''Project Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57018, @CreditCardCharge, N''Project Currency ID (Line)'', N''pCurrencyLineID'', NULL, NULL, N''Project Currency ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57019, @CreditCardCharge, N''Project Exchange Rate'', N''projectExchangeRate'', NULL, NULL, N''Project Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57020, @CreditCardCharge, N''Project Net Cost'', N''pTotalCost'', NULL, NULL, N''Project Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57021, @CreditCardCharge, N''Invoice Currency ID'', N''currencyID'', NULL, NULL, N''Invoice Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (57022, @CreditCardCharge, N''Comment'', N''comment'', NULL, NULL, N''Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)

--Credit Card Connector.. aka credit card transactions
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8034, @CreditCardConnector, N''GL Account Number'', N''glAccountNumber'', NULL, NULL, N''GL Account Number'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8035, @CreditCardConnector, N''Amount'', N''amount'', NULL, NULL, N''Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8037, @CreditCardConnector, N''FITID'', N''fITID'', NULL, NULL, N''FITID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8038, @CreditCardConnector, N''Payee Name'', N''payeeName'', NULL, NULL, N''Payee Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8039, @CreditCardConnector, N''Memo'', N''memo'', NULL, NULL, N''Memo'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8040, @CreditCardConnector, N''Date'', N''transactionPostedDate'', NULL, NULL, N''Date Posted'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8041, @CreditCardConnector, N''Transaction Type'', N''transactionType'', NULL, NULL, N''Transaction Type'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6201, @CreditCardConnector, N''Charged By'', N''chargedBy'', NULL, NULL, N''Charged By'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6202, @CreditCardConnector, N''Expense Account Number'', N''expenseAccount'', NULL, NULL, N''Expense Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6203, @CreditCardConnector, N''Item ID'', N''itemKey'', NULL, NULL, N''Item ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6204, @CreditCardConnector, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', NUll, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')

-- Currency Rates
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8042, @CurrencyRateKey, N''GL Company'', N''glCompanyName'', NULL, N''GLCompanyName'', N''GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8043, @CurrencyRateKey, N''Effective Date'', N''effectiveDate'', NULL, N''EffectiveDate'', N''Effective Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8044, @CurrencyRateKey, N''Exchange Rate'', N''exchangeRate'', NULL, N''ExchangeRate'', N''Exchange Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8045, @CurrencyRateKey, N''Currency'', N''currencyID'', NULL, N''CurrencyID'', N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (63001, @CurrencyRateKey, N''ToCurrency'', N''toCurrencyID'', NULL, N''ToCurrencyID'', N''ToCurrency'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Deliverables
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80001, @DeliverableKey, N''Deliverable ID'', N''deliverableID'', NULL, NULL, N''Deliverable ID'', NULL, NULL, NULL, 1, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80002, @DeliverableKey, N''Deliverable Name'', N''deliverableName'', NULL, NULL, N''Deliverable Name'', NULL, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80003, @DeliverableKey, N''Deliverable Status'', N''deliverableStatus'', NULL, NULL, N''Deliverable Status'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80004, @DeliverableKey, N''Deliverable Type'', N''deliverableType'', NULL, NULL, N''Deliverable Type'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80005, @DeliverableKey, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80006, @DeliverableKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80007, @DeliverableKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80008, @DeliverableKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80009, @DeliverableKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80010, @DeliverableKey, N''Approved Date'', N''approvedDate'', NULL, NULL, N''Approved Date'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField]) VALUES (80011, @DeliverableKey, N''Owner ID'', N''ownerID'', NULL, NULL, N''Owner User ID'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Department
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8046, 28, N''Department Name'', N''departmentName'', NULL, N''DepartmentName'', N''Department Name'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8047, 28, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Conversation
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11601, @ConversationKey, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11602, @ConversationKey, N''Activity Date'', N''activityDate'', NULL, NULL, N''Activity Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11603, @ConversationKey, N''Completed'', N''completed'', NULL, NULL, N''Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11604, @ConversationKey, N''Date Completed'', N''dateCompleted'', NULL, NULL, N''Date Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11605, @ConversationKey, N''Assigned To'', N''assignedUser'', NULL, NULL, N''Assigned To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11606, @ConversationKey, N''Private'', N''private'', NULL, NULL, N''Private'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11607, @ConversationKey, N''Folder'', N''cMFolderKey'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11608, @ConversationKey, N''Activity Type'', N''activityType'', NULL, NULL, N''Activity Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11609, @ConversationKey, N''Notes'', N''notes'', NULL, NULL, N''Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11610, @ConversationKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11611, @ConversationKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11612, @ConversationKey, N''Contact'', N''linkedContact'', NULL, NULL, N''Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11613, @ConversationKey, N''Company'', N''linkedCompany'', NULL, NULL, N''Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11614, @ConversationKey, N''Opportunity'', N''linkedLead'', NULL, NULL, N''Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11615, @ConversationKey, N''Lead'', N''linkedUserLead'', NULL, NULL, N''Lead'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11616, @ConversationKey, N''Start Time'', N''startTime'', NULL, NULL, N''Start Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11617, @ConversationKey, N''End Time'', N''endTime'', NULL, NULL, N''End Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11618, @ConversationKey, N''Reminder (minutes)'', N''reminderMinutes'', NULL, NULL, N''Reminder (minutes)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11619, @ConversationKey, N''Priority'', N''priority'', NULL, NULL, N''Priority'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11620, @ConversationKey, N''Originator'', N''originatorUserKey'', NULL, NULL, N''Originator'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11621, @ConversationKey, N''Visible To Client'', N''visibleToClient'', NULL, NULL, N''Visible To Client'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11622, @ConversationKey, N''View As'', N''activityEntity'', NULL, NULL, N''View As'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11623, @ConversationKey, N''Outcome'', N''outcome'', NULL, NULL, N''Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11624, @ConversationKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company, Required if GL Company is required '', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')

-- Employee
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8048, @EmployeeKey, N''First Name'', N''firstName'', NULL, NULL, N''First Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8049, @EmployeeKey, N''Middle Name'', N''middleName'', NULL, NULL, N''Middle Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8050, @EmployeeKey, N''Last Name'', N''lastName'', NULL, NULL, N''Last Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8051, @EmployeeKey, N''Salutation'', N''salutation'', NULL, NULL, N''Salutation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8052, @EmployeeKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8053, @EmployeeKey, N''Office'', N''office'', NULL, NULL, N''Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8054, @EmployeeKey, N''Department'', N''department'', NULL, NULL, N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8055, @EmployeeKey, N''Is Supervisor'', N''supervisor'', NULL, NULL, N''Is Supervisor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8056, @EmployeeKey, N''Timezone Index'', N''timeZoneIndex'', NULL, NULL, N''Timezone Index'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8057, @EmployeeKey, N''System ID'', N''systemID'', NULL, NULL, N''System ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8058, @EmployeeKey, N''Default Calendar Color'', N''defaultCalendarColor'', NULL, NULL, N''Default Calendar Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8059, @EmployeeKey, N''Phone'', N''phone'', NULL, NULL, N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8060, @EmployeeKey, N''Second Phone'', N''phone2'', NULL, NULL, N''Second Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8061, @EmployeeKey, N''Cell Phone'', N''cell'', NULL, NULL, N''Cell Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8062, @EmployeeKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8063, @EmployeeKey, N''Other'', N''pager'', NULL, NULL, N''Other'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8064, @EmployeeKey, N''Email'', N''email'', NULL, NULL, N''Email'', NULL, NULL, NULL, 2, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8065, @EmployeeKey, N''Hourly Cost'', N''hourlyCost'', NULL, NULL, N''Hourly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8066, @EmployeeKey, N''Monthly Cost'', N''monthlyCost'', NULL, NULL, N''Monthly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8067, @EmployeeKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8068, @EmployeeKey, N''Time Approver'', N''timeApprover'', NULL, NULL, N''Time Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810029, @EmployeeKey, N''Calendar Approver'', N''calendarApprover'', NULL, NULL, N''Meeting Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8069, @EmployeeKey, N''Expense Approver'', N''expenseApprover'', NULL, NULL, N''Expense Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8070, @EmployeeKey, N''Credit Card Approver'', N''creditCardApprover'', NULL, NULL, N''Credit Card Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8071, @EmployeeKey, N''Backup Approver'', N''backupApprover'', NULL, NULL, N''Backup Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8072, @EmployeeKey, N''Time Sheet Required'', N''timesheetRequired'', NULL, NULL, N''Time Sheet Required'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8073, @EmployeeKey, N''Require Times on Time Sheet'', N''requireUserTimeDetails'', NULL, NULL, N''Require Times on Time Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8074, @EmployeeKey, N''Require Minimum Hours'', N''requireMinimumHours'', NULL, NULL, N''Require Minimum Hours'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8075, @EmployeeKey, N''Minimum Hours Monday'', N''hoursMonday'', NULL, NULL, N''Minimum Hours Monday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8076, @EmployeeKey, N''Minimum Hours Tuesday'', N''hoursTuesday'', NULL, NULL, N''Minimum Hours Tuesday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8077, @EmployeeKey, N''Minimum Hours Wednesday'', N''hoursWednesday'', NULL, NULL, N''Minimum Hours Wednesday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8078, @EmployeeKey, N''Minimum Hours Thursday'', N''hoursThursday'', NULL, NULL, N''Minimum Hours Thursday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8079, @EmployeeKey, N''Minimum Hours Friday'', N''hoursFriday'', NULL, NULL, N''Minimum Hours Friday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8080, @EmployeeKey, N''Minimum Hours Saturday'', N''hoursSaturday'', NULL, NULL, N''Minimum Hours Saturday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8081, @EmployeeKey, N''Minimum Hours Sunday'', N''hoursSunday'', NULL, NULL, N''Minimum Hours Sunday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8082, @EmployeeKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8083, @EmployeeKey, N''Password'', N''password'', NULL, NULL, N''Password'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8084, @EmployeeKey, N''Security Group'', N''securityGroup'', NULL, NULL, N''Security Group'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8085, @EmployeeKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8086, @EmployeeKey, N''Locked'', N''locked'', NULL, NULL, N''Locked'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8087, @EmployeeKey, N''Subscribe to Diary'', N''subscribeDiary'', NULL, NULL, N''Subscribe to Diary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8088, @EmployeeKey, N''Subscribe to ToDo'', N''subscribeToDo'', NULL, NULL, N''Subscribe to ToDo'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8089, @EmployeeKey, N''Default Reviewer'', N''deliverableReviewer'', NULL, NULL, N''Default Reviewer'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8090, @EmployeeKey, N''Default Notify'', N''deliverableNotify'', NULL, NULL, N''Default Notify'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8091, @EmployeeKey, N''Date Hired'', N''dateHired'', NULL, NULL, N''Date Hired'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8092, @EmployeeKey, N''Anniversary'', N''anniversary'', NULL, NULL, N''Anniversary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8093, @EmployeeKey, N''Birthday'', N''birthday'', NULL, NULL, N''Birthday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8094, @EmployeeKey, N''Children'', N''children'', NULL, NULL, N''Children'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8095, @EmployeeKey, N''Spouse/Partner'', N''spouseName'', NULL, NULL, N''Spouse/Partner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8096, @EmployeeKey, N''Personal Work Address 1'', N''personalWorkAddress1'', NULL, NULL, N''Personal Work Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8097, @EmployeeKey, N''Personal Work Address 2'', N''personalWorkAddress2'', NULL, NULL, N''Personal Work Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8098, @EmployeeKey, N''Personal Work Address 3'', N''personalWorkAddress3'', NULL, NULL, N''Personal Work Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8099, @EmployeeKey, N''Personal Work City'', N''personalWorkCity'', NULL, NULL, N''Personal Work City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8100, @EmployeeKey, N''Personal Work State'', N''personalWorkState'', NULL, NULL, N''Personal Work State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8101, @EmployeeKey, N''Personal Work Postal Code'', N''personalWorkPostalCode'', NULL, NULL, N''Personal Work Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8102, @EmployeeKey, N''Personal Work Country'', N''personalWorkCountry'', NULL, NULL, N''Personal Work Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8103, @EmployeeKey, N''Home Address 1'', N''homeAddress1'', NULL, NULL, N''Home Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8104, @EmployeeKey, N''Home Address 2'', N''homeAddress2'', NULL, NULL, N''Home Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8105, @EmployeeKey, N''Home Address 3'', N''homeAddress3'', NULL, NULL, N''Home Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8106, @EmployeeKey, N''Home City'', N''homeCity'', NULL, NULL, N''Home City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8107, @EmployeeKey, N''Home State'', N''homeState'', NULL, NULL, N''Home State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8108, @EmployeeKey, N''Home Postal Code'', N''homePostalCode'', NULL, NULL, N''Home Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8109, @EmployeeKey, N''Home Country'', N''homeCountry'', NULL, NULL, N''Home Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8110, @EmployeeKey, N''Other Address 1'', N''otherAddress1'', NULL, NULL, N''Other Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8111, @EmployeeKey, N''Other Address 2'', N''otherAddress2'', NULL, NULL, N''Other Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8112, @EmployeeKey, N''Other Address 3'', N''otherAddress3'', NULL, NULL, N''Other Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8113, @EmployeeKey, N''Other City'', N''otherCity'', NULL, NULL, N''Other City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8114, @EmployeeKey, N''Other State'', N''otherState'', NULL, NULL, N''Other State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8115, @EmployeeKey, N''Other Postal Code'', N''otherPostalCode'', NULL, NULL, N''Other Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8116, @EmployeeKey, N''Other Country'', N''otherCountry'', NULL, NULL, N''Other Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8117, @EmployeeKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8118, @EmployeeKey, N''PO Order Limit'', N''poLimit'', NULL, NULL, N''PO Order Limit'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8119, @EmployeeKey, N''Insertion Order Limit'', N''ioLimit'', NULL, NULL, N''Insertion Order Limit'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8120, @EmployeeKey, N''Broadcast Order Limit'', N''bcLimit'', NULL, NULL, N''Broadcast Order Limit'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8121, @EmployeeKey, N''Default GL Company'', N''defaultGLCompany'', NULL, NULL, N''Default GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8122, @EmployeeKey, N''Services'', N''services'', NULL, NULL, N''Services, use ; to seperate multiple'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8123, @EmployeeKey, N''Default Service'', N''defaultService'', NULL, NULL, N''Default Service'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8124, @EmployeeKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8125, @EmployeeKey, N''Billing Title ID'', N''billingTitleID'', NULL, NULL, N''Billing Title ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3001, @EmployeeKey, N''Supervisor Name'', N''supervisorName'', NULL, NULL, N''Supervisor Name aka My Supervisor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3002, @EmployeeKey, N''Vendor Cost'', N''vendorCost'', NULL, NULL, N''Vendor Cost if user is a vendor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3003, @EmployeeKey, N''Require Min Hours Per Week'', N''requireMinHoursPerWeek'', NULL, NULL, N''Require Min Hours Per Week'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3004, @EmployeeKey, N''Min Hours Per Week'', N''minHoursPerWeek'', NULL, NULL, N''Minimum Hours Per Week'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3005, @EmployeeKey, N''Do Not Use SSO Auth'', N''doNotUseSSO'', NULL, NULL, N''Do Not Use SAML/SSO Authentication'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810026, @EmployeeKey, N''Overtime Cost'', N''overtimeCost'', NULL, NULL, N''Overtime Cost'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.TrackOvertime == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810027, @EmployeeKey, N''Overtime Vendor Cost'', N''overtimeVendorCost'', NULL, NULL, N''Overtime Vendor Cost'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.TrackOvertime == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (810028, @EmployeeKey, N''Contractor'', N''contractor'', NULL, NULL, N''Contractor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Estimates
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8126, @EstimateKey, N''Estimate Number'', N''estimateNumber'', NULL, NULL, N''Estimate Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8127, @EstimateKey, N''Estimate Name'', N''estimateName'', NULL, NULL, N''Estimate Name'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8128, @EstimateKey, N''Estimate Type'', N''estType'', NULL, NULL, N''Estimate Type'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8129, @EstimateKey, N''Revision'', N''revision'', NULL, NULL, N''Revision'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8130, @EstimateKey, N''Change Order'', N''changeOrder'', NULL, NULL, N''Change Order'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8131, @EstimateKey, N''Contact Name'', N''contactName'', NULL, NULL, N''Contact Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8132, @EstimateKey, N''Project Number'', N''projectKey'', NULL, NULL, N''Project Number'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8133, @EstimateKey, N''Estimate Date'', N''estimateDate'', NULL, NULL, N''Estimate Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8134, @EstimateKey, N''Estimate Description'', N''estDescription'', NULL, NULL, N''Estimate Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8135, @EstimateKey, N''Estimate Template'', N''estimateTemplateName'', NULL, NULL, N''Estimate Template'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8136, @EstimateKey, N''User Defined 1'', N''userDefined1'', NULL, NULL, N''User Defined 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8137, @EstimateKey, N''User Defined 2'', N''userDefined2'', NULL, NULL, N''User Defined 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8138, @EstimateKey, N''User Defined 3'', N''userDefined3'', NULL, NULL, N''User Defined 3'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8139, @EstimateKey, N''User Defined 4'', N''userDefined4'', NULL, NULL, N''User Defined 4'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8140, @EstimateKey, N''User Defined 5'', N''userDefined5'', NULL, NULL, N''User Defined 5'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8141, @EstimateKey, N''User Defined 6'', N''userDefined6'', NULL, NULL, N''User Defined 6'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8142, @EstimateKey, N''User Defined 7'', N''userDefined7'', NULL, NULL, N''User Defined 7'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8143, @EstimateKey, N''User Defined 8'', N''userDefined8'', NULL, NULL, N''User Defined 8'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8144, @EstimateKey, N''User Defined 9'', N''userDefined9'', NULL, NULL, N''User Defined 9'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8145, @EstimateKey, N''User Defined 10'', N''userDefined10'', NULL, NULL, N''User Defined 10'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8146, @EstimateKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8147, @EstimateKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8148, @EstimateKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8149, @EstimateKey, N''Approver'', N''internalApprover'', NULL, NULL, N''Approver'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8150, @EstimateKey, N''Approval Comment'', N''internalComments'', NULL, NULL, N''Approval Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8151, @EstimateKey, N''Approval Date'', N''approvalDate'', NULL, NULL, N''Approval Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8152, @EstimateKey, N''Layout Name'', N''layoutKey'', NULL, NULL, N''Layout Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8153, @EstimateKey, N''Labor Taxable'', N''laborTaxable'', NULL, NULL, N''Labor Taxable'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8154, @EstimateKey, N''Contingency'', N''contingency'', NULL, NULL, N''Contingency'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8155, @EstimateKey, N''Line Type'', N''lineType'', NULL, NULL, N''Line Type'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8156, @EstimateKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8157, @EstimateKey, N''Service Code'', N''serviceCode'', NULL, NULL, N''Service Code. Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8158, @EstimateKey, N''Person'', N''userKey'', NULL, NULL, N''Person'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8159, @EstimateKey, N''Hours'', N''hours'', NULL, NULL, N''Hours'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8160, @EstimateKey, N''Labor Net'', N''laborNet'', NULL, NULL, N''Labor Net'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8161, @EstimateKey, N''Labor Gross'', N''laborGross'', NULL, NULL, N''Labor Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8162, @EstimateKey, N''Labor Rate Net'', N''laborRateNet'', NULL, NULL, N''Labor Rate Net'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8163, @EstimateKey, N''Labor Rate Gross'', N''laborRateGross'', NULL, NULL, N''Labor Rate Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8164, @EstimateKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8165, @EstimateKey, N''Expense Net'', N''expenseNet'', NULL, NULL, N''Expense Net'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8166, @EstimateKey, N''Expense Gross'', N''expenseGross'', NULL, NULL, N''Expense Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8167, @EstimateKey, N''Item ID (Expense)'', N''itemKey'', NULL, NULL, N''Item ID (Expense). Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8168, @EstimateKey, N''Vendor ID (Expense)'', N''vendorKey'', NULL, NULL, N''Vendor ID (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8169, @EstimateKey, N''Billable (Expense)'', N''billable'', NULL, NULL, N''Billable (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8170, @EstimateKey, N''Taxable (Expense)'', N''taxable'', NULL, NULL, N''Taxable (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8171, @EstimateKey, N''Taxable 2 (Expense)'', N''taxable2'', NULL, NULL, N''Taxable 2 (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8172, @EstimateKey, N''Quantity (Expense)'', N''quantity'', NULL, NULL, N''Quantity (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8173, @EstimateKey, N''Description (Expense)'', N''description'', NULL, NULL, N''Description (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8174, @EstimateKey, N''Unit Cost (Expense)'', N''unitCost'', NULL, NULL, N''Unit Cost (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8175, @EstimateKey, N''Unit Rate (Expense)'', N''unitRate'', NULL, NULL, N''Unit Rate (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8176, @EstimateKey, N''Unit Description (Expense)'', N''unitDescription'', NULL, NULL, N''Unit Description (Expense). Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8177, @EstimateKey, N''Display Order (Expense)'', N''displayOrder'', NULL, NULL, N''Display Order (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8178, @EstimateKey, N''Class ID (Expense)'', N''classKey'', NULL, NULL, N''Class ID (Expense). Maybe required based on estimate type'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (16001, @EstimateKey, N''Long Description (Expense)'', N''longDescription'', NULL, NULL, N''Long Description (Expense)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Expense Report Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8179, 4, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8180, 4, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8181, 4, N''Unit Cost'', N''unitCost'', NULL, N''UnitCost'', N''Unit Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8182, 4, N''Markup'', N''markup'', NULL, N''Markup'', N''Markup'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8183, 4, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8184, 4, N''Always use Unit Rate for Gross Amount'', N''useUnitRate'', NULL, N''UseUnitRate'', N''Always use Unit Rate for Gross Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8185, 4, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8186, 4, N''Use Description on Expense Report'', N''useDescription'', NULL, N''UseDescription'', N''Use Description on Expense Report'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8187, 4, N''Billing Item ID'', N''workTypeKey'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8188, 4, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8189, 4, N''Expense Account Number'', N''expenseAccountKey'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8190, 4, N''Sales Account Number'', N''salesAccountKey'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8191, 4, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8192, 4, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8193, 4, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8194, 4, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID'', NULL, NULL, N''ClassID. Required if Class is required'', NULL, 2, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (819400, 4, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')

-- Expense Reports
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8195, @ExpenseReportKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8196, @ExpenseReportKey, N''Report Number'', N''envelopeNumber'', NULL, NULL, N''Report Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8197, @ExpenseReportKey, N''Name'', N''userName'', NULL, NULL, N''Name'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8198, @ExpenseReportKey, N''Sales Tax 1'', N''salesTaxID'', NULL, NULL, N''Sales Tax 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8199, @ExpenseReportKey, N''Sales Tax 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8200, @ExpenseReportKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8201, @ExpenseReportKey, N''Date'', N''expenseDate'', NULL, NULL, N''Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8202, @ExpenseReportKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if Items are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8203, @ExpenseReportKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8204, @ExpenseReportKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8205, @ExpenseReportKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if tasks are required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8206, @ExpenseReportKey, N''Paper Receipt'', N''paperReceipt'', NULL, NULL, N''Paper Receipt'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8207, @ExpenseReportKey, N''Quantity'', N''actualQty'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8208, @ExpenseReportKey, N''Unit Cost'', N''actualUnitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8209, @ExpenseReportKey, N''Net Cost'', N''actualCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8210, @ExpenseReportKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8211, @ExpenseReportKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8212, @ExpenseReportKey, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8213, @ExpenseReportKey, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8214, @ExpenseReportKey, N''Tax1 (Line)'', N''taxable'', NULL, NULL, N''Tax1 (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8215, @ExpenseReportKey, N''Tax2 (Line)'', N''taxable2'', NULL, NULL, N''Tax2 (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8216, @ExpenseReportKey, N''Sales Tax 1 Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax 1 Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8217, @ExpenseReportKey, N''Sales Tax 2 Amount'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax 2 Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8218, @ExpenseReportKey, N''Total Sales Tax Amount'', N''salesTaxAmount'', NULL, NULL, N''Total Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8219, @ExpenseReportKey, N''Comments (Line)'', N''commentsline'', NULL, NULL, N''Comments (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8220, @ExpenseReportKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8221, @ExpenseReportKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8222, @ExpenseReportKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (2201, @ExpenseReportKey, N''Approval Status'', N''approvalStatus'', NULL, NULL, N''Approval Staus - Unsubmitted, Submittted, Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- financial Budgets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8223, @GLBudget, N''Budget Name'', N''budgetName'', NULL, N''BudgetName'', N''Budget Name'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8224, @GLBudget, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8225, @GLBudget, N''GL Account'', N''glAccountNumber'', NULL, N''AccountNumber'', N''GL Account'', N''detail'', 1, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8226, @GLBudget, N''Client ID'', N''clientID'', NULL, N''ClientID'', N''Client ID'', N''detail'', NULL, N''CustomerID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8227, @GLBudget, N''GL Company'', N''glCompany'', NULL, N''GLCompanyID'', N''GL Company. Required if GL Company is required'', N''detail'', 2, N''GLCompanyName'', NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8228, @GLBudget, N''Office'', N''officeID'', NULL, N''OfficeID'', N''Office. Required if Office is required'', N''detail'', 2, N''OfficeName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8229, @GLBudget, N''Department'', N''department'', NULL, N''DepartmentName'', N''Department. Required if department is required'', N''detail'', 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8230, @GLBudget, N''Month 1'', N''month1'', NULL, N''Month1'', N''Month 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8231, @GLBudget, N''Month 2'', N''month2'', NULL, N''Month2'', N''Month 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8232, @GLBudget, N''Month 3'', N''month3'', NULL, N''Month3'', N''Month 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8233, @GLBudget, N''Month 4'', N''month4'', NULL, N''Month4'', N''Month 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8234, @GLBudget, N''Month 5'', N''month5'', NULL, N''Month5'', N''Month 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8235, @GLBudget, N''Month 6'', N''month6'', NULL, N''Month6'', N''Month 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8236, @GLBudget, N''Month 7'', N''month7'', NULL, N''Month7'', N''Month 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8237, @GLBudget, N''Month 8'', N''month8'', NULL, N''Month8'', N''Month 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8238, @GLBudget, N''Month 9'', N''month9'', NULL, N''Month9'', N''Month 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8239, @GLBudget, N''Month 10'', N''month10'', NULL, N''Month10'', N''Month 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8240, @GLBudget, N''Month 11'', N''month11'', NULL, N''Month11'', N''Month 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8241, @GLBudget, N''Month 12'', N''month12'', NULL, N''Month12'', N''Month 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8242, @GLBudget, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID. Required if Class is required'', N''detail'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
-- GL Accounts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8243, @GLAccountKey, N''Account Type'', N''accountType'', NULL, N''AccountTypeName'', N''Account Type'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8244, @GLAccountKey, N''Account Number'', N''accountNumber'', NULL, N''AccountNumber'', N''Account Number'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8245, @GLAccountKey, N''Account Name'', N''accountName'', NULL, N''AccountName'', N''Account Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8246, @GLAccountKey, N''Cash Account Type'', N''accountTypeCash'', NULL, N''AccountTypeNameCash'', N''Cash Account Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8247, @GLAccountKey, N''Payroll Expense Account'', N''payrollExpense'', NULL, N''PayrollExpenseYN'', N''Payroll Expense Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8248, @GLAccountKey, N''Facility Expense Account'', N''facilityExpense'', NULL, N''FacilityExpenseYN'', N''Facility Expense Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8249, @GLAccountKey, N''Labor Income'', N''laborIncome'', NULL, N''LaborIncome'', N''Labor Income'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8250, @GLAccountKey, N''Rollup Account'', N''rollup'', NULL, N''Rollup'', N''Rollup Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8251, @GLAccountKey, N''Sub Account Of'', N''parentAccountNumber'', NULL, N''ParentAccountNumber'', N''Sub Account Of (Enter ''''none'''', if changing from one to none)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8252, @GLAccountKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID. Required if the Account Type is credit card'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8253, @GLAccountKey, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8254, @GLAccountKey, N''Bank Account Number'', N''bankAccountNumber'', NULL, N''BankAccountNumber'', N''Bank Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8255, @GLAccountKey, N''Next Check Number'', N''nextCheckNumber'', NULL, N''NextCheckNumber'', N''Next Check Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8256, @GLAccountKey, N''No Journal Entries'', N''noJournalEntries'', NULL, N''NoJournalEntries'', N''No Journal Entries'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8257, @GLAccountKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (601, @GLAccountKey, N''EBITDA Account'', N''ebitdaaccount'', NULL, N''ebitdaaccount'', N''ebitdaaccount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (602, @GLAccountKey, N''Currency ID'', N''currencyID'', NULL, N''CurrencyID'', N''Currency ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- GL Classes
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8258, 54, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8259, 54, N''Class Name'', N''className'', NULL, N''ClassName'', N''Class Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8260, 54, N''Office'', N''officeID'', NULL, N''DepartmentName'', N''Office'', NULL, NULL, N''OfficeName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8261, 54, N''Department'', N''departmentID'', NULL, N''OfficeID'', N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8262, 54, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8263, 54, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--GL Companies
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8264, 33, N''Company Name'', N''glCompanyName'', NULL, N''GLCompanyName'', N''Company Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8265, 33, N''Company ID'', N''glCompanyID'', NULL, N''GLCompanyID'', N''Company ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8266, 33, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8268, 33, N''Printed Name'', N''printedName'', NULL, N''PrintedName'', N''Printed Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8269, 33, N''Phone'', N''phone'', NULL, N''Phone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8270, 33, N''Fax'', N''fax'', NULL, N''Fax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8271, 33, N''EIN Number'', N''eINNumber'', NULL, N''EINNumber'', N''EIN Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8272, 33, N''State EIN Number'', N''stateEINNumber'', NULL, N''StateEINNumber'', N''State EIN Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8273, 33, N''Web Site'', N''webSite'', NULL, N''WebSite'', N''Web Site'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8274, 33, N''Bank GL Account Number'', N''bankAccountNumber'', NULL, N''AccountNumber'', N''Bank GL Account Number'', NULL, NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
--Insertion Order
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8275, @IOKey, N''Order Number'', N''purchaseOrderNumber'', NULL, NULL, N''Order Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8276, @IOKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8277, @IOKey, N''Order Type'', N''purchaseOrderType'', NULL, NULL, N''Order Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8278, @IOKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number. Requierd if Link to Partner is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8279, @IOKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8280, @IOKey, N''Order Date'', N''pODate'', NULL, NULL, N''Order Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition], [SystemSettingFieldName]) VALUES (8281, @IOKey, N''Publication ID'', N''companyMediaID'', NULL, NULL, N''Publication ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL, N''IORequirePublications'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8282, @IOKey, N''Ordered By'', N''orderedBy'', NULL, NULL, N''Ordered By'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8283, @IOKey, N''Standard Header Text'', N''headerTextID'', NULL, NULL, N''Standard Header Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8284, @IOKey, N''Standard Footer Text'', N''footerTextID'', NULL, NULL, N''Standard Footer Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8285, @IOKey, N''Approver'', N''approvedBy'', NULL, NULL, N''Approver'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8286, @IOKey, N''Printing Mode'', N''orderDisplayMode'', NULL, NULL, N''Printing Mode'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8287, @IOKey, N''Print Client On Order'', N''printClientOnOrder'', NULL, NULL, N''Print Client On Order'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8288, @IOKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8289, @IOKey, N''Prebill At'', N''prebillAt'', NULL, NULL, N''Prebill At'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8290, @IOKey, N''Media Estimate ID'', N''mediaEstimateID'', NULL, NULL, N''Media Estimate ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8292, @IOKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8293, @IOKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line). Requierd if Link to Partner is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8294, @IOKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8295, @IOKey, N''Office ID'', N''officeID'', NULL, NULL, N''Office ID. Required if Office is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8296, @IOKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if item is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8298, @IOKey, N''Department'', N''departmentID'', NULL, NULL, N''Department'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8299, @IOKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Requierd if Link to Partner is required and task is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8300, @IOKey, N''Ad Number/Caption'', N''shortDescription'', NULL, NULL, N''Ad#/Caption'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8301, @IOKey, N''Comments'', N''longDescription'', NULL, NULL, N''Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8302, @IOKey, N''Gross'', N''grossAmount'', NULL, NULL, N''Gross'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8303, @IOKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8304, @IOKey, N''Commission Pct'', N''markup'', NULL, NULL, N''Commission Pct'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8305, @IOKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8306, @IOKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8307, @IOKey, N''Space Close'', N''spaceClose'', NULL, NULL, N''Space Close'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8308, @IOKey, N''Materials Due'', N''materialsDue'', NULL, NULL, N''Materials Due'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8309, @IOKey, N''*[MediaPrint3]'', N''userDate3'', NULL, NULL, N''*[MediaPrint3]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8310, @IOKey, N''*[MediaPrint4]'', N''userDate4'', NULL, NULL, N''*[MediaPrint4]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8311, @IOKey, N''*[MediaPrint5]'', N''userDate5'', NULL, NULL, N''*[MediaPrint5]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8312, @IOKey, N''*[MediaPrint6]'', N''userDate6'', NULL, NULL, N''*[MediaPrint6]'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34001, @IOKey, N''Traffic Instructions'', N''trafficInstructions'', NULL, NULL, N''Traffic Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34002, @IOKey, N''Special Instructions'', N''specialInstructions'', NULL, NULL, N''Special Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34003, @IOKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (34004, @IOKey, N''Insertion Date'', N''detailOrderStartDate'', NULL, NULL, N''Insertion Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3406, @IOKey, N''Currency ID'', N''currencyID'', NULL, NULL, N''Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3407, @IOKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3408, @IOKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3409, @IOKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3410, @IOKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3411, @IOKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3412, @IOKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3413, @IOKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3414, @IOKey, N''Header ID'', N''headerID'', NULL, NULL, N''Header ID, used for associating header and detail fields when they do not pass in the PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3415, @IOKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
-- invoices aka client invoices
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8313, @InvoiceKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8314, @InvoiceKey, N''Client ID'', N''clientKey'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8315, @InvoiceKey, N''Contact Name'', N''contactName'', NULL, NULL, N''Contact Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8316, @InvoiceKey, N''Project Number'', N''projectKey'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8317, @InvoiceKey, N''Office'', N''officeKey'', NULL, NULL, N''Office'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8318, @InvoiceKey, N''Advance Bill'', N''advanceBill'', NULL, NULL, N''Advance Bill'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8319, @InvoiceKey, N''Invoice Date'', N''invoiceDate'', NULL, NULL, N''Invoice Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8320, @InvoiceKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8321, @InvoiceKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8322, @InvoiceKey, N''AR Account Number'', N''aRAccountKey'', NULL, NULL, N''AR Account Number. Required if GL account is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8323, @InvoiceKey, N''Terms Description'', N''termsKey'', NULL, NULL, N''Terms Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8324, @InvoiceKey, N''Invoice Comment'', N''headerComment'', NULL, NULL, N''Invoice Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8325, @InvoiceKey, N''Invoice Template'', N''invoiceTemplateKey'', NULL, NULL, N''Invoice Template'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8326, @InvoiceKey, N''User Defined 1'', N''userDefined1'', NULL, NULL, N''User Defined 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8327, @InvoiceKey, N''User Defined 2'', N''userDefined2'', NULL, NULL, N''User Defined 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8328, @InvoiceKey, N''User Defined 3'', N''userDefined3'', NULL, NULL, N''User Defined 3'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8329, @InvoiceKey, N''User Defined 4'', N''userDefined4'', NULL, NULL, N''User Defined 4'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8330, @InvoiceKey, N''User Defined 5'', N''userDefined5'', NULL, NULL, N''User Defined 5'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8331, @InvoiceKey, N''User Defined 6'', N''userDefined6'', NULL, NULL, N''User Defined 6'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8332, @InvoiceKey, N''User Defined 7'', N''userDefined7'', NULL, NULL, N''User Defined 7'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8333, @InvoiceKey, N''User Defined 8'', N''userDefined8'', NULL, NULL, N''User Defined 8'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8334, @InvoiceKey, N''User Defined 9'', N''userDefined9'', NULL, NULL, N''User Defined 9'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8335, @InvoiceKey, N''User Defined 10'', N''userDefined10'', NULL, NULL, N''User Defined 10'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8336, @InvoiceKey, N''Sales Tax ID'', N''salesTaxKey'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8337, @InvoiceKey, N''Sales Tax ID 2'', N''salesTax2Key'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8338, @InvoiceKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8339, @InvoiceKey, N''Approver'', N''approvedByKey'', NULL, NULL, N''Approver'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8340, @InvoiceKey, N''Approval Comment'', N''approvalComment'', NULL, NULL, N''Approval Comment'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8341, @InvoiceKey, N''Approval Date'', N''approvalDate'', NULL, NULL, N''Approval Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8342, @InvoiceKey, N''GL Company'', N''glCompanyKey'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8343, @InvoiceKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8344, @InvoiceKey, N''Campaign ID'', N''campaignKey'', NULL, NULL, N''Campaign ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8345, @InvoiceKey, N''Layout Name'', N''layoutKey'', NULL, NULL, N''Layout Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8346, @InvoiceKey, N''Alternative Payer'', N''alternativePayer'', NULL, NULL, N''Alternative Payer'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8347, @InvoiceKey, N''Billing Group'', N''billingGroup'', NULL, NULL, N''Billing Group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8348, @InvoiceKey, N''Line Subject'', N''lineSubject'', NULL, NULL, N''Line Subject'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8349, @InvoiceKey, N''Line Description'', N''lineDescription'', NULL, NULL, N''Line Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8350, @InvoiceKey, N''Project Number (Line)'', N''projectKey'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8351, @InvoiceKey, N''Task ID'', N''taskKey'', NULL, NULL, N''Task ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8352, @InvoiceKey, N''Office (Line)'', N''officeKey'', NULL, NULL, N''Office (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8353, @InvoiceKey, N''Department'', N''departmentKey'', NULL, NULL, N''Department. Required if department is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8354, @InvoiceKey, N''Sales Account Number'', N''salesAccountKey'', NULL, NULL, N''Sales Account Number. Required if GL Account is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8355, @InvoiceKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8356, @InvoiceKey, N''Unit Amount'', N''unitAmount'', NULL, NULL, N''Unit Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8357, @InvoiceKey, N''Total Amount'', N''totalAmount'', NULL, NULL, N''Total Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110001, @InvoiceKey, N''Total Amount (Home Currency)'', N''hcTotalAmount'', NULL, NULL, N''Total Amount (Home Currency)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110002, @InvoiceKey, N''Class ID (line)'', N''classID'', NULL, NULL, N''Class ID (line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110003, @InvoiceKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)

INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8358, @InvoiceKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8359, @InvoiceKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8360, @InvoiceKey, N''Taxable'', N''taxable'', NULL, NULL, N''Taxable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8361, @InvoiceKey, N''Taxable 2'', N''taxable2'', NULL, NULL, N''Taxable 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8362, @InvoiceKey, N''Segment Name'', N''campaignSegmentKey'', NULL, NULL, N''Segment Name'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8363, @InvoiceKey, N''Retainer Title'', N''retainerKey'', NULL, NULL, N''Retainer Title'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8364, @InvoiceKey, N''Billing Item ID'', N''workTypeKey'', NULL, NULL, N''Billing Item ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8365, @InvoiceKey, N''Item Type'', N''entity'', NULL, NULL, N''Item Type'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8366, @InvoiceKey, N''Item ID'', N''entityKey'', NULL, NULL, N''Item ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8367, @InvoiceKey, N''Display Option'', N''displayOption'', NULL, NULL, N''Display Option'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8368, @InvoiceKey, N''Target GL Company'', N''targetGLCompanyKey'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8369, @InvoiceKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8370, @InvoiceKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (110011, @InvoiceKey, N''GL Company Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11001, @InvoiceKey, N''Posted'', N''posted'', NULL, NULL, N''Posted - this will posted the invoice if true'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Item Rate Sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8371, @ItemRateSheetKey, N''Rate Sheet Name'', N''rateSheetName'', NULL, N''RateSheetName'', N''Rate Sheet Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8372, @ItemRateSheetKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8373, @ItemRateSheetKey, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', N''detail'', 1, N''ItemID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8374, @ItemRateSheetKey, N''Markup'', N''markup'', NULL, N''Markup'', N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8375, @ItemRateSheetKey, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Journal Entries
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8376, @JEKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8377, @JEKey, N''Journal Number'', N''journalNumber'', NULL, NULL, N''Journal Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8378, @JEKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8379, @JEKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8380, @JEKey, N''Auto Reversing Entry'', N''autoReverse'', NULL, NULL, N''Auto Reversing Entry'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8381, @JEKey, N''Exclude From Cash Basis'', N''excludeCashBasis'', NULL, NULL, N''Exclude From Cash Basis'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8382, @JEKey, N''Exclude From Accrual Basis'', N''excludeAccrualBasis'', NULL, NULL, N''Exclude From Accrual Basis'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8383, @JEKey, N''Intercompany DT/DF Source'', N''intercompanyAccountSource'', NULL, NULL, N''Intercompany DT/DF Source'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8384, @JEKey, N''Account Number'', N''accountNumber'', NULL, NULL, N''Account Number'', N''detail'', 1, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8385, @JEKey, N''Client ID'', N''clientKey'', NULL, NULL, N''Client ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8386, @JEKey, N''Project'', N''projectKey'', NULL, NULL, N''Project'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8387, @JEKey, N''Office'', N''officeKey'', NULL, NULL, N''Office. Required if Office is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8388, @JEKey, N''Department'', N''departmentKey'', NULL, NULL, N''Department. Required if Department is required'', N''detail'', 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8389, @JEKey, N''Debit'', N''debitAmount'', NULL, NULL, N''Debit'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8390, @JEKey, N''Credit'', N''creditAmount'', NULL, NULL, N''Credit'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8391, @JEKey, N''Memo'', N''memo'', NULL, NULL, N''Memo'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8392, @JEKey, N''Target GL Company'', N''targetGLCompanyKey'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8393, @JEKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8394, @JEKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8395, @JEKey, N''Exchange Rate (Line)'', N''exchangeRateLine'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8396, @JEKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''detail'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (24001, @JEKey, N''Posted'', N''posted'', NULL, NULL, N''Posted - Yes Or No, to automatically post'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (24002, @JEKey, N''GLC Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')

-- Labor Budgets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8397, 75, N''Budget Name'', N''budgetName'', NULL, NULL, N''Budget Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8398, 75, N''Active'', N''active'', NULL, NULL, N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8399, 75, N''Employee Email'', N''email'', NULL, NULL, N''Employee Email'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8400, 75, N''Comments'', N''editComments'', NULL, NULL, N''Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8401, 75, N''Available Hours 1'', N''availableHours1'', NULL, NULL, N''Available Hours 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8402, 75, N''Target Hours 1'', N''targetHours1'', NULL, NULL, N''Target Hours 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8403, 75, N''Target Dollars 1'', N''targetDollars1'', NULL, NULL, N''Target Dollars 1'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8404, 75, N''Available Hours 2'', N''availableHours2'', NULL, NULL, N''Available Hours 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8405, 75, N''Target Hours 2'', N''targetHours2'', NULL, NULL, N''Target Hours 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8406, 75, N''Target Dollars 2'', N''targetDollars2'', NULL, NULL, N''Target Dollars 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8407, 75, N''Available Hours 3'', N''availableHours3'', NULL, NULL, N''Available Hours 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8408, 75, N''Target Hours 3'', N''targetHours3'', NULL, NULL, N''Target Hours 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8409, 75, N''Target Dollars 3'', N''targetDollars3'', NULL, NULL, N''Target Dollars 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8410, 75, N''Available Hours 4'', N''availableHours4'', NULL, NULL, N''Available Hours 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8411, 75, N''Target Hours 4'', N''targetHours4'', NULL, NULL, N''Target Hours 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8412, 75, N''Target Dollars 4'', N''targetDollars4'', NULL, NULL, N''Target Dollars 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8413, 75, N''Available Hours 5'', N''availableHours5'', NULL, NULL, N''Available Hours 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8414, 75, N''Target Hours 5'', N''targetHours5'', NULL, NULL, N''Target Hours 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8415, 75, N''Target Dollars 5'', N''targetDollars5'', NULL, NULL, N''Target Dollars 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8416, 75, N''Available Hours 6'', N''availableHours6'', NULL, NULL, N''Available Hours 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8417, 75, N''Target Hours 6'', N''targetHours6'', NULL, NULL, N''Target Hours 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8418, 75, N''Target Dollars 6'', N''targetDollars6'', NULL, NULL, N''Target Dollars 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8419, 75, N''Available Hours 7'', N''availableHours7'', NULL, NULL, N''Available Hours 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8420, 75, N''Target Hours 7'', N''targetHours7'', NULL, NULL, N''Target Hours 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8421, 75, N''Target Dollars 7'', N''targetDollars7'', NULL, NULL, N''Target Dollars 7'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8422, 75, N''Available Hours 8'', N''availableHours8'', NULL, NULL, N''Available Hours 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8423, 75, N''Target Hours 8'', N''targetHours8'', NULL, NULL, N''Target Hours 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8424, 75, N''Target Dollars 8'', N''targetDollars8'', NULL, NULL, N''Target Dollars 8'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8425, 75, N''Available Hours 9'', N''availableHours9'', NULL, NULL, N''Available Hours 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8426, 75, N''Target Hours 9'', N''targetHours9'', NULL, NULL, N''Target Hours 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8427, 75, N''Target Dollars 9'', N''targetDollars9'', NULL, NULL, N''Target Dollars 9'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8428, 75, N''Available Hours 10'', N''availableHours10'', NULL, NULL, N''Available Hours 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8429, 75, N''Target Hours 10'', N''targetHours10'', NULL, NULL, N''Target Hours 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8430, 75, N''Target Dollars 10'', N''targetDollars10'', NULL, NULL, N''Target Dollars 10'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8431, 75, N''Available Hours 11'', N''availableHours11'', NULL, NULL, N''Available Hours 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8432, 75, N''Target Hours 11'', N''targetHours11'', NULL, NULL, N''Target Hours 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8433, 75, N''Target Dollars 11'', N''targetDollars11'', NULL, NULL, N''Target Dollars 11'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8434, 75, N''Available Hours 12'', N''availableHours12'', NULL, NULL, N''Available Hours 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8435, 75, N''Target Hours 12'', N''targetHours12'', NULL, NULL, N''Target Hours 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8436, 75, N''Target Dollars 12'', N''targetDollars12'', NULL, NULL, N''Target Dollars 12'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--leads
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8437, @LeadKey, N''First Name'', N''firstName'', NULL, NULL, N''First Name'', NULL, NULL, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8438, @LeadKey, N''Middle Name'', N''middleName'', NULL, NULL, N''Middle Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8439, @LeadKey, N''Last Name'', N''lastName'', NULL, NULL, N''Last Name'', NULL, NULL, NULL, 2, N''Full Name'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8440, @LeadKey, N''Salutation'', N''salutation'', NULL, NULL, N''Salutation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8441, @LeadKey, N''Phone 1'', N''phone1'', NULL, NULL, N''Phone 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8442, @LeadKey, N''Phone 2'', N''phone2'', NULL, NULL, N''Phone 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8443, @LeadKey, N''Cell'', N''cell'', NULL, NULL, N''Cell'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8444, @LeadKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8445, @LeadKey, N''Pager'', N''pager'', NULL, NULL, N''Pager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8446, @LeadKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8447, @LeadKey, N''Email Address'', N''email'', NULL, NULL, N''Email Address'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8448, @LeadKey, N''Company'', N''companyName'', NULL, NULL, N''Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8449, @LeadKey, N''Company Main Phone'', N''companyPhone'', NULL, NULL, N''Company Main Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8450, @LeadKey, N''Company Fax'', N''companyFax'', NULL, NULL, N''Company Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8451, @LeadKey, N''Company Website'', N''companyWebsite'', NULL, NULL, N''Company Website'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8452, @LeadKey, N''Company Source'', N''companySourceKey'', NULL, NULL, N''Company Source'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8453, @LeadKey, N''Company Type'', N''companyTypeKey'', NULL, NULL, N''Company Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8454, @LeadKey, N''Business Address 1'', N''cAddress1'', NULL, NULL, N''Business Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8455, @LeadKey, N''Business Address 2'', N''cAddress2'', NULL, NULL, N''Business Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8456, @LeadKey, N''Business Address 3'', N''cAddress3'', NULL, NULL, N''Business Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8457, @LeadKey, N''Business City'', N''cCity'', NULL, NULL, N''Business City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8458, @LeadKey, N''Business State'', N''cState'', NULL, NULL, N''Business State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8459, @LeadKey, N''Business Postal Code'', N''cPostalCode'', NULL, NULL, N''Business Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8460, @LeadKey, N''Business Country'', N''cCountry'', NULL, NULL, N''Business Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8461, @LeadKey, N''Home Address 1'', N''hAddress1'', NULL, NULL, N''Home Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8462, @LeadKey, N''Home Address 2'', N''hAddress2'', NULL, NULL, N''Home Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8463, @LeadKey, N''Home Address 3'', N''hAddress3'', NULL, NULL, N''Home Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8464, @LeadKey, N''Home City'', N''hCity'', NULL, NULL, N''Home City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8465, @LeadKey, N''Home State'', N''hState'', NULL, NULL, N''Home State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8466, @LeadKey, N''Home Postal Code'', N''hPostalCode'', NULL, NULL, N''Home Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8467, @LeadKey, N''Home Country'', N''hCountry'', NULL, NULL, N''Home Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8468, @LeadKey, N''Other Address 1'', N''oAddress1'', NULL, NULL, N''Other Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8469, @LeadKey, N''Other Address 2'', N''oAddress2'', NULL, NULL, N''Other Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8470, @LeadKey, N''Other Address 3'', N''oAddress3'', NULL, NULL, N''Other Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8471, @LeadKey, N''Other City'', N''oCity'', NULL, NULL, N''Other City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8472, @LeadKey, N''Other State'', N''oState'', NULL, NULL, N''Other State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8473, @LeadKey, N''Other Postal Code'', N''oPostalCode'', NULL, NULL, N''Other Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8474, @LeadKey, N''Other Country'', N''oCountry'', NULL, NULL, N''Other Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8475, @LeadKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8476, @LeadKey, N''Department'', N''department'', NULL, NULL, N''Department'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8477, @LeadKey, N''Assistant'', N''assistant'', NULL, NULL, N''Assistant'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8478, @LeadKey, N''Assistant Phone'', N''assistantPhone'', NULL, NULL, N''Assistant Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8479, @LeadKey, N''Assistant Email'', N''assistantEmail'', NULL, NULL, N''Assistant Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8480, @LeadKey, N''Birthday'', N''birthday'', NULL, NULL, N''Birthday'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8481, @LeadKey, N''Spouse/Partner'', N''spouseName'', NULL, NULL, N''Spouse/Partner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8482, @LeadKey, N''Children'', N''children'', NULL, NULL, N''Children'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8483, @LeadKey, N''Anniversary'', N''anniversary'', NULL, NULL, N''Anniversary'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8484, @LeadKey, N''Hobbies'', N''hobbies'', NULL, NULL, N''Hobbies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8485, @LeadKey, N''Opportunity Subject'', N''opportunitySubject'', NULL, NULL, N''Opportunity Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8486, @LeadKey, N''Opportunity Amount'', N''opportunityAmount'', NULL, NULL, N''Opportunity Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8487, @LeadKey, N''Opportunity Project Type'', N''opportunityProjectTypeKey'', NULL, NULL, N''Opportunity Project Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8488, @LeadKey, N''Opportunity Description'', N''opportunityDescription'', NULL, NULL, N''Opportunity Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8489, @LeadKey, N''Lead Owner'', N''ownerKey'', NULL, NULL, N''Lead Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8490, @LeadKey, N''Folder'', N''cMFolderKey'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8491, @LeadKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8492, @LeadKey, N''Timezone Index'', N''timeZoneIndex'', NULL, NULL, N''Timezone Index'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8493, @LeadKey, N''Marketing Groups'', N''marketingLists'', NULL, NULL, N''Marketing Groups'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8494, @LeadKey, N''Preferred Contact Method'', N''contactMethod'', NULL, NULL, N''Preferred Contact Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8495, @LeadKey, N''Do Not Call'', N''doNotCall'', NULL, NULL, N''Do Not Call'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8496, @LeadKey, N''Do Not Email'', N''doNotEmail'', NULL, NULL, N''Do Not Email'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8497, @LeadKey, N''Do Not Mail'', N''doNotMail'', NULL, NULL, N''Do Not Mail'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8498, @LeadKey, N''Do Not Fax'', N''doNotFax'', NULL, NULL, N''Do Not Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8499, @LeadKey, N''GL Company'', N''glCompanyKey'', NULL, NULL, N''GL Company. Required if GL Company is required.'', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8500, @LeadKey, N''Role'', N''userRole'', NULL, NULL, N''Role'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyroles'''')'')
-- Media Market
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8501, 53, N''Market ID'', N''marketID'', NULL, N''MarketID'', N''Market ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8502, 53, N''Name'', N''marketName'', NULL, N''MarketName'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8503, 53, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Misc Costs
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8504, 23, N''Date'', N''expenseDate'', NULL, NULL, N''Date'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8505, 23, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8506, 23, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if "Require Tasks on Expenses" is set'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8507, 23, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if "Require Items" is set'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8508, 23, N''Department'', N''departmentID'', NULL, NULL, N''Department ID.  Required if "Require Departments" is set'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8509, 23, N''Description'', N''shortDescription'', NULL, NULL, N''Description'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8510, 23, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8511, 23, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8512, 23, N''Unit of Measure'', N''unitDescription'', NULL, NULL, N''Unit of Measure'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8513, 23, N''Net Amount'', N''totalCost'', NULL, NULL, N''Net Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8514, 23, N''Billable'', N''billable'', NULL, NULL, N''Billable'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8515, 23, N''Markup'', N''markup'', NULL, NULL, N''Markup'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8516, 23, N''Unit Billable Rate'', N''unitRate'', NULL, NULL, N''Unit Billable Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8517, 23, N''Gross Amount'', N''billableCost'', NULL, NULL, N''Gross Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8518, 23, N''Comments'', N''longDescription'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8519, 23, N''Billed'', N''billed'', NULL, NULL, N''Billed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8520, 23, N''Date Billed'', N''dateBilled'', NULL, NULL, N''Date Billed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8521, 23, N''Amount Billed'', N''amountBilled'', NULL, NULL, N''Amount Billed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8522, 23, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8523, 23, N''Class ID'', N''classID'', NULL, NULL, N''Class ID.  Required if "Require Class" is set'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8524, 55, N''Office ID'', N''officeID'', NULL, N''OfficeID'', N''Office ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8525, 55, N''Office Name'', N''officeName'', NULL, N''OfficeName'', N''Office Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8526, 55, N''Project Number Prefix'', N''projectNumPrefix'', NULL, N''ProjectNumPrefix'', N''Project Number Prefix'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8527, 55, N''Next Project Number'', N''nextProjectNum'', NULL, N''NextProjectNum'', N''Next Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8528, 55, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Opportunities
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8529, @OpportunitiesKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8530, @OpportunitiesKey, N''Primary Contact'', N''contactName'', NULL, NULL, N''Primary Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8531, @OpportunitiesKey, N''Opportunity Name'', N''subject'', NULL, NULL, N''Opportunity Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8532, @OpportunitiesKey, N''Opportunity Owner'', N''opportunityOwner'', NULL, NULL, N''Opportunity Owner'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8533, @OpportunitiesKey, N''Project Type'', N''projectType'', NULL, NULL, N''Project Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8534, @OpportunitiesKey, N''Folder'', N''cMFolder'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8535, @OpportunitiesKey, N''Competitors'', N''competitors'', NULL, NULL, N''Competitors'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8536, @OpportunitiesKey, N''Description'', N''comments'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8537, @OpportunitiesKey, N''Stage'', N''leadStageName'', NULL, NULL, N''Stage. Requied if Stage is required'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8538, @OpportunitiesKey, N''Status'', N''leadStatusName'', NULL, NULL, N''Status'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8539, @OpportunitiesKey, N''Next Steps'', N''currentStatus'', NULL, NULL, N''Next Steps'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8540, @OpportunitiesKey, N''Probability'', N''probability'', NULL, NULL, N''Probability'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8541, @OpportunitiesKey, N''Revenue'', N''saleAmount'', NULL, NULL, N''Revenue'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8542, @OpportunitiesKey, N''Production'', N''outsideCostsGross'', NULL, NULL, N''Production'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8543, @OpportunitiesKey, N''Production Margin Pct'', N''outsideCostsPercentage'', NULL, NULL, N''Production Margin Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8544, @OpportunitiesKey, N''Media'', N''mediaGross'', NULL, NULL, N''Media'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8545, @OpportunitiesKey, N''Media Margin Pct'', N''mediaPercentage'', NULL, NULL, N''Media Margin Pct'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8546, @OpportunitiesKey, N''Due Date of Estimate'', N''bidDate'', NULL, NULL, N''Due Date of Estimate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8547, @OpportunitiesKey, N''Forecasted Close Date'', N''estCloseDate'', NULL, NULL, N''Forecasted Close Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8548, @OpportunitiesKey, N''Outcome'', N''leadOutcome'', NULL, NULL, N''Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8549, @OpportunitiesKey, N''Actual Close Date'', N''actualCloseDate'', NULL, NULL, N''Actual Close Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8550, @OpportunitiesKey, N''Outcome Description'', N''outcomeComment'', NULL, NULL, N''Outcome Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8551, @OpportunitiesKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8552, @OpportunitiesKey, N''Sub Amount'', N''subAmount'', NULL, NULL, N''Sub Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8553, @OpportunitiesKey, N''Margin'', N''margin'', NULL, NULL, N''Margin'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8554, @OpportunitiesKey, N''Estimate Opportunity'', N''bid'', NULL, NULL, N''Estimate Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8555, @OpportunitiesKey, N''Start Date'', N''startDate'', NULL, NULL, N''Start Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8556, 38, N''WWP Need Supply'', N''wWPNeedSupply'', NULL, NULL, N''WWP Need Supply'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8557, 38, N''WWP Need Supply Comment'', N''wWPNeedSupplyComment'', NULL, NULL, N''WWP Need Supply Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8558, 38, N''WWP Timeline'', N''wWPTimeline'', NULL, NULL, N''WWP Timeline'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8559, 38, N''WWP Timeline Comment'', N''wWPTimelineComment'', NULL, NULL, N''WWP Timeline Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8560, 38, N''WWP Budget'', N''wWPBudget'', NULL, NULL, N''WWP Budget'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8561, 38, N''WWP Budget Comment'', N''wWPBudgetComment'', NULL, NULL, N''WWP Budget Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8562, 38, N''WWP Decision Makers'', N''wWPDecisionMakers'', NULL, NULL, N''WWP Decision Makers'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8563, 38, N''WWP Decision Makers Comment'', N''wWPDecisionMakersComment'', NULL, NULL, N''WWP Decision Makers Comment'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8564, @OpportunitiesKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company. Required if GL company is required'', NULL, 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38001, @OpportunitiesKey, N''Months'', N''months'', NULL, NULL, N''Months'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38002, @OpportunitiesKey, N''Labor'', N''labor'', NULL, NULL, N''Labor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38003, @OpportunitiesKey, N''Opportunity ID'', N''opportunityID'', NULL, NULL, N''Opportunity ID - cannot be set, it auto-increments.  Used for updating records'', NULL, NULL, NULL, 1, N''Opportunity ID'', NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38004, @OpportunitiesKey, N''Division'', N''clientDivision'', NULL, NULL, N''Client Division'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (38005, @OpportunitiesKey, N''Product'', N''clientProduct'', NULL, NULL, N''Client Product'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Opportunity Stages
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8565, 41, N''Stage'', N''leadStageName'', NULL, N''LeadStageName'', N''Stage'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8566, 41, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8567, 41, N''Default Probability'', N''defaultProbability'', NULL, N''DefaultProbability'', N''Default Probability'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9410, 41, N''Display On Dashboard'', N''displayOnDashboard'', NULL, N''DisplayOnDashboard'', N''Display On Dashboard'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9411, 41, N''Use Default Probability'', N''useDefaultProbability'', NULL, N''UseDefaultProbability'', N''Default Probability'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Opportunity Status
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8568, 42, N''Status'', N''leadStatusName'', NULL, N''LeadStatusName'', N''Status'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8569, 42, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8570, 42, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Opportunity Outcome
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8571, 43, N''Outcome'', N''outcome'', NULL, N''Outcome'', N''Outcome'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8572, 43, N''Positive Outcome'', N''positiveOutcome'', NULL, N''PositiveOutcome'', N''Positive Outcome'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Payment Methods
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8573, 50, N''Payment Method'', N''checkMethod'', NULL, N''CheckMethod'', N''Payment Method'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8574, 50, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Payment Terms
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8575, 7, N''Payment Term'', N''termsDescription'', NULL, N''TermsDescription'', N''Payment Term'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8576, 7, N''Days'', N''dueDays'', NULL, N''DueDays'', N''Days'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Print Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8577, 32, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8578, 32, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8579, 32, N''Standard Gross'', N''unitRate'', NULL, N''UnitRate'', N''Standard Gross'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8580, 32, N''Commission'', N''markup'', NULL, N''Markup'', N''Commission'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8581, 32, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8582, 32, N''Billing Item ID'', N''workType'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8583, 32, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8584, 32, N''Expense Account Number'', N''expenseAccount'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8585, 32, N''Sales Account Number'', N''salesAccount'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8586, 32, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8587, 32, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8588, 32, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8589, 32, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID. Required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (32001, 32, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', NULL, NULL, Null, NULL, NULL, NULL, Null)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (32002, 32, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')

-- Project Billing Status
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8590, 29, N''Status ID'', N''projectBillingStatusID'', NULL, N''ProjectBillingStatusID'', N''Status ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8591, 29, N''Name'', N''projectBillingStatus'', NULL, N''ProjectBillingStatus'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8592, 29, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8593, 29, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Projects
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8594, @ProjectKey, N''Copy Tasks from Project Number'', N''copyProjectNumber'', NULL, NULL, N''Copy Tasks from Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8595, @ProjectKey, N''Copy Estimate'', N''copyEstimate'', NULL, NULL, N''Copy Estimate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8597, @ProjectKey, N''Project Name'', N''projectName'', NULL, N''ProjectName'', N''Project Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8598, @ProjectKey, N''Project Number'', N''projectNumber'', NULL, N''ProjectNumber'', N''Project Number'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8599, @ProjectKey, N''Project Type'', N''projectType'', NULL, N''ProjectTypeName'', N''Project Type. May be required based on project number style'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8600, @ProjectKey, N''Project Color'', N''projectColor'', NULL, N''ProjectColor'', N''Project Color'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8601, @ProjectKey, N''Client ID'', N''client'', NULL, N''CustomerID'', N''Client ID. May be required based on project number style'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8602, @ProjectKey, N''Campaign ID'', N''campaignID'', NULL, N''CampaignID'', N''Campaign ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8603, @ProjectKey, N''Segment Name'', N''campaignSegment'', NULL, N'''', N''Segment Name '', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8604, @ProjectKey, N''Account Manager User ID'', N''accountManager'', NULL, N''Account Manager'', N''Account Manager User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8605, @ProjectKey, N''Account Team'', N''team'', NULL, N''TeamName'', N''Account Team'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8606, @ProjectKey, N''Client Project Number'', N''clientProjectNumber'', NULL, N''ClientProjectNumber'', N''Client Project Number'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8607, @ProjectKey, N''Primary Contact Full Name'', N''billingContact'', NULL, N''BillingContact'', N''Primary Contact Full Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8608, @ProjectKey, N''Grant Contact Access Automatically'', N''assignBillingContact'', NULL, N''Billing Manager Name'', N''Grant Contact Access Automatically'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8609, @ProjectKey, N''Opportunity'', N''opportunityID'', NULL, N''Opportunity ID'', N''Opportunity'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8610, @ProjectKey, N''Project Request ID'', N''requestID'', NULL, N''Project Request ID'', N''Project Request ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8611, @ProjectKey, N''GL Company'', N''glCompanyName'', NULL, N''Company ID'', N''GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8612, @ProjectKey, N''Office'', N''office'', NULL, N''Office ID'', N''Office. Required if Office is required'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8613, @ProjectKey, N''Billing Method'', N''billingMethod'', NULL, N''Billing Method'', N''Billing Method'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8614, @ProjectKey, N''Billing Group Code'', N''billingGroupCode'', NULL, N''Billing Group Code'', N''Billing Group Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8615, @ProjectKey, N''Billing Manager'', N''billingManager'', NULL, N''Billing Manager Name'', N''Billing Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8616, @ProjectKey, N''Expenses Not Included'', N''expensesNotIncluded'', NULL,N''ExpensesNotIncluded'', N''Expenses Not Included'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8617, @ProjectKey, N''Retainer'', N''retainerTitle'', NULL, N''Retainer Name'', N''Retainer'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8618, @ProjectKey, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8619, @ProjectKey, N''Status Notes'', N''statusNotes'', NULL, N''StatusNotes'', N''Status Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8620, @ProjectKey, N''Next Steps'', N''detailedNotes'', NULL, N''Next Steps'', N''Next Steps'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8621, @ProjectKey, N''Project Status ID'', N''projectStatus'', NULL, N''Project Status'', N''Project Status ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8622, @ProjectKey, N''Scheduling Direction'', N''scheduleDirection'', NULL, N''ScheduleDirection'', N''Scheduling Direction'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8623, @ProjectKey, N''Start Date'', N''startDate'', NULL, N''StartDate'', N''Start Date. Required if Schedule direction of from project start'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8624, @ProjectKey, N''Due Date'', N''completeDate'', NULL, N''CompleteDate'', N''Due Date. Required if schedule direction is from project completion'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8625, @ProjectKey, N''Flight Start Date'', N''flightStartDate'', NULL, N''FlightStartDate'', N''Flight Start Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8626, @ProjectKey, N''Flight End Date'', N''flightEndDate'', NULL, N''FlightEndDate'', N''Flight End Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8627, @ProjectKey, N''Flight Interval (D/W/S)'', N''flightInterval'', NULL, N''FlightInterval'', N''Flight Interval (D/W/S)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8628, @ProjectKey, N''Billing Status ID'', N''projectBillingStatus'', NULL, N''Project Billing Status'', N''Billing Status ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8629, @ProjectKey, N''Closed'', N''closed'', NULL, N''Closed'', N''Closed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8630, @ProjectKey, N''Non Billable'', N''nonBillable'', NULL, N''NonBillable'', N''Non Billable'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8632, @ProjectKey, N''Division Name'', N''clientDivision'', NULL, N''Client Division ID'', N''Division Name. May be required based on project number style'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8633, @ProjectKey, N''Product Name'', N''clientProduct'', NULL, N''Client Product ID'', N''Product Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8634, @ProjectKey, N''Get Rate From'', N''getRateFrom'', NULL, N''Get Labor Rate From'', N''Get Rate From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8635, @ProjectKey, N''Hourly Rate'', N''hourlyRate'', NULL, N''HourlyRate'', N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8636, @ProjectKey, N''Rate Sheet'', N''rateSheet'', NULL, N''Service Rate Sheet'', N''Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8637, @ProjectKey, N''Auto ID Task'', N''autoIDTask'', NULL, N''AutoIDTask'', N''Auto ID Task'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8638, @ProjectKey, N''Class ID'', N''classKey'', NULL, N''Class ID'', N''Class ID. Required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8639, @ProjectKey, N''*[KEYUSER1] User ID'', N''keyPeople1'', NULL, N''Key Person 1'', N''*[KEYUSER1] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8640, @ProjectKey, N''*[KEYUSER2] User ID'', N''keyPeople2'', NULL, N''Key Person 2'', N''*[KEYUSER2] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8641, @ProjectKey, N''*[KEYUSER3] User ID'', N''keyPeople3'', NULL, N''Key Person 3'', N''*[KEYUSER3] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8642, @ProjectKey, N''*[KEYUSER4] User ID'', N''keyPeople4'', NULL, N''Key Person 4'', N''*[KEYUSER4] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8643, @ProjectKey, N''*[KEYUSER5] User ID'', N''keyPeople5'', NULL, N''Key Person 5'', N''*[KEYUSER5] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8644, @ProjectKey, N''*[KEYUSER6] User ID'', N''keyPeople6'', NULL, N''Key Person 6'', N''*[KEYUSER6] User ID'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacykeypeople'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8645, @ProjectKey, N''Model Year'', N''modelYear'', NULL, N''ModeYear'', N''Model Year'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''spark44'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8646, @ProjectKey, N''Title Rate Sheet'', N''titleRateSheetKey'', NULL, N''Title Rate Sheet'', N''Title Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''billingtitles'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13001, @ProjectKey, N''Project Manager ID'', N''projectManager'', NULL, N''Project Manager'', N''Project Manager User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13002, @ProjectKey, N''Template'', N''template'', NULL, N''Template'', N''Template - yes or no'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13003, @ProjectKey, N''Get Markup From'', N''getMarkupFrom'', NULL, N''GetMarkupFrom'', N''Get Markup From'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13004, @ProjectKey, N''Item Rate Sheet'', N''itemRateSheet'', NULL, N''Item Rate Sheet'', N''Item Rate Sheet'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13005, @ProjectKey, N''Forecast As Fixed Fee'', N''forecastAsFixedFee'', NULL, N''Forecast As Fixed Fee'', N''Forecast As Fixed Fee'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13006, @ProjectKey, N''Split Billing'', N''splitBilling'', NULL, N''splitBilling'', N''Split Billing. format clientID:# example(ACME:60|WMJ:40)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13007, @ProjectKey, N''Avalara Tax Code'', N''avalaraTaxCode'', NULL, N''Avalara Tax Code'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Project Spec Sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8647, 73, N''Spec Sheet ID Prefix'', N''specSheetPrefix'', NULL, NULL, N''Spec Sheet ID Prefix'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8648, 73, N''Project ID'', N''projectID'', NULL, NULL, N''Project ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8649, 73, N''Full Spec ID'', N''fullSpecID'', NULL, NULL, N''Full Spec ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8650, 73, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (73001, 73, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Project Staff Rates
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (127000, @ProjectStaffRatesKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, 1, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (127001, @ProjectStaffRatesKey, N''User Name'', N''userName'', NULL, NULL, N''User Name'', NULL, 1, 1, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (127002, @ProjectStaffRatesKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', NULL, 1, 1, NULL, NULL, NULL, NULL)

-- Project Status
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8651, @ProjectStatusCodeKey, N''Status ID'', N''projectStatusID'', NULL, N''ProjectStatusID'', N''Status ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8652, @ProjectStatusCodeKey, N''Name'', N''projectStatus'', NULL, N''ProjectStatus'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8653, @ProjectStatusCodeKey, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8654, @ProjectStatusCodeKey, N''Project is Active'', N''isActive'', NULL, N''IsActive'', N''Project is Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8655, @ProjectStatusCodeKey, N''Allow Time Entries'', N''timeActive'', NULL, N''TimeActive'', N''Allow Time Entries'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8656, @ProjectStatusCodeKey, N''Allow Expense Entries'', N''expenseActive'', NULL, N''ExpenseActive'', N''Allow Expense Entries'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8657, @ProjectStatusCodeKey, N''Lock Status'', N''locked'', NULL, N''Locked'', N''Lock Status'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8658, @ProjectStatusCodeKey, N''On Hold'', N''onHold'', NULL, N''OnHold'', N''On Hold'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9271, @ProjectStatusCodeKey, N''Include In Forecast'', N''includeInForecast'', NULL, N''IncludeInForecast'', N''Include In Forecast'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (27001, @ProjectStatusCodeKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Project Types
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8659, 25, N''Project Type'', N''projectTypeName'', NULL, N''ProjectTypeName'', N''Project Type'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8660, 25, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8661, 25, N''Project Number Prefix'', N''projectNumPrefix'', NULL, N''ProjectNumPrefix'', N''Project Number Prefix'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8662, 25, N''Next Project Number'', N''nextProjectNum'', NULL, N''NextProjectNum'', N''Next Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8663, 25, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8664, 25, N''Subject1'', N''subject1'', NULL, N''Subject1'', N''Subject1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8665, 25, N''Subject2'', N''subject2'', NULL, N''Subject2'', N''Subject2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8666, 25, N''Subject3'', N''subject3'', NULL, N''Subject3'', N''Subject3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8667, 25, N''Subject4'', N''subject4'', NULL, N''Subject4'', N''Subject4'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8668, 25, N''Subject5'', N''subject5'', NULL, N''Subject5'', N''Subject5'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8669, 25, N''Subject6'', N''subject6'', NULL, N''Subject6'', N''Subject6'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8670, 25, N''Subject7'', N''subject7'', NULL, N''Subject7'', N''Subject7'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8671, 25, N''Subject8'', N''subject8'', NULL, N''Subject8'', N''Subject8'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8672, 25, N''Subject9'', N''subject9'', NULL, N''Subject9'', N''Subject9'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8673, 25, N''Subject10'', N''subject10'', NULL, N''Subject10'', N''Subject10'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8674, 25, N''Subject11'', N''subject11'', NULL, N''Subject11'', N''Subject11'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8675, 25, N''Subject12'', N''subject12'', NULL, N''Subject12'', N''Subject12'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Publication
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12001, @PublicationKey, N''Publication Name'', N''name'', NULL, N''Publication'', N''Publication Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12002, @PublicationKey, N''Publication ID'', N''publicationID'', NULL, N''publicationID'', N''Publication ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12003, @PublicationKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12004, @PublicationKey, N''Media Market'', N''mediaMarket'', NULL, N''Media Market'', N''Media Market'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12005, @PublicationKey, N''Item ID'', N''item'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12006, @PublicationKey, N''ContactName'', N''contact'', NULL, N''Contact'', N''contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12007, @PublicationKey, N''Address 1'', N''address1'', NULL, N''address1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12008, @PublicationKey, N''Address 2'', N''address2'', NULL, N''address2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12009, @PublicationKey, N''Address 3'', N''address3'', NULL, N''address3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12010, @PublicationKey, N''City'', N''city'', NULL, N''city'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12011, @PublicationKey, N''State'', N''state'', NULL, N''State'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12012, @PublicationKey, N''Postal Code'', N''postalCode'', NULL, N''PostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12013, @PublicationKey, N''Country'', N''country'', NULL, N''Country'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12014, @PublicationKey, N''Phone'', N''phone'', NULL, N''Phone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12015, @PublicationKey, N''Fax'', N''fax'', NULL, N''Fax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12016, @PublicationKey, N''Material Address 1'', N''mAddress1'', NULL, N''mAddress1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12017, @PublicationKey, N''Material Address 2'', N''mAddress2'', NULL, N''mAddress2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12018, @PublicationKey, N''Material Address 3'', N''mAddress3'', NULL, N''mAddress3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12019, @PublicationKey, N''Material City'', N''mCity'', NULL, N''mCity'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12020, @PublicationKey, N''Material State'', N''mState'', NULL, N''mState'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12021, @PublicationKey, N''Material Postal Code'', N''mPostalCode'', NULL, N''mPostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12022, @PublicationKey, N''Material Country'', N''mCountry'', NULL, N''mCountry'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12023, @PublicationKey, N''Material Phone'', N''mPhone'', NULL, N''mPhone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12024, @PublicationKey, N''Material Fax'', N''mFax'', NULL, N''mFax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12025, @PublicationKey, N''Space Close Number'', N''spaceCloseNumDays'', NULL, N''spaceCloseNumDays'', N''Space Close Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12026, @PublicationKey, N''Material Due Number'', N''materailsDueNumDays'', NULL, N''materailsDueNumDays'', N''Material Due Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Purchase Items
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8676, 5, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8677, 5, N''Item Name'', N''itemName'', NULL, N''ItemName'', N''Item Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8678, 5, N''Unit Cost'', N''unitCost'', NULL, N''UnitCost'', N''Unit Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8679, 5, N''Markup'', N''markup'', NULL, N''Markup'', N''Markup'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8680, 5, N''Unit Rate'', N''unitRate'', NULL, N''UnitRate'', N''Unit Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8681, 5, N''Always use Unit Rate for Gross Amount'', N''useUnitRate'', NULL, N''UseUnitRate'', N''Always use Unit Rate for Gross Amount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8682, 5, N''Unit Description'', N''unitDescription'', NULL, N''UnitDescription'', N''Unit Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8683, 5, N''Standard Description'', N''standardDescription'', NULL, N''StandardDescription'', N''Standard Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8684, 5, N''Billing Item ID'', N''billingItemID'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''BillingItemID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8685, 5, N''Department'', N''departmentName'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8686, 5, N''Expense Account Number'', N''expenseAccountNumber'', NULL, N''ExpenseAccountNumber'', N''Expense Account Number'', NULL, NULL, N''ExpenseAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8687, 5, N''Sales Account Number'', N''salesAccountNumber'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8688, 5, N''Quantity On Hand'', N''quantityOnHand'', NULL, N''QuantityOnHand'', N''Quantity On Hand'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8689, 5, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8690, 5, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8691, 5, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8692, 5, N''Class ID'', N''classID'', NULL, N''ClassID'', N''Class ID. Required if Class is required'', NULL, 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (869200, 5, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')
--Purchase Order
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8693, @POKey, N''PO Number'', N''purchaseOrderNumber'', NULL, NULL, N''PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8694, @POKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8695, @POKey, N''PO Type'', N''purchaseOrderType'', NULL, NULL, N''PO Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8696, @POKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8697, @POKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8698, @POKey, N''PO Date'', N''pODate'', NULL, NULL, N''PO Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8699, @POKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8700, @POKey, N''Ordered By'', N''orderedBy'', NULL, NULL, N''Ordered By'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8701, @POKey, N''Standard Header Text'', N''headerTextID'', NULL, NULL, N''Standard Header Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8702, @POKey, N''Standard Footer Text'', N''footerTextID'', NULL, NULL, N''Standard Footer Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8703, @POKey, N''Approver'', N''approvedBy'', NULL, NULL, N''Approver'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8704, @POKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8705, @POKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8706, @POKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8707, @POKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8708, @POKey, N''Order Description'', N''description'', NULL, NULL, N''Order Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8709, @POKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8711, @POKey, N''Office'', N''officeKey'', NULL, NULL, N''Office'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8712, @POKey, N''Department'', N''departmentID'', NULL, NULL, N''Department'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8713, @POKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8714, @POKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8715, @POKey, N''Description'', N''shortDescription'', NULL, NULL, N''Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8716, @POKey, N''Long Description'', N''longDescription'', NULL, NULL, N''Long Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8719, @POKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8720, @POKey, N''Unit Desc'', N''unitDescription'', NULL, NULL, N''Unit Desc'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8721, @POKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8722, @POKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8723, @POKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8724, @POKey, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8725, @POKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8726, @POKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8727, @POKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8728, @POKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8729, @POKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8730, @POKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8731, @POKey, N''Class ID (Line)'', N''classID'', NULL, NULL, N''Class ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18001, @POKey, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18002, @POKey, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18003, @POKey, N''Traffic Instructions'', N''trafficInstructions'', NULL, NULL, N''Traffic Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18004, @POKey, N''Special Instructions'', N''specialInstructions'', NULL, NULL, N''Special Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18005, @POKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID, used for selecting appropriate field group'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18006, @POKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID, used for selecting appropriate field group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (18007, @POKey, N''Header ID'', N''headerID'', NULL, NULL, N''Header ID, used for associating header and detail fields when they do not pass in the PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
-- Receipts
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11501, @ReceiptsKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', N''header'', 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11502, @ReceiptsKey, N''GL Company'', N''glCompany'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11503, @ReceiptsKey, N''Check Amount'', N''checkAmount'', NULL, NULL, N''Check Amount'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11504, @ReceiptsKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11505, @ReceiptsKey, N''Reference Number'', N''referenceNumber'', NULL, NULL, N''Reference Number'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11506, @ReceiptsKey, N''Payment Method'', N''paymentMethod'', NULL, NULL, N''Payment Method'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11507, @ReceiptsKey, N''Receipt Date'', N''checkDate'', NULL, NULL, N''Receipt Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11508, @ReceiptsKey, N''Deposit ID'', N''depositID'', NULL, NULL, N''Deposit ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11509, @ReceiptsKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11510, @ReceiptsKey, N''Cash Account Number'', N''cashAccountNumber'', NULL, NULL, N''Cash Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11511, @ReceiptsKey, N''Unapplied Payment Account Number'', N''prepayAccountNumber'', NULL, NULL, N''Unapplied Payment Account Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11512, @ReceiptsKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11513, @ReceiptsKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11514, @ReceiptsKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11515, @ReceiptsKey, N''GL Account'', N''glAccount'', NULL, NULL, N''GL Account'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11516, @ReceiptsKey, N''Description (Line)'', N''description'', NULL, NULL, N''Description (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11517, @ReceiptsKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11518, @ReceiptsKey, N''Department'', N''department'', NULL, NULL, N''Department. Required if Department is required.'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11519, @ReceiptsKey, N''Amount Applied'', N''amount'', NULL, NULL, N''Amount Applied'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11520, @ReceiptsKey, N''Office'', N''office'', NULL, NULL, N''Office. Required if Office ie required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11521, @ReceiptsKey, N''Target GL Company'', N''targetGLCompany'', NULL, NULL, N''Target GL Company. Required if GL Company is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11522, @ReceiptsKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11523, @ReceiptsKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11524, @ReceiptsKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11525, @ReceiptsKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11526, @ReceiptsKey, N''Receipt Key'', N''receiptKey'', NULL, NULL, N''Receipt Key'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11527, @ReceiptsKey, N''Action'', N''action'', NULL, NULL, N''Action - d for deleting a row'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- Report Groups
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8732, 40, N''Group Name'', N''groupName'', NULL, N''GroupName'', N''Group Name'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8733, 40, N''Display Order'', N''displayOrder'', NULL, N''DisplayOrder'', N''Display Order'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Request Reject Reasons
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8734, 67, N''Request Reject Reason'', N''reasonName'', NULL, N''ReasonName'', N''Request Reject Reason'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8735, 67, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8736, 67, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Project Requests
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8737, @ProjectRequestKey, N''Request Prefix'', N''requestPrefix'', NULL, NULL, N''Spec Sheet ID Prefix'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8738, @ProjectRequestKey, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8740, @ProjectRequestKey, N''Notify Email'', N''notifyEmail'', NULL, NULL, N''Notify Email'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8741, @ProjectRequestKey, N''Project Due Date'', N''dueDate'', NULL, NULL, N''Project Due Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (1, @ProjectRequestKey, N''Client Project Number'', N''clientProjectNumber'', NULL, NULL, N''Client Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (2, @ProjectRequestKey, N''Campaign ID'', N''campaignID'', NULL, NULL, N''Campaign ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (3, @ProjectRequestKey, N''Project Name'', N''subject'', NULL, NULL, N''Project Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (4, @ProjectRequestKey, N''Project Description'', N''projectDescription'', NULL, NULL, N''Project Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (5, @ProjectRequestKey, N''Requested By'', N''requestedBy'', NULL, NULL, N''Requested By'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (6, @ProjectRequestKey, N''Request ID'', N''requestID'', NULL, NULL, N''Request ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (76007, @ProjectRequestKey, N''Skip Approval Process'', N''skipApprovalProcess'', NULL, NULL, N''Skip Approval Process (True or False) - If true, then will not send out new emails'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
-- Request Spec Sheets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8742, 74, N''Spec Sheet ID Prefix'', N''specSheetPrefix'', NULL, NULL, N''Spec Sheet ID Prefix'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8743, 74, N''Request ID'', N''requestID'', NULL, NULL, N''Request ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8744, 74, N''Client ID'', N''clientID'', NULL, NULL, N''Client ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8745, 74, N''Full Spec ID'', N''fullSpecID'', NULL, NULL, N''Full Spec ID'', NULL, NULL, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8746, 74, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (10, 74, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Retainer
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11801, @RetainerKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11802, @RetainerKey, N''Amount Per Period'', N''amountPerPeriod'',NULL, NULL, N''Amount Per Period'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11803, @RetainerKey, N''Billing Manager'', N''billingManager'',NULL, NULL, N''Billing Manager'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11804, @RetainerKey, N''Class'', N''classKey'',NULL, NULL, N''Class'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11805, @RetainerKey, N''Client ID'', N''client'', NULL, NULL, N''Client ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11806, @RetainerKey, N''Contact'', N''contact'',NULL, NULL, N''Contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11807, @RetainerKey, N''Cost Per Period'', N''costPerPeriod'',NULL, NULL, N''Cost Per Period'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11808, @RetainerKey, N''Currency ID'', N''currencyID'',NULL, NULL, N''Currency ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11809, @RetainerKey, N''Description'', N''description'',NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11810, @RetainerKey, N''Frequency'', N''frequency'',NULL, NULL, N''Frequency (monthly, quarterly, yearly, weekly) '', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11811, @RetainerKey, N''Include Labor'', N''includeLabor'',NULL, NULL, N''Include Labor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11812, @RetainerKey, N''Include Expense'', N''includeExpense'',NULL, NULL, N''Include Expense'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11813, @RetainerKey, N''Invoice Approved By'', N''invoiceApprovedBy'',NULL, NULL, N''Invoice Approved By'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11814, @RetainerKey, N''Invoice Expenses Separate'', N''invoiceExpensesSeparate'',NULL, NULL, N''Invoice Expenses Separate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11815, @RetainerKey, N''Invoice Template'', N''invoiceTemplate'',NULL, NULL, N''Invoice Template'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11817, @RetainerKey, N''Last Billing Date'', N''lastBillingDate'',NULL, NULL, N''Last Billing Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11818, @RetainerKey, N''Layout'', N''layout'',NULL, NULL, N''Layout'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11819, @RetainerKey, N''Line Format'', N''lineFormat'',NULL, NULL, N''Line Format'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11820, @RetainerKey, N''Number Of Periods'', N''numberOfPeriods'',NULL, NULL, N''Number Of Periods'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11821, @RetainerKey, N''Office'', N''office'',NULL, NULL, N''Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11822, @RetainerKey, N''Sales Account'', N''salesAccount'',NULL, NULL, N''Sales Account'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11823, @RetainerKey, N''Start Date'', N''startDate'', NULL, NULL, N''Start Date'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11824, @RetainerKey, N''Title'', N''title'', NULL, NULL, N''Title'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (11825, @RetainerKey, N''GL Company'', N''glCompany'',NULL, NULL, N''GL Company'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Sales Tax
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8747, 8, N''Sales Tax ID'', N''salesTaxID'', NULL, N''SalesTaxID'', N''Sales Tax ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8748, 8, N''Sales Tax Name'', N''salesTaxName'', NULL, N''SalesTaxName'', N''Sales Tax Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8749, 8, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8750, 8, N''Pay To Vendor ID'', N''payTo'', NULL, N''VendorID'', N''Pay To Vendor ID'', NULL, NULL, N''PayToID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8751, 8, N''Tax Payable GL Account Number'', N''payableGLAccountKey'', NULL, N''PayableAccountNumber'', N''Tax Payable GL Account Number'', NULL, NULL, N''PayableGLAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8752, 8, N''Tax AP GL Account Number'', N''aPPayableGLAccountKey'', NULL, N''APAccountNumber'', N''Tax AP GL Account Number'', NULL, NULL, N''APPayableGLAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8753, 8, N''Tax Rate Percentage'', N''taxRate'', NULL, N''TaxRate'', N''Tax Rate Percentage'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8754, 8, N''Piggy Back Tax'', N''piggyBackTax'', NULL, N''PiggyBackTax'', N''Piggy Back Tax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8755, 8, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Service Rate Sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8756, @ServiceRateSheetKey, N''Rate Sheet Name'', N''rateSheetName'', NULL, N''RateSheetName'', N''Rate Sheet Name'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8757, @ServiceRateSheetKey, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8758, @ServiceRateSheetKey, N''Service Code'', N''serviceCode'', NULL, N''ServiceCode'', N''Service Code'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8759, @ServiceRateSheetKey, N''Rate 1'', N''rate1'', NULL, N''HourlyRate1'', N''Rate 1'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8760, @ServiceRateSheetKey, N''Rate 2'', N''rate2'', NULL, N''HourlyRate2'', N''Rate 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8761, @ServiceRateSheetKey, N''Rate 3'', N''rate3'', NULL, N''HourlyRate3'', N''Rate 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8762, @ServiceRateSheetKey, N''Rate 4'', N''rate4'', NULL, N''HourlyRate4'', N''Rate 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8763, @ServiceRateSheetKey, N''Rate 5'', N''rate5'', NULL, N''HourlyRate5'', N''Rate 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (58004, @ServiceRateSheetKey, N''Description'', N''description'', NULL, N''Description'', N''Service Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (58005, @ServiceRateSheetKey, N''Invoice Label'', N''invoiceLabel'', NULL, N''InvoiceLabel'', N''Invoice Label'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (58003, @ServiceRateSheetKey, N''Hourly Cost'', N''hourlyCost'', NULL, N''HourlyCost'', N''Hourly Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Services
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8764, 9, N''Service Code'', N''serviceCode'', NULL, N''ServiceCode'', N''Service Code'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8765, 9, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8766, 9, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8767, 9, N''Billing Item ID'', N''workTypeKey'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8768, 9, N''Department'', N''departmentKey'', NULL, N''DepartmentName'', N''Department'', NULL, NULL, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8769, 9, N''Sales Account Number'', N''glAccountKey'', NULL, N''SalesAccountNumber'', N''Sales Account Number'', NULL, NULL, N''SalesAccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8770, 9, N''Hourly Cost'', N''hourlyCost'', NULL, N''HourlyCost'', N''Hourly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8771, 9, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8772, 9, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8773, 9, N''Hourly Rate 1'', N''hourlyRate1'', NULL, N''HourlyRate1'', N''Hourly Rate 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8774, 9, N''Rate Description 1'', N''description1'', NULL, N''Description1'', N''Rate Description 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8775, 9, N''Hourly Rate 2'', N''hourlyRate2'', NULL, N''HourlyRate2'', N''Hourly Rate 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8776, 9, N''Rate Description 2'', N''description2'', NULL, N''Description2'', N''Rate Description 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8777, 9, N''Hourly Rate 3'', N''hourlyRate3'', NULL, N''HourlyRate3'', N''Hourly Rate 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8778, 9, N''Rate Description 3'', N''description3'', NULL, N''Description3'', N''Rate Description 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8779, 9, N''Hourly Rate 4'', N''hourlyRate4'', NULL, N''HourlyRate4'', N''Hourly Rate 4'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8780, 9, N''Rate Description 4'', N''description4'', NULL, N''Description4'', N''Rate Description 4'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8781, 9, N''Hourly Rate 5'', N''hourlyRate5'', NULL, N''HourlyRate5'', N''Hourly Rate 5'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8782, 9, N''Rate Description 5'', N''description5'', NULL, N''Description5'', N''Rate Description 5'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8783, 9, N''Class ID'', N''classKey'', NULL, N''ClassID'', N''Class ID'', NULL, NULL, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (87840, 9, N''Avalara Tax Code'', N''avalaraTaxCodeKey'', NULL, N''AvalaraTaxCode'', N''Avalara Tax Code'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''avalara'''')'')
-- Standard Text
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8784, 52, N''Type'', N''type'', NULL, N''Type'', N''Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8785, 52, N''Text Block Name'', N''textName'', NULL, N''TextName'', N''Text Block Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8786, 52, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8787, 52, N''Standard Text'', N''standardText'', NULL, N''StandardText'', N''Standard Text'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
-- Station
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12201, @StationKey, N''Station Name'', N''name'', NULL, N''StationName'', N''Station Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12202, @StationKey, N''Station ID'', N''stationID'', NULL, N''StationID'', N''Station ID'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12203, @StationKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12204, @StationKey, N''Media Market'', N''mediaMarket'', NULL, N''Media Market'', N''Media Market'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12205, @StationKey, N''Item ID'', N''item'', NULL, N''ItemID'', N''Item ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12206, @StationKey, N''ContactName'', N''contact'', NULL, N''Contact'', N''contact'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12207, @StationKey, N''Address 1'', N''address1'', NULL, N''address1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12208, @StationKey, N''Address 2'', N''address2'', NULL, N''address2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12209, @StationKey, N''Address 3'', N''address3'', NULL, N''address3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12210, @StationKey, N''City'', N''city'', NULL, N''city'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12211, @StationKey, N''State'', N''state'', NULL, N''State'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12212, @StationKey, N''Postal Code'', N''postalCode'', NULL, N''PostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12213, @StationKey, N''Country'', N''country'', NULL, N''Country'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12214, @StationKey, N''Phone'', N''phone'', NULL, N''Phone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12215, @StationKey, N''Fax'', N''fax'', NULL, N''Fax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12216, @StationKey, N''Material Address 1'', N''mAddress1'', NULL, N''mAddress1'', N''address1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12217, @StationKey, N''Material Address 2'', N''mAddress2'', NULL, N''mAddress2'', N''address2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12218, @StationKey, N''Material Address 3'', N''mAddress3'', NULL, N''mAddress3'', N''address3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12219, @StationKey, N''Material City'', N''mCity'', NULL, N''mCity'', N''city'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12220, @StationKey, N''Material State'', N''mState'', NULL, N''mState'', N''state'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12221, @StationKey, N''Material Postal Code'', N''mPostalCode'', NULL, N''mPostalCode'', N''postalCode'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12222, @StationKey, N''Material Country'', N''mCountry'', NULL, N''mCountry'', N''country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12223, @StationKey, N''Material Phone'', N''mPhone'', NULL, N''mPhone'', N''Phone'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12224, @StationKey, N''Material Fax'', N''mFax'', NULL, N''mFax'', N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12225, @StationKey, N''Space Close Number'', N''spaceCloseNumDays'', NULL, N''spaceCloseNumDays'', N''Space Close Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (12226, @StationKey, N''Material Due Number'', N''materailsDueNumDays'', NULL, N''materailsDueNumDays'', N''Material Due Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Sources
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8788, 48, N''Role'', N''sourceName'', NULL, N''SourceName'', N''Role'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8789, 48, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Tasks
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8792, @TaskKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', 1, NULL, 1, NULL, 2, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8794, @TaskKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', N''header'', NULL, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8795, @TaskKey, N''Task Name'', N''taskName'', NULL, NULL, N''Task Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8796, @TaskKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8798, @TaskKey, N''Summary Task ID'', N''summaryTaskID'', NULL, NULL, N''Summary Task ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8799, @TaskKey, N''Hourly Rate'', N''hourlyRate'', NULL, NULL, N''Hourly Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8800, @TaskKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8801, @TaskKey, N''IO Commission'', N''ioCommission'', NULL, NULL, N''IO Commission'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8802, @TaskKey, N''BC Commission'', N''bcCommission'', NULL, NULL, N''BC Commission'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8803, @TaskKey, N''Show Desc On Est'', N''showDescOnEst'', NULL, NULL, N''Show Desc On Est'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8805, @TaskKey, N''Taxable'', N''taxable'', NULL, NULL, N''Taxable'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8806, @TaskKey, N''Taxable2'', N''taxable2'', NULL, NULL, N''Taxable2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8807, @TaskKey, N''Billing Item ID'', N''workTypeID'', NULL, NULL, N''Billing Item ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8808, @TaskKey, N''Base Start'', N''baseStart'', NULL, NULL, N''Base Start'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8809, @TaskKey, N''Base Complete'', N''baseComplete'', NULL, NULL, N''Base Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8810, @TaskKey, N''Plan Start'', N''planStart'', NULL, NULL, N''Plan Start'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8811, @TaskKey, N''Plan Complete'', N''planComplete'', NULL, NULL, N''Plan Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8812, @TaskKey, N''Plan Duration'', N''planDuration'', NULL, NULL, N''Plan Duration'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8813, @TaskKey, N''Act Start'', N''actStart'', NULL, NULL, N''Act Start'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8814, @TaskKey, N''Act Complete'', N''actComplete'', NULL, NULL, N''Act Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8815, @TaskKey, N''Perc Comp'', N''percComp'', NULL, NULL, N''Perc Comp'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8816, @TaskKey, N''Task Constraint'', N''taskConstraint'', NULL, NULL, N''Task Constraint.  Possible values are:<br> As Soon As Possible<br> As Late As Possible<br> Must Start On<br> Must Finish On<br> Finish No Earlier Than<br> Finish No Later Than<br> Start No Earlier Than<br> Start No Later Than'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8817, @TaskKey, N''Status Comments'', N''comments'', NULL, NULL, N''Status Comments'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8818, @TaskKey, N''Schedule Task'', N''scheduleTask'', NULL, NULL, N''Schedule Task'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8819, @TaskKey, N''Track Budget'', N''trackBudget'', NULL, NULL, N''Track Budget'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8821, @TaskKey, N''Hide From Client'', N''hideFromClient'', NULL, NULL, N''Hide From Client'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8822, @TaskKey, N''Allow Anyone'', N''allowAnyone'', NULL, NULL, N''Allow Anyone'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8823, @TaskKey, N''Constraint Date'', N''constraintDate'', NULL, NULL, N''Constraint Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8824, @TaskKey, N''Work Any Day'', N''workAnyDay'', NULL, NULL, N''Work Any Day'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8825, @TaskKey, N''Perc Comp Separate'', N''percCompSeparate'', NULL, NULL, N''Track Actual Dates for Each Person'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8829, @TaskKey, N''Priority'', N''priority'', NULL, NULL, N''Priority. Use Priority Name value from Task Priority Setup.<br> Or use these values:<br>H<br>M<br>L'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8831, 69, N''Event Start Date and Time'', N''eventStart'', NULL, NULL, N''Event Start Date and Time'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8832, 69, N''Event End Date and Time'', N''eventEnd'', NULL, NULL, N''Event End Date and Time'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8834, @TaskKey, N''Due By Comments'', N''dueBy'', NULL, NULL, N''Due By Comments'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8835, @TaskKey, N''Reviewed By Traffic'', N''reviewedByTraffic'', NULL, NULL, N''Reviewed By Traffic'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8836, @TaskKey, N''Predecessors Complete'', N''predecessorsComplete'', NULL, NULL, N''Predecessors Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8838, @TaskKey, N''Schedule Notes'', N''scheduleNote'', NULL, NULL, N''Schedule Notes'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8839, @TaskKey, N''Constraint Day Of The Week'', N''constraintDayOfTheWeek'', NULL, NULL, N''Constraint Day Of The Week'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8840, @TaskKey, N''Exclude From Status'', N''excludeFromStatus'', NULL, NULL, N''Exclude From Status'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8841, @TaskKey, N''Allow Allocated Hours'', N''allowAllocatedHours'', NULL, NULL, N''Allow Allocated Hours'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (690, @TaskKey, N''Timeline Segment'', N''timelineSegment'', NULL, NULL, N''Timeline Segment'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (691, @TaskKey, N''Project Status When Task Complete'', N''taskCompleteProjectStatus'', NULL, NULL, N''Project Status When Task Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (692, 69, N''Assignment Comments'', N''aDescription'', NULL, NULL, N''Assignment Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8842, @TaskKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8843, @TaskKey, N''Detail Service Code'', N''detailServiceCode'', NULL, NULL, N''Detail Service Code'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8844, @TaskKey, N''Hours Allocated'', N''detailHours'', NULL, NULL, N''Hours Allocated'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69003, @TaskKey, N''Weekly Hours'', N''weeklyHours'', NULL, NULL, N''Weekly Bucket Hours (separate each weekly value with a | symbol). For example "2.2|3|4.55". If specified, Hours Allocated is calculated for this assignment, and the assignment will be makred as Manually Adjusted.'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8845, @TaskKey, N''Detail Perc Comp'', N''detailPercComp'', NULL, NULL, N''Detail Perc Comp'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8846, @TaskKey, N''Detail Act Start'', N''detailActStart'', NULL, NULL, N''Detail Act Start'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8847, @TaskKey, N''Detail Act Complete'', N''detailActComplete'', NULL, NULL, N''Detail Act Complete'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8848, 69, N''Detail Reviewed By Traffic'', N''detailReviewedByTraffic'', NULL, NULL, N''Detail Reviewed By Traffic'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8849, @TaskKey, N''Manual Adjustment'', N''manualAdjustment'', NULL, NULL, N''Manual Adjustment'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8850, @TaskKey, N''APlanStart'', N''aPlanStart'', NULL, NULL, N''APlanStart'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8852, @TaskKey, N''APlan Complete'', N''aPlanComplete'', NULL, NULL, N''APlan Complete'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8853, @TaskKey, N''Action'', N''action'', NULL, NULL, N''Action'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69001, @TaskKey, N''Predecessors'', N''predecessors'', NULL, NULL, N''Predecessors (lag), task ID comma seperated.  If want to add a lag please put it in () after the predecessor.  For example "2.1 (1)"'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69002, @TaskKey, N''Must Finish On Pred Complete'', N''mustFinishOnPredComplete'', NULL, NULL, N''Set to Must Finish On when Predecessor is Complete'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (69004, @TaskKey, N''Send Notifications'', N''sendNotifications'', NULL, NULL, N''Send Notifications to the user assigned to the task'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
-- Teams
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8854, 56, N''Team Name'', N''teamName'', NULL, N''TeamName'', N''Team Name'', NULL, 1, NULL, 1, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8855, 56, N''User ID'', N''userID'', NULL, N''UserID'', N''User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (56001, 56, N''User Name'', NULL, NULL, N''UserName'', N''User Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

-- Time
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8856, @TimeKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8857, @TimeKey, N''Actual Hours'', N''hours'', NULL, NULL, N''Actual Hours'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8858, @TimeKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8859, @TimeKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8860, @TimeKey, N''Service Code'', N''serviceCode'', NULL, NULL, N''Service Code. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8861, @TimeKey, N''Date'', N''workDate'', NULL, NULL, N''Date'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8862, @TimeKey, N''Comments'', N''comments'', NULL, NULL, N''Comments. May be required based on preferences'', NULL, 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (72100, @TimeKey, N''Overtime'', N''overtime'', NULL, NULL, N''Overtime'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)


 -- Time sheet
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8863, @TimeSheetKey, N''Date'', N''workDate'', NULL, NULL, N''Date'', N''detail'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8864, @TimeSheetKey, N''Start Date & Time'', N''startDate'', NULL, NULL, N''Start Date & Time. May be required based on preferences'', N''header'', 2, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8865, @TimeSheetKey, N''End Date & Time'', N''endDate'', NULL, NULL, N''End Date & Time. May be required based on preferences'', N''header'', 2, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8866, @TimeSheetKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8867, @TimeSheetKey, N''Task ID'', N''taskId'', NULL, NULL, N''Task ID. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8868, @TimeSheetKey, N''Service Code'', N''serviceCode'', NULL, NULL, N''Service Code. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8869, @TimeSheetKey, N''Actual Hours'', N''hours'', NULL, NULL, N''Actual Hours'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8870, @TimeSheetKey, N''Actual Rate'', N''actualRate'', NULL, NULL, N''Actual Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8871, @TimeSheetKey, N''Comments'', N''comments'', NULL, NULL, N''Comments. May be required based on preferences'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8872, @TimeSheetKey, N''Rate Level'', N''rateLevel'', NULL, NULL, N''Rate Level'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8873, @TimeSheetKey, N''Date Billed'', N''dateBilled'', NULL, NULL, N''Date Billed'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8874, @TimeSheetKey, N''Department'', N''departmentKey'', NULL, NULL, N''Department'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8875, @TimeSheetKey, N''Billing Title ID'', N''titleKey'', NULL, NULL, N''Billing Title ID'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8876, @TimeSheetKey, N''User ID'', N''userID'', NULL, NULL, N''User ID'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8877, @TimeSheetKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (21001, 21, N''Start Date'', N''startdate'', NULL, NULL, N''These are api only fields... Not used on import'', N''header'', 2, NULL, NULL, NULL, 1, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (21002, 21, N''End Date'', N''enddate'', NULL, NULL, N''These are api only fields... Not used on import'', N''header'', 2, NULL, NULL, NULL, 1, NULL)

-- Time sheet / Complete
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13201, @TimeSheetCompleteKey, N''TimeSheetKey'', N''timesheetKey'', NULL, NULL, N''timesheeetKey'', NULL, 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13202, @TimeSheetCompleteKey, N''Comments'', N''comments'', NULL, NULL, N''Approval Comments'', NULL, NULL, NULL, NULL, NULL, 1, NULL)

-- Time sheet / Reject
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13301, @TimeSheetRejectKey, N''TimeSheetKey'', N''timesheetKey'', NULL, NULL, N''timesheeetKey'', NULL, 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (13302, @TimeSheetRejectKey, N''Comments'', N''comments'', NULL, NULL, N''Rejection Comments'', NULL, NULL, NULL, NULL, NULL, 1, NULL)


-- Titles
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8878, 64, N''ID'', N''titleID'', NULL, N''TitleID'', N''ID'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8879, 64, N''Name'', N''titleName'', NULL, N''TitleName'', N''Name'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8880, 64, N''Hourly Rate'', N''hourlyRate'', NULL, N''HourlyRate'', N''Hourly Rate'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8881, 64, N''Hourly Cost'', N''hourlyCost'', NULL, N''HourlyCost'', N''Hourly Cost'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8882, 64, N''Department'', N''departmentName'', NULL, N''DepartmentName'', N''Department. Required if Department is required'', NULL, 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8883, 64, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8884, 64, N''Billing Item ID'', N''workTypeID'', NULL, N''WorkTypeID'', N''Billing Item ID'', NULL, NULL, N''WorkTypeID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8885, 64, N''Tax 1 Applies'', N''taxable'', NULL, N''Taxable'', N''Tax 1 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8886, 64, N''Tax 2 Applies'', N''taxable2'', NULL, N''Taxable2'', N''Tax 2 Applies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8887, 64, N''Service Code'', N''serviceKey'', NULL, N''ServiceCode'', N''Service Code'', NULL, NULL, N''ServiceCode'', NULL, NULL, NULL, NULL)
-- Title Rate Sheets
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8888, 65, N''Rate Sheet Name'', N''rateSheetName'', NULL, N''RateSheetName'', N''Rate Sheet Name'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8889, 65, N''Active'', N''active'', NULL, N''Active'', N''Active'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8890, 65, N''Title ID'', N''titleID'', NULL, N''TitleID'', N''Title ID'', N''detail'', 1, N''TitleID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8891, 65, N''Hourly Rate'', N''hourlyRate'', NULL, N''HourlyRate'', N''Hourly Rate'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
-- To Dos
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84001, @ToDoKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84002, @ToDoKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84003, @ToDoKey, N''Subject'', N''subject'', NULL, NULL, N''Subject'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84004, @ToDoKey, N''To Do Status'', N''status'', NULL, NULL, N''To Do Status'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84005, @ToDoKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84006, @ToDoKey, N''Notify Emails'', N''notifyEmails'', NULL, NULL, N''Notify Emails, separate with ; if multiple'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84007, @ToDoKey, N''To Do Type'', N''type'', NULL, NULL, N''To Do Type'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84008, @ToDoKey, N''Notes'', N''notes'', NULL, NULL, N''Notes'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84009, @ToDoKey, N''Assigned User ID'', N''assignedUserID'', NULL, NULL, N''Assigned User ID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (84010, @ToDoKey, N''Completed'', N''completed'', NULL, NULL, N''Completed'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Vouchers
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8892, @VoucherKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8893, @VoucherKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8894, @VoucherKey, N''Invoice Date'', N''invoiceDate'', NULL, NULL, N''Invoice Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8895, @VoucherKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date. Required if posting'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8896, @VoucherKey, N''Due Date'', N''dueDate'', NULL, NULL, N''Due Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8897, @VoucherKey, N''Date Received'', N''dateReceived'', NULL, NULL, N''Date Received'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8898, @VoucherKey, N''AP Account'', N''apAccountNumber'', NULL, NULL, N''AP Account. Required if GL Account is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8899, @VoucherKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8900, @VoucherKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8901, @VoucherKey, N''Approved By'', N''approvedByName'', NULL, NULL, N''Approved By'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8902, @VoucherKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8903, @VoucherKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8904, @VoucherKey, N''Sales Tax Rate'', N''salesTaxID'', NULL, NULL, N''Sales Tax Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8905, @VoucherKey, N''Sales Tax Rate 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax Rate 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8906, @VoucherKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8907, @VoucherKey, N''Office'', N''officeID'', NULL, NULL, N''Office. Required if Office is required'', N''header'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8908, @VoucherKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8909, @VoucherKey, N''Overhead'', N''overhead'', NULL, NULL, N''Overhead'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8910, @VoucherKey, N''Invoice Currency ID'', N''currencyID'', NULL, NULL, N''Invoice Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8911, @VoucherKey, N''Invoice Exchange Rate'', N''invoiceExchangeRate'', NULL, NULL, N''Invoice Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8912, @VoucherKey, N''Project Exchange Rate'', N''projectExchangeRate'', NULL, NULL, N''Project Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8913, @VoucherKey, N''Terms Days'', N''termsDays'', NULL, NULL, N''Terms Days'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8914, @VoucherKey, N''Terms Net'', N''termsNet'', NULL, NULL, N''Terms Net'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8915, @VoucherKey, N''Terms Percent'', N''termsPercent'', NULL, NULL, N''Terms Percent'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8916, @VoucherKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required base on Voucher Type'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8917, @VoucherKey, N''Description (Line)'', N''descriptionLine'', NULL, NULL, N''Description (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8918, @VoucherKey, N''GL Account'', N''expenseAccountNumber'', NULL, NULL, N''GL Account. Required if GL Acount is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8919, @VoucherKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8920, @VoucherKey, N''Unit Description'', N''unitDescription'', NULL, NULL, N''Unit Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8921, @VoucherKey, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8922, @VoucherKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8923, @VoucherKey, N''Markup'', N''markup'', NULL, NULL, N''Markup'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8924, @VoucherKey, N''Unit Rate'', N''unitRate'', NULL, NULL, N''Unit Rate'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8925, @VoucherKey, N''Gross Cost'', N''grossAmount'', NULL, NULL, N''Gross Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8926, @VoucherKey, N''Amount to Bill'', N''amountToBill'', NULL, NULL, N''Amount to Bill'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8927, @VoucherKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8928, @VoucherKey, N''Taxable'', N''taxable'', NULL, NULL, N''Taxable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8929, @VoucherKey, N''Taxable 2'', N''taxable2'', NULL, NULL, N''Taxable 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8930, @VoucherKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8931, @VoucherKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8932, @VoucherKey, N''Purchase Order Number'', N''purchaseOrderNumber'', NULL, NULL, N''Purchase Order Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8933, @VoucherKey, N''Purchase Order Line Number'', N''purchaseOrderLineNumber'', NULL, NULL, N''Purchase Order Line Number'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8934, @VoucherKey, N''Last Voucher'', N''lastVoucher'', NULL, NULL, N''Last Voucher'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8935, @VoucherKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8936, @VoucherKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if has a project and task is required on teh project'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8937, @VoucherKey, N''Client ID (Line)'', N''clientID'', NULL, NULL, N''Client ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8938, @VoucherKey, N''Office (Line)'', N''officeID'', NULL, NULL, N''Office (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8939, @VoucherKey, N''Department (Line)'', N''department'', NULL, NULL, N''Department (Line). Required if Department is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8940, @VoucherKey, N''Target GL Company'', N''targetGLCompanyKey'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8941, @VoucherKey, N''Write Off'', N''writeOff'', NULL, NULL, N''Write Off'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8942, @VoucherKey, N''Date Billed'', N''dateBilled'', NULL, NULL, N''Date Billed'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8943, @VoucherKey, N''Amount Billed'', N''amountBilled'', NULL, NULL, N''Amount Billed'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8944, @VoucherKey, N''Flight Start Date'', N''startDate'', NULL, NULL, N''Flight Start Date'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8945, @VoucherKey, N''Flight End Date'', N''endDate'', NULL, NULL, N''Flight End Date'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8946, @VoucherKey, N''Close'', N''close'', NULL, NULL, N''Close'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8947, @VoucherKey, N''Project Currency ID'', N''pCurrencyID'', NULL, NULL, N''Project Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8948, @VoucherKey, N''Project Currency ID (Line)'', N''pCurrencyID'', NULL, NULL, N''Project Currency ID (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8949, @VoucherKey, N''Project Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Project Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8950, @VoucherKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8951, @VoucherKey, N''Class ID (Line)'', N''classID'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120001, @VoucherKey, N''Project Net Cost'', N''pTotalCost'', NULL, NULL, N''Project Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120002, @VoucherKey, N''Net Cost (HC)'', N''hcTotalCost'', NULL, NULL, N''Net Cost (Home Currency)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120003, @VoucherKey, N''GL Company Exchange Rate'', N''glcExchangeRate'', NULL, NULL, N''GL Company Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120004, @VoucherKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID, used for selecting appropriate field group'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120005, @VoucherKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID, used for selecting appropriate field group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (120006, @VoucherKey, N''Vendor Invoice Type'', N''voucherType'', NULL, NULL, N''Vendor Invoice Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
--Vendor Payment
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8952, @VendorPaymentKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, N''VendorID'', 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8953, @VendorPaymentKey, N''Check Number'', N''checkNumber'', NULL, NULL, N''Check Number'', N''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8954, @VendorPaymentKey, N''Check Amount'', N''checkAmount'', NULL, NULL, N''Check Amount'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8955, @VendorPaymentKey, N''Check Date'', N''paymentDate'', NULL, NULL, N''Check Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8956, @VendorPaymentKey, N''Posting Date'', N''postingDate'', NULL, NULL, N''Posting Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8957, @VendorPaymentKey, N''Cash Account Number'', N''cashAccountID'', NULL, NULL, N''Cash Account Number'', N''header'', NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8958, @VendorPaymentKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company. Required if GL Company is required'', N''header'', 2, N''GLCompanyName'', NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8959, @VendorPaymentKey, N''Pay to Name'', N''payToName'', NULL, NULL, N''Pay to Name'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8960, @VendorPaymentKey, N''Pay to Address 1'', N''payToAddress1'', NULL, NULL, N''Pay to Address 1'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8961, @VendorPaymentKey, N''Pay to Address 2'', N''payToAddress2'', NULL, NULL, N''Pay to Address 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8962, @VendorPaymentKey, N''Pay to Address 3'', N''payToAddress3'', NULL, NULL, N''Pay to Address 3'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8963, @VendorPaymentKey, N''Pay to Address 4'', N''payToAddress4'', NULL, NULL, N''Pay to Address 4'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8964, @VendorPaymentKey, N''Pay to Address 5'', N''payToAddress5'', NULL, NULL, N''Pay to Address 5'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8965, @VendorPaymentKey, N''Opening Transaction'', N''openingTransaction'', NULL, NULL, N''Opening Transaction'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8966, @VendorPaymentKey, N''Unapplied Payment Account Number'', N''unappliedPaymentAccountID'', NULL, NULL, N''Unapplied Payment Account Number'', N''header'', NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8967, @VendorPaymentKey, N''Check Memo'', N''memo'', NULL, NULL, N''Check Memo'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8968, @VendorPaymentKey, N''Posted'', N''posted'', NULL, NULL, N''Posted'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8969, @VendorPaymentKey, N''GL Account Number'', N''glAccountID'', NULL, NULL, N''GL Account Number'', N''detail'', NULL, N''AccountNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8970, @VendorPaymentKey, N''Invoice Number'', N''invoiceNumber'', NULL, NULL, N''Invoice Number'', N''detail'', NULL, N''InvoiceNumber'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8971, @VendorPaymentKey, N''Voucher ID'', N''voucherID'', NULL, NULL, N''Voucher ID'', N''detail'', NULL, N''VoucherID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8972, @VendorPaymentKey, N''Description'', N''description'', NULL, NULL, N''Description'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8973, @VendorPaymentKey, N''Quantity'', N''quantity'', NULL, NULL, N''Quantity'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8974, @VendorPaymentKey, N''Unit Amount'', N''unitAmount'', NULL, NULL, N''Unit Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8975, @VendorPaymentKey, N''Payment Amount'', N''paymentAmount'', NULL, NULL, N''Payment Amount'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8976, @VendorPaymentKey, N''Discount Amount'', N''discAmount'', NULL, NULL, N''Discount Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8977, @VendorPaymentKey, N''Office'', N''officeID'', NULL, NULL, N''Office. Required if Office is required'', N''detail'', 2, N''OfficeName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8978, @VendorPaymentKey, N''Department'', N''departmentID'', NULL, NULL, N''Department. Required if Department is required'', N''detail'', 2, N''DepartmentName'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8979, @VendorPaymentKey, N''Exclude from 1099'', N''exclude1099'', NULL, NULL, N''Exclude from 1099'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8980, @VendorPaymentKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''detail'', NULL, N''SalesTaxID'', NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8981, @VendorPaymentKey, N''Target GL Company'', N''targetGLCompanyID'', NULL, NULL, N''Target GL Company'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8982, @VendorPaymentKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8983, @VendorPaymentKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8984, @VendorPaymentKey, N''Class ID'', N''classID'', NULL, NULL, N''Class ID. Required if Class is required'', N''header'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8985, @VendorPaymentKey, N''Class ID (detail)'', N''classID'', NULL, NULL, N''Class ID (detail). Required if Class is required'', N''detail'', 2, N''ClassID'', NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
-- Vendors
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8986, @VendorKey, N''Company Name'', N''companyName'', NULL, NULL, N''Company Name'', NULL, 1, NULL, 3, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8987, @VendorKey, N''Phone'', N''phone'', NULL, NULL, N''Phone'', NULL, NULL, NULL, 4, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8988, @VendorKey, N''Fax'', N''fax'', NULL, NULL, N''Fax'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8989, @VendorKey, N''Web Site'', N''webSite'', NULL, NULL, N''Web Site'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8990, @VendorKey, N''Company Address 1'', N''address1'', NULL, NULL, N''Company Address 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8991, @VendorKey, N''Company Address 2'', N''address2'', NULL, NULL, N''Company Address 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8992, @VendorKey, N''Company Address 3'', N''address3'', NULL, NULL, N''Company Address 3'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8993, @VendorKey, N''Company City'', N''city'', NULL, NULL, N''Company City'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8994, @VendorKey, N''Company State'', N''state'', NULL, NULL, N''Company State'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8995, @VendorKey, N''Company Postal Code'', N''postalCode'', NULL, NULL, N''Company Postal Code'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8996, @VendorKey, N''Company Country'', N''country'', NULL, NULL, N''Company Country'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8997, @VendorKey, N''Folder'', N''folderName'', NULL, NULL, N''Folder'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8998, @VendorKey, N''Active'', N''active'', NULL, NULL, N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (8999, @VendorKey, N''Date Converted'', N''dateConverted'', NULL, NULL, N''Date Converted'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9000, @VendorKey, N''Comments'', N''comments'', NULL, NULL, N''Comments'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9001, @VendorKey, N''Default Office'', N''office'', NULL, NULL, N''Default Office'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9002, @VendorKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID. Required if passing in a vendor'', NULL, 2, NULL, 2, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9003, @VendorKey, N''Overhead Vendor'', N''overheadVendor'', NULL, NULL, N''Overhead Vendor'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9004, @VendorKey, N''On Hold'', N''onHold'', NULL, NULL, N''On Hold'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9005, @VendorKey, N''Vendor Downloaded'', N''vendorDownloaded'', NULL, NULL, N''Vendor Downloaded'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9006, @VendorKey, N''Terms Percent'', N''termsPercent'', NULL, NULL, N''Terms Percent'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9007, @VendorKey, N''Terms Days'', N''termsDays'', NULL, NULL, N''Terms Days'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9008, @VendorKey, N''Terms Net'', N''termsNet'', NULL, NULL, N''Terms Net'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9009, @VendorKey, N''Default Expense Account'', N''defaultExpenseAccount'', NULL, NULL, N''Default Expense Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9010, @VendorKey, N''Default AP Account'', N''defaultAPAccount'', NULL, NULL, N''Default AP Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9011, @VendorKey, N''Default AP Approver'', N''defaultAPApprover'', NULL, NULL, N''Default AP Approver'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9012, @VendorKey, N''Default Sales Tax ID 1'', N''vendorSalesTax'', NULL, NULL, N''Default Sales Tax ID 1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9013, @VendorKey, N''Default Sales Tax ID 2'', N''vendorSalesTax2'', NULL, NULL, N''Default Sales Tax ID 2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9014, @VendorKey, N''1099 Form'', N''type1099'', NULL, NULL, N''1099 Form'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9015, @VendorKey, N''1099 Box'', N''box1099'', NULL, NULL, N''1099 Box'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9016, @VendorKey, N''FATCA Filing Requirement'', N''fATCAFilingRequirement'', NULL, NULL, N''FATCA Filing Requirement'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9017, @VendorKey, N''DBA'', N''dBA'', NULL, NULL, N''DBA'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9018, @VendorKey, N''Print DBA On Checks'', N''useDBAForPayment'', NULL, NULL, N''Print DBA On Checks'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9019, @VendorKey, N''Credit Card Account'', N''ccAccountNumber'', NULL, NULL, N''Credit Card Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9020, @VendorKey, N''Email Credit Card Info To'', N''emailCCToAddress'', NULL, NULL, N''Email Credit Card Info To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9021, @VendorKey, N''Credit Card Payee Name'', N''ccPayeeName'', NULL, NULL, N''Credit Card Payee Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9022, @VendorKey, N''Accepts VPay'', N''vCardAccepted'', NULL, NULL, N''Accepts VPay'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9023, @VendorKey, N''One Payment per Invoice'', N''onePaymentPerVoucher'', NULL, NULL, N''One Payment per Invoice'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9024, @VendorKey, N''EIN Number'', N''eINNumber'', NULL, NULL, N''EIN Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9025, @VendorKey, N''Default Memo'', N''defaultMemo'', NULL, NULL, N''Default Memo'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9026, @VendorKey, N''Payment Address'', N''paymentAddress'', NULL, NULL, N''Payment Address'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9027, @VendorKey, N''Accepts Credit Cards'', N''ccAccepted'', NULL, NULL, N''Accepts Credit Cards'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9028, @VendorKey, N''Bank Account Number'', N''bankAccountNumber'', NULL, NULL, N''Bank Account Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9029, @VendorKey, N''Bank Routing Number'', N''bankRoutingNumber'', NULL, NULL, N''Bank Routing Number'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9030, @VendorKey, N''Name on Bank Account'', N''bankAccountName'', NULL, NULL, N''Name on Bank Account'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9031, @VendorKey, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70001, @VendorKey, N''ACH Enabled'', N''achEnabled'', NULL, NULL, N''ACH Enabled'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70002, @VendorKey, N''Company Owner'', N''companyOwner'', NULL, NULL, N''Company Owner'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70003, @VendorKey, N''GL Companies'', N''glCompanies'', NULL, NULL, N''GL Companies'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70004, @VendorKey, N''Email ACH Info To'', N''emailACHToAddress'', NULL, NULL, N''Email ACH Info To'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70005, @VendorKey, N''Bank Account Type'', N''bankAccountType'', NULL, NULL, N''Bank Account Type (Checking or Saving)'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (70006, @VendorKey, N''Company Address Name'', N''addressName'', NULL, NULL, N''Company Address Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--Write Off Reasons
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9032, 51, N''Write Off Reason'', N''reasonName'', NULL, N''ReasonName'', N''Write Off Reason'', NULL, 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9033, 51, N''Description'', N''description'', NULL, N''Description'', N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9034, 51, N''Active'', N''active'', NULL, N''Active'', N''Active'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Projects
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9035, 13, N''Invoice Layout'', N''invoiceLayout'', NULL, NULL, N''Invoice Layout'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9037, 13, N''Currency'', N''currencyID'', NULL, NULL, N''Currency'', NULL, NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9039, 13, N''Anyone to Charge Time'', N''anyoneChargeTime'', NULL, NULL, N''Anyone to Charge Time'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (9040, 13, N''Do Not Post WIP'', N''doNotPostWIP'', NULL, NULL, N''Do Not Post WIP'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
-- Broadcast Orders
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7701, @BOKey, N''BO Number'', N''purchaseOrderNumber'', NULL, NULL, N''BO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7702, @BOKey, N''Vendor ID'', N''vendorID'', NULL, NULL, N''Vendor ID'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7703, @BOKey, N''BO Type'', N''purchaseOrderType'', NULL, NULL, N''BO Type'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7704, @BOKey, N''Project Number'', N''projectNumber'', NULL, NULL, N''Project Number'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7705, @BOKey, N''Contact'', N''contact'', NULL, NULL, N''Contact'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7706, @BOKey, N''BO Date'', N''pODate'', NULL, NULL, N''BO Date'', N''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77007, @BOKey, N''Flight Start Date'', N''flightStartDate'', NULL, NULL, N''Flight Start Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77008, @BOKey, N''Flight End Date'', N''flightEndDate'', NULL, NULL, N''Flight End Date'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7709, @BOKey, N''Standard Header Text'', N''headerTextID'', NULL, NULL, N''Standard Header Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7710, @BOKey, N''Standard Footer Text'', N''footerTextID'', NULL, NULL, N''Standard Footer Text'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7711, @BOKey, N''Approver'', N''approvedBy'', NULL, NULL, N''Approver'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7712, @BOKey, N''Approved'', N''approved'', NULL, NULL, N''Approved'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7713, @BOKey, N''Sales Tax ID'', N''salesTaxID'', NULL, NULL, N''Sales Tax ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7714, @BOKey, N''Sales Tax ID 2'', N''salesTax2ID'', NULL, NULL, N''Sales Tax ID 2'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7715, @BOKey, N''GL Company'', N''glCompanyID'', NULL, NULL, N''GL Company. Required if GL Companies are required'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.prefs.UseGLCompany == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7716, @BOKey, N''Order Description'', N''description'', NULL, NULL, N''Order Description'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7717, @BOKey, N''Project Number (Line)'', N''projectNumber'', NULL, NULL, N''Project Number (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7719, @BOKey, N''Office'', N''officeKey'', NULL, NULL, N''Office. Required if Office is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7720, @BOKey, N''Department'', N''departmentID'', NULL, NULL, N''Department. Required if Department is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7721, @BOKey, N''Item ID'', N''itemID'', NULL, NULL, N''Item ID. Required if Item is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7722, @BOKey, N''Task ID'', N''taskID'', NULL, NULL, N''Task ID. Required if Task is required'', N''detail'', 2, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7724, @BOKey, N''Comments'', N''longDescription'', NULL, NULL, N''Comments'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7727, @BOKey, N''Spots'', N''spots'', NULL, NULL, N''Spots'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7728, @BOKey, N''Unit Desc'', N''unitDescription'', NULL, NULL, N''Unit Desc'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7729, @BOKey, N''Commission'', N''markup'', NULL, NULL, N''Commission'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7730, @BOKey, N''Billable'', N''billable'', NULL, NULL, N''Billable'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7731, @BOKey, N''Net Cost'', N''totalCost'', NULL, NULL, N''Net Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7733, @BOKey, N''Sales Tax Amount'', N''salesTax1Amount'', NULL, NULL, N''Sales Tax Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7734, @BOKey, N''Sales Tax Amount 2'', N''salesTax2Amount'', NULL, NULL, N''Sales Tax Amount 2'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7735, @BOKey, N''Currency ID'', N''currencyID'', NULL, NULL, N''Currency ID'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7736, @BOKey, N''Exchange Rate'', N''exchangeRate'', NULL, NULL, N''Exchange Rate'', N''header'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7737, @BOKey, N''Exchange Rate (Line)'', N''pExchangeRate'', NULL, NULL, N''Exchange Rate (Line)'', N''detail'', NULL, NULL, NULL, NULL, NULL, N''System.prefs.MultiCurrency == 1'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7738, @BOKey, N''Class ID'', N''classKey'', NULL, NULL, N''Class ID. Required if Class is required.'', N''header'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7739, @BOKey, N''Class ID (Line)'', N''classKey'', NULL, NULL, N''Class ID (Line). Required if Class is required'', N''detail'', 2, NULL, NULL, NULL, NULL, N''System.hasCustomization(''''legacyclasses'''')'')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7740, @BOKey, N''Space Close'', N''spaceClose'', NULL, NULL, N''Space Close'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7741, @BOKey, N''Materials Due'', N''materialsDue'', NULL, NULL, N''Materials Due'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7743, @BOKey, N''User Defined Date 3'', N''userDate3'', NULL, NULL, N''User Defined Date 3'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (7744, @BOKey, N''User Defined Date 4'', N''userDate4'', NULL, NULL, N''User Defined Date 4'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77077, @BOKey, N''User Defined Date 5'', N''userDate5'', NULL, NULL, N''User Defined Date 5'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77078, @BOKey, N''User Defined Date 6'', N''userDate6'', NULL, NULL, N''User Defined Date 6'', N''detail'', NULL, NULL, NULL, NULL, NULL, N'''')
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77001, @BOKey, N''Unit Cost'', N''unitCost'', NULL, NULL, N''Unit Cost'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77002, @BOKey, N''Gross Amount'', N''grossAmount'', NULL, NULL, N''Gross Amount'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77003, @BOKey, N''Order Days'', N''orderDays'', NULL, NULL, N''Order Days'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77004, @BOKey, N''Order Time'', N''orderTime'', NULL, NULL, N''Order Time'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77005, @BOKey, N''Order Length'', N''orderLength'', NULL, NULL, N''Order Length'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77006, @BOKey, N''Detail Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Detail Field Group ID, used for selecting appropriate field group'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition], [SystemSettingFieldName]) VALUES (77009, @BOKey, N''Station ID'', N''stationID'', NULL, NULL, N''stationID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL, N''BCRequireStations'') 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77010, @BOKey, N''Media Estimate ID'', N''mediaEstimateID'', NULL, NULL, N''Media Estimate ID'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77011, @BOKey, N''Traffic Instructions'', N''trafficInstructions'', NULL, NULL, N''Traffic Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77012, @BOKey, N''Ordered By'', N''orderedBy'', NULL, NULL, N''Ordered By'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77013, @BOKey, N''Special Instructions'', N''specialInstructions'', NULL, NULL, N''Special Instructions'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL) 
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77014, @BOKey, N''Detail Order Start Date'', N''detailOrderStartDate'', NULL, NULL, N''Detail Order Start Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77015, @BOKey, N''Detail Order End Date'', N''detailOrderEndDate'', NULL, NULL, N''Detail Order End Date'', N''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77016, @BOKey, N''Header Field Group ID'', N''fieldGroupID'', NULL, NULL, N''Header Field Group ID, used for selecting appropriate field group'', N''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77017, @BOKey, N''Item Name (Program)'', N''shortDescription'', NULL, NULL, N''Item Name (Program)'', N''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (77018, @BOKey, N''Header ID'', N''headerID'', NULL, NULL, N''Header ID, used for associating header and detail fields when they do not pass in the PO Number'', N''header'', 1, NULL, NULL, NULL, 1, NULL)
-- View
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78001, @ViewKey, N''ViewKey'', N''viewKey'', NULL, NULL, N''ViewKey'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78002, @ViewKey, N''Name'', N''name'', NULL, NULL, N''Name'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78003, @ViewKey, N''ReportType'', N''reportType'', NULL, NULL, N''ReportType'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78004, @ViewKey, N''ReportFilter'', N''reportFilter'', NULL, NULL, N''ReportFilter'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78005, @ViewKey, N''Definition'', N''definition'', NULL, NULL, N''Definition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78006, @ViewKey, N''FieldDefinition'', N''fieldDefinition'', NULL, NULL, N''FieldDefinition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78007, @ViewKey, N''ConditionDefinition'', N''conditionDefinition'', NULL, NULL, N''ConditionDefinition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78008, @ViewKey, N''Private'', N''private'', NULL, NULL, N''Private'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78009, @ViewKey, N''ReportHeading1'', N''reportHeading1'', NULL, NULL, N''ReportHeading1'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78010, @ViewKey, N''ReportHeading1Align'', N''reportHeading1Align'', NULL, NULL, N''ReportHeading1Align'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78011, @ViewKey, N''ReportHeading2'', N''reportHeading2'', NULL, NULL, N''ReportHeading2'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78012, @ViewKey, N''ReportHeading2Align'', N''reportHeading2Align'', NULL, NULL, N''ReportHeading2Align'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78013, @ViewKey, N''Orientation'', N''orientation'', NULL, NULL, N''Orientation'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78014, @ViewKey, N''GroupBy'', N''groupBy'', NULL, NULL, N''GroupBy'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78015, @ViewKey, N''ShowConditions'', N''showConditions'', NULL, NULL, N''ShowConditions'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78016, @ViewKey, N''ReportID'', N''reportID'', NULL, NULL, N''ReportID'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78017, @ViewKey, N''GroupByDefinition'', N''groupByDefinition'', NULL, NULL, N''GroupByDefinition'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78018, @ViewKey, N''LockedColumns'', N''lockedColumns'', NULL, NULL, N''LockedColumns'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78020, @ViewKey, N''AutoExpandGroups'', N''autoExpandGroups'', NULL, NULL, N''AutoExpandGroups'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78021, @ViewKey, N''ApplicationVersion'', N''applicationVersion'', NULL, NULL, N''ApplicationVersion'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78022, @ViewKey, N''AutoRun'', N''autoRun'', NULL, NULL, N''AutoRun'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78023, @ViewKey, N''Description'', N''description'', NULL, NULL, N''Description'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78024, @ViewKey, N''DisplayType'', N''displayType'', NULL, NULL, N''DisplayType'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78025, @ViewKey, N''TabName'', N''tabName'', NULL, NULL, N''TabName'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78026, @ViewKey, N''DataTargetUpper'', N''dataTargetUpper'', NULL, NULL, N''DataTargetUpper'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78027, @ViewKey, N''DataTargetLower'', N''dataTargetLower'', NULL, NULL, N''DataTargetLower'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78028, @ViewKey, N''MaxItemCount'', N''maxItemCount'', NULL, NULL, N''MaxItemCount'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78029, @ViewKey, N''XAxisLabel'', N''xAxisLabel'', NULL, NULL, N''XAxisLabel'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78030, @ViewKey, N''YAxisLabel'', N''yAxisLabel'', NULL, NULL, N''YAxisLabel'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78031, @ViewKey, N''ReportGroupName'', N''reportGroupName'', NULL, NULL, N''ReportGroupName'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78032, @ViewKey, N''XAxisHasCField'', N''xAxisHasCField'', NULL, NULL, N''XAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78033, @ViewKey, N''YAxisHasCField'', N''yAxisHasCField'', NULL, NULL, N''YAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78034, @ViewKey, N''SeriesHasCField'', N''seriesHasCField'', NULL, NULL, N''SeriesHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78035, @ViewKey, N''DefaultReportView'', N''sefaultReportView'', NULL, NULL, N''DefaultReportView'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78036, @ViewKey, N''PivotSettings'', N''pivotSettings'', NULL, NULL, N''PivotSettings'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78037, @ViewKey, N''XAxisHasCField'', N''xAxisHasCField'', NULL, NULL, N''XAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78038, @ViewKey, N''YAxisHasCField'', N''yAxisHasCField'', NULL, NULL, N''YAxisHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) VALUES (78039, @ViewKey, N''SeriesHasCField'', N''seriesHasCField'', NULL, NULL, N''SeriesHasCField'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)

--Media Plans
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80015, @MediaPlanKey, N''Plan ID'', N''planID'', NULL, N''PlanID'', N''Plan ID'', ''header'', 1, NULL, 1, NULL, 1, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80016, @MediaPlanKey, N''Media Plan Key'', N''mediaPlanKey'', NULL, N''MediaPlanKey'', N''Media Plan Key - only required in PUT'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80017, @MediaPlanKey, N''Plan Name'', N''planName'', NULL, N''PlanName'', N''Plan Name'', ''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80019, @MediaPlanKey, N''Project Number'', N''projectNumber'', NULL, N''ProjectKey'', N''Project number'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80020, @MediaPlanKey, N''Description'', N''description'', NULL, N''Description'', N''Description of the plan'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80021, @MediaPlanKey, N''Item ID'', N''itemID'', NULL, N''ItemID'', N''Item ID'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80022, @MediaPlanKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorID'', N''Vendor ID'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80023, @MediaPlanKey, N''Station ID'', N''stationID'', NULL, N''StationID'', N''Station ID'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80024, @MediaPlanKey, N''Spot Link ID'', N''spotLinkID'', NULL, N''SpotLinkID'', N''The ID of the media buy in your system'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80025, @MediaPlanKey, N''Description (Buy)'', N''description'', NULL, N''Description'', N''The description of the media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80026, @MediaPlanKey, N''Start Date'', N''startDate'', NULL, N''StartDate'', N''The start date of the media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80027, @MediaPlanKey, N''End Date'', N''endDate'', NULL, N''EndDate'', N''The end date of the media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80028, @MediaPlanKey, N''Order Days'', N''orderDays'', NULL, N''OrderDays'', N''Order Days'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80029, @MediaPlanKey, N''Order Time'', N''orderTime'', NULL, N''OrderTime'', N''Order Time'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80030, @MediaPlanKey, N''Order Length'', N''orderLength'', NULL, N''OrderLength'', N''Order Length'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80031, @MediaPlanKey, N''Space Close'', N''spaceClose'', NULL, N''Date1'', N''Space Close'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80032, @MediaPlanKey, N''Materials Due'', N''materialsDue'', NULL, N''Date2'', N''Materials Due'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80033, @MediaPlanKey, N''Quantity'', N''quantity'', NULL, N''Quantity'', N''The number of spots'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80034, @MediaPlanKey, N''Cost'', N''cost'', NULL, N''Cost'', N''The total net of the media buy'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80035, @MediaPlanKey, N''Commission'', N''commission'', NULL, N''Markup'', N''Commission'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80036, @MediaPlanKey, N''Unit Rate'', N''unitRate'', NULL, N''UnitCost'', N''Unit rate'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80037, @MediaPlanKey, N''Gross'', N''gross'', NULL, N''Gross'', N''The total gross of the media buy'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80038, @MediaPlanKey, N''Amount to Bill'', N''amountToBill'', NULL, N''AmountToBill'', N''The amount to bill of the media buy'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80039, @MediaPlanKey, N''Line Number'', N''lineNumber'', NULL, N''LineNumber'', N''The line number of the media buy'', ''detail'', Null, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80040, @MediaPlanKey, N''Action'', N''action'', NULL, N''Action'', N''The action on the media buy. Only supported action for PUT is delete'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80041, @MediaPlanKey, N''Order Link ID'', N''orderLinkID'', NULL, N''OrderLinkID'', N''The ID of the media buy  order in your system'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80041, @MediaPlanKey, N''Media Plan Detail Key'', N''mediaPlanDetailKey'', NULL, N''MediaPlanDetailKey'', N''Media Buy Key - only required in PUT'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- Media Plan Vouchers
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80050, @MediaPlanVoucherKey, N''Media Plan Vendor Invoice Key'', N''mediaPlanVoucherKey'', NULL, N''MediaPlanVoucherKey'', N''Media Plan Vendor Invoice Key - only required in PUT'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80051, @MediaPlanVoucherKey, N''Plan ID'', N''planID'', NULL, N''mediaPlanKey'', N''Plan ID'', ''header'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80052, @MediaPlanVoucherKey, N''Vendor ID'', N''vendorID'', NULL, N''VendorKey'', N''Vendor ID'', ''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80053, @MediaPlanVoucherKey, N''Invoice Number'', N''invoiceNumber'', NULL, N''InvoiceNumber'', N''Invoice number'', ''header'', 1, NULL, 1, NULL, 1, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80054, @MediaPlanVoucherKey, N''Invoice Date'', N''invoiceDate'', NULL, N''InvoiceDate'', N''Invoice Date'', ''header'', 1, NULL, NULL, NULL, NULL, NULL)
--INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
--VALUES (80055, @MediaPlanVoucherKey, N''Media Plan Vendor Invoice Detail Key'', N''mediaPlanVoucherDetailKey'', NULL, N''MediaPlanVoucherDetailKey'', N''Vendor invoice detail Key - only required in PUT'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80055, @MediaPlanVoucherKey, N''Invoice Link ID'', N''invoiceLinkID'', NULL, N''InvoiceLinkID'', N''The ID of the vendor invoice in your system'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80067, @MediaPlanVoucherKey, N''Bottom Line Invoice'', N''bottomLineInvoice'', NULL,N''BottomLineInvoice'', N''Is this a Bottom Line Invoice?'', ''header'', NULL, NULL, NULL, NULL, NULL, NULL)

INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80056, @MediaPlanVoucherKey, N''Link ID'', N''linkID'', NULL, N''LinkID'', N''The ID of the media vendor invoice detail in your system'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80057, @MediaPlanVoucherKey, N''Spot Link ID'', N''spotLinkID'', NULL, N''Spot LinkID'', N''The ID of the media buy in your system'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80058, @MediaPlanVoucherKey, N''Description'', N''description'', NULL, N''Description'', N''The description of the vendor invoice detail'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80060, @MediaPlanVoucherKey, N''Cost'', N''appliedCost'', NULL, N''Cost'', N''The total net of the vendor invoice detail'', ''detail'', 1, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80065, @MediaPlanVoucherKey, N''Action'', N''action'', NULL, N''Action'', N''The action on the vendor invoice detail. Only supported action for PUT is delete'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80066, @MediaPlanVoucherKey, N''Last Invoice'', N''lastVoucher'', NULL, N''LastVoucher'', N''This indicates that this is the last vendor invoice detail applied to a media buy'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80068, @MediaPlanVoucherKey, N''Order Link ID'', N''orderLinkID'', NULL, N''OrderLinkID'', N''The ID of the order in your system (POST and bottom line invoice only)'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80069, @MediaPlanVoucherKey, N''Invoice Total'', N''invoiceTotal'', NULL, N''InvoiceTotal'', N''The desired invoice total (POST and bottom line invoice only)'', ''detail'', NULL, NULL, NULL, NULL, NULL, NULL)

-- Media Plan release
INSERT [dbo].[tImportExportDetail] ([ImportExportDetailKey], [ImportExportKey], [ImportExportFieldName], [ApiFieldName], [BusinessClassFieldName], [DBFieldName], [Description], [Section], [Required], [ExportField], [MatchingRow], [MatchingRowLabel], [LinkField], [Condition]) 
VALUES (80070, @MediaPlanReleaseKey, N''Spot Link ID'', N''spotLinkID'', NULL, N''SpotLinkID'', N''The ID of the media buy in your system'', NULL, NULL, NULL, NULL, NULL, NULL, NULL)


SET IDENTITY_INSERT [dbo].[tImportExportDetail] OFF

----------------------------------------------------------------------
------- Update Descriptions
----------------------------------------------------------------------
	--1 Contacts
	UPDATE tImportExport SET [Description] = ''Contacts is the location of all the people in the system except for those found in the Leads area. Most will be associated with a Company, but it is not required. You are able to keep track of multiple addresses and other pertinent contact information. You are also able to view a history of each Activity and Meeting associated with the contact.''
	WHERE ImportExportKey = 1

	--3  Employees
	UPDATE tImportExport SET [Description] = ''There are a number of basic fields that need to be entered on the employee record to ensure Projects, Billing and Reporting will contain the correct information for your staff.''
	WHERE ImportExportKey = 3

	--4 Expense Report Items
	UPDATE tImportExport SET [Description] = ''Expense Report items are used on to track and categorize personal expenses incurred on the agency''''s behalf by your staff. These will typically be entered via an Expense Report, but are also available via a Vendor Voucher.''
	WHERE ImportExportKey = 4

	--5 Purchase Items
	UPDATE tImportExport SET [Description] = N''Purchase Items allow you to track and categorize outside expenses for use in Purchase Orders, Vendor Vouchers, Misc. Project Costs and Client Invoices.''
	WHERE ImportExportKey = 5

	--6 GL Accounts
	UPDATE tImportExport SET [Description] = N''The General Ledger Accounts or Chart of Accounts, form the basis of your financial records in the system. By default, Workamajig has a chart of accounts already setup for you. These are based upon industry standards as provided by Second Wind.''
	WHERE ImportExportKey = 6

	 --7 Payment Terms
	 UPDATE tImportExport SET [Description] = ''This area allows you to set the various payment terms that may be used for your client invoices.''
	 WHERE ImportExportKey = 7

	 --8 Sales Tax
	UPDATE tImportExport SET [Description] = N''Sales Tax Rates are used to automatically calculate sales tax amounts on project estimates and client invoices. Sales Tax Rates can also be linked to vendors, so you can automatically determine the amount of sales tax due at the end of the year.''
	WHERE ImportExportKey = 8

	--9 Services
	UPDATE tImportExport SET [Description] = N''Services allows you to track and categorize employee labor for use in Task Assignments, Time Entry, Tracking/Reporting, and Client Invoices.''
	 WHERE ImportExportKey = 9

	--10 Billing Items
	UPDATE tImportExport SET [Description] = ''Billing items allow you to track and organize Services, Purchase Items, Expense Report Items, and Media Items for use in project reporting and Client Invoices. The billing items allow you to group similar services and expenses and create invoice lines based upon these groups. Billing items can also be used as a way to Post Sales Amounts, on an invoice to several sales GL Accounts from a single line item on an invoice''
	WHERE ImportExportKey = 10

	--11 Invoices
	UPDATE tImportExport SET [Description] = N''These can be created manually by Adding a New Client Invoice, or generated based on your client setup and billing process such as Billing Worksheets, Mass Billing or from the individual projects Billing screen. ''
	 WHERE ImportExportKey = 11

	--12 Vendor Invoices
	UPDATE tImportExport SET [Description] = N''The vendor invoice system integrates tightly with the purchase order system so that purchase order details can be easily pulled onto a vendor invoice. It helps the Accounts Payable processing system for recording expenses to projects as well as administrative invoices''
	 WHERE ImportExportKey = 12
	--13 Projects
	UPDATE tImportExport SET [Description] = N''While projects have many aspects to them, the main purpose of a project is to track, and manage timelines that tie directly into employee''''s timesheets, and can then determine how billing is to proceed.'' 
	WHERE ImportExportKey = @ProjectKey


	--16 Estimates
	UPDATE tImportExport SET [Description] = N''In Workamajig, there are two kinds of estimates. There is a Campaign-based estimate and a Project-based estimate. In this section, the project-based estimate will be discussed.''
	WHERE ImportExportKey = 16

	--18 Purchase Order
	UPDATE tImportExport SET [Description] = N''A purchase order is used to tell a vendor that you want to purchase some item; it acts like a contract with the vendor. It is helpful in tracking expenses incurred toward a project. It allows the company to set controls on things like who could purchase items or how much can be spent on something and therefore is good for budgeting and expense tracking purposes''
	WHERE ImportExportKey = 18

	--19 Receipts, aka Client Receipts, aka client payments
	UPDATE tImportExport SET [Description] = ''DEPRECATED 1/1/2019...Please use Receipts end point moving foward.  When entering a receipt, you are able to apply all, or a portion of the amount, towards open client invoices, a designated sales account or leave as an unapplied amount to be applied towards a future invoice.''
	WHERE ImportExportKey = @ClientPaymentsKey

	--20 Vendor Payments
	UPDATE tImportExport SET [Description] = ''Vendor Payments allow you to track how much you actually pay vendors and print checks directly from Workamajig. Payments will usually be created using Menu > Payments > Select Invoices For Payment screen''
	WHERE ImportExportKey = 20

	--21 Timesheets
	UPDATE tImportExport SET [Description] = N''While the Timesheets section from the main menu navigation will give you access to all of your timesheets entered in the system.  For the API to act on behalf of another person you will need the right "View anyone''''s timesheet" or be an administrator.''
	WHERE ImportExportKey = @TimeSheetKey

	--22 Expense Reports
	UPDATE tImportExport SET [Description] = N''Expense Reports are used for staff members to track out of pocket expenses incurred while working on the company''''s behalf. Each line of the expense report is treated much like a Purchase Order, in that it can be tracked to a client project for billing purposes. Following approval, the approver can convert the expense report into a vendor invoice for reimbursement. The vendor used for the vendor invoice is defaulted from the employee record, but ultimately must be specified at the top of the expense report.''
	WHERE ImportExportKey = 22

	--23 Misc Project Costs
	UPDATE tImportExport SET [Description] = N''This area allows you to enter expenses directly into the project. There is no approval process for these items. Typically, Misc Costs are a way to take items that have been purchased in bulk by your agency and associate a portion of the cost towards a client project, such as, stock photography, DVDs/Jewel case, and copies.''
	WHERE ImportExportKey = 23

	--24 Journal Entry
	UPDATE tImportExport SET [Description] = N''Workamajig allows you to create journal entries in order to account for transactions that are not connected to a Client Invoice or Vendor Voucher, such as rent and agency payroll, or to make adjustments to your General Ledger accounts. The Total Debits - Credits: must total $0.00 for the Journal Entry to be posted to the General Ledger.''
	WHERE ImportExportKey = 24

	--25 Project Types
	UPDATE tImportExport SET [Description] = N''Project types allow you to group your projects into different categories for reporting purposes.''
	WHERE ImportExportKey = 25

	--27 Project Status
	UPDATE tImportExport SET [Description] = N''Project status codes are used to determine where a project is in an overall production status.  While each project can have a unique schedule and set of tasks that need to be completed on the project, most projects move through a similar overall flow through the business.''
	WHERE ImportExportKey = 27

	--28 Departments
	UPDATE tImportExport SET [Description] = ''Departments are used to group your information into different functional areas.  Departments can be used on several reports for filtering and grouping data. Departments are global across a company and will be the same from office to office.''
	WHERE ImportExportKey = 28

	--29 Project Billing Status
	UPDATE tImportExport SET [Description] = N''Project billing status codes are most commonly used to help determine where a project is in the billing cycle.  The project billing status code can also be used to flag the accounting group as to which projects should be billed and when they should be billed.''
	WHERE ImportExportKey = 29

	--31 Broadcast items
	UPDATE tImportExport SET [Description] = ''Broadcast Items are used to categorize your purchases of different types of broadcast purchases. These would typically include Radio and Television. The item is also used to expense the purchase to the correct expense account when a vendor invoice is billed and WIP is tracked in the general ledger.''
	WHERE ImportExportKey = 31

	--32 Print Items
	UPDATE tImportExport SET [Description] = N''Print Items are used to categorize your purchases of different types of Print purchases. These would typically include Magazine, Newspaper and Outdoor. The item is also used to expense the purchase to the correct expense account when a vendor invoice is billed and WIP is tracked in the general ledger.''
	WHERE ImportExportKey = 32

	--33 GL Companies
	UPDATE tImportExport SET [Description] = N''Workamajig has always supported multiple GL Companies as a way of segregating data into specific GL Companies for tracking and reporting purposes.  Recently, the ability to handle Intercompany transactions was added to further advance the multiple company capabilities and in doing so, the need to secure data by GL Company became necessary. The Security and Access settings are only necessary if GL Companies are being used and access to data for specific companies needs to be secured for users.''
	WHERE ImportExportKey = 33

	--34 Insertion Orders
	UPDATE tImportExport SET [Description] = N''Insertion Orders are like Purchase Orders used to place orders to Publications. Insertion Orders are entered using the gross amount and a commission percentage to determine the net amount. Insertion orders also allow you to track user definable dates on each line item of the order.''
	WHERE ImportExportKey = 34

	--36 Leads
	UPDATE tImportExport SET [Description] = N''Leads is the area of Workamajig used to track your pre-sales efforts. A lead is considered a non-qualified contact, either client or vendor. A Lead record consists of contact information at the personal and company level. Lead records are created individually, via import or via the Web to Leads feature. You are also able to track the communication history. Once a Lead has been qualified, the Lead can be converted into a Contact/Company record. ''
	WHERE ImportExportKey = 36

	--37 Companies
	UPDATE tImportExport SET [Description] = ''The Company area includes all Companies in your system, including Clients and Vendors. This area will not include any data from the Leads area. To prevent duplication of Company and Contacts, it is recommended that you first create a company, then add contacts via the new company: Contacts area.''
	WHERE ImportExportKey = 37

	--38 Opportunities
	UPDATE tImportExport SET [Description] = N''The purpose of an Opportunity is to serve as a starting point and a tracing of your project proposal. It allows you to convert to a working project.''
	WHERE ImportExportKey = 38

	--39 Activities
	UPDATE tImportExport SET [Description] = ''An activity in Workamajig is used to document "touch points" regarding Clients, Vendors, Opportunities, Projects, and Leads. You are able to notify multiple people and link the activity to multiple projects, contacts, companies, etc. to increase the visibility of the necessary information your staff needs to get their job done.''
	WHERE ImportExportKey = 39

	--40 Report Groups
	UPDATE tImportExport SET [Description] = N''Report groups are used to organize different custom reports in the system.  On the reports page, the system allows you to create an unlimited number of custom reports.  You can set up different report groups here to better organize your custom reports.''
	WHERE ImportExportKey = 40

	--41 Opportunity Stages
	UPDATE tImportExport SET [Description] = N''Opportunity stages allow you to create a sales funnel through which you can track your different opportunities and determine which state in the sales process they are currently at.''
	WHERE ImportExportKey = 41

	--42 Opportunity Status
	UPDATE tImportExport SET [Description] = N''Opportunity Status allows you to define the status of the opportunity. Typical settings are Postponed, Closed or Open.''
	WHERE ImportExportKey = 42

	--43, N''Opportunity Outcome
	UPDATE tImportExport SET [Description] = N''When tracking opportunities in the contact management system, you can use opportunity outcomes to categorize the outcome of each opportunity you enter into the system.  This can give you valuable information on your conversion statistics, as well as, how many opportunities you win versus lose, and the reasons for winning and losing them.''
	WHERE ImportExportKey = 43

	--44 Company Types
	UPDATE tImportExport SET [Description] = ''Company types are used in contact management to segment your contact database. Company types can be used to quickly find different types of companies, vendors or clients. You can add as many company types as you would like and then use them in custom listings and reports.''
	WHERE ImportExportKey = 44

	--45 Meeting Types
	UPDATE tImportExport SET [Description] = ''These apply to calendar meetings in Workamajig and allow you to define the meeting without having to include this in the subject of the meeting.''
	WHERE ImportExportKey = 45

	--46 Calendar Resources  
	UPDATE tImportExport SET [Description] = ''This section contains a list of calendars associated with the various resources you need to schedule, Ex. conference rooms and OHPs.''
	WHERE ImportExportKey = 46

	-- 48 Sources  
	UPDATE tImportExport SET [Description] = N''Source is ultimately seen as being connected to a Company record. You are able to select a Source via a Lead record:Company Info area or from the Company record:Company Info area.  After defining the Source,  you are able to use this field for reporting and grouping of records in the listing screens and reports associated with Leads, Contacts, Companies, and Opportunities. ''
	WHERE ImportExportKey = 48

	-- 49 Conversation Types 
	UPDATE tImportExport SET [Description] = ''This allows you to create a custom dropdown when using Activities and Diary posts. The main benefit being that you can run reports based on which type was chosen by the one creating the activity or Diary post.''
	WHERE ImportExportKey = 49

	 -- 50 Payment Methods  
	UPDATE tImportExport SET [Description] = N''Payment methods are used to categorize receipts from clients. Typical options would include check, cash, credit card, EFT.''
	WHERE ImportExportKey = 50

	 -- 51 Write Off Reasons 
	UPDATE tImportExport SET [Description] = N''When closing out transactions on a project, you have several Form Actions to choose from: Bill Selected Items, Mark as Billed, or Write Them Off (to name just a few). When you write off the transaction in the billing worksheet, it does not have a direct impact on the general ledger unless you are??re tracking work in progress in the ledger''
	WHERE ImportExportKey = 51

	  -- 52 Standard Text  
	  UPDATE tImportExport SET [Description] = N''This is simply where you can create a Header and/or Footer Text that is then selectable for each order.''
	 WHERE ImportExportKey = 52

	  -- 53 Media Markets  
	  UPDATE tImportExport SET [Description] = ''Media Markets are used to track stations and publications to different areas of the country, and can be used when reporting on purchases.''
	  WHERE ImportExportKey = 53

	  -- 54 GL Classes  
	  UPDATE tImportExport SET [Description] = N''GL classes are used to segment transactions posted to the general ledger.  They can be used for several different types of needs.  The most common use of classes is to segment transactions by company, department or office.  When entering transactions such as vendor invoices or client invoices, you can select different classes on each transaction at the header and the line. When the transaction is posted to the general ledger, the system will add the class from the transaction on each entry that is posted.  When running your financial reports, you will be able to filter the transactions on the report by class.''
	  WHERE ImportExportKey = 54

	  -- 55 Offices  
	  UPDATE tImportExport SET [Description] = N''Workamajig allows you to separate out Employees, Projects and project file access using office. This can be useful when reporting on chargeability and project profitability reports and controlling access to your file storage server. Offices will flow through to the general ledger when posting transactions''
	  WHERE ImportExportKey = 55

	  -- 56 Teams  
	  UPDATE tImportExport SET [Description] = N''These are referred to as Account Teams in Client and Project setup.''
	  WHERE ImportExportKey = 56

	  -- 57 Credit Card Charges 
	  UPDATE tImportExport SET [Description] = ''The Credit Card Charges feature under the Purchasing menu allows you to pay vendor invoices using a credit card, add credit card charges for purchases, reconciling credit card statements and pay your credit card bills.  You can setup a supported provider to automatically download credit card charges, import .ofx files from the credit card, or setup an import file to quickly import numerous credit card charges at once.''
	  WHERE ImportExportKey = 57

	   -- 58 Service Rate Sheets  
	   UPDATE tImportExport SET [Description] = N''Service Rate Sheets allow you to create multiple billing rates for your services. A Service Rate Sheet can be pre-assigned to the client to be used as a default for the clients projects (additional workflow setup required). This can also be used for creating Rush Rates, etc''
	   WHERE ImportExportKey = 58

	   -- 59 Item Rate Sheets  
	   UPDATE tImportExport SET [Description] = N''Purchase Item Rate Sheets are used to standardize markups for items for different clients. Item rate sheets work the same way as service rate sheets. You can set different markups for the same item on each rate sheet and then on each project, select a different rate sheet based on the client.''
	   WHERE ImportExportKey = 59

	   -- 60 Financial Budgets  
	   UPDATE tImportExport SET [Description] = N''Workamajig allows for Financial Budgets to be put into the system at a number of different levels. The budget can be used for comparison purposes when running your P&L financial reports. The following dimensions can be defined on your financial budget: GL Company, Office, Department, GL Class and Client.''
	   WHERE ImportExportKey = @GLBudget

	   -- 61 Billing Groups  
	   UPDATE tImportExport SET [Description] = N''This feature is used to group together projects for billing purposes. Though the same Billing Group can be used to identify projects across multiple projects, Workamajig will generate a Master Billing Worksheet for each client and each Billing Group identified on the individual client projects.''
	   WHERE ImportExportKey = 61

	   -- 62 Credit Card Transactions  
	   UPDATE tImportExport SET [Description] = N''The purpose of the connector is to allow you a chance to review and code your incoming charges to the correct project and other settings.''
	   WHERE ImportExportKey = 62

	   -- 63 Currency Rates  
	   UPDATE tImportExport SET [Description] = N''When entering transactions in foreign currencies, a default currency rate is pulled from a table in the database. You can manage your own exchange rates under the Admin or System Setup/GL Settings/Currency Rates screen''
	   WHERE ImportExportKey = 63

	   -- 64 Titles  
	   UPDATE tImportExport SET [Description] = N''A service is what is being performed by the user. Think of them as job titles.''
	   WHERE ImportExportKey = 64

	   -- 65 Title Rate Sheets  
	   UPDATE tImportExport SET [Description] = N''Service Rate Sheets allow you to create multiple billing rates for your services. A Service Rate Sheet can be pre-assigned to the client to be used as a default for the clients projects (additional workflow setup required). This can also be used for creating Rush Rates, etc. ''
		WHERE ImportExportKey = 65

	   -- 67 Request Reject Reasons  
	   --UPDATE tImportExport SET 
	 	 --  WHERE ImportExportKey = 67

	   -- 69 Tasks  
	   UPDATE tImportExport SET [Description] = N''Master Tasks are used to create a standard list of tasks that are used on each project. Each master task can have assignments underneath it. On a master task, you can specify default accounting information and description of work performed. Keep in mind that when using master tasks, you can only enter a task once onto the project, so you may need a Review 1, or a Review 2 set of tasks if you commonly repeat certain activities.''
		WHERE ImportExportKey = 69

	   -- 70 Vendors  
	   UPDATE tImportExport SET [Description] = ''The Vendors section within Purchasing is designed to only pull the results of "companies" that are flagged as a vendor, in the company > vendor setup screen.''
		WHERE ImportExportKey = 70

	   -- 71 Clients 
	    UPDATE tImportExport SET [Description] = ''Client refers to the term of a company record that is setup as a client.''
		WHERE ImportExportKey = @ClientKey

	   -- 72 Time  
	   UPDATE tImportExport SET [Description] = N''While the Timesheets section from the main menu navigation will give you access to all of your timesheets entered in the system.  For the API to act on behalf of another person you will need the right "View anyone''''s timesheet" or be an administrator.''
	   WHERE ImportExportKey = @TimeKey

	   -- 73 Project Spec Sheets  
	   UPDATE tImportExport SET [Description] = N''Spec Sheets have a variety of uses, they can be applied to a Project, Project Request, Opportunity, Purchase Order. However they must have a layout defined, this is done by going to Menu > Admin > System Setup > Tracking > Define Spec Sheets.''
		WHERE ImportExportKey = 73

	   -- 74 Request Spec Sheets  
	   UPDATE tImportExport SET [Description] = N''Spec Sheets have a variety of uses, they can be applied to a Project, Project Request, Opportunity, Purchase Order. However they must have a layout defined, this is done by going to Menu > Admin > System Setup > Tracking > Define Spec Sheets.''
		WHERE ImportExportKey = 74

	   -- 75 Labor Budgets  
	   UPDATE tImportExport SET [Description] = ''Labor Budgets allow you to plan the amount of hours and billable dollars your staff will generate during the year. This is helpful for forecasting labor revenue when people may work more than a standard work week. These labor budgets are then used in the Chargeability Reports and Widgets.''
		WHERE ImportExportKey = 75

	   -- 76 Project Request  
	   UPDATE tImportExport SET [Description] = N''Project Requests allow your team and clients to initiate a request for something to be done by your team. You can define multiple Project Request forms, and in addition to our standard fields, you can add Custom Fields to the initial form and link pre-built specification sheets as the additional pages to fill out''
	 	   WHERE ImportExportKey = 76

	   -- 77 Broadcast Orders  
	   UPDATE tImportExport SET Description = ''Broadcast Orders are like Purchase Orders used to place orders to Stations for broadcasting. Broadcast Orders are entered by spots for each ad, either on a weekly, daily or summary basis using the gross amount and a commission percentage to determine the net amount. Broadcast orders also allow you to track user definable dates on each line item of the order.''
	   WHERE ImportExportKey = 77

	   --79 Address
	   UPDATE tImportExport SET Description = ''Address represents the phsyical location of a company''
	   WHERE ImportExportKey = @AddressKey

	   --80 Deliverables
	   UPDATE tImportExport SET Description = N''Digital artwork internally for review before sending to your clients for their comments''
	   WHERE ImportExportKey = @DeliverableKey

	   --100 Opportunties/List
		UPDATE tImportExport SET [Description] = N''The purpose of an Opportunity is to serve as a starting point and a tracing of your project proposal. It allows you to convert to a working project.''
		WHERE ImportExportKey = 100

		--109 Reports
		UPDATE tImportExport SET [Description] = N''The purpose of Reports is to pull data out of workamajig.''
		WHERE ImportExportKey = @ReportKey

		--115 Receipts, - replaceing client payments 1/1/2020
		UPDATE tImportExport SET [Description] = ''When entering a receipt, you are able to apply all, or a portion of the amount, towards open client invoices, a designated sales account or leave as an unapplied amount to be applied towards a future invoice.''
		WHERE ImportExportKey = @ReceiptsKey

		--118 Retainer
		UPDATE tImportExport SET [Description] = ''Client Retainers.''
		WHERE ImportExportKey = @RetainerKey

	--127 Project Staff Rates
	UPDATE tImportExport SET [Description] = N''The purpose of project staff rates is to update the hourly rates per user on a project that has the Get Rate From = Project User to a custom amount.  The PUT is the only method that works with this endpoint because you can only edit, not create staff rates.'' 
	WHERE ImportExportKey = @ProjectStaffRatesKey

		---------------------------------------------------------
		--tImportExportParms
		---------------------------------------------------------
		DELETE From [tImportExportParms]
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''id'', N''Project ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''key'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''projectkey'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''searchFor'', N''search for'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''searchField'', N''search field, including "projectnumber", "projectname", "companyname", "campaignname", "description"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeTeam'', N''Include project team, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''all'', N''include all details, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeDiary'', N''include diary, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeTodos'', N''include To Do''''s, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeTasks'', N''include Tasks, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeMiscCosts'', N''include Misc Costs, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeEstimates'', N''include Estimates, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeEstimateData'', N''include Estimate Data dataset, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeSpecSheets'', N''include Spec Sheets, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectKey, N''includeSpecSheetData'', N''Project Spec Sheet Data dataset, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (39, N''activityKey'', N''Activity Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (61, N''billingGroupKey'', N''Billing Group Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (10, N''workTypeKey'', N''Billing Item Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (31, N''broadcastItemKey'', N''Broadcast Item Key'')
		--77 broadcast order
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@BOKey, N''searchfor'', N''will search what you enter in PO number, project, or vendor'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@BOKey, N''orderKey'', N''Broadcast Order Key'')

		--33 GL Company
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (33, N''glCompanyKey'', N''GL Company Key'')
		
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (46, N''calendarResourceKey'', N''Calendar Resource Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ClientPaymentsKey, N''checkKey'', N''Check Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ClientPaymentsKey, N''clientID'', N''Client ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ClientKey, N''companyKey'', N''Client Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (37, N''companyKey'', N''Company Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (44, N''companyTypeKey'', N''Company Type Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (1, N''search'', N''search fields: "name", "companyKey", "getFavorites", "getRecents", "dateUpdated"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (1, N''contactKey'', N''contact Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (49, N''activityTypeKey'', N''Activity Type Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (57, N''voucherKey'', N''Voucher Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (62, N''glAccountKey'', N''GL Account Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CurrencyRateKey, N''currencyID'', N''Currency ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CurrencyRateKey, N''startDate'', N''Start Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CurrencyRateKey, N''endDate'', N''End Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (28, N''departmentKey'', N''Department Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (3, N''employeeKey'', N''Employee Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (3, N''showInactive'', N''search Inactive'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (16, N''estimateKey'', N''Estimate Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (4, N''expenseReportItemKey'', N''Expense Report Item Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (22, N''expenseReportKey'', N''Expense Report Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@GLBudget, N''glBudgetKey'', N''GL Budget Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@GLAccountKey, N''glAccountKey'', N''GL Account Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@GLAccountKey, N''glAccountNumber'', N''GL Account Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (54, N''ClassKey'', N''Class Key'')
		
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@IOKey, N''searchfor'', N''will search what you enter in PO number, project, or vendor'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@IOKey, N''purchaseOrderKey'', N''Purchase Order Key'')

		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@InvoiceKey, N''invoiceNumber'', N''Invoice Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ItemRateSheetKey, N''itemRateSheetKey'', N''Item Rate Sheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (24, N''search'', N''Search'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (24, N''journalEntryKey'', N''Journal Entry Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (75, N''laborBudgetKey'', N''Labor Budget Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (36, N''userLeadKey'', N''User Lead Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (53, N''mediaMarketKey'', N''Media Market Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (23, N''projectNumber'', N''Project Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (23, N''miscCostKey'', N''Misc Cost Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (55, N''officeKey'', N''Office Key'')
		--INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (38, N''list'', N''List all opportunities, "type", "range"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (38, N''opportunityKey'', N''Opportunity Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (38, N''id'', N''Opportunity ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (43, N''opportunityOutcomeKey'', N''Opportunity Outcome Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (41, N''opportunityStageKey'', N''Opportunity Stage Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (42, N''opportunityStatusKey'', N''Opportunity Status Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (50, N''paymentMethodKey'', N''Payment Method Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (7, N''paymentTermsKey'', N''Payment Terms Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (32, N''printItemKey'', N''Print Item Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (29, N''projectBillingKey'', N''Project Billing Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (73, N''specID'', N''Spec Sheet ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (27, N''projectStatusKey'', N''Project Status Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (25, N''projectTypeKey'', N''Project Type Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (5, N''ItemID'', N''Item ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@POKey, N''searchfor'', N''will search what you enter in PO number, project, or vendor'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@POKey, N''purchaseOrderKey'', N''Purchase Order Key'')

		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (40, N''reportGroupKey'', N''Report Group Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectRequestKey, N''requestKey'', N''Request Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (74, N''specID'', N''Request Spec ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (8, N''salesTaxKey'', N''Sales Tax Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ServiceRateSheetKey, N''serviceRateSheetKey'', N''Service Rate Sheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (48, N''sourceKey'', N''Source Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (52, N''standardTextKey'', N''Standard Text Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''projectKey'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''includeTaskUser'', N''Include Task User, enter true'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''projectNumber'', N''Project Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (69, N''taskKey'', N''Task Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (56, N''teamKey'', N''Team Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (56, N''userId'', N''UserID of a team member'')
		-- 72 time
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''timesheetKey'', N''Timesheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''timeKey'', N''Time Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''status'', N''Status valid status include "unsubmitted", "submitted", "rejected", "approved"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''userKey'', N''User Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''startdate'', N''Start Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''enddate'', N''End Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''includeService'', N''Include Service'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeKey, N''includeTime'', N''include Time'')
		--21 timesheet
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''timesheetKey'', N''Timesheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''status'', N''Status valid status include "unsubmitted", "submitted", "rejected", "approved"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''userKey'', N''User Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''startdate'', N''Start Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''enddate'', N''End Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''includeService'', N''Include Service, enter 1'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (21, N''includeTime'', N''Include Time, enter 1'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (65, N''titleRateSheetKey'', N''Title Rate Sheet Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (64, N''titleKey'', N''Title Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@VoucherKey, N''voucherKey'', N''Voucher Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@VendorPaymentKey, N''paymentKey'', N''Payment Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (70, N''companyKey'', N''Company Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (51, N''writeOffReasonKey'', N''Write Off Reason Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (5, N''itemID'', N''Purchase Item ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@AddressKey, N''addressKey'', N''Address Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@DeliverableKey, N''deliverableID'', N''Deliverable ID'')
		-- 84 to do
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ToDoKey, N''todokey'', N''To Do Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ToDoKey, N''projectkey'', N''Project Key'')
		--100 opportunities/list
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (100, N''type'', N''types include "byStage", "byLevel" and "byNeglected" '')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (100, N''range'', N''for "byStage", will be stage lead stage key, for "byLevel", 1:Unaware 2:Contemplating   3:Planning  4:Action,<br> for "byNeglected" 1: last 7 days, 2: last 30 days, 3 older than 30 days'')
		--101 activities/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (101, N''date'', N''activity date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (101, N''mode'', N''"today","thisweek", "unread", "open", "favorites"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (101, N''dateupdated'', N''activity date updated'')
		--102 companies/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''text'', N''searches company name, parent company name, vendor ID and client ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''getFavorites'', N''getFavorites - enter 1 to include your favorites'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''getRecents'', N''getRecents - enter 1 to include your recents'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (102, N''dateUpdated'', N''dateUpdated'')
		--103 contacts/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''name'', N''name'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''getFavorites'', N''getFavorites - enter 1 to include your favorites, only use with name, dateupdated or companyKey'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''getRecents'', N''getRecents - enter 1 to include your recents, only use with name, dateupdated or companyKey'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''dateUpdated'', N''dateUpdated'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (103, N''companyKey'', N''Company Key'')
		--104 employees/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''name'', N''Name. Can only search for one per request: name, email or userID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''showInactive'', N''Show Inactive employees'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''email'', N''employees email. Can only search for one per request: name, email or userID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (104, N''userID'', N''employees UserID. Can only search for one per request: name, email or userID '')
		--105 journalentries/search
		--Not yet implemented
		--106 leads/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''name'', N''lead name'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''getFavorites'', N''getFavorites - enter 1 to include your favorites, only use with name, dateupdated or companyKey'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''getRecents'', N''getRecents - enter 1 to include your recents, only use with name, dateupdated or companyKey'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''dateUpdated'', N''dateUpdated'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (106, N''companyKey'', N''Company Key'')
		--107 timesheets/time
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeSheetTimeKey, N''workdatemin'', N''start date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@TimeSheetTimeKey, N''workdatemax'', N''end date'')
		--108 vendors/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''text'', N''will search company name and vendor ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''getFavorites'', N''getFavorites - enter 1 to include your favorites'') 
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''getRecents'', N''getRecents - enter 1 to include your recents'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (108, N''dateUpdated'', N''dateUpdated'')
		--109 Reports
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReportKey, N''ReportKey'', N''ReportKey, also the API Access Key from setting screen of the view/report'')
		--111 Media Plans
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@MediaPlanKey, N''planID'', N''Plan ID'')
		--112 Media Plan Vouchers
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@MediaPlanVoucherKey, N''vendorID'', N''Vendor ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@MediaPlanVoucherKey, N''invoiceNumber'', N''InvoiceNumber'')
		--115 Receipts
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''receiptKey'', N''Receipt Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''clientID'', N''Client ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''depositID'', N''Deposit ID'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''referenceNumber'', N''Reference Number'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''receiptDate'', N''Receipt Date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ReceiptsKey, N''invoiceNumber'', N''Invoice Number'')
		--116 Conversation
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationKey, N''conversationKey'', N''Conversation Key'')
		--118 Retainer
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationKey, N''retainerKey'', N''Retainer Key'')
		--120 PUblication
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@PublicationKey, N''publicationKey'', N''Publication Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@PublicationKey, N''publicationID'', N''Publication ID'')
		--122 Station
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@StationKey, N''stationKey'', N''Station Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@StationKey, N''stationID'', N''Station ID'')

		--124 Campaign
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CampaignKey, N''campaignKey'', N''Campaign Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@CampaignKey, N''campaignID'', N''Campaign ID'')

		--127 Project Staff Rates
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectStaffRatesKey, N''projectKey'', N''Project Key'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ProjectStaffRatesKey, N''projectNumber'', N''Project Number'')

		--131 Conversations/search
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''date'', N''activity date'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''mode'', N''"today","thisweek", "unread", "open", "favorites"'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''dateupdated'', N''activity date updated'')
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@ConversationSearchKey, N''projectNumber'', N''project number'')

		--135 Billing Schedule
		INSERT [dbo].[tImportExportParms] ([ImportExportKey], [ParameterName], [Description]) VALUES (@BillingScheduleKey, N''billingScheduleKey'', N''Billing Schedule Key'')
exec sptImportExportSamplesSeedDoco

/*
|| 04/28/18		MCM 18.5.0.0 Created when removed doco fields from convert app seed
|| 05/03/18		MCM 18.5.0.0 Adding in Description field values\\

|| 01/24/18     MCM 19.0.2.0 Moving data from convertAppSeed since really belong in different locations
|| 01/25/18     MCM 19.0.0.0 (442119) Added Address Info
|| 02/08/19     MCM 19.0.3.0 (441055) Change name from client payments to client receipts
|| 02/20/19     MCM 19.0.3.0 (444534) Added Exclude 1099 to the credit card charges
|| 03/14/19     MCM 19.0.4.0 (450619) Added estimateLaborTaxable to the clients 
|| 05/16/19     MCM 19.0.6.0 (454943) Added void and get by Client ID for the client payments
|| 05/22/19     RLS 19.0.6.0 (459855) Added UserName to Teams
|| 06/27/19     MCM 19.0.7.0 (467154) Added Opportunity ID to the parmaters
|| 07/08/19     MCM 19.0.8.0 (465477) Added Opportunity ID as input field for Imports and we''ll match on it.
|| 08/15/19     MCM 19.0.9.0 (435391) Added Approved to be a link field on the timesheet import
|| 08/23/19     MCM 19.0.9.0 (475644) Added custom field header info for PO, IO and BO.
|| 09/12/19     MCM 19.1.0.0 (435391) Made workDate a link field for Timesheet
|| 09/19/19     MCM 19.1.0.0 (435391) Removed billing title and department from the timesheet import
|| 09/23/19     MCM 19.1.0.0 (476967) Added deliverable information
|| 09/25/19     GHL 19.1.0.0 Added media plan + media plan voucher doco fields
|| 10/10/19     MCM 19.1.1.0 (481271) Added receipts endpoint and started phasing out client payments
|| 10/21/19     GHL 19.1.1.0 (484211) Removed tMediaPlan.POKind, added tMediaPlanVoucherDetail.LastVoucher
|| 10/28/19     MCM 19.1.1.0 (465486) Added client division and client product to the opportunity import
|| 10/29/19     MCM 19.1.1.0 (468646) Added the Service Description for service rate sheet export
|| 11/04/19     MCM 19.1.2.0 (484799) Fixed spelling of address Name on the address import
|| 11/18/19     MCM 19.1.2.0 (488559) Fixed [DBFieldName] of ''Unit Rate'' to ''UnitRate'' having ImportExportDetailKey of 32001
|| 11/26/19     MCM 20.0.1.0 (489864) Added project status active field
|| 12/02/19     GHL 20.0.1.0 Added media plan release function
|| 12/19/19     RLS 20.0.1.0 (493105) Made NotifyEmail required for ProjectRequest
|| 12/27/19     MCM 20.0.1.0 (492818) Adding the diary endpoint
|| 12/30/19     GHL 20.0.1.0 Made media plans available for import
|| 01/07/20     GAR 20.0.2.0 (488171) Added project manager to the clients and companies imports
|| 01/09/20     GHL 20.0.2.0 Changes to media plans
|| 01/15/20     MCM 20.0.2.0 (496824) Fix the comments line field on the expense report
|| 01/22/20     MCM 20.0.2.0 (49218) Chaning info from diary endpoint to conversation Endpoint
|| 01/24/20     MCM 20.0.2.0 (494033) Updated GL Account comments for none if want to remove subaccount
|| 02/10/20     MCM 20.0.3.0 (501147) Fixed spelling and made @Client
|| 02/13/20     GHL 20.0.3.0 Removed keys for the API media plan updates (we use IDs now)
|| 02/13/20     MCM 20.0.3.0 (501440) Change PO, classKey to classID
|| 02/17/20     GHL 20.0.3.0 Setting MatchRow and Put on media plans/media plan vouchers to use in Update mode
|| 02/21/20     MCM 20.0.3.0 (496256) Adding the project manager to the projects
|| 02/28/20     MCM 20.0.4.0 (504341) Added @timeKey
|| 05/01/20     MCM 20.0.6.0 (501819) Added posted to the Journal Entry to automatically post the entry
|| 06/01/20     MCM 20.0.7.0 (517369) Added skipApprovalProcess to the Project Request update
|| 06/19/20     MCM 20.0.7.0 (518055) Added defaultFFLineFormat to the Client import
|| 06/24/20     MCM 20.0.7.0 (520218) Added info about employee service delimiter a '';''
|| 06/25/20     MCM 20.0.7.0 (519140) Added ''|DeliverableType'' to CustomFieldEntity in order for all custom fields to show up
|| 07/07/20     GHL 20.0.8.0 Added OrderLinkID, InvoiceLinkID, BottomLineInvoice, InvoiceTotal to media plans 
|| 07/14/20     MCM 20.0.8.0 (521779) Updated Opportunity ID desecription.
|| 07/17/20     MCM 20.0.8.0 (522660) Added template and getMarkupFrom as a field for the project import
|| 07/28/20     MCM 20.0.8.0 (479239) Added to do info
|| 07/31/20     MCM 20.0.9.0 (522660) Added Project fields
|| 09/03/20     MCM 20.0.9.0 (528216) Updated task perc comp seperate description to indicate it goes to "Track Actual Dates for Each Person"
|| 09/11/20     MCM 20.1.0.0 (529111) Updated project Rate Sheet from timeRateSheetKey to ratesheet.
|| 10/09/20     MCM 20.1.1.0 (531998) Added Predecessors to the task import
|| 10/23/20     MCM 20.1.1.0 (534675) Added ACHEnabled to the vendor Import
|| 10/26/20     MCM 20.1.1.0 (522683) Added Retainer Import
|| 10/28/20     MCM 20.1.1.0 (531964) Added company owner to vendor, updated field to be company owner on client and company from contactOwner
|| 11/13/20     MCM 20.1.2.0 (536745) Added invoiceExcludeAttachment to contacts
|| 11/16/20     MCM 20.1.2.0 (537251) Added notifyEmails to the ToDo''s
|| 04/07/21     MCM 21.04.18 (554094) Added toDoType to the ToDo''s
|| 04/19/21	    MCM 21.05.16 (551714) Added Stations and Publications
|| 05/27/21	    MCM 21.06.20 (556803) Added Campaigns
|| 06/09/21     MCM 21.07    (561292) Added Project Export Info
|| 06/24/21     MCM 21.07    (562794) Added copy campaign fields
|| 06/28/21     MCM 21.07    (560843) Updated Campaigns so that the segment supports add/update/delete
|| 06/29/21     GHL 21.07    (563439) Cleaned up duplicates/descriptions for currency on vendor invoices 
|| 07/09/21     MCM 21.07    (563565) Added Supervisor Name to the employee import
|| 07/16/21     GHL 21.08    (565228) Added Net Cost (HC) hcTotalCost to Vendor Invoices 
|| 07/16/21     GHL 21.08    (565228) Added Total Amount (HC) hcTotalAmount to Client Invoices 
|| 07/19/21     MCM 21.08    (565174) Added forecastAsFixedFee to project import
|| 07/22/21		MCM 21.08	 (563565) Added Get Campaign by ID
|| 08/12/21     MCM 21.09    (568099) Made the PO Linked fields required
|| 09/29/21		MCM 21.10.17 (571693) added ebitda to the glaccounts
|| 11/19/21		QMD 21.12.19 (577998) changed timesheet verbage
|| 11/23/21     MCM 21.12.19 (578655) added possible values for oneinvoiceper
|| 12/07/21		MCM 21.12.19 (579940) added classID to the invoice header and details
|| 01/10/22     MCM 22.02.   (581894) Added conversations
|| 01/19/22     MCM 22.02.   (583018) Added Vendor Cost to the Employee endpoint
|| 02/01/22		MCM 22.02.	 (585206) Added RequireMinHoursPerWeek MinHoursPerWeek to employee import
|| 02/15/22		MCM 22.03.x  (587517) added includeSpecSheets to the parameters
|| 02/21/22     MCM 22.03.   (588899) Added ACHRececipts and CCReceipts for the client import
|| 03/07/22     MCM 22.03.x  (585814) Added Estimate Data and Project Spec Sheet Data to the project parameters
|| 03/28/22     MCM 22.04.x  (589336) Added doNotUseSSO (screen calls is Do Not use SAML/SSO Authentication) to contact 
|| 03/30/22     MCM 22.04.17 (593606) Added clientCampaignNumber to the Campaign
|| 03/30/22     MCM 22.04.x  (593664) Added doNotUseSSO (screen calls is Do Not use SAML/SSO Authentication) to contact 
|| 05/25/22     GHL 22.06.x  (451878) Added glcExchangeRate for client and vendor invoices
|| 06/21/22     RLS 22.07.x  (603837) Added CopyCampaignFiles to the campaigns section
|| 07/07/22     QMD 22.07.24 (602949) Added userId to the Team endpoint
|| 07/11/22     MCM 22.08.x  (595350) Added GLCompanies to the vendor 
|| 07/26/22		MCM 22.08.x  (606848) Removed action from the task import. It was for assignments and causes confustion.
|| 07/22/22     GHL 22.08.00 (604153) Added tTime.Overtime
|| 08/10/22	    MCM 22.09.x  (606828) Updated Voucher to include custom fields on both header and detail
|| 08/10/22	    RLB 22.09.x  (607677) added tVendor.EmailACHToAddress
|| 09/08/22     RLB 22.10.x  (611239) Added Subject to project spec sheet import section
|| 09/21/22     MCM 22.10.x  (612989) Adding class ID Line back into the voucher.  Accidently got removed
|| 09/21/22     RLB 22.10.x  (611076) added Vendor Overtime Cost and Overtime Cost
|| 09/21/22     RLB 22.11.x  (607483) added Contractor to employee import
|| 10/11/22     MCM 22.11.x  (613579) Updated Credit card charge fields to allow for multiple details (expenses and vouchers)
|| 11/07/22     MCM 22.12.x  (618337) updated description to descriptionLine when have to map
|| 11/17/22     MCM 22.12.x  (619769) updated the linked fields (Reference Number in credit card charges and Check Number in vendor payment) to be required as well.
|| 11/30/22     MCM 22.12.x  (613579) Added office line for the credit card charges
|| 12/05/22     MCM 22.12.x  (622066) Removed the reference number as a required field.  The vb will fill on in if none passed in.
|| 01/06/23		MCM 23.02.x  (621970) Added Primary contact and billing contact to client/company
|| 01/30/23     MCM 23.02.x  (628296) Added update ability to vendor payment and receipts
|| 02/14/23     GAR 23.04.x  (DEV2605-MAIN) Added export for Avalara Tax Codes
|| 04/04/23     MCM 23.05.x  (636756) Added bank account type to the vendor import
|| 05/24/23     CRG 23.06.18 (604775) Added documentation for new Task Priority values
|| 06/02/23		MCM 23.06.18 (639431) Added new Credit Card charge fields for multicurrency fields
|| 07/17/23		MCM 23.08.x  (643701) Added long description to the estimate import
|| 08/21/23     MCM 23.09.x  (643543) Added Predecessor Lag field to the task Import
|| 09/07/23     MCM 23.10.x  (649355) Changed name on voucher from Department to "Department (Line)"
|| 10/31/23     RLB 23.11.19 (654959) added missing parms for graph import
|| 11/08/23		MCM 23.12.x  (655841) Added MustFinishOnPredComplete to the Task
*/





END


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptTaskUserGetTaskList2]'
GO
IF OBJECT_ID(N'[dbo].[sptTaskUserGetTaskList2]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptTaskUserGetTaskList2]
 (  
 @UserKey int  
 ,@PredecessorsComplete int -- 0 All or 1 PredecessorsComplete only    
 ,@DateOption int   
 ,@IncludeActivities tinyint = 0  
 ,@Completed tinyint = 0
 ,@RestrictActivitiesToAssigned tinyint = 0 --If 1, only activites that are assigned to @UserKey, or are not assigned at all will be returned
 ,@OpenToDoOnly tinyint = 0
 ,@OpenDeliverablesOnly tinyint = 0
 ,@ProjectKey int = NULL -- NULL = any ProjectKey that fits the other filters, > 0 = filter for only this ProjectKey, -1 = filter for only ProjectKeys in #ProjectKeys
 ,@WKStartDate smalldatetime
 ,@WKEndDate smalldatetime
 ,@DefaultTimeStart datetime = null
 )  
AS --Encrypt  
  
 SET NOCOUNT ON  
  
/*  
|| When     Who Rel      What  
|| 01/14/14 GWG 10.5.7.6 Created for today page in new app
|| 04/28/14	MAS 10.5.7.6 Copied sptTaskUserGetTaskList and modified for the new app adding the count(*)s for the
||                       (!) XX New Update counts in the Today Task cards
|| 07/10/14 MAS 10.5.8.1 (222322) Exclude tasks that are already included in the user''s favorites
|| 07/31/14 QMD 10.5.8.2 Changed User.Today.MyTasks to today.creative.myTasks
|| 01/13/14 MAS 10.5.8.8 (242143)Added security to check if the user has the prjViewOtherToDos right.
|| 04/20/15 GWG 10.5.9.1 Added a hook out to deliverables through the taskuser record.
|| 08/18/15 MCM 10.5.9.5 (266562) Added is null logic to Campaign and CampaignFullName to show No Campaign
|| 09/09/15 RLB 10.5.9.6 added OldPercComp in case it needs to be reset
|| 12/31/15 RLB 10.5.9.9 (273258) added for grouping enhancement
|| 01/06/16 MCM 10.5.9.9 Removed where clause that excluding items that were in the user''s favorites (az DEV1730)
|| 02/22/16 MFT 10.6.0.1 (289064) Added PercCompSeparate
|| 05/27/16 GWG 10.6.0.4 Added appfavoritekey to highlight favorited tasks
|| 11/16/16 RLB 10.6.1.0 (321059) added default Rate level
|| 12/15/16 MCM 10.6.1.1 (315980) added the ProjectCustomFieldKey so we can add project custom fields to the today.creative page
|| 11/05/18  RLS 18.9.3  (428022) Use tu.APlanStart and tu.APlanComplete if they''re populated in place of t.PlanStart & t.PlanComplete
|| 04/10/19 CRG 19.0.5.0 (454523) Added PlanningProject
|| 07/30/19 RLB 19.0.8.0 (471378) Added project manager options to today creative 
|| 01/22/20 GHL 20.0.2.0 (495402) Moved update of PlanningProject and CustomFieldKey at the end, so that they use a smaller set of tasks
|| 02/07/20 GAR 20.0.3.0 (499184) If Open Deliverables Only flag is on, then delete all projects that don''t have an open deliverable
|| 02/13/20 RLB 20.0.3.0 (500992) added count for activites linked to a task
|| 03/18/20 GAR 20.0.4.0 (506143) Added project start date and project complete date
|| 11/02/20 RLS 20.1.2.0 (535729) Changed TaskDescription to nvarchar
|| 11/17/20 RLS 20.1.2.0 (535729) Changed TaskName to nvarchar
|| 01/04/21 RLS 21.0.1.0 (542041) Added AND ss.Status <> 5 to the "get spec sheets" section of UpdateCount. This is to exclude revised spec sheets from the count of unread spec sheets. This will keep it consistent with the listing page that does not show status 5.
|| 02/11/21 RLS 21.0.3.0 (535729) Changed TaskIDName to nvarchar
|| 02/11/21 RLS 21.0.3.0 (535729) Changed SummaryTaskName and SummaryTask to nvarchar
|| 02/15/21 RLB 21.0.3.0  Noticed Error when checked what data pulled for issue (548304) no bug created but should be pulled into latest
|| 03/08/21 RLS 21.0.4.0 (551203) TaskDescription to NVARCHAR(MAX)
|| 04/30/21 CRG 21.05.16 (556855) Added @ProjectKey to handle real time notification updates
|| 07/19/21 RLS 21.0.8.0 (559791) Added TaskUserStatusKey and TaskUserStatusName
|| 07/26/21 RLS 21.0.8.0 (566012) Changed the update to TaskUserStatusKey and TaskUserStatusName to use the view
|| 08/31/21 RLS 21.0.9.0 (564254) Changed TaskID to nvarchar
|| 10/28/21 RLB 21.11.14 (570179 added worked this week and remaining for just current week
|| 02/11/22 AMP xx.xx.xx (DEV2506-485) Changed the Open To Do count to be the To Dos that are not tied to a deliverable
|| 04/11/22 RLB 22.05.15 (594696) change pull count of open deliverables off Completed from approved
|| 04/27/22 RLB 22.04.17 (596854) removed deliverablekey filter to dos on deliverable 
|| 06/07/22 RLB 22.07.17 (598422) when pulling all task without completed pred check limit it to tasks that start after 3 months from todays date
|| 06/16/22 CRG 22.07.17 (603297) Modified OpenToDos to use new rollup table
|| 06/27/22 WDF 22.07.17 (603776) Added KeyPeople
|| 07/17/22 RLB 22.07.17 (598422) fixed it should only limit it when @PredecessorsComplete = 0
|| 07/19/22 RLB 22.07.17 (606316) fixed issue where task with no to do''s would appear when the open to show just tasks with to do''s option was checked
|| 07/22/22 RLB 22.07.17 (606613) change the filter to not pull tasks that start after 6 weeks in the future 
|| 10/13/22 RLB 22.11.20 (610106) added pull of LimitProjectServices
|| 11/14/22 RLB 22.12.18 (618115)  maybe project type into a select list on myTasks
|| 12/14/22 GAR 23.01.15 (623551) Update comments for UpdateCount - let others know other SPs to update
|| 03/21/23 RLB 23.04.16 (632084) added timeline segment
|| 04/03/23 RLB 23.05.14 (633964) Added product name for grouping
|| 05/08/23 CRG 23.06.18 (604775) Now using tTaskPriority
|| 09/27/23 RLS 23.10.15 (650572) Added DetailedNotes field
|| 06/12/24 RLB 24.07.14 (670085) changed AssignedPercComp to be just task user perc comp changed actual hours to included todays entered hours. Added week actualhourstoday
|| 08/28/24 CRG 24.10.20 (681784) Added #ProjectKeys temp table to allow RTN updates of multiple ProjectKeys at one time
|| 09/26/24 RLB 24.10.20 (683962) Changed Priority pull to the display order not the Key
|| 10/15/24 GAR 24.10.20 (683966) Added ProjectColor to today.creatives
|| 02/07/25 RLB 25.03.16 (694579) fixed actual wk hours not seperating actual time on the same task user but with different hours issue
|| 06/27/25 RLS 25.07.20 (701652) Added AllTaskUsers
|| 08/08/25 RLS 25.09.14 (708527) Added ISNULL() to tu.PerComp
|| 08/19/25 RLS 25.09.14 (708120) Added ConversationCount
|| 09/02/25 RLB 25.09.14 (708120) moved count out of main pull just did in update for speed
|| 10/28/25 RLS 25.11.16 (711139) Added AllTaskUserNames
|| 11/10/25 RLS 25.11.16 (715509) Changed AllTaskUserNames in the temp table to NVARCHAR(4000) to match the substring length in the update statement. Fix for above issue (711139) where the field was added
|| 03/31/26 GAR 26.04.19 (723332) Added ProjectStatusColor
*/
  
/*
		ATTENTION: BE CAREFUL WHEN PULLING DATA DURING INITIAL QUERY
		THE DATA HAS TO BE PART OF AN INDEX
		IF IT IS NOT, THIS WILL RESULT IN PERFORMANCE DEGRADATION
		ON THE MY TASKS WIDGET
*/

declare @SecurityGroupKey int, @Administrator tinyint

Select @SecurityGroupKey = SecurityGroupKey,  @Administrator = ISNULL(Administrator, 0) from tUser (nolock) Where UserKey = @UserKey

IF object_id(''tempdb..#projectTypeKeys'') IS NULL
		CREATE TABLE #projectTypeKeys (ProjectTypeKey int NULL)

DECLARE @AllProjectTypes int

if (Select  count(*) from #projectTypeKeys) = 0
		Select @AllProjectTypes = 0
	else
		Select @AllProjectTypes = 1

  
CREATE TABLE #tTask (TaskUserKey INT NULL  
     --,ClientKey INT NULL  
     ,ProjectKey INT NULL  
     ,CampaignKey INT NULL  
    ,BudgetTaskKey INT NULL
     ,TaskKey INT NULL  
     ,UserKey INT NULL  
     ,ServiceKey INT NULL  
     ,AssignedServiceKey INT NULL  
     --,ProjectNumber VARCHAR(50) NULL  
     --,ProjectName VARCHAR(100) NULL  
     --,ProjectFullName VARCHAR(155) NULL  
     --,BillingContact INT NULL  
     ,ProjectStatus VARCHAR(300) NULL
     ,TaskID NVARCHAR(30) NULL  
     ,TaskName NVARCHAR(500) NULL  
     ,TaskIDName NVARCHAR(535) NULL  
     --,AccountManagerName VARCHAR(500) NULL  
     
     ,DetailTaskKey INT NULL --Used by TimeEntryWidget  
     ,DetailTaskName VARCHAR(500) NULL --Used by TimeEntryWidget  
     ,BudgetTaskID NVARCHAR(30) NULL --Used by TimeEntryWidget  
       
     ,TaskDescription NVARCHAR(MAX) NULL  
     ,PlanStart SMALLDATETIME NULL  
     ,PlanComplete SMALLDATETIME NULL  
     ,PlanDuration  INT NULL
	 ,BaseStart SMALLDATETIME null
	 ,BaseComplete SMALLDATETIME null
     
     ,ScheduleNote VARCHAR(200) NULL  
     ,Comments VARCHAR(4000) NULL  
     ,DueBy VARCHAR(200) NULL  
     ,TaskStatus SMALLINT NULL  
     ,Priority INT NULL
     ,PriorityName NVARCHAR(100) NULL
     ,TaskType SMALLINT NULL  -- Needed for task status renderer 
     ,TaskTypeDesc VARCHAR(200) NULL   
     ,ScheduleTask SMALLINT NULL -- Needed for task status renderer  
     ,TimeActive SMALLINT NULL -- need to distinguish if this row allows time
     
     ,PredecessorsComplete INT NULL  
     ,PercComp INT NULL -- From tTaskUser  
     ,PercCompSeparate TINYINT NULL
     ,ActStart SMALLDATETIME NULL  
     ,ActComplete SMALLDATETIME NULL  
     ,AssignedPercComp INT NULL  
       
     ,AssignedHours DECIMAL(24, 4) NULL  
     ,ActualHours DECIMAL(24, 4) NULL
	 ,RemainingHours DECIMAL(24, 4) NULL

	 ,WKActualHours DECIMAL(24, 4) NULL  
	 ,WKActualHoursBefore DECIMAL(24, 4) NULL 
	 ,WKDisplayHours DECIMAL(24, 4) NULL
	 ,WKRemainingHours DECIMAL(24, 4) NULL
	 ,WKActualHoursToday DECIMAL(24, 4) NULL

     ,TrackBudget TINYINT NULL
     ,ProjectOrder INT NULL
     ,SummaryTaskKey INT NULL
     ,SummaryTaskID NVARCHAR(30) NULL  
     ,SummaryTaskName NVARCHAR(500) NULL  
     ,SummaryTask NVARCHAR(535) NULL
     ,ProjectTypeKey INT NULL
     ,ProjectTypeName VARCHAR(100) NULL
     ,OpenToDos INT NULL
     ,CustomFieldKey INT NULL
	 ,OpenDeliverables INT NULL
	 ,TaskUserStatusKey int NULL
	 ,TaskUserStatusName VARCHAR(200) NULL
	 ,TimelineSegmentKey int NULL
	 ,ProjectColor VARCHAR(10) NULL
	 ,ConversationCount INT NULL
	 ,AllTaskUsers TEXT NULL
	 ,AllTaskUserNames NVARCHAR(4000) NULL
     )  
CREATE TABLE #tTime (TaskKey INT NULL, DetailTaskKey INT NULL, ServiceKey INT NULL, ActualHours DECIMAL(24, 4) NULL)  

DECLARE @CompanyKey INT, @RateLevel INT, @ShowActualHours INT
DECLARE @EndDate SMALLDATETIME, @BeginDate SMALLDATETIME
  
SELECT @CompanyKey = ISNULL(OwnerCompanyKey, CompanyKey)
      ,@RateLevel = RateLevel
FROM   tUser (NOLOCK)
WHERE  UserKey = @UserKey
  
Select @ShowActualHours = ISNULL(ShowActualHours, 0)
From   tPreference (nolock) 
Where  CompanyKey = @CompanyKey

SELECT @DefaultTimeStart = ISNULL(@DefaultTimeStart, GETDATE())
  
if @Completed = 0
BEGIN
	/*  
	DateOption  
	0:Due on or before Today  
	1:Due on or before a week from Today  
	2:Due on or before 2 weeks from Today  
	3:Start on or before Today  
	4:Start on or before a week from Today  
	5:Start on or before 2 weeks from Today  
	6:All  
	*/  
	  
	IF @DateOption IN (0, 3)   
	 SELECT @EndDate = GETDATE()   
	IF @DateOption IN (1, 4)  
	BEGIN   
	 SELECT @EndDate = GETDATE()   
	 SELECT @EndDate = DATEADD(day, 7, @EndDate)  
	END  
	IF @DateOption IN (2, 5)  
	BEGIN   
	 SELECT @EndDate = GETDATE()   
	 SELECT @EndDate = DATEADD(day, 14, @EndDate)  
	END 
	IF @DateOption = 6
	 SELECT @EndDate = GETDATE()
	  
	-- remove hours   
	SELECT @EndDate = CONVERT(SMALLDATETIME, CONVERT(VARCHAR(10), @EndDate, 101), 101)
	SELECT @BeginDate = DATEADD(week, 6, @EndDate) 

-- First do insert with minimum fields, all these fields MUST BE in indexes!!!!!!!!!!!!!
-- DO NOT GENERATE TABLE SCANS HERE
	if @PredecessorsComplete = 1
		INSERT #tTask (
			-- keys
			TaskUserKey, ProjectKey, CampaignKey, TaskKey ,DetailTaskKey, UserKey, ServiceKey, AssignedServiceKey   
			-- project status info
		   ,ProjectStatus, TimeActive, ProjectTypeKey
		   -- task info  
		   ,PlanStart,PlanComplete,PlanDuration, PredecessorsComplete  
		   -- task user info
		   ,PercComp,PercCompSeparate,ActStart,ActComplete,AssignedPercComp,AssignedHours,TimelineSegmentKey
		   )  
		SELECT tu.TaskUserKey, t.ProjectKey, p.CampaignKey, t.TaskKey, t.TaskKey, tu.UserKey, ISNULL(tu.ServiceKey, u.DefaultServiceKey), tu.ServiceKey
		  , ps.ProjectStatus, ps.TimeActive, 0 -- ,p.ProjectTypeKey -- removed by Gil because not part of an index
		  , ISNULL(tu.APlanStart, t.PlanStart), ISNULL(tu.APlanComplete, t.PlanComplete),t.PlanDuration ,t.PredecessorsComplete
		  ,ISNULL(tu.PercComp, 0),ISNULL(t.PercCompSeparate, 0),tu.ActStart,tu.ActComplete  
		  ,ISNULL(tu.PercComp, 0)
		  ,tu.Hours,t.TimelineSegmentKey
		FROM   tTask t (NOLOCK)  
		inner join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey  
		inner join tProject p (nolock) on p.ProjectKey = t.ProjectKey  
		inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey  
		inner join tUser u (nolock) on tu.UserKey = u.UserKey
		Where tu.UserKey = @UserKey
		And p.CompanyKey = @CompanyKey   
		AND (@ProjectKey IS NULL 
			OR p.ProjectKey = @ProjectKey
			OR (@ProjectKey = -1 AND p.ProjectKey IN (SELECT ProjectKey FROM #ProjectKeys)))
		And p.Closed = 0   
		AND p.Active = 1
		And ISNULL(ps.OnHold, 0) = 0   
		And (  
		 (ISNULL(t.PercCompSeparate, 0) = 0 and ISNULL(t.PercComp, 0) < 100)   
		  Or   
		 (ISNULL(t.PercCompSeparate, 0) = 1 and ISNULL(tu.PercComp, 0) < 100)  
		 )  
		And t.PredecessorsComplete >= @PredecessorsComplete  
		And (  
		 (@DateOption = 6)  
          Or 
		 (@DateOption IN (0, 1, 2) AND ISNULL(tu.APlanComplete, t.PlanComplete) <= @EndDate)  
		  Or  
		 (@DateOption IN (3, 4, 5) AND ISNULL(tu.APlanStart, t.PlanStart) <= @EndDate )  
		 )  
	else 
		INSERT #tTask (
			-- keys
			TaskUserKey, ProjectKey, CampaignKey, TaskKey ,DetailTaskKey, UserKey, ServiceKey, AssignedServiceKey   
			-- project status info
		   ,ProjectStatus, TimeActive, ProjectTypeKey
		   -- task info  
		   ,PlanStart,PlanComplete,PlanDuration, PredecessorsComplete  
		   -- task user info
		   ,PercComp,PercCompSeparate,ActStart,ActComplete,AssignedPercComp,AssignedHours,TimelineSegmentKey
		   )  
		SELECT tu.TaskUserKey, t.ProjectKey, p.CampaignKey, t.TaskKey, t.TaskKey, tu.UserKey, ISNULL(tu.ServiceKey, u.DefaultServiceKey), tu.ServiceKey
		  , ps.ProjectStatus, ps.TimeActive, 0 -- ,p.ProjectTypeKey -- removed by Gil because not part of an index
		  , ISNULL(tu.APlanStart, t.PlanStart), ISNULL(tu.APlanComplete, t.PlanComplete),t.PlanDuration ,t.PredecessorsComplete
		  ,ISNULL(tu.PercComp, 0),ISNULL(t.PercCompSeparate, 0),tu.ActStart,tu.ActComplete  
		  ,ISNULL(tu.PercComp, 0)
		  ,tu.Hours,t.TimelineSegmentKey
		FROM   tTask t (NOLOCK)  
		inner join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey  
		inner join tProject p (nolock) on p.ProjectKey = t.ProjectKey  
		inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey  
		inner join tUser u (nolock) on tu.UserKey = u.UserKey
		Where tu.UserKey = @UserKey
		And p.CompanyKey = @CompanyKey   
		AND (@ProjectKey IS NULL 
			OR p.ProjectKey = @ProjectKey
			OR (@ProjectKey = -1 AND p.ProjectKey IN (SELECT ProjectKey FROM #ProjectKeys)))
		And p.Closed = 0   
		AND p.Active = 1
		And ISNULL(ps.OnHold, 0) = 0   
		And (  
		 (ISNULL(t.PercCompSeparate, 0) = 0 and ISNULL(t.PercComp, 0) < 100)   
		  Or   
		 (ISNULL(t.PercCompSeparate, 0) = 1 and ISNULL(tu.PercComp, 0) < 100)  
		 )  
		And t.PredecessorsComplete >= @PredecessorsComplete  
		And (  
		 (@DateOption = 6 AND  ISNULL(tu.APlanStart, t.PlanStart) <= @BeginDate)  
		  Or  
		 (@DateOption IN (0, 1, 2) AND ISNULL(tu.APlanComplete, t.PlanComplete) <= @EndDate)  
		  Or  
		 (@DateOption IN (3, 4, 5) AND ISNULL(tu.APlanStart, t.PlanStart) <= @EndDate )  
		 )  

END
ELSE
BEGIN

	/*  
	DateOption    
	1:In the last 1 week
	2:In the last 2 week
	3:In the last 3 week
	*/  
	  
	SELECT @EndDate = CONVERT(SMALLDATETIME, CONVERT(VARCHAR(10), GETDATE(), 101), 101)  
	SELECT @BeginDate = DATEADD(week, -1 * @DateOption, @EndDate)   

	INSERT #tTask (
		-- keys
		TaskUserKey, ProjectKey, CampaignKey, TaskKey ,DetailTaskKey, UserKey, ServiceKey, AssignedServiceKey
		-- project status info
	   ,ProjectStatus, TimeActive, ProjectTypeKey
	   -- task info  
	   ,PlanStart,PlanComplete,PlanDuration, PredecessorsComplete  
	   -- task user info
	   ,PercComp,PercCompSeparate,ActStart,ActComplete,AssignedPercComp,AssignedHours,TimelineSegmentKey 
	   )  
	SELECT tu.TaskUserKey, t.ProjectKey, p.CampaignKey, t.TaskKey, t.TaskKey, tu.UserKey, ISNULL(tu.ServiceKey, u.DefaultServiceKey), tu.ServiceKey 
	  , ps.ProjectStatus, ps.TimeActive, 0 -- ,p.ProjectTypeKey -- removed by Gil because not part of an index
	  , ISNULL(tu.APlanStart, t.PlanStart), ISNULL(tu.APlanComplete, t.PlanComplete),t.PlanDuration ,t.PredecessorsComplete
	  ,ISNULL(tu.PercComp, 0),ISNULL(t.PercCompSeparate, 0),tu.ActStart,tu.ActComplete  
	  ,ISNULL(tu.PercComp,0)
	  ,tu.Hours,t.TimelineSegmentKey
	FROM   tTask t (NOLOCK)  
	inner join tTaskUser tu (nolock) on t.TaskKey = tu.TaskKey  
	inner join tProject p (nolock) on p.ProjectKey = t.ProjectKey  
	inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey  
	inner join tUser u (nolock) on tu.UserKey = u.UserKey
	Where tu.UserKey = @UserKey
	AND p.CompanyKey = @CompanyKey   
	AND (@ProjectKey IS NULL 
		OR p.ProjectKey = @ProjectKey
		OR (@ProjectKey = -1 AND p.ProjectKey IN (SELECT ProjectKey FROM #ProjectKeys)))
	AND p.Closed = 0   
	AND p.Active = 1
	AND ISNULL(ps.OnHold, 0) = 0   
	AND (  
	 (ISNULL(t.PercCompSeparate, 0) = 0 and ISNULL(t.PercComp, 0) = 100)   
	  Or   
	 (ISNULL(t.PercCompSeparate, 0) = 1 and ISNULL(tu.PercComp, 0) = 100)  
	 )  
	AND ISNULL(tu.APlanStart, t.PlanStart) <= @EndDate 
	AND ISNULL(tu.APlanComplete, t.PlanComplete) >= @BeginDate  

END

-- After initial queries, delete as many records as we can based on filters
UPDATE	#tTask
SET		#tTask.ProjectTypeKey = p.ProjectTypeKey
		,#tTask.ProjectTypeName = pt.ProjectTypeName
FROM	tProject p (NOLOCK)
	    LEFT OUTER JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey 
WHERE	#tTask.ProjectKey = p.ProjectKey

if @AllProjectTypes = 1
	delete #tTask where isnull(ProjectTypeKey, 0) not in (Select ProjectTypeKey from #projectTypeKeys)

if ((@Administrator = 1) OR exists (Select 1 from tRightAssigned (nolock) Where RightKey = 90933 and EntityType = ''Security Group'' and EntityKey = @SecurityGroupKey))
	begin
		-- Can see all the todos
		update #tTask
		set    #tTask.OpenToDos = (SELECT SUM(r.OpenToDoCount) FROM tOpenToDoRollup r (nolock) WHERE r.TaskKey = #tTask.TaskKey)
	end
else
	begin
		-- Can only see their todos
		update #tTask
		set    #tTask.OpenToDos = (SELECT SUM(r.OpenToDoCount) FROM tOpenToDoRollup r (nolock) WHERE r.TaskKey = #tTask.TaskKey AND (r.AssignedUserKey = @UserKey or ISNULL(r.AssignedUserKey, 0) = 0))
	end	

-- set opentodos to 0 where it is null 606316
update #tTask set OpenToDos = 0 where OpenToDos IS NULL

if isnull(@OpenToDoOnly, 0) > 0
	delete #tTask where OpenToDos = 0

-- 499184 - GAR - If Open Deliverables Only flag is on, then delete all projects that don''t have an open deliverable
update #tTask
set    #tTask.OpenDeliverables = (
	select count(*) 
	from   tReviewDeliverable d (nolock)
	where  #tTask.TaskKey = d.TaskKey
	and    ISNULL(d.Completed,0) = 0
)

if isnull(@OpenDeliverablesOnly, 0) > 0
	delete #tTask where OpenDeliverables = 0

-- Only now get missing info on a smaller number of tasks

-- get task info, I prefer to do a separate join 
update #tTask
set    #tTask.TaskID = t.TaskID
	  ,#tTask.TaskName = t.TaskName
      ,#tTask.TaskIDName = ISNULL(t.TaskID, '''') + ''-'' + ISNULL(t.TaskName, '''')
      ,#tTask.DetailTaskName = t.TaskName
      ,#tTask.TaskDescription = t.Description
      ,#tTask.ScheduleNote = t.ScheduleNote
      ,#tTask.Comments = t.Comments
      ,#tTask.DueBy = t.DueBy
      ,#tTask.TaskStatus = t.TaskStatus
      ,#tTask.Priority = tp.DisplayOrder
      ,#tTask.PriorityName = tp.PriorityName
      ,#tTask.TaskType = t.TaskType
      ,#tTask.TaskTypeDesc = ta.TaskAssignmentType
      ,#tTask.ScheduleTask = t.ScheduleTask
      ,#tTask.TrackBudget = t.TrackBudget
      ,#tTask.ProjectOrder = t.ProjectOrder
      ,#tTask.BudgetTaskKey = t.BudgetTaskKey
      ,#tTask.SummaryTaskKey = st.TaskKey
      ,#tTask.SummaryTaskID = st.TaskID
      ,#tTask.SummaryTaskName = st.TaskName
      ,#tTask.SummaryTask = ISNULL(st.TaskID, '''') + ''-'' + ISNULL(st.TaskName, '''')
	  ,#tTask.BaseStart = t.BaseStart
	  ,#tTask.BaseComplete = t.BaseComplete

from   tTask t (nolock)
left outer join tTask st (NOLOCK) on t.SummaryTaskKey = st.TaskKey
left outer join tTaskAssignmentType ta (NOLOCK) on ta.TaskAssignmentTypeKey = t.TaskAssignmentTypeKey
left outer join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey
where  #tTask.TaskKey = t.TaskKey

    
update #tTask
set    #tTask.BudgetTaskID = bt.TaskID
from   tTask bt (nolock)
where  #tTask.BudgetTaskKey = bt.TaskKey

  
-- added to pull actaul hrs entered today
declare @TodayStartDate as datetime , @TodayEndDate as DateTime
select @TodayStartDate = CAST(CAST(GETDATE() as date) as datetime)
select @TodayEndDate = DATEADD(day, 1, @TodayStartDate)
select @TodayEndDate = DATEADD(second,-1, @TodayEndDate)

IF @ShowActualHours = 1
BEGIN
	INSERT #tTime (TaskKey, DetailTaskKey, ServiceKey, ActualHours)  
	SELECT ti.TaskKey, ti.DetailTaskKey, ti.ServiceKey, ti.ActualHours   
	FROM tTime ti WITH (INDEX=IX_tTime_1, NOLOCK)  
		,(select Distinct(TaskKey) from #tTask (nolock)) as ta     
	WHERE ti.UserKey = @UserKey  
	AND   (ti.TaskKey = ta.TaskKey OR ti.DetailTaskKey = ta.TaskKey)
	
	UPDATE #tTask  
	SET    #tTask.ActualHours = ISNULL(  
       (SELECT SUM(ti.ActualHours) FROM #tTime ti   
       WHERE (ti.TaskKey = #tTask.TaskKey OR ti.DetailTaskKey = #tTask.TaskKey))   
       ,0)  

	   -- wk data
	UPDATE #tTask  
		SET    #tTask.WKActualHours = t.ActualHours 
		FROM   
				(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours   
				FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
						FROM	tTime ti (NOLOCK)
						INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
						WHERE	ti.UserKey = @UserKey
						AND		ti.WorkDate <= @WKEndDate
						AND     ti.WorkDate >= @WKStartDate
						AND		((ti.WorkDate <= dbo.fFormatDateNoTime(@DefaultTimeStart) AND Verified = 1) OR Verified = 0)) alltime
				GROUP BY DetailTaskKey) t
		WHERE	t.DetailTaskKey = #tTask.TaskKey

			-------- get all actual hours before the start of this week
	UPDATE	#tTask  
		SET		#tTask.WKActualHoursBefore = tb.ActualHours 
		FROM	
				(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours
				FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
						FROM	tTime ti (NOLOCK)
						INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
						WHERE	ti.UserKey = @UserKey
						AND		ti.WorkDate < @WKStartDate) alltime
				GROUP BY DetailTaskKey) tb
		WHERE	tb.DetailTaskKey = #tTask.TaskKey

	UPDATE #tTask  
		SET    #tTask.WKActualHoursToday = t.ActualHours 
		FROM   
				(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours   
				FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
						FROM	tTime ti (NOLOCK)
						INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
						WHERE	ti.UserKey = @UserKey
						AND		ti.WorkDate <= @TodayEndDate
						AND     ti.WorkDate >= @TodayStartDate
						) alltime
				GROUP BY DetailTaskKey) t
		WHERE	t.DetailTaskKey = #tTask.TaskKey

END
ELSE
BEGIN

	INSERT #tTime (TaskKey, DetailTaskKey, ServiceKey, ActualHours)  
	SELECT ti.TaskKey, ti.DetailTaskKey, ti.ServiceKey, ti.ActualHours   
	FROM tTime ti WITH (INDEX=IX_tTime_1, NOLOCK)  
		,#tTask ta     
	WHERE ti.UserKey = @UserKey  
	AND   (ti.TaskKey = ta.TaskKey OR ti.DetailTaskKey = ta.TaskKey)
	AND   (ta.AssignedServiceKey is null OR ti.ServiceKey = ta.AssignedServiceKey)

	UPDATE #tTask  
	SET    #tTask.ActualHours = ISNULL(  
       (SELECT SUM(ti.ActualHours) FROM #tTime ti   
       WHERE (ti.TaskKey = #tTask.TaskKey OR ti.DetailTaskKey = #tTask.TaskKey) AND (#tTask.AssignedServiceKey is null OR ti.ServiceKey = #tTask.AssignedServiceKey))   
       ,0)  

	--- wk data
	UPDATE	#tTask  
		SET		#tTask.WKActualHours = t.ActualHours 
		FROM	
				(SELECT	DetailTaskKey, ServiceKey, SUM(ActualHours) AS ActualHours
				FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.ServiceKey, ti.WorkDate, ti.ActualHours
						FROM	tTime ti (NOLOCK)
						INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
						WHERE	ti.UserKey = @UserKey
						AND		ti.WorkDate <= @WKEndDate
						AND		ti.WorkDate >= @WKStartDate
						AND		ti.WorkDate <= dbo.fFormatDateNoTime(@DefaultTimeStart)
						AND		(ta.AssignedServiceKey is null
								OR
								ti.ServiceKey = ta.AssignedServiceKey)) alltime
				GROUP BY DetailTaskKey, ServiceKey) t
		WHERE	t.DetailTaskKey = #tTask.TaskKey and (#tTask.AssignedServiceKey is null OR t.ServiceKey = #tTask.AssignedServiceKey)

		---------- get all actual hours before the start of this week
		UPDATE #tTask  
		SET    #tTask.WKActualHoursBefore = ti.ActualHours 
		FROM   
				(SELECT	DetailTaskKey, ServiceKey, SUM(ActualHours) AS ActualHours  
				FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.ServiceKey, ti.WorkDate, ti.ActualHours
						FROM	tTime ti (NOLOCK)
						INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
						WHERE	ti.UserKey = @UserKey
						AND		ti.WorkDate < @WKStartDate
						AND		(ta.AssignedServiceKey is null
								OR
								ti.ServiceKey = ta.AssignedServiceKey)) alltime
				GROUP BY DetailTaskKey, ServiceKey) ti
		WHERE	ti.DetailTaskKey = #tTask.TaskKey and (#tTask.AssignedServiceKey is null OR ti.ServiceKey = #tTask.AssignedServiceKey)

		UPDATE	#tTask  
		SET		#tTask.WKActualHoursToday = t.ActualHours 
		FROM	
				(SELECT	DetailTaskKey, ServiceKey, SUM(ActualHours) AS ActualHours
				FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.ServiceKey, ti.WorkDate, ti.ActualHours
						FROM	tTime ti (NOLOCK)
						INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
						WHERE	ti.UserKey = @UserKey
						AND		ti.WorkDate <= @TodayEndDate
						AND		ti.WorkDate >= @TodayStartDate
						AND		(ta.AssignedServiceKey is null
								OR
								ti.ServiceKey = ta.AssignedServiceKey)) alltime
				GROUP BY DetailTaskKey, ServiceKey) t
		WHERE	t.DetailTaskKey = #tTask.TaskKey and (#tTask.AssignedServiceKey is null OR t.ServiceKey = #tTask.AssignedServiceKey)
END  

UPDATE #tTask
SET #tTask.RemainingHours = ISNULL(#tTask.AssignedHours, 0) - ISNULL(#tTask.ActualHours, 0)

update #tTask
set    #tTask.CustomFieldKey = p.CustomFieldKey, #tTask.ProjectColor = p.ProjectColor
from   tProject p (nolock)
where  #tTask.ProjectKey = p.ProjectKey



UPDATE	#tTask
			SET		TaskUserStatusKey = vtus.TaskUserStatusKey
			FROM	vTaskUserStatus vtus (nolock)
			WHERE	vtus.TaskUserKey = #tTask.TaskUserKey


UPDATE	#tTask
			SET		TaskUserStatusName = tus.StatusName
			FROM	vTaskUserStatus vtus (nolock)
			INNER JOIN tTaskUserStatus tus on vtus.TaskUserStatusKey = tus.TaskUserStatusKey
			WHERE	vtus.TaskUserKey = #tTask.TaskUserKey

UPDATE	#tTask
			SET		WKDisplayHours = v.Hours
			FROM	#tTask t
			INNER JOIN vTaskUserHour v ON t.TaskUserKey = v.TaskUserKey
			WHERE	v.BucketStart BETWEEN @WKStartDate AND @WKEndDate

UPDATE #tTask
SET #tTask.WKRemainingHours = ISNULL(#tTask.WKDisplayHours, 0) - ISNULL(#tTask.WKActualHours, 0)

--- (708120) removed from main pull for speed RLB just do update here
update #tTask
set    #tTask.ConversationCount = (
	select count(*) 
	from    tActivity a (nolock)
	inner join tActivityLink al (nolock) on a.ActivityKey = al.ActivityKey
	Where al.Entity = ''tTask'' and al.EntityKey  = #tTask.TaskKey
	and a.ParentActivityKey = 0 and a.ActivityEntity = ''Diary''
)


update #tTask 
set AllTaskUsers = (
Substring((Select '',''+ LTRIM(str(ttu.UserKey))  AS [text()]   
            From tTaskUser ttu
			WHERE ttu.TaskKey = #tTask.TaskKey
            For XML PATH ('''')),2, 4000) 

)

update #tTask
set AllTaskUserNames = (
	Substring((Select '',''+ LTRIM(vu.UserFullName) AS [text()]   
            From vUserName vu (nolock)
			INNER JOIN tTaskUser ttusr (nolock) on vu.UserKey = ttusr.UserKey
			WHERE ttusr.TaskKey = #tTask.TaskKey
            For XML PATH ('''')),2, 4000)
)

update #tTask set ConversationCount = 0 where ConversationCount IS NULL




-- And final query
SELECT t.* 
	,ISNULL(c.CustomerID, '''''''') as ClientID
	,c.CompanyName as ClientName
	,c.Phone,c.CustomerID + ''-'' + c.CompanyName as ClientFullName   
	,p.DetailedNotes
    ,p.ProjectNumber
    ,p.ProjectName
    ,p.ProjectNumber + ''-'' + p.ProjectName AS ProjectFullName
	,p.LimitProjectServices

    ,cp.CampaignID
    ,ISNULL(cp.CampaignName, ''No Campaign'') as CampaignName
    , CASE WHEN cp.CampaignID iS NULL THEN ''No Campaign''
	  ELSE cp.CampaignID + ''-'' + cp.CampaignName
	  END AS CampaignFullName
	,ISNULL(cps.SegmentName, ''No Campaign Segment'') as SegmentName
 
	,cu.FirstName + '' '' + cu.LastName as PrimaryContact
	,cu.Phone1, cu.Email   
    ,am.FirstName + '' '' + am.LastName AS AccountManagerName
	,pm.FirstName + '' '' + pm.LastName AS ProjectManagerName

	,CASE
       WHEN kp1.FirstName IS NULL AND kp1.LastName IS NULL THEN NULL
       ELSE LTRIM(RTRIM(ISNULL(kp1.FirstName + '' '','''')  + ISNULL(kp1.LastName,'''')))
	 END AS [KeyPeople1]
	,CASE
       WHEN kp2.FirstName IS NULL AND kp2.LastName IS NULL THEN NULL
       ELSE LTRIM(RTRIM(ISNULL(kp2.FirstName + '' '','''')  + ISNULL(kp2.LastName,'''')))
	 END AS [KeyPeople2]
	,CASE
       WHEN kp3.FirstName IS NULL AND kp3.LastName IS NULL THEN NULL
       ELSE LTRIM(RTRIM(ISNULL(kp3.FirstName + '' '','''')  + ISNULL(kp3.LastName,'''')))
	 END AS [KeyPeople3]
	,CASE
       WHEN kp4.FirstName IS NULL AND kp4.LastName IS NULL THEN NULL
       ELSE LTRIM(RTRIM(ISNULL(kp4.FirstName + '' '','''')  + ISNULL(kp4.LastName,'''')))
	 END AS [KeyPeople4]
	,CASE
       WHEN kp5.FirstName IS NULL AND kp5.LastName IS NULL THEN NULL
       ELSE LTRIM(RTRIM(ISNULL(kp5.FirstName + '' '','''')  + ISNULL(kp5.LastName,'''')))
	 END AS [KeyPeople5]
	,CASE
       WHEN kp6.FirstName IS NULL AND kp6.LastName IS NULL THEN NULL
       ELSE LTRIM(RTRIM(ISNULL(kp6.FirstName + '' '','''')  + ISNULL(kp6.LastName,'''')))
	 END AS [KeyPeople6]
  
    ,rd.DeliverableName
    ,tu.DeliverableKey
	,tu.ADescription
    -- these keys were in original query
    ,p.ClientKey
    ,p.BillingContact
	,t.PercComp as OldPercComp
	,@RateLevel as RateLevel
	,Case @RateLevel 
	When 1 then ISNULL(s.Description1, s.Description)
	When 2 then ISNULL(s.Description2, s.Description)
	When 3 then ISNULL(s.Description3, s.Description)
	When 4 then ISNULL(s.Description4, s.Description)
	When 5 then ISNULL(s.Description5, s.Description)
	else s.Description
	end as ServiceDescription
	
	,s.ServiceCode
    ,af.AppFavoriteKey
    -- if you modify this field, also modify sptAppFavoriteGetList, spRMGetAssignmentsForUser, and sptTaskUserGetTaskList2
	-- get all with task on activity
	,(select Count(*) from tActivity a (nolock)
	left outer join (Select * from tAppRead (nolock) Where UserKey = @UserKey) as ar on a.ActivityKey = ar.EntityKey and ar.Entity = ''tActivity''
	Where a.ActivityEntity = ''Diary'' and a.TaskKey = t.TaskKey and ISNULL(ar.IsRead, 0) = 0) +
	-- get any links with taskkey on them
	(select Count(*) from tActivityLink al (nolock)
	inner join tActivity a (nolock) on al.ActivityKey = a.ActivityKey and al.Entity = ''tTask''
	left outer join tActivity lda (nolock) on  al.EntityKey = lda.ActivityKey
	left outer join (Select * from tAppRead (nolock) Where UserKey = @UserKey) as ar on al.ActivityKey = ar.EntityKey and ar.Entity = ''tActivity''
	where al.EntityKey = t.TaskKey and a.ActivityEntity = ''Diary'' and al.EntityKey <> a.TaskKey and ISNULL(ar.IsRead, 0) = 0) +
	-- get spec sheets
	(select Count(*) from tSpecSheet ss (nolock)
	left outer join (Select * from tAppRead (nolock) Where UserKey = @UserKey) as ar on ss.SpecSheetKey = ar.EntityKey and ar.Entity = ''tSpecSheet''
	Where ss.EntityKey = t.ProjectKey and ss.Entity = ''Project'' and ISNULL(ar.IsRead, 0) = 0 AND ss.Status <> 5) as UpdateCount 
    ,cf.*
	,p.StartDate
	,p.CompleteDate	 
	,p.PlanningProject
	,clp.ProductName
	,ISNULL(tls.SegmentName, ''No Timeline Segment'') AS TimelineSegmentName
	,t.ProjectColor
	,ISNULL(ps.ProjectStatusColor, '''') AS ProjectStatusColor

 from #tTask t (nolock)
 INNER JOIN tProject p (nolock) ON t.ProjectKey = p.ProjectKey   
 INNER JOIN tTaskUser tu (nolock) ON t.TaskUserKey = tu.TaskUserKey
 LEFT OUTER JOIN tCampaign cp (nolock) ON cp.CampaignKey = t.CampaignKey 
  LEFT OUTER JOIN tCampaignSegment cps (nolock) on p.CampaignSegmentKey = cps.CampaignSegmentKey  
 LEFT OUTER JOIN tTimelineSegment tls (NOLOCK) on t.TimelineSegmentKey = tls.TimelineSegmentKey 
 left outer join tClientProduct clp (nolock) on p.ClientProductKey = clp.ClientProductKey
 LEFT OUTER JOIN tCompany c (nolock) on p.ClientKey = c.CompanyKey   
 LEFT OUTER JOIN tUser cu (nolock) ON p.BillingContact = cu.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 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 tService s (nolock) on t.ServiceKey = s.ServiceKey
 LEFT OUTER JOIN #tCustomFields1 cf (nolock) ON p.CustomFieldKey = cf.CustomFieldKey
 LEFT OUTER JOIN tReviewDeliverable rd (nolock) on tu.DeliverableKey = rd.ReviewDeliverableKey
 LEFT OUTER JOIN (Select * from tAppFavorite (nolock) Where ActionID = ''today.creative.myTasks'' and UserKey = @UserKey) as af on t.TaskUserKey = af.ActionKey
 LEFT OUTER JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey
 
 if @IncludeActivities = 1
 
 BEGIN
 
	Select  a.*,
			ISNULL(a.StartTime, a.ActivityDate) as SortDate,
			p.ProjectNumber + '' '' + p.ProjectName as ProjectFullName,
			case when t.TaskID is null then t.TaskName else t.TaskID + '' - '' + t.TaskName end as TaskFullName,
			u.FirstName + '' '' + u.LastName as AssignedUserName,
			a.ActivityTypeKey,
			p.ProjectNumber,
			p.ProjectName,
			t.TaskID,
			t.TaskName
	From tActivity a (nolock)
	inner join tActivityLink al (nolock) on a.ActivityKey = al.ActivityKey
	inner join #tTask t (nolock) on al.EntityKey = t.TaskKey and al.Entity = ''tTask''
	left outer join tUser u (nolock) on a.AssignedUserKey = u.UserKey
	left outer join tProject p (nolock) on a.ProjectKey = p.ProjectKey
	Where a.CompanyKey = @CompanyKey and Completed = 0
	AND	(@RestrictActivitiesToAssigned = 0 OR ISNULL(a.AssignedUserKey, 0) = 0 OR a.AssignedUserKey = @UserKey)
	Order By a.ActivityDate DESC, a.DateUpdated DESC
 END
   
RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptCampaignUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptCampaignUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptCampaignUpdate]
	@CampaignKey int,
	@UserKey int,
	@CompanyKey int,
	@CampaignID varchar(50),
	@CampaignName nvarchar(200),
	@ClientKey int,
	@Description nvarchar(max),
	@Objective text,
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@AEKey int,
	@Active tinyint,
	@CustomFieldKey int,
	@GetActualsBy smallint,
	@LayoutKey int = null,
	@MultipleSegments tinyint = null,
	@BillBy smallint = null,
	@OneLinePer smallint = null,
	@ContactKey int = null,
	@GLCompanyKey int = null,
	@ClientDivisionKey int = null,
	@ClientProductKey int = null,
	@NextProjectNum int = 1,
	@CurrencyID varchar(10) = null,
	@LeadKey int = null,
	@PMKey int = null,
	@UseCampaignBudget int = NULL,
	@ExpensesNotIncluded tinyint = NULL,
	@BillByFF smallint = 1,
	@ClientCampaignNumber nvarchar(200) = NULL,
	@AvalaraTaxCodeKey int = NULL,
	@RequestKey int = NULL,
	@OfficeKey int = null
AS --Encrypt

/*
|| When      Who Rel      What
|| 5/23/07   CRG 8.4.3    (9293) Added GetActualsBy
|| 12/15/09  CRG 10.5.1.5 Added insert logic
|| 1/19/10   CRG 10.5.1.7 Added @MultipleSegments parameter.  Also made @MultipleSegments and @LayoutKey optional for compatability with CMP and old WMJ screens.
|| 2/3/10    CRG 10.5.1.8 Added optional parameter @BillBy
|| 2/25/10   GWG 10.5.2.0 Added One line per optional param
|| 4/6/10    GHL 10.5.2.1 Added ContactKey param
|| 11/2/10   CRG 10.5.3.7 (92555) Now if MultipleSegments is turned off, we are setting the CampaignSegmentKey to NULL in tProject and deleting the Campaign Segments.
|| 03/02/11  GHL 10.5.4.1 (103729) Added logic to get a campaign id/number for enhancement
|| 04/25/12  GHL 10.5.5.5 Added GLCompanyKey param, the logic for the validation of the GLCompanyKey will be
||                        If GLCompanyKey is null, all projects must have a null GLCompanyKey
||                        If GLCompanyKey is >0, all projects must have the same GLCompanyKey Or 
||                        tGLCompanyMap.TargetGLCompanyKey where SourceGLCompanyKey = GLCompanyKey
|| 11/6/12   WDF 10.5.6.2 (157606) Added ClientDivisionKey and ClientProductKey parameters.
|| 01/22/13  MAS 10.5.6.4 Added UserKey parameters and logging when the active flag is changed
|| 06/18/13  GHL 10.5.6.9 (181721) Added next project number for new project numbers by campaign
|| 07/25/13  GHL 10.5.7.0 Error out if CampaignID is null
|| 10/07/13  GHL 10.5.7.3 Added currency ID to support multi currency
|| 11/07/13  WDF 10.5.7.4 (195877) Error Out if BillBy = 2 and Project Clients not equal Campaign Clients
|| 03/13/14  KMC 10.5.7.8 (209594) Remove the ISNULL check on the LayoutKey so it can be removed instead of just default back to the old LayoutKey
|| 10/13/15  RLB 10.5.9.7 added check for campainid matching any project numbers which can not be because of Plat changes
|| 10/14/15  CRG 10.5.9.7 Added call to sptCampaignWebDavSafeFolders
|| 11/28/17  WDF 10.6.6.6 (374150) Set MultipleSegments flag based on the Segment count for an existing Campaign
|| 09/19/18  RLB 18.9.1.0 (419876) move validation for projects to match campaign GL Company to Bill by Campaign
|| 12/10/18  RLS 19.1.0.0 (423384) Allow for CampaignID to be passed in for new campaigns (insert) (Added @CampaignIDForInsert)
|| 04/09/19  GAR 19.0.5.0 (442365) Adding ability to link opportunities to campaigns - added update of leadkey.
|| 04/16/20  GAR 19.0.5.0 (473704) Added Project Manager
|| 01/07/21  RLS 21.02.14 (535729) Changed @CampaignName to nvarchar
|| 01/27/21  RLS 21.0.2.0 (535729) Changed @Description to nvarchar
|| 04/12/21  MFT 21.0.5.0 (455922) Added UseCampaignBudget, ExpensesNotIncluded, BillByFF param/field
|| 11/01/21  RLS 21.12.19 (574953) Added DateCreated
|| 03/14/22  MFT 22.0.4.0 (578711) Added ClientCampaignNumber
|| 09/26/22  GAR 22.10.16 (DEV2605) Added AvalaraTaxCode
|| 04/04/23 CRG 23.05.14  (621941) Now checking tPreference.DefaultCampaignBillBy when adding a new campaign
|| 11/30/23 RLB 23.12.17  (649537) Added DefaultCampUseCampaignBudget and DefaultCampExpensesNotIncluded new campaign tPreference options on add
|| 02/06/24 RLB 24.03.17  (658052) adding requestkey on insert
|| 02/08/24 RLS 24.03.17  (664126) Fix isnull() param - change to 0 for DefaultCampUseCampaignBudget and DefaultCampExpensesNotIncluded
|| 05/30/24 MCM 24.07.x   (651173) Added OfficeKey
|| 02/19/26 RLS 26.03.15  (720383) Added RequestKey to the update section
|| 03/31/26 GAR 26.04.19  (721911) Allow projects that are child client projects if the client on the campaign is a parent company.
*/
	DECLARE	@OldGetActualsBy smallint,
			@OldLayoutKey int,
			@OldMultipleSegments tinyint,
			@OldBillBy smallint,
			@OldOneLinePer smallint,
			@RetVal	INTEGER,
			@NextTranNo VARCHAR(100),
			@OldActive tinyint,
			@Date smalldatetime,
			@MultiCurrency int,
			@OldCurrencyID varchar(10)

     SELECT @Date = GETUTCDATE()	
     
	 -- Get the next number
	 IF @CampaignID IS NULL OR @CampaignID = '''' -- Will be true for new Campaigns
	 BEGIN
		EXEC sptCampaignGetNextCampaignNum
			@CompanyKey,
			@ClientKey,
			@RetVal OUTPUT,
			@NextTranNo OUTPUT

		IF @RetVal <> 1
			RETURN -1

		IF @NextTranNo IS NULL
			RETURN -1
	END
	ELSE
	BEGIN
		-- Check for a duplicate campaign id/number
		if isnull(@CampaignKey,0) > 0 
		begin
			IF EXISTS(
				SELECT 1 FROM tCampaign (NOLOCK) 
				WHERE
					CampaignID = @CampaignID AND
					CompanyKey = @CompanyKey AND
					CampaignKey <> @CampaignKey
					)
				RETURN -2
			IF EXISTS(
				SELECT 1 FROM tProject (NOLOCK) 
				WHERE
					ProjectNumber = @CampaignID AND
					CompanyKey = @CompanyKey			
					)
				RETURN -7
		end
		ELSE
		begin
			IF EXISTS(
				SELECT 1 FROM tCampaign (NOLOCK) 
				WHERE
					CampaignID = @CampaignID AND
					CompanyKey = @CompanyKey
					)
				RETURN -2
		end

		IF EXISTS(
			SELECT 1 FROM tProject (NOLOCK) 
			WHERE
				ProjectNumber = @CampaignID AND
				CompanyKey = @CompanyKey			
				)
			RETURN -7

		SELECT @NextTranNo = @CampaignID
	END

	SELECT @NextTranNo = LTRIM(RTRIM(REPLACE(REPLACE(REPLACE(REPLACE(@NextTranNo, ''&'', ''''), '','', ''''), ''"'', ''''), '''''''', '''')))
 
	IF @CampaignKey > 0
	BEGIN
				
	SELECT	@OldGetActualsBy = GetActualsBy,
				@OldLayoutKey = LayoutKey,
				@OldMultipleSegments = MultipleSegments,
				@OldBillBy = BillBy,
				@OldOneLinePer = OneLinePer,
				@OldCurrencyID = CurrencyID
		FROM	tCampaign (nolock)
		WHERE	CampaignKey = @CampaignKey

		-- Validation of CurrencyID
		select @MultiCurrency = isnull(MultiCurrency, 0) from tPreference (nolock) where CompanyKey = @CompanyKey
		if @MultiCurrency = 1
		begin
			IF EXISTS (SELECT 1 FROM tProject (NOLOCK) 
						WHERE CampaignKey = @CampaignKey 
						AND   isnull(CurrencyID, '''') <> isnull(@CurrencyID, '''')
					)
					RETURN -4 
					
			IF isnull(@OldCurrencyID, '''') <> isnull(@CurrencyID, '''') AND EXISTS (SELECT 1 FROM tEstimate (NOLOCK)
				WHERE CompanyKey = @CompanyKey
				AND   CampaignKey = @CampaignKey
				)
				RETURN -5 
		end
	
		IF @BillBy = 2
		BEGIN
			--If BillBy was set to Campaign but projects are linked to it that have a different client than this campaign, then return error
			--721911-GAR - Change this to include all child client projects if this is a parent client
			IF EXISTS
					(SELECT	NULL
					FROM	tProject p (nolock)
						INNER JOIN tCompany c (nolock) ON p.ClientKey = c.CompanyKey
					WHERE	p.CampaignKey = @CampaignKey
					AND		p.ClientKey <> @ClientKey
					AND     p.ClientKey NOT IN (SELECT CompanyKey FROM tCompany (nolock) WHERE ParentCompanyKey = @ClientKey))
				RETURN -6

		-- Validation of GLCompanyKey this only applies when billing by campaign
		IF EXISTS (SELECT 1 FROM tProject (NOLOCK) WHERE CampaignKey = @CampaignKey AND NOT ISNULL(GLCompanyKey, 0) IN (
						SELECT ISNULL(@GLCompanyKey, 0) 
						UNION
						(SELECT TargetGLCompanyKey FROM tGLCompanyMap (NOLOCK) WHERE SourceGLCompanyKey =  @GLCompanyKey)
				  )
				)
				RETURN -3
		END

		SELECT	@MultipleSegments = (SELECT CASE WHEN (Select Count(*) from tCampaignSegment (nolock) WHERE CampaignKey = @CampaignKey) > 0 THEN 1 ELSE 0 END) 

		IF @MultipleSegments = 0 AND @OldMultipleSegments = 1
		BEGIN
			UPDATE	tProject
			SET		CampaignSegmentKey = NULL
			WHERE	CampaignKey = @CampaignKey

			DELETE	tCampaignSegment
			WHERE	CampaignKey = @CampaignKey
		END
		
		SELECT @OldActive = ISNULL(Active, 0)	
		FROM   tCampaign (nolock)
		WHERE  CampaignKey = @CampaignKey
			
		IF @OldActive <> @Active
		BEGIN
			IF @Active = 1
				EXEC sptActionLogInsert ''Campaign'',@CampaignKey, @CompanyKey, 0, ''Active'', @Date, NULL, ''Campaign marked active'', @CampaignID, NULL, @UserKey  
			ELSE
				EXEC sptActionLogInsert ''Campaign'',@CampaignKey, @CompanyKey, 0, ''Inactive'', @Date, NULL, ''Campaign marked inactive'', @CampaignID, NULL, @UserKey  
		END
	
		UPDATE
			tCampaign
		SET
			CompanyKey = @CompanyKey,
			CampaignID = @NextTranNo, 
			CampaignName = @CampaignName,
			ClientKey = @ClientKey,
			Description = @Description,
			Objective = @Objective,
			StartDate = @StartDate,
			EndDate = @EndDate,
			AEKey = @AEKey,
			Active = @Active,
			CustomFieldKey = @CustomFieldKey,
			GetActualsBy = @GetActualsBy,
			LayoutKey = @LayoutKey,
			MultipleSegments = ISNULL(@MultipleSegments, @OldMultipleSegments),
			BillBy = ISNULL(@BillBy, @OldBillBy),
			UseCampaignBudget = @UseCampaignBudget,
			ExpensesNotIncluded = @ExpensesNotIncluded,
			BillByFF = @BillByFF,
			OneLinePer = ISNULL(@OneLinePer, @OldOneLinePer),
			ContactKey = @ContactKey,
			GLCompanyKey = @GLCompanyKey,
			ClientDivisionKey = @ClientDivisionKey,
			ClientProductKey = @ClientProductKey,
			NextProjectNum = @NextProjectNum,
			CurrencyID = @CurrencyID,
			LeadKey = @LeadKey,
			PMKey = @PMKey,
			ClientCampaignNumber = @ClientCampaignNumber,
			AvalaraTaxCodeKey = @AvalaraTaxCodeKey,
			OfficeKey = @OfficeKey,
			RequestKey = @RequestKey
		WHERE
			CampaignKey = @CampaignKey 

		--If GetActualsBy has changed, clear the budget items
		IF @GetActualsBy <> @OldGetActualsBy
			DELETE	tCampaignBudgetItem
			WHERE	CampaignKey = @CampaignKey

		--If not using Project for Actuals, clear out any links from tProject
		IF @GetActualsBy < 3
			UPDATE	tProject
			SET		CampaignBudgetKey = NULL
			WHERE	CampaignKey = @CampaignKey	
		
		RETURN @CampaignKey
	END
	ELSE
	BEGIN
		-- New Campaign; a new CampaignID may have been passed in (423384). If so, use it. If not use @NextTranNo which was set above.
		 DECLARE @CampaignIDForInsert VARCHAR(100)
		 IF @CampaignID IS NOT NULL AND @CampaignID <> ''''
			SELECT @CampaignIDForInsert = @CampaignID
		 ELSE
			SELECT @CampaignIDForInsert = @NextTranNo

		SELECT	@BillBy = ISNULL(DefaultCampaignBillBy, 1), @UseCampaignBudget = ISNULL(DefaultCampUseCampaignBudget, 0), @ExpensesNotIncluded = ISNULL(DefaultCampExpensesNotIncluded, 0)
		FROM	tPreference (nolock)
		WHERE	CompanyKey = @CompanyKey
			
		INSERT tCampaign
			(
			CompanyKey,
			CampaignID,
			CampaignName,
			ClientKey,
			Description,
			Objective,
			StartDate,
			EndDate,
			AEKey,
			Active,
			CustomFieldKey,
			GetActualsBy,
			LayoutKey,
			MultipleSegments,
			BillBy,
			UseCampaignBudget,
			ExpensesNotIncluded,
			BillByFF,
			OneLinePer,
			ContactKey,
			GLCompanyKey,
			ClientDivisionKey,
			ClientProductKey,
			NextProjectNum,
			CurrencyID,
			LeadKey,
			PMKey,
			DateCreated,
			ClientCampaignNumber,
			AvalaraTaxCodeKey,
			RequestKey,
			OfficeKey
			)

		VALUES
			(
			@CompanyKey,
			@CampaignIDForInsert,
			@CampaignName,
			@ClientKey,
			@Description,
			@Objective,
			@StartDate,
			@EndDate,
			@AEKey,
			@Active,
			@CustomFieldKey,
			@GetActualsBy,
			@LayoutKey,
			@MultipleSegments,
			@BillBy,
			@UseCampaignBudget,
			@ExpensesNotIncluded,
			@BillByFF,
			@OneLinePer,
			@ContactKey,
			@GLCompanyKey,
			@ClientDivisionKey,
			@ClientProductKey,
			@NextProjectNum,
			@CurrencyID,
			@LeadKey,
			@PMKey,
			GETUTCDATE(),
			@ClientCampaignNumber,
			@AvalaraTaxCodeKey,
			@RequestKey,
			@OfficeKey
			)
	
		SELECT @CampaignKey = @@IDENTITY
		
		--Set the WebDav safe folder names
		EXEC sptCampaignWebDavSafeFolders @CampaignKey, 0
		
		RETURN @CampaignKey	
	END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'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
*/

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

	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 
		select  @Total = fdi.Total
			    , @StartDate  = CASE 
					WHEN @ByMonth = 0 then fdi.StartDate
					ELSE fd.StartDate
				 end 
			   ,@EndDate = CASE 
					WHEN @ByMonth = 0 then fdi.EndDate
					ELSE DATEADD(DAY, -1, DATEADD(MONTH, @Months, fd.StartDate))
				 end 
			   ,@Labor = fdi.Labor 
		from tForecastDetailItem fdi  (nolock)
			left join tForecastDetail fd (nolock) on fd.ForecastDetailKey = fdi.ForecastDetailKey
        WHERE    fdi.ForecastDetailKey = @ForecastDetailKey
		and    [Sequence] = @Sequence     

		-- 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 (LTRIM(STR(ISNULL(@ByMonth, 0))) = 0 )
	begin

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

	------else evenly by number of months	
	--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/@Months

	if (LTRIM(STR(ISNULL(@ByMonth, 0))) = 1 and @Entity = ''tLead'') OR (ISNULL(@ByMonth, 0) = 1 and @Opportunity = 1)
		begin		
			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
		if (LTRIM(STR(ISNULL(@ByMonth, 0))) = 0 )
	    begin
			select @BucketIdx = max(Idx) 
			from #tBuckets 
			where NumDays <> 0	
		end			

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

	if @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'Creating [dbo].[tMCPClient]'
GO
IF OBJECT_ID(N'[dbo].[tMCPClient]', 'U') IS NULL
CREATE TABLE [dbo].[tMCPClient]
(
[MCPClientKey] [int] NOT NULL IDENTITY(1, 1),
[ClientID] [nvarchar] (128) NOT NULL,
[ClientName] [nvarchar] (256) NOT NULL CONSTRAINT [DF__tMCPClien__Clien__2359C46D] DEFAULT (''),
[RedirectURIs] [nvarchar] (2048) NOT NULL CONSTRAINT [DF__tMCPClien__Redir__244DE8A6] DEFAULT (''),
[CreatedDate] [datetime] NOT NULL CONSTRAINT [DF__tMCPClien__Creat__25420CDF] DEFAULT (getutcdate())
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tMCPClient] on [dbo].[tMCPClient]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tMCPClient]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tMCPClient]', 'U'))
ALTER TABLE [dbo].[tMCPClient] ADD CONSTRAINT [PK_tMCPClient] PRIMARY KEY CLUSTERED ([MCPClientKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tMCPClient_ClientID] on [dbo].[tMCPClient]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tMCPClient_ClientID' AND object_id = OBJECT_ID(N'[dbo].[tMCPClient]'))
CREATE UNIQUE NONCLUSTERED INDEX [IX_tMCPClient_ClientID] ON [dbo].[tMCPClient] ([ClientID])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMCPClientRegister]'
GO
IF OBJECT_ID(N'[dbo].[sptMCPClientRegister]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptMCPClientRegister]
    @ClientID       nvarchar(128),
    @ClientName     nvarchar(256),
    @RedirectURIs   nvarchar(2048)
AS
BEGIN
    SET NOCOUNT ON

    IF NOT EXISTS (SELECT 1 FROM tMCPClient WITH (nolock) WHERE ClientID = @ClientID)
    BEGIN
        INSERT INTO tMCPClient (ClientID, ClientName, RedirectURIs)
        VALUES (@ClientID, @ClientName, @RedirectURIs)
    END
    ELSE
    BEGIN
        -- Update name/URIs if client re-registers
        UPDATE tMCPClient
        SET ClientName   = @ClientName,
            RedirectURIs = @RedirectURIs
        WHERE ClientID = @ClientID
    END
END
'
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'Creating [dbo].[tMCPToken]'
GO
IF OBJECT_ID(N'[dbo].[tMCPToken]', 'U') IS NULL
CREATE TABLE [dbo].[tMCPToken]
(
[MCPTokenKey] [int] NOT NULL IDENTITY(1, 1),
[CompanyKey] [int] NOT NULL,
[Token] [nvarchar] (256) NOT NULL,
[APIAccessToken] [nvarchar] (256) NOT NULL,
[UserToken] [nvarchar] (256) NOT NULL,
[UserKey] [bigint] NOT NULL,
[Expires] [datetime] NOT NULL,
[CreatedDate] [datetime] NOT NULL CONSTRAINT [DF__tMCPToken__Creat__281E798A] DEFAULT (getutcdate())
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tMCPToken] on [dbo].[tMCPToken]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tMCPToken]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tMCPToken]', 'U'))
ALTER TABLE [dbo].[tMCPToken] ADD CONSTRAINT [PK_tMCPToken] PRIMARY KEY CLUSTERED ([MCPTokenKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tMCPToken_CompanyKey] on [dbo].[tMCPToken]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tMCPToken_CompanyKey' AND object_id = OBJECT_ID(N'[dbo].[tMCPToken]'))
CREATE NONCLUSTERED INDEX [IX_tMCPToken_CompanyKey] ON [dbo].[tMCPToken] ([CompanyKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tMCPToken_Token] on [dbo].[tMCPToken]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tMCPToken_Token' AND object_id = OBJECT_ID(N'[dbo].[tMCPToken]'))
CREATE UNIQUE NONCLUSTERED INDEX [IX_tMCPToken_Token] ON [dbo].[tMCPToken] ([Token])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMCPTokenGet]'
GO
IF OBJECT_ID(N'[dbo].[sptMCPTokenGet]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptMCPTokenGet]
    @Token  nvarchar(256)
AS
BEGIN
    SET NOCOUNT ON

    SELECT CompanyKey, APIAccessToken, UserToken, UserKey
    FROM   tMCPToken WITH (nolock)
    WHERE  Token   = @Token
      AND  Expires > GETUTCDATE()
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptApiHookInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptApiHookInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptApiHookInsert]
	@UserKey INT,
	@CompanyKey INT,
	@Url VARCHAR(1000),
	@Entity VARCHAR(100),
	@Action VARCHAR(10),
	@APIAccessToken VARCHAR(1000),
	@UserToken VARCHAR(1000),
	@ApiHookKey INT OUTPUT
		
AS --Encrypt

/*
|| When      Who Rel      What
|| 05/12/15  QMD 10.5.9.2 Created for Api webhooks
|| 10/29/24  MCM 24.11.x (686692) Updated logic for setting the @APIAccessToken and @UserToken to be two different if statements
|| 03/13/26  CRG 26.04.19 Set the ApiHookKey output parm to the identity
*/
	
	IF EXISTS(SELECT * FROM tApiHook (NOLOCK) WHERE CompanyKey = @CompanyKey AND Url = @Url AND Entity = @Entity AND [Action] = @Action)
	   BEGIN
	    SELECT @ApiHookKey = ApiHookKey FROM tApiHook (NOLOCK) WHERE CompanyKey = @CompanyKey AND Url = @Url AND Entity = @Entity AND [Action] = @Action
		RETURN -1
	   END
		
	IF @UserKey > 0 AND ISNULL(@APIAccessToken,'''') = ''''
	   BEGIN
		SELECT	@APIAccessToken = APIAccessToken
		FROM	tPreference (NOLOCK)
		WHERE	CompanyKey = @CompanyKey
	   END

	IF @UserKey > 0 AND ISNULL(@UserToken,'''') = '''' 
	   BEGIN
	   	SELECT	@UserToken = PublicUserToken
		FROM	tUserPreference 
		WHERE	UserKey = @UserKey
	   END

	INSERT INTO tApiHook (CompanyKey, Url, Entity, [Action], UserToken, APIAccessToken)
	VALUES (@CompanyKey, @Url, @Entity, @Action, @UserToken, @APIAccessToken)

	SELECT @ApiHookKey = @@IDENTITY
	
	RETURN @ApiHookKey
	
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMCPTokenSave]'
GO
IF OBJECT_ID(N'[dbo].[sptMCPTokenSave]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptMCPTokenSave]
    @CompanyKey         int,
    @Token              nvarchar(256),
    @APIAccessToken     nvarchar(256),
    @UserToken          nvarchar(256),
    @UserKey            bigint,
    @ExpiryDays         int = 90
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO tMCPToken
        (CompanyKey, Token, APIAccessToken, UserToken, UserKey, Expires)
    VALUES
        (@CompanyKey, @Token, @APIAccessToken, @UserToken, @UserKey,
         DATEADD(DAY, @ExpiryDays, GETUTCDATE()))
END
'
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
 */

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
	left outer join tActionLog al ON p.ProjectKey = al.EntityKey AND Action = ''Project Made Live'' 
	LEFT OUTER JOIN vUserName con (nolock) on cl.ContactOwnerKey = con.UserKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptLayoutProjectItemRollup]'
GO
IF OBJECT_ID(N'[dbo].[sptLayoutProjectItemRollup]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptLayoutProjectItemRollup]
	(
	@CompanyKey int
	,@Entity varchar(50) -- ''tCampaign'', ''tCampaignNoSegment'', ''tCampaignSegment'', ''tProject'', etc...
	,@EntityKey int
	,@LayoutKey int
	)
AS
	SET NOCOUNT ON
	
/*
|| When      Who Rel      What
|| 01/07/10  GHL 10.5.1.? Creation for campaign layouts
||                        Returns:
||                        Billing Item 1, Item 1, rollup values
||                        Billing Item 1, Item 2, rollup values
||                        Billing Item 2, Item 3, rollup values
||                        Billing Item 2, Item 4, rollup values
|| 01/14/10  CRG 10.5.1.7 Modified to use customized billing item names for the entity
|| 01/26/10  GHL 10.5.1.7 Added @Entity,@EntityKey as part of the results to be used in grids for drill downs
|| 4/21/10   GHL 10.5.2.2 Added additional columns for campaign estimates 
|| 10/7/10   RLB 10.5.3.6 (89933)Added Sales Tax   AmountBilled - AmountBilledNoTax
|| 10/7/10   RLB 10.5.3.7 Added Total Gross Unbilled Fixed Fee
|| 11/15/10  GHL 10.5.3.8 (93504) During testing for 93504, found out that TotalGross was incorrect due to the fact that
||                        OpenOrderGross used to be calculated for unbilled po, but now includes them
||                        so use OpenOrderGrossUnbilled = tProjectItemRollup.OpenOrderUnbilled 
|| 01/04/13  WDF 10.5.6.3 Added DepartmentName
|| 01/07/13  GHL 10.5.6.3 Added nolock hints
|| 02/18/13 GHL 10.5.6.5 (168695) Added Allocated hours
|| 03/06/13 GHL 10.566   (167702) Added Total Gross After WriteOff
|| 06/27/13 MFT 10.569   (177496) Corrected HoursBilledRemaining calc
|| 10/08/13 GHL 10.573    Using now PTotalCost to support multi currency
|| 10/31/13 GHL 10.573    When LayoutKey = 0, manufacture a unique WorkTypeDisplayOrder for sorts on grids
||                       (because of some sorting issues on the project budget screen by BI and Item, 
||                        Phoenix Marketing, project OAPI1001)
||                       (193975) Added PurchasedQty and Budgeted Quantities
|| 11/15/13 GHL 10.573   (196880) Corrected typo with the WorkTypeDisplayOrder when LayoutKey > 0
|| 03/09/15 GHL 10.590   Added values for ItemID for ServiceKey = 0 for Abelson Taylor
||                       Could happen now if estimate is by title only
|| 05/26/16 GHL 10.604   (295137) Added write off data for enhancement for AT
|| 01/10/17 GHL 10.612  (326322) Recalculating now Costs Gross After WO w/o Orders as:
||                       Total Cost Gross - Expense WO instead of Inside Costs Gross + Voucher Gross - Expense WO
||                      Added Open Orders Unbilled to Costs Gross After WO w Orders for consistency with other budgets
|| 04/14/17 GHL 10.615  (340960) Added pulling of HoursWriteOff from tProjectItemRollup at the top 
|| 10/26/17 RLS 10.621   Added RemainingAllocatedHours
|| 08/04/21 MCM 21.090  (566562) Added CurrentTotalBudgetNoTax
|| 08/27/21 MCM 21.090  (566456) Added HoursUnbilled 
|| 11/22/21 MCM 21.12x  (578053) Added LaborHoursWriteOff
|| 07/22/22 RLS 22.08x  (606282) Changes ItemName to nvarchar
|| 01/29/25 RLB 25.03.16 (688067) adding new fields CurrentBudgetExpenseQuantity and ActualQuantity for Project item for project budget bash 
|| 08/18/25 RLB 25.10.19 (707695) adding new field RemainingAllocatedHoursP temp table will need this field
|| 04/13/25 RLB 26.05.17 (726310) added missing fields FutureLaborGrossRemaining, FutureAllocatedGross, AllocatedGross, FutureAllocatedHours. They are on other tabs but not this one
*/

	create table #projects(ProjectKey int null)

	-- other data, non summarized in tProjectRollup...
	create table #project_other(Entity varchar(50) null, EntityKey int null, AllocatedHours decimal(24,4) null, FutureAllocatedHours decimal(24,4) null, AllocatedGross money null, FutureAllocatedGross money null, projectKey int NULL, )
	
	-- Project Item Rollup table	
	create table #roll (
	    Entity varchar(50) NULL, -- tItem, tService
		EntityKey int NULL,      -- ItemKey, ServiceKey
		ItemID varchar(50),      -- ItemID or ServiceCode
		ItemName nvarchar(200),   -- ItemName or Description
		DepartmentName varchar(200) NULL,
		WorkTypeKey int,
		WorkTypeID varchar(100),
		WorkTypeName varchar(200),		
		WorkTypeDisplayOrder int, -- WorkType display order

		-- these fields are in tProjectItemRollup
		Hours decimal(24, 4) NULL ,
		HoursApproved decimal(24, 4) NULL ,
		HoursBilled decimal(24, 4) NULL ,
		HoursInvoiced decimal(24, 4) NULL ,
		HoursWriteOff decimal(24,4) null,
		HoursAfterWriteOff decimal(24,4) null,
		HoursUnbilled decimal(24, 4) NULL,
		LaborNet money NULL ,
		LaborNetApproved money NULL ,
		LaborGross money NULL ,
		LaborGrossApproved money NULL ,
		LaborUnbilled money NULL ,
		LaborBilled money NULL ,
		LaborInvoiced money NULL ,
		LaborWriteOff money NULL ,
		LaborHoursWriteOff money NULL ,
		LaborGrossAfterWriteOff money NULL ,
		MiscCostNet money NULL ,
		MiscCostGross money NULL ,
		MiscCostUnbilled money NULL ,
		MiscCostWriteOff money NULL ,
		MiscCostBilled money NULL ,
		MiscCostInvoiced money NULL ,
		ExpReceiptNet money NULL ,
		ExpReceiptNetApproved money NULL ,
		ExpReceiptGross money NULL ,
		ExpReceiptGrossApproved money NULL ,
		ExpReceiptUnbilled money NULL ,
		ExpReceiptWriteOff money NULL ,
		ExpReceiptBilled money NULL ,
		ExpReceiptInvoiced money NULL ,
		VoucherNet money NULL ,
		VoucherNetApproved money NULL ,
		VoucherGross money NULL ,
		VoucherGrossApproved money NULL ,
		VoucherOutsideCostsGross money NULL ,
		VoucherOutsideCostsGrossApproved money NULL ,
		VoucherUnbilled money NULL ,
		VoucherWriteOff money NULL ,
		VoucherBilled money NULL ,
		VoucherInvoiced money NULL ,
		OpenOrdersNet money NULL ,
		OpenOrderNetApproved money NULL ,
		OpenOrderGross money NULL ,
		OpenOrderGrossApproved money NULL ,
		OpenOrderUnbilled money NULL ,
		OrderPrebilled money NULL ,
		AmountBilled money NULL ,
		AmountBilledNoTax money NULL ,
		AdvanceBilled money NULL ,
		AdvanceBilledOpen money NULL,

		AllocatedHours decimal(24,4) null,
		FutureAllocatedHours decimal(24,4) null,
		AllocatedGross money null,
		FutureAllocatedGross money null,
		FutureLaborGrossRemaining money null,

		SalesTax money NULL,
		TotalGrossUnbilledFixedFee money NULL,
		EstQty decimal(24,4) NULL,
		EstNet money NULL,
		EstGross money NULL,
		EstCOQty decimal(24,4) NULL,
		EstCONet money NULL,
		EstCOGross money NULL,
		
		-- Actuals fields...Cloned from spRptBudgetAnalysis
		OutsideCostsNet money null
		,InsideCostsNet money null
		
		,OpenOrdersGrossUnbilled money null
		,OutsideCostsGrossUnbilled money null
		,InsideCostsGrossUnbilled money null
		
		,OutsideCostsGross money null
		,InsideCostsGross money null
		
		,ExpenseWriteOff money null		
		,ExpenseBilled money null		
		,ExpenseInvoiced money null	
		
		,ActualQuantity decimal(24,4)
				
		-- Budget fields...Cloned from spRptBudgetAnalysis
		,CurrentBudgetHours decimal(24,4) null
		,CurrentBudgetQty decimal(24,4) null
		,CurrentBudgetLaborNet money null
		,CurrentBudgetLaborGross money null
		,CurrentBudgetExpenseNet money null
		,CurrentBudgetExpenseGross money null
		,CurrentBudgetContingency money null
		,CurrentTotalBudget money null
		,CurrentTotalBudgetCont money null
		,CurrentTotalBudgetWithTax money null		-- not calc''ed, but added for rendering on the grid (was blank)
		,CurrentTotalBudgetContWithTax money null
		,CurrentTotalBudgetNoTax money null
		,CurrentBudgetExpenseQuantity decimal(24,4)

		,COBudgetHours decimal(24,4) null
		,COBudgetQty decimal(24,4) null
		,COBudgetLaborNet money null
		,COBudgetLaborGross money null
		,COBudgetExpenseNet money null
		,COBudgetExpenseGross money null
		,COBudgetContingency money null
		,COTotalBudget money null
		,COTotalBudgetCont money null
		,COTotalBudgetWithTax money null
		,COTotalBudgetContWithTax money null

		,OriginalBudgetHours decimal(24,4) null
		,OriginalBudgetQty decimal(24,4) null
		,OriginalBudgetLaborNet money null
		,OriginalBudgetLaborGross money null
		,OriginalBudgetExpenseNet money null
		,OriginalBudgetExpenseGross money null
		,OriginalBudgetContingency money null
		,OriginalTotalBudget money null
		,OriginalTotalBudgetCont money null
		,OriginalTotalBudgetWithTax money null
		,OriginalTotalBudgetContWithTax money null
		
		-- Campaign Budget fields
		,C_CurrentBudgetHours decimal(24,4) null
		,C_CurrentBudgetLaborNet money null
		,C_CurrentBudgetLaborGross money null
		,C_CurrentBudgetExpenseNet money null
		,C_CurrentBudgetExpenseGross money null
		,C_CurrentBudgetContingency money null
		,C_CurrentTotalBudget money null
		,C_CurrentTotalBudgetWithTax money null
		,C_CurrentTotalBudgetCont money null
		,C_CurrentTotalBudgetContWithTax money null

		,C_COBudgetHours decimal(24,4) null
		,C_COBudgetLaborNet money null
		,C_COBudgetLaborGross money null
		,C_COBudgetExpenseNet money null
		,C_COBudgetExpenseGross money null
		,C_COBudgetContingency money null
		,C_COTotalBudget money null
		,C_COTotalBudgetWithTax money null
		,C_COTotalBudgetCont money null
		,C_COTotalBudgetContWithTax money null

		,C_OriginalBudgetHours decimal(24,4) null
		,C_OriginalBudgetLaborNet money null
		,C_OriginalBudgetLaborGross money null
		,C_OriginalBudgetExpenseNet money null
		,C_OriginalBudgetExpenseGross money null
		,C_OriginalBudgetContingency money null
		,C_OriginalTotalBudget money null
		,C_OriginalTotalBudgetWithTax money null
		,C_OriginalTotalBudgetCont money null
		,C_OriginalTotalBudgetContWithTax money null

		-- Totals...Cloned from spRptBudgetAnalysis
		,TotalCostsNet money null				-- InsideCostsNet + OutsideCostsNet
		,TotalCostsGrossUnbilled money null		-- InsideCostsGrossUnbilled + OutsideCostsGrossUnbilled
		,TotalCostsGross money null				-- InsideCostsGross + OutsideCostsGross

		,TotalNet money null					-- InsideCostsNet + OutsideCostsNet + OpenOrdersNet + LaborNet
		,TotalGrossUnbilled money null			-- InsideCostsGrossUnbilled + OutsideCostsGrossUnbilled + OpenOrdersGrossUnbilled + LaborGrossUnbilled
		,TotalGross money null					-- InsideCostsGross + OutsideCostsGross + OpenOrdersGrossUnbilled + LaborGross
		,TotalGrossAfterWriteOff money null     -- TotalGross - LaborWriteOff - ExpenseWriteOff
		,TotalCostsGrossAfterWriteOff  money null -- TotalCostsGross + Open Orders Unbilled - ExpenseWriteOff
		,TotalCostsGrossAfterWriteOffNoOrder  money null -- TotalCostsGross  - ExpenseWriteOff  

		-- Variance calcs...Cloned from spRptBudgetAnalysis
		,HoursBilledRemaining decimal(24,4) null
		,HoursBilledRemainingP decimal(24,4) null
		,HoursRemaining decimal(24,4) null
		,HoursRemainingP decimal(24,4) null
		,LaborNetRemaining money null
		,LaborNetRemainingP decimal(24,4) null
		,LaborGrossRemaining money null
		,LaborGrossRemainingP decimal(24,4) null

		,HoursAfterWriteOffRemaining decimal(24,4) null
		,HoursAfterWriteOffRemainingP decimal(24,4) null
		,RemainingAllocatedHours decimal(24,4) null
		,RemainingAllocatedHoursP decimal(24,4) null
		,LaborGrossAfterWriteOffRemaining money null
		,LaborGrossAfterWriteOffRemainingP decimal(24,4) null
		,CostsGrossAfterWriteOffRemaining money null
		,CostsGrossAfterWriteOffRemainingP decimal(24,4) null
		,CostsGrossAfterWriteOffNoOrderRemaining  money null
		,CostsGrossAfterWriteOffNoOrderRemainingP decimal(24,4) null

		,CostsNetRemaining money null
		,CostsNetRemainingP decimal(24,4) null
		,CostsGrossRemaining money null
		,CostsGrossRemainingP decimal(24,4) null

		,ToBillRemaining money null
		,ToBillRemainingP decimal(24,4) null
		,GrossRemaining money null
		,GrossRemainingP decimal(24,4) null
				
		-- New fields added, not part of the project rollup table		
		,BilledDifference money null
		,PurchasedQty decimal(24,4) NULL -- MiscCost and VI only
	
	) 

	declare @CampaignKey int
	
	select @LayoutKey = isnull(@LayoutKey, 0)
	
	if not exists (select 1 from tLayout (nolock) where LayoutKey = @LayoutKey)
		select @LayoutKey = 0
	
	if @Entity = ''tProject''
	begin
		insert #projects (ProjectKey) values (@EntityKey)

		select @CampaignKey = CampaignKey
		from   tProject (nolock)
		where  ProjectKey = @EntityKey
	end
	else if @Entity = ''tCampaignSegment''
	begin
		insert #projects (ProjectKey) 
		select ProjectKey from tProject (nolock) 
		where CompanyKey = @CompanyKey 
		and CampaignSegmentKey = @EntityKey
	
		-- needed for index in tCampaignEstByItem
		select @CampaignKey = CampaignKey
		from   tCampaignSegment (nolock)
		where  CampaignSegmentKey = @EntityKey
	end
	else if @Entity = ''tCampaign''
	begin
		insert #projects (ProjectKey) 
		select ProjectKey from tProject (nolock) 
		where CompanyKey = @CompanyKey 
		and CampaignKey = @EntityKey

		select @CampaignKey = @EntityKey
	end
	else if @Entity = ''tCampaignNoSegment''
	begin
		insert #projects (ProjectKey) 
		select ProjectKey from tProject (nolock) 
		where CompanyKey = @CompanyKey 
		and CampaignKey = @EntityKey
		and isnull(CampaignSegmentKey, 0) = 0
		
		select @CampaignKey = @EntityKey
	end
	
	insert #roll (
	    Entity, 
		EntityKey,
		ItemID, 
		ItemName,
		WorkTypeKey,
		WorkTypeID,
		WorkTypeName,	
		WorkTypeDisplayOrder,	
		Hours,
		HoursApproved,
		HoursBilled,
		HoursInvoiced,
		HoursWriteOff,
		HoursUnbilled,
		LaborNet,
		LaborNetApproved,
		LaborGross,
		LaborGrossApproved ,
		LaborUnbilled ,
		LaborBilled ,
		LaborInvoiced ,
		LaborWriteOff,
		LaborHoursWriteOff,
		MiscCostNet,
		MiscCostGross,
		MiscCostUnbilled,
		MiscCostWriteOff,
		MiscCostBilled,
		MiscCostInvoiced,
		ExpReceiptNet,
		ExpReceiptNetApproved,
		ExpReceiptGross,
		ExpReceiptGrossApproved,
		ExpReceiptUnbilled,
		ExpReceiptWriteOff,
		ExpReceiptBilled,
		ExpReceiptInvoiced,
		VoucherNet,
		VoucherNetApproved,
		VoucherGross,
		VoucherGrossApproved,
		VoucherOutsideCostsGross,
		VoucherOutsideCostsGrossApproved,
		VoucherUnbilled,
		VoucherWriteOff,
		VoucherBilled,
		VoucherInvoiced,
		OpenOrdersNet,
		OpenOrderNetApproved,
		OpenOrderGross,
		OpenOrderGrossApproved,
		OpenOrderUnbilled,
		OrderPrebilled,
		AmountBilled,
		AmountBilledNoTax,
		AdvanceBilled,
		AdvanceBilledOpen,
		EstQty,
		EstNet,
		EstGross,
		EstCOQty,
		EstCONet,
		EstCOGross)
   select Entity, 
		EntityKey,
		case when Entity = ''tItem'' then ''[No Item ID]'' else ''[No Service Code]'' end, --ItemID, 
		case when Entity = ''tItem'' then ''[No Item]'' else ''[No Service]'' end, --ItemName,
		0,    --WorkTypeKey,
		''[No Billing Item ID]'', --WorkTypeID,
		''[No Billing Item]'', --WorkTypeName,
		0,    --WorkTypeDisplayOrder		
		sum(Hours),
		sum(HoursApproved),
		sum(HoursBilled),
		sum(HoursInvoiced),
		sum(HoursWriteOff),
		sum(HoursUnbilled),
		sum(LaborNet),
		sum(LaborNetApproved),
		sum(LaborGross),
		sum(LaborGrossApproved),
		sum(LaborUnbilled),
		sum(LaborBilled),
		sum(LaborInvoiced),
		sum(LaborWriteOff),
		sum(HoursWriteOff),  --LaborHoursWriteOff
		sum(MiscCostNet),
		sum(MiscCostGross),
		sum(MiscCostUnbilled),
		sum(MiscCostWriteOff),
		sum(MiscCostBilled),
		sum(MiscCostInvoiced),
		sum(ExpReceiptNet),
		sum(ExpReceiptNetApproved),
		sum(ExpReceiptGross),
		sum(ExpReceiptGrossApproved),
		sum(ExpReceiptUnbilled),
		sum(ExpReceiptWriteOff),
		sum(ExpReceiptBilled),
		sum(ExpReceiptInvoiced),
		sum(VoucherNet),
		sum(VoucherNetApproved),
		sum(VoucherGross),
		sum(VoucherGrossApproved),
		sum(VoucherOutsideCostsGross),
		sum(VoucherOutsideCostsGrossApproved),
		sum(VoucherUnbilled),
		sum(VoucherWriteOff),
		sum(VoucherBilled),
		sum(VoucherInvoiced),
		sum(OpenOrderNet),
		sum(OpenOrderNetApproved),
		sum(OpenOrderGross),
		sum(OpenOrderGrossApproved),
		sum(OpenOrderUnbilled),
		sum(OrderPrebilled),
		sum(BilledAmount),
		sum(BilledAmountNoTax),
		sum(AdvanceBilled),
		sum(AdvanceBilledOpen),
		sum(EstQty),
		sum(EstNet),
		sum(EstGross),
		sum(EstCOQty),
		sum(EstCONet),
		sum(EstCOGross)
	from tProjectItemRollup roll (nolock)
	inner join #projects b on roll.ProjectKey = b.ProjectKey
	group by Entity, EntityKey
	
	-- now add the items on the campaign estimates
	-- they may likely not be in tProjectItemRollup 

	if @Entity = ''tCampaign''
	insert #roll (
	    Entity, 
		EntityKey,
		WorkTypeKey,
		WorkTypeDisplayOrder)
	select distinct ''tItem'', cebi.EntityKey, 0,0
	from   tCampaignEstByItem cebi (nolock)
	where  cebi.CampaignKey = @CampaignKey
	and    cebi.Entity = ''tItem''
	and    cebi.EntityKey not in (select EntityKey from #roll where Entity = ''tItem'')
			
	if @Entity = ''tCampaignSegment''
	insert #roll (
	    Entity, 
		EntityKey,
		WorkTypeKey,
		WorkTypeDisplayOrder)
	select distinct ''tItem'', cebi.EntityKey, 0,0
	from   tCampaignEstByItem cebi (nolock)
	where  cebi.CampaignKey = @CampaignKey
	and    cebi.CampaignSegmentKey = @EntityKey
	and    cebi.Entity = ''tItem''
	and    cebi.EntityKey not in (select EntityKey from #roll where Entity = ''tItem'')

	if @Entity = ''tCampaign''	
	insert #roll (
	    Entity, 
		EntityKey,
		WorkTypeKey,
		WorkTypeDisplayOrder)
	select distinct ''tService'', cebi.EntityKey, 0,0
	from   tCampaignEstByItem cebi (nolock)
	where  cebi.CampaignKey = @CampaignKey
	and    cebi.Entity = ''tService''
	and    cebi.EntityKey not in (select EntityKey from #roll where Entity = ''tService'')
	
	if @Entity = ''tCampaignSegment''	
	insert #roll (
	    Entity, 
		EntityKey,
		WorkTypeKey,
		WorkTypeDisplayOrder)
	select distinct ''tService'', cebi.EntityKey, 0,0
	from   tCampaignEstByItem cebi (nolock)
	where  cebi.CampaignKey = @CampaignKey
	and    cebi.CampaignSegmentKey = @EntityKey
	and    cebi.Entity = ''tService''
	and    cebi.EntityKey not in (select EntityKey from #roll where Entity = ''tService'')


	----- adding future data
	declare @Today smalldatetime
	SELECT @Today = CONVERT(SMALLDATETIME, (CONVERT(VARCHAR(10), GETDATE(), 101)), 101)

	insert #project_other (Entity, EntityKey, AllocatedHours, AllocatedGross)
	select ''tService'', isnull(tu.ServiceKey, 0), sum(tu.Hours), SUM(tu.Hours * tu.AHourlyRate)
	from   tTaskUser tu (nolock)
	inner join tTask t (nolock) on tu.TaskKey = t.TaskKey
	inner join #projects p (nolock) on t.ProjectKey = p.ProjectKey
	group by isnull(tu.ServiceKey, 0)

	UPDATE #project_other
			SET    #project_other.FutureAllocatedHours = ISNULL((
				select SUM(tu.Hours) 
				from   vTaskUserHour tu (nolock)
				inner join #projects p (nolock) on tu.ProjectKey = p.ProjectKey
				where tu.BucketStart > DATEADD(week, -1, @Today) 
				and   isnull(tu.ServiceKey, 0) = isnull(#project_other.EntityKey, 0) -- must join with the service key in EntityKey
				), 0)

	UPDATE #project_other
			SET    #project_other.FutureAllocatedGross = ISNULL((
				select SUM(tu.Hours * tu.AHourlyRate)
				from   vTaskUserHour tu (nolock)
				inner join #projects p (nolock) on tu.ProjectKey = p.ProjectKey
				where tu.BucketStart > DATEADD(week, -1, @Today) 
				and   isnull(tu.ServiceKey, 0) = isnull(#project_other.EntityKey, 0) -- must join with the service key in EntityKey
				), 0)
	


	insert #roll (
	    Entity, 
		EntityKey,
		WorkTypeKey,
		WorkTypeDisplayOrder
		)
	select ''tService'', b.EntityKey, 0,0
	from   #project_other b
	where  b.Entity = ''tService''
	and    b.EntityKey not in (select EntityKey from #roll where Entity = ''tService'')

	update #roll
	set    #roll.AllocatedHours = b.AllocatedHours,
		   #roll.AllocatedGross = b.AllocatedGross,
		   #roll.FutureAllocatedHours = b.FutureAllocatedHours,
		   #roll.FutureAllocatedGross = b.FutureAllocatedGross
	from   #project_other b
	where  #roll.Entity = b.Entity
	and    #roll.EntityKey = b.EntityKey

	-- now updates actuals like in Budget Analysis and budget fields 
	update #roll
	set    #roll.OutsideCostsNet = #roll.VoucherNet
	      ,#roll.InsideCostsNet = #roll.MiscCostNet + #roll.ExpReceiptNet
	      ,#roll.OpenOrdersGrossUnbilled = #roll.OpenOrderUnbilled -- used to be calculated unbilled, so use new field OpenOrderUnbilled 
	      ,#roll.OutsideCostsGrossUnbilled = #roll.VoucherUnbilled
	      ,#roll.InsideCostsGrossUnbilled = #roll.MiscCostUnbilled + #roll.ExpReceiptUnbilled
	      ,#roll.OutsideCostsGross = #roll.OrderPrebilled + #roll.VoucherOutsideCostsGross -- + roll.OpenOrderGross (34827)
		  ,#roll.InsideCostsGross = #roll.MiscCostGross + #roll.ExpReceiptGross
		  ,#roll.ExpenseWriteOff = #roll.MiscCostWriteOff + #roll.ExpReceiptWriteOff + #roll.VoucherWriteOff
		  ,#roll.ExpenseBilled = #roll.MiscCostBilled + #roll.ExpReceiptBilled + #roll.VoucherBilled + #roll.OrderPrebilled
		  ,#roll.ExpenseInvoiced = #roll.MiscCostInvoiced + #roll.ExpReceiptInvoiced + #roll.VoucherInvoiced + #roll.OrderPrebilled

	      ,#roll.CurrentBudgetHours = case when Entity = ''tService'' then EstQty + EstCOQty else 0 end
		  ,#roll.CurrentBudgetQty = case when Entity = ''tItem'' then EstQty + EstCOQty else 0 end
		  ,#roll.CurrentBudgetLaborNet = case when Entity = ''tService'' then EstNet + EstCONet else 0 end
		  ,#roll.CurrentBudgetLaborGross = case when Entity = ''tService'' then EstGross + EstCOGross else 0 end
		  ,#roll.CurrentBudgetExpenseNet = case when Entity = ''tItem'' then EstNet + EstCONet else 0 end
		  ,#roll.CurrentBudgetExpenseGross = case when Entity = ''tItem'' then EstGross + EstCOGross else 0 end
		  ,#roll.CurrentBudgetContingency = 0
		  ,#roll.CurrentTotalBudget = EstGross + EstCOGross
		  ,#roll.CurrentTotalBudgetCont = EstGross + EstCOGross
		  ,#roll.CurrentTotalBudgetNoTax = EstGross + EstCOGross
		  ,#roll.CurrentBudgetExpenseQuantity = case when Entity = ''tItem'' then EstQty + EstCOQty else 0 end

		  ,#roll.COBudgetHours = case when Entity = ''tService'' then EstCOQty else 0 end
		  ,#roll.COBudgetQty = case when Entity = ''tItem'' then EstCOQty else 0 end
		  ,#roll.COBudgetLaborNet = case when Entity = ''tService'' then EstCONet else 0 end
		  ,#roll.COBudgetLaborGross = case when Entity = ''tService'' then EstCOGross else 0 end
		  ,#roll.COBudgetExpenseNet = case when Entity = ''tItem'' then EstCONet else 0 end
		  ,#roll.COBudgetExpenseGross = case when Entity = ''tItem'' then EstCOGross else 0 end
		  ,#roll.COBudgetContingency= 0
		  ,#roll.COTotalBudget = EstCOGross 
		  ,#roll.COTotalBudgetCont = EstCOGross

		  ,#roll.OriginalBudgetHours = case when Entity = ''tService'' then EstQty else 0 end
		  ,#roll.OriginalBudgetQty = case when Entity = ''tItem'' then EstQty else 0 end
		  ,#roll.OriginalBudgetLaborNet = case when Entity = ''tService'' then EstNet else 0 end
		  ,#roll.OriginalBudgetLaborGross = case when Entity = ''tService'' then EstGross else 0 end
		  ,#roll.OriginalBudgetExpenseNet = case when Entity = ''tItem'' then EstNet else 0 end
		  ,#roll.OriginalBudgetExpenseGross = case when Entity = ''tItem'' then EstGross else 0 end
		  ,#roll.OriginalBudgetContingency = 0
		  ,#roll.OriginalTotalBudget = EstGross 
		  ,#roll.OriginalTotalBudgetCont = EstGross
	      
	    -- now update the campaign budget fields (from estimates on campaigns)  

	    if @Entity = ''tCampaignSegment''
		begin
			update #roll
			set    #roll.C_CurrentBudgetHours = case when #roll.Entity = ''tService'' then cebi.Qty + cebi.COQty else 0 end	
			      ,#roll.C_CurrentBudgetLaborNet = case when #roll.Entity = ''tService'' then cebi.Net + cebi.CONet else 0 end
		          ,#roll.C_CurrentBudgetLaborGross = case when #roll.Entity = ''tService'' then cebi.Gross + cebi.COGross else 0 end
		          ,#roll.C_CurrentBudgetExpenseNet = case when #roll.Entity = ''tItem'' then cebi.Net + cebi.CONet else 0 end
		          ,#roll.C_CurrentBudgetExpenseGross = case when #roll.Entity = ''tItem'' then cebi.Gross + cebi.COGross else 0 end
		          ,#roll.C_CurrentBudgetContingency = 0
		          ,#roll.C_CurrentTotalBudget = cebi.Gross + cebi.COGross
		          ,#roll.C_CurrentTotalBudgetCont = cebi.Gross + cebi.COGross

				  ,#roll.C_COBudgetHours = case when #roll.Entity = ''tService'' then cebi.COQty else 0 end
				  ,#roll.C_COBudgetLaborNet = case when #roll.Entity = ''tService'' then cebi.CONet else 0 end
				  ,#roll.C_COBudgetLaborGross = case when #roll.Entity = ''tService'' then cebi.COGross else 0 end
				  ,#roll.C_COBudgetExpenseNet = case when #roll.Entity = ''tItem'' then cebi.CONet else 0 end
				  ,#roll.C_COBudgetExpenseGross = case when #roll.Entity = ''tItem'' then cebi.COGross else 0 end
				  ,#roll.C_COBudgetContingency= 0
				  ,#roll.C_COTotalBudget = cebi.COGross 
				  ,#roll.C_COTotalBudgetCont = cebi.COGross

				  ,#roll.C_OriginalBudgetHours = case when #roll.Entity = ''tService'' then cebi.Qty else 0 end
				  ,#roll.C_OriginalBudgetLaborNet = case when #roll.Entity = ''tService'' then cebi.Net else 0 end
				  ,#roll.C_OriginalBudgetLaborGross = case when #roll.Entity = ''tService'' then cebi.Gross else 0 end
				  ,#roll.C_OriginalBudgetExpenseNet = case when #roll.Entity = ''tItem'' then cebi.Net else 0 end
				  ,#roll.C_OriginalBudgetExpenseGross = case when #roll.Entity = ''tItem'' then cebi.Gross else 0 end
				  ,#roll.C_OriginalBudgetContingency = 0
				  ,#roll.C_OriginalTotalBudget = cebi.Gross 
				  ,#roll.C_OriginalTotalBudgetCont = cebi.Gross
		  
			from   tCampaignEstByItem cebi (nolock)
			where  cebi.CampaignSegmentKey = @EntityKey
			and    cebi.CampaignKey = @CampaignKey
			and    cebi.Entity = #roll.Entity COLLATE DATABASE_DEFAULT
			and    cebi.EntityKey = #roll.EntityKey
			
		end
		
		if @Entity = ''tCampaign''
		begin
			update #roll
			set    #roll.C_CurrentBudgetHours = case when #roll.Entity = ''tService'' then cebi.Qty + cebi.COQty else 0 end	
			      ,#roll.C_CurrentBudgetLaborNet = case when #roll.Entity = ''tService'' then cebi.Net + cebi.CONet else 0 end
		          ,#roll.C_CurrentBudgetLaborGross = case when #roll.Entity = ''tService'' then cebi.Gross + cebi.COGross else 0 end
		          ,#roll.C_CurrentBudgetExpenseNet = case when #roll.Entity = ''tItem'' then cebi.Net + cebi.CONet else 0 end
		          ,#roll.C_CurrentBudgetExpenseGross = case when #roll.Entity = ''tItem'' then cebi.Gross + cebi.COGross else 0 end
		          ,#roll.C_CurrentBudgetContingency = 0
		          ,#roll.C_CurrentTotalBudget = cebi.Gross + cebi.COGross
		          ,#roll.C_CurrentTotalBudgetCont = cebi.Gross + cebi.COGross

				  ,#roll.C_COBudgetHours = case when #roll.Entity = ''tService'' then cebi.COQty else 0 end
				  ,#roll.C_COBudgetLaborNet = case when #roll.Entity = ''tService'' then cebi.CONet else 0 end
				  ,#roll.C_COBudgetLaborGross = case when #roll.Entity = ''tService'' then cebi.COGross else 0 end
				  ,#roll.C_COBudgetExpenseNet = case when #roll.Entity = ''tItem'' then cebi.CONet else 0 end
				  ,#roll.C_COBudgetExpenseGross = case when #roll.Entity = ''tItem'' then cebi.COGross else 0 end
				  ,#roll.C_COBudgetContingency= 0
				  ,#roll.C_COTotalBudget = cebi.COGross 
				  ,#roll.C_COTotalBudgetCont = cebi.COGross

				  ,#roll.C_OriginalBudgetHours = case when #roll.Entity = ''tService'' then cebi.Qty else 0 end
				  ,#roll.C_OriginalBudgetLaborNet = case when #roll.Entity = ''tService'' then cebi.Net else 0 end
				  ,#roll.C_OriginalBudgetLaborGross = case when #roll.Entity = ''tService'' then cebi.Gross else 0 end
				  ,#roll.C_OriginalBudgetExpenseNet = case when #roll.Entity = ''tItem'' then cebi.Net else 0 end
				  ,#roll.C_OriginalBudgetExpenseGross = case when #roll.Entity = ''tItem'' then cebi.Gross else 0 end
				  ,#roll.C_OriginalBudgetContingency = 0
				  ,#roll.C_OriginalTotalBudget = cebi.Gross 
				  ,#roll.C_OriginalTotalBudgetCont = cebi.Gross
		  
			from   
					(select CampaignKey, Entity, EntityKey
					, Sum(Qty) As Qty, Sum(Net) As Net, Sum(Gross) As Gross
					, Sum(COQty) As COQty, Sum(CONet) As CONet, Sum(COGross) As COGross
					 from   tCampaignEstByItem  (nolock)
					 where CampaignKey = @EntityKey
					 group by CampaignKey, Entity, EntityKey) as cebi  
			where  cebi.Entity = #roll.Entity COLLATE DATABASE_DEFAULT
			and    cebi.EntityKey = #roll.EntityKey
			
		end
		
		UPDATE #roll
		SET #roll.BilledDifference = ISNULL((SELECT SUM(Round(t.BilledHours * t.BilledRate, 2) -
														Round(t.ActualHours * t.ActualRate, 2) 
		                                                ) 
								FROM tTime t (NOLOCK) 
								WHERE t.ProjectKey in (select ProjectKey from #projects)
								AND   #roll.Entity = ''tService''
								AND   ISNULL(t.ServiceKey, 0) = #roll.EntityKey
								AND  t.InvoiceLineKey > 0  
								), 0) 
								+
								ISNULL((
								SELECT SUM(mc.AmountBilled - mc.BillableCost) 
								FROM tMiscCost mc (NOLOCK)
								WHERE mc.ProjectKey in (select ProjectKey from #projects)
								AND   #roll.Entity = ''tItem''
								AND   ISNULL(mc.ItemKey, 0) = #roll.EntityKey
								AND   mc.InvoiceLineKey > 0
								), 0)
								+
								ISNULL((
								SELECT SUM(er.AmountBilled - er.BillableCost) 
								FROM tExpenseReceipt er (NOLOCK)
								WHERE er.ProjectKey in (select ProjectKey from #projects)
								AND   #roll.Entity = ''tItem''
								AND   ISNULL(er.ItemKey, 0) = #roll.EntityKey
								AND   er.VoucherDetailKey IS NULL 
								AND   er.InvoiceLineKey > 0
								), 0)
								+
								ISNULL((
								SELECT SUM(vd.AmountBilled - vd.BillableCost) 
								FROM tVoucherDetail vd (NOLOCK)
									INNER JOIN tVoucher v (NOLOCK) ON vd.VoucherKey = v.VoucherKey
								WHERE vd.ProjectKey in (select ProjectKey from #projects)
								AND   #roll.Entity = ''tItem''
								AND   ISNULL(vd.ItemKey, 0) = #roll.EntityKey
								AND   vd.InvoiceLineKey > 0
								), 0)
								+
								ISNULL((
								SELECT SUM(pod.AmountBilled - 
										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) -- BillableCost 
								FROM tPurchaseOrderDetail pod (NOLOCK)
									INNER JOIN tPurchaseOrder po (NOLOCK) ON pod.PurchaseOrderKey = po.PurchaseOrderKey
								WHERE po.CompanyKey = @CompanyKey  
								AND  pod.ProjectKey in (select ProjectKey from #projects)
								AND   #roll.Entity = ''tItem''
								AND   ISNULL(pod.ItemKey, 0) = #roll.EntityKey
								AND pod.InvoiceLineKey > 0
								), 0)
	
	-- just for the project budget screen 			 
	if @Entity = ''tProject''
	begin
		 update #roll
		set    #roll.PurchasedQty = ISNULL((
			select sum(mc.Quantity) from tMiscCost mc (nolock)
			where  mc.ProjectKey = @EntityKey -- use index by Project
			and    mc.ItemKey = #roll.EntityKey and #roll.Entity = ''tItem'' 
		),0)

		 update #roll
		set    #roll.PurchasedQty = ISNULL(#roll.PurchasedQty, 0) + ISNULL((
			select sum(vd.Quantity) from tVoucherDetail vd (nolock)
			where  vd.ProjectKey = @EntityKey -- use index by Project
			and    vd.ItemKey = #roll.EntityKey and #roll.Entity = ''tItem'' 
		),0)

		 update #roll
		set    #roll.ActualQuantity = ISNULL((
			select sum(mc.Quantity) from tMiscCost mc (nolock)
			where  mc.ProjectKey = @EntityKey -- use index by Project
			and    mc.ItemKey = #roll.EntityKey and #roll.Entity = ''tItem'' 
		),0)

		 update #roll
		set    #roll.ActualQuantity = ISNULL(#roll.ActualQuantity, 0) + ISNULL((
			select sum(er.ActualQty) from tExpenseReceipt er (nolock)
			where  er.ProjectKey = @EntityKey -- use index by Project
			and    er.ItemKey = #roll.EntityKey and #roll.Entity = ''tItem'' 
		),0)

		 update #roll
		set    #roll.ActualQuantity = ISNULL(#roll.ActualQuantity, 0) + ISNULL((
			select sum(vd.Quantity) from tVoucherDetail vd (nolock)
			where  vd.ProjectKey = @EntityKey -- use index by Project
			and    vd.ItemKey = #roll.EntityKey and #roll.Entity = ''tItem'' 
		),0)


	end

	-- Final Calculations
	UPDATE #roll
	SET    OutsideCostsNet				= ISNULL(OutsideCostsNet, 0) -- + ISNULL(OpenOrdersNet, 0)  -- 10/15/2008
		   ,OutsideCostsGrossUnbilled	= ISNULL(OutsideCostsGrossUnbilled,0) -- + ISNULL(OpenOrdersGrossUnbilled, 0) -- 10/15/2008	
	
	UPDATE #roll
    SET    TotalCostsNet			= ISNULL(InsideCostsNet, 0) + ISNULL(OutsideCostsNet, 0)  
          ,TotalCostsGrossUnbilled	= ISNULL(InsideCostsGrossUnbilled,0) + ISNULL(OutsideCostsGrossUnbilled, 0)
          ,TotalCostsGross			= ISNULL(InsideCostsGross, 0) + ISNULL(OutsideCostsGross, 0)	
		  
		  -- These 2 added 10/15/2008
		  ,TotalNet					= ISNULL(LaborNet, 0) + ISNULL(InsideCostsNet, 0) + ISNULL(OutsideCostsNet, 0)
		                              + ISNULL(OpenOrdersNet, 0) 
		  ,TotalGrossUnbilled		= ISNULL(LaborUnbilled, 0) + ISNULL(InsideCostsGrossUnbilled, 0) + ISNULL(OutsideCostsGrossUnbilled, 0)
		                              + ISNULL(OpenOrdersGrossUnbilled, 0) 
	
		  ,TotalGross				= ISNULL(LaborGross, 0) + ISNULL(InsideCostsGross, 0) + ISNULL(OutsideCostsGross, 0)
		                              + ISNULL(OpenOrdersGrossUnbilled, 0) -- Added 10/15/2008
		  ,SalesTax					= ISNULL(AmountBilled,0) - ISNULL(AmountBilledNoTax, 0)
		  
	UPDATE #roll
    SET  TotalGrossUnbilledFixedFee = ISNULL(TotalGross,0) - ISNULL(AmountBilledNoTax, 0)
	
	--select 	LaborGross , InsideCostsGross, + OutsideCostsGross, OpenOrdersGrossUnbilled from #roll
	
	-- WriteOff stuff for Abelson Taylor
	UPDATE #roll
	SET   TotalGrossAfterWriteOff	= ISNULL(TotalGross,0) - ISNULL(LaborWriteOff, 0) - ISNULL(ExpenseWriteOff, 0) 
		 ,HoursAfterWriteOff		= ISNULL(Hours, 0) - ISNULL(HoursWriteOff , 0)
		 ,LaborGrossAfterWriteOff	= ISNULL(LaborGross, 0) - ISNULL(LaborWriteOff , 0)
		 ,TotalCostsGrossAfterWriteOff			= ISNULL(TotalCostsGross, 0) + ISNULL(OpenOrdersGrossUnbilled, 0) - ISNULL(ExpenseWriteOff, 0)
		 ,TotalCostsGrossAfterWriteOffNoOrder	= ISNULL(TotalCostsGross, 0) - ISNULL(ExpenseWriteOff, 0)
		 	
	-- mainly for better rendering on grid
	update #roll 
	    set Hours = isnull(Hours , 0),
		HoursApproved  = isnull(HoursApproved , 0),
		HoursBilled  = isnull(HoursBilled , 0),
		HoursInvoiced  = isnull(HoursInvoiced , 0),
		HoursWriteOff  = isnull(HoursWriteOff , 0),
		HoursUnbilled  = isnull(HoursUnbilled , 0),
		LaborNet  = isnull( LaborNet, 0),
		LaborNetApproved  = isnull(LaborNetApproved , 0),
		LaborGross  = isnull(LaborGross , 0),
		LaborGrossApproved  = isnull(LaborGrossApproved , 0),
		LaborUnbilled  = isnull(LaborUnbilled , 0),
		LaborBilled  = isnull(LaborBilled , 0),
		LaborInvoiced  = isnull(LaborInvoiced , 0),
		LaborWriteOff = isnull(LaborWriteOff , 0),
		LaborHoursWriteOff = isnull(LaborHoursWriteOff , 0),
		MiscCostNet = isnull(MiscCostNet , 0),
		MiscCostGross  = isnull(MiscCostGross , 0),
		MiscCostUnbilled  = isnull(MiscCostUnbilled , 0),
		MiscCostWriteOff = isnull(MiscCostWriteOff , 0),
		MiscCostBilled = isnull(MiscCostBilled , 0),
		MiscCostInvoiced = isnull(MiscCostInvoiced , 0),
		ExpReceiptNet = isnull(ExpReceiptNet , 0),
		ExpReceiptNetApproved = isnull(ExpReceiptNetApproved , 0),
		ExpReceiptGross = isnull(ExpReceiptGross , 0),
		ExpReceiptGrossApproved = isnull(ExpReceiptGrossApproved , 0),
		ExpReceiptUnbilled = isnull(ExpReceiptUnbilled , 0),
		ExpReceiptWriteOff = isnull(ExpReceiptWriteOff , 0),
		ExpReceiptBilled = isnull(ExpReceiptBilled , 0),
		ExpReceiptInvoiced = isnull(ExpReceiptInvoiced , 0),
		VoucherNet = isnull(VoucherNet , 0),
		VoucherNetApproved = isnull(VoucherNetApproved , 0),
		VoucherGross  = isnull(VoucherGross , 0),
		VoucherGrossApproved = isnull(VoucherGrossApproved , 0),
		VoucherOutsideCostsGross = isnull(VoucherOutsideCostsGross , 0),
		VoucherOutsideCostsGrossApproved = isnull(VoucherOutsideCostsGrossApproved , 0),
		VoucherUnbilled = isnull(VoucherUnbilled , 0),
		VoucherWriteOff = isnull(VoucherWriteOff , 0),
		VoucherBilled = isnull(VoucherBilled , 0),
		VoucherInvoiced = isnull(VoucherInvoiced , 0),
		OpenOrdersNet = isnull(OpenOrdersNet , 0),
		OpenOrderNetApproved = isnull(OpenOrderNetApproved , 0),
		OpenOrderGross = isnull(OpenOrderGross , 0),
		OpenOrderGrossApproved = isnull(OpenOrderGrossApproved , 0),
		OrderPrebilled = isnull( OrderPrebilled, 0),
		AmountBilled = isnull(AmountBilled , 0),
		AmountBilledNoTax  = isnull(AmountBilledNoTax , 0),
		AdvanceBilled  = isnull(AdvanceBilled , 0),
		AdvanceBilledOpen = isnull(AdvanceBilledOpen , 0),

		AllocatedHours = isnull(AllocatedHours , 0),
		AllocatedGross = isnull(AllocatedGross , 0),
		FutureAllocatedHours = isnull(FutureAllocatedHours , 0),
		FutureAllocatedGross = isnull(FutureAllocatedGross , 0),

		EstQty = isnull(EstQty , 0),
		EstNet = isnull(EstNet , 0),
		EstGross = isnull(EstGross , 0),
		EstCOQty  = isnull(EstCOQty , 0),
		EstCONet = isnull( EstCONet, 0),
		EstCOGross  = isnull(EstCOGross , 0),
		
		-- Actuals fields...Cloned from spRptBudgetAnalysis
		OutsideCostsNet = isnull(OutsideCostsNet , 0)
		,InsideCostsNet = isnull( InsideCostsNet, 0)
		
		,OpenOrdersGrossUnbilled  = isnull(OpenOrdersGrossUnbilled , 0)
		,OutsideCostsGrossUnbilled  = isnull(OutsideCostsGrossUnbilled , 0)
		,InsideCostsGrossUnbilled  = isnull(InsideCostsGrossUnbilled , 0)
		
		,OutsideCostsGross = isnull(OutsideCostsGross , 0)
		,InsideCostsGross = isnull(InsideCostsGross , 0)
		
		,ExpenseWriteOff = isnull(ExpenseWriteOff , 0)
		,ExpenseBilled = isnull(ExpenseBilled , 0)	
		,ExpenseInvoiced = isnull(ExpenseInvoiced , 0)	
				
		-- Budget fields...Cloned from spRptBudgetAnalysis
		,CurrentBudgetHours = isnull(CurrentBudgetHours , 0)
		,CurrentBudgetQty = isnull(CurrentBudgetQty , 0)
		,CurrentBudgetLaborNet = isnull(CurrentBudgetLaborNet , 0)
		,CurrentBudgetLaborGross = isnull(CurrentBudgetLaborGross , 0)
		,CurrentBudgetExpenseNet = isnull(CurrentBudgetExpenseNet , 0)
		,CurrentBudgetExpenseGross = isnull(CurrentBudgetExpenseGross , 0)
		,CurrentBudgetContingency = isnull(CurrentBudgetContingency , 0)
		,CurrentTotalBudget = isnull(CurrentTotalBudget , 0)
		,CurrentTotalBudgetCont = isnull(CurrentTotalBudgetCont , 0)
		,CurrentTotalBudgetWithTax  = isnull(CurrentTotalBudgetWithTax , 0)		-- not calc''ed, but added for rendering on the grid (was blank)
		,CurrentTotalBudgetContWithTax = isnull(CurrentTotalBudgetContWithTax , 0)
		,CurrentTotalBudgetNoTax = isnull(CurrentTotalBudgetNoTax , 0)

		,COBudgetHours  = isnull(COBudgetHours , 0)
		,COBudgetQty  = isnull(COBudgetQty , 0)
		,COBudgetLaborNet  = isnull(COBudgetLaborNet , 0)
		,COBudgetLaborGross = isnull(COBudgetLaborGross , 0)
		,COBudgetExpenseNet = isnull(COBudgetExpenseNet , 0)
		,COBudgetExpenseGross = isnull(COBudgetExpenseGross , 0)
		,COBudgetContingency = isnull(COBudgetContingency , 0)
		,COTotalBudget  = isnull(COTotalBudget , 0)
		,COTotalBudgetCont  = isnull(COTotalBudgetCont , 0)
		,COTotalBudgetWithTax  = isnull(COTotalBudgetWithTax , 0)
		,COTotalBudgetContWithTax  = isnull(COTotalBudgetContWithTax , 0)

		,OriginalBudgetHours  = isnull( OriginalBudgetHours, 0)
		,OriginalBudgetQty  = isnull( OriginalBudgetQty, 0)
		,OriginalBudgetLaborNet  = isnull( OriginalBudgetLaborNet, 0)
		,OriginalBudgetLaborGross  = isnull(OriginalBudgetLaborGross , 0)
		,OriginalBudgetExpenseNet  = isnull(OriginalBudgetExpenseNet , 0)
		,OriginalBudgetExpenseGross  = isnull(OriginalBudgetExpenseGross , 0)
		,OriginalBudgetContingency  = isnull( OriginalBudgetContingency, 0)
		,OriginalTotalBudget  = isnull(OriginalTotalBudget , 0)
		,OriginalTotalBudgetCont = isnull(OriginalTotalBudgetCont , 0)
		,OriginalTotalBudgetWithTax = isnull(OriginalTotalBudgetWithTax , 0)
		,OriginalTotalBudgetContWithTax  = isnull(OriginalTotalBudgetContWithTax , 0)
		
		-- Campaign Budget fields
		,C_CurrentBudgetHours = isnull(C_CurrentBudgetHours , 0)
		,C_CurrentBudgetLaborNet = isnull(C_CurrentBudgetLaborNet , 0)
		,C_CurrentBudgetLaborGross = isnull(C_CurrentBudgetLaborGross , 0)
		,C_CurrentBudgetExpenseNet = isnull(C_CurrentBudgetExpenseNet , 0)
		,C_CurrentBudgetExpenseGross  = isnull(C_CurrentBudgetExpenseGross , 0)
		,C_CurrentBudgetContingency  = isnull(C_CurrentBudgetContingency , 0)
		,C_CurrentTotalBudget  = isnull(C_CurrentTotalBudget , 0)
		,C_CurrentTotalBudgetWithTax  = isnull(C_CurrentTotalBudgetWithTax , 0)
		,C_CurrentTotalBudgetCont  = isnull(C_CurrentTotalBudgetCont , 0)
		,C_CurrentTotalBudgetContWithTax  = isnull(C_CurrentTotalBudgetContWithTax , 0)

		,C_COBudgetHours = isnull(C_COBudgetHours , 0)
		,C_COBudgetLaborNet  = isnull(C_COBudgetLaborNet , 0)
		,C_COBudgetLaborGross  = isnull(C_COBudgetLaborGross , 0)
		,C_COBudgetExpenseNet  = isnull(C_COBudgetExpenseNet , 0)
		,C_COBudgetExpenseGross  = isnull(C_COBudgetExpenseGross , 0)
		,C_COBudgetContingency  = isnull(C_COBudgetContingency , 0)
		,C_COTotalBudget = isnull(C_COTotalBudget , 0)
		,C_COTotalBudgetWithTax  = isnull(C_COTotalBudgetWithTax , 0)
		,C_COTotalBudgetCont  = isnull(C_COTotalBudgetCont , 0)
		,C_COTotalBudgetContWithTax  = isnull(C_COTotalBudgetContWithTax , 0)

		,C_OriginalBudgetHours  = isnull(C_OriginalBudgetHours , 0)
		,C_OriginalBudgetLaborNet  = isnull(C_OriginalBudgetLaborNet , 0)
		,C_OriginalBudgetLaborGross  = isnull(C_OriginalBudgetLaborGross , 0)
		,C_OriginalBudgetExpenseNet  = isnull(C_OriginalBudgetExpenseNet , 0)
		,C_OriginalBudgetExpenseGross  = isnull(C_OriginalBudgetExpenseGross , 0)
		,C_OriginalBudgetContingency  = isnull(C_OriginalBudgetContingency , 0)
		,C_OriginalTotalBudget  = isnull(C_OriginalTotalBudget , 0)
		,C_OriginalTotalBudgetWithTax  = isnull(C_OriginalTotalBudgetWithTax , 0)
		,C_OriginalTotalBudgetCont  = isnull(C_OriginalTotalBudgetCont , 0)
		,C_OriginalTotalBudgetContWithTax = isnull(C_OriginalTotalBudgetContWithTax , 0)

		-- Totals...Cloned from spRptBudgetAnalysis
		,TotalCostsNet  = isnull(TotalCostsNet , 0)				-- InsideCostsNet + OutsideCostsNet
		,TotalCostsGrossUnbilled  = isnull(TotalCostsGrossUnbilled , 0)		-- InsideCostsGrossUnbilled + OutsideCostsGrossUnbilled
		,TotalCostsGross  = isnull(TotalCostsGross , 0)				-- InsideCostsGross + OutsideCostsGross

		,TotalNet  = isnull(TotalNet , 0)					-- InsideCostsNet + OutsideCostsNet + OpenOrdersNet + LaborNet
		,TotalGrossUnbilled  = isnull(TotalGrossUnbilled , 0)			-- InsideCostsGrossUnbilled + OutsideCostsGrossUnbilled + OpenOrdersGrossUnbilled + LaborGrossUnbilled
		,TotalGross  = isnull(TotalGross , 0)					-- InsideCostsGross + OutsideCostsGross + OpenOrdersGrossUnbilled + LaborGross
		,SalesTax = ISNULL(SalesTax, 0)
		,TotalGrossUnbilledFixedFee = ISNULL(TotalGrossUnbilledFixedFee, 0)
		-- Variance calcs...Cloned from spRptBudgetAnalysis
		,HoursBilledRemaining  = isnull(HoursBilledRemaining , 0)
		,HoursBilledRemainingP  = isnull(HoursBilledRemainingP , 0)
		,HoursRemaining  = isnull(HoursRemaining , 0)
		,HoursRemainingP  = isnull(HoursRemainingP , 0)
		,LaborNetRemaining  = isnull(LaborNetRemaining , 0)
		,LaborNetRemainingP  = isnull(LaborNetRemainingP , 0)
		,LaborGrossRemaining  = isnull(LaborGrossRemaining , 0)
		,LaborGrossRemainingP  = isnull(LaborGrossRemainingP , 0)

		,CostsNetRemaining = isnull(CostsNetRemaining , 0)
		,CostsNetRemainingP  = isnull(CostsNetRemainingP , 0)
		,CostsGrossRemaining  = isnull(CostsGrossRemaining , 0)
		,CostsGrossRemainingP  = isnull(CostsGrossRemainingP , 0)

		,ToBillRemaining  = isnull(ToBillRemaining , 0)
		,ToBillRemainingP  = isnull(ToBillRemainingP , 0)
		,GrossRemaining  = isnull(GrossRemaining , 0)
		,GrossRemainingP  = isnull(GrossRemainingP , 0)
				
		-- BilledDifference		
		,BilledDifference  = isnull(BilledDifference , 0)
			
		,PurchasedQty = isnull(PurchasedQty , 0)

	
	UPDATE #roll
	SET    HoursBilledRemaining	= CurrentBudgetHours - HoursBilled
		   ,HoursRemaining		= CurrentBudgetHours - Hours 
     	   ,LaborNetRemaining	= CurrentBudgetLaborNet - LaborNet 
		   ,LaborGrossRemaining	= CurrentBudgetLaborGross - LaborGross
		   ,CostsNetRemaining	= CurrentBudgetExpenseNet - TotalCostsNet 
		   ,CostsGrossRemaining	= CurrentBudgetExpenseGross - TotalCostsGross 
		   ,ToBillRemaining		= CurrentTotalBudget - AmountBilled 
		   ,GrossRemaining		= CurrentTotalBudget - TotalGross
		 
			-- Write off stuff for Abelson Taylor
			,HoursAfterWriteOffRemaining		= CurrentBudgetHours - HoursAfterWriteOff 
			,RemainingAllocatedHours = AllocatedHours - Hours
			,LaborGrossAfterWriteOffRemaining	= CurrentBudgetLaborGross - LaborGrossAfterWriteOff
			,CostsGrossAfterWriteOffRemaining	= CurrentBudgetExpenseGross - TotalCostsGrossAfterWriteOff 
		    ,CostsGrossAfterWriteOffNoOrderRemaining	= CurrentBudgetExpenseGross - TotalCostsGrossAfterWriteOffNoOrder 
			,FutureLaborGrossRemaining		= FutureAllocatedGross  - LaborGross
		    ,HoursAfterWriteOffRemainingP				= CASE WHEN CurrentBudgetHours = 0		THEN 0 ELSE 100 * (CurrentBudgetHours - HoursAfterWriteOff)/CurrentBudgetHours END
		    ,LaborGrossAfterWriteOffRemainingP			= CASE WHEN CurrentBudgetLaborGross = 0	THEN 0 ELSE 100 * (CurrentBudgetLaborGross - LaborGrossAfterWriteOff)/CurrentBudgetLaborGross END
		    ,CostsGrossAfterWriteOffRemainingP			= CASE WHEN CurrentBudgetExpenseGross = 0 THEN 0 ELSE 100 * (CurrentBudgetExpenseGross - TotalCostsGrossAfterWriteOff)/CurrentBudgetExpenseGross END
		    ,CostsGrossAfterWriteOffNoOrderRemainingP	= CASE WHEN CurrentBudgetExpenseGross = 0 THEN 0 ELSE 100 * (CurrentBudgetExpenseGross - TotalCostsGrossAfterWriteOffNoOrder)/CurrentBudgetExpenseGross END
		  
			-- If numerator is zero, I take 0% arbitrarilly	
		   ,HoursBilledRemainingP	= CASE WHEN CurrentBudgetHours = 0				THEN 0 ELSE 100 * (CurrentBudgetHours - HoursBilled) /CurrentBudgetHours END
		   ,HoursRemainingP			= CASE WHEN CurrentBudgetHours = 0		THEN 0 ELSE 100 * (CurrentBudgetHours - Hours)/CurrentBudgetHours END
		   ,LaborNetRemainingP		= CASE WHEN CurrentBudgetLaborNet = 0	THEN 0 ELSE 100 * (CurrentBudgetLaborNet - LaborNet)/CurrentBudgetLaborNet END
	       ,LaborGrossRemainingP	= CASE WHEN CurrentBudgetLaborGross = 0	THEN 0 ELSE 100 * (CurrentBudgetLaborGross - LaborGross)/CurrentBudgetLaborGross END
		   ,CostsNetRemainingP		= CASE WHEN CurrentBudgetExpenseNet = 0	THEN 0 ELSE 100 * (CurrentBudgetExpenseNet - TotalCostsNet)/CurrentBudgetExpenseNet END
		   ,CostsGrossRemainingP	= CASE WHEN CurrentBudgetExpenseGross = 0 THEN 0 ELSE 100 * (CurrentBudgetExpenseGross - TotalCostsGross)/CurrentBudgetExpenseGross END
		   ,ToBillRemainingP		= CASE WHEN CurrentTotalBudget = 0		THEN 0 ELSE 100 * (CurrentTotalBudget - AmountBilled)/CurrentTotalBudget END
		   ,GrossRemainingP			= CASE WHEN CurrentTotalBudget = 0		THEN 0 ELSE 100 * (CurrentTotalBudget - TotalGross)/CurrentTotalBudget END
		   ,RemainingAllocatedHoursP = CASE WHEN AllocatedHours = 0		THEN 0 ELSE 100 * (AllocatedHours - Hours)/AllocatedHours END

	update #roll
    set    #roll.ItemID = ''No Item ID''
          ,#roll.ItemName = ''No Item''
    where  #roll.Entity = ''tItem''
    and    #roll.EntityKey = 0

	update #roll
    set    #roll.ItemID = ''No Service Code''
          ,#roll.ItemName = ''No Service''
    where  #roll.Entity = ''tService''
    and    #roll.EntityKey = 0
      
	update #roll
    set    #roll.ItemID = i.ItemID
          ,#roll.ItemName = i.ItemName
          ,#roll.WorkTypeKey = isnull(i.WorkTypeKey, 0)
    from   tItem i (nolock)
    where  #roll.Entity = ''tItem''
    and    #roll.EntityKey = i.ItemKey
     
	update #roll
    set    #roll.ItemID = s.ServiceCode
          ,#roll.ItemName = s.Description
          ,#roll.WorkTypeKey = isnull(s.WorkTypeKey, 0)
    from   tService s (nolock)
    where  #roll.Entity = ''tService''
    and    #roll.EntityKey = s.ServiceKey

	update #roll
	set    WorkTypeID = ''[No Billing Item ID]''
		   ,WorkTypeName = ''[No Billing Item]''
		   ,WorkTypeKey = isnull(WorkTypeKey, 0)
	where  isnull(WorkTypeKey, 0) = 0

	if @LayoutKey = 0
	begin
		-- problem here because display order in tWorkType not unique or missing
		create table #sorted (SortKey int identity(1,1), Entity varchar(50) null, EntityKey int null)
	
		-- no layout, rely on WT display order then Item Name
		update #roll
		set    #roll.WorkTypeID = wt.WorkTypeID
			  ,#roll.WorkTypeName = wt.WorkTypeName
			  ,#roll.WorkTypeDisplayOrder = wt.DisplayOrder
		from   tWorkType wt (nolock)
		where  #roll.WorkTypeKey = wt.WorkTypeKey 

		-- Now update entity specific WorkTypeNames
		UPDATE	#roll
		SET		#roll.WorkTypeName = cust.Subject
		FROM	tWorkTypeCustom cust (nolock)
		WHERE	#roll.WorkTypeKey = cust.WorkTypeKey
		AND		cust.Entity = @Entity
		AND		cust.EntityKey = @EntityKey

		insert  #sorted (Entity, EntityKey)
		select  Entity, EntityKey
		from    #roll
		order   by isnull(WorkTypeDisplayOrder,0), WorkTypeName, ItemName

		update  #roll
		set     #roll.WorkTypeDisplayOrder = #sorted.SortKey
		from    #sorted
		where   #roll.Entity = #sorted.Entity collate database_default
		and     #roll.EntityKey = #sorted.EntityKey

	end
	else
	begin
		-- the items have been reorganized on the layout 
		update #roll
		set    #roll.WorkTypeKey = 0
	
		-- get WT key only when parent entity is tWorkType	
		update #roll
		set    #roll.WorkTypeKey = lb.ParentEntityKey
		from   tLayoutBilling lb (nolock)
		where  lb.LayoutKey = @LayoutKey
		and    #roll.Entity = lb.Entity COLLATE DATABASE_DEFAULT
		and    #roll.EntityKey = lb.EntityKey     				
	    and    lb.ParentEntity = ''tWorkType''
	

		update #roll
		set    #roll.WorkTypeID = wt.WorkTypeID
			  ,#roll.WorkTypeName = wt.WorkTypeName
		from   tWorkType wt (nolock)
		where  #roll.WorkTypeKey = wt.WorkTypeKey 
		
		-- Now update entity specific WorkTypeNames
		UPDATE	#roll
		SET		#roll.WorkTypeName = cust.Subject
		FROM	tWorkTypeCustom cust (nolock)
		WHERE	#roll.WorkTypeKey = cust.WorkTypeKey
		AND		cust.Entity = @Entity
		AND		cust.EntityKey = @EntityKey

		-- but always get the Layout Order
		update #roll
		set    #roll.WorkTypeDisplayOrder = lb.LayoutOrder
		from   tLayoutBilling lb (nolock)
		where  lb.LayoutKey = @LayoutKey
		and    #roll.Entity = lb.Entity COLLATE DATABASE_DEFAULT
		and    #roll.EntityKey = lb.EntityKey     				

	end

	-- redo this because we modified WTKey
	update #roll
	set    WorkTypeID = ''[No Billing Item ID]''
		   ,WorkTypeName = ''[No Billing Item]''
		   ,WorkTypeKey = isnull(WorkTypeKey, 0)
	where  isnull(WorkTypeKey, 0) = 0

	-- Set the DepartmentName for tItem
	Update #roll 
	   set #roll.DepartmentName = d.DepartmentName
	from  tItem i (nolock)
	LEFT JOIN tDepartment d (nolock) ON i.DepartmentKey = d.DepartmentKey
	Where #roll.Entity = ''tItem''
	and   #roll.EntityKey = i.ItemKey

	-- Set the DepartmentName for tService
	Update #roll 
	   set #roll.DepartmentName = d.DepartmentName
	from  tService s (nolock)
	LEFT JOIN tDepartment d (nolock) ON s.DepartmentKey = d.DepartmentKey
	Where #roll.Entity = ''tService''
	and   #roll.EntityKey = s.ServiceKey


	select @Entity as GroupEntity -- how we grouped the projects
	       ,@EntityKey as GroupEntityKey
	       ,* 
	from #roll 
	order by WorkTypeDisplayOrder, WorkTypeID, ItemName

			     	
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[tMCPAuthCode]'
GO
IF OBJECT_ID(N'[dbo].[tMCPAuthCode]', 'U') IS NULL
CREATE TABLE [dbo].[tMCPAuthCode]
(
[MCPAuthCodeKey] [int] NOT NULL IDENTITY(1, 1),
[CompanyKey] [int] NOT NULL,
[Code] [nvarchar] (128) NOT NULL,
[ClientID] [nvarchar] (128) NOT NULL,
[RedirectURI] [nvarchar] (1024) NOT NULL,
[CodeChallenge] [nvarchar] (256) NOT NULL,
[CodeChallengeMethod] [nvarchar] (10) NOT NULL CONSTRAINT [DF__tMCPAuthC__CodeC__1F893389] DEFAULT ('S256'),
[APIAccessToken] [nvarchar] (256) NOT NULL,
[UserToken] [nvarchar] (256) NOT NULL,
[UserKey] [bigint] NOT NULL,
[Expires] [datetime] NOT NULL,
[CreatedDate] [datetime] NOT NULL CONSTRAINT [DF__tMCPAuthC__Creat__207D57C2] DEFAULT (getutcdate())
)
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating primary key [PK_tMCPAuthCode] on [dbo].[tMCPAuthCode]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[PK_tMCPAuthCode]', 'PK') AND parent_object_id = OBJECT_ID(N'[dbo].[tMCPAuthCode]', 'U'))
ALTER TABLE [dbo].[tMCPAuthCode] ADD CONSTRAINT [PK_tMCPAuthCode] PRIMARY KEY CLUSTERED ([MCPAuthCodeKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tMCPAuthCode_Code] on [dbo].[tMCPAuthCode]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tMCPAuthCode_Code' AND object_id = OBJECT_ID(N'[dbo].[tMCPAuthCode]'))
CREATE UNIQUE NONCLUSTERED INDEX [IX_tMCPAuthCode_Code] ON [dbo].[tMCPAuthCode] ([Code])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMCPAuthCodeConsume]'
GO
IF OBJECT_ID(N'[dbo].[sptMCPAuthCodeConsume]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptMCPAuthCodeConsume]
    @Code       nvarchar(128),
    @ClientID   nvarchar(128)
AS
BEGIN
    SET NOCOUNT ON

    DECLARE @t TABLE (
        CompanyKey          int,
        RedirectURI         nvarchar(1024),
        CodeChallenge       nvarchar(256),
        CodeChallengeMethod nvarchar(10),
        APIAccessToken      nvarchar(256),
        UserToken           nvarchar(256),
        UserKey             bigint
    )

    -- DELETE ... OUTPUT is atomic: no second caller can retrieve the same code
    DELETE FROM tMCPAuthCode WITH (ROWLOCK)
    OUTPUT
        DELETED.CompanyKey,
        DELETED.RedirectURI,
        DELETED.CodeChallenge,
        DELETED.CodeChallengeMethod,
        DELETED.APIAccessToken,
        DELETED.UserToken,
        DELETED.UserKey
    INTO @t
    WHERE Code     = @Code
      AND ClientID = @ClientID
      AND Expires  > GETUTCDATE()

    SELECT * FROM @t
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMCPAuthCodeSave]'
GO
IF OBJECT_ID(N'[dbo].[sptMCPAuthCodeSave]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptMCPAuthCodeSave]
    @CompanyKey             int,
    @Code                   nvarchar(128),
    @ClientID               nvarchar(128),
    @RedirectURI            nvarchar(1024),
    @CodeChallenge          nvarchar(256),
    @CodeChallengeMethod    nvarchar(10),
    @APIAccessToken         nvarchar(256),
    @UserToken              nvarchar(256),
    @UserKey                bigint,
    @ExpiryMinutes          int = 5
AS
BEGIN
    SET NOCOUNT ON

    -- Clean up any stale codes first
    DELETE FROM tMCPAuthCode WHERE Expires < GETUTCDATE()

    INSERT INTO tMCPAuthCode
        (CompanyKey, Code, ClientID, RedirectURI, CodeChallenge, CodeChallengeMethod,
         APIAccessToken, UserToken, UserKey, Expires)
    VALUES
        (@CompanyKey, @Code, @ClientID, @RedirectURI, @CodeChallenge, @CodeChallengeMethod,
         @APIAccessToken, @UserToken, @UserKey, DATEADD(MINUTE, @ExpiryMinutes, GETUTCDATE()))
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptMCPClientGet]'
GO
IF OBJECT_ID(N'[dbo].[sptMCPClientGet]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptMCPClientGet]
    @ClientID   nvarchar(128)
AS
BEGIN
    SET NOCOUNT ON

    SELECT ClientID, ClientName, RedirectURIs
    FROM   tMCPClient WITH (nolock)
    WHERE  ClientID = @ClientID
END
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAISearchContacts]'
GO
IF OBJECT_ID(N'[dbo].[spApiAISearchContacts]', 'P') IS NULL
EXEC sp_executesql N'Create   PROCEDURE [dbo].[spApiAISearchContacts]
	(
		@CompanyKey int,
		@UserKey int,
		@SearchTerm nvarchar(500)
	)
AS
BEGIN
	SET NOCOUNT ON;

	Declare @RestrictToGLCompany int

	Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0) from tPreference (nolock) Where CompanyKey = @CompanyKey

	SELECT 
		v.UserKey as contactKey,
		v.UserFullName as fullName,
		v.Email as email,
		v.UserName as contactName,
		v.Phone1 as phone,
		v.Cell as mobile,
		v.Title as title,
		v.CompanyName as companyName,
		v.Address1 as address1,
		v.Address2 as address2,
		v.City as city,
		v.State as state,
		v.PostalCode as postalCode,
		v.Country as country
	FROM vUserName v (nolock)
	WHERE v.OwnerCompanyKey = @CompanyKey and v.Active = 1
		AND (
			v.UserFullName LIKE ''%'' + @SearchTerm + ''%''
			OR v.Email LIKE ''%'' + @SearchTerm + ''%''
			OR v.UserName LIKE ''%'' + @SearchTerm + ''%''
			OR v.CompanyName LIKE ''%'' + @SearchTerm + ''%''
		)
		AND (@RestrictToGLCompany = 0 OR v.GLCompanyKey IN (SELECT GLCompanyKey FROM tUserGLCompanyAccess (nolock) WHERE UserKey = @UserKey))
	ORDER BY v.UserFullName

END'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spRptGLTrialBalance]'
GO
IF OBJECT_ID(N'[dbo].[spRptGLTrialBalance]', 'P') IS NOT NULL
EXEC sp_executesql N'--exec spRptGLTrialBalance 1986, ''3/3/2013''

ALTER PROCEDURE [dbo].[spRptGLTrialBalance]
(
	@CompanyKey int,
	@AsOfDate smalldatetime,
	@CashBasis int = 0,
	@UserKey int = null,
	@RunInGLCHomeCurrency int = 0 -- 0 run in main home curr, 1 run in the home currency of the GL company
)

AS --Encrypt

/*
|| When      Who Rel     What
|| 10/18/07  CRG 8.5     Added GLCompanyKey parameter.
||					     Also now look for Office and Department directly on the Transaction, rather than going through the Class. 
|| 06/03/11  GHL 10.545  Added CashBasis parameter to run the report against GL or cash basis GL
|| 04/12/12  GHL 10.555  Added UserKey for UserGLCompanyAccess
|| 10/09/12  MFT 10.561  Added #GLCompanyKeys filter structure and included DisplayOrder (for ORDER BY)
|| 10/30/12  MFT 10.562  Changed Debit/Credit columns to show the Net amount or NULL (the same as the PDF report)
||               Removed @GLCompanyKey and @ClassKey from input parameters, added support for #ClassKeys filter
|| 12/5/12   GWG 10.562  Added different way to get default classes (from trans to prevent no data from invalid classes) and protection against 0 class 
|| 12/7/12   GWG 10.563  Made it <> instead of > for Key > 0
|| 03/01/13  GWG 10.5.6.5Added the display order of the RE account to properly slot it in place
|| 01/06/14  GHL 10.576  Using now vHTransaction (Debit mapped to HDebit)
|| 10/05/21  MCM 21.11x (573199) Added logic for GL Account Access and moved logic for Debit and Credit to subquery
|| 11/10/21  MCM 21.11x (577363) Fix logic where messed credit - debit instead of othere way for credit for AccountType in (31, 40, 41, 50, 51, 52) 
|| 11/05/24  MCM 24.12x (673149) Added param @RunInGLCHomeCurrency to support GL comp with different currency
|| 02/27/26  AMP 26.03.15 (713493) Added ''Active'' flag to filter out the inactive/zero accounts
|| 05/05/26  AMP 26.05.17 (728130) Corrected the issue when running for GL Company that does not use multi currency
*/

-- Calculate the beginning of fiscal year
Declare @BeginningDate smalldatetime
Declare @FirstMonth int
Declare @FirstYear int
Declare @MultiCurrency int

Select @FirstMonth = ISNULL(FirstMonth, 1) 
	,@MultiCurrency = ISNULL(MultiCurrency, 0)
from tPreference (nolock) Where CompanyKey = @CompanyKey

if @MultiCurrency =1
begin
	exec spRptGLTrialBalanceCurrency @CompanyKey, @AsOfDate, @CashBasis, @UserKey, @RunInGLCHomeCurrency
	return 1
end 

Select @FirstYear = Year(@AsOfDate)
if @FirstMonth > Month(@AsOfDate)
	Select @FirstYear = @FirstYear - 1
	
Select @BeginningDate = Cast(Cast(@FirstMonth as Varchar) + ''/1/'' + cast(@FirstYear as Varchar) as smalldatetime)

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)

--To allow sp to be called as a stand alone
IF OBJECT_ID(''tempdb..#GLCompanyKeys'') IS NULL
	BEGIN
		CREATE TABLE #GLCompanyKeys(GLCompanyKey int NOT NULL PRIMARY KEY)
	END
IF OBJECT_ID(''tempdb..#ClassKeys'') IS NULL
	BEGIN
		CREATE TABLE #ClassKeys(ClassKey int NOT NULL PRIMARY KEY)
	END

--If filtered in the UI, selected keys
--will be there, otherwise insert all
DECLARE @GLCount int
SELECT @GLCount = COUNT(*) FROM #GLCompanyKeys

IF @GLCount = 0
	BEGIN
		IF @RestrictToGLCompany = 0
			BEGIN
				INSERT INTO #GLCompanyKeys VALUES(0)
				INSERT INTO #GLCompanyKeys
				SELECT Distinct GLCompanyKey
				FROM tTransaction (nolock) 
				WHERE CompanyKey = @CompanyKey and GLCompanyKey is not null and GLCompanyKey <> 0
			END
		ELSE
			INSERT INTO #GLCompanyKeys
			SELECT GLCompanyKey
			FROM tUserGLCompanyAccess (nolock)
			WHERE UserKey = @UserKey
	END
DECLARE @ClassCount int
SELECT @ClassCount = COUNT(*) FROM #ClassKeys
IF @ClassCount = 0
	BEGIN
		INSERT INTO #ClassKeys VALUES(0)
		INSERT INTO #ClassKeys
		SELECT Distinct ClassKey
		FROM tTransaction (nolock)
		WHERE CompanyKey = @CompanyKey and ClassKey is not null and ClassKey <> 0
	END

Declare @GLAccountKey int
Declare @AccountNumber varchar(50)
Declare @AccountName varchar(100)
Declare @REAmountCR money
Declare @REAmountDB money
Declare @REAmountCR2 money
Declare @REAmountDB2 money
Declare @REDisplayOrder int

Create table #GLTran
(
	CompanyKey int,
	GLAccountKey int,
	GLCompanyKey int,
	TransactionDate smalldatetime,
	Debit money,
	Credit money
)


IF @CashBasis = 0
	INSERT	#GLTran (CompanyKey, GLAccountKey, GLCompanyKey, TransactionDate, Debit, Credit)
	SELECT	CompanyKey, GLAccountKey, t.GLCompanyKey, TransactionDate, Debit, Credit
	FROM	vHTransaction t (nolock)
				INNER JOIN #GLCompanyKeys glc ON ISNULL(t.GLCompanyKey, 0) = glc.GLCompanyKey
				INNER JOIN #ClassKeys c ON ISNULL(t.ClassKey, 0) = c.ClassKey
	WHERE	CompanyKey = @CompanyKey
ELSE
	INSERT	#GLTran (CompanyKey, GLAccountKey, GLCompanyKey, TransactionDate, Debit, Credit)
	SELECT	CompanyKey, GLAccountKey, t.GLCompanyKey, TransactionDate, Debit, Credit
	FROM	vHCashTransaction t (nolock)
				INNER JOIN #GLCompanyKeys glc ON ISNULL(t.GLCompanyKey, 0) = glc.GLCompanyKey
				INNER JOIN #ClassKeys c ON ISNULL(t.ClassKey, 0) = c.ClassKey
	WHERE	CompanyKey = @CompanyKey


-- Get the retained Earnings Account
Declare @REAccountKey int

if @CashBasis = 0
	Select @REAccountKey = GLAccountKey from tGLAccount (nolock) Where CompanyKey = @CompanyKey and AccountType = 32
else
	Select @REAccountKey = GLAccountKey from tGLAccount (nolock) Where CompanyKey = @CompanyKey and isnull(AccountTypeCash,AccountType) = 32

-- if there is no retained earnings account, create a virtual account
if @REAccountKey is null
	Select @GLAccountKey = -1, @AccountNumber = ''000'', @AccountName = ''Retained Earnings'', @REDisplayOrder = 999999
else
	Select @GLAccountKey = GLAccountKey, @AccountNumber = AccountNumber, @AccountName = AccountName, @REDisplayOrder = DisplayOrder from tGLAccount (nolock) Where GLAccountKey = @REAccountKey

-- Calculate the Retained Earnings Amount
-- Move prior net income over to retained earnings
if @CashBasis = 0
	Select @REAmountCR = ISNULL(SUM(Credit), 0), @REAmountDB = ISNULL(SUM(Debit), 0) 
		from #GLTran t (nolock) inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
		Where t.CompanyKey = @CompanyKey and AccountType in (31, 40, 41, 50, 51, 52) and TransactionDate < @BeginningDate
else
	Select @REAmountCR = ISNULL(SUM(Credit), 0), @REAmountDB = ISNULL(SUM(Debit), 0) 
		from #GLTran t (nolock) inner join tGLAccount gl (nolock) on t.GLAccountKey = gl.GLAccountKey
		Where t.CompanyKey = @CompanyKey and isnull(AccountTypeCash,AccountType) in (31, 40, 41, 50, 51, 52) and TransactionDate < @BeginningDate
	
	-- Get any transactions posted directly to retained earnings
	If @REAccountKey is null
		Select @REAmountCR2 = 0, @REAmountDB2 = 0
	else	
		Select @REAmountCR2 = ISNULL(SUM(Credit), 0), @REAmountDB2 = ISNULL(SUM(Debit), 0)  
		from #GLTran t (nolock)
		Where t.GLAccountKey = @REAccountKey and TransactionDate <= @AsOfDate
		
	Select @REAmountDB = @REAmountDB + @REAmountDB2, @REAmountCR = @REAmountCR + @REAmountCR2

-- This summarizes all the do not close accounts.
if @CashBasis = 0
	-- Regular/Accrual GL

	Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,gl.AccountType
		,CASE WHEN (
			Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
			from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate )
			> 0 THEN
			(Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0) 
			 from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate 
			 )
			ELSE NULL END AS Debit
		,CASE WHEN (
			Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
			from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate ) > 0 THEN
			NULL ELSE 
			(Select ISNULL(SUM(t.Credit), 0) - ISNULL(SUM(t.Debit), 0) 
			 from #GLTran t (nolock)
			 WHERE gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate 
			) 
			END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock) 
		left outer join tGLCompanyAccess glcaC (nolock) on glcaC.EntityKey = gl.GLAccountKey and glcaC.Entity = ''tGLAccount''
		left outer join tUserGLCompanyAccess glcaU (nolock) on glcaU.GLCompanyKey = glcaC.GLCompanyKey
	Where
		gl.CompanyKey = @CompanyKey and
		gl.AccountType <= 30 and
		gl.Rollup = 0 and
		(ISNULL(gl.RestrictToGLCompany,0) = 0 OR glcaU.UserKey = @UserKey)
	Group By gl.GLAccountKey ,gl.AccountNumber ,gl.AccountName,gl.AccountType,DisplayOrder,Active
		
Union ALL

Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,gl.AccountType
		,CASE WHEN (
			Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
			from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate 
			 and TransactionDate >= @BeginningDate ) > 0 THEN
				(Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0) 
				 from #GLTran t (nolock) 
				 Where gl.GLAccountKey = t.GLAccountKey
				 and t.TransactionDate  <= @AsOfDate 
				 and TransactionDate >= @BeginningDate 
				 ) ELSE NULL 
			END AS Debit
		,CASE WHEN 
			(Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
				from #GLTran t (nolock) 
				 Where gl.GLAccountKey = t.GLAccountKey
				 and t.TransactionDate  <= @AsOfDate 
				 and t.TransactionDate >= @BeginningDate ) > 0 
				THEN NULL 
				ELSE 
					(Select ISNULL(SUM(t.Credit), 0) - ISNULL(SUM(t.Debit), 0)
					from #GLTran t (nolock) 
					 Where gl.GLAccountKey = t.GLAccountKey
					 and t.TransactionDate  <= @AsOfDate 
					 and t.TransactionDate >= @BeginningDate )
			END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join tGLCompanyAccess glcaC (nolock) on glcaC.EntityKey = gl.GLAccountKey and glcaC.Entity = ''tGLAccount''
		left outer join tUserGLCompanyAccess glcaU (nolock) on glcaU.GLCompanyKey = glcaC.GLCompanyKey		
	Where
		gl.CompanyKey = @CompanyKey and
		gl.AccountType in (31, 40, 41, 50, 51, 52) and
		gl.Rollup = 0 and 
		(ISNULL(gl.RestrictToGLCompany,0) = 0 OR glcaU.UserKey = @UserKey)
	Group By gl.GLAccountKey ,gl.AccountNumber ,gl.AccountName,gl.AccountType,DisplayOrder,Active
		
-- Include the retained earnings account
Union ALL
	Select
		 @GLAccountKey
		,@AccountNumber
		,@AccountName
		,32
		,CASE WHEN ISNULL(SUM(@REAmountDB), 0) - ISNULL(SUM(@REAmountCR), 0) > 0 THEN
			ISNULL(SUM(@REAmountDB), 0) - ISNULL(SUM(@REAmountCR), 0) ELSE NULL END AS Debit
		,CASE WHEN ISNULL(SUM(@REAmountDB), 0) - ISNULL(SUM(@REAmountCR), 0) > 0 THEN
			NULL ELSE ISNULL(SUM(@REAmountCR), 0) - ISNULL(SUM(@REAmountDB), 0) END AS Credit
		,@REDisplayOrder
		,1
	ORDER BY DisplayOrder
		
ELSE
	-- Cash Basis GL

	Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,ISNULL(gl.AccountTypeCash, gl.AccountType) AS AccountType
		,CASE WHEN (
			Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
			from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate )
			> 0 THEN
			(Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0) 
			 from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate 
			 )
			ELSE NULL 
			END AS Debit
		,CASE WHEN (
			Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
			from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate ) > 0 THEN
			NULL ELSE 
			(Select ISNULL(SUM(t.Credit), 0) - ISNULL(SUM(t.Debit), 0) 
			 from #GLTran t (nolock)
			 WHERE gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate 
			) 
			END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join tGLCompanyAccess glcaC (nolock) on glcaC.EntityKey = gl.GLAccountKey and glcaC.Entity = ''tGLAccount''
		left outer join tUserGLCompanyAccess glcaU (nolock) on glcaU.GLCompanyKey = glcaC.GLCompanyKey
	Where
		gl.CompanyKey = @CompanyKey and
		isnull(gl.AccountTypeCash, gl.AccountType) <= 30 and
		gl.Rollup = 0 and 
		(ISNULL(gl.RestrictToGLCompany,0) = 0 OR glcaU.UserKey = @UserKey)
	Group By gl.GLAccountKey ,gl.AccountNumber ,gl.AccountName,isnull(gl.AccountTypeCash, gl.AccountType),DisplayOrder,Active
		
Union ALL

Select 
		 gl.GLAccountKey
		,gl.AccountNumber
		,gl.AccountName
		,isnull(gl.AccountTypeCash, gl.AccountType) As AccountType
,CASE WHEN (
			Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
			from #GLTran t (nolock) 
			 Where gl.GLAccountKey = t.GLAccountKey
			 and t.TransactionDate  <= @AsOfDate 
			 and TransactionDate >= @BeginningDate ) > 0 THEN
				(Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0) 
				 from #GLTran t (nolock) 
				 Where gl.GLAccountKey = t.GLAccountKey
				 and t.TransactionDate  <= @AsOfDate 
				 and TransactionDate >= @BeginningDate 
				 ) ELSE NULL 
			END AS Debit
		,CASE WHEN 
			(Select ISNULL(SUM(t.Debit), 0) - ISNULL(SUM(t.Credit), 0)
				from #GLTran t (nolock) 
				 Where gl.GLAccountKey = t.GLAccountKey
				 and t.TransactionDate  <= @AsOfDate 
				 and t.TransactionDate >= @BeginningDate ) > 0 
				THEN NULL 
				ELSE 
					(Select ISNULL(SUM(t.Credit), 0) - ISNULL(SUM(t.Debit), 0)
					from #GLTran t (nolock) 
					 Where gl.GLAccountKey = t.GLAccountKey
					 and t.TransactionDate  <= @AsOfDate 
					 and t.TransactionDate >= @BeginningDate )
			END AS Credit
		,DisplayOrder
		,Active
	From
		tGLAccount gl (nolock)
		left outer join tGLCompanyAccess glcaC (nolock) on glcaC.EntityKey = gl.GLAccountKey and glcaC.Entity = ''tGLAccount''
		left outer join tUserGLCompanyAccess glcaU (nolock) on glcaU.GLCompanyKey = glcaC.GLCompanyKey
	Where
		gl.CompanyKey = @CompanyKey and
		isnull(gl.AccountTypeCash, gl.AccountType) in (31, 40, 41, 50, 51, 52) and
		gl.Rollup = 0 and 
		(ISNULL(gl.RestrictToGLCompany,0) = 0 OR glcaU.UserKey = @UserKey)
	Group By gl.GLAccountKey ,gl.AccountNumber ,gl.AccountName,isnull(gl.AccountTypeCash, gl.AccountType),DisplayOrder,Active
		
-- Include the retained earnings account
Union ALL
	Select
		 @GLAccountKey
		,@AccountNumber
		,@AccountName
		,32
		,CASE WHEN ISNULL(SUM(@REAmountDB), 0) - ISNULL(SUM(@REAmountCR), 0) > 0 THEN
			ISNULL(SUM(@REAmountDB), 0) - ISNULL(SUM(@REAmountCR), 0) ELSE NULL END AS Debit
		,CASE WHEN ISNULL(SUM(@REAmountDB), 0) - ISNULL(SUM(@REAmountCR), 0) > 0 THEN
			NULL ELSE ISNULL(SUM(@REAmountCR), 0) - ISNULL(SUM(@REAmountDB), 0) END AS Credit
		,@REDisplayOrder
		,1
	ORDER BY DisplayOrder
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAITimerInsert]'
GO
IF OBJECT_ID(N'[dbo].[spApiAITimerInsert]', 'P') IS NULL
EXEC sp_executesql N'
CREATE   PROCEDURE [dbo].[spApiAITimerInsert]
(
    @CompanyKey INT, 
    @UserKey INT,
    @ProjectNumber VARCHAR(50) = NULL,
    @TaskID NVARCHAR(100) = NULL,
    @ServiceName NVARCHAR(200) = NULL
    
)
AS
BEGIN
    SET NOCOUNT ON;
    
    DECLARE @ProjectKey INT = NULL;
    DECLARE @TaskKey INT = NULL;
    DECLARE @ServiceKey INT = NULL;
    DECLARE @StartTimeUTC DATETIME;
    
    -- Set UTC start time
    SET @StartTimeUTC = GETUTCDATE();
    
    -- Lookup ProjectKey from ProjectNumber if provided
    IF @ProjectNumber IS NOT NULL
    BEGIN
        SELECT @ProjectKey = ProjectKey
        FROM dbo.tProject (nolock)
        WHERE ProjectNumber = @ProjectNumber;
        
        IF @ProjectKey IS NULL
        BEGIN
            RAISERROR(''Project not found for ProjectNumber: %s'', 16, 1, @ProjectNumber);
            RETURN;
        END
    END
    
    -- Lookup TaskKey from TaskID if provided (and ProjectKey is known)
    IF @TaskID IS NOT NULL AND @ProjectKey IS NOT NULL
    BEGIN
        SELECT @TaskKey = TaskKey
        FROM dbo.tTask (nolock)
        WHERE TaskID = @TaskID 
            AND ProjectKey = @ProjectKey;
        
        IF @TaskKey IS NULL
        BEGIN
            RAISERROR(''Task not found for TaskID: %s'', 16, 1, @TaskID);
            RETURN;
        END
    END
    
    -- Lookup ServiceKey from ServiceCode/Description if provided
    IF @ServiceName IS NOT NULL
    BEGIN
        SELECT @ServiceKey = ServiceKey
        FROM dbo.tService (nolock)
        WHERE (ServiceCode = @ServiceName OR Description = @ServiceName)
            AND Active = 1;
        
        IF @ServiceKey IS NULL
        BEGIN
            RAISERROR(''Service not found for ServiceName: %s'', 16, 1, @ServiceName);
            RETURN;
        END
    END
   
    
    -- Insert the timer record
    INSERT INTO tTimer (
        CompanyKey,
        UserKey,
        ProjectKey,
        TaskKey,
        ServiceKey,
        StartTime,
        PauseSeconds,
        Paused,
        RateLevel
    )
    VALUES (
        @CompanyKey,
        @UserKey,
        @ProjectKey,
        @TaskKey,
        @ServiceKey,
        @StartTimeUTC,
        0,
        0, -- Not paused
        1  -- Default rate level
    );
    
    -- Return the new TimerKey
    SELECT SCOPE_IDENTITY() AS TimerKey;
    
END

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[spApiAIGetActionLog]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetActionLog]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[spApiAIGetActionLog]
    (
        @CompanyKey		int,
        @UserKey		int,
        @ProjectNumber	varchar(100) = null,
        @Username		varchar(500) = null,
        @StartDate		datetime = null,
        @EndDate		datetime = null,
        @UTCOffsetHours	int      = 0
    )
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
*/

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

    -- Default date range: one year back to one year into the future
    if @StartDate is null
        set @StartDate = DATEADD(YEAR, -1, GETUTCDATE())

    if @EndDate is null
        set @EndDate = DATEADD(YEAR, 1, GETUTCDATE())

    -- Adjust caller-supplied local dates to UTC for ActionDate comparisons
    -- (same pattern as sptActionLogGetList: subtract the UTC offset)
    set @UTCStartDate = DATEADD(HOUR, (-1 * @UTCOffsetHours), @StartDate)
    set @UTCEndDate   = DATEADD(HOUR, (-1 * @UTCOffsetHours), @EndDate)

    -- Get requesting user''s security profile
    select	@SecurityGroupKey = SecurityGroupKey,
            @IsAdministrator  = Administrator
    from	tUser (nolock)
    where	UserKey    = @UserKey
    and		CompanyKey = @CompanyKey

    -- -----------------------------------------------------------------------
    -- Project path: look up project, run GL company + assignment security
    -- -----------------------------------------------------------------------
    if @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'')
        end
        else if @IsAdministrator = 0 or @IsAdministrator is null
        begin
            -- GL Company check
            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 = @ProjectGLCompanyKey
                )
                begin
                    insert into #errors (errorType, errorCode, errorMessage, fieldName)
                    values (''error'', ''ACCESS_DENIED'', ''User does not have access to this project''''s GL Company.'', ''projectNumber'')
                end
            end

            -- Project assignment check
            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
                )
                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.'', ''projectNumber'')
                end
            end
        end

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

        -- Return action log for the project
        select	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.ProjectKey = @ProjectKey
        and		al.ActionDate >= @UTCStartDate
        and		al.ActionDate <= @UTCEndDate
        order	by al.ActionDate desc

        drop table #errors
        return 0
    end

    -- -----------------------------------------------------------------------
    -- User path: resolve @Username to a UserKey, default to @UserKey
    -- -----------------------------------------------------------------------
    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
            -- Fall back to requesting user and warn
            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	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
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoActionInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoActionInsert]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptAutoActionInsert]
  @RuleKey int,
  @ActionType varchar(50),
  @DisplayOrder int,
  @Options varchar(max) = NULL
AS
INSERT INTO tAutoAction (RuleKey, ActionType, DisplayOrder, Options)
VALUES (@RuleKey, @ActionType, @DisplayOrder, @Options)

return SCOPE_IDENTITY()
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spScheduleFlashSaveWMJ]'
GO
IF OBJECT_ID(N'[dbo].[spScheduleFlashSaveWMJ]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spScheduleFlashSaveWMJ]
	(
	@ProjectKey int,
	@ProjectStatusKey int,
	@StartDate smalldatetime,
	@CompleteDate smalldatetime,
	@ScheduleDirection smallint,
	@DetailedNotes varchar(4000),
	@WorkMon tinyint,
	@WorkTue tinyint,
	@WorkWed tinyint,
	@WorkThur tinyint,
	@WorkFri tinyint,
	@WorkSat tinyint,
	@WorkSun tinyint,
	@Duration int,
	@PercComp int,
	@AutoIDTask tinyint,
	@SimpleSchedule tinyint,
	@UserKey int = NULL,
	@Platinum tinyint = 0,
	@ValidatePreds tinyint = 1,
	@tasksFromTemplate tinyint = 0	
	)

AS -- Encrypt

  /*
  || When     Who Rel   What
  || 10/19/06 GHL 8.4   Added tTaskUser Rollup logic 
  || 11/27/06 GHL 8.4   Added update of tProject.Active 
  || 12/20/06 GHL 8.4   Added verification logic for predecessors similar to tasks
  || 12/21/06 GHL 8.4   Added logic to prevent duplicates in tAssignment
  || 01/03/07 GHL 8.4   Added patch to cleanup SummaryTaskKey = TaskKey situation
  || 01/03/07 GHL 8.4   Added protection against null PercComp
  || 01/22/07 GHL 8.4   Added logic for completed time and user
  || 02/09/07 GHL 8.4   Adding now user in tAssignment if missing there but is in tTaskUser
  ||                    Bug 8250 at Media Logic
  || 04/13/07 GHL 8.4   Added update of tProject.TaskStatus     
  || 05/18/07 RTC 8.5   (8314) Added custom field handling       
  || 09/06/07 GHL 8.435 Added patch for incorrect MoneyTask flag         
  || 05/09/08 RTC 8.5.1 Added logic for Task User Assignments to handle insert and updates, instead of delete all and re-insert      
  || 08/02/08 GWG 10.006 Added UserKey to the update tTaskUser to handle reasigning tasks. 
  || 09/03/08 GHL 10.008 (30569, 33987) Added/Fixed patch to update the BudgetTaskKey when missing
  || 09/29/08 GHL 10.009 (35379) Added patch to fix problem with TaskType = Tracking with existing subtasks
  ||                     i.e. should be TaskType = Summary  
  || 10/07/08 GHL 10.010 (36176) Added patch for incorrect MoneyTask flag (when TrackBudget = 1 and MoneyTask = 0)
  || 6/8/09   CRG 10.5.0.0 Added ServiceKey, Subject, Description, Comments to be updated from the #tTaskUser table
  || 09/14/09 RLB 10.5.1.0 Added DetailedNotes, Saving Next step comments on the project Schedule Project Setup area
  || 01/04/10 GHL 10.516 Added check of tran transfer status (task deletion)
  || 01/08/10 GHL 10.516 Added check of tran WIP status (task deletion) 
  || 01/11/10 GHL 10.516 (71304) Removed check of time DetailTaskKey (task deletion)
  || 01/21/10 GHL 10.517 (72908) Reviewed the deletion of transferred trans at the bottom of sp
  ||                     to increase perfo
  || 3/2/10   CRG 10.5.1.9 Added @AutoIDTask and @SimpleSchedule
  || 3/11/10  CRG 10.5.1.9 Added code to make sure that any tasks where ShowOnCalendar = 1 have the date part of EventStart/End matching the PlanStart/Complete dates
  || 04/14/10 GHL 10.521 (78802) Checking now amounts and rates on approved estimates
  ||                      if 0, we can delete the tasks
  || 7/12/10  CRG 10.5.3.2 Added ShowOnTimeline and TaskColor
  || 7/14/10  GWG 10.5.3.2 Added the rollup of names and allocated hours
  || 7/27/10  CRG 10.5.3.3 Now copying over Activities if the new Task was dragged onto the Schedule screen.
  ||                       Added optional UserKey parameter for use by the Activity copy SP.
  || 10/19/10 CRG 10.5.3.7 Removed ShowOnTimeline and TaskColor. Added TimelineSegmentKey.
  || 12/30/10 GHL 10.5.3.9 (87237) When checking if the tasks are in tEstimateTask before deleting them
  ||                       check if the estimate is for the project, because this could be for an opportunity
  ||                       If this for an opportunity, it is OK to delete because the task structure 
  ||                       is temporary stored in tEstimateTaskTemp
  || 2/11/11  RLB 10.5.4.1 (101827) changed error code on Task Predecessors to help locate where an error is coming from
  || 3/8/11   CRG 10.5.4.2 Now calling spScheduleSaveReassignToDo to reassign To Do items
  || 3/23/11  RLB 10.5.4.2 (106451) only pull tasks with PercComp < 100 when setting project task status
  || 4/19/11  GHL 10.5.4.3 (109241) Added recalc of estimates data when deleting tasks on estimates
  || 8/03/11  GHL 10.5.4.6 (118043) Removed an error when trying to delete a predecessor relationship which is already deleted 
  || 11/4/11  GHL 10.5.4.9 (125561) Instead of deleting tEstimateTaskExpense recs, set TaskKey = null when deleting tasks
  || 12/15/11 GWG 10.5.5.1 Added handling of defaults for subscribing and deliverable review and notify
  || 03/12/12 GHL 10.5.5.3 (136576) Modified the queries setting BudgetTaskKey (i.e I set them even if BTK <> 0)
  ||                       cause we keep on getting corrupted tasks at CenterLine
  || 03/21/12 GWG 10.554  Modified the call to copy activities so it will also copy project level todo''s
  || 05/15/12 GHL 10.556  Modified the insertion of tTaskUser so that we can have duplicate (TaskKey,UserKey,ServiceKey)
  || 10/30/12 RLB 10.5.6.1 Kohls enhancement for Constraint Day of the Week 
  || 10/30/12 RLB 10.5.6.2 Kohls enhancement for Exclude From Status
  || 06/20/13 RLB 10.5.6.9 Added for Enhancement (172776) 
  || 10/28/13 WDF 10.5.7.3 Added Logging of Task deletes
  || 03/06/14 RLB 10.5.7.8 (196273) Adding AllowAllocatedHours for enhancement
  || 04/13/17 GHL 10.615 (340912) Added deletion of estimate labor titles
  || 04/24/17 RLB 10.6.1.5 Added InWeeks on Preds for Kolhs change
  || 04/02/18 CRG 18.4.0   Added @Platinum parm to update platinum specific columns
  || 04/03/18 CRG 18.4.0   Added delete of tTaskUserHour when tTaskUser records are deleted
  || 04/20/18 GWG 18.5    Added sp call to set assignment hourly rates.
  || 05/03/18 RLB 18.5.0.0 Added some protection on plan complete getting time on it and plan start
  || 06/14/18 GWG 18.6.0.0 Don''t update tProject if you are coming from plat
  || 06/21/18 CRG 18.7.0.0 Added requirement in validation of predecessors that the PredecessorKey be a valid Task before it returns an error related to it
  || 06/29/18 CRG 18.7.0.0 Added TCProjectStatusKey
  || 07/09/18 CRG 18.8.0.0 Added validation of predecessor keys before save
  || 08/31/18 CRG 18.9.0.0 Added PercAssigned to the insert of tTaskUser
  || 09/28/18 CRG 18.9.1.0 Added logic to mark tasks for deletion when they have invalid SummaryTaskKeys
  || 09/28/18 RLB 18.9.1.0 Add update to project Task Status
  || 10/01/18 CRG 18.9.1.0 Removed error return if task marked for deletion is not already in the DB. We''ll just let it try to delete, and then continue on since it doesn''t hurt anything.
  || 10/26/18 CRG 18.9.2.0 (427769) Removed error return if tasks are no longer in schedule on DB. We''ll just let it try to save and then continue on.
  || 12/17/18 CRG 19.0.1.0  Added optional @ValidatePreds parameter
  || 06/21/19 RLS 19.0.7.0 (465965) Added @TasksFromTemplate parameter and operations on #tProjectUserServices
  || 06/24/19 CRG 19.0.7.0 (467392) Preventing duplicate predecessors
  || 07/18/19 GAR 19.0.8.0 (454300) Only copy todos if the preference is not turned off
  || 09/25/19 RLS 19.1.0.0 (480937) Changed the where clause in DELETE tProjectUserServices to: AND #tAssignment.Action = 3 instead of  #tAssignment.Action in (1,3)
  || 09/07/21 CRG 21.09.18 (569967) Now only updating PercComp, ActStart, and ActComplete if they''ve changed since the screen was loaded
  || 09/23/21 CRG 21.09.18 (572146) Cleaned up the NULL checking for OrigActStart and OrigActComplete
  || 10/08/21 CRG 21.11.14 (573148) Added fix to ensure that any copied tasks with negative SummaryTaskKeys are removed from the DB
  || 10/28/21 AMP xx.xx.xx (DEV2506-502) Added a flag to hide the task on the deliverable board 
  || 06/22/22 CRG 22.07.17 (604204) Moved the Copy To Do logic outside of the transaction
  || 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
  || 09/23/22 GAR 22.10.16 (DEV2605) Added AvalaraTaxCodeKey
  || 03/21/22 CRG 23.04.16 (622919) Added NoTimeEntry for Deborah Wood customization
  || 03/24/23 CRG 23.04.16 (635797) Now deleting task sub-tables when cleaning up tasks at the end with negative SummaryTaskKeys
  || 04/25/23 RLB 23.05.14 (623383) Added new col ADescriptionLastModified update
  || 05/08/23 CRG 23.06.18 (604775) Changed Priority to TaskPriorityKey
  || 10/04/23 CRG 23.11.19 (647340) Added MustFinishOnPredComplete
  || 06/23/25 CRG 25.07.20 (703934) Added DISTINCT to query of tProjectUserServices to ensure it''s unique 
  || 07/02/25 CRG 25.08.17 (705248) Performance improvements for large schedules
  || 08/22/25 CRG 25.10.19 (709445) Added ability to only update ProjectOrder, DisplayOrder, and TaskID to improve efficiency
  || 09/10/25 CRG 25.10.19 (710574) Now returning whether or not this project is a cross project pred, so it can be added to the queue later
  || 12/17/25 CRG 26.02.15 (548907) Added recurring task fields
  || 12/22/25 CRG 26.02.15 Added call to sptTaskUserUpdateRecurringTasks
  || 02/26/26 RLS 26.04.19 (721929) Added TaskUserStatusKey to tTaskUser insert and update sections
  || 05/13/26 RLS 26.05.17 (728544) Added zero/NULL check for TaskUserStatusKey
  || 
  */

	SET NOCOUNT ON
	 
    /* 
    Assume that the following tables have been populated
    #tTask
    #tTaskPredecessor
    #tTaskUser
    #tAssignment
    Also
    
    CREATE TABLE #NewKeys(Entity VARCHAR(50) NULL, OldKey INT NULL, NewKey INT NULL)
    
    Validation of temp tables ex #tTask

	Action = 1 Insert, 2 Update, 3 Delete, 4 Cannot Delete, 99 Update ProjectOrder, DisplayOrder, TaskID only
	
    #tTask.TaskKey  | #tTask.Action | Currently in DB
    ------------------------------------------------
        x		           2                x
        y                  2                y
        w                  2       
        -1                 1
        -2                 1
        u                  3                u
        v                  3
                                            z
        
        -1 and -2 will be inserted
        x and y can be updated
        u can be deleted
        
        w cannot be updated = ABORT
        z was not sent from flash = ABORT
        v cannot be deleted = ABORT 
	
	*/
	
	-- Tasks
	-- will capture case z 
	
	/* Assume created in VB
	CREATE TABLE #CopyToDos
		(FromTaskKey int NULL, 
		NewTaskKey int NULL)
	*/

	--FOR DEBUGGING ONLY!!!!
	DECLARE	@saveTiming tinyint,
			@debugTimeStamp datetime,
			@timingMsg nvarchar(max)
	SELECT	@saveTiming = 0, --SET TO 0 FOR PRODUCTION!!!!
			@debugTimeStamp = GETDATE(),
			@timingMsg = ''''

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tTime (NOLOCK)  
	WHERE	#tTask.TaskKey = tTime.TaskKey
	AND     tTime.TransferToKey is null -- not transferred
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tTime (NOLOCK)  
	WHERE	#tTask.TaskKey = tTime.TaskKey
	AND     tTime.TransferToKey is not null -- transferred
	AND     tTime.WIPPostingInKey > 0      -- WIP
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tExpenseReceipt (NOLOCK)  
	WHERE	#tTask.TaskKey = tExpenseReceipt.TaskKey
	AND     tExpenseReceipt.TransferToKey is null -- not transferred
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tExpenseReceipt (NOLOCK)  
	WHERE	#tTask.TaskKey = tExpenseReceipt.TaskKey
	AND     tExpenseReceipt.TransferToKey is not null -- transferred
	AND     tExpenseReceipt.WIPPostingInKey > 0       -- in wip
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tPurchaseOrderDetail (NOLOCK)  
	WHERE	#tTask.TaskKey = tPurchaseOrderDetail.TaskKey
	AND     tPurchaseOrderDetail.TransferToKey is null -- not transferred
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tVoucherDetail (NOLOCK)  
	WHERE	#tTask.TaskKey = tVoucherDetail.TaskKey 
	AND     tVoucherDetail.TransferToKey is null	-- not transferred
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tVoucherDetail (NOLOCK)  
	WHERE	#tTask.TaskKey = tVoucherDetail.TaskKey 
	AND     tVoucherDetail.TransferToKey is not null -- transferred
	AND     tVoucherDetail.WIPPostingInKey > 0 -- in wip
	AND     #tTask.Action = 3
	
	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tMiscCost (NOLOCK)  
	WHERE	#tTask.TaskKey = tMiscCost.TaskKey
	AND     tMiscCost.TransferToKey is null -- not transferred
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tMiscCost (NOLOCK)  
	WHERE	#tTask.TaskKey = tMiscCost.TaskKey
	AND     tMiscCost.TransferToKey is not null -- transferred
	AND     tMiscCost.WIPPostingInKey > 0      -- in wip
	AND     #tTask.Action = 3

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tInvoiceLine (NOLOCK)  
	WHERE	#tTask.TaskKey = tInvoiceLine.TaskKey
	AND     #tTask.Action = 3

	-- Cannot delete if on an approved estimate
	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tEstimateTask et (NOLOCK)
		  ,tEstimate e (NOLOCK)  
	WHERE	#tTask.TaskKey = et.TaskKey
	AND     et.EstimateKey = e.EstimateKey
	AND    ISNULL(et.EstLabor, 0) + ISNULL(et.EstExpenses, 0) <> 0
	AND     ((isnull(e.ExternalApprover, 0) > 0 and  e.ExternalStatus = 4) 
			Or (isnull(e.ExternalApprover, 0) = 0 and  e.InternalStatus = 4))  
	AND     #tTask.Action = 3
	AND     e.ProjectKey = @ProjectKey -- could be a tLead estimate, OK to delete

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tEstimateTaskLabor etl (NOLOCK)
		   ,tEstimate e (NOLOCK)  
	WHERE	#tTask.TaskKey = etl.TaskKey
	AND     etl.EstimateKey = e.EstimateKey
	AND     etl.Rate <> 0
	AND     ((isnull(e.ExternalApprover, 0) > 0 and  e.ExternalStatus = 4) 
			Or (isnull(e.ExternalApprover, 0) = 0 and  e.InternalStatus = 4))  
	AND     #tTask.Action = 3
	AND     e.ProjectKey = @ProjectKey -- could be a tLead estimate, OK to delete

	UPDATE	#tTask
	SET		#tTask.Action = 4
	FROM	tEstimateTaskExpense ete (NOLOCK)
		   ,tEstimate e (NOLOCK)  
	WHERE	#tTask.TaskKey = ete.TaskKey
	AND     ete.EstimateKey = e.EstimateKey
	AND     ((isnull(e.ExternalApprover, 0) > 0 and e.ExternalStatus = 4) 
			Or (isnull(e.ExternalApprover, 0) = 0 and  e.InternalStatus = 4)) 
	AND     #tTask.Action = 3
	AND     e.ProjectKey = @ProjectKey -- could be a tLead estimate, OK to delete
				
	-- Abort if we cannot delete
	IF EXISTS (SELECT 1 FROM #tTask Where Action = 4)
		RETURN -3

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''A: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	--Remove Tasks that point to invalid SummaryTaskKeys
	--If we are saving using the new DM process then @ValidatePreds will not be 1. 
	--This will prevent us from validating parents here, as not all tasks are in the temp table anymore
	IF @ValidatePreds = 1
		UPDATE	#tTask
		SET		Action = 3
		WHERE	SummaryTaskKey > 0
		AND		SummaryTaskKey NOT IN (SELECT TaskKey FROM #tTask)
	                          
	DECLARE @TaskKey INT
	       ,@NewTaskKey INT
	       ,@Error INT
		   ,@Rowcount INT
	       ,@Active INT
		   ,@FromTaskKey int
	       ,@RecalcEstimate int
		   ,@RequireTasks int
		   ,@CopyToDos tinyint

	SELECT @Active = IsActive
	FROM tProjectStatus (NOLOCK) 
	WHERE ProjectStatusKey = @ProjectStatusKey

	select	@RequireTasks = pref.RequireTasks
		,@CopyToDos = ISNULL(CopyToDos, 1)
	from tPreference pref (nolock)
	inner join tProject p (nolock) on p.CompanyKey = pref.CompanyKey 
	where p.ProjectKey = @ProjectKey 

	--Make sure the TaskKey and PredecessorKey are still valid tasks (especially with cross-project preds) to 
	--avoid foreign key constraint errors

	--ValidKeys values:
	-- 1: Valid TaskKey
	-- 2: Valid TaskKey & PredecessorKey
	UPDATE	#tTaskPredecessor
	SET		ValidKeys = 1 --Valid TaskKey
	FROM	tTask t (nolock)
	WHERE	#tTaskPredecessor.TaskKey = t.TaskKey
	AND		#tTaskPredecessor.Action IN (1, 2) --Inserts and Updates only

	UPDATE	#tTaskPredecessor
	SET		ValidKeys = 2 --Valid PredecessorKey
	FROM	tTask t (nolock)
	WHERE	#tTaskPredecessor.TaskKey = t.TaskKey
	AND		#tTaskPredecessor.Action IN (1, 2) --Inserts and Updates only
	AND		#tTaskPredecessor.ValidKeys = 1 --Only check if the TaskKey was already validated

	DELETE	#tTaskPredecessor
	WHERE	ValidKeys <> 2 --If the TaskKey & PredecessorKey are not both valid, remove the predecessor from the temp table
	AND		Action IN (1, 2)

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''B: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	/*
	 * tTask Inserts
	 */

	BEGIN TRAN

	SELECT	*
	INTO	#InsertedTasks
	FROM	#NewKeys
	WHERE	1=2

	INSERT	tTask
			(
			ProjectKey,
			TaskID,
			TaskName,
			Description,
			TaskType,
			SummaryTaskKey,
			BudgetTaskKey,
			HourlyRate,
			Markup,
			IOCommission,
			BCCommission,
			ShowDescOnEst,
			ServiceKey,
			Taxable,
			Taxable2,
			WorkTypeKey,
			BaseStart,
			BaseComplete,
			PlanStart,
			PlanComplete,
			PlanDuration,
			ActStart,
			ActComplete,
			PercComp,
			TaskConstraint,
			Comments,
			ScheduleTask,
			TrackBudget,
			MoneyTask,
			HideFromClient,
			AllowAnyone,
			MasterTaskKey,
			ConstraintDate,
			WorkAnyDay,
			PercCompSeparate,
			ProjectOrder,
			DisplayOrder,
			TaskLevel,
			TaskAssignmentTypeKey,
			TaskPriorityKey,
			ShowOnCalendar,
			EventStart,
			EventEnd,
			TimeZoneIndex,
			DueBy,
			ReviewedByTraffic,
			ReviewedByDate,
			ReviewedByKey,
			PredecessorsComplete,
			TaskStatus,
			ScheduleNote,
			CompletedByDate,
			CompletedByKey,
			TimelineSegmentKey,
			ConstraintDayOfTheWeek,
			ExcludeFromStatus,
			TimelineSegmentDisplayName,
			AllowAllocatedHours,
			TCProjectStatusKey,
			HideFromDeliverable,
			MustFinishOnPredComplete,
			InsertTempKey,
			RecurringFreq,
			RecurringMax,
			RecurringParentKey,
			RecurringOrder,
			OrigRecurringStart,
			ModifiedOccurrence
			)
	OUTPUT ''tTask'', INSERTED.InsertTempKey, INSERTED.TaskKey
	INTO	#InsertedTasks
	SELECT	ProjectKey,
			TaskID,
			TaskName,
			Description,
			TaskType,
			SummaryTaskKey,
			BudgetTaskKey,
			HourlyRate,
			Markup,
			IOCommission,
			BCCommission,
			ShowDescOnEst,
			ServiceKey,
			Taxable,
			Taxable2,
			WorkTypeKey,
			BaseStart,
			BaseComplete,
			dbo.fFormatDateNoTime(PlanStart),
			dbo.fFormatDateNoTime(PlanComplete),
			PlanDuration,
			ActStart,
			ActComplete,
			ISNULL(PercComp, 0),
			TaskConstraint,
			Comments,
			ScheduleTask,
			TrackBudget,
			MoneyTask,
			HideFromClient,
			AllowAnyone,
			MasterTaskKey,
			ConstraintDate,
			WorkAnyDay,
			PercCompSeparate,
			ProjectOrder,
			DisplayOrder,
			TaskLevel,
			TaskAssignmentTypeKey,
			TaskPriorityKey,
			ShowOnCalendar,
			EventStart,
			EventEnd,
			TimeZoneIndex,
			DueBy,
			ReviewedByTraffic,
			ReviewedByDate,
			ReviewedByKey,
			PredecessorsComplete,
			TaskStatus,
			ScheduleNote,
			CompletedByDate,
			CompletedByKey,
			TimelineSegmentKey,
			ConstraintDayOfTheWeek,
			ExcludeFromStatus,
			TimelineSegmentDisplayName,
			AllowAllocatedHours,
			TCProjectStatusKey,
			HideFromDeliverable,
			MustFinishOnPredComplete,
			TaskKey,
			RecurringFreq,
			RecurringMax,
			RecurringParentKey,
			ISNULL(RecurringOrder, 1),
			OrigRecurringStart,
			ModifiedOccurrence
	FROM	#tTask
	WHERE	Action = 1 --Insert

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''C: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
		
	UPDATE	#tTask 
	SET		NewTaskKey = it.NewKey
	FROM	#InsertedTasks it
	WHERE	#tTask.TaskKey = it.OldKey

	IF @CopyToDos = 1
		INSERT	#CopyToDos 
				(FromTaskKey, NewTaskKey)
		SELECT	t.FromTaskKey, it.NewKey
		FROM	#tTask t
		INNER JOIN #InsertedTasks it ON t.TaskKey = it.OldKey
		WHERE	ISNULL(t.FromTaskKey, 0) > 0
		        		       
	/*
	 * tTask Updates
	 */
	
	UPDATE  tTask
	SET tTask.TaskID = #tTask.TaskID,
			tTask.TaskName = #tTask.TaskName,
			tTask.Description = #tTask.Description,
			tTask.TaskType = #tTask.TaskType,
			tTask.SummaryTaskKey = #tTask.SummaryTaskKey,
			tTask.BudgetTaskKey = #tTask.BudgetTaskKey,
			tTask.HourlyRate = #tTask.HourlyRate,
			tTask.Markup = #tTask.Markup,
			tTask.IOCommission = #tTask.IOCommission,
			tTask.BCCommission = #tTask.BCCommission,
			tTask.ShowDescOnEst = #tTask.ShowDescOnEst,
			tTask.ServiceKey = #tTask.ServiceKey,
			tTask.Taxable = #tTask.Taxable,
			tTask.Taxable2 = #tTask.Taxable2,
			tTask.WorkTypeKey = #tTask.WorkTypeKey,
			tTask.BaseStart = #tTask.BaseStart,
			tTask.BaseComplete = #tTask.BaseComplete,
			tTask.PlanStart = dbo.fFormatDateNoTime(#tTask.PlanStart),
			tTask.PlanComplete = dbo.fFormatDateNoTime(#tTask.PlanComplete), 
			tTask.PlanDuration = #tTask.PlanDuration,
			--tTask.ActStart = #tTask.ActStart,
			--tTask.ActComplete = #tTask.ActComplete,
			--tTask.PercComp = ISNULL(#tTask.PercComp, 0),
			tTask.TaskConstraint = #tTask.TaskConstraint,
			tTask.Comments = #tTask.Comments,
			tTask.ScheduleTask = #tTask.ScheduleTask,
			tTask.TrackBudget = #tTask.TrackBudget ,
			tTask.MoneyTask = #tTask.MoneyTask,
			tTask.HideFromClient = #tTask.HideFromClient,
			tTask.AllowAnyone = #tTask.AllowAnyone,
			tTask.MasterTaskKey = #tTask.MasterTaskKey,
			tTask.ConstraintDate = #tTask.ConstraintDate,
			tTask.WorkAnyDay = #tTask.WorkAnyDay,
			tTask.PercCompSeparate = #tTask.PercCompSeparate,
			tTask.ProjectOrder = #tTask.ProjectOrder,
			tTask.DisplayOrder = #tTask.DisplayOrder,
			tTask.TaskLevel = #tTask.TaskLevel,
			tTask.TaskAssignmentTypeKey = #tTask.TaskAssignmentTypeKey,
			tTask.TaskPriorityKey = #tTask.TaskPriorityKey,
			tTask.ShowOnCalendar = #tTask.ShowOnCalendar,
			tTask.EventStart = #tTask.EventStart,
			tTask.EventEnd = #tTask.EventEnd,
			tTask.TimeZoneIndex = #tTask.TimeZoneIndex,
			tTask.DueBy = #tTask.DueBy,
			tTask.ReviewedByTraffic = #tTask.ReviewedByTraffic,
			tTask.ReviewedByDate = #tTask.ReviewedByDate,
			tTask.ReviewedByKey = #tTask.ReviewedByKey,
			tTask.PredecessorsComplete = #tTask.PredecessorsComplete,
			tTask.TaskStatus = #tTask.TaskStatus,
			tTask.ScheduleNote = #tTask.ScheduleNote,
			tTask.CompletedByDate = #tTask.CompletedByDate,
			tTask.CompletedByKey = #tTask.CompletedByKey,
			tTask.TimelineSegmentKey = ISNULL(#tTask.TimelineSegmentKey, tTask.TimelineSegmentKey), --Temp table could be null from CMP90, then keep existing value
			tTask.ConstraintDayOfTheWeek = #tTask.ConstraintDayOfTheWeek,
			tTask.ExcludeFromStatus = #tTask.ExcludeFromStatus,
			tTask.TimelineSegmentDisplayName = #tTask.TimelineSegmentDisplayName,
			tTask.AllowAllocatedHours = #tTask.AllowAllocatedHours,
			tTask.TCProjectStatusKey = 
				CASE 
					WHEN #tTask.TCProjectStatusKey = -1 THEN tTask.TCProjectStatusKey --If the value in the temp table is -1, then keep the existing value
					ELSE #tTask.TCProjectStatusKey
				END,
		    tTask.HideFromDeliverable = #tTask.HideFromDeliverable,
			tTask.AvalaraTaxCodeKey = #tTask.AvalaraTaxCodeKey,
			tTask.NoTimeEntry = #tTask.NoTimeEntry,
			tTask.MustFinishOnPredComplete = #tTask.MustFinishOnPredComplete,
			tTask.RecurringFreq = #tTask.RecurringFreq,
			tTask.RecurringMax = #tTask.RecurringMax,
			tTask.RecurringParentKey = #tTask.RecurringParentKey,
			tTask.RecurringOrder = ISNULL(#tTask.RecurringOrder, 1),
			tTask.OrigRecurringStart = #tTask.OrigRecurringStart,
			tTask.ModifiedOccurrence = #tTask.ModifiedOccurrence
	FROM    #tTask
	WHERE   tTask.TaskKey = #tTask.TaskKey
	AND     tTask.ProjectKey = @ProjectKey
	AND     #tTask.Action = 2
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''D: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	UPDATE	tTask
	SET		tTask.ProjectOrder = #tTask.ProjectOrder,
			tTask.DisplayOrder = #tTask.DisplayOrder,
			tTask.TaskID = #tTask.TaskID
	FROM    #tTask
	WHERE   tTask.TaskKey = #tTask.TaskKey
	AND     tTask.ProjectKey = @ProjectKey
	AND     #tTask.Action = 99 --Only update ProjectOrder, DisplayOrder, TaskID

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''D2: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	UPDATE	tTask
	SET		tTask.PercComp = ISNULL(#tTask.PercComp, 0)
	FROM    #tTask
	WHERE   tTask.TaskKey = #tTask.TaskKey
	AND     tTask.ProjectKey = @ProjectKey
	AND     #tTask.Action = 2
	AND		((ISNULL(#tTask.PercComp, 0) <> ISNULL(#tTask.OrigPercComp, 0)) OR @Platinum <> 1)

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	UPDATE	tTask
	SET		tTask.ActStart = #tTask.ActStart
	FROM    #tTask
	WHERE   tTask.TaskKey = #tTask.TaskKey
	AND     tTask.ProjectKey = @ProjectKey
	AND     #tTask.Action = 2
	AND		((#tTask.ActStart IS NULL AND #tTask.OrigActStart IS NOT NULL)
			OR (#tTask.ActStart IS NOT NULL AND #tTask.OrigActStart IS NULL)
			OR (#tTask.ActStart <> #tTask.OrigActStart)
			OR (@Platinum <> 1))

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	UPDATE	tTask
	SET		tTask.ActComplete = #tTask.ActComplete
	FROM    #tTask
	WHERE   tTask.TaskKey = #tTask.TaskKey
	AND     tTask.ProjectKey = @ProjectKey
	AND     #tTask.Action = 2
	AND		((#tTask.ActComplete IS NULL AND #tTask.OrigActComplete IS NOT NULL)
			OR (#tTask.ActComplete IS NOT NULL AND #tTask.OrigActComplete IS NULL)
			OR (#tTask.ActComplete <> #tTask.OrigActComplete)
			OR (@Platinum <> 1))

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

					
	-- Now update the summary and budget tasks			
	UPDATE tTask
	SET    tTask.SummaryTaskKey = #tTask.NewTaskKey
	FROM   #tTask
	WHERE  tTask.SummaryTaskKey = #tTask.TaskKey
	AND    tTask.ProjectKey = @ProjectKey
	AND    tTask.SummaryTaskKey < 0
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	UPDATE tTask
	SET    tTask.BudgetTaskKey = #tTask.NewTaskKey
	FROM   #tTask
	WHERE  tTask.BudgetTaskKey = #tTask.TaskKey
	AND    tTask.ProjectKey = @ProjectKey
	AND    tTask.BudgetTaskKey < 0
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''E: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
	
	-- Also save new keys in #tTaskPredecessor 
	UPDATE #tTaskPredecessor
	SET    #tTaskPredecessor.TaskKey = #tTask.NewTaskKey
	FROM   #tTask
	WHERE  #tTaskPredecessor.TaskKey = #tTask.TaskKey
	AND #tTaskPredecessor.TaskKey < 0
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	UPDATE #tTaskPredecessor
	SET    #tTaskPredecessor.PredecessorKey = #tTask.NewTaskKey
	FROM   #tTask
	WHERE  #tTaskPredecessor.PredecessorKey = #tTask.TaskKey
	AND    #tTaskPredecessor.PredecessorKey < 0
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	-- Save new keys in #tTaskUser 
	UPDATE #tTaskUser
	SET    #tTaskUser.TaskKey = #tTask.NewTaskKey
	FROM   #tTask
	WHERE  #tTaskUser.TaskKey = #tTask.TaskKey
	AND    #tTaskUser.TaskKey < 0
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	/*
	 * tTask Deletes
	 */

	--Add Recurring children to be deleted
	INSERT	#tTask (TaskKey, Action)
	SELECT	t.TaskKey, 3
	FROM	tTask t (nolock)
	INNER JOIN #tTask tmp ON t.RecurringParentKey = tmp.TaskKey AND t.TaskKey <> tmp.TaskKey
	WHERE	tmp.Action = 3
	
	DELETE	tTaskUserHour
	FROM	tTaskUserHour tuh
	INNER JOIN tTaskUser tu ON tuh.TaskUserKey = tu.TaskUserKey
	INNER JOIN #tTask t ON tu.TaskKey = t.TaskKey
	WHERE	t.Action = 3

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
		 
	-- Same order than in sptTaskDelete for deadlocks
	-- However we updated tTask first!!!! The order is different
	delete tTaskUser
	from   #tTask 
	where  tTaskUser.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	-- We should update the tasks on tTaskPredecessor before deleting
	UPDATE  tTaskPredecessor
	SET		tTaskPredecessor.TaskKey = #tTaskPredecessor.TaskKey
			,tTaskPredecessor.PredecessorKey = #tTaskPredecessor.PredecessorKey
			,tTaskPredecessor.Lag = #tTaskPredecessor.Lag
			,tTaskPredecessor.InWeeks = #tTaskPredecessor.InWeeks
	FROM    #tTaskPredecessor  		
	WHERE   tTaskPredecessor.TaskPredecessorKey = #tTaskPredecessor.TaskPredecessorKey  		
	AND		Action = 2
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	delete tTaskPredecessor
	from   #tTask 
	where  tTaskPredecessor.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	delete tTaskPredecessor
	from   #tTask 
	where  tTaskPredecessor.PredecessorKey = #tTask.TaskKey
	and    #tTask.Action = 3

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''F: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
			
	if isnull(@RequireTasks, 0) = 1
	begin
		-- tasks are required on expenses
		delete tEstimateTaskExpense
		from   #tTask 
		where  tEstimateTaskExpense.TaskKey = #tTask.TaskKey
		and    #tTask.Action = 3
	
		select @Error = @@ERROR, @Rowcount = @@ROWCOUNT

		If @Rowcount > 0
			select @RecalcEstimate = 1

		IF @Error <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -99
		END
	end
	else
	begin
		-- tasks are not required on expenses
		update tEstimateTaskExpense
		set    tEstimateTaskExpense.TaskKey = null
		from   #tTask 
		where  tEstimateTaskExpense.TaskKey = #tTask.TaskKey
		and    #tTask.Action = 3

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -99
		END
	end

	delete tEstimateTaskLabor
	from   #tTask 
	where  tEstimateTaskLabor.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3
	
	select @Error = @@ERROR, @Rowcount = @@ROWCOUNT

	If @Rowcount > 0
		select @RecalcEstimate = 1

	IF @Error <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	delete tEstimateTaskLaborTitle
	from   #tTask 
	where  tEstimateTaskLaborTitle.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3
		
	delete tEstimateTaskLaborLevel
	from   #tTask 
	where  tEstimateTaskLaborLevel.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3

	delete tEstimateTaskAssignmentLabor
	from   #tTask 
	where  tEstimateTaskAssignmentLabor.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
	
	delete tEstimateTask
	from   #tTask 
	where  tEstimateTask.TaskKey = #tTask.TaskKey
	and    #tTask.Action = 3
	
	select @Error = @@ERROR, @Rowcount = @@ROWCOUNT

	If @Rowcount > 0
		select @RecalcEstimate = 1

	IF @Error <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''G: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	-- Log Tasks being deleted from the Schedule
	DECLARE @CompanyKey int, @ProjectNumber VARCHAR(100), @Now as datetime, @Comments varchar(4000), @ActionBy nvarchar(500)

	SELECT @ProjectNumber = ProjectNumber, @CompanyKey = CompanyKey from tProject (nolock) where ProjectKey = @ProjectKey
	SELECT @Now = GETUTCDATE()
	
	IF ISNULL(@UserKey,0) > 0
		SELECT @ActionBy = UserName FROM vUserName WHERE UserKey = @UserKey

	INSERT	tActionLog
			(
			Entity,
			EntityKey,
			CompanyKey,
			ProjectKey,
			Action,
			ActionDate,
			ActionBy,
			Comments,
			Reference,
			SourceCompanyID,
			UserKey
			)
	SELECT	''Project'', 
			tmp.TaskKey, 
			@CompanyKey, 
			@ProjectKey, 
			''Task Deleted'',
			@Now,
			@ActionBy,
			''Task '' + ISNULL(t.TaskID, '''') + '' - '' + ISNULL(t.TaskName, '''') + '' was deleted'',
			@ProjectNumber,
			NULL,
			@UserKey
	FROM	#tTask tmp
	INNER JOIN tTask t (nolock) ON tmp.TaskKey = t.TaskKey
	WHERE	Action = 3 --Delete
	

	-- Delete the tasks			
	DELETE tTask 
	FROM   #tTask
	WHERE  tTask.TaskKey = #tTask.TaskKey
	AND    tTask.ProjectKey = @ProjectKey
	AND    #tTask.Action = 3
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''H: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	
	/*
	 * tTaskUser 
	 */

	DELETE	tTaskUserHour
	FROM	tTaskUserHour tuh
	INNER JOIN #tTaskUser tu ON tuh.TaskUserKey = tu.TaskUserKey
	WHERE	tu.Action = 3

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END
		
	DELETE  tTaskUser
	FROM    #tTaskUser  		
	WHERE   tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey  		
	AND     Action = 3

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''I: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()


	--Call SP to reassign ToDo items	
	EXEC spScheduleSaveReassignToDo

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''J: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	--If this is not a Platinum save, populate the Platinum specific field values in the temp table with the existing values so that
	--they''re not lost when Flash saves.
	IF @Platinum <> 1
		UPDATE	#tTaskUser
		SET		#tTaskUser.APlanStart = tTaskUser.APlanStart,
				#tTaskUser.APlanComplete = tTaskUser.APlanComplete,
				#tTaskUser.ADescription = tTaskUser.ADescription,
				#tTaskUser.ManualAdjustment = ISNULL(tTaskUser.ManualAdjustment, 0),
				#tTaskUser.PercAssigned = tTaskUser.PercAssigned
		FROM	tTaskUser
		WHERE	tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey		
		AND		Action = 2
	
	-- (728544) Treat 0 as NULL (unassigned) so the default TaskUserStatus can be applied.
	UPDATE  #tTaskUser
	SET     TaskUserStatusKey = NULL
	WHERE   ISNULL(TaskUserStatusKey, 0) = 0

	UPDATE tTaskUser
	SET		tTaskUser.UserKey = #tTaskUser.UserKey,
			tTaskUser.Hours = #tTaskUser.Hours,
			--tTaskUser.PercComp = #tTaskUser.PercComp,
			--tTaskUser.ActStart = #tTaskUser.ActStart,
			--tTaskUser.ActComplete = #tTaskUser.ActComplete,
			tTaskUser.ReviewedByTraffic = #tTaskUser.ReviewedByTraffic,
			tTaskUser.ReviewedByDate = #tTaskUser.ReviewedByDate,
			tTaskUser.ReviewedByKey = #tTaskUser.ReviewedByKey,
			tTaskUser.CompletedByDate = #tTaskUser.CompletedByDate,
			tTaskUser.CompletedByKey = #tTaskUser.CompletedByKey,
			tTaskUser.ServiceKey = #tTaskUser.ServiceKey,
			tTaskUser.Subject = #tTaskUser.Subject,
			tTaskUser.Description = #tTaskUser.Description,
			tTaskUser.Comments = #tTaskUser.Comments,
			tTaskUser.DeliverableKey = #tTaskUser.DeliverableKey,
			tTaskUser.APlanStart = #tTaskUser.APlanStart,
			tTaskUser.APlanComplete = #tTaskUser.APlanComplete,
			tTaskUser.ADescription = #tTaskUser.ADescription,
			tTaskUser.ManualAdjustment = ISNULL(#tTaskUser.ManualAdjustment, 0),
			tTaskUser.PercAssigned = #tTaskUser.PercAssigned,
			tTaskUser.TaskUserStatusKey = #tTaskUser.TaskUserStatusKey
	FROM	#tTaskUser
	WHERE	tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey		
	AND		Action = 2
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	UPDATE	tTaskUser
	SET		tTaskUser.PercComp = ISNULL(#tTaskUser.PercComp, 0)
	FROM    #tTaskUser
	WHERE   tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey
	AND     #tTaskUser.Action = 2
	AND		((ISNULL(#tTaskUser.PercComp, 0) <> ISNULL(#tTaskUser.OrigPercComp, 0)) OR @Platinum <> 1)

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	UPDATE	tTaskUser
	SET		tTaskUser.ActStart = #tTaskUser.ActStart
	FROM    #tTaskUser
	WHERE   tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey
	AND     #tTaskUser.Action = 2
	AND		((#tTaskUser.ActStart IS NULL AND #tTaskUser.OrigActStart IS NOT NULL)
			OR (#tTaskUser.ActStart IS NOT NULL AND #tTaskUser.OrigActStart IS NULL)
			OR (#tTaskUser.ActStart <> #tTaskUser.OrigActStart)
			OR (@Platinum <> 1))

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	UPDATE	tTaskUser
	SET		tTaskUser.ActComplete = #tTaskUser.ActComplete
	FROM    #tTaskUser
	WHERE   tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey
	AND     #tTaskUser.Action = 2
	AND		((#tTaskUser.ActComplete IS NULL AND #tTaskUser.OrigActComplete IS NOT NULL)
			OR (#tTaskUser.ActComplete IS NOT NULL AND #tTaskUser.OrigActComplete IS NULL)
			OR (#tTaskUser.ActComplete <> #tTaskUser.OrigActComplete)
			OR (@Platinum <> 1))

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END	
	
	UPDATE	tTaskUser
	SET		tTaskUser.ADescriptionLastModified = GETUTCDATE()
	FROM    #tTaskUser
	WHERE   tTaskUser.TaskUserKey = #tTaskUser.TaskUserKey
	AND     #tTaskUser.Action = 2
	AND		ISNULL(#tTaskUser.ADescription, '''') <> ISNULL(#tTaskUser.OrigADescription, '''')

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END		

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''K: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	INSERT tTaskUser
			(
			UserKey,
			TaskKey,
			Hours,
			PercComp,
			ActStart,
			ActComplete,
			ReviewedByTraffic,
			ReviewedByDate,
			ReviewedByKey,
			CompletedByDate,
			CompletedByKey,
			ServiceKey,
			Subject,
			Description,
			Comments,
			DeliverableKey,
			APlanStart,
			APlanComplete,
			ADescription,
			ADescriptionLastModified,
			ManualAdjustment,
			PercAssigned,
			TaskUserStatusKey,
			InsertTempKey
			)
	OUTPUT ''tTaskUser'', INSERTED.InsertTempKey, INSERTED.TaskUserKey
	INTO	#InsertedTasks
	SELECT
			UserKey,
			TaskKey,
			Hours,
			PercComp,
			ActStart,
			ActComplete,
			ReviewedByTraffic,
			ReviewedByDate,
			ReviewedByKey,
			CompletedByDate,
			CompletedByKey,
			ServiceKey,
			Subject,
			Description,
			Comments,
			DeliverableKey,
			APlanStart,
			APlanComplete,
			ADescription,
			GETUTCDATE(),
			ISNULL(ManualAdjustment, 0),
			PercAssigned,
			TaskUserStatusKey,
			TaskUserKey
	FROM	#tTaskUser
	WHERE	TaskUserKey <= 0
	AND		Action = 1

	INSERT	#NewKeys
	SELECT	*
	FROM	#InsertedTasks

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''L: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	/*
	 * tTaskPredecessor 
	 */		

	DELETE  tTaskPredecessor
	FROM    #tTaskPredecessor  		
	WHERE   tTaskPredecessor.TaskPredecessorKey = #tTaskPredecessor.TaskPredecessorKey  		
	AND     Action = 3

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @ValidatePreds = 1
	BEGIN
		DELETE  tTaskPredecessor
			FROM tTask (NOLOCK)
		WHERE   tTaskPredecessor.TaskKey = tTask.TaskKey
		AND     tTask.ProjectKey = @ProjectKey
		AND     tTaskPredecessor.TaskPredecessorKey NOT IN (SELECT TaskPredecessorKey FROM #tTaskPredecessor)

		IF @@ERROR <> 0
		BEGIN
			ROLLBACK TRAN
			RETURN -99
		END
	END

	--Prevent duplicate inserts
	DELETE	#tTaskPredecessor
	FROM	tTaskPredecessor
	WHERE	#tTaskPredecessor.TaskKey = tTaskPredecessor.TaskKey
	AND		#tTaskPredecessor.PredecessorKey = tTaskPredecessor.PredecessorKey
	AND		#tTaskPredecessor.Action = 1
	
	INSERT  tTaskPredecessor (TaskKey, PredecessorKey, Type, Lag, InWeeks)
	SELECT  #tTaskPredecessor.TaskKey
			,#tTaskPredecessor.PredecessorKey
			,#tTaskPredecessor.Type
			,#tTaskPredecessor.Lag
			,#tTaskPredecessor.InWeeks
	FROM    #tTaskPredecessor  		
	WHERE   Action = 1

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -99
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''M: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	-- For returns to Flash
	INSERT #NewKeys (Entity, OldKey, NewKey)
	SELECT ''tTaskPredecessor'', TaskPredecessorKey, NULL
	FROM   #tTaskPredecessor
	WHERE  Action = 1
	
	UPDATE #NewKeys
	SET    #NewKeys.NewKey = b.TaskPredecessorKey 
	FROM   #tTaskPredecessor a
	       ,tTaskPredecessor b (NOLOCK)  
	WHERE  a.TaskPredecessorKey = #NewKeys.OldKey
	AND    a.TaskKey = b.TaskKey
	AND    a.PredecessorKey = b.PredecessorKey
	AND    #NewKeys.Entity = ''tTaskPredecessor''
	
	COMMIT TRAN

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''N: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

		 
	-- fix for issues where project status
	UPDATE tProject 
	SET TaskStatus = ISNULL((SELECT MAX(tTask.TaskStatus) 
	FROM tTask (NOLOCK) 
	WHERE tTask.ProjectKey = tProject.ProjectKey
	AND tTask.PercComp < 100
	AND tTask.ScheduleTask = 1
	AND tTask.TaskType = 2), 1)
	WHERE tProject.ProjectKey = @ProjectKey

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''O: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
				
	/*
	 * tAssignment
	 * Did not put any SQL Transaction since the original code does not have any 
	 */		

	 --Inserts and Deletes only, do not process Updates
	IF @tasksFromTemplate = 0
	BEGIN	
		DELETE tProjectUserServices
		FROM   #tAssignment
		WHERE  tProjectUserServices.ProjectKey = @ProjectKey
		AND    tProjectUserServices.UserKey = #tAssignment.UserKey
		AND    #tAssignment.Action = 3
	END
	ELSE 
	BEGIN
		DELETE tProjectUserServices
		FROM   #tProjectUserServices
		WHERE  tProjectUserServices.ProjectKey = @ProjectKey
		AND    tProjectUserServices.UserKey = #tProjectUserServices.UserKey
		AND	   #tProjectUserServices.ServiceKey <> 0
	END
			
	-- Deletes
	DELETE tAssignment
	FROM   #tAssignment
	WHERE  tAssignment.ProjectKey = @ProjectKey 
	AND    tAssignment.UserKey = #tAssignment.UserKey
	AND    #tAssignment.Action = 3	

	-- Before inserting, check if already there
	UPDATE #tAssignment
	SET    #tAssignment.Action = 4 -- do not process later
	FROM   tAssignment (NOLOCK)
	WHERE  tAssignment.ProjectKey = @ProjectKey 
	AND    tAssignment.UserKey = #tAssignment.UserKey 
	
	INSERT tAssignment(ProjectKey,UserKey, HourlyRate, SubscribeDiary, SubscribeToDo, DeliverableReviewer, DeliverableNotify)
	SELECT DISTINCT @ProjectKey, u.UserKey, ISNULL(u.HourlyRate, 0), ISNULL(u.SubscribeDiary, 0), ISNULL(u.SubscribeToDo, 0), ISNULL(u.DeliverableReviewer, 0), ISNULL(u.DeliverableNotify, 0)
	FROM   #tAssignment
	INNER JOIN tUser u (nolock) on #tAssignment.UserKey = u.UserKey
	WHERE  #tAssignment.Action = 1

	-- protection against duplicates
	DELETE tAssignment
	WHERE  tAssignment.ProjectKey = @ProjectKey
	AND    tAssignment.AssignmentKey > (SELECT MIN(a2.AssignmentKey) FROM tAssignment a2 (NOLOCK)
							WHERE  a2.ProjectKey = @ProjectKey
							AND    a2.UserKey = tAssignment.UserKey)
		
	-- protection against missing users (Bug 8250)
	-- not sure why, but it happened at Media Logic
	INSERT tAssignment (ProjectKey, UserKey, HourlyRate, SubscribeDiary, SubscribeToDo, DeliverableReviewer, DeliverableNotify)
	SELECT DISTINCT @ProjectKey, tu.UserKey, u.HourlyRate, ISNULL(u.SubscribeDiary, 0), ISNULL(u.SubscribeToDo, 0), ISNULL(u.DeliverableReviewer, 0), ISNULL(u.DeliverableNotify, 0)
	FROM   tTaskUser tu (NOLOCK)
		INNER JOIN tTask t (NOLOCK) ON tu.TaskKey = t.TaskKey
		INNER JOIN tUser u (NOLOCK) ON tu.UserKey = u.UserKey
	WHERE t.ProjectKey = @ProjectKey
	AND   tu.UserKey NOT IN (SELECT UserKey FROM tAssignment (NOLOCK) WHERE ProjectKey = @ProjectKey)

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''P: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
			
	-- For returns to Flash
	INSERT #NewKeys (Entity, OldKey, NewKey)
	SELECT ''tAssignment'', AssignmentKey, AssignmentKey
	FROM   #tAssignment
	WHERE  Action = 1
	
	UPDATE #NewKeys
	SET    #NewKeys.NewKey = b.AssignmentKey 
	FROM   #tAssignment a
	       ,tAssignment b (NOLOCK)  
	WHERE  a.AssignmentKey = #NewKeys.OldKey
	AND    b.ProjectKey = @ProjectKey
	AND    a.UserKey = b.UserKey
	AND    #NewKeys.Entity = ''tAssignment''
	
	IF @tasksFromTemplate = 0
	BEGIN
		Insert tProjectUserServices (ProjectKey, UserKey, ServiceKey)
		Select @ProjectKey, u.UserKey, u.DefaultServiceKey
		from   tUser u (nolock)
		 ,#tAssignment b
		Where  b.UserKey = u.UserKey
		And    b.Action = 1
		And    u.DefaultServiceKey IS NOT NULL
	END
	ELSE
	BEGIN
		Insert tProjectUserServices (ProjectKey, UserKey, ServiceKey)
		Select Distinct @ProjectKey, UserKey, ServiceKey
		from   #tProjectUserServices 
		WHERE  ProjectKey = @ProjectKey
		AND	   ServiceKey <> 0
	END

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''Q: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
	
	-- SummaryTaskKey
	UPDATE tTask SET SummaryTaskKey = 0 WHERE ProjectKey = @ProjectKey AND TaskKey = SummaryTaskKey 	

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''R: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	--Fix to ensure that tasks that were copied on the screen and not linked properly are deleted
	DELETE	tTaskUserHour
	FROM	tTaskUserHour tuh
	INNER JOIN tTaskUser tu ON tuh.TaskUserKey = tu.TaskUserKey
	INNER JOIN tTask t ON tu.TaskKey = t.TaskKey
	WHERE	t.ProjectKey = @ProjectKey
	AND		t.SummaryTaskKey < 0

	DELETE	tTaskUser
	FROM	tTaskUser tu
	INNER JOIN tTask t ON tu.TaskKey = t.TaskKey
	WHERE	t.ProjectKey = @ProjectKey
	AND		t.SummaryTaskKey < 0

	DELETE	tTaskPredecessor
	FROM	tTaskPredecessor pred
	INNER JOIN tTask t ON pred.TaskKey = t.TaskKey
	WHERE	t.ProjectKey = @ProjectKey
	AND		t.SummaryTaskKey < 0

	DELETE	tTaskPredecessor
	FROM	tTaskPredecessor pred
	INNER JOIN tTask t ON pred.PredecessorKey = t.TaskKey
	WHERE	t.ProjectKey = @ProjectKey
	AND		t.SummaryTaskKey < 0
	
	DELETE	tTask
	WHERE	ProjectKey = @ProjectKey
	AND		SummaryTaskKey < 0
	-- -------------------------------------------

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''S: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	-- MoneyTask
	
	-- Fix MoneyTask at the level we track budget
	UPDATE tTask
	SET    tTask.MoneyTask = 1
	WHERE  tTask.ProjectKey = @ProjectKey
	AND    tTask.MoneyTask = 0
	AND    tTask.TrackBudget = 1
	
	-- Fix MoneyTask one level higher than the level where we track budget
	UPDATE tTask
	SET    tTask.MoneyTask = 1
	FROM   tTask (NOLOCK)
		   ,tTask track (NOLOCK) 
	WHERE  tTask.ProjectKey = @ProjectKey
	AND    tTask.ProjectKey = track.ProjectKey 
	AND    tTask.TaskKey = track.SummaryTaskKey 
	AND    track.TrackBudget = 1
	AND    tTask.MoneyTask = 0

	-- BudgetTaskKey
	update tTask
	set    tTask.BudgetTaskKey = tTask.SummaryTaskKey
	from   tTask (NOLOCK)
		  ,tTask summary (NOLOCK)
	where  tTask.SummaryTaskKey = summary.TaskKey
	--and    ISNULL(tTask.BudgetTaskKey, 0) = 0  -- for (136576)
	and    summary.TrackBudget = 1
	and    tTask.TrackBudget = 0
	and    tTask.ProjectKey = @ProjectKey
	and    summary.ProjectKey = @ProjectKey
	
	update tTask
	set    tTask.BudgetTaskKey = summary.SummaryTaskKey
	from   tTask (NOLOCK)
		  ,tTask summary (NOLOCK)
		  ,tTask summary2 (NOLOCK)
	where  tTask.SummaryTaskKey = summary.TaskKey
	and    summary.SummaryTaskKey = summary2.TaskKey
	--and    ISNULL(tTask.BudgetTaskKey, 0) = 0 -- for (136576)
	and    summary2.TrackBudget = 1
	and    tTask.TrackBudget = 0
	and    tTask.ProjectKey = @ProjectKey
	and    summary.ProjectKey = @ProjectKey
	and    summary2.ProjectKey = @ProjectKey

	update tTask
	set    tTask.BudgetTaskKey = tTask.TaskKey
	where  tTask.TrackBudget = 1
	and    ISNULL(tTask.BudgetTaskKey, 0) = 0
	and    tTask.ProjectKey = @ProjectKey

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''T: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	-- patch for TaskType
	update tTask
	set    tTask.TaskType = 1 -- summary
	where  tTask.ProjectKey = @ProjectKey
	and    tTask.TaskType = 2 -- tracking
	and    exists (select 1 from tTask t2 (nolock) 
					where t2.ProjectKey = @ProjectKey
					and   t2.SummaryTaskKey = tTask.TaskKey)  
	
	--Make sure that the date parts of EventStart/End match the dates in PlanStart and PlanComplete
	UPDATE	tTask
	SET		EventStart = dbo.fSyncDate(EventStart, PlanStart),
			EventEnd = dbo.fSyncDate(EventEnd, PlanComplete)
	WHERE	ProjectKey = @ProjectKey
	AND		ShowOnCalendar = 1	
	
	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''U: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	   
	-- Re rollup assigned names, allocations
	exec sptProjectRollupSchedule @ProjectKey, @PercComp, @Duration

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''W: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
	
	-- GHL: I placed this outside of the SQL transaction because it takes too long
	-- and this concerns only transferred transactions
	if exists (select 1 from #tTask where TaskKey > 0 and Action = 3)
	begin
		-- At this time, we have established at the top of the sp that all tTime records have been
		-- 1) Transferred
		-- 2) And not in WIP
		-- we can safely delete tTime records without testing TransferToKey
		
		-- Same logic for other transactions
		
		delete tTime
		from   #tTask 
		where  tTime.ProjectKey = @ProjectKey -- Limit to ProjectKey
		and    tTime.TaskKey = #tTask.TaskKey 
		--and    tTime.TransferToKey is not null -- Avoid a costly RID lookup to read TransferToKey
		and    #tTask.Action = 3 -- delete action
		and    #tTask.TaskKey > 0
		
		create table #time(TimeKey uniqueidentifier null)
		
		insert #time (TimeKey)
		select TimeKey
		from   tTime (nolock)
		      ,#tTask 
		where  tTime.ProjectKey = @ProjectKey
		and    tTime.DetailTaskKey = #tTask.TaskKey
		and    #tTask.Action = 3 -- delete action
		and    #tTask.TaskKey > 0
 
		if (select count(*) from #time) > 0
		begin		 
			update tTime
			set    tTime.DetailTaskKey = null
			from   #time
			where  tTime.TimeKey = #time.TimeKey
		end
		
		
		delete tExpenseReceipt
		from   #tTask 
		where  tExpenseReceipt.ProjectKey = @ProjectKey
		and    tExpenseReceipt.TaskKey = #tTask.TaskKey
		--and    tExpenseReceipt.TransferToKey is not null -- was transferred
		and    #tTask.Action = 3 -- delete action
		and    #tTask.TaskKey > 0
		
		
		delete tVoucherDetail
		from   #tTask 
		where  tVoucherDetail.ProjectKey = @ProjectKey
		and    tVoucherDetail.TaskKey = #tTask.TaskKey
		--and    tVoucherDetail.TransferToKey is not null -- was transferred
		and    #tTask.Action = 3 -- delete action
		and    #tTask.TaskKey > 0
		
		delete tPurchaseOrderDetail
		from   #tTask 
		where  tPurchaseOrderDetail.ProjectKey = @ProjectKey
		and    tPurchaseOrderDetail.TaskKey = #tTask.TaskKey
		--and    tPurchaseOrderDetail.TransferToKey is not null -- was transferred
		and    #tTask.Action = 3 -- delete action
		and    #tTask.TaskKey > 0
		
		delete tMiscCost
		from   #tTask 
		where  tMiscCost.ProjectKey = @ProjectKey
		and    tMiscCost.TaskKey = #tTask.TaskKey
		--and    tMiscCost.TransferToKey is not null -- was transferred
		and    #tTask.Action = 3 -- delete action
		and    #tTask.TaskKey > 0
		
	end

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''X: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	declare @EstimateKey int, @ApprovedQty int, @SalesTax1Amount money, @SalesTax2Amount money
	if isnull(@RecalcEstimate, 0) > 0
	begin
		select @EstimateKey = 0

		while (1=1)
		begin
			select @EstimateKey = min(EstimateKey)
			from   tEstimate (nolock)
			where  ProjectKey = @ProjectKey
			and    EstimateKey > @EstimateKey
			-- And not approved
			AND    NOT  ((isnull(ExternalApprover, 0) > 0 and  ExternalStatus = 4) 
						Or (isnull(ExternalApprover, 0) = 0 and  InternalStatus = 4))  

			if @EstimateKey is null
				break

			Select @ApprovedQty = ApprovedQty from tEstimate (nolock) where EstimateKey = @EstimateKey
			Exec sptEstimateRecalcSalesTax @EstimateKey, @ApprovedQty, @SalesTax1Amount OUTPUT, @SalesTax2Amount OUTPUT
			Update tEstimate set SalesTaxAmount = @SalesTax1Amount, SalesTax2Amount = @SalesTax2Amount where EstimateKey = @EstimateKey

			exec sptEstimateTaskRollupDetail @EstimateKey

		end

	end

	IF @saveTiming = 1
		SELECT	@timingMsg = @timingMsg + ''Y: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

	-- Sets hourly rates on assignment records where possible
	Exec sptProjectRollupSetAssignmentRates @ProjectKey

	IF @saveTiming = 1
	BEGIN
		SELECT	@timingMsg = @timingMsg + ''Z: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
	END

	--Update the task assignments for future recurring tasks
	EXEC sptTaskUserUpdateRecurringTasks @ProjectKey

	IF @saveTiming = 1
	BEGIN
		SELECT	@timingMsg = @timingMsg + ''AA: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()
	END

	EXEC spScheduleValidateRecurring @ProjectKey

	IF @saveTiming = 1
	BEGIN
		SELECT	@timingMsg = @timingMsg + ''AB: '' + CAST(DATEDIFF(MILLISECOND, @debugTimeStamp, GETDATE()) as varchar)+ ''; '',
				@debugTimeStamp = GETDATE()

		UPDATE	tProject
		SET		StatusNotes = @timingMsg
		WHERE	ProjectKey = @ProjectKey
	END

	IF EXISTS(SELECT NULL
			FROM	vTaskPredecessorCrossProject
			WHERE	PredProjectKey = @ProjectKey
			AND		CrossProject = 1)
		RETURN 2 --This is a cross project pred
			  						 			
	RETURN 1 --Not a cross project pred


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

ALTER PROCEDURE [dbo].[sptCampaignGetProjectList]
	@CampaignKey int,
	@IncludeTasks tinyint = 1,
	@ProjectKey int = null
AS

/*
|| When      Who Rel      What
|| 1/14/10   CRG 10.5.1.7 Created
|| 4/26/10   CRG 10.5.2.1 Added PlanDuration to project query
|| 4/27/10   CRG 10.5.2.1 Added TaskStatus to project query
|| 7/8/10    CRG 10.5.3.2 Removed ProjectNumber and TaskID from DisplayName
|| 8/17/10   CRG 10.5.3.3 Added optional @IncludeTasks parm so that this can be called by sptCampaignGet to just return the projects.
||                        Also added CampaignOrder
|| 11/18/10  GHL 10.5.3.8 Changed DisplayName to project full name
|| 11/19/20  GHL 10.5.3.8 Added fields to change on the task edit ballon on the schedule grid
|| 11/23/10  GHL 10.5.3.9 Added ProjectKey to restrict the dataset after task edit balloon 
|| 11/23/10  GHL 10.5.3.9 Added fields to change on the project edit ballon on the schedule grid
|| 11/30/10  GHL 10.5.3.9 Added openIcon to control visibility of open icon for projects/segments
|| 10/04/12  RLB 10.5.6.0 (155991) Added check for project with a locked status
|| 10/07/15  RLB 10.5.9.7 Added Plat Fields
|| 04/15/19  RLB 19.0.5.0 (455180) Added TaskName because the gantt needs the field
|| 05/16/19  RLB 19.0.6.0 (443501) added ScheduleTask to control printing certain date fields
|| 06/28/19  GAR 19.0.7.0 (431684) Added timeline segment color to campaign tasks
|| 08/23/19  GAR 19.0.9.0 (473474) Added project manager
|| 11/27/19  GAR 20.0.1.0 (489889) Add the primary contact from the project if there is one
|| 12/02/19  GAR 20.0.1.0 (489890) Add the percent complete at the project level
|| 05/13/20  RLB 20.0.6.0 (514574) Added project''s division and or product
|| 07/10/20  CRG 20.0.8.0 (521933) Added join to services to get assignments for services
|| 07/01/21  RLB 21.08.15 (562793) added fields needs to use all reg schedule cols  
|| 08/30/21  GAR 21.10.17 (564462) Added an Active value for use in the campaign project listing
|| 09/14/21  RLB 21.10.17 (569007) Added cross project data and pulling pred data
|| 05/08/23  CRG 23.06.18 (604775) Now using tTaskPriority
|| 09/05/23  RLB 23.10.15 (649724) Added project Type
|| 09/28/23  RLB 23.10.15 (651884) Added ProjectFullName
|| 01/10/24  RLS 24.02.18 (653569) Changed ProjectFullName to nvarchar
|| 03/31/26  GAR 26.04.19 (723332) Added ProjectStatusColor
|| 04/21/26  RLS 26.05.17 (726803) Added t.ApprovedCOHours to the select list
*/


create table #projects (ProjectKey int null, ScheduleDirection int null, WorkSun int null, WorkMon int null, WorkTue int null, WorkWed int null, WorkThur int null, WorkFri int null, WorkSat int null, FullProjectName nvarchar(300) null)
 
if isnull(@ProjectKey, 0) > 0 
	insert #projects (ProjectKey, FullProjectName, ScheduleDirection, WorkSun, WorkMon, WorkTue, WorkWed, WorkThur, WorkFri, WorkSat)
	SELECT	p.ProjectKey, ISNULL(p.ProjectNumber + '' - '', '''') + ISNULL(p.ProjectName, '''')
			-- fields needed by Task Edit balloon
			,p.ScheduleDirection,p.WorkSun, p.WorkMon, p.WorkTue, p.WorkWed, p.WorkThur, p.WorkFri, p.WorkSat  
	FROM	tProject p (nolock)
	WHERE	p.ProjectKey = @ProjectKey
else
	insert #projects (ProjectKey, FullProjectName, ScheduleDirection, WorkSun, WorkMon, WorkTue, WorkWed, WorkThur, WorkFri, WorkSat)
	SELECT	p.ProjectKey
			,ISNULL(p.ProjectNumber + '' - '', '''') + ISNULL(p.ProjectName, '''')
			-- fields needed by Task Edit balloon
			,p.ScheduleDirection,p.WorkSun, p.WorkMon, p.WorkTue, p.WorkWed, p.WorkThur, p.WorkFri, p.WorkSat
	FROM	tProject p (nolock)
	LEFT JOIN tCampaignSegment cs (nolock) ON p.CampaignSegmentKey = cs.CampaignSegmentKey
	WHERE	p.CampaignKey = @CampaignKey
	OR		cs.CampaignKey = @CampaignKey

	SELECT	p.ProjectKey,
			p.ProjectNumber,
			p.ProjectName, 
			p.Closed,
			ISNULL(p.ProjectNumber + '' - '', '''') + ISNULL(p.ProjectName, '''') AS DisplayName, 
		    p.Description,
			p.AccountManager,
			isnull(u.FirstName + '' '', '''') + u.LastName as AccountManagerName,
			p.ProjectStatusKey,
			p.CampaignSegmentKey,
			cs.SegmentName,
			cs.DisplayOrder as SegmentDisplayOrder,
			p.StartDate AS PlanStart,
			p.CompleteDate AS PlanComplete,
			DATEDIFF(DAY, p.StartDate, p.CompleteDate) AS PlanDuration,
			1 AS TaskStatus, --Initialize to 1, the MAX from the tasks will be rolled up in Flex by the Rollup manager
			ISNULL(p.CampaignOrder, 0) AS CampaignOrder
			-- fields needed by the Project Edit balloon
			,''edit'' as editIcon
			,p.StatusNotes
			,p.ClientNotes
			,p.DetailedNotes
			,p.ProjectColor
			,ps.ProjectStatusID 
			,ps.ProjectStatus
			,ps.Locked 
			,pbs.ProjectBillingStatusID 
			,pbs.ProjectBillingStatus
			-- fields needed by the Task Add balloon
			,''new'' as addIcon
			-- fields needed by the Project Open balloon (target)
			,''menuPC'' as openIcon
			,isnull(pm.FirstName + '' '', '''') + pm.LastName as ProjectManagerName
			,isnull(pc.FirstName + '' '', '''') + pc.LastName as PrimaryContactName
			,isnull(p.PercComp, 0) AS PercComp
			,cd.DivisionName 
			,cp.ProductName
			,p.Active
			,pt.ProjectTypeName
			,ISNULL(ps.ProjectStatusColor, '''') AS ProjectStatusColor
	FROM	tProject p (nolock)
	INNER JOIN #projects tmp ON p.ProjectKey = tmp.ProjectKey
	left outer join tUser u (nolock) on p.AccountManager = u.UserKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey
	left outer join tUser pc (nolock) on p.BillingContact = pc.UserKey
	left outer join tProjectStatus ps (nolock) on ps.ProjectStatusKey = p.ProjectStatusKey
	left join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey
	left outer join tProjectBillingStatus pbs (nolock) on pbs.ProjectBillingStatusKey = p.ProjectBillingStatusKey
	left outer join tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
	left outer join tClientProduct cp (nolock) on p.ClientProductKey = cp.ClientProductKey
	ORDER BY cs.DisplayOrder, p.CampaignOrder

	IF @IncludeTasks = 1
	BEGIN
		SELECT	t.TaskKey
		INTO	#tasks
		FROM	tTask t (nolock)
		INNER JOIN #projects tmp ON t.ProjectKey = tmp.ProjectKey
		WHERE	t.ScheduleTask = 1
	
		SELECT	t.TaskKey,
				t.ProjectKey,
				ISNULL(t.TaskName, '''') AS DisplayName,
				t.TaskName,
				t.DisplayOrder,
				t.ProjectOrder,
				t.SummaryTaskKey,
				t.TaskType,
				t.TaskLevel,
				t.PlanStart,
				t.PlanComplete,
				t.PercComp,
				t.PercCompSeparate,
				t.BaseStart,
				t.BaseComplete,
				t.PlanDuration,
				t.TaskID,
				t.TaskStatus,
				-- fields below needed for task edit balloon
				case when t.TaskType = 2 then ''edit'' else null end as editIcon,
				t.ActStart,
				t.ActComplete,
				t.TaskConstraint,
				t.ConstraintDate,
				t.HideFromClient,
				t.WorkAnyDay,
				t.Priority,
				t.Comments,
				t.Description,
				t.ScheduleTask,
				t.DueBy,
				t.HourlyRate,
				t.IOCommission,
				t.Markup,
				t.ReviewedByTraffic,
				t.ShowDescOnEst,
				t.EventStart,
				t.EventEnd,
				t.Taxable,
				t.Taxable2,
				t.TrackBudget,
				t.ExcludeFromStatus,
				ts.SegmentName,
				p.ScheduleDirection,
				p.FullProjectName,
				p.WorkSun, p.WorkMon, p.WorkTue, p.WorkWed, p.WorkThur, p.WorkFri, p.WorkSat,
				ts.SegmentColor AS TaskColor,
				t.PercComp as OrigPercComp,
				t.EstHours,
				t.ApprovedCOHours,
				t2.TaskName as SummaryTaskName,
				t.AllowAnyone,
				wt.WorkTypeName,
				t.BCCommission,
				t.UserChangedDate,
				CASE 
					WHEN ISNULL(t.TaskConstraint,0) = 0 THEN 
						CASE 
							WHEN p.ScheduleDirection = 1 THEN ''As Soon As Possible'' 
							ELSE ''As Late As Possible''
						END
					WHEN ISNULL(t.TaskConstraint,0) = 1 THEN ''Must Start On'' 
					WHEN ISNULL(t.TaskConstraint,0) = 2 THEN ''Must Finish On'' 
					WHEN ISNULL(t.TaskConstraint,0) = 3 THEN ''Finish No Earlier Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 4 THEN ''Finish No Later Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 5 THEN ''Start No Earlier Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 6 THEN ''Start No Later Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 7 THEN ''Duration Of Project''
					ELSE ''Client''
			  END AS ConstraintName,
			tp.PriorityName,
			CASE 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 0 THEN ''Any Day''
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 1 THEN ''Sunday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 2 THEN ''Monday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 3 THEN ''Tuesday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 4 THEN ''Wednesday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 5 THEN ''Thursday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 6 THEN ''Friday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 7 THEN ''Saturday'' 
					ELSE ''Any Day''
			  END AS ConstraintDayOfTheWeekName,
			(select count(*) from tForm f (nolock) Where f.TaskKey = t.TaskKey and	f.DateClosed IS NULL) as FormCount,
			ISNULL((Select Sum(ActualHours) from tTime ti (nolock) Where ti.ProjectKey = t.ProjectKey And ti.TaskKey = t.TaskKey), 0) as ActualHours,
			ISNULL((Select Sum(Hours) from tTaskUser tau (nolock) Where tau.TaskKey = t.TaskKey), 0) as AllocatedHours,
			(select count(*) from tAttachment (nolock) Where AssociatedEntity = ''Task'' AND EntityKey = t.TaskKey) as AttachmentCount,
			(SELECT COUNT(*) FROM tActivity a (nolock) INNER JOIN tActivityLink al (nolock) ON a.ActivityKey = al.ActivityKey WHERE al.Entity = ''tTask'' AND al.EntityKey = t.TaskKey AND a.Completed = 0) AS OpenActivities,
			ISNULL((Select Count(*) from tActivity (nolock) Where ActivityEntity = ''ToDo'' and TaskKey = t.TaskKey and Completed = 0), 0) as ToDoCount,
			(SELECT COUNT(*) FROM tActivity a (nolock) WHERE a.TaskKey = t.TaskKey AND Completed = 0 AND a.ActivityEntity = ''ToDo'' AND ParentActivityKey = 0) AS OpenToDos,
			 CASE
				WHEN ISNULL(t.MoneyTask, 0) = 1 THEN ISNULL(t.ApprovedCOHours, 0) + ISNULL(t.EstHours, 0)
				ELSE 0
			 END AS TotalEstHours,
			ISNULL(tcps.ProjectStatus, '''') as TCProjectStatus,
			ISNULL(tcps.ProjectStatusID, '''') as TCProjectStatusID
		FROM	tTask t (nolock)
		INNER JOIN #tasks tmp ON t.TaskKey = tmp.TaskKey
		INNER JOIN #projects p ON t.ProjectKey = p.ProjectKey
		left join tTimelineSegment ts (nolock) ON t.TimelineSegmentKey = ts.TimelineSegmentKey
		left join tTask t2 (nolock) ON t.SummaryTaskKey = t2.TaskKey
		left join tWorkType wt (nolock) on t.WorkTypeKey = wt.WorkTypeKey
		left join tProjectStatus tcps (nolock) on t.TCProjectStatusKey = tcps.ProjectStatusKey
		left join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey

		ORDER BY t.ProjectKey, t.ProjectOrder

		SELECT	v.PredecessorKey,
			v.TaskKey,
			v.TaskPredecessorKey,
			v.Lag, 
			ISNULL(v.InWeeks, 0) AS InWeeks,
			v.Type,
			v.PredTaskID + '' '' + v.PredTaskName AS TaskFullName,
			v.PredProjectOrder AS ProjectOrder,
			v.PredTaskID AS TaskID, 
			v.PredTaskName AS TaskName, 
			v.PredProjectKey AS ProjectKey,	
			predProj.ProjectNumber, 
			predProj.ProjectName, 
			v.CrossProject,
			v.PredPlanComplete,
			v.PredPlanDuration,
			v.PredPercComp
		FROM	vTaskPredecessorCrossProject v
		INNER JOIN tProject predProj (nolock) ON v.PredProjectKey = predProj.ProjectKey
		INNER JOIN #tasks tmp ON v.TaskKey = tmp.TaskKey
		ORDER BY v.TaskKey, v.PredProjectOrder
	
		SELECT	tu.*,
				SUBSTRING(ISNULL(FirstName, ''''),1,1) + SUBSTRING(ISNULL(MiddleName, ''''),1,1) + SUBSTRING(ISNULL(LastName, ''''),1,1) AS Initials,
				ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,'''') AS UserName,
				s.ServiceCode
		FROM	tTaskUser tu (nolock)
		LEFT JOIN tUser u (nolock) ON tu.UserKey = u.UserKey
		LEFT JOIN tService s (nolock) ON tu.ServiceKey = s.ServiceKey
		INNER JOIN #tasks tmp ON tu.TaskKey = tmp.TaskKey
	END

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

	(
		@StartDate datetime= NULL,
		@EndDate datetime= NULL,
		@CompanyKey int = NULL,
		@CalendarKey int = NULL
	)

AS --Encrypt

/*
|| When      Who Rel      What
|| 1/20/10   CRG 10.5.1.7 (72888) Modified the ReminderTime restriction to allow records with ParentKey > 0.
||                        Otherwise, modified occurrences that have ReminderTime set to 0 were not being grabbed,
||                        which caused the Task Manager to send out reminders for the original meeting time.
||                        The Task Manager has been modified to not send an email out if the ReminderTime = 0.
|| 09/10/20  CRG 20.1.0.0 Added OrganizerKey for new TaskManager email reminders
|| 10/13/22  CRG 22.11.20 (615895) Added optional CompanyKey and CalendarKey to limit the search
|| 05/11/26  CRG 26.06.14 Modified to limit recurring meetings to ones that apply to the date range
*/

		SELECT	c.CalendarKey
		INTO	#CalendarKeys
		FROM	tCalendar c (nolock)
		INNER JOIN tCalendarAttendee ca (nolock) on c.CalendarKey = ca.CalendarKey and ca.Entity = ''Organizer''
		INNER JOIN tUser org (nolock) ON ca.EntityKey = org.UserKey and ca.Entity = ''Organizer''
		INNER JOIN tCompany co (nolock) on c.CompanyKey = co.CompanyKey
		WHERE
			(
				@StartDate IS NULL
				OR
				((DateAdd("n", -1 * c.ReminderTime, c.EventStart) > @StartDate and DateAdd("n", -1 * c.ReminderTime, c.EventStart) <= @EndDate ) or (c.Recurring =1) or (c.Deleted = 1) or (ParentKey > 0))
			)
			and	org.Active = 1
			and (c.ReminderTime > 0 OR c.ParentKey > 0)
			and co.Locked = 0
			and (@CompanyKey IS NULL OR c.CompanyKey = @CompanyKey)
			and (@CalendarKey IS NULL OR c.CalendarKey = @CalendarKey)

		IF @StartDate IS NOT NULL
		BEGIN
			DELETE	#CalendarKeys
			FROM	#CalendarKeys ck
			INNER JOIN tCalendar c (nolock) on ck.CalendarKey = c.CalendarKey
			WHERE	c.Recurring = 1
			AND		c.RecurringEndDate IS NOT NULL
			AND		c.RecurringEndDate < @StartDate	

			DELETE	#CalendarKeys
			FROM	#CalendarKeys ck
			INNER JOIN tCalendar c (nolock) on ck.CalendarKey = c.CalendarKey
			WHERE	(c.ParentKey > 0 OR c.Deleted = 1)
			AND		c.OriginalStart IS NOT NULL
			AND		c.OriginalStart < @StartDate
		END

		SELECT	c.*,
				convert(char(8), c.EventStart, 108) as StartTime
				,convert(char(8), c.EventEnd, 108) as EndTime				

				,ISNULL(u.FirstName+'' '', '''')+ISNULL(u.LastName, '''') AS AuthorName
				,u.Email
				,u.TimeZoneIndex
				,cc.CompanyName
				,case When caddr.AddressKey is null then addr.Address1 else caddr.Address1 end as Address1
				,case When caddr.AddressKey is null then addr.Address2 else caddr.Address2 end as Address2
				,case When caddr.AddressKey is null then addr.Address3 else caddr.Address3 end as Address3
				,case When caddr.AddressKey is null then addr.City else caddr.City end as City
				,case When caddr.AddressKey is null then addr.State else caddr.State end as State
				,case When caddr.AddressKey is null then addr.PostalCode else caddr.PostalCode end as PostalCode
				,ISNULL(cu.Phone1, cc.Phone) as Phone
				,ISNULL(cu.FirstName, '''') + '' '' + ISNULL(cu.LastName, '''') as ContactName
				,p.ProjectNumber
				,p.ProjectName
				,org.UserKey AS OrganizerKey
		FROM	#CalendarKeys ck
		INNER JOIN tCalendar c (nolock) ON ck.CalendarKey = c.CalendarKey
		INNER JOIN tCalendarAttendee ca (nolock) on c.CalendarKey = ca.CalendarKey and ca.Entity = ''Organizer''
		INNER JOIN tUser org (nolock) ON ca.EntityKey = org.UserKey and ca.Entity = ''Organizer''
		Left Outer Join tUser u (nolock) on ca.EntityKey = u.UserKey
		LEFT OUTER JOIN tCompany cc (nolock) on c.ContactCompanyKey = cc.CompanyKey
		LEFT OUTER JOIN tUser cu (nolock) on c.ContactUserKey = cu.UserKey
		LEFT OUTER JOIN tProject p (nolock) on c.ProjectKey = p.ProjectKey
		left outer join tAddress addr (nolock) on cc.DefaultAddressKey = addr.AddressKey
		left outer join tAddress caddr (nolock) on cu.AddressKey = caddr.AddressKey




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

ALTER VIEW [dbo].[vReport_Voucher]
AS

/*
|| When     Who Rel    What
|| 01/10/07 BSH 8.4001 Added ApprovedDate
|| 10/11/07 CRG 8.5    Added GLCompany, Class, Office, Department
|| 04/16/07 GWG 10.23  Added Item Department. 
|| 05/11/07 GWG 10.025 Added several order line fields
|| 09/11/09 GHL 10.5   Added Transferred Out
|| 12/10/09 GHL 10.514 (68925) Added Estimate ID + Name
|| 01/19/10 GHL 10.517 (72527) Added Billing Item info
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
|| 04/26/10 RLB 10.521  (78143) added custom fields for lines Project Client companies.
|| 04/30/10 RLB 10.522 (63218)Added Parent Company Name
|| 04/26/10 RLB 10.522  (78143) Client wanted Client contact customfields not company. (fixed to join on project billing contact to user)
|| 07/23/10 RLB 10.532 (81660) Added Project Primary Contact and Clients Project Number
|| 09/28/10 RLB 10.535 (91043) Added Opening Transaction to report
|| 10/25/10 RLB 10.537 (91944) Added Vendor and Client Custom fields to this report.
|| 02/22/11 RLB 10.541 (89417) Add Sales Tax line data
|| 08/22/11 GWG 10.547  Tweaked the definition of Sales tax applied to make sure a tax has been selecte and the box on the line is checked
|| 04/24/12 GHL 10.555  Added GLCompanyKey in order to map/restrict
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey
|| 11/08/12 RLB 10.5.6.2 (159062) Added Purchased By
|| 01/23/13 WDF 10.5.6.4 (165985) Added Expense Account Name
|| 06/24/13 RLB 10.5.6.9 (180813) Added voucher description field
|| 07/01/13 GHL 10.5.6.9 (182649) Added [Vendor Accepts CreditCard Cards]
|| 07/18/13 WDF 10.5.7.0 (176497) Added VoucherID
|| 09/03/13 GWG 10.5.7.1 Added fields to assist in Order Analysis
|| 09/09/13 GWG 10.5.7.1 Made the join to vendor left outer for reporting on credit cards
|| 11/15/13 GWG 10.5.7.4 Added client id through the estimate
|| 01/03/14 WDF 10.5.7.6 (188500) Added CreatedByKey and DateCreated
|| 02/05/14 WDF 10.5.7.7 (205342) Added Division Name and Product Name
|| 03/07/14 GHL 10.5.7.6   Added Currency
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
|| 03/10/15 WDF 10.5.9.0 (249110) Added TermsPercent, TermsDays and TermsNet
|| 03/11/15 RLB 10.5.9.0 (249671) Added WIP Posting In and Out Date
|| 03/13/15 RLB 10,5.9.0 (249671) Added WIP Issue In and Out
|| 07/16/15 WDF 10.5.9.4 (263548) Added DBA
|| 11/17/15 WDF 10.5.9.8 (278453) Added Project Type
|| 02/26/16 GHL 10.6.0.1 (290954) Added Exchange Rate
|| 07/05/16 GWG 10.6.0.5 (305230) Changed billable cost to Amount to Bill and GrossAmount to Line Gross Amount
|| 08/04/16 WDF 10.6.0.6 (307138) Wrapped pod.AmountBilled in ISNULL
|| 11/16/16 WDF 10.6.1.0 (318451) Added [Date Updated]
|| 02/06/17 WDF 10.6.1.3 (330555) Added [Campaign ID]
|| 02/08/17 GWG 10.6.1.3 Added client from the voucher line
|| 12/20/17 GWG 18.1     Added exchange rates
|| 05/03/18 AMP 18.5.0.0 (399144) Added Company Type 
|| 08/30/18 MCM 18.9.0.0 (418314) Adding in default address info, phones and web site
|| 10/25/18 GHL 18.9.2.0 (423844) Added QuestDownloaded, this is a customization for Quest Diagnostics
|| 12/31/18 RLS 19.1.0   (437657) Added VCardAccepted
|| 07/09/19 RLB 19.0.8.0 (449833) Added Project Customfields
|| 12/16/19 AMP 20.1.2.0 (488224) Added Line Account Manager and Line Project Manager based on the project on the vendor invoice line
|| 05/22/20 AMP 20.0.6.0 (515852) Added Target GL Company Name from the Vendor Invoice Line
|| 08/04/20 MCM 20.0.9.0 (516999) Added Estimate Full Name, number and name
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 03/02/21 RLB 21.04.18 (549289) Adding Primary Company Contact
|| 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
|| 08/23/23 AMP 23.09.17 (649117) Added ACH Enabled field (Yes/No)
|| 10/03/24 RLB 24.10.20 (680328) Added payment address fields from vendor invoice header
|| 12/06/24 RLB 25.01.19 (689057) Added Paid in CC and Cash
|| 01/29/25 GAR 25.02.16 (692983) Added Line Project Number
|| 02/06/25 AMP 25.03.16 (691808) Added Date Paid
|| 03/11/25 GAR 25.04.20 (695035) Changed Project Number, Name, and Full Name to pull from the header.  Also added Line Project Name and Line Project Full Name and LineProjectKey
|| 04/07/25 AMP 25.05.18 (697727) Added Media Plan ID and Media Plan Name
|| 04/30/25 RLB 25.05.18 (700511) Added Line Division ID and Name
|| 04/30/25 RLB 25.05.18 (700143) Added Order Line Order Header Description
|| 04/30/25 GAR 25.05.18 (700706) Changed Project Type back to look at the line instead of the header
|| 05/19/25 RLS 25.06.15 (700131) Added [Paid By Client]
|| 06/19/25 AMP 25.07.20 (704239) Correction for Vendor Invoice Date Paid when its paid by a Credit Card Charge
|| 08/01/25 RLB 25.09.14 (707623) Added sales tax name 1 and 2 from the voucher header
|| 10/08/25 RLB 25.11.16 (712796) Added Overhead
|| 10/29/25 RLB 25.11.16 (712304) added Header attachment count
|| 02/25/26 MFT 26.03.00 (722977) Add CampaignID/Name for Project on line
|| 04/07/26 GAR 26.05.17 (725874) Added Transaction Status (from vListing_Transactions)
|| 05/11/26 MCM 26.06.x  (728460) Updated Transaction Status to pull from tVoucherDetial instead of vListing_Transactions
*/

SELECT 
	v.CompanyKey,
	isnull(vd.TargetGLCompanyKey, v.GLCompanyKey) as GLCompanyKey, 
	cc.CustomFieldKey,
	c.CustomFieldKey as CustomFieldKey2,
	cClient.CustomFieldKey as CustomFieldKey3,
	lp.CustomFieldKey as CustomFieldKey4,
	hp.ProjectNumber AS [Project Number],
	hp.ProjectName AS [Project Name], 
	hp.ProjectNumber + '' - '' + hp.ProjectName AS [Project Full Name],
	pt.ProjectTypeName AS [Project Type],
	pt.ProjectTypeColor as [Project Type Color],
	Case hp.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project],
	LTRIM(RTRIM(ISNULL(cc.FirstName + '' '','''')  + ISNULL(cc.LastName,''''))) AS [Project Primary Contact],
	hp.ClientProjectNumber AS [Client Project Number],
	div.DivisionName AS [Division Name],
	div.DivisionID as [Division ID],
	ldiv.DivisionName AS [Line Division Name],
	ldiv.DivisionID as [Line Division ID],
	pro.ProductName AS [Product Name],
	pro.ProductID as [Product ID],
	cp.CampaignName as [Campaign Name],
	cp.CampaignID as [Campaign ID],
	lc.CampaignName as [Line Campaign Name],
	lc.CampaignID as [Line Campaign ID],
	cClient.CustomerID as [Client ID],
	cClient.CompanyName as [Client Name],
	cClient.CustomerID + '' - '' + cClient.CompanyName as [Client Full Name],
	lClient.CustomerID as [Line Client ID],
	lClient.CompanyName as [Line Client Name],
	lClient.CustomerID + '' - '' + lClient.CompanyName as [Line Client Full Name],
	meClient.CustomerID as [Estimate Client ID],
	meClient.CompanyName as [Estimate Client Name],
	meClient.CustomerID + '' - '' + meClient.CompanyName as [Estimate Client Full Name],
	t.TaskID AS [Task ID], 
	t.TaskID + '' - '' + t.TaskName AS [Task Full Name],
	c.CompanyName AS [Vendor Name], 
	c.VendorID AS [Vendor ID], 
	c.VendorID + '' - '' + c.CompanyName AS [Vendor Full Name],
	c.DBA AS [Doing Business As],
	LTRIM(RTRIM(ISNULL(cbk.FirstName + '' '','''')  + ISNULL(cbk.LastName,''''))) AS [Created By Name],
	case when c.CCAccepted = 1 then ''YES'' else ''NO'' end as [Vendor Accepts Credit Cards],   
	v.InvoiceDate AS [Invoice Date], 
	v.PostingDate AS [Posting Date],
	MONTH(v.PostingDate) as [Posting Month],
	YEAR(v.PostingDate) as [Posting Year],
	v.DateReceived as [Date Received],
	v.DueDate as [Invoice Due Date],
	v.InvoiceNumber AS [Invoice Number],
	v.VoucherID as [Unique Auto Number],
	v.ApprovedDate AS [Date Approved],
	v.DateCreated AS [Date Created], 
	v.DateUpdated as [Date Updated],
	v.Description AS [Header Description],
	
	v.VoucherTotal - v.AmountPaid as [Invoice Amount Open],
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Approver Name],
	po.PurchaseOrderNumber AS [Purchase Order Number],
	po.Description AS  [Order Line Order Header Description],
	pod.LineNumber as [Order Line Number],
	pod.AdjustmentNumber as [Order Line Adjustment Number],
	pod.TotalCost as [Order Line Net],
	pod.BillableCost as [Order Line Gross],
	ISNULL(pod.AmountBilled, 0) as [Order Line Amt Billed],
	pod.DetailOrderDate as [Order Line Start Date],
	pod.DetailOrderEndDate as [Order Line End Date],
	ISNULL(pod.AccruedCost, 0) as [Order Line Accrued Cost],
	pod.PExchangeRate as [Order Line Project Exchange Rate],
	pod.Markup as [Order Line Markup],
	Case po.BillAt When 0 then ''Gross''
		When 1 then ''Net''
		When 2 then ''Commission'' end as [Order Bill At],
	case when vd.Taxable = 1 and v.SalesTaxKey > 0 then ''YES'' else ''NO'' end as [Line Sales Tax 1 Applied],
	case when vd.Taxable2 = 1 and v.SalesTax2Key > 0 then ''YES'' else ''NO'' end as [Line Sales Tax 2 Applied],
	vd.SalesTax1Amount as [Line Sales 1 Tax Amount],
	vd.SalesTax2Amount as [Line Sales 2 Tax Amount],
	vd.SalesTaxAmount as [Line Sales Tax Total Amount],
	ISNULL(st1.SalesTaxName,'''') as [Sales Tax 1 Name],
	ISNULL(st2.SalesTaxName,'''') as [Sales Tax 2 Name],
	vd.ShortDescription AS [Line Description], 
	vd.Quantity AS [Line Quantity], 
	vd.UnitCost AS [Line Unit Cost], 
	vd.UnitDescription AS [Line Unit Description], 
	vd.TotalCost AS [Line Net Cost], 
	vd.PExchangeRate as [Line Project Exchange Rate],
	vd.LastVoucher as [Last Invoice for Order],
	ISNULL(vd.PrebillAmount, 0) as [Amount Unaccrued],
	(Select SUM(ISNULL(PrebillAmount, 0)) from tVoucherDetail Where PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey) as [Order Line Unaccrued All Invoices],
	(Select MAX(PostingDate) from tVoucherDetail 
		inner join tVoucher on tVoucherDetail.VoucherKey = tVoucher.VoucherKey
		Where PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey and ISNULL(PrebillAmount, 0) <> 0) as [Order Line Last Unaccrue Date],
	case vd.Billable when 1 then ''YES'' else ''NO'' end as Billable,
	vd.Markup, 
	vd.BillableCost AS [Billable Amount], 
	vd.GrossAmount AS [Line Gross Amount],
	vd.AmountBilled AS [Line Amount Billed], 
	case when isnull(i.InvoiceStatus, 0) = 4 then isnull(vd.AmountBilled, 0) else 0 end AS [Line Amount Billed Approved], 
	vd.DatePaidByClient as [Date Paid by Client],
	it.ItemID as [Line Item ID],
	it.ItemName as [Line Item Name],
	i.InvoiceNumber as [Line Invoice Number],
	i.PostingDate as [Client Invoice Posting Date],
	MONTH(i.PostingDate) as [Client Invoice Posting Month],
	YEAR(i.PostingDate) as [Client Invoice Posting Year],
	gl.AccountNumber as [AP Account Number],
	gl2.AccountNumber as [Expense Account Number],
	gl2.AccountName as [Expense Account Name],
	Case When vd.InvoiceLineKey IS NULL then
		Case vd.WriteOff When 1 then ''Write Off'' else ''Unbilled'' end
		When vd.InvoiceLineKey = 0 then ''Marked as Billed''
		else ''Billed'' end as [Billing Status],
	case vd.WriteOff when 1 then ''YES'' else ''NO'' end as WriteOff, 
	case v.Posted when 1 then ''YES'' else ''NO'' end as Posted,
	case v.OpeningTransaction when 1 then ''YES'' else ''NO'' end as [Opening Transaction],
	Case v.Status
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case v.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
		end as [Invoice Status],
	Case When vd.WIPPostingInKey = 0 then ''NO'' else ''YES'' end as [Posted Into WIP],
	Case When vd.WIPPostingOutKey = 0 then ''NO'' else ''YES'' end as [Posted Out Of WIP],
	wpi.PostingDate as [WIP Posting In Date],
	CASE 
		WHEN wpi.PostingDate IS NOT NULL THEN
			case 
				when MONTH(v.PostingDate) = Month(wpi.PostingDate) AND YEAR(v.PostingDate) = YEAR(wpi.PostingDate) then ''No''
				else ''Yes'' End
		ELSE ''No''
	END as [WIP In Issue],
	wpo.PostingDate as [WIP Posting Out Date],
	CASE 
		WHEN wpo.PostingDate IS NOT NULL THEN
			case 
				when MONTH(vd.DateBilled) = Month(wpo.PostingDate)  AND YEAR(vd.DateBilled) = YEAR(wpo.PostingDate) then ''No''
				else ''Yes'' End
		ELSE ''No''
	END as [WIP Out Issue],
	vd.DateBilled as [Date Billed],
	Month(vd.DateBilled) as [Month Billed],
	Year(vd.DateBilled) as [Year Billed],
	isnull(glcT.GLCompanyID, glc.GLCompanyID) as [Company ID], 
	isnull(glcT.GLCompanyName, glc.GLCompanyName) as [Company Name], 
	pc.CompanyName as [Parent Company],
	cl.ClassID as [Class ID],
	cl.ClassName as [Class Name],
	o.OfficeID as [Office ID],
	o.OfficeName as [Office Name],
	o.OfficeColor as [Office Color],
	d.DepartmentName as [Line Department],
	d.DepartmentColor as [Line Department Color],
	id.DepartmentName as [Item Department],
	id.DepartmentColor as [Item Department Color],
    case when vd.TransferToKey is null then ''NO'' else ''YES'' end as [Transferred Out],
    me.EstimateID as [Media Estimate ID],
    me.EstimateName as [Media Estimate Name]
    ,case when hp.LayoutKey is not null then wt.WorkTypeID 
	      else wti.WorkTypeID 
     end as [Billing Item ID] 
    ,case when hp.LayoutKey is not null then isnull(wtcust.Subject, wt.WorkTypeName) 
	      else isnull(wtcusti.Subject, wti.WorkTypeName)  
     end as [Billing Item Name] 
	,case when v.CreditCard = 1 then ''Credit Card Charge'' else ''Vendor Invoice'' end as [Type of Voucher]
	,v.BoughtFrom as [Purchased From]
	,LTRIM(RTRIM(ISNULL(pb.FirstName + '' '','''')  + ISNULL(pb.LastName,''''))) AS [Purchased By]
	,hp.ProjectKey
	,v.ExchangeRate as [Exchange Rate] 
	,v.CurrencyID as [Currency]
	,v.TermsDays as [Terms Days]
	,v.TermsNet as [Terms Net]
	,v.TermsPercent as [Terms Percent]
    ,ct.CompanyTypeName as [Company Type Name]
	,ad.Address1
	,ad.Address2
	,ad.Address3
	,ad.City
	,ad.State
	,ad.PostalCode
	,ad.Country
	,ap.Address1 AS [Payment Address1]
	,ap.Address2 AS [Payment Address2]
	,ap.Address3 AS [Payment Address3] 
	,ap.City AS [Payment City] 
	,ap.State AS [Payment State]
	,ap.PostalCode AS [Payment Postal Code]  
	,ap.Country AS [Payment Country]
	,c.Phone
	,c.Fax
	,c.WebSite
	,case when (c.VCardAccepted is null or c.VCardAccepted = 0) then ''NO'' else ''YES'' end as [Accepts VPay]
	,v.QuestDownloaded  as [Date Time Downloaded]
	,case when hp.AccountManager is null then LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,'''')))
	  else LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) 
	  end as [Line Account Manager] 
	,case when hp.ProjectManager is null then LTRIM(RTRIM(ISNULL(u3.FirstName + '' '','''')  + ISNULL(u3.LastName,''''))) 
	  else LTRIM(RTRIM(ISNULL(u3.FirstName + '' '','''')  + ISNULL(u3.LastName,'''')))
	  end as [Line Project Manager] 
	,glc2.GLCompanyName as [Target GL Company Name]
	,e.EstimateName as [Estimate Name]
	,e.EstimateNumber as [Estimate Number]
	,e.EstimateNumber + '' - '' + e.EstimateName as [Estimate Full Name]
	,LTRIM(RTRIM(ISNULL(pcc.FirstName + '' '','''')  + ISNULL(pcc.LastName,''''))) AS [Primary Contact Name]
	,case when (c.ACHEnabled is null or c.ACHEnabled = 0) then ''NO'' else ''YES'' end as [ACH Enabled]	
	,(select ISNULL(Sum(Amount), 0) + ISNULL(sum(DiscAmount), 0) from tPaymentDetail (nolock) Where VoucherKey = v.VoucherKey and Prepay = 0) as  [Paid in Cash]
	,(select ISNULL(Sum(Amount), 0) + ISNULL(sum(DiscAmount), 0) from tVoucherCC (nolock) Where VoucherKey = v.VoucherKey) as [Paid in Credit]
	,lp.ProjectNumber AS [Line Project Number]
	,case when oa.OpenAmount = 0 then dp.PaymentDate else null end as [Date Paid]
	,lp.ProjectName AS [Line Project Name]
	,lp.ProjectNumber + '' - '' + lp.ProjectName AS [Line Project Full Name]
	,mp2.PlanID  as [Media Plan ID]
	,mp2.PlanName as [Media Plan Name]
	,lp.ProjectKey as LineProjectKey
	,CASE WHEN (SELECT COUNT(*) 
                  FROM tVoucherDetail vd (nolock)
                 WHERE vd.VoucherKey = v.VoucherKey 
                   AND v.Status = 4 
                   AND vd.DatePaidByClient IS NOT NULL
                ) > 0 
          THEN ''YES'' 
          ELSE ''NO'' 
     END AS [Paid By Client]
	,case when (v.VoucherType  is null or v.VoucherType  = 0) then ''NO'' else ''YES'' end as [Overhead]
	,ISNULL(AttachmentCount,0) as [Attachment Count]
	,case
		when vd.TransferToKey is null and v.Status < 4 and isnull(vd.OnHold,0) = 0 then ''Unapproved'' 
		--when pt.TransferToKey is null and pt.UIDTransferToKey is null and pt.Status = 4 and pt.WriteOff = 1 then ''Write Off'' 
		when vd.WriteOff = 1 then ''Write Offs'' 
		when vd.InvoiceLineKey > 0 then ''Invoiced''
		when vd.TransferToKey is null and v.Status = 4 and vd.WriteOff = 0 and vd.InvoiceLineKey is null and isnull(vd.OnHold,0) = 0 then ''Unbilled''
		when vd.TransferToKey is null and v.Status = 4 and vd.WriteOff = 0 and vd.InvoiceLineKey = 0 and isnull(vd.OnHold,0) = 0 then ''Marked As Billed''
		--when pt.TransferToKey is null and pt.UIDTransferToKey is null and isnull(pt.OnHold,0) = 1 then ''On Hold''
		when isnull(vd.OnHold,0) = 1 then ''On Hold''
		when vd.TransferOutDate is not null and isnull(vd.AdjustmentType,0) = 0 then ''Transferred''
		when vd.TransferOutDate is not null and vd.AdjustmentType > 0 then ''Adjusted''
	end as [Transaction Status]
From
	tVoucher v (nolock)
	Inner Join tVoucherDetail vd (nolock) on v.VoucherKey = vd.VoucherKey
	Left Outer Join tCompany c (nolock) on v.VendorKey = c.CompanyKey
	Left Outer Join tCompanyType  ct (nolock) on c.CompanyTypeKey = ct.CompanyTypeKey
	Left Outer Join tUser u (nolock) on v.ApprovedByKey = u.UserKey
	Left Outer Join tUser cbk (nolock) on v.CreatedByKey = cbk.UserKey
	Left Outer Join tProject hp (nolock) on v.ProjectKey = hp.ProjectKey
	left outer join tProject lp (nolock) on vd.ProjectKey = lp.ProjectKey
	Left Outer Join tUser u2 (nolock) on hp.AccountManager = u2.UserKey
	Left Outer Join tUser u3 (nolock) on hp.ProjectManager = u3.UserKey
	Left Outer Join tProjectType pt (nolock) on pt.ProjectTypeKey = lp.ProjectTypeKey
	Left Outer Join tClientDivision div (nolock) on div.ClientDivisionKey = hp.ClientDivisionKey
	Left Outer Join tClientProduct pro (nolock) on pro.ClientProductKey = hp.ClientProductKey
	Left Outer Join tTask t (nolock) on vd.TaskKey = t.TaskKey
	Left Outer Join tItem it (nolock) on vd.ItemKey = it.ItemKey
	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 tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey 
	Left outer join tEstimateTaskExpenseOrder (nolock) eteo on pod.PurchaseOrderDetailKey = eteo.PurchaseOrderDetailKey
	Left outer join tEstimateTaskExpense ete (nolock) on eteo.EstimateTaskExpenseKey = ete.EstimateTaskExpenseKey
	Left outer join tEstimate e (nolock) on ete.EstimateKey = e.EstimateKey
	Left Outer Join tCompany cClient (nolock) on hp.ClientKey = cClient.CompanyKey
	Left Outer Join tCompany meClient (nolock) on me.ClientKey = meClient.CompanyKey
	Left Outer Join tCompany lClient (nolock) on vd.ClientKey = lClient.CompanyKey
	Left Outer Join tInvoiceLine il (nolock) on vd.InvoiceLineKey = il.InvoiceLineKey
	Left Outer Join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
	Left Outer Join tCampaign cp (nolock) on hp.CampaignKey = cp.CampaignKey
	Left Outer Join tCampaign lc (nolock) on lc.CampaignKey = lp.CampaignKey
	Left Outer Join tGLAccount gl (nolock) on v.APAccountKey = gl.GLAccountKey
	Left Outer Join tGLAccount gl2 (nolock) on vd.ExpenseAccountKey = gl2.GLAccountKey
	Left Outer Join tClass cl (nolock) on vd.ClassKey = cl.ClassKey
	Left Outer Join tGLCompany glc (nolock) on v.GLCompanyKey = glc.GLCompanyKey
	Left Outer Join tGLCompany glcT (nolock) on vd.TargetGLCompanyKey = glcT.GLCompanyKey
	Left Outer Join tOffice o (nolock) on vd.OfficeKey = o.OfficeKey
	Left Outer Join tDepartment d (nolock) on vd.DepartmentKey = d.DepartmentKey
	Left Outer Join tDepartment id (nolock) on it.DepartmentKey = id.DepartmentKey 
	Left Outer Join tWIPPosting wpi (nolock) on vd.WIPPostingInKey = wpi.WIPPostingKey
	Left Outer Join tWIPPosting wpo (nolock) on vd.WIPPostingOutKey = wpo.WIPPostingKey
	LEFT OUTER JOIN tSalesTax st1 (nolock) on v.SalesTaxKey = st1.SalesTaxKey
	LEFT OUTER JOIN tSalesTax st2 (nolock) on v.SalesTax2Key = st2.SalesTaxKey
	Left Outer Join tLayoutBilling lb (nolock) on hp.LayoutKey = lb.LayoutKey and lb.Entity = ''tItem'' and lb.EntityKey = vd.ItemKey
	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 = hp.ProjectKey
	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 = hp.ProjectKey
	Left Outer Join tCompany pc (nolock) on c.ParentCompanyKey = pc.CompanyKey
	Left Outer Join tUser cc (nolock) on hp.BillingContact = cc.UserKey
	Left Outer Join tUser pb (nolock) on v.BoughtByKey = pb.UserKey
	Left Outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
	LEFT OUTER JOIN tAddress ap (NOLOCK) ON ISNULL(v.PaymentAddressKey, c.PaymentAddressKey) = ap.AddressKey
	left outer join tGLCompany glc2 (nolock) on vd.TargetGLCompanyKey = glc2.GLCompanyKey
	left outer join tUser pcc (nolock) on c.PrimaryContact = pcc.UserKey	
	Left Outer Join tClientDivision ldiv (nolock) on ldiv.ClientDivisionKey = lp.ClientDivisionKey
	left outer join (Select EntityKey, count(*) as AttachmentCount from tAttachment (nolock) where AssociatedEntity = ''tVoucher'' group by EntityKey) att on att.EntityKey = v.VoucherKey

	-- derived tables to calculate the [Date Paid] field 
	left outer join	(
		SELECT
			v.VoucherKey,			
			ISNULL(v.VoucherTotal, 0) - (ISNULL(pd.PaymentAmount, 0) + ISNULL(vc.CreditAmount, 0) + ISNULL(vcc.CCAmount, 0) - ISNULL(ca.CreditedAmount, 0)) AS OpenAmount
		FROM
			tVoucher v (nolock)
			LEFT JOIN (
				SELECT ISNULL(SUM(Amount), 0) + ISNULL(SUM(DiscAmount), 0) AS PaymentAmount, VoucherKey
				FROM
					tPaymentDetail pd (nolock)
				GROUP BY pd.VoucherKey
			) pd ON v.VoucherKey = pd.VoucherKey
			LEFT JOIN (
				SELECT SUM(Amount) AS CreditAmount, vc.VoucherKey
				FROM
					tVoucherCredit vc (nolock)
				GROUP BY vc.VoucherKey
			) vc ON v.VoucherKey = vc.VoucherKey
			LEFT JOIN (
				SELECT SUM(Amount) AS CCAmount, vcc.VoucherKey
				FROM
					tVoucherCC vcc (nolock)
				GROUP BY vcc.VoucherKey
			) vcc ON v.VoucherKey = vcc.VoucherKey
			LEFT JOIN (
				SELECT SUM(Amount) AS CreditedAmount, CreditVoucherKey
				FROM
					tVoucherCredit ca (nolock)
				GROUP BY ca.CreditVoucherKey
			) ca ON v.VoucherKey = ca.CreditVoucherKey
		) oa ON oa.VoucherKey = v.VoucherKey
	left outer join (
		SELECT MAX(PaymentDate) AS PaymentDate, VoucherKey
		FROM (
			SELECT PaymentDate, VoucherKey
			FROM (
					SELECT p.PaymentDate AS PaymentDate, pd.VoucherKey AS VoucherKey
					FROM
						tPaymentDetail pd (nolock)
						INNER JOIN tPayment p (nolock) ON pd.PaymentKey = p.PaymentKey
					GROUP BY pd.VoucherKey, p.PaymentDate

					UNION

					SELECT v.InvoiceDate AS PaymentDate, vc.VoucherKey
					FROM
						tVoucherCredit vc (nolock)
						INNER JOIN tVoucher v (nolock) ON vc.VoucherKey = v.VoucherKey
					GROUP BY vc.VoucherKey, v.InvoiceDate

					UNION

					SELECT v.InvoiceDate AS PaymentDate, vcc.VoucherKey
					FROM
						tVoucherCC vcc (nolock)
						INNER JOIN tVoucher v (nolock) ON vcc.VoucherCCKey = v.VoucherKey
					GROUP BY vcc.VoucherKey, v.InvoiceDate

					UNION

					SELECT v.InvoiceDate AS PaymentDate, CreditVoucherKey
					FROM
						tVoucherCredit ca (nolock)
						INNER JOIN tVoucher v (nolock) ON ca.CreditVoucherKey = v.VoucherKey
					GROUP BY ca.CreditVoucherKey, v.InvoiceDate
			) x1
		) x2
		GROUP BY x2.VoucherKey
	) dp on dp.VoucherKey = v.VoucherKey
	left outer join 
				 (SELECT mp.PlanID, mp.PlanName, pod.PurchaseOrderKey
				  FROM
					  tPurchaseOrderDetail pod
					  INNER JOIN tMediaPlanDetail mpd (nolock) on mpd.PurchaseOrderDetailKey =  pod.PurchaseOrderDetailKey
					  INNER JOIN tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
				  	  INNER JOIN tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey						
				  GROUP BY mp.PlanID, mp.PlanName, pod.PurchaseOrderKey) AS mp2 on mp2.PurchaseOrderKey = pod.PurchaseOrderKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectGetBasic]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectGetBasic]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptProjectGetBasic]
 @ProjectKey int
 ,@GetLockCompany int = 1

AS --Encrypt

/*
|| When     Who Rel     What
|| 03/01/07 RTC 8.4.0.3 Added TimeActive flag from Project Status table (#8362)
|| 10/19/07 BSH 8.5     Company & Office are locked once a PO is created. 
|| 11/1/07  CRG 8.5     Added ProjectBillingStatus
|| 01/20/10 GHL 10.517  (72908) Server running slow. sptProjectGetBasic @ProjectKey = 0 in my SQL trace
||                       Added check of ProjectKey before looking up in trans
|| 08/27/10 GHL 10.534  Added GLCompanyID, ClassName for flex lookups
|| 12/07/10 GHL 10.538  Added contact name + LayoutName to default on flex client invoice
|| 09/12/12 GHL 10.560  Added Billing Group Code for HMI request
|| 12/05/13 GHL 10.575  Added BillAt info from client for PO Flex screen
|| 06/04/15 GHL 10.593  Added ProjectTypeName for WJAPP lookup + added param to prevent queries in tTime, etc...
|| 06/19/15 GAR 10.593  Added fields to use in the new Platinum project settings screen.
|| 09/28/15 GHL 10.596  Since project templates do not have a project status, change to left join with tProjectStatus
|| 03/02/16 MCM 10.601	Adding Fields for the API call
|| 03/11/16 MCM 10.602  Removed api fields since we created a seperate stored proc just for the api 
|| 05/03/16 GHL 10.603  Added isnull around first/last names
|| 01/12/17 GAR 10.612  (327695) Added key people for editing in project setup.
|| 06/13/17 MCM 10.617  (347862) Added LockLaborRate and LockMarkupFrom from the Company
|| 07/07/17 GHL 10.617  (353563) Added client full name
|| 07/28/17 WDF 10.618  (356247) Added ''TemplateIsActive'' for ''TemplateActive'' since VB function ''getASObjectFromDataRow'' does not return fields with NULL values
|| 10/18/17 WDF 10.621  (368040) Added ''KeyPeople'' labels
|| 03/02/18 WDF 18.4.0  (387140) Added ''TemplateGLCompanyKey'' and ''TemplateGLCompanyNames''
|| 05/18/18 WDF 18.6.0  (401167) Set ''TemplateGLCompanyKey'' and ''TemplateGLCompanyNames'' to '''' if NUll
|| 08/01/18 GHL 18.8.0  Added HasEstimates to use on project schedule edit2 for retainer projects (need menu to view estimates) 
|| 09/25/18 GWG 18.9.1  Removed code which should have been in spProjectLoadProject which does the full load. this is supposed to be a lighter query for basic project info
|| 10/15/18 GHL 18.9.1  Put back estimate counts for demos at the conference
|| 08/29/19 GAR 19.0.9  (476961) Added project closed for use in estimates listing to disable new estimate
|| 11/12/19 RLS 19.1.2  (488027) Added CompanyName (related to 464118)
|| 12/12/19 MCM 19.2.0  (492247) Adding Expense Active so can hide the ability to add miscCost if shouldn''t be able to
|| 01/31/20 GHL 20.030  (497071) Added ExpensesNonBillable flag to use instead on NonBillable because expenses on opp projects
||                       should be billable even if NonBillable = 1  
|| 02/13/20 MFT 20.020  (455922) Added table alias to BillingMethod; duplicate name now in tCampaign
|| 04/17/20 GAR 19.050  (473704) Added Project Manager Name
|| 04/06/22 GAR 22.040  (593151) Added SlackChannelID for determining Slack channel
|| 03/28/23 MFT 23.040  (636032) Removed the TemplateIsActive field which was only used in one place and was confusing
|| 10/14/25 MCM 25.11x  (711735) Added AvalaraTaxCode
|| 03/11/26 CRG 26.04.19 (721964) Added fields for automation
*/

Declare @HasApprovedEstimates int
Declare @HasEstimates int
Declare @MaxEstimateKey int
Select @HasApprovedEstimates = 0, @HasEstimates = 0, @MaxEstimateKey = 0

Select @HasApprovedEstimates =  COUNT(*) FROM tEstimate (NOLOCK) 
WHERE ((isnull(ExternalApprover, 0) > 0 and  ExternalStatus = 4) 
Or (isnull(ExternalApprover, 0) = 0 
and  InternalStatus = 4)) 
AND ProjectKey = @ProjectKey
	
Select @HasEstimates =  COUNT(*) FROM tEstimate (NOLOCK) 
WHERE ProjectKey = @ProjectKey

Select @MaxEstimateKey =  MAX(EstimateKey) FROM tEstimate (NOLOCK) -- we will go directly to the estimate if the count is 1 
WHERE ProjectKey = @ProjectKey

Select @HasApprovedEstimates = isnull(@HasApprovedEstimates, 0)
	, @HasEstimates = isnull(@HasEstimates, 0)
	, @MaxEstimateKey = isnull(@MaxEstimateKey, 0)

  SELECT pr.*
     ,@HasApprovedEstimates as HasApprovedEstimates
	 ,@HasEstimates as HasEstimates
	 ,@MaxEstimateKey as MaxEstimateKey

     ,ISNULL(cl.CompanyName,'''') as ClientName
     ,isnull(CustomerID,'''') as CustomerID
	 ,ISNULL(cl.CompanyName, ''No Client'') AS CompanyName
	 ,isnull(cl.CustomerID + '' - '', '''') + isnull(cl.CompanyName, '''') as ClientFullName
     ,cl.ItemMarkup as ClientItemMarkup
     ,cl.IOCommission as ClientIOCommission
     ,cl.BCCommission as ClientBCCommission
	 ,cl.IOBillAt as ClientIOBillAt
	 ,cl.BCBillAt as ClientBCBillAt
	 ,ps.ProjectStatus
     ,ps.Locked as StatusLocked
     ,ps.TimeActive
	 ,ps.ExpenseActive
     ,r.RequestID
	 ,ca.CampaignID
	 ,ca.CampaignName
	 ,isnull(am.FirstName + '' '', '''') + isnull(am.LastName, '''') as AccountManagerName
	 ,am.FirstName AS AMFirstName
	 ,isnull(lockedby.FirstName + '' '', '''') + isnull(lockedby.LastName, '''') as ScheduleLockedByName
	 ,isnull(bcu.FirstName + '' '', '''') + isnull(bcu.LastName, '''') as BillingContactName
	 ,glc.GLCompanyID
	 ,glc.GLCompanyName
	 ,o.OfficeID
	 ,o.OfficeName
     ,c.ClassID
	 ,c.ClassName
     ,isnull(pbs.ProjectBillingStatus, '''') as ProjectBillingStatus
	 ,l.LayoutName
	 ,bg.BillingGroupCode as BillingGroup -- could not return bg.BillingGroupCode because of pr.BillingGroupCode (needed for conversion) 
	 ,bg.[Description] as BillingGroupName
	 ,pt.ProjectTypeName
	 ,le.[Subject] as LeadName
	 ,cas.SegmentName
	 ,cd.DivisionName 
	 ,cp.ProductName
	 ,t.TeamName
	 ,CASE 
			WHEN ISNULL(ScheduleDirection,0) = 1 THEN ''From Project Start'' 
			WHEN ISNULL(ScheduleDirection,0) = 2 THEN ''From Project Completion'' 
			ELSE ''From Project Start''
		END AS ScheduleDirectionName	
	,CASE 
			WHEN ISNULL(GLCompanySource,0) = 0 THEN ''Project'' 
			WHEN ISNULL(GLCompanySource,0) = 1 THEN ''Person'' 
			ELSE ''Project''
		END AS GLCompanySourceName	
	,cur.[Description] AS CurrencyName
	,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 BillingMethodName
	,ret.Title AS RetainerName
	,isnull(bm.FirstName + '' '', '''') + isnull(bm.LastName, '''') as BillingManagerName
	,bm.FirstName AS BMFirstName
	,CASE 
			WHEN ISNULL(pr.GetRateFrom,0) = 1 THEN ''Client'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 2 THEN ''Project'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 3 THEN ''Project User'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 4 THEN ''Service'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 5 THEN ''Service Rate Sheet'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 6 THEN ''Task'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 9 THEN ''Billing Title'' 
			WHEN ISNULL(pr.GetRateFrom,0) = 10 THEN ''Billing Title Rate Sheet'' 
			ELSE ''Client''
		END AS GetRateFromName
	,CASE 
			WHEN ISNULL(pr.GetMarkupFrom,0) = 1 THEN ''Client'' 
			WHEN ISNULL(pr.GetMarkupFrom,0) = 2 THEN ''Project'' 
			WHEN ISNULL(pr.GetMarkupFrom,0) = 3 THEN ''Item'' 
			WHEN ISNULL(pr.GetMarkupFrom,0) = 4 THEN ''Item Rate Sheet'' 
			WHEN ISNULL(pr.GetMarkupFrom,0) = 5 THEN ''Task'' 
			ELSE ''Client''
		END AS GetMarkupFromName
	,trs.RateSheetName AS TitleRateSheetName
	,tms.RateSheetName
	,irs.RateSheetName AS ItemRateSheetName
	,CASE 
			WHEN ISNULL(pr.FlightInterval,0) = 1 THEN ''Daily'' 
			WHEN ISNULL(pr.FlightInterval,0) = 2 THEN ''Weekly'' 
			WHEN ISNULL(pr.FlightInterval,0) = 3 THEN ''Summary'' 
			ELSE ''Daily''
		END AS FlightIntervalName
	,isnull(k1.FirstName + '' '', '''') + isnull(k1.LastName, '''') as KeyPeople1Name
	,isnull(k2.FirstName + '' '', '''') + isnull(k2.LastName, '''') as KeyPeople2Name
	,isnull(k3.FirstName + '' '', '''') + isnull(k3.LastName, '''') as KeyPeople3Name
	,isnull(k4.FirstName + '' '', '''') + isnull(k4.LastName, '''') as KeyPeople4Name
	,isnull(k5.FirstName + '' '', '''') + isnull(k5.LastName, '''') as KeyPeople5Name
	,isnull(k6.FirstName + '' '', '''') + isnull(k6.LastName, '''') as KeyPeople6Name
	,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser1'' and CompanyKey = pr.CompanyKey) as KeyPeople1Label
	,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser2'' and CompanyKey = pr.CompanyKey) as KeyPeople2Label
	,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser3'' and CompanyKey = pr.CompanyKey) as KeyPeople3Label
	,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser4'' and CompanyKey = pr.CompanyKey) as KeyPeople4Label
	,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser5'' and CompanyKey = pr.CompanyKey) as KeyPeople5Label
	,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser6'' and CompanyKey = pr.CompanyKey) as KeyPeople6Label
	,cl.LockLaborRate
	,cl.LockMarkupFrom
	,pr.Closed
	,case when isnull(pr.Opportunity,0) = 1 then 0
	else isnull(pr.NonBillable, 0) 
	end as ExpensesNonBillable
	,isnull(pm.FirstName + '' '', '''') + isnull(pm.LastName, '''') as ProjectManagerName
	,pm.FirstName AS PMFirstName
	,pr.SlackChannelID
	,atc.AvalaraTaxCode
    FROM tProject pr (nolock)
    left outer join tProjectStatus ps (nolock) on pr.ProjectStatusKey = ps.ProjectStatusKey
    left outer join tCompany cl (nolock) on pr.ClientKey = cl.CompanyKey
    left outer join tProjectBillingStatus pbs (nolock) on pr.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
    left outer join tClass c (nolock) on pr.ClassKey = c.ClassKey
    left outer join tOffice o (nolock) on pr.OfficeKey = o.OfficeKey
    left outer join tGLCompany glc (nolock) on pr.GLCompanyKey = glc.GLCompanyKey
    left outer join tUser lockedby (nolock) on pr.ScheduleLockedByKey = lockedby.UserKey
    left outer join tUser am (nolock) on pr.AccountManager = am.UserKey
    left outer join tCampaign ca (nolock) on pr.CampaignKey = ca.CampaignKey
    left outer join tRequest r (nolock) on pr.RequestKey = r.RequestKey
    left outer join tUser bcu (nolock) on pr.BillingContact = bcu.UserKey
	left outer join tLayout l (nolock) on pr.LayoutKey = l.LayoutKey
	left outer join tBillingGroup bg (nolock) on pr.BillingGroupKey = bg.BillingGroupKey  
	left outer join tProjectType pt (nolock) on pr.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tLead le (nolock) on pr.LeadKey = le.LeadKey
	left outer join tCampaignSegment cas (nolock) on pr.CampaignSegmentKey = cas.CampaignSegmentKey
	left outer join tClientDivision cd (nolock) on pr.ClientDivisionKey = cd.ClientDivisionKey
	left outer join tClientProduct cp (nolock) on pr.ClientProductKey = cp.ClientProductKey
	left outer join tTeam t (nolock) on pr.TeamKey = t.TeamKey
	left outer join tCurrency cur (nolock) on pr.CurrencyID = cur.CurrencyID
	left outer join tRetainer ret (nolock) on pr.RetainerKey = ret.RetainerKey
	left outer join tUser bm (nolock) on pr.BillingManagerKey = bm.UserKey
	left outer join tTitleRateSheet trs (nolock) on pr.TitleRateSheetKey = trs.TitleRateSheetKey
	left outer join tTimeRateSheet tms (nolock) on pr.TimeRateSheetKey = tms.TimeRateSheetKey
	left outer join tItemRateSheet irs (nolock) on pr.ItemRateSheetKey = irs.ItemRateSheetKey
	left outer join tAvalaraTaxCode atc (nolock) on pr.AvalaraTaxCodeKey = atc.AvalaraTaxCodeKey
	left outer join tUser k1 (nolock) on pr.KeyPeople1 = k1.UserKey
	left outer join tUser k2 (nolock) on pr.KeyPeople2 = k2.UserKey
	left outer join tUser k3 (nolock) on pr.KeyPeople3 = k3.UserKey
	left outer join tUser k4 (nolock) on pr.KeyPeople4 = k4.UserKey
	left outer join tUser k5 (nolock) on pr.KeyPeople5 = k5.UserKey
	left outer join tUser k6 (nolock) on pr.KeyPeople6 = k6.UserKey
	left outer join tUser pm (nolock) on pr.ProjectManager = pm.UserKey

  WHERE
   pr.ProjectKey = @ProjectKey
  
 RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spFixedFeesCampaignSegmentList]'
GO
IF OBJECT_ID(N'[dbo].[spFixedFeesCampaignSegmentList]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spFixedFeesCampaignSegmentList]
	(
	@CampaignKey int
	,@EstimateKey int = 0 -- 0 = All
	)
AS --Encrypt

  /*
  || When     Who Rel		What
  || 05/10/10 GHL 10.522	Creation for campaign FF billing
  || 02/16/12 GHL 10.553	(134167) calc labor as sum(round(hours * rate))
  || 01/14/13 GHL 10.564	(163923) Added contributions thru tEstimateProject
  || 09/16/20 GHL 20.100	When calculating amount billed, exclude adv bill
  || 04/02/26 GAR 26.05.17	(722819) Added TotalGrossUnbilled
  */
  
	SET NOCOUNT ON

	DECLARE @kNoItemDisplayOrder INT SELECT @kNoItemDisplayOrder = 9999 -- At bottom, -1 At top

	if @EstimateKey = 0
		
		select  ''tCampaignSegment''				as Entity
		        ,cs.CampaignSegmentKey          as EntityKey
		        ,NULL                           as	EntityID
		        ,cs.SegmentName					as	EntityName
                ,cs.SegmentDescription			as	EntityDescription
                ,cs.DisplayOrder                as  DisplayOrder
                
                -- Amounts of ALL Estimates are already on tCampaignSegment
                ,isnull(cs.EstHours, 0) + isnull(cs.ApprovedCOHours, 0)			as EstHours
                ,isnull(cs.EstLabor, 0) + isnull(cs.ApprovedCOLabor, 0)			as EstLabor 
                ,isnull(cs.EstExpenses, 0) + isnull(cs.ApprovedCOExpense, 0)	as EstExpenses 
                 
                -- Actuals ...not by estimates 
                ,ISNULL((select sum(roll.Hours) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0) 
					As ActHours
		
				,ISNULL((select sum(roll.LaborGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0) 			
					As ActLabor

				 ,ISNULL((select sum(roll.ExpReceiptGross + roll.MiscCostGross + roll.VoucherGross + roll.OpenOrderGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0) 			
					As ActExpenses
			 
				 -- Billed	
				 ,ISNULL((
				  select sum(il.TotalAmount) 
				  from tInvoiceLine il (nolock) 
				      inner join tInvoice i (nolock) on i.InvoiceKey = il.InvoiceKey
				  where i.CampaignKey = @CampaignKey
				  and   il.CampaignSegmentKey = cs.CampaignSegmentKey   
				  and   i.AdvanceBill = 0
				  ), 0) 			
					As Billed

				 -- Total Gross Unbilled
				 ,ISNULL((select sum(roll.LaborUnbilled + roll.MiscCostUnbilled + roll.ExpReceiptUnbilled + roll.VoucherUnbilled + roll.OpenOrderUnbilled) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
				 ), 0) 			
					As TotalGrossUnbilled
				
			     ,0 As [Percent]
			     ,0 As BillAmt
		         ,0 As Selected 
				 ,2 As LineType -- detail

		from    tCampaignSegment cs (nolock)
		where   cs.CampaignKey = @CampaignKey
        
		/*
		UNION ALL
		
				select  ''tCampaignSegment''				as Entity
		        ,0                                      as EntityKey
		        ,''[No Segment]''                         as EntityID
		        ,''[No Segment]''					        as EntityName
                ,''[No Segment]''			                as EntityDescription
                ,@kNoItemDisplayOrder                   as DisplayOrder
                
                -- ALL estimates should have a segment, so return 0 here
                ,0                                      as EstHours
                ,0                                      as EstLabor 
                ,0                                      as EstExpenses 
                 
                -- Actuals
                ,ISNULL((select sum(roll.Hours) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = 0
					), 0) 
					As ActHours
		
				,ISNULL((select sum(roll.LaborGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = 0
					), 0) 			
					As ActLabor

				 ,ISNULL((select sum(roll.ExpReceiptGross + roll.MiscCostGross + roll.VoucherGross + roll.OpenOrderGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = 0
					), 0) 			
					As ActExpenses
			 
				 -- Billed	
				 ,ISNULL((
				  select sum(il.TotalAmount) 
				  from tInvoiceLine il (nolock) 
				      inner join tInvoice i (nolock) on i.InvoiceKey = il.InvoiceKey
				  where i.CampaignKey = @CampaignKey
				  and   isnull(il.CampaignSegmentKey, 0) = 0   
				  ), 0) 			
					As Billed
					 
			     ,0 As [Percent]
			     ,0 As BillAmt
		         ,0 As Selected 
		*/

		order by DisplayOrder
	
	else
	
		select  ''tCampaignSegment''				as Entity
		        ,cs.CampaignSegmentKey          as EntityKey
		        ,NULL                           as	EntityID
		        ,cs.SegmentName					as	EntityName
                ,cs.SegmentDescription			as	EntityDescription
                ,cs.DisplayOrder                as  DisplayOrder
                
                -- Amounts on Estimates 
                , ISNULL((
					Select Sum(etl.Hours) 
					from tEstimateTaskLabor etl  (nolock) 
						inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(etl.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0)
				   + ISNULL((
					Select Sum(etl.Hours) 
					from tEstimateTaskLabor etl  (nolock) 
						inner join tEstimateProject ep (nolock) on etl.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0)
				  + ISNULL((
					Select Sum(et.Hours) 
					from tEstimateTask et  (nolock) 
						inner join tEstimateProject ep (nolock) on et.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0)
					As EstHours
                
				, 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.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(etl.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0)
				+ ISNULL((
					Select Sum(Round(ISNULL(etl.Hours, 0) * ISNULL(etl.Rate, 0),2))
					from tEstimateTaskLabor etl  (nolock) 
						inner join tEstimateProject ep (nolock) on etl.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0)
				+ ISNULL((
					Select Sum(Round(ISNULL(et.Hours, 0) * ISNULL(et.Rate, 0),2))
					from tEstimateTask et  (nolock) 
						inner join tEstimateProject ep (nolock) on et.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0)
				As EstLabor              
                
                ,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.CampaignKey = @CampaignKey
				and e.EstimateKey = @EstimateKey
				and e.Approved = 1
				and isnull(ete.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
				), 0)
				+ ISNULL((
					Select Sum(case 
							when pe.ApprovedQty = 1 Then ete.BillableCost
							when pe.ApprovedQty = 2 Then ete.BillableCost2
							when pe.ApprovedQty = 3 Then ete.BillableCost3
							when pe.ApprovedQty = 4 Then ete.BillableCost4
							when pe.ApprovedQty = 5 Then ete.BillableCost5
							when pe.ApprovedQty = 6 Then ete.BillableCost6											 
							end ) 
					from tEstimateTaskExpense ete  (nolock) 
						inner join tEstimateProject ep (nolock) on ete.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join tEstimate pe (nolock) on ep.ProjectEstimateKey = pe.EstimateKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and pe.EstType > 1
					and isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
				), 0)
				+ ISNULL((
					Select Sum(et.EstExpenses) 
					from tEstimateTask et  (nolock) 
						inner join tEstimateProject ep (nolock) on et.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join tEstimate pe (nolock) on ep.ProjectEstimateKey = pe.EstimateKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
				), 0)
				As EstExpenses
                 
                -- Actuals ...not by estimates 
                ,ISNULL((select sum(roll.Hours) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0) 
					As ActHours
		
				,ISNULL((select sum(roll.LaborGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0) 			
					As ActLabor

				 ,ISNULL((select sum(roll.ExpReceiptGross + roll.MiscCostGross + roll.VoucherGross + roll.OpenOrderGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
					), 0) 			
					As ActExpenses
			 
				 -- Billed	
				 ,ISNULL((
				  select sum(il.TotalAmount) 
				  from tInvoiceLine il (nolock) 
				      inner join tInvoice i (nolock) on i.InvoiceKey = il.InvoiceKey
				  where i.CampaignKey = @CampaignKey
				  and   il.CampaignSegmentKey = cs.CampaignSegmentKey 
				  and   il.EstimateKey = @EstimateKey
				  and   i.AdvanceBill = 0   
				  ), 0) 			
					As Billed

				 -- Total Gross Unbilled
				 ,ISNULL((select sum(roll.LaborUnbilled + roll.MiscCostUnbilled + roll.ExpReceiptUnbilled + roll.VoucherUnbilled + roll.OpenOrderUnbilled) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					and   isnull(p.CampaignSegmentKey, 0) = cs.CampaignSegmentKey
				 ), 0) 			
					As TotalGrossUnbilled

                 ,0 As [Percent]
			     ,0 As BillAmt
		         ,0 As Selected 
				 ,2 As LineType -- detail
					 
		from    tCampaignSegment cs (nolock)
		where   cs.CampaignKey = @CampaignKey
		
		/*
		UNION ALL
		
				select  ''tCampaignSegment''				as Entity
		        ,0                                      as EntityKey
		        ,''[No Segment]''                         as EntityID
		        ,''[No Segment]''					        as EntityName
                ,''[No Segment]''			                as EntityDescription
                ,@kNoItemDisplayOrder                   as DisplayOrder
                
                -- ALL estimates should have a segment, so return 0 here
                ,0                                      as EstHours
                ,0                                      as EstLabor 
                ,0                                      as EstExpenses 
                 
                -- Actuals
                ,ISNULL((select sum(roll.Hours) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignSegmentKey, 0) = 0
					), 0) 
					As ActHours
		
				,ISNULL((select sum(roll.LaborGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignSegmentKey, 0) = 0
					), 0) 			
					As ActLabor

				 ,ISNULL((select sum(roll.ExpReceiptGross + roll.MiscCostGross + roll.VoucherGross + roll.OpenOrderGross) 
					from tProjectRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignSegmentKey, 0) = 0
					), 0) 			
					As ActExpenses
			 
				 -- Billed	
				 ,ISNULL((
				  select sum(il.TotalAmount) 
				  from tInvoiceLine il (nolock) 
				      inner join tInvoice i (nolock) on i.InvoiceKey = il.InvoiceKey
				  where i.CampaignKey = @CampaignKey
				  and   isnull(il.CampaignSegmentKey, 0) = 0   
				  and   isnull(il.EstimateKey, 0) = @EstimateKey
				  ), 0) 			
					As Billed

			     ,0 As [Percent]
			     ,0 As BillAmt
		         ,0 As Selected 
		*/
					 		
		order by DisplayOrder

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

  /*
  || When     Who Rel		What
  || 05/10/10 GHL 10.522	Creation for campaign FF billing
  || 12/02/10 GHL 10.539	Changed signature of spBillingLinesGroupByBillingItem
  ||						for billing by project
  || 02/16/12 GHL 10.553	(134167) calc labor as sum(round(hours * rate))
  || 01/14/13 GHL 10.564	(163923) Added contributions thru tEstimateProject
  || 09/16/20 GHL 20.100	When calculating amount billed, exclude adv bill
  || 04/02/26 GAR 26.05.17	(722819) Added TotalGrossUnbilled
  */
  
	SET NOCOUNT ON
	
	create table #item (
		Entity varchar(50) null
		,EntityKey int null
		,EntityID varchar(250) null
		,EntityName varchar(500) null
		,EntityDescription text null
		
		,WorkTypeKey int null
		,WorkTypeID varchar(200) null
		,WorkTypeName varchar(250) null
		,WorkTypeDescription text null
		
		,DisplayOrder int null
		,Taxable int null
		,Taxable2 int null
		
		,EstHours decimal(24, 4) null
		,EstLabor money null
		,EstExpenses money null
		
		,ActHours decimal(24, 4) null
		,ActLabor money null
		,ActExpenses money null

		,Billed money null

		,RootEntity varchar(50) null
		,RootEntityKey int null

		,TotalGrossUnbilled money null

		)
	
	DECLARE @kNoItemDisplayOrder INT SELECT @kNoItemDisplayOrder = 9999 -- At bottom, -1 At top
	
	DECLARE @CompanyKey INT
	        ,@LayoutKey INT
	               
	SELECT @CompanyKey = CompanyKey
	       ,@LayoutKey = isnull(LayoutKey, 0)
	FROM   tCampaign (NOLOCK)
	WHERE  CampaignKey = @CampaignKey	
	
	insert #item(Entity, EntityKey, EntityID, EntityName, EntityDescription, WorkTypeKey)
	select ''tService'', 0, ''[No Service]'', ''[No Service]'', ''[No Service]'', 0
	insert #item(Entity, EntityKey, EntityID, EntityName, EntityDescription, WorkTypeKey)
	select ''tItem'', 0, ''[No Item]'', ''[No Item]'', ''[No Item]'', 0
	
	insert #item(Entity, EntityKey, EntityID, EntityName, EntityDescription
	, WorkTypeKey, Taxable, Taxable2)
	select ''tService'', ServiceKey, ServiceCode, isnull(InvoiceDescription, Description), null
	, isnull(WorkTypeKey, 0),isnull(Taxable, 0), isnull(Taxable2, 0)
	from   tService (nolock)
	where  CompanyKey = @CompanyKey
	
	insert #item(Entity, EntityKey, EntityID, EntityName, EntityDescription
	, WorkTypeKey, Taxable, Taxable2)
	select ''tItem'', ItemKey, ItemID, ItemName, StandardDescription
	, isnull(WorkTypeKey, 0),isnull(Taxable, 0), isnull(Taxable2, 0)
	from   tItem (nolock)
	where  CompanyKey = @CompanyKey
	
	-- Estimate data
	
	if @EstimateKey = 0
		update #item
		set    #item.EstHours = isnull((
						select sum(cebi.Qty + cebi.COQty) from tCampaignEstByItem cebi (nolock) 
						where cebi.CampaignKey = @CampaignKey
						and   cebi.Entity = ''tService'' 
						and   #item.Entity = ''tService'' 
						and   cebi.EntityKey = #item.EntityKey 
						), 0)
						
	          ,#item.EstLabor = isnull((
						select sum(cebi.Gross + cebi.COGross) from tCampaignEstByItem cebi (nolock) 
						where cebi.CampaignKey = @CampaignKey
						and   cebi.Entity = ''tService'' 
						and   #item.Entity = ''tService'' 
						and   cebi.EntityKey = #item.EntityKey 
						), 0)

	          ,#item.EstExpenses = isnull((
						select sum(cebi.Gross + cebi.COGross) from tCampaignEstByItem cebi (nolock) 
						where cebi.CampaignKey = @CampaignKey
						and   cebi.Entity = ''tItem'' 
						and   #item.Entity = ''tItem'' 
						and   cebi.EntityKey = #item.EntityKey 
						), 0)
		else
		begin
			-- there is an estimate
			update #item
			set    #item.EstHours = isnull((
						Select Sum(etl.Hours) 
						from tEstimateTaskLabor etl  (nolock) 
							inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
						Where e.CampaignKey = @CampaignKey
						and e.EstimateKey = @EstimateKey
						and e.Approved = 1
						and #item.Entity = ''tService''
						and isnull(etl.ServiceKey, 0) = #item.EntityKey
					),0)
					 + ISNULL((
					Select Sum(etl.Hours) 
					from tEstimateTaskLabor etl  (nolock) 
						inner join tEstimateProject ep (nolock) on etl.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and #item.Entity = ''tService''
					and isnull(etl.ServiceKey, 0) = #item.EntityKey
					), 0)
					 + ISNULL((
					Select Sum(et.Hours) 
					from tEstimateTask et  (nolock) 
						inner join tEstimateProject ep (nolock) on et.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and #item.Entity = ''tService''
					and #item.EntityKey = 0
					), 0)
				  ,#item.EstLabor = isnull((
						Select Sum(Round(etl.Hours * etl.Rate,2)) 
						from tEstimateTaskLabor etl  (nolock) 
							inner join vEstimateApproved e (nolock) on etl.EstimateKey = e.EstimateKey
						Where e.CampaignKey = @CampaignKey
						and e.EstimateKey = @EstimateKey
						and e.Approved = 1
						and #item.Entity = ''tService''
						and isnull(etl.ServiceKey, 0) = #item.EntityKey
					),0)
					+ ISNULL((
					Select Sum(Round(etl.Hours * etl.Rate,2)) 
					from tEstimateTaskLabor etl  (nolock) 
						inner join tEstimateProject ep (nolock) on etl.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and #item.Entity = ''tService''
					and isnull(etl.ServiceKey, 0) = #item.EntityKey
					), 0)
					 + ISNULL((
					Select Sum(Round(et.Hours * et.Rate,2))
					from tEstimateTask et  (nolock) 
						inner join tEstimateProject ep (nolock) on et.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and #item.Entity = ''tService''
					and #item.EntityKey = 0
					), 0)	
				  ,#item.EstExpenses = 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.CampaignKey = @CampaignKey
						and e.EstimateKey = @EstimateKey
						and e.Approved = 1
						and #item.Entity = ''tItem''
						and isnull(ete.ItemKey, 0) = #item.EntityKey
				), 0)
				+ ISNULL((
					Select Sum(case 
							when pe.ApprovedQty = 1 Then ete.BillableCost
							when pe.ApprovedQty = 2 Then ete.BillableCost2
							when pe.ApprovedQty = 3 Then ete.BillableCost3
							when pe.ApprovedQty = 4 Then ete.BillableCost4
							when pe.ApprovedQty = 5 Then ete.BillableCost5
							when pe.ApprovedQty = 6 Then ete.BillableCost6											 
							end ) 
					from tEstimateTaskExpense ete  (nolock) 
						inner join tEstimateProject ep (nolock) on ete.EstimateKey = ep.ProjectEstimateKey 
						inner join tEstimate pe (nolock) on ep.ProjectEstimateKey = pe.EstimateKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and pe.EstType > 1
					and #item.Entity = ''tItem''
					and isnull(ete.ItemKey, 0) = #item.EntityKey
				), 0)
				+ ISNULL((
					Select Sum(et.EstExpenses) 
					from tEstimateTask et  (nolock) 
						inner join tEstimateProject ep (nolock) on et.EstimateKey = ep.ProjectEstimateKey 
						inner join tProject p (nolock) on ep.ProjectKey = p.ProjectKey
						inner join tEstimate pe (nolock) on ep.ProjectEstimateKey = pe.EstimateKey
						inner join vEstimateApproved e (nolock) on ep.EstimateKey = e.EstimateKey
					Where e.CampaignKey = @CampaignKey
					and e.EstimateKey = @EstimateKey
					and e.Approved = 1
					and #item.Entity = ''tItem''
					and #item.EntityKey = 0
				), 0)	
		end
					
		-- Actuals			
		update #item
		set    #item.ActHours = ISNULL((select sum(roll.Hours) 
					from tProjectItemRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					And   roll.Entity = ''tService''
					And #item.Entity = ''tService''
					And isnull(roll.EntityKey, 0) = #item.EntityKey
					), 0) 
					
				,#item.ActLabor = ISNULL((select sum(roll.LaborGross) 
					from tProjectItemRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
						inner join tService s (nolock) on roll.EntityKey = s.ServiceKey
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					And   roll.Entity = ''tService''
					And #item.Entity = ''tService''
					And isnull(roll.EntityKey, 0) = #item.EntityKey
					), 0) 			

				 ,#item.ActExpenses = ISNULL((select sum(roll.ExpReceiptGross + roll.MiscCostGross + roll.VoucherGross + roll.OpenOrderGross) 
					from tProjectItemRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					And   roll.Entity = ''tItem''
					And #item.Entity = ''tItem''
					And isnull(roll.EntityKey, 0) = #item.EntityKey
					), 0) 	
					
				 ,#item.TotalGrossUnbilled = ISNULL((select sum(roll.LaborUnbilled + roll.MiscCostUnbilled + roll.ExpReceiptUnbilled + roll.VoucherUnbilled + roll.OpenOrderUnbilled) 
					from tProjectItemRollup roll (nolock)
						inner join tProject p (nolock) on roll.ProjectKey = p.ProjectKey 
					Where isnull(p.CampaignKey, 0) = @CampaignKey
					And isnull(roll.EntityKey, 0) = #item.EntityKey
					), 0) 	
					
				
	if @EstimateKey = 0
	begin
			update #item
			set    #item.Billed = 
			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) = #item.EntityKey
				AND   inv.AdvanceBill = 0
				), 0)
			where #item.Entity = ''tService''

			update #item
			set    #item.Billed = 
			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, ''tItem'') = ''tItem'' -- nulls with tInvoiceSummary go with expenses
				AND   ISNULL(isum.EntityKey, 0) = #item.EntityKey
				AND   inv.AdvanceBill = 0
				), 0)
			where #item.Entity = ''tItem''

	end
	else
	begin
			update #item
			set    #item.Billed = 
			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 inv.InvoiceKey = il.InvoiceKey
 				WHERE inv.CampaignKey = @CampaignKey
				AND   isum.Entity = ''tService''
				AND   il.EstimateKey = @EstimateKey 
				AND   ISNULL(isum.EntityKey, 0) = #item.EntityKey
				AND   inv.AdvanceBill = 0
				), 0)
			where #item.Entity = ''tService''

			update #item
			set    #item.Billed = 
			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 inv.InvoiceKey = il.InvoiceKey
 				WHERE inv.CampaignKey = @CampaignKey
				AND   isnull(isum.Entity, ''tItem'') = ''tItem'' -- nulls with tInvoiceSummary go with expenses
				AND   il.EstimateKey = @EstimateKey 
				AND   ISNULL(isum.EntityKey, 0) = #item.EntityKey
				AND   inv.AdvanceBill = 0
				), 0)
			WHERE #item.Entity = ''tItem''
	end
				

	delete #item 
	where  EstHours = 0 And EstLabor = 0 And EstExpenses = 0 
	    And ActHours = 0 And ActLabor = 0 And ActExpenses = 0
		And Billed = 0
		
	if @LayoutKey = 0
	begin
		-- no layout, rely on WT display order then Item Name
		
		update #item 
		set    #item.DisplayOrder = @kNoItemDisplayOrder
		      ,#item.WorkTypeID = ''[No Billing Item]''
			  ,#item.WorkTypeName = ''[No Billing Item]''
			  ,#item.WorkTypeDescription = ''[No Billing Item]''
				
		update #item
		set    #item.WorkTypeID = wt.WorkTypeID
			  ,#item.WorkTypeName = wt.WorkTypeName
			  ,#item.WorkTypeDescription = wt.Description
			  ,#item.DisplayOrder = isnull(wt.DisplayOrder, 0)
		from   tWorkType wt (nolock)
		where  #item.WorkTypeKey = wt.WorkTypeKey 

		-- Now update entity specific WorkTypeNames
		UPDATE	#item
		SET		#item.WorkTypeName = cust.Subject
				,#item.WorkTypeDescription = cust.Description
		FROM	tWorkTypeCustom cust (nolock)
		WHERE	#item.WorkTypeKey = cust.WorkTypeKey
		AND		cust.Entity = ''tCampaign''
		AND		cust.EntityKey = @CampaignKey

		-- the Display Order are null in tWorkType, so reorg by BI name
		declare @DisplayOrder int
		        ,@WorkTypeName varchar(250)
		        
		select @DisplayOrder = 1, @WorkTypeName = '''' 
		while (1=1)
		begin
			select @WorkTypeName = min(WorkTypeName)
			from   #item
			where  WorkTypeName is not null
			and    WorkTypeName > @WorkTypeName
			and    DisplayOrder = 0
			
			if @WorkTypeName is null
				break
				
			update #item
			set    #item.DisplayOrder = @DisplayOrder
			where  WorkTypeName = @WorkTypeName
				
			select @DisplayOrder = @DisplayOrder + 1
		end
	
		/*
		select * 
		      ,0 As BillAmt
		      ,0 As Selected 
		from   #item 
		order by DisplayOrder, WorkTypeName, EntityName
		*/

	end
	else
	begin
		-- the items have been reorganized on the layout 
		update #item
		set    #item.WorkTypeKey = 0
	          ,#item.DisplayOrder = @kNoItemDisplayOrder
		      ,#item.WorkTypeID = ''[No Billing Item]''
			  ,#item.WorkTypeName = ''[No Billing Item]''
			  ,#item.WorkTypeDescription = ''[No Billing Item]''
	           
	    update #item
		set    #item.WorkTypeKey = 0
		      ,#item.DisplayOrder = lb.LayoutOrder
		      ,#item.WorkTypeID = ''[No Billing Item]''
			  ,#item.WorkTypeName = ''[No Billing Item]''
			  ,#item.WorkTypeDescription = ''[No Billing Item]''
		from   tLayoutBilling lb (nolock)
		where  lb.LayoutKey = @LayoutKey
		and    #item.Entity = lb.Entity COLLATE DATABASE_DEFAULT
		and    #item.EntityKey = lb.EntityKey
		and    lb.ParentEntity = ''tProject''
		       
		-- get WT key only when parent entity is tWorkType	
		update #item
		set    #item.WorkTypeKey = lb.ParentEntityKey
		from   tLayoutBilling lb (nolock)
		where  lb.LayoutKey = @LayoutKey
		and    #item.Entity = lb.Entity COLLATE DATABASE_DEFAULT
		and    #item.EntityKey = lb.EntityKey     				
	    and    lb.ParentEntity = ''tWorkType''
	

		update #item
		set    #item.WorkTypeID = wt.WorkTypeID
			  ,#item.WorkTypeName = wt.WorkTypeName
			  ,#item.WorkTypeDescription = wt.Description
		from   tWorkType wt (nolock)
		where  #item.WorkTypeKey = wt.WorkTypeKey 
		
		-- Now update entity specific WorkTypeNames
		UPDATE	#item
		SET		#item.WorkTypeName = cust.Subject
			   ,#item.WorkTypeDescription = cust.Description
		FROM	tWorkTypeCustom cust (nolock)
		WHERE	#item.WorkTypeKey = cust.WorkTypeKey
		AND		cust.Entity = ''tCampaign''
		AND		cust.EntityKey = @CampaignKey

		-- but always get the Layout Order
		update #item
		set    #item.DisplayOrder = lb.LayoutOrder
		from   tLayoutBilling lb (nolock)
		where  lb.LayoutKey = @LayoutKey
		and    #item.Entity = lb.Entity COLLATE DATABASE_DEFAULT
		and    #item.EntityKey = lb.EntityKey     				
	
		/*
		select * 
		      ,0 As BillAmt
		      ,0 As Selected 
		from #item 
		order by DisplayOrder, WorkTypeName, EntityName
		*/
	end
			
	update #item
	set    RootEntity = ''tCampaign''
	      ,RootEntityKey = @CampaignKey
			
	-- Output
    create table #line(
		LineKey INT IDENTITY(1,1)
		,ParentLineKey int null
		,LineSubject varchar(500) null
		,LineDescription text null
		,Entity varchar(50) null
		,EntityKey int null
		,WorkTypeKey int null
		
		,DisplayOrder int null
		,NewDisplayOrder int null
		,InvoiceOrder int null
		,DisplayOption int null
		,LineType int null

		,RootEntity varchar(50) null
		,RootEntityKey int null
		)
		
	exec spBillingLinesGroupByBillingItem @CompanyKey, @LayoutKey, ''tCampaign'', @CampaignKey, ''tCampaign'', @CampaignKey

	select #line.LineKey
			,#line.ParentLineKey
			,#line.LineSubject 
			,#line.LineDescription 
			,#line.Entity 
			,#line.EntityKey 
			,#line.WorkTypeKey 
		
			,#line.DisplayOrder  As OldDisplayOrder  -- for the CMHD in Flex
			,#line.NewDisplayOrder As DisplayOrder
			,#line.InvoiceOrder 
			,#line.DisplayOption 
			,#line.LineType 
			,#line.LineType - 1 as LineLevel 

			,#line.RootEntity 
			,#line.RootEntityKey 

	       ,#line.LineSubject as EntityName

	       ,isnull(EstHours, 0) as EstHours
		   ,isnull(EstLabor, 0) as EstLabor 
		   ,isnull(EstExpenses, 0) as EstExpenses
		   ,0 as EstTotal
		   	
		   ,isnull(ActHours, 0) as ActHours
		   ,isnull(ActLabor, 0) as ActLabor
		   ,isnull(ActExpenses, 0) as ActExpenses 
		   ,0 as ActTotal

		    ,isnull(Billed, 0) as Billed

	        ,0 as [Percent]
			,0 as BillAmt
		    ,0 as Remaining
		    ,0 as Selected

			,TotalGrossUnbilled
	
	from   #line
	left outer join #item on #line.Entity = #item.Entity and #line.EntityKey = #item.EntityKey
	order by InvoiceOrder
													
	RETURN 1

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







ALTER View [dbo].[vListing_MediaTrafficIO]
AS

  /*
  || When     Who Rel   What
  || 09/25/06 RTC 8.35  Changed inner join to outer from PO to Project.  POs linking through media
  ||                    estimates were not shown.
  || 10/16/06 WES 8.356 Added Client Name and ID fields
  || 09/13/07 GHL 8.436 Fixed Client Name and ID fields
  || 10/10/07 CRG 8.5   Added Class, GLCompany, Office, and Department
  || 01/21/10 RLB 10517 (72879) Added POLine Custom fields
  || 12/12/11 RLB 10551 (119167) Added Line Comments
  || 04/25/12 GHL 10555 Added GLCompanyKey for map/restrict
  || 03/22/13 WDF 10566 (172559) Added Transferred Out
  || 01/20/14 GHL 10576 Added Order Description
  || 11/07/14 WDF 10586 (234091) Added Special and Traffic Instructions
  || 01/27/15 WDF 10588 (Abelson Taylor) Added Division and Product
  || 02/18/15 GHL 10588 (246235) Rolled back 243930. Greg, did you mean media worksheets instead of media estimates? 
  || 02/07/20 GHL 20.030 (500841) Added Materials Sent Date (was on vListing_InsertionOrder by mistake)
  || 09/02/20 RLB 20.100 (523772) making anything using user name common format
  || 01/26/23 AMP 23.03.19 (628305) Added Media Plan ID and Media Plan Name
  || 02/06/25 AMP 25.02.16 (688666) Added Order Type, Order Line Field
  || 02/02/26 RLB 26.03.15 (718217) Added Media Plan Full Name
  || 04/23/26 MCM 26.05.x  (725435) Added InteractiveAdUnitName as Ad Size
 */

Select
     po.PurchaseOrderKey
	,pod.PurchaseOrderDetailKey
    ,po.CompanyKey
    ,po.GLCompanyKey
    ,po.CustomFieldKey
	,pod.CustomFieldKey as POLineCustomFieldKey
	,po.POKind
    ,c.CompanyKey as VendorKey
    ,po.PurchaseOrderNumber AS [Order Number]
    ,c.VendorID AS [Vendor ID]
    ,c.CompanyName AS [Vendor Name]
    ,c.VendorID + '' - '' + c.CompanyName AS [Vendor Full Name]
    ,po.Contact AS [Vendor Contact]
    ,po.Address1 AS [Address 1]
    ,po.Address2 AS [Address 2]
    ,po.Address3 AS [Address 3]
    ,po.City AS [Address City]
    ,po.State AS [Address State]
    ,po.PostalCode AS [Address Postal Code]
    ,po.Country AS [Address Country]
    ,po.DateCreated AS [Date Created]
    ,po.PODate AS [Order Date]
    ,po.OrderedBy AS [Ordered By]
    ,po.Revision AS [Revision Number]
    ,po.ApprovedDate AS [Approved Date]
    ,Case When po.Closed = 1 then ''Closed'' else 
		case po.Status 
			when 1 then ''Not Sent For Approval''
			when 2 then ''Sent for Approval''
			when 3 then ''Rejected''
			when 4 then ''Open Approved'' end 
		end as [Status]
    ,case po.Closed when 1 then ''YES'' else ''NO'' end as [Closed]
	,case po.Printed when 1 then ''YES'' else ''NO'' end as [Printed]
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Selected Approver]
	,p.ProjectNumber as [Project Number]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName as [Project Full Name]
	,me.EstimateID as [Media Estimate ID]
	,me.EstimateName as [Media Estimate Name]
	,me.EstimateID + '' - '' + me.EstimateName as [Media Estimate Full Name]
	,cm.StationID as [Publication ID]
	,cm.Name as [Publication Name]
	,cm.StationID + '' - '' + cm.Name as [Publication Full Name]
	,pod.LineNumber AS [Line Number]
	,pod.ShortDescription AS [Caption]
	,pod.DetailOrderDate as [Insertion Date]
    ,pod.LongDescription AS [Line Long Description]
    ,pod.LongDescription AS [Line Comments]
    ,pod.TotalCost AS [Net]
    ,pod.AppliedCost AS [Applied Invoices]
	,pod.TotalCost - ISNULL(pod.AppliedCost, 0) AS [Open Amount]
    ,pod.Markup as [Commission]
	,pod.BillableCost AS [Gross]
	,pod.UserDate1 as [User Defined Date 1]
	,pod.UserDate2 as [User Defined Date 2]
	,pod.UserDate3 as [User Defined Date 3]
	,pod.UserDate4 as [User Defined Date 4]
	,pod.UserDate5 as [User Defined Date 5]
	,pod.UserDate6 as [User Defined Date 6]
	,pod.MaterialsSentDate as [Materials Sent Date]
	,pod.InteractiveAdUnitName AS [Ad Size]

	,Case When pod.TransferToKey IS NULL Then ''NO'' else ''YES'' end as [Transferred Out]
	,i.ItemID as [Item ID]
	,i.ItemName as [Item Name]
	,mm.MarketID as [Market ID]  
    ,mm.MarketName as [Market Name]
	,case when isnull(pref.IOClientLink, 1) = 1 then pc.CompanyName else mc.CompanyName end as [Client Name] 
	,case when isnull(pref.IOClientLink, 1) = 1 then pc.CustomerID else mc.CustomerID end as [Client ID] 
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,cl.ClassID as [Class ID]
	,cl.ClassName as [Class Name]
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,d.DepartmentName as Department
	,po.[Description] as [Order Description] 
	,po.SpecialInstructions as [Special Instructions]
	,po.DeliveryInstructions as [Traffic Instructions]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cp.ProductID as [Client Product ID]
    ,cp.ProductName as [Client Product]
    ,mp.PlanID as [Media Plan ID]
	,mp.PlanName as [Media Plan Name]
	,mp.PlanID + '' - '' + mp.PlanName as [Media Plan Full Name]
	,pot.PurchaseOrderTypeName AS [Order Type]	
	,fs.FieldSetName as [Order Line Field]

FROM 
	tPurchaseOrder po (nolock)
	INNER JOIN tPurchaseOrderDetail pod (nolock) on po.PurchaseOrderKey = pod.PurchaseOrderKey
	INNER JOIN tPreference pref (nolock) on po.CompanyKey = pref.CompanyKey	
    INNER JOIN tCompany c (nolock) ON po.VendorKey = c.CompanyKey 
	left outer join tProject p (nolock) on po.ProjectKey = p.ProjectKey
	left outer join tProject pline (nolock) on pod.ProjectKey = pline.ProjectKey
	left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	left outer join tCompanyMedia cm (nolock) on po.CompanyMediaKey = cm.CompanyMediaKey
	left outer join tMediaMarket mm (nolock) on cm.MediaMarketKey = mm.MediaMarketKey
	left outer join tUser u (nolock) on po.ApprovedByKey = u.UserKey
	left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
	left outer join tCompany pc (nolock) on pline.ClientKey = pc.CompanyKey
	left outer join tCompany mc (nolock) on me.ClientKey = mc.CompanyKey
	left outer join tClass cl (nolock) on pod.ClassKey = cl.ClassKey
	left outer join tGLCompany glc (nolock) on po.GLCompanyKey = glc.GLCompanyKey
	left outer join tOffice o (nolock) on pod.OfficeKey = o.OfficeKey
	left outer join tDepartment d (nolock) on pod.DepartmentKey = d.DepartmentKey
	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 tMediaPlanDetail mpd (nolock) on mpd.PurchaseOrderDetailKey	=  pod.PurchaseOrderDetailKey			 
	left outer join tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
	left outer join tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey
	left outer join tPurchaseOrderType pot (nolock) on po.PurchaseOrderTypeKey = pot.PurchaseOrderTypeKey
	left outer join tObjectFieldSet ofs (nolock) on pod.CustomFieldKey = ofs.ObjectFieldSetKey
	left outer join tFieldSet fs (nolock) on fs.FieldSetKey = ofs.FieldSetKey
Where po.POKind = 1 -- and isnull(po.MediaEstimateKey, 0) = 0
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptProjectTrackingGetListApp]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectTrackingGetListApp]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptProjectTrackingGetListApp]
 (  
 @CompanyKey int  
 ,@UserKey int  
 ,@BudgetWarning int = 0
 ,@CheckAssignment tinyint = 1
 ,@RestrictToGLCompany tinyint = 0
 ,@GLCompanyKey int = null
 ,@OpenAssignmentsOnly tinyint = 0
 ,@OnlyYourOpenAssignments tinyint = 1
 ,@PlanningProject tinyint = 0 --Returns only Planning Projects
 ,@IncludePlanningProjects tinyint = 0 --Includes Planning Projects in the regular project list
 ,@IAmAM tinyint = 0
 ,@IAmPM tinyint = 0
 ,@IAmBM tinyint = 0



 )  
AS -- Encrypt  
  
/*  exec sptProjectTrackingGetListApp 100, 16
|| 12/17/13 MAS 10.5.7.5	Copied sptProjectTrackingGetList for the NEW APP - commented out CF until we know how we want to handle things
|| 09/03/14 MAS 10.5.8.3	Changed projects.dashboard.dash to projects.dashboard.dash
|| 12/11/14 WDF 10.5.8.7	Added Description
|| 09/17/15 GHL 10.5.9.6	Filter out templates
|| 09/17/15 RLB 10.5.9.6    Added columns for grid format
|| 09/18/15 RLB 10.5.9.6    Added IsFavorite and open assigments only
|| 10/13/15 GWG 10.5.9.7    Added Open Todos
|| 11/5/15  GWG 10.5.9.7    Added where clasuse to remove comments
|| 12/31/15 RLB 10.5.9.9    Added For Enhancement 273258
|| 01/15/16 GWG 10.6.0.0	Added ProjectTaskStatusColor
|| 02/12/16 GAR 10.6.0.1    289387 - Honor CheckAssignment parameter.
|| 04/08/16 GWG 10.6.0.3    Leave project in even if they are favorites.  
|| 07/28/16 GAR 10.6.0.6    308537 - Add HasEstimate for project listing
|| 07/29/16 GAR 10.6.0.6    305563 - Add FlightDates for project listing 
|| 09/08/16 GWG 10.6.0.7	Added Project Description
|| 10/7/16  GWG 10.6.0.8    Fixed check assignment
|| 10/10/16 MAS 10.6.0.8    (310903) Added ProjectTypeKey
|| 10/10/16 MAS 10.6.0.8    (310903) Added ISNULL to PercComp & ProjectTaskStatusColor for @OpenAssignmentsOnly <> 1
|| 12/12/16 MCM 10.6.1.1    (323922) Added customFieldKey to the select statement because need it to show custom fields on projects.production.dash page
|| 01/22/17 GWG 10.6.1.1    Changed how custom fields are loaded to pull using cfmanager merge method  call cf.mergeSPCustomFields(d, companyKey, cols, "Project", "tProject", "General", "", "project")  first
|| 03/30/17 GWG 10.6.1.4    Changed all active to < 0 since the lookup changed to a -3, but was a -1 so the list was showing up blank. only called for all active.
|| 05/05/17 GAR 10.6.1.6    (344028) Added ProjectBillingStatusID to help with the lookup display when clicked
|| 04/26/18 RLB 18.5.0.0    (398392) Added ProjectStatusLocked
|| 06/11/18 GWG 18.7.0.0	If you blank the project status it will default to all active.
|| 07/25/18 RLS 18.8.0.0	(411781) Added @CreateTempTableProjectType and #ProjectType
|| 08/08/18 WDF 10.9.0.0	(408048) Set AccountManagerName to ''[No Account Managaer]'' if NULL
|| 08/10/18 RLS 18.9.0.0	(414443) Removed parameter from 411781 (two above) and added inner join on #ProjectStatus and #ProjectBillingStatus
|| 09/27/18 RLS 18.9.1.0	(422195) Added TotalLaborGross and TotalCostsGross
|| 11/30/18 AMP 18.9.3.0    (418338) Added Amount Advance Billed, and Amount Advance Billed Open to Production Dash
|| 12/07/18 RLB 19.1.0.0    (423437) Added option to production dash to show all open assigments on a project
|| 01/11/19 RLS 19.0.2.0    (438746) Added ProjectToBillRemaining, ProjectRemainingHours and ProjectRemainingBudget
|| 02/01/19 CRG 19.0.3.0    (421239) Added PlanningProject
|| 03/18/19 AMP 19.0.4.0    (449681) Added the Currency field as an available field to the projects screen
|| 05/23/19 CRG 19.0.6.0    (460946) Added IncludePlanningProjects
|| 06/04/19 RLS 19.0.7.0    (462309) Added LastTaskDueDate
|| 06/06/19 RLB 19.0.7.0    (446229) Adding Project Manager
|| 07/22/19 RLB 19.0.8.0    (448328) Added Schedule direction and work days
|| 09/23/19 GAR 19.1.0.0    (480171) Added Project Type Color
|| 10/23/19 GAR 19.1.1.0    (484469) Added Estimate Profit
|| 10/30/19 GWG 19.q.q.0	Added deliverable count
|| 12/03/19 RLS 19.1.2.0    (471599) Added defaults for Campaign, Campaign Segment, Project Status and Project Type
|| 12/10/19 CRG 19.1.2.0    (492002) Changed query for deliverable count to a derived table because it was killing the performance on the servers
|| 02/04/20 RLB 20.0.3.0    (497728) Added client select list temp table
|| 06/29/20 RLS 20.0.7.0    (518686) Added GLCompanySource
|| 08/31/20 RLS 20.0.9.0    (525753) Added LastTimeEntry
|| 08/31/20 GAR 20.1.0.0    (526908) Added key people for use in projects.production.dash
|| 09/15/20 GAR 20.1.0.0    (526681) Honor @OpenAssignmentsOnly and @OnlyYourOpenAssignments separately - before you needed both checked to honor @OnlyYourOpenAssignments
|| 10/16/20 GAR 20.1.1.0    (533409) Fixed an issue with key people queries taking a long time
|| 10/28/20 WDF 20.1.1.0    (533727) Pre-select Project Keys into a temp table
|| 11/04/20 GHL 20.1.1.0    (533727) Kept Bill''s idea of initial temp table. Because I noticed it was faster
||                           Added index on it. Removed recent subqueries
|| 11/30/20 GHL 20.1.2.0    (537843) Combined the 2 queries in 1, also converted old subqueries to derived tables 
|| 03/03/21 RLB 21.04.18    (544932) Added Total Gross Unbilled as a new column need the data now
|| 05/24/21 GHL 21.06.20    (559523) Added Misc Costs to Total Gross
|| 08/31/21 RLS 21.0.9.0    (566254) Added AllocatedHours
|| 12/17/21 RLB 22.01.16    (578277) Added new grouping field ParentClientName from project client
|| 02/15/22 RLS 22.03.20    (585537) Added @IAmAM and @IAmPM
|| 02/21/22 RLB 22.03.20    (587756) Added planned project name, number and full name to productionDashPlanning
|| 05/24/22 RLS 22.06.19    (596984) Added RemainingLaborBudget and RemainingExpenseBudget
|| 07/07/22 AMP 22.07.24    (604434) Added Retainer Name, Client Key, and RetainerKey for Retainer Name to be an available field on Column Sets on projects.production.dash 
|| 08/04/22 AMP 22.08.14    (606737) Added Billing Method Name 
|| 09/19/22 CRG 22.10.16    (612355) Removed subquery for AlloctedHours to improve performance
|| 09/27/22 RLB 22.10.16    (612598) Added ProjectDueDateGantt if project complete is null try to use the LastTaskDueDate
|| 09/28/22 CRG 22.10.16    (613568) Moved query restrictions to the initial temp table select in order to improve performance
|| 12/19/22 RLB 23.01.15    (622435) added Campaign update
|| 01/12/23 RLS 23.01.15    (627502) Fix - Changed redundant CampaignName to CampaignKey
|| 06/30/23 AMP 23.07.23    (644091) Added GL Company Name
|| 09/14/23 RLB 23.10.15    (651219) wrapped ScheduleAdherance, EffortVariance and ProjectPerformance with ISNULL because null value was causing the progress bar to not display
|| 06/06/24 RLS 24.07.14    (671824) Added AllocatedRemaining
|| 06/27/24 RLB 24.07.14    (675370) Added Filter for I am BM
|| 06/28/24 RLB 24.07.14    (674339) changed Budget Remaining field to match project dash board as best it can
|| 09/10/24 RLB 24.10.20    (682644) added pr.OpenOrderUnbilled to the total gross of ProjectRemainingBudget to match the project dash board Calc
|| 09/19/24 RLS 24.10.20    (682428) added pr.OpenOrdersGross
|| 12/31/24 RLS 25.01.19	(688590) Added ISNULL() to CurrencyID and join to tPreference
|| 04/16/25 RLB 25.05.18    (699375) Added Office to group by
|| 04/24/25 RLB 25.05.18    (699936) Added Office table for office any of
|| 06/13/25 GAR 25.07.20    (703925) Added Office Name
|| 06/24/25 RLB 25.07.20    (703414) Added update fields to only update what was changed
|| 08/25/25 AMP 25.08.17    (709683) Added UpdateStatusNotes, UpdateClientNotes, UpdateDetailNotes
|| 12/11/25 RLB 26.01.18    (717026) added HoursBilled from the rollup
|| 12/18/25 RLS 26.01.18    (715665) Added [HoursAfterWriteoff]
|| 03/31/26 GAR 26.04.19    (723332) Added ProjectStatusColor
*/

declare @KeyUser1 varchar(500)
declare @KeyUser2 varchar(500)
declare @KeyUser3 varchar(500)
declare @KeyUser4 varchar(500)
declare @KeyUser5 varchar(500)
declare @KeyUser6 varchar(500)

select @KeyUser1= StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser1'' and  CompanyKey = @CompanyKey
select @KeyUser2= StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser2'' and  CompanyKey = @CompanyKey
select @KeyUser3= StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser3'' and  CompanyKey = @CompanyKey
select @KeyUser4= StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser4'' and  CompanyKey = @CompanyKey
select @KeyUser5= StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser5'' and  CompanyKey = @CompanyKey
select @KeyUser6= StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser6'' and  CompanyKey = @CompanyKey

declare @DummyDate smalldatetime -- just to get the date type

 SELECT p.ProjectKey, @DummyDate as LastTimeEntry, 0 as OpenAssignments, 0 as OpenToDo, 0 as EstimateCount, 
		@DummyDate as LastTaskDueDate, CAST(0 AS decimal(24,4)) AS AllocatedHours
   INTO #ProjectKeys
   FROM tProject p INNER JOIN #ProjectType (nolock) on isnull(p.ProjectTypeKey, 0) = #ProjectType.ProjectTypeKey
			       INNER JOIN #ProjectStatus (nolock) on isnull(p.ProjectStatusKey, 0) = #ProjectStatus.ProjectStatusKey
			       INNER JOIN #ProjectBillingStatus (nolock) on isnull(p.ProjectBillingStatusKey, 0) = #ProjectBillingStatus.ProjectBillingStatusKey
			       INNER JOIN #Clients (nolock) on isnull(p.ClientKey, 0) = #Clients.ClientKey
				   INNER JOIN #Offices (nolock) on isnull(p.OfficeKey, 0) = #Offices.OfficeKey
  WHERE p.CompanyKey = @CompanyKey  
    AND p.Deleted = 0  
    AND isnull(p.Template, 0) = 0
	AND (@CheckAssignment = 0 OR p.ProjectKey in (SELECT ProjectKey FROM tAssignment (nolock) WHERE ProjectKey = p.ProjectKey AND UserKey = @UserKey) )
	AND (@GLCompanyKey IS NULL OR p.GLCompanyKey = @GLCompanyKey)
	AND (@GLCompanyKey IS NOT NULL OR (@RestrictToGLCompany = 0 OR isnull(p.GLCompanyKey, 0) in (select GLCompanyKey from tUserGLCompanyAccess (nolock) where UserKey = @UserKey)))
	AND (ISNULL(p.PlanningProject, 0) = @PlanningProject OR (@IncludePlanningProjects = 1 AND @PlanningProject <> 1))
	AND (@IAmAM  = 0 OR ISNULL(p.AccountManager, 0) = @UserKey)
	AND (@IAmPM  = 0 OR ISNULL(p.ProjectManager, 0) = @UserKey)
	AND (@IAmBM  = 0 OR ISNULL(p.BillingManagerKey, 0) = @UserKey)
				
create index Index_Proj on #ProjectKeys (ProjectKey) 

/* Truth table for the 2 main flags
@OnlyYourOpenAssignments    @OpenAssignmentsOnly
0                           0
0                           1
1                           0                     < Impossible situation, change below
1                           1
*/

-- if we ask for open assignments for a user, globally the project will have assigments
if @OnlyYourOpenAssignments = 1
	select @OpenAssignmentsOnly = 1

if @OnlyYourOpenAssignments = 1
	update #ProjectKeys
	set    #ProjectKeys.OpenAssignments = assign.OpenAssignments
	from #ProjectKeys
	inner join (SELECT	COUNT(*) as OpenAssignments , t.ProjectKey
								FROM	tTask t (NOLOCK) INNER JOIN tTaskUser tu (NOLOCK) ON tu.TaskKey = t.TaskKey   
								WHERE	tu.UserKey = @UserKey  
								AND (t.PercCompSeparate = 1 and tu.ActComplete IS NULL Or  t.PercCompSeparate = 0 and t.ActComplete IS NULL)	
								group by t.ProjectKey
		) as assign	on #ProjectKeys.ProjectKey = assign.ProjectKey 
else
	update #ProjectKeys
	set    #ProjectKeys.OpenAssignments = assign.OpenAssignments
	from #ProjectKeys
	inner join (SELECT	COUNT(*) as OpenAssignments , t.ProjectKey
								FROM	tTask t (NOLOCK) INNER JOIN tTaskUser tu (NOLOCK) ON tu.TaskKey = t.TaskKey   
								WHERE	(t.PercCompSeparate = 1 and tu.ActComplete IS NULL Or  t.PercCompSeparate = 0 and t.ActComplete IS NULL)	
								group by t.ProjectKey
		) as assign	on #ProjectKeys.ProjectKey = assign.ProjectKey 


if @OpenAssignmentsOnly = 1
	delete #ProjectKeys where isnull(OpenAssignments,0) = 0

-- other derived tables (instead of subqueries) 
update #ProjectKeys
set    #ProjectKeys.LastTimeEntry = times.WorkDate
	from #ProjectKeys
	inner join (select max(t.WorkDate) as WorkDate, t.ProjectKey  from tTime t (nolock)
				group by t.ProjectKey
				) as times on times.ProjectKey = #ProjectKeys.ProjectKey

update #ProjectKeys
set #ProjectKeys.OpenToDo = act.OpenToDo
from #ProjectKeys
	inner join (SELECT COUNT(a.ActivityKey) as OpenToDo , a.ProjectKey FROM tActivity a (NOLOCK) 
	where a.Completed = 0 and a.ActivityEntity = ''ToDo'' and a.ParentActivityKey = 0
	group by a.ProjectKey
	) as act on act.ProjectKey = #ProjectKeys.ProjectKey

update #ProjectKeys
set #ProjectKeys.EstimateCount = est.EstimateCount
from #ProjectKeys
	inner join (SELECT COUNT(EstimateKey) as EstimateCount, ProjectKey FROM tEstimate (nolock) Group By ProjectKey)
	as est on est.ProjectKey = #ProjectKeys.ProjectKey

update #ProjectKeys
set #ProjectKeys.LastTaskDueDate = task.LastTaskDueDate
from #ProjectKeys
inner join (SELECT MAX(t.PlanComplete) as LastTaskDueDate, t.ProjectKey  FROM tTask t (NOLOCK) 
			Group By t.ProjectKey
		) as task on task.ProjectKey = #ProjectKeys.ProjectKey

update #ProjectKeys
set #ProjectKeys.AllocatedHours = alloc.Hours
from	#ProjectKeys
inner join (select Sum(tu.Hours) as Hours, t.ProjectKey from tTaskUser tu (NOLOCK) inner join tTask t (nolock) on tu.TaskKey = t.TaskKey
			Group By t.ProjectKey
		) as alloc on alloc.ProjectKey = #ProjectKeys.ProjectKey		
	

		 SELECT	p.ProjectKey  
					,ISNULL(p.ProjectNumber,'''') + '' - '' + ISNULL(p.ProjectName,'''') AS ProjectFullName  
					,CASE ISNULL(c.CustomerID,'''')
						WHEN '''' THEN ISNULL(ISNULL(c.CompanyName,''''), '''')
					ELSE 
						CASE ISNULL(c.CompanyName,'''')
							WHEN '''' THEN ISNULL(c.CustomerID,'''')
						ELSE c.CustomerID + '' - '' + c.CompanyName
						END
					END AS CustomerFullName
					,CASE ISNULL(pc.CustomerID,'''')
						WHEN '''' THEN ISNULL(ISNULL(pc.CompanyName,''''), '''')
					ELSE 
						CASE ISNULL(pc.CompanyName,'''')
							WHEN '''' THEN ISNULL(pc.CustomerID,'''')
						ELSE pc.CustomerID + '' - '' + pc.CompanyName
						END
					END AS ParentClientName
					,ISNULL(ps.Locked, 0) As ProjectStatusLocked  
					,ISNULL(ps.ProjectStatus, ''[No Project Status]'') AS ProjectStatus
					,ps.ProjectStatusID AS ProjectStatusID
					,ISNULL(ps.ProjectStatusKey, 0) AS ProjectStatusKey
					,0 AS UpdateProjectStatus
					,ISNULL(ps.ProjectStatusColor, '''') AS ProjectStatusColor
					,ISNULL(pbs.ProjectBillingStatus, '''') AS ProjectBillingStatus
					,ISNULL(pbs.ProjectBillingStatusID, '''') AS ProjectBillingStatusID
					,ISNULL(pbs.ProjectBillingStatusKey, 0) AS ProjectBillingStatusKey
					,0 AS UpdateProjectBillingStatus
					,ISNULL(pt.ProjectTypeName, ''[No Project Type]'') AS ProjectTypeName
					,ISNULL(pt.ProjectTypeColor, '''') AS ProjectTypeColor
					,ISNULL(pt.ProjectTypeKey, 0) AS ProjectTypeKey
					,0 AS UpdateProjectType
					,ISNULL(p.PercComp, 0) as ProjectPercComp
					,ISNULL(ca.CampaignName, ''[No Campaign]'') AS CampaignName
					,ISNULL(ca.CampaignID, '''') AS CampaignID
					,ISNULL(ca.CampaignKey, 0) AS CampaignKey
					,0 AS UpdateCampaign

					,LTRIM(RTRIM(ISNULL(u.FirstName,'''') + '' '' + ISNULL(u.LastName,''''))) AS PrimaryContact
					,u.Phone1 
					,u.Email 
					,ISNULL(c.CompanyName, '''') AS CompanyName
					,c.Phone
					,ISNULL(p.TaskStatus, 1) AS ProjectTaskStatus
					/*
					,Case @OnlyYourOpenAssignments
						When 1 Then
							(	SELECT	COUNT(*)   
								FROM	tTask t (NOLOCK) INNER JOIN tTaskUser tu (NOLOCK) ON tu.TaskKey = t.TaskKey   
								WHERE	t.ProjectKey = p.ProjectKey  
								AND tu.UserKey = @UserKey  
								AND (t.PercCompSeparate = 1 and tu.ActComplete IS NULL Or  t.PercCompSeparate = 0 and t.ActComplete IS NULL)				        
							)
						Else
							(	SELECT	COUNT(*)   
								FROM	tTask t (NOLOCK) INNER JOIN tTaskUser tu (NOLOCK) ON tu.TaskKey = t.TaskKey   
								WHERE	t.ProjectKey = p.ProjectKey    
								AND (t.PercCompSeparate = 1 and tu.ActComplete IS NULL Or  t.PercCompSeparate = 0 and t.ActComplete IS NULL)				        
							)
					END AS OpenAssignments
					*/
					,pk.OpenAssignments
					,Case ISNULL(p.TaskStatus, 1) When 1 then ''Green'' When 2 then ''Yellow'' When 3 then ''Red'' else ''Green'' end as ProjectTaskStatusColor
					--,( SELECT COUNT(*) FROM tActivity a (NOLOCK) Where a.ProjectKey = p.ProjectKey and Completed = 0 and a.ActivityEntity = ''ToDo'' and ParentActivityKey = 0 ) as OpenToDo
					,pk.OpenToDo
					,(ISNULL(pr.LaborGross, 0) + ISNULL(pr.ExpReceiptGross, 0)) + ISNULL(pr.MiscCostGross, 0)  
					+ ISNULL(pr.VoucherOutsideCostsGross, 0) + ISNULL(pr.OpenOrderUnbilled, 0) + ISNULL(pr.OrderPrebilled, 0) 
						AS TotalGross
					,ISNULL(pr.LaborUnbilled, 0) + ISNULL(pr.MiscCostUnbilled, 0) + ISNULL(pr.ExpReceiptUnbilled, 0) 
					+ ISNULL(pr.VoucherUnbilled, 0) + ISNULL(pr.OpenOrderUnbilled, 0) as TotalGrossUnbilled

					-- Budgeted data  
					,p.EstHours AS OriginalBudgetHours -- [Estimate Hours]  
					,p.EstLabor AS  OriginalBudgetLaborGross -- [Estimate Labor]  
					,p.BudgetExpenses AS OriginalBudgetExpenseNet -- [Estimate Expense Net]  
					,p.EstExpenses AS OriginalBudgetExpenseGross -- [Estimate Expense Gross]  
					,p.ApprovedCOHours AS COBudgetHours -- [Approved CO Hours]  
					,p.ApprovedCOLabor AS COBudgetLaborGross -- [Approved CO Labor]  
					,p.ApprovedCOExpense AS COBudgetExpenseGross -- [Approved CO Expense Gross]  
					,p.EstHours + p.ApprovedCOHours AS CurrentBudgetHours -- [Estimate Total Hours]  
					,p.EstLabor + p.ApprovedCOLabor AS CurrentBudgetLaborGross -- [Estimate Total Labor]  
					,p.EstExpenses + p.ApprovedCOExpense AS CurrentBudgetExpenseGross --[Estimate Total Gross Expense]  
					,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense AS TotalBudget -- [Estimate Total]  
					,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense 
						+ ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0) AS TotalBudgetwTaxes --New field  

					,pr.BilledAmount
					,pr.BilledAmountNoTax
					,pr.Hours as ActualHours
					,ISNULL(pr.HoursBilled, 0) as HoursBilled
					,ISNULL(pk.AllocatedHours, 0) -ISNULL(pr.Hours, 0) as AllocatedRemaining
					,ISNULL(pr.LaborGross, 0) as TotalLaborGross
					,ISNULL(pr.MiscCostGross, 0) 
						+ ISNULL(pr.ExpReceiptGross, 0) 
						+ ISNULL(pr.OrderPrebilled, 0) 
						+ ISNULL(pr.VoucherOutsideCostsGross, 0) as TotalCostsGross
					,pr.AdvanceBilled
			        ,pr.AdvanceBilledOpen
					,ISNULL(pr.OpenOrderGross, 0) as OpenOrdersGross
					,ISNULL(pr.Hours, 0) - ISNULL(pr.HoursWriteOff, 0) as [HoursAfterWriteoff]

					-- (596984)
					-- Difference between CurrentBudgetLaborGross and TotalLaborGross
					 ,(p.EstLabor + p.ApprovedCOLabor) - ISNULL(pr.LaborGross, 0) as RemainingLaborBudget
					 -- Difference between CurrentBudgetExpenseGross and TotalCostsGross
					 ,(p.EstExpenses + p.ApprovedCOExpense) - 
					    (ISNULL(pr.MiscCostGross, 0) 
						+ ISNULL(pr.ExpReceiptGross, 0) 
						+ ISNULL(pr.OrderPrebilled, 0) 
						+ ISNULL(pr.VoucherOutsideCostsGross, 0)) as RemainingExpenseBudget

					-- Need these for the project.dash grid edit
					,p.StatusNotes AS StatusNotes  
					,p.StatusNotesUpdated AS UpdateStatusNotes					
					,p.ClientNotes AS ClientNotes 
					,p.ClientNotesUpdated AS UpdateClientNotes
					,p.DetailedNotes AS DetailedNotes 
					,p.DetailedNotesUpdated AS UpdateDetailNotes

					-- Leaving ProjectStatusNote & ProjectStatusDescription as they are used in a couple of screens
					,p.StatusNotes AS ProjectStatusNote  
					,p.DetailedNotes AS ProjectStatusDescription 
					,p.Description AS ProjectDescription  
					,p.StartDate AS ProjectStartDate 
					,0 AS UpdateProjectStartDate
					,p.CompleteDate AS ProjectDueDate  
					,0 AS UpdateProjectDueDate
					,ISNULL(p.CompleteDate, pk.LastTaskDueDate) AS ProjectDueDateGantt
					,p.CreatedDate AS CreatedDate  

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

					,CASE p.NonBillable WHEN 1 THEN ''YES'' ELSE ''NO'' END AS NonBillableProject  
					,CASE p.Closed When 1 THEN ''YES'' ELSE ''NO'' END AS ClosedProject
					,0 AS UpdateProjectClosed
					,p.ProjectNumber
					,p.ProjectName
					,p.ProjectColor
					,0 AS UpdateProjectColor
					,ISNULL(cps.SegmentName, ''[No Campaign Segment]'') AS SegmentName
					,ISNULL(po.OfficeName, ''[No Office Name]'') AS OfficeName
					,cd.DivisionName
					,cp.ProductName
					,CASE WHEN ISNULL(af.AppFavoriteKey, 0) > 0 THEN 1 ELSE 0 END AS IsFavorite
					,p.Description
					,CASE
						WHEN ISNULL(LTRIM(RTRIM(am.FirstName)) + LTRIM(RTRIM(am.LastName)), '''') = '''' THEN ''[No Account Manager]''
						ELSE am.FirstName + '' '' + am.LastName
						END AS AccountManagerName
					,ISNULL(am.UserKey, 0) as AccountManagerKey
					,0 AS UpdateAM
					,CASE
						WHEN ISNULL(LTRIM(RTRIM(upm.FirstName)) + LTRIM(RTRIM(upm.LastName)), '''') = '''' THEN ''[No Project Manager]''
						ELSE upm.FirstName + '' '' + upm.LastName
						END AS ProjectManagerName
					,ISNULL(upm.UserKey, 0) as ProjectManagerKey
					,0 AS UpdatePM
					,LTRIM(RTRIM(ISNULL(ubm.FirstName,'''') + '' '' + ISNULL(ubm.LastName,''''))) as BillingManagerName
					,ISNULL(ubm.UserKey, 0) as BillingManagerKey
					,0 AS UpdateBM
					,p.ClientProjectNumber
					,0 AS UpdateClientProjectNumber
					,ISNULL(p.CurrencyID, pref.CurrencyID) as [CurrencyID]
					,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as TestEst
					,ISNULL(pr.LaborGross, 0) + ISNULL(pr.MiscCostGross, 0) + ISNULL(pr.ExpReceiptGross, 0) + ISNULL(pr.VoucherGross, 0) + ISNULL(pr.OpenOrderGross, 0) as TestCost
					,CASE 
						WHEN (p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense) = 0 THEN 1
						WHEN (ISNULL(pr.LaborGross, 0) + ISNULL(pr.MiscCostGross, 0) + ISNULL(pr.ExpReceiptGross, 0) + ISNULL(pr.VoucherGross, 0) + ISNULL(pr.OpenOrderGross, 0) )  > 
								p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense THEN 3
						WHEN (ISNULL(pr.LaborGross, 0) + ISNULL(pr.MiscCostGross, 0) + ISNULL(pr.ExpReceiptGross, 0) + ISNULL(pr.VoucherGross, 0) + ISNULL(pr.OpenOrderGross, 0) ) / 
								(p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense) * 100 >= @BudgetWarning THEN 2
						ELSE 1
						END AS FinancialStatusImage
					--,CASE WHEN (SELECT COUNT(*) FROM tEstimate (nolock) WHERE ProjectKey = p.ProjectKey) > 0 THEN 1 ELSE 0 END AS HasEstimate  
					,case when pk.EstimateCount > 0 then 1 else 0 end as HasEstimate
					,p.FlightStartDate
					,p.FlightEndDate
					,p.ScheduleDirection
					,p.PlanningProject
					,p.WorkSun
					,p.WorkMon
					,p.WorkTue
					,p.WorkWed
					,p.WorkThur
					,p.WorkFri
					,p.WorkSat
					,rd.DelCount as Deliverables
					,pk.AllocatedHours
					,cf.*
					-- The next 3 fields added for (438746)
				,(p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense + ISNULL(p.SalesTax,0) + ISNULL(p.ApprovedCOSalesTax,0)) - ISNULL(pr.BilledAmount, 0) AS ProjectToBillRemaining
				,(p.EstHours + p.ApprovedCOHours) - ISNULL(pr.Hours, 0) AS ProjectRemainingHours
				,((p.EstLabor + p.ApprovedCOLabor) + (p.EstExpenses + p.ApprovedCOExpense)) - (ISNULL(pr.MiscCostGross, 0) + ISNULL(pr.ExpReceiptGross, 0) + (ISNULL(pr.OrderPrebilled, 0) + ISNULL(pr.VoucherOutsideCostsGross, 0) + ISNULL(pr.OpenOrderUnbilled, 0)) + ISNULL(pr.LaborGross, 0)) AS ProjectRemainingBudget
				--,(SELECT MAX(t.PlanComplete) FROM tTask t (NOLOCK) WHERE t.ProjectKey = p.ProjectKey) as LastTaskDueDate
				,pk.LastTaskDueDate
				,p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense - p.BudgetExpenses - p.BudgetLabor - p.ApprovedCOBudgetLabor - p.ApprovedCOBudgetExp  as EstimateProfit
				,CASE 
					WHEN ISNULL(p.GLCompanySource,0) = 0 THEN ''Project'' 
					WHEN ISNULL(p.GLCompanySource,0) = 1 THEN ''Person'' 
					ELSE ''Project''
				END AS ''GLCompanySource''
				,p.KeyPeople1
				,0 AS UpdateKeyPeople1
				,p.KeyPeople2
				,0 AS UpdateKeyPeople2
				,p.KeyPeople3
				,0 AS UpdateKeyPeople3
				,p.KeyPeople4
				,0 AS UpdateKeyPeople4
				,p.KeyPeople5
				,0 AS UpdateKeyPeople5
				,p.KeyPeople6
				,0 AS UpdateKeyPeople6
				-- Avoid subqueries
				--,(Select Max(tTime.WorkDate) from tTime (nolock) Where tTime.ProjectKey = p.ProjectKey) as LastTimeEntry
				,pk.LastTimeEntry
				,0 AS UpdatePlanningProjectKey
				,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 PlanningProjectNumber
				,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 PlanningProjectName
				,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 PlanningProjectFullName

				,kp1.UserName as KeyPeople1Name
				,kp2.UserName as KeyPeople2Name
				,kp3.UserName as KeyPeople3Name
				,kp4.UserName as KeyPeople4Name
				,kp5.UserName as KeyPeople5Name
				,kp6.UserName as KeyPeople6Name

				,@KeyUser1 as KeyPeople1Label
				,@KeyUser2 as KeyPeople2Label
				,@KeyUser3 as KeyPeople3Label
				,@KeyUser4 as KeyPeople4Label
				,@KeyUser5 as KeyPeople5Label
				,@KeyUser6 as KeyPeople6Label

				,ISNULL(pr.ScheduleAdherance, 0) as ScheduleAdherance
				,Case  When ISNULL(pr.ScheduleAdherance, 0) < -5 then ''Green'' When ISNULL(pr.ScheduleAdherance, 0) > 5 then ''Red'' else ''Yellow'' end as ScheduleAdheranceColor
				,ISNULL(pr.EffortVariance, 0) as EffortVariance
				,Case  When ISNULL(pr.EffortVariance, 0) > 95 then ''Red'' When ISNULL(pr.EffortVariance, 0) < 90 then ''Green'' else ''Yellow'' end as EffortVarianceColor
				,ISNULL(pr.ProjectPerformance, 0) as ProjectPerformance
				,Case  When ISNULL(pr.ProjectPerformance, 0) > 95 then ''Green'' When ISNULL(pr.ProjectPerformance, 0) < 90 then ''Red'' else ''Yellow'' end as ProjectPerformanceColor

				-- avoid subqueries
				--,case when p.KeyPeople1 is null then null else (SELECT UserName FROM vUserName WHERE UserKey = p.KeyPeople1) end AS KeyPeople1Name
				--,case when p.KeyPeople2 is null then null else (SELECT UserName FROM vUserName WHERE UserKey = p.KeyPeople2) end AS KeyPeople2Name
				--,case when p.KeyPeople3 is null then null else (SELECT UserName FROM vUserName WHERE UserKey = p.KeyPeople3) end AS KeyPeople3Name
				--,case when p.KeyPeople4 is null then null else (SELECT UserName FROM vUserName WHERE UserKey = p.KeyPeople4) end AS KeyPeople4Name
				--,case when p.KeyPeople5 is null then null else (SELECT UserName FROM vUserName WHERE UserKey = p.KeyPeople5) end AS KeyPeople5Name
				--,case when p.KeyPeople6 is null then null else (SELECT UserName FROM vUserName WHERE UserKey = p.KeyPeople6) end AS KeyPeople6Name
				--,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser1'' and CompanyKey = p.CompanyKey) as KeyPeople1Label
				--,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser2'' and CompanyKey = p.CompanyKey) as KeyPeople2Label
				--,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser3'' and CompanyKey = p.CompanyKey) as KeyPeople3Label
				--,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser4'' and CompanyKey = p.CompanyKey) as KeyPeople4Label
				--,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser5'' and CompanyKey = p.CompanyKey) as KeyPeople5Label
				--,(Select StringSingular from tStringCompany (nolock) Where StringID = ''KeyUser6'' and CompanyKey = p.CompanyKey) as KeyPeople6Label
		        ,r.Title as RetainerName
				,ISNULL(r.RetainerKey, 0) AS RetainerKey
				,0 AS UpdateRetainer
				,r.ClientKey
				,p.ClientKey as ProjectClientKey
				,Case ISNULL(p.BillingMethod, 1) When 1 then ''Time and Materials'' When 2 then ''Fixed Fee'' When 3 then ''Retainer'' end as BillingMethodName
	            ,gl.GLCompanyName as GLCompanyName
				,Case ISNULL(p.PlanningBillOption, 1) When 1 then ''Only bill the plan'' When 2 then ''Bill the plan and project separately'' end as PlanningBillingOptionName
				,ISNULL(po.OfficeID, ''[No Office ID]'') AS OfficeID
				,po.OfficeKey
				,0 AS UpdateOffice
		FROM	#ProjectKeys pk    
				INNER JOIN tProject p (NOLOCK) on (pk.ProjectKey = p.ProjectKey)
				INNER JOIN tProjectStatus ps (nolock) ON p.ProjectStatusKey = ps.ProjectStatusKey 
				LEFT  JOIN tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey   
				LEFT  JOIN tCampaign ca (nolock)  ON p.CampaignKey = ca.CampaignKey  
				LEFT  JOIN tCampaignSegment cps (nolock)  ON p.CampaignSegmentKey = cps.CampaignSegmentKey  
				LEFT  JOIN tCompany c (nolock)   ON p.ClientKey = c.CompanyKey 
				LEFT  JOIN tCompany pc (nolock) ON c.ParentCompanyKey = pc.CompanyKey
				LEFT  JOIN tUser u (nolock)   ON p.BillingContact = u.UserKey  
				LEFT  JOIN tUser am (nolock)   ON p.AccountManager = am.UserKey  
				LEFT  JOIN tUser ubm (nolock) ON p.BillingManagerKey = ubm.UserKey
				LEFT  JOIN tUser upm (nolock) ON p.ProjectManager = upm.UserKey
				LEFT  JOIN tRetainer r (nolock) ON p.RetainerKey = r.RetainerKey						
				LEFT  JOIN tProjectRollup pr (nolock)  ON p.ProjectKey = pr.ProjectKey  
				LEFT  JOIN tProjectBillingStatus pbs (nolock) ON p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
				LEFT  JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
				LEFT  JOIN tClientProduct cp (nolock) on p.ClientProductKey = cp.ClientProductKey
				left outer join tGLCompany gl (nolock) on p.GLCompanyKey = gl.GLCompanyKey
				left outer join tOffice po (nolock) on p.OfficeKey = po.OfficeKey
				left outer join tProject pp (nolock) on p.PlanningProjectKey = pp.ProjectKey			  
				LEFT OUTER JOIN tAppFavorite af (nolock) on p.ProjectKey = af.ActionKey AND af.ActionID = ''projects.dashboard.dash'' and af.UserKey = @UserKey
				LEFT OUTER JOIN #tCustomFields1 cf (nolock) ON p.CustomFieldKey = cf.CustomFieldKey
				--- LEFT JOIN #tCustomFields cf (nolock) ON p.CustomFieldKey = cf.CustomFieldKey 
				LEFT JOIN (Select Count(*) as DelCount, ProjectKey from tReviewDeliverable (nolock) where CompanyKey = @CompanyKey group by ProjectKey) rd on p.ProjectKey = rd.ProjectKey
	
				left outer join vUserName kp1 (nolock) on p.KeyPeople1 = kp1.UserKey
				left outer join vUserName kp2 (nolock) on p.KeyPeople2 = kp2.UserKey
				left outer join vUserName kp3 (nolock) on p.KeyPeople3 = kp3.UserKey
				left outer join vUserName kp4 (nolock) on p.KeyPeople4 = kp4.UserKey
				left outer join vUserName kp5 (nolock) on p.KeyPeople5 = kp5.UserKey
				left outer join vUserName kp6 (nolock) on p.KeyPeople6 = kp6.UserKey
				left outer join tPreference pref (nolock) on p.CompanyKey = pref.CompanyKey
	
		WHERE	(@OpenAssignmentsOnly  = 0 OR OpenAssignments  > 0)

 RETURN 1

 
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPurchaseOrderDetailInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderDetailInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptPurchaseOrderDetailInsert]
	@PurchaseOrderKey int,
	@LineNumber int,
	@ProjectKey int,
	@TaskKey int,
	@ItemKey int,
	@ClassKey int,
	@ShortDescription varchar(max),
	@Quantity decimal(24,4),
	@UnitCost money,
	@UnitDescription varchar(30),
	@TotalCost money,
	@UnitRate money,
	@Billable tinyint,
	@Markup decimal(24,4),
	@BillableCost money,
	@LongDescription nvarchar(max),
	@CustomFieldKey int,
	@DetailOrderDate smalldatetime,
	@DetailOrderEndDate smalldatetime,
	@UserDate1 smalldatetime,
	@UserDate2 smalldatetime,
	@UserDate3 smalldatetime,
	@UserDate4 smalldatetime,
	@UserDate5 smalldatetime,
	@UserDate6 smalldatetime,
	@OrderDays varchar(50),
	@OrderTime varchar(50),
	@OrderLength varchar(50),
	@Taxable tinyint,
	@Taxable2 tinyint,
	@OfficeKey int,
	@DepartmentKey int,	
	@GrossAmount money = null,
	@PCurrencyID varchar(10) = null,
	@PExchangeRate decimal(24,7) = 1,
	@PTotalCost money = null,  
	@SkipRollUps tinyint = null,  
	@InteractiveAdUnitName varchar (100) = null,
	@oIdentity INT OUTPUT
AS --Encrypt

/*
|| When     Who Rel    What
|| 04/13/07 BSH 8.4.5  DateUpdated needed to be updated. 
|| 07/16/07 BSH 8.5    (9659)Insert OfficeKey, DepartmentKey
|| 1/21/09  GWG 10.018 Added Rounding protection on cost and gross
|| 07/01/11 GHL 10.546 (111482) Added call to sptPurchaseOrderRollupAmounts for tax amounts 
|| 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @ShortDescription from 200 to 300
|| 12/17/13 GHL 10.5.7.5 Added currency parameters
|| 12/30/13 CRG 10.5.7.5 Fixed Line Number logic for Interactive orders
|| 04/23/14 RLB 10.5.7.9 (209351) will now allow adding lines to a PO if a line on it is on a voucher also making description field larger for (214240)
|| 09/03/14 GHL 10.5.8.4 (228377) If PTotalCost is null, set PTotalCost = Round(TotalCost, 2)
||                       i.e. not PTotalCost = TotalCost
|| 08/11/15 GHL 10.5.9.5 (263071) LongDescription is now varchar(max)
|| 03/16/21 RLS 21.0.4.0 (550747) Changed @LongDescription to nvarchar(max)
|| 06/25/21 GHL 21.0.7.0 Added validation of PCurrencyID and PExchangeRate (in case of timing issue on the UI). Also flag SP for 451878
|| 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
|| 04/22/26 MCM 26.5.x  (725435) Added @InteractiveAdUnitName for PurchaseOrderDetail
*/

declare @POKind smallint
declare @FlightInterval tinyint
declare @FlightStartDate smalldatetime
declare @FlightEndDate smalldatetime
declare @DefaultDate smalldatetime
declare @ExchangeRate decimal(24,7)
declare @PODate smalldatetime
declare @CompanyKey int
declare @GLCompanyKey int
declare @CurrencyID varchar(10)

	select @DefaultDate = cast(datepart(yyyy,getdate()) as varchar(4)) + ''-'' + cast(datepart(mm,getdate()) as varchar(2)) + ''-'' + cast(datepart(dd,getdate()) as varchar(2)) 

	select @POKind = POKind
	      ,@FlightInterval = isnull(FlightInterval,3)
	      ,@FlightStartDate = isnull(FlightStartDate,@DefaultDate)
	      ,@FlightEndDate = isnull(FlightEndDate,isnull(FlightStartDate,@DefaultDate))
		  ,@PODate = ISNULL(PODate, @DefaultDate)
		  ,@ExchangeRate = isnull(ExchangeRate, 1)
		  ,@CompanyKey = CompanyKey
		  ,@GLCompanyKey = GLCompanyKey
		  ,@CurrencyID = CurrencyID
	  from tPurchaseOrder (nolock)
	 where PurchaseOrderKey = @PurchaseOrderKey
/*	 
	if @POKind = 0
		IF EXISTS (SELECT 1
				FROM   tVoucherDetail vd (NOLOCK)
						,tPurchaseOrderDetail pod (NOLOCK)
						,tPurchaseOrder po (NOLOCK)
				WHERE  po.PurchaseOrderKey = @PurchaseOrderKey
				AND    po.PurchaseOrderKey = pod.PurchaseOrderKey
							AND    pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey)
			RETURN -1
*/
	
	if @POKind IN (1,2)
		begin 
			if exists(SELECT 1
					    FROM tPurchaseOrder po (NOLOCK)
				       WHERE po.PurchaseOrderKey = @PurchaseOrderKey
					     AND po.Closed = 1)
				update tPurchaseOrder
				   set Closed = 0 
				 where PurchaseOrderKey = @PurchaseOrderKey
		end	
	else   
		begin                    
			IF EXISTS (SELECT 1
						 FROM tPurchaseOrder po (NOLOCK)
						WHERE po.PurchaseOrderKey = @PurchaseOrderKey
						  AND (po.Closed = 1 or po.Downloaded = 1))
				RETURN -2
		end
	           
		
	if ISNULL(@ProjectKey, 0) > 0
		IF NOT EXISTS(Select 1 from tProject p (nolock) inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
			Where p.ProjectKey = @ProjectKey and ps.ExpenseActive = 1)
			Return -3
			
	DECLARE @NextNum as int

	-- Default value for NextNum
	SELECT @NextNum = ISNULL(Max(LineNumber),0) + 1 FROM tPurchaseOrderDetail (NOLOCK) WHERE PurchaseOrderKey = @PurchaseOrderKey
	
	if @POKind in (1, 4)
		begin
			if isnull(@LineNumber,0) > 0
				begin
					select @NextNum = @LineNumber					
				end
		end
		
	if @POKind = 2
		begin
			-- associate this line to an existing line if importing from Strata or SmartPlus
			if isnull(@LineNumber,0) > 0
				begin
					select @NextNum = @LineNumber					
				end 
			else
			    begin
					-- line number will be zero, use calculated number and calculate dates
					if @FlightInterval = 1 and @DetailOrderDate is null
						select @DetailOrderDate = @FlightStartDate
							  ,@DetailOrderEndDate = @FlightStartDate
					if @FlightInterval = 2 and @DetailOrderDate is null
						select @DetailOrderDate = @FlightStartDate
							  ,@DetailOrderEndDate = dateadd(d,6,@FlightStartDate)
					if @FlightInterval = 3 and @DetailOrderDate is null
						begin
							select @DetailOrderDate = isnull(@DetailOrderDate,@FlightStartDate)
							      ,@DetailOrderEndDate = isnull(@DetailOrderEndDate,@FlightEndDate)
						end	
				end			
		end
	 		 
	if @GrossAmount is null
		select @GrossAmount = ROUND(@BillableCost, 2)

	if @PTotalCost is null
		select @PTotalCost = ROUND(@TotalCost, 2)

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

	-- fix to prevent timing issues where the project is changed and then immediately saved
	-- without getting the currency and exchange rate
	declare @MultiCurrency int
	declare @ProjectCurrencyID varchar(10)
	declare @RateHistory int

	select @MultiCurrency = pref.MultiCurrency 
	from  tPreference pref (nolock)
	where pref.CompanyKey = @CompanyKey

	if @ProjectKey > 0 and @MultiCurrency = 1
	begin
		select @ProjectCurrencyID = CurrencyID from tProject (nolock) where ProjectKey = @ProjectKey
		if isnull(@PCurrencyID, '''') <> isnull(@ProjectCurrencyID, '''')
		begin
			select @PCurrencyID = @ProjectCurrencyID
			if isnull(@PCurrencyID, '''') = ''''
				select @PExchangeRate = 1
			else
			begin
				if isnull(@PCurrencyID, '''') = isnull(@CurrencyID, '''') 
					select @PExchangeRate = @ExchangeRate
				else
					exec sptCurrencyGetRate @CompanyKey, @GLCompanyKey, @PCurrencyID, @PODate, @PExchangeRate output, @RateHistory output
			end

			if @PExchangeRate > 0
				select @PTotalCost = (@TotalCost * @ExchangeRate) / @PExchangeRate 
						,@BillableCost = (@GrossAmount * @ExchangeRate) / @PExchangeRate
		end
	end


	INSERT tPurchaseOrderDetail
		(
		PurchaseOrderKey,
		LineNumber,
		ProjectKey,
		TaskKey,
		ItemKey,
		ClassKey,
		ShortDescription,
		Quantity,
		UnitCost,
		UnitDescription,
		TotalCost,
		UnitRate,
		Billable,
		Markup,
		BillableCost,
		LongDescription,
		CustomFieldKey,
		DetailOrderDate,
		DetailOrderEndDate,
		UserDate1,
		UserDate2,
		UserDate3,
		UserDate4,
		UserDate5,
		UserDate6,
		OrderDays,
		OrderTime,
		OrderLength,
		Taxable,
		Taxable2,
		OfficeKey,
		DepartmentKey,
		GrossAmount,
		PCurrencyID,
		PExchangeRate,
		PTotalCost,
		InteractiveAdUnitName
		)

	VALUES
		(
		@PurchaseOrderKey,
		@NextNum,		-- @LineNumber,
		@ProjectKey,
		@TaskKey,
		@ItemKey,
		@ClassKey,
		@ShortDescription,
		@Quantity,
		@UnitCost,
		@UnitDescription,
		Round(@TotalCost, 2),
		@UnitRate,
		@Billable,
		@Markup,
		Round(@BillableCost, 2),
		@LongDescription,
		@CustomFieldKey,
		@DetailOrderDate,
		@DetailOrderEndDate,
		@UserDate1,
		@UserDate2,
		@UserDate3,
		@UserDate4,
		@UserDate5,
		@UserDate6,
		@OrderDays,
		@OrderTime,
		@OrderLength,
		@Taxable,
		@Taxable2,
		@OfficeKey,
		@DepartmentKey,
		@GrossAmount,
		@PCurrencyID,
		@PExchangeRate,
		@PTotalCost,
		@InteractiveAdUnitName
		)
	
	SELECT @oIdentity = @@IDENTITY
	
	If ISNULL(@SkipRollUps, 0) = 0
		Begin
			EXEC sptPurchaseOrderDetailUpdateApprover @PurchaseOrderKey

			EXEC sptPurchaseOrderRollupAmounts @PurchaseOrderKey 
		End
	
		
	RETURN 1
	


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

ALTER PROCEDURE [dbo].[sptPurchaseOrderDetailAdjust]
	(
		@PurchaseOrderDetailKey int	-- Minimum of PurchaseOrderDetailKey for a line # and PO
		,@MediaRevisionReasonKey int
		,@Quantity decimal(24, 4)
		,@UnitCost money
		,@Markup decimal(24,4)
		,@TotalCost money
		,@BillableCost money
		,@SpotDate datetime		-- only used by BC daily and weekly, will help locate spot for a line # 
		,@GrossAmount money = null
		,@Quantity1 decimal(24, 4) = null
		,@Quantity2 decimal(24, 4) = null
		,@UnitRate money = null
		,@Commission decimal(24, 4) = null
		,@AdjustmentsOptionFromPO int = 0
		,@Taxable tinyint = 0
		,@Taxable2 tinyint = 0
		,@SalesTaxAmount money = 0
		,@SalesTax1Amount money = 0
		,@SalesTax2Amount money = 0
		,@oIdentity int Output
		,@oIdentityReversal int Output
		,@SkipRollup int = 0
	)

AS -- Encrypt

/*
|| When     Who Rel    What
|| 03/01/07 GHL 8.4    Added Project Rollup
|| 09/18/07 BSH 8.5    Added Office and Department Keys.
|| 06/23/11 RLB 10.545 (114864) get new custom fields keys for the revision lines
|| 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @ShortDescription from 200 to 300
|| 03/21/13 WDF 10.5.6.6 (172223) Adjust negative amounts when doing revisions with reversals
|| 10/09/13 CRG 10.5.7.3 Added @GrossAmount, @Quantity1, @Quantity2, @UnitRate, @Commission
|| 12/17/13 GHL 10.5.7.5 Changes for multi currency
|| 04/29/14 RLB 10.5.7.9 (214240) increasing short description
|| 05/01/14 GHL 10.5.7.9 Added @oIdentityReversal the reversal PO detail created if ShowAdjustmentsAsSingleLine = 0
||                       i.e. 1 reversal and a new value 
|| 05/02/14 GHL 10.5.7.9 Added option to read adjustment method from PO
|| 08/26/14 GHL 10.5.8.3 Added taxes for new media screens
|| 08/11/15 GHL 10.5.9.5 (263071) LongDescription is now varchar(max)
|| 08/09/17 GHL 10.6.1.9 Remove setting of LineType = rev because Voucher Total is incorrect on the UI (sptPurchaseOrderGet)
|| 07/22/19 GHL 19.0.8.0 Allow for @SpotDate = null for the new media plans, i.e. do not modified the POD key
|| 07/31/19 GHL 19.0.8.0 Added on reversals a pointer ReversedKey to the POD key being reversed
|| 03/16/21 RLS 21.0.4.0 (550747) Changed @LongDescription to nvarchar(max)
|| 08/12/22 QMD 22.09.18 (609307) added @SkipRollup flag
|| 12/14/22 MCM 23.01.x  (623540) return the @RetVal from sptPurchaseOrderDetailInsert so can show user good error message
|| 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
|| 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName

*/
	SET NOCOUNT ON
		
	select @oIdentityReversal = null

	-- General purpose vars	
	declare @NewPurchaseOrderDetailKey int
			,@SpotPurchaseOrderDetailKey int
			,@ShowAdjustmentsAsSingleLine int
			,@CompanyKey int
			,@POKind Int			-- 0:PO ,1:IO, 2:BC
			,@FlightInterval Int	-- 1: Daily, 2: Weekly, 3: Summary
			,@RetVal Int
			,@AdjustmentNumber Int
			,@PTotalCost money -- we need to recalc this

	-- Vars for reversal
	declare	@InsertReversal int
			,@RevQuantity decimal(24, 4)
			,@RevUnitCost money
			,@RevMarkup decimal(24,4)
			,@RevTotalCost money
			,@RevBillableCost money
			,@RevGrossAmount money
			,@RevQuantity1 decimal(24, 4)
			,@RevQuantity2 decimal(24, 4)
			,@RevUnitRate money
			,@RevCommission decimal(24, 4)
		    ,@RevSalesTaxAmount money
			,@RevSalesTax1Amount money
			,@RevSalesTax2Amount money
			,@RevTaxable tinyint
			,@RevTaxable2 tinyint

	-- Vars for POD capture							
	declare @PurchaseOrderKey int,
			@LineNumber int,
			@ProjectKey int,
			@TaskKey int,
			@ItemKey int,
			@ClassKey int,
			@ShortDescription varchar(max),
			@UnitDescription varchar(30),
			@Billable tinyint,
			@LongDescription nvarchar(max),
			@CustomFieldKey int,
			@DetailOrderDate smalldatetime,
			@DetailOrderEndDate smalldatetime,
			@UserDate1 smalldatetime,
			@UserDate2 smalldatetime,
			@UserDate3 smalldatetime,
			@UserDate4 smalldatetime,
			@UserDate5 smalldatetime,
			@UserDate6 smalldatetime,
			@OrderDays varchar(50),
			@OrderTime varchar(50),
			@OrderLength varchar(50),
			@OfficeKey int,
			@DepartmentKey int,
			@FieldSetKey int,
			@ObjectFieldSetKey int,
			@FieldSet2Key int,
			@ObjectFieldSet2Key int,
			@PCurrencyID varchar(3),
			@PExchangeRate decimal(24,7),
			@ExchangeRate decimal(24,7)
				
		Select  
			@PurchaseOrderKey = pod.PurchaseOrderKey,
			@LineNumber = pod.LineNumber,
			@POKind = po.POKind,
			@FlightInterval = po.FlightInterval,
			@ShowAdjustmentsAsSingleLine = 
			case when @AdjustmentsOptionFromPO = 0 then	
				CASE 
					WHEN po.POKind = 1 THEN ISNULL(pref.IOShowAdjustmentsAsSingleLine, 1)
					WHEN po.POKind = 2 THEN ISNULL(pref.BCShowAdjustmentsAsSingleLine, 1)
					ELSE 1
				END
			else ISNULL(po.ShowAdjustmentsAsSingleLine, 1)
			end
				,
			@ExchangeRate = po.ExchangeRate	 
		From tPurchaseOrderDetail pod (NOLOCK)
			inner join tPurchaseOrder po (NOLOCK) ON pod.PurchaseOrderKey = po.PurchaseOrderKey
			inner join tPreference pref (NOLOCK) ON po.CompanyKey = pref.CompanyKey
		Where pod.PurchaseOrderDetailKey = @PurchaseOrderDetailKey

		IF @POKind = 2 AND @FlightInterval IN (1, 2) AND @SpotDate is not null 
		BEGIN
			-- Broadcast orders And Daily/Weekly case
			-- We may not have the right spot, check for date to get exact POD
			SELECT @SpotPurchaseOrderDetailKey = PurchaseOrderDetailKey
			From   tPurchaseOrderDetail pod (NOLOCK)
			Where  pod.PurchaseOrderKey = @PurchaseOrderKey
			And    pod.LineNumber = @LineNumber 
			AND    pod.DetailOrderDate = @SpotDate		
			
			IF @SpotPurchaseOrderDetailKey IS NOT NULL
				-- We had the wrong one, correct it
				SELECT @PurchaseOrderDetailKey = @SpotPurchaseOrderDetailKey
		END
			
	-- Get a copy of the detail record 	
	Select  @PurchaseOrderKey = pod.PurchaseOrderKey,
			@LineNumber = pod.LineNumber,
			@ProjectKey = pod.ProjectKey,
			@TaskKey = pod.TaskKey,
			@ItemKey = pod.ItemKey,
			@ClassKey = pod.ClassKey,
			@ShortDescription = pod.ShortDescription,
			--@Quantity decimal(24,4),
			--@UnitCost money,
			@UnitDescription = pod.UnitDescription,
			--@TotalCost = TotalCost,
			@Billable = 1, -- pod.Billable,  -- Or 1?
			--@Markup = Markup,
			--@BillableCost = BillableCost,
			@LongDescription = pod.LongDescription,
			@CustomFieldKey = pod.CustomFieldKey,
			@DetailOrderDate = pod.DetailOrderDate,
			@DetailOrderEndDate = pod.DetailOrderEndDate,
			@UserDate1 = pod.UserDate1,
			@UserDate2 = pod.UserDate2,
			@UserDate3 = pod.UserDate3,
			@UserDate4 = pod.UserDate4,
			@UserDate5 = pod.UserDate5,
			@UserDate6 = pod.UserDate6,
			@OrderDays = pod.OrderDays,
			@OrderTime = pod.OrderTime,
			@OrderLength = pod.OrderLength,
			--@Taxable = pod.Taxable,
			--@Taxable2 = pod.Taxable2,
			@OfficeKey = pod.OfficeKey,
			@DepartmentKey = pod.DepartmentKey,
			@PCurrencyID = pod.PCurrencyID,
			@PExchangeRate = pod.PExchangeRate
		From tPurchaseOrderDetail pod (NOLOCK)
		Where pod.PurchaseOrderDetailKey = @PurchaseOrderDetailKey

	if @PExchangeRate = 0
		select @PExchangeRate = 1 -- Cannot divide by 0

	IF ISNULL(@CustomFieldKey,0) > 0
    BEGIN
		SELECT	@FieldSetKey = FieldSetKey
		FROM	tObjectFieldSet (NOLOCK)
		WHERE	ObjectFieldSetKey = @CustomFieldKey
		
		EXEC spCF_tObjectFieldSetInsert @FieldSetKey, @ObjectFieldSetKey OUTPUT
		
		IF ISNULL(@ObjectFieldSetKey,0) > 0
			INSERT	tFieldValue
					(FieldValueKey, FieldDefKey, ObjectFieldSetKey, FieldValue)
			SELECT	newid(), FieldDefKey, @ObjectFieldSetKey, FieldValue
			FROM	tFieldValue (NOLOCK)
			WHERE	ObjectFieldSetKey = @CustomFieldKey
    END
	ELSE
			SELECT @ObjectFieldSetKey = NULL


	Select @InsertReversal = 1

	IF @POKind = 2 AND @SpotPurchaseOrderDetailKey IS NULL AND @FlightInterval IN (1, 2)  AND @SpotDate is not null
	BEGIN
		-- We could not find the spot
		-- The user picked a date that was not used so far for that line
		-- We cannot do the reversal
		Select @InsertReversal = 0
		
		-- Now get the dates from the spot date entered by user
		SELECT @DetailOrderDate = @SpotDate
		IF @FlightInterval = 2 -- Weekly
			SELECT @DetailOrderEndDate = DATEADD(Day, 6, @DetailOrderDate)
		ELSE
			SELECT @DetailOrderEndDate = @DetailOrderDate
		
	END 

	IF @ShowAdjustmentsAsSingleLine = 1
	BEGIN
		-- Just copy what we have
		-- The quantity is the Net Difference
			
		-- need to recalc PTotalCost
		select @PTotalCost =  round( 
				(isnull(@ExchangeRate, 1) * @TotalCost) / isnull(@PExchangeRate, 1) 
					,2)

		EXEC @RetVal = sptPurchaseOrderDetailInsert 
			@PurchaseOrderKey = @PurchaseOrderKey,
			@LineNumber = @LineNumber,
			@ProjectKey = @ProjectKey,
			@TaskKey = @TaskKey,
			@ItemKey = @ItemKey,
			@ClassKey = @ClassKey,
			@ShortDescription = @ShortDescription,
			@Quantity = @Quantity,
			@UnitCost = @UnitCost,
			@UnitDescription = @UnitDescription,
			@TotalCost = @TotalCost,
			@UnitRate = NULL,
			@Billable = @Billable,
			@Markup = @Markup,
			@BillableCost = @BillableCost,
			@LongDescription = @LongDescription,
			@CustomFieldKey = @ObjectFieldSetKey,
			@DetailOrderDate = @DetailOrderDate,
			@DetailOrderEndDate = @DetailOrderEndDate,
			@UserDate1 = @UserDate1,
			@UserDate2 = @UserDate2,
			@UserDate3 = @UserDate3,
			@UserDate4 = @UserDate4,
			@UserDate5 = @UserDate5,
			@UserDate6 = @UserDate6,
			@OrderDays = @OrderDays,
			@OrderTime = @OrderTime,
			@OrderLength = @OrderLength,
			@Taxable = @Taxable,
			@Taxable2 = @Taxable2,
			@OfficeKey = @OfficeKey,
			@DepartmentKey = @DepartmentKey,
			@GrossAmount = @GrossAmount,
			@PCurrencyID = @PCurrencyID,
			@PExchangeRate = @PExchangeRate,
			@PTotalCost = @PTotalCost,
			@SkipRollUps = NULL,
			@InteractiveAdUnitName = NULL,
			@oIdentity = @NewPurchaseOrderDetailKey OUTPUT

		-- Check returns later !!!!!!!!
		IF @NewPurchaseOrderDetailKey IS NULL
			RETURN @RetVal
			
		SELECT @AdjustmentNumber = MAX(AdjustmentNumber)
		FROM   tPurchaseOrderDetail (NOLOCK)
		WHERE  PurchaseOrderKey = @PurchaseOrderKey
		AND    LineNumber = @LineNumber
		
		SELECT @AdjustmentNumber = ISNULL(@AdjustmentNumber, 0) + 1 
		
		UPDATE tPurchaseOrderDetail
		SET    MediaRevisionReasonKey = @MediaRevisionReasonKey
			  ,AdjustmentNumber = @AdjustmentNumber
			  ,GrossAmount = @GrossAmount
			  ,Quantity1 = @Quantity1
			  ,Quantity2 = @Quantity2
			  ,UnitRate = @UnitRate
			  ,Commission = @Commission

			  -- Removed by GHL 8/9/2017 because of the query in sptPurchaseOrderGet, we do not use the new media screens anymore
			  --,LineType = ''rev'' --only used by the new media screens, so it doesn''t hurt to always set it here

			  ,SalesTaxAmount = @SalesTaxAmount
			  ,SalesTax1Amount = @SalesTax1Amount
			  ,SalesTax2Amount = @SalesTax2Amount
			   
		WHERE  PurchaseOrderDetailKey = @NewPurchaseOrderDetailKey
	END

	IF @ShowAdjustmentsAsSingleLine = 0
	BEGIN
		-- We need to insert 2 rows, first is a reversal of the old one
		-- The second is a new amount
		
		If @InsertReversal = 1
		BEGIN
			SELECT 	@RevQuantity = Quantity * -1
					,@RevUnitCost = UnitCost
					,@RevMarkup = Markup
					,@RevTotalCost = TotalCost * -1
					,@RevBillableCost = BillableCost * -1
					,@RevGrossAmount = GrossAmount * -1
					,@RevQuantity1 = Quantity1 * - 1
					,@RevQuantity2 = Quantity2 * - 1
					,@RevUnitRate = UnitRate * - 1
					,@RevCommission = Commission
					,@RevSalesTaxAmount = SalesTaxAmount * -1
					,@RevSalesTax1Amount = SalesTax1Amount * -1
					,@RevSalesTax2Amount = SalesTax2Amount * -1

			FROM    tPurchaseOrderDetail (NOLOCK)
			WHERE   PurchaseOrderDetailKey = @PurchaseOrderDetailKey		

			if isnull(@RevSalesTax1Amount, 0) = 0
				select @RevTaxable = 0
			else
				select @RevTaxable = 1
			
			if isnull(@RevSalesTax2Amount, 0) = 0
				select @RevTaxable2 = 0
			else
				select @RevTaxable2 = 1

			/* This does not seem to work well with the UI and the new media screens
			-- Adjust IO Revisions with a Negative BillableCost
			IF @POKind = 1
			  IF @BillableCost < 0		        
					Select @BillableCost = (@RevBillableCost * -1) + @BillableCost
					      ,@TotalCost = @BillableCost  - (@BillableCost * (@Markup / 100))
						  
			-- Adjust BC Revisions with a Negative Quantity
			IF @POKind = 2
			  IF @Quantity < 0		        
					Select @Quantity = (@RevQuantity * -1) + @Quantity
					      ,@TotalCost = (@Quantity * @UnitCost) - ((@Quantity * @UnitCost) * (@Markup / 100))
						  ,@BillableCost = (@Quantity * @UnitCost)

			*/

		-- need to recalc PTotalCost
		select @PTotalCost =  round( 
				(isnull(@ExchangeRate, 1) * @RevTotalCost) / isnull(@PExchangeRate, 1) 
					,2)

			EXEC @RetVal = sptPurchaseOrderDetailInsert 
				@PurchaseOrderKey = @PurchaseOrderKey,
				@LineNumber = @LineNumber,
				@ProjectKey = @ProjectKey,
				@TaskKey = @TaskKey,
				@ItemKey = @ItemKey,
				@ClassKey = @ClassKey,
				@ShortDescription = @ShortDescription,
				@Quantity = @RevQuantity,
				@UnitCost = @RevUnitCost,
				@UnitDescription = @UnitDescription,
				@TotalCost = @RevTotalCost,
				@UnitRate = NULL,
				@Billable = @Billable,
				@Markup = @RevMarkup,
				@BillableCost = @RevBillableCost,
				@LongDescription = @LongDescription,
				@CustomFieldKey = @ObjectFieldSetKey,
				@DetailOrderDate = @DetailOrderDate,
				@DetailOrderEndDate = @DetailOrderEndDate,
				@UserDate1 = @UserDate1,
				@UserDate2 = @UserDate2,
				@UserDate3 = @UserDate3,
				@UserDate4 = @UserDate4,
				@UserDate5 = @UserDate5,
				@UserDate6 = @UserDate6,
				@OrderDays = @OrderDays,
				@OrderTime = @OrderTime,
				@OrderLength = @OrderLength,
				@Taxable = @RevTaxable,
				@Taxable2 = @RevTaxable2,
				@OfficeKey = @OfficeKey,
				@DepartmentKey = @DepartmentKey,
				@GrossAmount = @RevGrossAmount,
				@PCurrencyID = @PCurrencyID,
				@PExchangeRate = @PExchangeRate,
				@PTotalCost = @PTotalCost,
				@SkipRollUps = NULL,
				@InteractiveAdUnitName = NULL,
				@oIdentity = @NewPurchaseOrderDetailKey OUTPUT

			-- Check returns later !!!!!!!!
			IF @NewPurchaseOrderDetailKey IS NULL
				RETURN @RetVal
				
			SELECT @oIdentityReversal = @NewPurchaseOrderDetailKey

			SELECT @AdjustmentNumber = MAX(AdjustmentNumber)
			FROM   tPurchaseOrderDetail (NOLOCK)
			WHERE  PurchaseOrderKey = @PurchaseOrderKey
			AND    LineNumber = @LineNumber
			
			SELECT @AdjustmentNumber = ISNULL(@AdjustmentNumber, 0) + 1 
			
			UPDATE tPurchaseOrderDetail
			SET    MediaRevisionReasonKey = @MediaRevisionReasonKey
				  ,AdjustmentNumber = @AdjustmentNumber
				  ,GrossAmount = @RevGrossAmount
				  ,Quantity1 = @RevQuantity1
				  ,Quantity2 = @RevQuantity2
				  ,UnitRate = @RevUnitRate
				  ,Commission = @RevCommission

				  -- Removed by GHL 8/9/2017 because of the query in sptPurchaseOrderGet, we do not use the new media screens anymore
				  --,LineType = ''rev'' --only used by the new media screens, so it doesn''t hurt to always set it here
			
				  ,SalesTaxAmount = @RevSalesTaxAmount
				  ,SalesTax1Amount = @RevSalesTax1Amount
			      ,SalesTax2Amount = @RevSalesTax2Amount

				  -- added for the new media plans
				  ,ReversedKey = @PurchaseOrderDetailKey
			WHERE  PurchaseOrderDetailKey = @NewPurchaseOrderDetailKey
		
		END

		IF ISNULL(@CustomFieldKey,0) > 0
		BEGIN
			SELECT	@FieldSet2Key = FieldSetKey
			FROM	tObjectFieldSet (NOLOCK)
			WHERE	ObjectFieldSetKey = @CustomFieldKey
			
			EXEC spCF_tObjectFieldSetInsert @FieldSet2Key, @ObjectFieldSet2Key OUTPUT
			
			IF ISNULL(@ObjectFieldSet2Key,0) > 0
				INSERT	tFieldValue
						(FieldValueKey, FieldDefKey, ObjectFieldSetKey, FieldValue)
				SELECT	newid(), FieldDefKey, @ObjectFieldSet2Key, FieldValue
				FROM	tFieldValue (NOLOCK)
				WHERE	ObjectFieldSetKey = @CustomFieldKey
		END
		ELSE
			SELECT @ObjectFieldSet2Key = NULL
		
		SELECT @NewPurchaseOrderDetailKey = NULL
		

		-- need to recalc PTotalCost
		select @PTotalCost =  round( 
				(isnull(@ExchangeRate, 1) * @TotalCost) / isnull(@PExchangeRate, 1) 
					,2)

		-- Now insert the new amount 
		EXEC @RetVal = sptPurchaseOrderDetailInsert 
			@PurchaseOrderKey = @PurchaseOrderKey,
			@LineNumber = @LineNumber,
			@ProjectKey = @ProjectKey,
			@TaskKey = @TaskKey,
			@ItemKey = @ItemKey,
			@ClassKey = @ClassKey,
			@ShortDescription = @ShortDescription,
			@Quantity = @Quantity,
			@UnitCost = @UnitCost,
			@UnitDescription = @UnitDescription,
			@TotalCost = @TotalCost,
			@UnitRate = NULL,
			@Billable = @Billable,
			@Markup = @Markup,
			@BillableCost = @BillableCost,
			@LongDescription = @LongDescription,
			@CustomFieldKey = @ObjectFieldSet2Key,
			@DetailOrderDate = @DetailOrderDate,
			@DetailOrderEndDate = @DetailOrderEndDate,
			@UserDate1 = @UserDate1,
			@UserDate2 = @UserDate2,
			@UserDate3 = @UserDate3,
			@UserDate4 = @UserDate4,
			@UserDate5 = @UserDate5,
			@UserDate6 = @UserDate6,
			@OrderDays = @OrderDays,
			@OrderTime = @OrderTime,
			@OrderLength = @OrderLength,
			@Taxable = @Taxable,
			@Taxable2 = @Taxable2,
			@OfficeKey = @OfficeKey,
			@DepartmentKey = @DepartmentKey,
			@GrossAmount = @GrossAmount,
			@PCurrencyID = @PCurrencyID,
			@PExchangeRate = @PExchangeRate,
			@PTotalCost = @PTotalCost,
			@SkipRollUps = NULL,
			@InteractiveAdUnitName = NULL,
			@oIdentity = @NewPurchaseOrderDetailKey OUTPUT

		-- Check returns later !!!!!!!!
		IF @NewPurchaseOrderDetailKey IS NULL
			RETURN @RetVal
			
		SELECT @AdjustmentNumber = MAX(AdjustmentNumber)
		FROM   tPurchaseOrderDetail (NOLOCK)
		WHERE  PurchaseOrderKey = @PurchaseOrderKey
		AND    LineNumber = @LineNumber
		
		SELECT @AdjustmentNumber = ISNULL(@AdjustmentNumber, 0) + 1 
		
		UPDATE tPurchaseOrderDetail
		SET    MediaRevisionReasonKey = @MediaRevisionReasonKey
			  ,AdjustmentNumber = @AdjustmentNumber
			  ,GrossAmount = @GrossAmount
			  ,Quantity1 = @Quantity1
			  ,Quantity2 = @Quantity2
			  ,UnitRate = @UnitRate
			  ,Commission = @Commission
			 
			  -- Removed by GHL 8/9/2017 because of the query in sptPurchaseOrderGet, we do not use the new media screens anymore
			  --,LineType = ''rev'' --only used by the new media screens, so it doesn''t hurt to always set it here
		
		      ,SalesTaxAmount = @SalesTaxAmount
			  ,SalesTax1Amount = @SalesTax1Amount
			  ,SalesTax2Amount = @SalesTax2Amount
		WHERE  PurchaseOrderDetailKey = @NewPurchaseOrderDetailKey
				 						
	END

	SELECT @oIdentity = @NewPurchaseOrderDetailKey

	IF @SkipRollup = 0
		EXEC sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1
														
	RETURN 1




'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptMediaPlanDetailUpdateAccounting]'
GO
IF OBJECT_ID(N'[dbo].[sptMediaPlanDetailUpdateAccounting]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER procedure [dbo].[sptMediaPlanDetailUpdateAccounting]  
 (  
 @MediaPlanDetailKey int  
 )  
as --Encrypt  
/*  
|| When     Who Rel			What  
|| 07/22/19 GHL 19.080		Created for new media plans  
||							This procedure updates the PODs under an MPD (Media Plan Detail)  
||							This is done after updating the MPD and the MPD history   
|| 10/18/19 GHL 19.110		(484211) Get the POKind from the item, not the media plan  
|| 05/14/20 GHL 20.060		To create ErrMsgOrder cast @RetVal to string  
|| 08/12/22 QMD 22.09.18	(609307) added @SkipRollup flag 
|| 03/25/26 MAS 26.04.19	(725067) sptMediaPlanDetailUpdateAPIWorker was changed to only create MediaPlanDetailHistory if something changed. As a result
||                                   @PrevMediaPlanDetailHistoryKey may be NULL
|| 04/30/26 MAS 26.04.19	(727514) Restored history-based financial change detection after full API history creation was restored
*/  
  
/*  
 if POD is missing then   
     do nothing/i.e. wait for `Release to Billing/Accounting'' action  
  return  
 end if  
   
 determine if Financials have changed by comparing the 2 last records in MPD history  
  
 determine if the last POD is locked  
  
 set adjust values = new/current values by default  
  
 if Financials have changed AND POD is locked (prebilled or applied) then  
  if @ShowAdjustmentsAsSingleLine = 1   
   set adjust values = new/current values - old values  
  
  create revisions, create new POD  
 else  
  if Financials have changed  
   update Financials  
 end if  
   
 update other fields on last/unlocked POD  
*/  
  
-- if POD is missing wait for `Release to Billing/Accounting'' action  
if not exists (select 1 from tPurchaseOrderDetail (nolock)  
 where MediaPlanDetailKey = @MediaPlanDetailKey  
 )  
 return 1  
  

update tMediaPlanDetail  
set    ErrMsgOrder = null  
where  MediaPlanDetailKey = @MediaPlanDetailKey  
  
-- vars for the comparison of financials  
 declare @FinancialsChanged int   
   ,@ShowAdjustmentsAsSingleLine int  
   ,@POKind int  
   ,@CompanyKey int  
   ,@PurchaseOrderDetailKey int  
  
 declare @MediaPlanDetailHistoryKey int  -- current history key  
   ,@PrevMediaPlanDetailHistoryKey int -- previous history key  
  
 declare @OldQuantity decimal(24, 6)   
   ,@OldCost decimal(24, 6)   
   ,@OldUnitCost decimal(24, 6)   
   ,@OldMarkup decimal(24, 6)   
   ,@OldGross decimal(24, 6)   
   ,@OldAmountToBill decimal(24, 6)   
  
 declare @AdjustQuantity decimal(24, 6)   
   ,@AdjustCost decimal(24, 6)   
   ,@AdjustUnitCost decimal(24, 6)   
   ,@AdjustMarkup decimal(24, 6)   
   ,@AdjustGross decimal(24, 6)   
   ,@AdjustAmountToBill decimal(24, 6)   
  
-- vars for the PODs  
 declare @NewPurchaseOrderDetailKey int  
 declare @ReversedPurchaseOrderDetailKey int  
 declare @InvoiceLineKey int  
 declare @AppliedCost money  
 declare @Locked int  
 declare @RetVal int  
  
 declare @SpotLinkID varchar(50)   
  ,@StartDate smalldatetime   
  ,@EndDate smalldatetime   
  ,@Description varchar(max)  
  ,@OrderDays varchar(50)   
  ,@OrderTime varchar(50)   
  ,@OrderLength varchar(50)   
  ,@Date1 smalldatetime   
  ,@Date2 smalldatetime   
  ,@Quantity decimal(24, 6)   
  ,@Cost decimal(24, 6)   
  ,@UnitCost decimal(24, 6)   
  ,@Markup decimal(24, 6)   
  ,@Gross decimal(24, 6)   
  ,@AmountToBill decimal(24, 6)   
  ,@Status varchar(100)   
  ,@LineNumber int  
  
  -- var for the project / PO rollup  
 declare @ProjectKey int  
   ,@PurchaseOrderKey int  
  
 /*  
  determine if Financials have changed by comparing the 2 last records in MPD history  
 */  
  
 -- get current values  
 select @SpotLinkID = SpotLinkID   
  ,@StartDate = StartDate   
  ,@EndDate = EndDate   
  ,@Description = Description  
  ,@OrderDays = OrderDays   
  ,@OrderTime = OrderTime   
  ,@OrderLength = OrderLength    
  ,@Date1 = Date1   
  ,@Date2 = Date2   
  ,@Quantity = Quantity   
  ,@Cost = Cost   
  ,@UnitCost = UnitCost   
  ,@Markup = Markup   
  ,@Gross = Gross   
  ,@AmountToBill = AmountToBill   
  ,@Status = Status  
  ,@LineNumber = LineNumber  
 from  tMediaPlanDetail (nolock)  
 where MediaPlanDetailKey = @MediaPlanDetailKey  
  
 select  @CompanyKey = mp.CompanyKey   
   ,@ShowAdjustmentsAsSingleLine =   
   CASE   
    --WHEN mp.POKind = 1 THEN ISNULL(pref.IOShowAdjustmentsAsSingleLine, 1)  
    --WHEN mp.POKind = 2 THEN ISNULL(pref.BCShowAdjustmentsAsSingleLine, 1)  
    WHEN i.ItemType = 1 THEN ISNULL(pref.IOShowAdjustmentsAsSingleLine, 1)  
    WHEN i.ItemType = 2 THEN ISNULL(pref.BCShowAdjustmentsAsSingleLine, 1)  
    ELSE 1  
   END  
   ,@POKind = i.ItemType  
   ,@ProjectKey = mp.ProjectKey  
 from    tMediaPlanDetail mpd (nolock)  
  inner join tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey  
  inner join tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey  
  inner join tPreference pref (nolock) on mp.CompanyKey = pref.CompanyKey    
  inner join tItem i (nolock) on mpv.ItemKey = i.ItemKey  
 where   MediaPlanDetailKey = @MediaPlanDetailKey  
  
 -- get old values  
 select @MediaPlanDetailHistoryKey = max(MediaPlanDetailHistoryKey)  
 from   tMediaPlanDetailHistory (nolock)  
 where  MediaPlanDetailKey = @MediaPlanDetailKey  
  
 if isnull(@MediaPlanDetailHistoryKey, 0) > 0  
 begin  
  select @PrevMediaPlanDetailHistoryKey = max(MediaPlanDetailHistoryKey)  
  from   tMediaPlanDetailHistory (nolock)  
  where  MediaPlanDetailKey = @MediaPlanDetailKey  
  and    MediaPlanDetailHistoryKey < @MediaPlanDetailHistoryKey  
 end   
  
 select @FinancialsChanged = 0  
  
 select  @OldQuantity = mpd.Quantity   
   ,@OldCost = mpd.Cost   
   ,@OldUnitCost = mpd.UnitCost   
   ,@OldMarkup = mpd.Markup   
   ,@OldGross = mpd.Gross   
   ,@OldAmountToBill = mpd.AmountToBill   
 from    tMediaPlanDetailHistory mpd (nolock)    
 where   MediaPlanDetailHistoryKey = @PrevMediaPlanDetailHistoryKey  
  
 if isnull(@OldQuantity,0) <> isnull(@Quantity,0)  
  select @FinancialsChanged = 1  
 if isnull(@OldCost,0) <> isnull(@Cost,0)  
  select @FinancialsChanged = 1  
 if isnull(@OldUnitCost,0) <> isnull(@UnitCost,0)  
  select @FinancialsChanged = 1  
 if isnull(@OldMarkup,0) <> isnull(@Markup,0)  
  select @FinancialsChanged = 1  
 if isnull(@OldGross,0) <> isnull(@Gross,0)  
  select @FinancialsChanged = 1  
 if isnull(@OldAmountToBill,0) <> isnull(@AmountToBill,0)  
  select @FinancialsChanged = 1

 -- determine if the POD is locked  
  
 select @PurchaseOrderDetailKey = max(PurchaseOrderDetailKey)  
 from tPurchaseOrderDetail (nolock)  
 where MediaPlanDetailKey = @MediaPlanDetailKey  
  
 select @InvoiceLineKey = InvoiceLineKey  
   ,@AppliedCost =  AppliedCost   
   ,@PurchaseOrderKey = PurchaseOrderKey  
 from  tPurchaseOrderDetail (nolock)  
 where PurchaseOrderDetailKey = @PurchaseOrderDetailKey  
  
 if @InvoiceLineKey is not null Or @AppliedCost <> 0  
  select @Locked = 1  
 else  
  select @Locked = 0  

  

 -- by default the values to adjust = new/current values  
 select @AdjustQuantity = @Quantity   
   ,@AdjustCost = @Cost   
   ,@AdjustUnitCost = @UnitCost   
   ,@AdjustMarkup = @Markup   
   ,@AdjustGross = @Gross   
   ,@AdjustAmountToBill = @AmountToBill   
  
 --select  @FinancialsChanged as FinancialsChanged , @Locked as Locked  
  
 if @FinancialsChanged = 1 and @Locked = 1  
 begin  
  if @ShowAdjustmentsAsSingleLine = 1  
   begin  
    -- No reversal will be created, we muss pass in the Adjust value = Desired value - Original value  
    -- or Adjust value = New value - Old value  
    -- in other words, New value = Old value + Adjust value  
    if @POKind = 2 -- only for broadcast, the qty is always 1 for insertion orders  
     select @AdjustQuantity = isnull(@Quantity, 0) - isnull(@OldQuantity, 0)    
    select @AdjustCost = isnull(@Cost, 0) - isnull(@OldCost, 0)    
    select @AdjustGross = isnull(@Gross, 0) - isnull(@OldGross, 0)    
    select @AdjustAmountToBill = isnull(@AmountToBill, 0) - isnull(@OldAmountToBill, 0)    
  
    select @AdjustMarkup = [dbo].[fCommissionFromNetGross] (@AdjustCost, @AdjustGross)  
  
    -- The UnitCost is a rate, so calculate from the gross  
    if @AdjustQuantity = 0  
     select @AdjustUnitCost = 0  
    else  
     select @AdjustUnitCost = @AdjustGross/ @AdjustQuantity  
  
   end  
  -- else  
  -- A reversal line will be created, and a new POD for the new values passed in  
  -- end if  
  
  -- create a revision  

  exec @RetVal = sptPurchaseOrderDetailAdjust  
   @PurchaseOrderDetailKey = @PurchaseOrderDetailKey   
   ,@MediaRevisionReasonKey = null  
   ,@Quantity = @AdjustQuantity  
   ,@UnitCost = @AdjustUnitCost  
   ,@Markup = @AdjustMarkup  
   ,@TotalCost = @AdjustCost  
   ,@BillableCost = @AdjustAmountToBill  
   ,@SpotDate = null   
   ,@GrossAmount = @AdjustGross  
   ,@Quantity1  = null  
   ,@Quantity2  = null  
   ,@UnitRate = null  
   ,@Commission  = null  
   ,@AdjustmentsOptionFromPO  = 0  
   ,@Taxable  = 0  
   ,@Taxable2  = 0  
   ,@SalesTaxAmount  = 0  
   ,@SalesTax1Amount  = 0  
   ,@SalesTax2Amount  = 0  
   ,@oIdentity = @NewPurchaseOrderDetailKey Output  
   ,@oIdentityReversal = @ReversedPurchaseOrderDetailKey Output  
   ,@SkipRollup = 1

   if @RetVal < 0  
	begin 

    update tMediaPlanDetail   
    set    tMediaPlanDetail.ErrMsgOrder = ''Error adjusting an order (error '' + cast(@RetVal as varchar(20)) + '')''   
    where  MediaPlanDetailKey = @MediaPlanDetailKey  
     
    return -1  
   end  
  

  -- also update everything else on the last POD  
  
  -- and update the MPDkey  
  update tPurchaseOrderDetail   
  set MediaPlanDetailKey = @MediaPlanDetailKey  
  where PurchaseOrderDetailKey in (@NewPurchaseOrderDetailKey, @ReversedPurchaseOrderDetailKey)  
  
  -- now point to the last one (could have used @NewPurchaseOrderDetailKey)  
  select @PurchaseOrderDetailKey = max(PurchaseOrderDetailKey)  
  from tPurchaseOrderDetail (nolock)  
  where MediaPlanDetailKey = @MediaPlanDetailKey  
  
  -- and point to the last POD  
  update tMediaPlanDetail   
  set    tMediaPlanDetail.PurchaseOrderDetailKey = @PurchaseOrderDetailKey  
  where  MediaPlanDetailKey = @MediaPlanDetailKey  
  
 end --if @FinancialsChanged = 1 and @Locked = 1  
 else  
 begin  
  -- no need to create revisions  
  if @FinancialsChanged = 1  
  begin 

    -- We muss pass in the Adjust value = Desired value - sum(Original value on other PODs)  
  
    select @OldQuantity = sum(Quantity)  
          ,@OldCost = sum(TotalCost)  
       ,@OldGross = sum(GrossAmount)  
          ,@OldAmountToBill = sum(BillableCost)  
    from   tPurchaseOrderDetail (nolock)  
    where  MediaPlanDetailKey = @MediaPlanDetailKey   
    and    PurchaseOrderDetailKey <> @PurchaseOrderDetailKey  
  
    if @POKind = 2  
     select @AdjustQuantity = isnull(@Quantity, 0) - isnull(@OldQuantity, 0)    
      
    select @AdjustCost = isnull(@Cost, 0) - isnull(@OldCost, 0)    
    select @AdjustGross = isnull(@Gross, 0) - isnull(@OldGross, 0)    
    select @AdjustAmountToBill = isnull(@AmountToBill, 0) - isnull(@OldAmountToBill, 0)    
  
    select @AdjustMarkup = [dbo].[fCommissionFromNetGross] (@AdjustCost, @AdjustGross)  
  
    -- The UnitCost is a rate, so calculate from the gross  
    if @AdjustQuantity = 0  
     select @AdjustUnitCost = 0  
    else  
     select @AdjustUnitCost = @AdjustGross/ @AdjustQuantity  

    update tPurchaseOrderDetail  
    set    Quantity = isnull(@AdjustQuantity,0)  
       ,TotalCost = isnull(@AdjustCost,0)  
       ,UnitCost = isnull(@AdjustUnitCost,0)  
       ,Markup = isnull(@AdjustMarkup,0)  
       ,GrossAmount = isnull(@AdjustGross,0)  
       ,BillableCost = isnull(@AdjustAmountToBill,0)  
    where PurchaseOrderDetailKey = @PurchaseOrderDetailKey  
    
   exec sptPurchaseOrderRollupAmounts @PurchaseOrderKey  

  end  
 end  
  
 -- Now update the non financials  
 update tPurchaseOrderDetail  
   set    LinkID = @SpotLinkID  
      ,DetailOrderDate = @StartDate  
      ,DetailOrderEndDate = @EndDate  
      ,ShortDescription = @Description  
      ,OrderDays = @OrderDays  
      ,OrderTime = @OrderTime  
      ,OrderLength = @OrderLength  
      ,UserDate1 = @Date1  
      ,UserDate2 = @Date2  
   where PurchaseOrderDetailKey = @PurchaseOrderDetailKey  
  
return 1  
   
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptMediaPlanDetailDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptMediaPlanDetailDelete]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER procedure [dbo].[sptMediaPlanDetailDelete]
	(
	@MediaPlanDetailKey int
	)
	as
--Encrypt

 /*
  || When     Who Rel    What
  || 05/24/19 GHL 19.060 Created for new media plans 
  || 08/06/19 GHL 19.090 Reviewed the deletion logic
  ||              Prevent delete if WMJ tables have been created
  ||              Cascade delete MediaPlan tables
  || 09/19/19 GHL 19.100 After review with Greg
  ||              Prevent delete if MPVD records are created
  ||              If PODs created, null the cost and mark MPD as Deleted
  || 10/18/19 GHL 19.110 (484211) Get the POKind from the item, not the media plan
  || 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
  || 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName
  */
  declare @Delete int		select @Delete = 1
 
  if exists (select 1 from tPurchaseOrderDetail (nolock)
	  where  MediaPlanDetailKey = @MediaPlanDetailKey
	  )
	  select @Delete = 0 -- return -1 changed 9/19/19 

  -- restrict if there is a MP voucher detail
  if exists (select 1 from tMediaPlanVoucherDetail mpvd (nolock)
	 where  mpvd.MediaPlanDetailKey = @MediaPlanDetailKey
	 ) return -2


  -- cascade delete tMPVD, that could leave a tMPV record without details
  -- Removed 9/19/19, instead of cascade delete, we will restrict
  /*
   if exists (select 1 from tMediaPlanVoucherDetail mpvd (nolock)
	inner join tVoucherDetail vd (nolock) on mpvd.MediaPlanVoucherDetailKey = vd.MediaPlanVoucherDetailKey 
	where  mpvd.MediaPlanDetailKey = @MediaPlanDetailKey
	) return -2

  declare @MediaPlanVoucherDetailKey int
  
  select @MediaPlanVoucherDetailKey = -1
  while (1=1)
  begin
		select @MediaPlanVoucherDetailKey =  min(MediaPlanVoucherDetailKey)
		from   tMediaPlanVoucherDetail (nolock)
		where  MediaPlanDetailKey = @MediaPlanDetailKey
		and    MediaPlanVoucherDetailKey > @MediaPlanVoucherDetailKey
		
		if @MediaPlanVoucherDetailKey is null 		
			break

		exec sptMediaPlanVoucherDetailDelete @MediaPlanVoucherDetailKey
  end 
  */
  		
   if @Delete = 1
   begin
	  delete tMediaPlanDetail 
	  where  MediaPlanDetailKey = @MediaPlanDetailKey
   
	  return 1
   end

   -- PODs exist, we must make the cost = 0 so null them out

   update tMediaPlanDetail set Deleted = 1 
   where MediaPlanDetailKey = @MediaPlanDetailKey

   declare @PurchaseOrderDetailKey int
		,@NewPurchaseOrderDetailKey int
		,@POKind int
		,@SpotLinkID varchar(50) -- link to media plan detail ID
		,@Quantity decimal(24, 4)
		,@UnitCost money
		,@Markup decimal(24,4)
		,@TotalCost money
		,@BillableCost money
		,@GrossAmount money = null
		,@UnitRate money = null
		,@Taxable int
		,@Taxable2 int
		,@PTotalCost money
		,@AdjustmentNumber int
		,@RetVal int

   	-- Vars for POD capture							
	declare @PurchaseOrderKey int,
			@LineNumber int,
			@ProjectKey int,
			@TaskKey int,
			@ItemKey int,
			@ClassKey int,
			@ShortDescription varchar(max),
			@UnitDescription varchar(30),
			@Billable tinyint,
			@LongDescription varchar(max),
			@CustomFieldKey int,
			@DetailOrderDate smalldatetime,
			@DetailOrderEndDate smalldatetime,
			@UserDate1 smalldatetime,
			@UserDate2 smalldatetime,
			@UserDate3 smalldatetime,
			@UserDate4 smalldatetime,
			@UserDate5 smalldatetime,
			@UserDate6 smalldatetime,
			@OrderDays varchar(50),
			@OrderTime varchar(50),
			@OrderLength varchar(50),
			@OfficeKey int,
			@DepartmentKey int,
			@FieldSetKey int,
			@ObjectFieldSetKey int,
			@PCurrencyID varchar(3),
			@PExchangeRate decimal(24,7),
			@ExchangeRate decimal(24,7),
			@SalesTaxAmount money,
			@SalesTax1Amount money,
			@SalesTax2Amount money


		-- there are 2 ways to recalc the financials, 1 from tMediaPlanDetail, 2 from the tPurchaseOrderDetail recs
		-- option 2 might be the safest because we want to erase the WMJ recs

		select @POKind = i.ItemType --mp.POKind
			   ,@SpotLinkID = mpd.SpotLinkID
		from    tMediaPlanDetail mpd (nolock)
		inner join tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
		inner join tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey
		inner join tItem i (nolock) on mpv.ItemKey = i.ItemKey
		where   MediaPlanDetailKey = @MediaPlanDetailKey

		select @Quantity = sum(Quantity)
		      ,@TotalCost = sum(TotalCost) 
		      ,@GrossAmount = sum(GrossAmount)
			  ,@BillableCost = sum(BillableCost)
			  ,@SalesTaxAmount = sum(SalesTaxAmount)
			  ,@SalesTax1Amount = sum(SalesTax1Amount)
			  ,@SalesTax2Amount = sum(SalesTax2Amount)

		from  tPurchaseOrderDetail (nolock)
		where MediaPlanDetailKey = @MediaPlanDetailKey

		-- The UnitCost is a rate, so calculate from the gross
		-- for print, that should not be visible on the UI
		if @Quantity = 0
			select @UnitCost = 0
		else
			select @UnitCost = @GrossAmount/ @Quantity

		-- if print, qty = -1
		if @POKind = 1
			select @Quantity = -1

		if @SalesTax1Amount <> 0
			select Taxable = 1
		if @SalesTax2Amount <> 0
			select Taxable2 = 1

		-- we store the commission in tPurchaseOredrDetail.Markup
		select @Markup = [dbo].[fCommissionFromNetGross] (@TotalCost, @GrossAmount)

		-- reverse everything to null/delete the MPD
		select @TotalCost = -1 *  @TotalCost
		      ,@GrossAmount = -1 *  @GrossAmount
			  ,@BillableCost = -1 *  @BillableCost
			  ,@SalesTaxAmount = -1 *  @SalesTaxAmount
			  ,@SalesTax1Amount = -1 *  @SalesTax1Amount
			  ,@SalesTax2Amount = -1 *  @SalesTax2Amount

		-- if there is nothing to reverse, abort
		if @TotalCost = 0 and @GrossAmount = 0 and @BillableCost = 0 and @SalesTax1Amount = 0 and @SalesTax2Amount = 0
			return 1

		select @PurchaseOrderDetailKey = min(PurchaseOrderDetailKey)
		from  tPurchaseOrderDetail (nolock)
		where MediaPlanDetailKey = @MediaPlanDetailKey

	-- Get a copy of the detail record 	
	Select  @PurchaseOrderKey = pod.PurchaseOrderKey,
			@LineNumber = pod.LineNumber,
			@ProjectKey = pod.ProjectKey,
			@TaskKey = pod.TaskKey,
			@ItemKey = pod.ItemKey,
			@ClassKey = pod.ClassKey,
			@ShortDescription = pod.ShortDescription,
			--@Quantity decimal(24,4),
			--@UnitCost money,
			@UnitDescription = pod.UnitDescription,
			--@TotalCost = TotalCost,
			@Billable = 1, -- pod.Billable,  -- Or 1?
			--@Markup = Markup,
			--@BillableCost = BillableCost,
			@LongDescription = pod.LongDescription,
			@CustomFieldKey = pod.CustomFieldKey,
			@DetailOrderDate = pod.DetailOrderDate,
			@DetailOrderEndDate = pod.DetailOrderEndDate,
			@UserDate1 = pod.UserDate1,
			@UserDate2 = pod.UserDate2,
			@UserDate3 = pod.UserDate3,
			@UserDate4 = pod.UserDate4,
			@UserDate5 = pod.UserDate5,
			@UserDate6 = pod.UserDate6,
			@OrderDays = pod.OrderDays,
			@OrderTime = pod.OrderTime,
			@OrderLength = pod.OrderLength,
			--@Taxable = pod.Taxable,
			--@Taxable2 = pod.Taxable2,
			@OfficeKey = pod.OfficeKey,
			@DepartmentKey = pod.DepartmentKey,
			@PCurrencyID = pod.PCurrencyID,
			@PExchangeRate = pod.PExchangeRate
		From tPurchaseOrderDetail pod (NOLOCK)
		Where pod.PurchaseOrderDetailKey = @PurchaseOrderDetailKey

		
	if @PExchangeRate = 0
		select @PExchangeRate = 1 -- Cannot divide by 0

	IF ISNULL(@CustomFieldKey,0) > 0
    BEGIN
		SELECT	@FieldSetKey = FieldSetKey
		FROM	tObjectFieldSet (NOLOCK)
		WHERE	ObjectFieldSetKey = @CustomFieldKey
		
		EXEC spCF_tObjectFieldSetInsert @FieldSetKey, @ObjectFieldSetKey OUTPUT
		
		IF ISNULL(@ObjectFieldSetKey,0) > 0
			INSERT	tFieldValue
					(FieldValueKey, FieldDefKey, ObjectFieldSetKey, FieldValue)
			SELECT	newid(), FieldDefKey, @ObjectFieldSetKey, FieldValue
			FROM	tFieldValue (NOLOCK)
			WHERE	ObjectFieldSetKey = @CustomFieldKey
    END
	ELSE
			SELECT @ObjectFieldSetKey = NULL

	-- need to recalc PTotalCost
		select @PTotalCost =  round( 
				(isnull(@ExchangeRate, 1) * @TotalCost) / isnull(@PExchangeRate, 1) 
					,2)

		/*
		Note: Markup stores the commission
		      UnitCost  stores the UnitRate
		*/

		EXEC @RetVal = sptPurchaseOrderDetailInsert 
			@PurchaseOrderKey = @PurchaseOrderKey,
			@LineNumber = @LineNumber,
			@ProjectKey = @ProjectKey,
			@TaskKey = @TaskKey,
			@ItemKey = @ItemKey,
			@ClassKey = @ClassKey,
			@ShortDescription = @ShortDescription,
			@Quantity = @Quantity,
			@UnitCost = @UnitCost,
			@UnitDescription = @UnitDescription,
			@TotalCost = @TotalCost,
			@UnitRate = NULL,
			@Billable = @Billable,
			@Markup = @Markup,
			@BillableCost = @BillableCost,
			@LongDescription = @LongDescription,
			@CustomFieldKey = @ObjectFieldSetKey,
			@DetailOrderDate = @DetailOrderDate,
			@DetailOrderEndDate = @DetailOrderEndDate,
			@UserDate1 = @UserDate1,
			@UserDate2 = @UserDate2,
			@UserDate3 = @UserDate3,
			@UserDate4 = @UserDate4,
			@UserDate5 = @UserDate5,
			@UserDate6 = @UserDate6,
			@OrderDays = @OrderDays,
			@OrderTime = @OrderTime,
			@OrderLength = @OrderLength,
			@Taxable = @Taxable,
			@Taxable2 = @Taxable2,
			@OfficeKey = @OfficeKey,
			@DepartmentKey = @DepartmentKey,
			@GrossAmount = @GrossAmount,
			@PCurrencyID = @PCurrencyID,
			@PExchangeRate = @PExchangeRate,
			@PTotalCost = @PTotalCost,
			@SkipRollUps = NULL,
			@InteractiveAdUnitName = NULL,
			@oIdentity = @NewPurchaseOrderDetailKey OUTPUT

		IF @NewPurchaseOrderDetailKey IS NULL
			RETURN -1
			
		SELECT @AdjustmentNumber = MAX(AdjustmentNumber)
		FROM   tPurchaseOrderDetail (NOLOCK)
		WHERE  PurchaseOrderKey = @PurchaseOrderKey
		AND    LineNumber = @LineNumber
		
		SELECT @AdjustmentNumber = ISNULL(@AdjustmentNumber, 0) + 1 
		
		UPDATE tPurchaseOrderDetail
		SET    AdjustmentNumber = @AdjustmentNumber
			  ,Commission = @Markup
			  ,SalesTaxAmount = @SalesTaxAmount
			  ,SalesTax1Amount = @SalesTax1Amount
			  ,SalesTax2Amount = @SalesTax2Amount

			  -- link POD to MPD
			  ,MediaPlanDetailKey = @MediaPlanDetailKey
			  ,LinkID = @SpotLinkID
		WHERE  PurchaseOrderDetailKey = @NewPurchaseOrderDetailKey

		Update tPurchaseOrder
		set    Closed = 0
		WHERE  PurchaseOrderKey = @PurchaseOrderKey
    

  return 1'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptMediaPlanDetailUpdateAPIWorker]'
GO
IF OBJECT_ID(N'[dbo].[sptMediaPlanDetailUpdateAPIWorker]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER procedure [dbo].[sptMediaPlanDetailUpdateAPIWorker]    
 (    
	@CompanyKey INT,
	@MediaPlanKey INT,
	@PlanID VARCHAR(50), 
	@Timestamp INT
 )    
AS    
--Encrypt    
    
  /*    
  || When     Who	Rel			What    
  || 08/04/22 QMD	22.09.17	(609307) Created for media plans.  Took the procs Gil did and made it set based.
  || 08/19/22 QMD	22.09.17	(609307) Fix issue for new media plans
  || 06/21/23 MAS	23.07.16	Removed Old Media tables
  || 09/10/23 MAS	23.10.16	(646370) Added TimeStamp
  || 01/22/24 MAS	24.01.21	(661977) Added StationID to the "Update worker table with the newly created MediaPlanVendorKey" update
  || 06/22/24 MAS	24.06.16	(669638) Added sptMediaPlanDetailDelete
  || 09/27/24 MAS	24.10.20	(683656) Ensure that when setting the MediaPlanVendorKey, the ItemKey is also considered to account for scenarios where a vendor has multiple items. 
								Previously, only one vendor was included when creating mediaPlanDetail lines, even though tMediaPlanVendor records 
								were correctly created for all items associated with that vendor.
  || 11/12/24 MAS	24.11.17	(684125) Fixed the sort order when determining the LineNumbers
  || 09/04/25 MAS	25.09.21	(708512) Added error messages when deleting MediaPlanDetail line
  || 10/07/25 MAS	25.11.??	(712850) Added error messages when an existing SpotLinkID is sent over attached to a different Order
  || 10/09/25 MAS	25.09.21	Added @InitialMediaPlanKey to eliminate possible PRIMARY KEY violations on tMediaPlanDetailWorker
  || 12/01/25 MAS	26.12.14	(717669) Retain the original LineNumber when creating MediaPlanDetailHistory records & Only create MediaPlanDetailHistory records when something changes
  || 04/23/25 MAS	26.04.19	(727087) Restored sptMediaPlanDetailUpdateAPIWorker to use the legacy -69 placeholder for new media plan worker rows
  || 04/30/26 MAS	26.04.19	(727514) Restored full history creation for API updates; removed unused @InitialMediaPlanKey
  */    

  /*    
  The structure for tMediaPlan/tMediaPlanVendor/tMediaPlanDetail has 3 levels    
  But the API only has 2 levels, so this stored proc for the API will create the intermediate level    
  tMediaPlanVendor and call the regular sptMediaPlanDetailUpdate    
  */    

    
  -- since the API now updates records based on the ID, rather than on the keys    
  -- it could happen that the keys do not belong to the same plan    

  	PRINT ''--------------------------''
	PRINT '' Starting ''
	PRINT ''--------------------------''
	PRINT ''''
	PRINT GETDATE()	

	/* *******************************************************************************
		If new Media Orders need to update the mediaplankey 
		-69 is used for new orders along with the mediaplanid
	   ******************************************************************************* */
	IF NOT EXISTS (	
					SELECT	1
					FROM	tMediaPlanDetailWorker mpw (NOLOCK)
					WHERE	mpw.CompanyKey = @CompanyKey 
							AND mpw.MediaPlanKey = @MediaPlanKey
							AND mpw.Timestamp = @Timestamp
				   )
		BEGIN
			UPDATE	mpw
			SET		mpw.MediaPlanKey = @MediaPlanKey
			FROM	tMediaPlanDetailWorker mpw (NOLOCK)
			WHERE	mpw.CompanyKey = @CompanyKey
					AND mpw.MediaPlanID = @PlanID
					AND mpw.MediaPlanKey = -69
		END 

	/* *******************************************************************************
		A SpotLinkID can ONLY ever be associated with one OrderLinkID
	   ******************************************************************************* */
	IF EXISTS (    
			SELECT	1
			FROM	tMediaPlanDetailWorker mpw (NOLOCK)
					INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.SpotLinkID = mpd.SpotLinkID  
			WHERE	mpw.CompanyKey = @CompanyKey
					AND mpw.Timestamp = @Timestamp							
					AND mpw.OrderLinkID <> mpd.OrderLinkID
			)
			RETURN -3 


	/* *******************************************************************************
		Update MediaPlanDetailKey
	   ******************************************************************************* */

	UPDATE	mpw
	SET		mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey   
	--SELECT	mpd.MediaPlanDetailKey, *
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlan mp (NOLOCK) ON mpw.MediaPlanKey = mp.MediaPlanKey
				INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mp.MediaPlanKey = mpv.MediaPlanKey    
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpv.MediaPlanVendorKey = mpd.MediaPlanVendorKey    
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND mpw.MediaPlanDetailKey <= -1000
			--AND mp.MediaPlanKey = @MediaPlanKey  
			AND  upper(rtrim(ltrim(mpd.SpotLinkID))) = upper(rtrim(ltrim(mpw.SpotLinkID)))    

  
  
/* *******************************************************************************
	Update ItemID
   ******************************************************************************* */
   	
	PRINT ''--------------------------''
	PRINT ''Update Item''
	PRINT ''--------------------------''
	PRINT ''''

	UPDATE	mpw
	SET		mpw.ItemKey = i.ItemKey
	--SELECT	mpw.ItemKey, mpw.MediaPlanDetailKey, i.ItemKey
	FROM	tMediaPlanDetailWorker mpw (NOLOCK) INNER JOIN tItem i (NOLOCK) ON mpw.ItemID = i.ItemID AND i.CompanyKey = @CompanyKey
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND i.ItemType = CASE WHEN -1 >= 0 THEN -1 ELSE i.ItemType END
		
	UPDATE	mpw
	SET		mpw.ItemKey = i.ItemKey
	--SELECT	mpw.ItemKey, mpw.MediaPlanDetailKey, i.ItemKey
	FROM	tMediaPlanDetailWorker mpw (NOLOCK) INNER JOIN tItem i (NOLOCK) ON mpw.ItemID = i.ItemID AND i.CompanyKey = @CompanyKey
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND i.ItemName = mpw.ItemID
			AND i.ItemType = CASE WHEN -1 >= 0 THEN -1 ELSE i.ItemType END
			AND ISNULL(mpw.ItemKey,0) = 0

/* *******************************************************************************
	Check for invalid PO types
	Mark invalid
   ******************************************************************************* */
	UPDATE	mpw
	SET		mpw.ErrMsg = ''Invalid item, items can only be 1 (Print) or 2 (Broadcast)''
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK) INNER JOIN tItem i (NOLOCK) ON mpw.ItemKey = i.ItemKey
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND i.ItemType NOT IN (1,2)


/* *******************************************************************************
	Get Vendor - sptCompanyMediaGet
   ******************************************************************************* */
	
	PRINT ''--------------------------''
	PRINT '' Get and Set Vendor''
	PRINT ''--------------------------''
	PRINT ''''

	--------------------------------------
	-- PART 1/2 No Vendor in Worker Table
	--------------------------------------

	UPDATE	mpw
	SET		mpw.VendorID = c.VendorID, mpw.VendorKey = cm.VendorKey
	-- SELECT	*
	FROM 	tMediaPlanDetailWorker mpw (NOLOCK)
			INNER JOIN tCompanyMedia cm (nolock) ON mpw.StationKey = cm.CompanyMediaKey
			INNER JOIN tCompany c (nolock) ON cm.VendorKey = c.CompanyKey 
			--LEFT JOIN tUser u (nolock) on cm.VendorContactKey = u.UserKey
			--LEFT JOIN tUser u2 (nolock) on c.PrimaryContact = u2.UserKey
			--LEFT JOIN tMediaMarket mm (nolock) ON cm.MediaMarketKey = mm.MediaMarketKey 	
			--LEFT JOIN tItem i (nolock) on cm.ItemKey = i.ItemKey
			--LEFT JOIN tSalesTax st (nolock) on cm.SalesTaxKey = st.SalesTaxKey
			--LEFT JOIN tSalesTax st2 (nolock) on cm.SalesTax2Key = st2.SalesTaxKey

	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND mpw.VendorID IS NULL

	--------------------------------------
	-- PART 2/2 Worker table Has Vendor - sptCompanyValidVendor
	--------------------------------------

	-- Changed the rule to only update active vendors
	-- All inactive vendors will be marked with an error

	UPDATE	mpw
	SET		mpw.VendorKey = c.CompanyKey
	-- SELECT	c.CompanyKey, *
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tCompany c (NOLOCK) ON mpw.CompanyKey = c.OwnerCompanyKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND mpw.VendorID = c.VendorID
			AND c.Vendor = 1
			AND mpw.VendorID IS NOT NULL
			AND mpw.VendorKey IS NULL
			AND c.Active = 1

	UPDATE	mpw
	SET		mpw.ErrMsg = ''Inactive vendor''
	--  SELECT	c.CompanyKey, *
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tCompany c (NOLOCK) ON mpw.CompanyKey = c.OwnerCompanyKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND mpw.VendorID = c.VendorID
			AND c.Vendor = 1
			AND c.Active = 0

		

	IF EXISTS (    
				SELECT	1
				FROM	tMediaPlanDetailWorker mpw (NOLOCK)
							INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
							INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey    
							INNER JOIN tMediaPlan mp (NOLOCK) ON mpv.MediaPlanKey = mp.MediaPlanKey    
				WHERE	mpw.CompanyKey = @CompanyKey
						AND mpw.MediaPlanKey = @MediaPlanKey
						AND mpw.Timestamp = @Timestamp
						AND mpw.MediaPlanDetailKey > 0
						AND mpw.MediaPlanKey <> mp.MediaPlanKey
				)
				RETURN -1


/* *******************************************************************************
	Get StationKey - sptCompanyMediaValidID
   ******************************************************************************* */
   	
	PRINT ''--------------------------''
	PRINT ''Get Station ''
	PRINT ''--------------------------''
	PRINT ''''

	UPDATE	mpw
	SET		mpw.StationKey = cm.CompanyMediaKey
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tCompanyMedia cm (NOLOCK) ON mpw.VendorKey = cm.VendorKey
				INNER JOIN tItem i (NOLOCK) ON mpw.ItemKey = i.ItemKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND cm.MediaKind = i.ItemType
			AND mpw.StationID = cm.StationID
			AND mpw.VendorID IS NULL

	UPDATE	mpw
	SET		mpw.StationKey = cm.CompanyMediaKey
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tCompanyMedia cm (NOLOCK) ON mpw.VendorKey = cm.VendorKey
				INNER JOIN tCompany c (NOLOCK) ON c.CompanyKey = cm.VendorKey
				INNER JOIN tItem i (NOLOCK) ON mpw.ItemKey = i.ItemKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND cm.MediaKind = i.ItemType
			AND c.VendorID = mpw.VendorID
			AND mpw.StationID = cm.StationID
			AND mpw.VendorID IS NOT NULL

/* *******************************************************************************
	Update MediaPlanVendorKey where is null or less than equal to 0 - sptMediaPlanDetailUpdateAPI
   ******************************************************************************* */
	UPDATE	mpw
	SET		mpw.MediaPlanVendorKey = mpv.MediaPlanVendorKey
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)

			-- Ensure that when setting the MediaPlanVendorKey, the ItemKey is also considered to account for scenarios where a vendor has multiple items. 
			-- Previously, only one vendor was included when creating mediaPlanDetail lines, even though tMediaPlanVendor records were correctly created for all items associated with that vendor.
			INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpw.MediaPlanKey = mpv.MediaPlanKey AND mpw.ItemKey = mpv.ItemKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanVendorKey,0) <=0	
		
			AND ISNULL(mpw.VendorKey,0) = ISNULL(mpv.VendorKey,0)
			AND ISNULL(mpw.ItemKey,0) = ISNULL(mpv.ItemKey,0)
			AND ISNULL(mpw.StationKey,0) = ISNULL(mpv.StationKey,0)
		
			AND ISNULL(mpw.VendorID,'''') = ISNULL(mpv.VendorID,'''')
			AND ISNULL(mpw.ItemID,'''') = ISNULL(mpv.ItemLinkID,'''')
			AND ISNULL(mpw.StationID,'''') = ISNULL(mpv.StationID,'''')
  
  
 /* *******************************************************************************
	Update tMediaPlanVendor - sptMediaPlanVendorUpdate
   ******************************************************************************* */
	
	PRINT ''--------------------------''
	PRINT ''Update tMediaPlanVendor''
	PRINT ''--------------------------''
	PRINT ''''
	--------------------------------------
	-- validate the item
	--------------------------------------
	--IF EXISTS (
	--			SELECT	1
	--			FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	--						INNER JOIN tItem i (NOLOCK) ON mpw.ItemKey = i.ItemKey AND i.ItemType NOT IN (1,2)
	--			WHERE	mpw.CompanyKey = @CompanyKey
	--					AND mpw.MediaPlanKey = @MediaPlanKey
	--					AND ISNULL(mpw.ItemKey,0) > 0 -- API call may have no item 
	--		  )
	--		  RETURN -1 


	--------------------------------------
	-- on an update, and PODs have been created we really need an item
	--------------------------------------	
	IF EXISTS (
				SELECT	1
				FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				WHERE	mpw.CompanyKey = @CompanyKey
						AND mpw.MediaPlanKey = @MediaPlanKey
						AND mpw.Timestamp = @Timestamp
						AND MediaPlanVendorKey > 0 						
						AND ISNULL(ItemKey, 0) = 0
						AND EXISTS (
									SELECT	1 
									FROM	tMediaPlanDetail mpd (NOLOCK)
											INNER JOIN tPurchaseOrderDetail pod (NOLOCK) ON pod.MediaPlanDetailKey = mpd.MediaPlanDetailKey
									WHERE	mpd.MediaPlanVendorKey = mpw.MediaPlanVendorKey
									)
			  )
			  RETURN -1

	--------------------------------------
	-- on an update, and PODs have been created we really need an item
	--------------------------------------		
	UPDATE	mpw
	SET		mpw.ItemType = i.ItemType
	--SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tItem i (NOLOCK) ON mpw.ItemKey = i.ItemKey 
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.ItemKey,0) > 0
		
	--------------------------------------
	-- on an update, and PODs have been created we really need an item
	--------------------------------------	
	UPDATE	mpw
	SET		mpw.MediaKind = i.MediaKind
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tCompanyMedia i (NOLOCK) ON mpw.StationKey = i.CompanyMediaKey
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.StationKey,0) > 0

	--------------------------------------
	-- on an update, and PODs have been created we really need an item
	--------------------------------------	
	IF EXISTS (
				SELECT	1
				FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				WHERE	mpw.CompanyKey = @CompanyKey 
						AND mpw.MediaPlanKey = @MediaPlanKey
						AND mpw.Timestamp = @Timestamp
						AND	ISNULL(mpw.ItemKey,0) > 0
						AND ISNULL(mpw.StationKey,0) > 0
						AND ISNULL(mpw.ItemType,0) <> ISNULL(mpw.MediaKind,0)
			  )
			  RETURN -2

	--------------------------------------
	-- Error Checks 
	--------------------------------------	

	PRINT ''--------------------------''
	PRINT ''Error Checks''
	PRINT ''--------------------------''
	PRINT ''''

	-- is there a composite key? do we check uniqueness of MediaPlanKey/VendorKey/StationKey/ItemKey?
	UPDATE	mpw
	SET		ErrMsg = ''Invalid Vendor. ''
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.VendorKey, 0) = 0

	UPDATE	mpw
	SET		ErrMsg = ErrMsg + ''Invalid Item. ''
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.ItemKey, 0) = 0

	UPDATE	mpw
	SET		ErrMsg = ErrMsg + ''Invalid Station/Publication. ''
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.StationKey, 0) = 0


   	--------------------------------------
	-- Update tMediaPlanVendor
	--
	-- complete the update before the insert
	-- so that we can then update the mediaplanvendorkeys
	--------------------------------------	
	
	PRINT ''--------------------------''
	PRINT ''Insert tMediaPlanDetail''
	PRINT ''--------------------------''
	PRINT ''''

	UPDATE	mpv
	SET		MediaPlanKey	= mpw.MediaPlanKey
			,VendorID		= mpw.VendorID
			,VendorKey		= mpw.VendorKey
			,StationID		= mpw.StationID
			,StationKey		= mpw.StationKey
			,ItemLinkID		= mpw.ItemID
			,ItemKey		= mpw.ItemKey
			,ErrMsg			= mpw.ErrMsg
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpw.MediaPlanVendorKey = mpv.MediaPlanVendorKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanVendorKey,0) > 0

   	--------------------------------------
	-- Insert into MediaPlanVendor
	--------------------------------------	
	
	PRINT ''--------------------------''
	PRINT ''Insert tMediaPlanVendor''
	PRINT ''--------------------------''
	PRINT ''''

	INSERT INTO tMediaPlanVendor
			([MediaPlanKey]
			,[VendorID]
			,[VendorKey]
			,[StationID]
			,[StationKey]
			,[ItemLinkID]
			,[ItemKey]
			,[ErrMsg])
	SELECT  DISTINCT 
			mpw.MediaPlanKey
			,mpw.VendorID
			,mpw.VendorKey 
			,mpw.StationID 
			,mpw.StationKey
			,mpw.ItemID
			,mpw.ItemKey
			,mpw.ErrMsg
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(MediaPlanVendorKey,0) <= 0

	
 	--------------------------------------
	-- Update worker table with the newly
	-- created MediaPlanVendorKey
	--------------------------------------		
	--Q-DO -- Figure a way to update the identity in the worker table.   Might be able to join on the vendorID  to get the key and update the mediaplanvendorkey in the worker table.

	UPDATE	mpw 
	SET		mpw.MediaPlanVendorKey = mpv.MediaPlanVendorKey
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpv.MediaPlanKey = mpw.MediaPlanKey 
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanVendorKey,0) <= 0
			AND mpw.VendorID = mpv.VendorID
			AND mpw.StationID = mpv.StationID
			AND mpw.ItemKey = mpv.ItemKey
 

 /* *******************************************************************************
	Update tMediaPlanDetail - sptMediaPlanDetailUpdate
   ******************************************************************************* */    
	--------------------------------------
	-- POKind - Update the itemtype/pokind
	--------------------------------------	 
	PRINT ''--------------------------''
	PRINT ''POKind''
	PRINT ''--------------------------''
	PRINT ''''

	UPDATE	mpw
	SET		mpw.ItemType = i.ItemType
	--SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpw.MediaPlanVendorKey = mpv.MediaPlanVendorKey
				INNER JOIN tMediaPlan mp (NOLOCK) ON mpv.MediaPlanKey = mp.MediaPlanKey
				INNER JOIN tItem i (NOLOCK) ON mpv.ItemKey = i.ItemKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			

	--------------------------------------
	-- The SpotLinkID is a cross reference to the external system
	--------------------------------------	 
	
	PRINT ''--------------------------''
	PRINT ''SpotLinkID''
	PRINT ''--------------------------''
	PRINT ''''

	IF EXISTS (
				SELECT	1
				FROM	tMediaPlanDetailWorker mpw (NOLOCK)
							INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
							INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
							INNER JOIN tMediaPlan mp (NOLOCK) ON mpv.MediaPlanKey = mp.MediaPlanKey
				WHERE	mpw.CompanyKey = @CompanyKey
						AND mpw.MediaPlanKey = @MediaPlanKey
						AND mpw.Timestamp = @Timestamp
						AND mp.CompanyKey = @CompanyKey
						AND mpd.MediaPlanDetailKey <> ISNULL(mpw.MediaPlanDetailKey, 0)
						AND mpd.SpotLinkID = mpw.SpotLinkID
			  )
			  RETURN -4


	PRINT ''--------------------------''
	PRINT '' Set Start and End dates''
	PRINT ''--------------------------''
	PRINT ''''

	--------------------------------------
	-- Set null startdate
	--------------------------------------	
	UPDATE	mpw
	SET		StartDate = [dbo].[fFormatDateNoTime](getdate())
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND mpw.StartDate IS NULL

	--------------------------------------
	-- Set null enddate
	--------------------------------------	
	UPDATE	mpw
	SET		EndDate = [dbo].[fFormatDateNoTime](getdate())
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND mpw.EndDate IS NULL
			AND mpw.ItemType = 2  -- this is POKind


	--------------------------------------
	-- Set line number
	--------------------------------------	

	PRINT ''--------------------------''
	PRINT '' Set Line Numbers''
	PRINT ''--------------------------''
	PRINT ''''

	DECLARE @NextNumber INT 

	SELECT	@NextNumber = ISNULL(MAX(mpd.LineNumber),0)
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanVendorKey = mpd.MediaPlanVendorKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp

	UPDATE	mp
	SET		mp.LineNumber = m.Row
	--SELECT	m.Row, *
	FROM	(
			SELECT	ROW_NUMBER() OVER(ORDER BY ISNULL(mpw.LineNumber,1) ASC) + @NextNumber AS Row, mpw.CompanyKey, mpw.MediaPlanKey, mpw.MediaPlanDetailKey	
			FROM	tMediaPlanDetailWorker mpw (NOLOCK)
			WHERE	mpw.CompanyKey = @CompanyKey 
					AND mpw.MediaPlanKey = @MediaPlanKey
					AND mpw.Timestamp = @Timestamp
			) m, tMediaPlanDetailWorker mp
	WHERE	mp.CompanyKey = @CompanyKey
			AND mp.MediaPlanKey = @MediaPlanKey
			AND mp.MediaPlanDetailKey = m.MediaPlanDetailKey
					
	
	--------------------------------------
	-- Update tMediaPlanDetail
	--------------------------------------	

	PRINT ''--------------------------''
	PRINT ''Update tMediaPlanDetail''
	PRINT ''--------------------------''
	PRINT ''''

	-- if an order was created, do not change the Order Link ID		
	UPDATE	mpw
	SET		mpw.OrderLinkID = mpd.OrderLinkID
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
				INNER JOIN tPurchaseOrderDetail pod (NOLOCK) ON mpd.MediaPlanDetailKey = pod.MediaPlanDetailKey
	WHERE	mpw.CompanyKey = @CompanyKey 
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp


	-- create temp table for account call below
	SELECT	mpw.CompanyKey, mpw.MediaPlanKey, mpw.MediaPlanDetailKey, ROW_NUMBER() OVER(ORDER BY ISNULL(mpw.LineNumber,1) DESC) AS RowNumber
	INTO	#MediaPlanDetailUpdateAccounting
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanDetailKey,0) > 0
			AND ISNULL(mpw.Deleted, 0 ) = 0

	UPDATE	tMediaPlanDetail
	SET		MediaPlanVendorKey	= mpw.MediaPlanVendorKey
			,SpotLinkID			= mpw.SpotLinkID
			,StartDate			= mpw.StartDate
			,EndDate			= mpw.EndDate
			,[Description]		= mpw.[Description]
			,OrderDays			= mpw.OrderDays
			,OrderTime			= mpw.OrderTime
			,OrderLength		= mpw.OrderLength
			,Date1				= mpw.Date1
			,Date2				= mpw.Date2
			,Quantity			= mpw.Quantity
			,Cost				= mpw.Cost
			,UnitCost			= mpw.UnitCost
			,Markup				= mpw.Markup
			,Gross				= mpw.Gross
			,AmountToBill		= mpw.AmountToBill
			,DateModified		= GETUTCDATE()
			,[Status]			= mpw.[Status]
			,OrderLinkID		= mpw.OrderLinkID
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanDetailKey,0) > 0
	

	--------------------------------------
	-- Insert tMediaPlanDetail
	--------------------------------------

	PRINT ''--------------------------''
	PRINT ''Insert tMediaPlanDetail''
	PRINT ''--------------------------''
	PRINT ''''	

	INSERT INTO dbo.tMediaPlanDetail
			(MediaPlanVendorKey
			,SpotLinkID
			,LineNumber
			,StartDate
			,EndDate
			,[Description]
			,OrderDays
			,OrderTime
			,OrderLength
			,Date1
			,Date2
			,Quantity
			,Cost
			,UnitCost
			,Markup
			,Gross
			,AmountToBill
			,DateAdded
			,DateModified
			,PurchaseOrderDetailKey
			,Status
			,OrderLinkID
			)
	SELECT	mpw.MediaPlanVendorKey
			,mpw.SpotLinkID
			,mpw.LineNumber
			,mpw.StartDate
			,mpw.EndDate
			,mpw.[Description]
			,mpw.OrderDays
			,mpw.OrderTime
			,mpw.OrderLength
			,mpw.Date1
			,mpw.Date2
			,mpw.Quantity
			,mpw.Cost
			,mpw.UnitCost
			,mpw.Markup
			,mpw.Gross
			,mpw.AmountToBill
			,GETUTCDATE()	--DateAdded
			,GETUTCDATE()	--DateModified
			,NULL			--PurchaseOrderDetailKey
			,mpw.Status
			,mpw.OrderLinkID
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				--INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanDetailKey,0) <= 0


	--------------------------------------
	-- Update the media plan detail keys 
	-- in the worker table after the insert
	-- link based on mediaplankey, vendorkey 
	-- and spotlinkid - wasn''t in original code
	-- added after walk through with mas.
	--------------------------------------	

	UPDATE	mpw
	SET		mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
	-- SELECT	*
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlan mp (NOLOCK) ON mpw.MediaPlanKey = mp.MediaPlanKey
				INNER JOIN tMediaPlanVendor mpv (NOLOCK) ON mpv.MediaPlanKey = mp.MediaPlanKey
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
	WHERE 	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			AND ISNULL(mpw.MediaPlanDetailKey,0) <= 0
			AND mpd.SpotLinkID = mpw.SpotLinkID
			AND mpv.VendorKey = mpw.VendorKey


 /* *******************************************************************************
	Update tMediaPlanDetailHistory
    ******************************************************************************* */    

	PRINT ''--------------------------''
	PRINT ''Update tMediaPlanDetailHistory''
	PRINT ''--------------------------''
	PRINT ''''

	INSERT INTO dbo.tMediaPlanDetailHistory
			(MediaPlanDetailKey
			,MediaPlanVendorKey
			,SpotLinkID
			,LineNumber
			,StartDate
			,EndDate
			,Description
			,OrderDays
			,OrderTime
			,OrderLength
			,Date1
			,Date2
			,Quantity
			,Cost
			,UnitCost
			,Markup
			,Gross
			,AmountToBill
			,DateAdded
			,Status
			,OrderLinkID
			)
	SELECT	mpw.MediaPlanDetailKey
			,mpw.MediaPlanVendorKey
			,mpw.SpotLinkID
			,mpd.LineNumber -- The LineNumber should never change for an Existing line.  ISNULL(MAX(mpd.LineNumber),0) 
			,mpw.StartDate
			,mpw.EndDate
			,mpw.[Description]
			,mpw.OrderDays
			,mpw.OrderTime
			,mpw.OrderLength
			,mpw.Date1
			,mpw.Date2	
			,mpw.Quantity
			,mpw.Cost
			,mpw.UnitCost
			,mpw.Markup
			,mpw.Gross
			,mpw.AmountToBill
			,GETUTCDATE()
			,mpw.[Status]
			,mpw.OrderLinkID
	FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				INNER JOIN tMediaPlanDetail mpd (NOLOCK) ON mpw.MediaPlanDetailKey = mpd.MediaPlanDetailKey
	WHERE	mpw.CompanyKey = @CompanyKey
			AND mpw.MediaPlanKey = @MediaPlanKey
			AND mpw.Timestamp = @Timestamp
			--AND ISNULL(mpw.MediaPlanDetailKey,0) <= 0

	--------------------------------------
	-- Update Accounting
	--------------------------------------	

	PRINT GETDATE()	
	PRINT ''--------------------------''
	PRINT ''Update Accounting''
	PRINT ''--------------------------''

	IF EXISTS (SELECT 1 FROM #MediaPlanDetailUpdateAccounting)
	BEGIN

		DECLARE @MediaPlanDetailKey INT
		DECLARE @Count BIGINT 
		DECLARE @RunningCounter BIGINT 

		SET @Count = 0 
		SET @RunningCounter = 1

		-- get a count of total rows to process 
		SELECT @Count = MAX(RowNumber) FROM #MediaPlanDetailUpdateAccounting
 
		WHILE @RunningCounter <= @Count
		BEGIN
			PRINT @RunningCounter
			PRINT GETDATE()

			SELECT	@MediaPlanDetailKey = MediaPlanDetailKey
			FROM	#MediaPlanDetailUpdateAccounting
			WHERE	RowNumber = @RunningCounter
	
			EXEC sptMediaPlanDetailUpdateAccounting @MediaPlanDetailKey
    
			SET @RunningCounter = @RunningCounter + 1 
 
		END
	END 

	PRINT GETDATE()	
	PRINT ''--------------------------''
	PRINT ''Deleting Deleted Detail lines ''
	PRINT ''--------------------------''

	IF EXISTS (SELECT 1 FROM	tMediaPlanDetailWorker mpw (NOLOCK)
						WHERE	mpw.CompanyKey = @CompanyKey 
						AND		mpw.MediaPlanKey = @MediaPlanKey
						AND		mpw.Timestamp = @Timestamp
						AND		ISNULL(mpw.Deleted, 0) = 1)
	BEGIN
		DECLARE @CurrentMediaPlanDetailKey INT = -1

		WHILE 1=1
			BEGIN
				SELECT @CurrentMediaPlanDetailKey = MIN(MediaPlanDetailKey) 
				FROM	tMediaPlanDetailWorker mpw (NOLOCK)
				WHERE	mpw.CompanyKey = @CompanyKey 
				AND		mpw.MediaPlanKey = @MediaPlanKey
				AND		mpw.Timestamp = @Timestamp
				AND		ISNULL(mpw.Deleted, 0) = 1
				AND		MediaPlanDetailKey > @CurrentMediaPlanDetailKey
	
				IF @CurrentMediaPlanDetailKey IS NULL
					BREAK
			
				DECLARE @ReturnValue INT
				EXEC @ReturnValue = sptMediaPlanDetailDelete @CurrentMediaPlanDetailKey
    
				 IF @ReturnValue = -2
					BEGIN
						UPDATE tMediaPlanDetail 
						SET ErrMsgOrder = ''Cannot delete the line because it is linked to a Voucher Detail Line.'' 
						WHERE MediaPlanDetailKey = @CurrentMediaPlanDetailKey
					END
					ELSE IF @ReturnValue = -1
					BEGIN					
						UPDATE tMediaPlanDetail 
						SET ErrMsgOrder = ''Cannot delete the line due to an unspecified purchase order detail error.'' 
						WHERE MediaPlanDetailKey = @CurrentMediaPlanDetailKey
					END
			END
	END

	PRINT GETDATE()	
	PRINT ''--------------------------''
	PRINT ''Project Rollup''
	PRINT ''--------------------------''
	DECLARE @ProjectKey INT

	SELECT	@ProjectKey = ProjectKey
	FROM	tMediaPlan (NOLOCK)
	WHERE	MediaPlanKey = @MediaPlanKey

	 if @ProjectKey > 0  
	begin
		print ''Starting rollup''
		exec sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1  
		print ''Rollup Done''
	end 


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














ALTER VIEW [dbo].[vReport_Deliverables]
AS

/*
|| When      Who Rel     What
|| 12/18/14  WDF 10.587 (230861) Created from vListing_Deliverables adding Comments
|| 01/27/15  WDF 10.588 (Abelson Taylor) Added Division and Product
|| 06/29/18  WDF 18.7.0 (408035) Added [File Count] 
|| 07/20/18  GWG 18.8.0 Added person''s name who made the comment
|| 09/04/18  RLS 18.9.0 (418542) Added Project Type
|| 02/18/19  MCM 19.0.2 (446837) Removing r.LatestRound = 1 and a.ActiveStep = 1 from a left outer join and adding it to the select list.  Also, for Approval Status, set it to '''' instead of Rejected
|| 03/22/19  RLS 19.0.4 (446470) Added [Round Count]
|| 04/29/19  GAR 19.0.5 (457565) Added CustomFieldKey, added DeliverableStatus
|| 08/14/19  RLB 19.0.9 (473466) Changed Approval Status to match listing
|| 08/22/19  AMP 19.0.9 (475016) Added Project Manager
|| 08/29/19  GAR 19.0.9 (476924) Added Deliverable ID
|| 09/19/19  GAR 19.1.0 (476989) Changed Approval Status to be the status of the entire deliverable and added Approver Status
|| 10/10/19  GAR 19.1.1 (456345) Removed the Date Decision Completed field that GG added - was adding too many rows
|| 10/10/19  GAR 19.1.1 (481255) Adding Current Approver Due Date
|| 02/20/20  RLS 20.0.3 (502033) Added [Page Number]
|| 04/23/20  RLS 20.0.5 (510289) Added RequestID and RequestName
|| 07/17/20  RLS 20.0.8.0  (520834)  Added Project Start Date, Project End Date, Campaign Start Date and Campaign End Date along with join on tCampaign
|| 09/08/20  RLS 20.0.9.0  (519691)  Added CustomFieldKey2 for Project custom fields
|| 06/09/21  WDF 21.07.18  (559492) Added [Date Round Approved]
|| 06/29/22  RLS 22.07.17  (559492) Added [Campaign ID] and [Campaign Name]
|| 08/11/23  RLB 23.09.17  (648008) added project type color, Deliverable Status Color and Type Color
|| 01/28/25  GAR 25.02.16  (689798) Added Task Plan Start Date, Task Actual Start Date, Task Plan Complete Date, Task Actual Completion Date
|| 04/20/26  RLB  26.05.17  (726348) Added Union since projectkey can mean project or campaign dependant on +- number

*/

SELECT
	 rd.ReviewDeliverableKey
	,rd.OwnerKey 
	,rd.CompanyKey	
	,r.ReviewRoundKey
	,p.GLCompanyKey
	,p.ProjectKey
	,rd.Description AS [Description]
	,rd.DeliverableName AS [Deliverable Name]
	,rd.DueDate AS [Due Date]
	,p.ProjectNumber AS [Project Number]
	,p.ProjectName AS [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name]
	,pm.FirstName + '' '' + pm.LastName as [Project Manager]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' '' + c.CompanyName as [Client Full Name]
	,r.RoundName AS [Current Round]
	,(SELECT Count(*) FROM tReviewRoundFile (NOLOCK) WHERE ReviewRoundKey = r.ReviewRoundKey) As [File Count] 
	,(SELECT Count(*) FROM tReviewRound (NOLOCK) WHERE ReviewDeliverableKey = rd.ReviewDeliverableKey) As [Round Count] 
	,rc.Comment AS [Comment]
	,rc.DateAdded AS [Comment Date]
	,pt.ProjectTypeName AS [Project Type]
	,pt.ProjectTypeColor as [Project Type Color]
	,Case a.EnableRouting
		WHEN 1 THEN ''In Order''
		WHEN 0 THEN ''Everyone''
	 END AS [Routing]
	,CASE a.Internal 
		WHEN 1 THEN ''Internal''
		WHEN 0 THEN ''External''
	 END AS [Current Step]
	 ,CASE ISNULL(a.Pause,0)
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Paused]
	 ,CASE a.LoginRequired
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Login Required]
	 ,CASE a.AllApprove
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Everyone Must Review]
	 ,CASE rd.Approved
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Approved]
	 ,rd.DueDate as [Date Due]
	 ,rd.ApprovedDate as [Date Approved]
	,r.DateSent AS [Date Sent]
	,Case When a.ActiveStep = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Reviewing'' end
	 Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		Else 
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		End 
	 End as [Approval Status]
	 ,Case When a.ActiveStep = 1 then a.ApproverStatus 
	  Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		ELSE
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		END
	End As [Approver Status]
	,u.UserName as [Account Manager]
	,own.UserName as [Deliverable Owner]
	,Case p.Active When 1 Then ''YES'' else ''NO'' end as [Active Project]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cp.ProductID as [Client Product ID]
    ,cp.ProductName as [Client Product]
	,ISNULL(cu.UserName, rc.UserName) as [Comment Added By]
	,Case r.LatestRound WHEN 1 THEN ''YES'' ELSE ''NO'' end as [Active Round]
	,Case a.ActiveStep WHEN 1 THEN ''YES'' ELSE ''NO'' end as [Active Step]
	,rd.CustomFieldKey
	,p.CustomFieldKey as CustomFieldKey2 
	,ds.StatusName AS [Deliverable Status]
	,ds.StatusColor AS [Deliverable Status Color]
	,rd.DeliverableID AS [Deliverable ID]
	--,asu.DateCompleted as [Date Decision Completed]
	--,asu.DueDate as [Date Decision Due]
	--,asu.DateActivated as [Date Sent for Decision]
	,(SELECT MIN(DueDate) FROM tApprovalStepUser (NOLOCK) WHERE ActiveUser = 1 AND CompletedUser = 0 AND ApprovalStepKey = a.ApprovalStepKey) AS [Current Approver Due Date]
	,rc.Page+1 as [Page Number] -- Page is zero-based
	,pr.RequestID as [Request ID]
	,reqdef.RequestName as [Request Type]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project End Date]
	,ca.StartDate as [Campaign Start Date]
	,ca.EndDate as [Campaign End Date]
	,r.DateRoundApproved as [Date Round Approved]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign name]
	,dt.TypeName as [Deliverable Type]
	,dt.TypeColor as [Deliverable Type Color]
	,t.PlanStart as [Task Plan Start Date]
	,t.ActStart as [Task Actual Start Date]
	,t.PlanComplete as [Task Plan Complete Date]
	,t.ActComplete as [Task Actual Complete Date]
FROM tReviewDeliverable rd (NOLOCK)
	left outer join tProject p (NOLOCK) ON rd.ProjectKey = p.ProjectKey
	left outer join tCompany c (NOLOCK) on p.ClientKey = c.CompanyKey
	left outer join tReviewRound r (NOLOCK) ON rd.ReviewDeliverableKey = r.ReviewDeliverableKey
	left outer join tApprovalStep a (NOLOCK) ON a.EntityKey = r.ReviewRoundKey and a.Entity = ''tReviewRound'' 
	--left outer join tApprovalStepUser asu (nolock)  on a.ApprovalStepKey = asu.ApprovalStepKey
	left outer join tReviewComment rc (NOLOCK) ON rc.ReviewRoundKey = r.ReviewRoundKey and a.ApprovalStepKey = rc.ApprovalStepKey
	left outer join vUserName cu (nolock) on rc.UserKey = cu.UserKey
	left outer join vUserName u (NOLOCK) on p.AccountManager = u.UserKey
	left outer join vUserName own (NOLOCK) on rd.OwnerKey = own.UserKey
	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 tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tDeliverableStatus ds (nolock) on rd.DeliverableStatusKey = ds.DeliverableStatusKey
	left outer join tDeliverableType dt (NOLOCK) on rd.DeliverableTypeKey = dt.DeliverableTypeKey
    left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey 
	left outer join tRequest pr (nolock) on rd.RequestKey = pr.RequestKey
	left outer join tRequestDef reqdef (nolock) on pr.RequestDefKey = reqdef.RequestDefKey
	left outer join tCampaign ca (NOLOCK) on p.CampaignKey = ca.CampaignKey
	left outer join tTask t (NOLOCK) on rd.TaskKey = t.TaskKey
Where rd.ProjectKey > 0

UNION

SELECT
	 rd.ReviewDeliverableKey
	,rd.OwnerKey 
	,rd.CompanyKey	
	,r.ReviewRoundKey
	,ca.GLCompanyKey
	,null
	,rd.Description AS [Description]
	,rd.DeliverableName AS [Deliverable Name]
	,rd.DueDate AS [Due Date]
	,'''' AS [Project Number]
	,'''' AS [Project Name]
	,'''' AS [Project Full Name]
	,pm.FirstName + '' '' + pm.LastName as [Project Manager]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' '' + c.CompanyName as [Client Full Name]
	,r.RoundName AS [Current Round]
	,(SELECT Count(*) FROM tReviewRoundFile (NOLOCK) WHERE ReviewRoundKey = r.ReviewRoundKey) As [File Count] 
	,(SELECT Count(*) FROM tReviewRound (NOLOCK) WHERE ReviewDeliverableKey = rd.ReviewDeliverableKey) As [Round Count] 
	,rc.Comment AS [Comment]
	,rc.DateAdded AS [Comment Date]
	,'''' AS [Project Type]
	,'''' as [Project Type Color]
	,Case a.EnableRouting
		WHEN 1 THEN ''In Order''
		WHEN 0 THEN ''Everyone''
	 END AS [Routing]
	,CASE a.Internal 
		WHEN 1 THEN ''Internal''
		WHEN 0 THEN ''External''
	 END AS [Current Step]
	 ,CASE ISNULL(a.Pause,0)
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Paused]
	 ,CASE a.LoginRequired
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Login Required]
	 ,CASE a.AllApprove
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Everyone Must Review]
	 ,CASE rd.Approved
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Approved]
	 ,rd.DueDate as [Date Due]
	 ,rd.ApprovedDate as [Date Approved]
	,r.DateSent AS [Date Sent]
	,Case When a.ActiveStep = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Reviewing'' end
	 Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		Else 
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		End 
	 End as [Approval Status]
	 ,Case When a.ActiveStep = 1 then a.ApproverStatus 
	  Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		ELSE
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		END
	End As [Approver Status]
	,u.UserName as [Account Manager]
	,own.UserName as [Deliverable Owner]
	,Case ca.Active When 1 Then ''YES'' else ''NO'' end as [Active Project]
	,'''' as [Client Division ID]
    ,'''' as [Client Division]
    ,'''' as [Client Product ID]
    ,'''' as [Client Product]
	,ISNULL(cu.UserName, rc.UserName) as [Comment Added By]
	,Case r.LatestRound WHEN 1 THEN ''YES'' ELSE ''NO'' end as [Active Round]
	,Case a.ActiveStep WHEN 1 THEN ''YES'' ELSE ''NO'' end as [Active Step]
	,rd.CustomFieldKey
	,null as CustomFieldKey2 
	,ds.StatusName AS [Deliverable Status]
	,ds.StatusColor AS [Deliverable Status Color]
	,rd.DeliverableID AS [Deliverable ID]
	--,asu.DateCompleted as [Date Decision Completed]
	--,asu.DueDate as [Date Decision Due]
	--,asu.DateActivated as [Date Sent for Decision]
	,(SELECT MIN(DueDate) FROM tApprovalStepUser (NOLOCK) WHERE ActiveUser = 1 AND CompletedUser = 0 AND ApprovalStepKey = a.ApprovalStepKey) AS [Current Approver Due Date]
	,rc.Page+1 as [Page Number] -- Page is zero-based
	,pr.RequestID as [Request ID]
	,reqdef.RequestName as [Request Type]
	,'''' as [Project Start Date]
	,'''' as [Project End Date]
	,ca.StartDate as [Campaign Start Date]
	,ca.EndDate as [Campaign End Date]
	,r.DateRoundApproved as [Date Round Approved]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign name]
	,dt.TypeName as [Deliverable Type]
	,dt.TypeColor as [Deliverable Type Color]
	,t.PlanStart as [Task Plan Start Date]
	,t.ActStart as [Task Actual Start Date]
	,t.PlanComplete as [Task Plan Complete Date]
	,t.ActComplete as [Task Actual Complete Date]
FROM tReviewDeliverable rd (NOLOCK)
	left outer join tCampaign ca (NOLOCK) on ABS(rd.ProjectKey) = ca.CampaignKey
	left outer join tCompany c (NOLOCK) on ca.ClientKey = c.CompanyKey
	left outer join tReviewRound r (NOLOCK) ON rd.ReviewDeliverableKey = r.ReviewDeliverableKey
	left outer join tApprovalStep a (NOLOCK) ON a.EntityKey = r.ReviewRoundKey and a.Entity = ''tReviewRound'' 
	--left outer join tApprovalStepUser asu (nolock)  on a.ApprovalStepKey = asu.ApprovalStepKey
	left outer join tReviewComment rc (NOLOCK) ON rc.ReviewRoundKey = r.ReviewRoundKey and a.ApprovalStepKey = rc.ApprovalStepKey
	left outer join vUserName cu (nolock) on rc.UserKey = cu.UserKey
	left outer join vUserName u (NOLOCK) on ca.AEKey = u.UserKey
	left outer join vUserName own (NOLOCK) on rd.OwnerKey = own.UserKey
	left outer join tDeliverableStatus ds (nolock) on rd.DeliverableStatusKey = ds.DeliverableStatusKey
	left outer join tDeliverableType dt (NOLOCK) on rd.DeliverableTypeKey = dt.DeliverableTypeKey
    left outer join tUser pm (nolock) on ca.PMKey = pm.UserKey 
	left outer join tRequest pr (nolock) on rd.RequestKey = pr.RequestKey
	left outer join tRequestDef reqdef (nolock) on pr.RequestDefKey = reqdef.RequestDefKey
	left outer join tTask t (NOLOCK) on rd.TaskKey = t.TaskKey
Where rd.ProjectKey < 0


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

	 @CompanyKey int
	,@UserKey int
	,@IgnoreDates int
	,@LinkID varchar(50)
	,@VendorID nvarchar(50)
	,@InvoiceNumber varchar(50)
	,@InvoiceDate smalldatetime
	,@MatchedDate smalldatetime  = NULL
	,@DueDate smalldatetime
	,@EstimateID varchar(50)
	,@POLinkID varchar(50)
	,@InvoiceMonth varchar(2)
	,@InvoiceYear varchar(4)
	,@TotalInvoiceGross decimal(24,6)
	,@TotalInvoiceNet decimal(24,6)
	,@CMP tinyint = 0,	-- syncing from CMP?  WMJ = 0 / CMP = 1
	@UseDesc tinyint = 0,
    @Desc varchar(500) = '''',
    @UseOverRidePostingDate tinyint = 0,
    @OverRidePostingDate smalldatetime = null

as --Encrypt

/*
|| When     Who Rel      What
|| 06/10/08 RTC	8.5.1.3  New For Bottom Line Invoicing
|| 06/18/08 GHL 8.513    Added OpeningTransaction
|| 09/16/08 RTC 10.0.0.9 Insure vendor is active.
|| 07/17/09 MAS 10.5.0   (57112) Always checks for @ExpenseAccountKey 
|| 07/20/09 MAS 10.5.5   (58132) Apply the difference in the TotalInvoiceNet vs the TotalOrderAmount, 
						 Removed the insure "the total voucher net is not more than the associated orders net amount" check and error code
|| 11/11/09 MAS 10.5.1.3 (47035)
|| 03/25/10 MAS 10.5.1.3 (76058) Added the option to use the ClearDate from Strata as the PostingDate	
|| 07/26/10 MAS 10.5.3.2 (85965) Account for Broadcast Months (The broadcast calendar is a M-Su weekly calendar, and the month
||                        of the week is determined by the month that the Sunday falls into.  Spot (broadcast) buying is done on
||                        a broadcast month.  Bottom-line invoicing is only available in our spot module so the month will always be broadcast month. )
|| 10/15/10 MAS 10.5.3.6 (92260) Added sptVoucherRecalcAmounts
|| 11/08/11 MAS 10.5.4.9 Added VoucherType to sptVoucherInsert
|| 01/17/12 GHL 10.5.5.2 VoucherType = 0 now since the Voucher UI can handle all po kinds 	
|| 03/28/12 GHL 10.5.5.4 Passing @TargetGLCompanyKey = null to sptVoucherDetailUpdate	
|| 08/13/12 MAS 10.5.5.9 Use the Vendor''s DefaultAPAccountKey if it''s set.  Otherwise default to the Company DefaultAPAccountKey	
|| 08/23/12 MAS 10.5.5.9 (152132)Changed the percision of all the client costing params 
|| 08/16/12 MAS 10.5.7.0 (187109)Added @ClassKey to sptVoucherInsert, sptVoucherDetailInsert and sptVoucherDetailUpdate 
|| 11/20/13 GHL 10.5.7.3 Added GrossAmount and Commission when calling sptInvoiceDetailInsert/Update
|| 11/22/13 GHL 10.5.7.4  Added PCurrency and PExchangeRate parms when calling sptInvoiceDetailInsert
|| 12/06/13 MAS 10.5.7.1 (187514, 189765)Account for orders that are greater than the BLI being applied and create a negative vouche detail line for the difference
|| 03/05/14 PLC 10.5.7.7 Added logic clear month for a bottom line invoice.
|| 06/14/14 PLC 10.5.8.1 Move logic clear month for a bottom line invoice to pref.
|| 06/14/14 PLC 10.5.8.1 Added invoice month to post date logic.
|| 08/01/14 PLC 10.5.8.2 Fixed logic to close bottomline invoice so all purdetails get closed.
|| 08/29/14 PLC 10.5.8.3 Added logic to ignore dates on bottomline invoice so all purdetails get closed.
|| 11/25/14 PLC 10.5.8.6 Fixed logic to import an invoice into a closed month
|| 01/20/15 RLB 10.5.8.7 Adding missing parm
|| 10/05/16 PLC 10.6.0.8 Adding parms to handle desc, and posting date	
|| 10/18/16 PLC 10.6.0.9 added logic to handle excat matches and remove the revisions	
|| 01/24/18 GHL 18.2.0.0 (378300) Corrected equation for commission 
|| 03/21/18 MAS 18.4.0   Added @PostingDate = dbo.fFormatDateNoTime(@MatchedDate) && @PostingDate = dbo.fFormatDateNoTime(@InvoiceDate)
|| 04/23/18 MAS 18.5.0  (379452) Problem calculating @Commission for the Final POD Line. @LineTotalGross = isnull(BillableCost, 0) -- Was AppliedCost which caused a problem calculating @Commission before
||                      Adding the revision line when applying an additional invoice amount
|| 05/21/18 MAS 18.6.0   Added ApprovedDate = dbo.fFormatDateNoTime(@curentdate)
|| 02/19/19 MAS 19.0.3.0 (445490) Check for payments applied to the voucher
|| 08/06/20 GHL 20.1.0.0 (451878) Added GLCExchangeRate param when calling sptVoucherDetailUpdate
|| 11/12/21 RLS 21.12.19 (574346) Changed @VendorID to nvarchar(50)
|| 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
|| 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName

*/

declare @VoucherKey int
declare @PurchaseOrderKey int
declare @VendorKey int
declare @GLCompanyKey int
declare @POStatus smallint
declare @TermsPercent decimal(24,4)
declare @TermsDays int
declare @TermsNet int
declare @RetVal int
declare @APAccountKey int
declare @OfficeKey int
declare @BCClientLink smallint
declare @ProjectKey int
declare	@AutoApproveExternalInvoices tinyint
declare @Status smallint
declare @Error int
declare @PurchaseOrderDetailKey int
declare @LineNumber int
declare @AdjustmentNumber int
declare @DetailOrderDate smalldatetime
declare @AmtApplyGross decimal(24,4)
declare @AmtApplyNet decimal(24,4)
declare @TaskKey int
declare @ItemKey int
declare @DepartmentKey int
declare @BillAt smallint
declare @VoucherDetailKey int
declare @DeleteExistingVoucher tinyint
declare @LineTotalCost decimal(24,4)
declare @LineTotalGross decimal(24,4)
declare @RequireItems tinyint
declare @RequireTasks tinyint
declare @ExpenseAccountKey int
declare @RequireAccounts tinyint
declare @Commission decimal(24,4)
declare @DateRangeBegin smalldatetime
declare @DateRangeEnd smalldatetime
declare @TranStarted tinyint
declare @OrderLineTotalCost decimal(24,4)
declare @ClassKey int
declare @Active tinyint
declare @LastPurchaseOrderDetailKey int
declare @ClientKey int
declare @PostingDate smalldatetime
declare @UseClearedDate int
declare @CloseMonthBLInvoice tinyint
declare @Closed tinyint
declare @MatchedTotals decimal(24,4)

			Declare @PODLinkID varchar(50)
			Declare @SpotLinkID varchar(50)
			Declare @StartDate smalldatetime
			Declare @EndDate smalldatetime
			Declare @UserDate1 smalldatetime
			Declare @UserDate2 smalldatetime
			Declare @UserDate3 smalldatetime
			Declare @UserDate4 smalldatetime
			Declare @UserDate5 smalldatetime
			Declare @UserDate6 smalldatetime
			Declare @Quantity decimal(24,4)
			Declare @Markup decimal(24,4)
			Declare @UnitRate decimal(24,4)
			Declare @PODGross decimal(24,4)
			Declare @PODMarkup decimal(24,4)
			Declare @Program varchar(300)
			Declare @Comments varchar(1000)
			Declare @OrderDays varchar(50)
			Declare @OrderTime varchar(50)
			Declare @OrderLength varchar(50)
			Declare @RevisionPurchaseOrderDetailKey int
			declare @curentdate smalldatetime 

			Select @RevisionPurchaseOrderDetailKey = NULL
			select @curentdate  = GETDATE()


--init transaction flag
select @TranStarted = 0

--set date range
select @DateRangeBegin = cast(@InvoiceYear as varchar(4)) + ''-'' + @InvoiceMonth + ''-01 00:00:00''
if @InvoiceMonth = ''12''
	select @DateRangeEnd = cast(cast(cast(@InvoiceYear as int) + 1 as varchar(4)) + ''-'' + ''01-01 00:00:00'' as smalldatetime)
else
	select @DateRangeEnd = cast(cast(@InvoiceYear as varchar(4)) + ''-'' + cast(cast(@InvoiceMonth as int) + 1 as varchar(2)) + ''-01 00:00:00'' as smalldatetime)

-- Adjust dates for broadcast month
Select @DateRangeBegin = DateAdd(day, -6, DateAdd(day, (8-DatePart(weekday, 
    DateAdd(Month, DateDiff(Month, 0, @DateRangeBegin), 0)))%7, 
    DateAdd(Month, DateDiff(Month, 0, @DateRangeBegin), 0)))

Select @DateRangeEnd = DateAdd(day, -7,	DateAdd(day, (8-DatePart(weekday, 
    DateAdd(Month, DateDiff(Month, 0, @DateRangeEnd), 0)))%7, 
    DateAdd(Month, DateDiff(Month, 0, @DateRangeEnd), 0)))    

--find associated purchase order
select	 @PurchaseOrderKey = PurchaseOrderKey
		,@POStatus = Status
		,@BillAt = BillAt
from tPurchaseOrder (nolock)
where CompanyKey = @CompanyKey
and LinkID = @POLinkID
and POKind = 2

select @VendorKey = CompanyKey 
	  ,@Active = isnull(Active, 0)
	  ,@APAccountKey = DefaultAPAccountKey 	
from tCompany (nolock) 
where OwnerCompanyKey = @CompanyKey 
and Vendor = 1 
and VendorID = @VendorID
	
if @VendorKey is null
	return -3

if @Active <> 1
	return -20
			
select	 @ClassKey = ClassKey
		,@ProjectKey = ProjectKey
		,@GLCompanyKey = GLCompanyKey
		,@OfficeKey = OfficeKey
from	tMediaEstimate (nolock)
where	EstimateID = @EstimateID
and		CompanyKey = @CompanyKey
		
--validate associated purchase order conditions
if @PurchaseOrderKey is null
	return -1
	
if @POStatus < 4 
	return -2
			
if @InvoiceDate is null
	return -7
			
if @InvoiceNumber is null
	return -8

-- Use the company defualt APAccountKey if the vendor didn''t have one setup
If 	@APAccountKey IS NULL								
	--get defaults needed
	select   @BCClientLink = isnull(BCClientLink,1)
			,@RequireItems = RequireItems
			,@RequireTasks = RequireTasks
			,@RequireAccounts = RequireGLAccounts      
			,@APAccountKey = DefaultAPAccountKey
			,@AutoApproveExternalInvoices = AutoApproveExternalInvoices	
			,@UseClearedDate = ISNULL(UseClearedDate, 0) 
			,@CloseMonthBLInvoice = ISNULL(CloseMonthBLInvoice, 0) 
	from tPreference (nolock)
	where CompanyKey = @CompanyKey
Else
	--get defaults needed
	select   @BCClientLink = isnull(BCClientLink,1)
			,@RequireItems = RequireItems
			,@RequireTasks = RequireTasks
			,@RequireAccounts = RequireGLAccounts      
			,@AutoApproveExternalInvoices = AutoApproveExternalInvoices	
			,@UseClearedDate = ISNULL(UseClearedDate, 0) 
			,@CloseMonthBLInvoice = ISNULL(CloseMonthBLInvoice, 0)
	from tPreference (nolock)
	where CompanyKey = @CompanyKey

If @UseClearedDate = 1 
	Select @PostingDate = dbo.fFormatDateNoTime(@MatchedDate)
else If @UseClearedDate = 0
	Select @PostingDate = dbo.fFormatDateNoTime(@InvoiceDate)
else
	begin -- new option number 2 invoice month the below code has been tested above with week begin
		DECLARE @dtDate DATETIME
		SET @dtDate = cast(@InvoiceYear as varchar(4)) + ''-'' + @InvoiceMonth + ''-01 00:00:00''
		SELECT @PostingDate = dbo.fFormatDateNoTime(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@dtDate)+1,0)))
	end  
	
if @UseDesc = 0
    Select @Desc = NULL
    
if @AutoApproveExternalInvoices = 1
	select @Status = 4
else
	select @Status = 2	
				
select   @TermsPercent = isnull(TermsPercent, 0)
		,@TermsDays = isnull(TermsDays, 0)
		,@TermsNet = isnull(TermsNet, 0) 
from tCompany (nolock)
where CompanyKey = @VendorKey
		
select @DueDate = dateadd(day, @TermsNet, @InvoiceDate)
				 			
--check if voucher exists	
select @VoucherKey = min(VoucherKey) 
from tVoucher (nolock)
where CompanyKey = @CompanyKey 
and LinkID = @LinkID
and InvoiceNumber = @InvoiceNumber

--if bottom line voucher already exists, check both voucher and lines to make sure thay can be updated
if isnull(@VoucherKey, 0) > 0
	begin
		--existing voucher, make sure it''s not already been posted
		if (select Posted
			from tVoucher (nolock)
			where VoucherKey = @VoucherKey) = 1
				return -4 
		
		--existing voucher, make sure voucher detail lines have not been invoiced to client or written off
		if exists(select 1 
					from tVoucherDetail vd (nolock)
					where vd.VoucherKey = @VoucherKey
					and (WriteOff = 1 or isnull(InvoiceLineKey,-1) >= 0))
			return -5

		--existing voucher, make sure voucher detail lines are not on billing worksheets
		if exists(select 1 
					from tBillingDetail bd (nolock) inner join tVoucherDetail vd (nolock) on bd.EntityKey = vd.VoucherDetailKey
					where vd.VoucherKey = @VoucherKey
					and bd.Entity = ''tVoucherDetail'')
			return -6

		if exists(select 1 from tVoucher (nolock)
			where VoucherKey = @VoucherKey
			AND ISNULL(AmountPaid,0) > 0)
				return -22 --voucher has payments applied, do not update
		
		--loop through existing voucher lines subtracting total net amount from bottom line invoice total amount
		select @VoucherDetailKey = -1
		while 1=1
			begin
				select @VoucherDetailKey = min(VoucherDetailKey)
				from tVoucherDetail (nolock)
				where VoucherKey = @VoucherKey
				and VoucherDetailKey > @VoucherDetailKey
				
				if @VoucherDetailKey is null
					break
					
				select @LineTotalCost = vd.TotalCost
						,@OrderLineTotalCost = pod.TotalCost
				from tVoucherDetail vd (nolock) inner join tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
				where VoucherDetailKey = @VoucherDetailKey

				--if this is a partial invoice line, delete it, may end up re-adding it later
				if @LineTotalCost < @OrderLineTotalCost
					begin
						if @TranStarted = 0
							begin
								select @TranStarted = 1
								begin tran
							end	
														
						exec @RetVal = sptVoucherDetailDelete @VoucherDetailKey, 0
						if @RetVal <> 1 
							begin
								rollback tran
								return -11
							end				
					end
				else
					if @LineTotalCost < @TotalInvoiceNet
						select @TotalInvoiceNet = @TotalInvoiceNet - @LineTotalCost
					else
						begin
							if @LineTotalCost = @TotalInvoiceNet
								begin
									select @TotalInvoiceNet = 0
									break
								end
							else
								--the invoice line total cost is greater than the invoice total net, need to delete this and all remaining lines
								begin
									select @VoucherDetailKey = @VoucherDetailKey  -1
									break
								end
						end
			end
					
		--delete lines if needed
		if @VoucherDetailKey is not null
			begin
				if @TranStarted = 0
					begin
						select @TranStarted = 1
						begin tran
					end	
					
				while 1=1
					begin
						select @VoucherDetailKey = min(VoucherDetailKey)
						from tVoucherDetail (nolock)
						where VoucherKey = @VoucherKey
						and VoucherDetailKey > @VoucherDetailKey
						
						if @VoucherDetailKey is null
							break	
							
						exec @RetVal = sptVoucherDetailDelete @VoucherDetailKey, 0
						if @RetVal <> 1 
							begin
								rollback tran
								return -11
							end				
					end 
			end
	end --end of existing voucher processing
else
	begin
		if @TranStarted = 0
			begin
				select @TranStarted = 1
				begin tran
			end	
		
		--need to add new voucher header
		exec @RetVal = sptVoucherInsert
			@CompanyKey,
			@VendorKey,
			@InvoiceDate,
			@PostingDate,
			@InvoiceNumber,
			@InvoiceDate,
			@UserKey,
			@TermsPercent,
			@TermsDays,
			@TermsNet,
			@DueDate,
			@Desc,
			@ProjectKey,
			@UserKey,
			@APAccountKey,
			@ClassKey,
			null,
			null,
			@GLCompanyKey,
			@OfficeKey,
			0, --OpeningTransaction
			0,
			null, -- CurrencyID
			1,    -- ExchangeRate
			null, -- PCurrencyID
			1,    -- PExchangeRate
			null, -- CompanyMediaKey		
			@VoucherKey output
			
		if @RetVal = -1
			begin
				rollback tran
				return -9  --Invoice number already exists
			end
			
		if @RetVal = -2
			begin
				rollback tran
				return -10  --Project status is not accepting costs
			end		

		update tVoucher 
		set LinkID = @LinkID
		,Status = @Status 
		,BottomLineInvoice = 1
		,InvoiceMonth = @InvoiceMonth
		,InvoiceYear = @InvoiceYear
		where VoucherKey = @VoucherKey
	end
	
		if @Status = 4 and @UseOverRidePostingDate = 1
		Update tVoucher Set PostingDate = dbo.fFormatDateNoTime(@OverRidePostingDate) Where VoucherKey = @VoucherKey
		
	If @Status = 4 
		begin
			update tVoucher Set ApprovedDate = dbo.fFormatDateNoTime(@curentdate) Where VoucherKey = @VoucherKey
						
			exec @RetVal = sptActionLogInsert
								''VOUCHER'',--@Entity varchar(50),
								@VoucherKey, -- Entity key
								@CompanyKey, --@CompanyKey int,
								@ProjectKey, -- @ProjectKey int,
								''Approved'', -- @Action varchar(200),
								@curentdate, --@ActionDate smalldatetime,
								''Strata Link'', --@ActionBy varchar(500),
								''Approved by Strata Sync'', --@Comments varchar(4000),
								@InvoiceNumber, --@Reference varchar(200),
								@CompanyKey, --@SourceCompanyID varchar(100),
								@UserKey, --@UserKey int = NULL,
								NULL  --@CampaignKey int = NULL)
		
		end


if @TranStarted = 0
	begin
		select @TranStarted = 1
		begin tran
	end	
-- get matched numbers	
if @IgnoreDates = 1
	select @MatchedTotals = sum(isnull(TotalCost, 0) - isnull(AppliedCost, 0)) - @TotalInvoiceNet
	from tPurchaseOrderDetail (nolock)
	where PurchaseOrderKey = @PurchaseOrderKey
	and Closed = 0
	and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
else
	select @MatchedTotals = sum(isnull(TotalCost, 0) - isnull(AppliedCost, 0)) - @TotalInvoiceNet
	from tPurchaseOrderDetail (nolock)
	where PurchaseOrderKey = @PurchaseOrderKey
	and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
	and Closed = 0
	and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0	
	
-- now we have a voucher header, create new voucher details by looping through order details
select @LineNumber = -1
while 1=1
	begin
        if @IgnoreDates = 1
			select @LineNumber = min(LineNumber) 
			from tPurchaseOrderDetail (nolock)
			where PurchaseOrderKey = @PurchaseOrderKey
			and LineNumber > @LineNumber
			and Closed = 0
			and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
		else
			select @LineNumber = min(LineNumber) 
			from tPurchaseOrderDetail (nolock)
			where PurchaseOrderKey = @PurchaseOrderKey
			and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
			and LineNumber > @LineNumber
			and Closed = 0
			and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0			
		
		if @LineNumber is null
			break 

		select @AdjustmentNumber = -1
		while 1=1
			begin
				if @TotalInvoiceNet = 0 and @MatchedTotals <> 0
				break

				if @IgnoreDates = 1
					select @AdjustmentNumber = min(AdjustmentNumber)
					from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and LineNumber = @LineNumber
					and AdjustmentNumber > @AdjustmentNumber
					and Closed = 0
					and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
				else
					select @AdjustmentNumber = min(AdjustmentNumber)
					from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
					and LineNumber = @LineNumber
					and AdjustmentNumber > @AdjustmentNumber
					and Closed = 0
					and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
				


				if @AdjustmentNumber is null
					break

				select @DetailOrderDate = ''1990-01-01''
				while 1=1
					begin 
						if @TotalInvoiceNet = 0 and @MatchedTotals <> 0
						break

						if @IgnoreDates = 1
							select @DetailOrderDate = min(DetailOrderDate)
							from tPurchaseOrderDetail (nolock)
							where PurchaseOrderKey = @PurchaseOrderKey
							and LineNumber = @LineNumber
							and AdjustmentNumber = @AdjustmentNumber
							and DetailOrderDate > @DetailOrderDate
							and Closed = 0
							and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
						else
							select @DetailOrderDate = min(DetailOrderDate)
							from tPurchaseOrderDetail (nolock)
							where PurchaseOrderKey = @PurchaseOrderKey
							and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
							and LineNumber = @LineNumber
							and AdjustmentNumber = @AdjustmentNumber
							and DetailOrderDate > @DetailOrderDate
							and Closed = 0
							and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
						
						
						if @DetailOrderDate is null
							break
						
						select @PurchaseOrderDetailKey = -1
						while 1=1
							begin 
								if @TotalInvoiceNet = 0 and @MatchedTotals <> 0
								break

								if @IgnoreDates = 1
									select @PurchaseOrderDetailKey = min(PurchaseOrderDetailKey) 
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and PurchaseOrderDetailKey > @PurchaseOrderDetailKey
									and LineNumber = @LineNumber
									and AdjustmentNumber = @AdjustmentNumber
									and DetailOrderDate = @DetailOrderDate
									and Closed = 0
									and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
								else
									select @PurchaseOrderDetailKey = min(PurchaseOrderDetailKey) 
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
									and PurchaseOrderDetailKey > @PurchaseOrderDetailKey
									and LineNumber = @LineNumber
									and AdjustmentNumber = @AdjustmentNumber
									and DetailOrderDate = @DetailOrderDate
									and Closed = 0
									and isnull(TotalCost, 0) - isnull(AppliedCost, 0) <> 0
								

								if @PurchaseOrderDetailKey is null
									break
										
								Select @LastPurchaseOrderDetailKey = @PurchaseOrderDetailKey

								select @AmtApplyNet = isnull(TotalCost, 0) - isnull(AppliedCost, 0)
								,@AmtApplyGross = 
									case @BillAt
										when 0 then isnull(BillableCost, 0) - isnull(AmountBilled, 0)
										when 1 then isnull(TotalCost, 0) - isnull(AmountBilled, 0)
										when 2 then isnull(BillableCost, 0) - isnull(TotalCost, 0) - isnull(AmountBilled, 0)
									end 
								,@LineTotalGross = isnull(BillableCost, 0)
								,@LineTotalCost = isnull(TotalCost, 0)	
								,@ProjectKey = ProjectKey
								,@TaskKey = TaskKey
								,@ItemKey = ItemKey
								,@OfficeKey = OfficeKey
								,@DepartmentKey = DepartmentKey
								from tPurchaseOrderDetail (nolock)
								where PurchaseOrderDetailKey = @PurchaseOrderDetailKey
							
								--what can we apply? if line > than invoice left to allocate, need to adjust
								if @AmtApplyNet > @TotalInvoiceNet
									select @AmtApplyNet = @TotalInvoiceNet  --apply remaining balance of invoice
									
								-- check for zero cost spots
								--if @LineTotalCost = 0
								--	select @Commission = 0
								--else
								--	select @Commission = ((@LineTotalGross/@LineTotalCost) - 1) * 100
								
								--Comm = (1 - Net/Gross) * 100
								if @LineTotalGross = 0
									select @Commission = 0
								else
									select @Commission = (1 - @LineTotalCost/@LineTotalGross) * 100

								if @BCClientLink = 1 --	link to client through project (required)
									begin
										if isnull(@ProjectKey, 0) = 0
											begin
												rollback tran
												return -13
											end
									
										if isnull(@TaskKey, 0) = 0
											if @RequireTasks = 1
												begin
													rollback tran
													return -14
												end
									end			
								   
								if @RequireItems = 1
									if @ItemKey is null
										begin
											rollback tran
											return -15
										end										

								if ISNULL(@ItemKey, 0) > 0
									Select @ExpenseAccountKey = ExpenseAccountKey from tItem (NOLOCK) Where ItemKey = @ItemKey

								if ISNULL(@ExpenseAccountKey, 0) = 0
									Select @ExpenseAccountKey = DefaultExpenseAccountKey from tCompany (NOLOCK) Where CompanyKey = @VendorKey
									
								if ISNULL(@ExpenseAccountKey, 0) = 0
									Select @ExpenseAccountKey = DefaultExpenseAccountKey from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
											
								if @RequireAccounts = 1 and ISNULL(@ExpenseAccountKey, 0) = 0
										begin
											rollback tran
											return -16
										end
								
								-- If using Projects/Tasks - Check to see if the associated Task is completed
								if ISNULL(@CMP,0) = 0 and ISNULL(@TaskKey,0) > 0
									BEGIN
										exec @RetVal = spTaskValidatePercComp ''tVoucherDetail'',NULL, NULL, @ProjectKey, NULL, @TaskKey, @UserKey
										if @RetVal < -1 
											BEGIN
												rollback tran
												return -21
											END
									END
																		
								exec @RetVal = sptVoucherDetailInsert
									@VoucherKey,
									@PurchaseOrderDetailKey,
									null,
									@ProjectKey,
									@TaskKey,
									@ItemKey,
									@ClassKey,
									'''', --Comments
									1,  -- always set quantity to 1 since the line is at spot level or bottom line, either way it s/b 1  
									null,
									null,
									@AmtApplyNet,
									null,
									1,
									null, -- Markup, because null, will be recalculated in sp
									@AmtApplyGross,
									@ExpenseAccountKey,
									0,
									0,
									1, -- LastVoucher
									@OfficeKey,
									@DepartmentKey,
									1, -- @CheckProject
									@Commission,
									null, -- GrossAmount, because null, will be recalculated in sp
									null,        -- PCurrencyID
									1,           -- PExchangeRate
									@AmtApplyNet,  -- PTotalCost
									@VoucherDetailKey output
									
								if @RetVal = -2
									begin
										rollback tran
										return -17 --Project Status does not allow additional costs
									end
									
								if @RetVal = -1
									begin
										rollback tran
										return -18 --Problem inserting line
									end
									
								--now subtract just applied amount from total invoice amount left to apply
								select @TotalInvoiceNet = @TotalInvoiceNet - @AmtApplyNet
								if @TotalInvoiceNet = 0 and @MatchedTotals <> 0
									break
							end	
					end	
			end
	end
	
-- Apply the remaining amount
if @TotalInvoiceNet > 0 
	begin
		-- Which PurchaseOrderDetailKey should we use
		if @LastPurchaseOrderDetailKey is null
			Begin
				Select @PurchaseOrderDetailKey = max(PurchaseOrderDetailKey)
				From tPurchaseOrderDetail (nolock)
				where PurchaseOrderKey = @PurchaseOrderKey
				
				Select @AmtApplyNet = @TotalInvoiceNet
				,@AmtApplyGross = 0
				,@LineTotalGross = 0
				,@LineTotalCost = @TotalInvoiceNet
				,@LinkID = SUBSTRING(LinkID, 0, CHARINDEX(''-'', LinkID)) 
				,@SpotLinkID = SUBSTRING(LinkID, CHARINDEX(''-'', LinkID)+1, LEN(LinkID))
				,@StartDate = DetailOrderDate
				,@EndDate = DetailOrderEndDate
				,@Quantity = 1
				,@UnitRate = UnitRate
				,@PODMarkup =ISNULL(Markup,0)
				,@Program = ShortDescription
				,@Comments = LongDescription
				,@OrderDays = OrderDays
				,@OrderTime = OrderTime
				,@UserDate1 = UserDate1
				,@UserDate2 = UserDate2
				,@UserDate3 = UserDate3
				,@UserDate4 = UserDate4
				,@UserDate5 = UserDate5
				,@UserDate6 = UserDate6
				,@OrderLength = OrderLength
				,@ProjectKey = ProjectKey
				,@TaskKey = TaskKey
				,@ItemKey = ItemKey
				,@OfficeKey = OfficeKey
				,@DepartmentKey = DepartmentKey
			from tPurchaseOrderDetail (nolock)
			where PurchaseOrderDetailKey = @PurchaseOrderDetailKey

			if @RequireItems = 1
				if @ItemKey is null
					begin
						rollback tran
						return -15
					end										

			if ISNULL(@ItemKey, 0) > 0
				Select @ExpenseAccountKey = ExpenseAccountKey from tItem (NOLOCK) Where ItemKey = @ItemKey

			if ISNULL(@ExpenseAccountKey, 0) = 0
				Select @ExpenseAccountKey = DefaultExpenseAccountKey from tCompany (NOLOCK) Where CompanyKey = @VendorKey
				
			if ISNULL(@ExpenseAccountKey, 0) = 0
				Select @ExpenseAccountKey = DefaultExpenseAccountKey from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
						
			if @RequireAccounts = 1 and ISNULL(@ExpenseAccountKey, 0) = 0
				begin
					rollback tran
					return -16
				end				
			
			-- *** Create the Revision line here ***
			
			EXEC @RetVal = sptPurchaseOrderDetailInsert 
				@PurchaseOrderKey = @PurchaseOrderKey,
				@LineNumber = @LineNumber,
				@ProjectKey = @ProjectKey,
				@TaskKey = @TaskKey,
				@ItemKey = @ItemKey,
				@ClassKey = @ClassKey,
				@ShortDescription = @Program,
				@Quantity = 1,
				@UnitCost = @TotalInvoiceNet,
				@UnitDescription = NULL,
				@TotalCost = @TotalInvoiceNet,
				@UnitRate = @TotalInvoiceNet,
				@Billable = 1,
				@Markup = @PODMarkup,
				@BillableCost = @TotalInvoiceGross,
				@LongDescription = @Comments,
				@CustomFieldKey = 0,
				@DetailOrderDate = @StartDate,
				@DetailOrderEndDate = @EndDate,
				@UserDate1 = @UserDate1,
				@UserDate2 = @UserDate2,
				@UserDate3 = @UserDate3,
				@UserDate4 = @UserDate4,
				@UserDate5 = @UserDate5,
				@UserDate6 = @UserDate6,
				@OrderDays = @OrderDays,
				@OrderTime = @OrderTime,
				@OrderLength = @OrderLength,
				@Taxable = 0,
				@Taxable2 = 0,
				@OfficeKey = @OfficeKey,
				@DepartmentKey = @DepartmentKey,
				@GrossAmount = @TotalInvoiceGross,
				@PCurrencyID = NULL,
				@PExchangeRate = 1,
				@PTotalCost = @TotalInvoiceNet,
				@SkipRollUps = NULL,
				@InteractiveAdUnitName = NULL,
				@oIdentity = @RevisionPurchaseOrderDetailKey OUTPUT
								
			if ISNULL(@RevisionPurchaseOrderDetailKey, 0) > 0
				Begin
					update tPurchaseOrderDetail
					set AutoAdjustment = 2
					where PurchaseOrderDetailKey = @RevisionPurchaseOrderDetailKey
				End
				
			if @RetVal < 0
			begin
				rollback tran
				return -19 --Problem applying Total Invoice Net difference
			end
			
			Select @PurchaseOrderDetailKey = @RevisionPurchaseOrderDetailKey
			select @LastPurchaseOrderDetailKey = @PurchaseOrderDetailKey
			
			Select @LastPurchaseOrderDetailKey = @PurchaseOrderDetailKey

			select @AmtApplyNet = isnull(TotalCost, 0) - isnull(AppliedCost, 0)
			,@AmtApplyGross = 
				case @BillAt
					when 0 then isnull(BillableCost, 0) - isnull(AmountBilled, 0)
					when 1 then isnull(TotalCost, 0) - isnull(AmountBilled, 0)
					when 2 then isnull(BillableCost, 0) - isnull(TotalCost, 0) - isnull(AmountBilled, 0)
				end 
			,@LineTotalGross = isnull(BillableCost, 0)
			,@LineTotalCost = isnull(TotalCost, 0)	
			,@ProjectKey = ProjectKey
			,@TaskKey = TaskKey
			,@ItemKey = ItemKey
			,@OfficeKey = OfficeKey
			,@DepartmentKey = DepartmentKey
			from tPurchaseOrderDetail (nolock)
			where PurchaseOrderDetailKey = @PurchaseOrderDetailKey
							
			--what can we apply? if line > than invoice left to allocate, need to adjust
			if @AmtApplyNet > @TotalInvoiceNet
				select @AmtApplyNet = @TotalInvoiceNet  --apply remaining balance of invoice
									
			-- check for zero cost spots
			--if @LineTotalCost = 0
			--	select @Commission = 0
			--else
			--	select @Commission = ((@LineTotalGross/@LineTotalCost) - 1) * 100
								
			--Comm = (1 - Net/Gross) * 100
			if @LineTotalGross = 0
				select @Commission = 0
			else
				select @Commission = (1 - @LineTotalCost/@LineTotalGross) * 100


			if @BCClientLink = 1 --	link to client through project (required)
				begin
					if isnull(@ProjectKey, 0) = 0
						begin
							rollback tran
							return -13
						end
									
					if isnull(@TaskKey, 0) = 0
						if @RequireTasks = 1
							begin
								rollback tran
								return -14
							end
				end			
								   
			if @RequireItems = 1
				if @ItemKey is null
					begin
						rollback tran
						return -15
					end										

			if ISNULL(@ItemKey, 0) > 0
				Select @ExpenseAccountKey = ExpenseAccountKey from tItem (NOLOCK) Where ItemKey = @ItemKey

			if ISNULL(@ExpenseAccountKey, 0) = 0
				Select @ExpenseAccountKey = DefaultExpenseAccountKey from tCompany (NOLOCK) Where CompanyKey = @VendorKey
									
			if ISNULL(@ExpenseAccountKey, 0) = 0
				Select @ExpenseAccountKey = DefaultExpenseAccountKey from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
											
			if @RequireAccounts = 1 and ISNULL(@ExpenseAccountKey, 0) = 0
					begin
						rollback tran
						return -16
					end
								
			-- If using Projects/Tasks - Check to see if the associated Task is completed
			if ISNULL(@CMP,0) = 0 and ISNULL(@TaskKey,0) > 0
				BEGIN
					exec @RetVal = spTaskValidatePercComp ''tVoucherDetail'',NULL, NULL, @ProjectKey, NULL, @TaskKey, @UserKey
					if @RetVal < -1 
						BEGIN
							rollback tran
							return -21
						END
				END
																		
			exec @RetVal = sptVoucherDetailInsert
				@VoucherKey,
				@PurchaseOrderDetailKey,
				null,
				@ProjectKey,
				@TaskKey,
				@ItemKey,
				@ClassKey,
				'''', --Comments
				1,  -- always set quantity to 1 since the line is at spot level or bottom line, either way it s/b 1  
				null,
				null,
				@AmtApplyNet,
				null,
				1,
				null, -- Markup, because null, will be recalculated in sp
				@AmtApplyGross,
				@ExpenseAccountKey,
				0,
				0,
				1, -- LastVoucher
				@OfficeKey,
				@DepartmentKey,
				1, -- @CheckProject
				@Commission,
				null, -- GrossAmount, because null, will be recalculated in sp
				null,        -- PCurrencyID
				1,           -- PExchangeRate
				@AmtApplyNet,  -- PTotalCost
				@VoucherDetailKey output
									
			if @RetVal = -2
				begin
					rollback tran
					return -17 --Project Status does not allow additional costs
				end
									
			if @RetVal = -1
				begin
					rollback tran
					return -18 --Problem inserting line
				end
								
			
			end
		else
		begin
			Select @PurchaseOrderDetailKey = @LastPurchaseOrderDetailKey
		
		-- Which VoucherDetail record should we update
		Select @VoucherDetailKey = VoucherDetailKey
			 , @ClientKey = ClientKey
			 , @ExpenseAccountKey = ExpenseAccountKey
			 , @AmtApplyGross = BillableCost
		From tVoucherDetail (nolock)
		Where PurchaseOrderDetailKey = @PurchaseOrderDetailKey
		
		select @AmtApplyNet = isnull(AppliedCost, 0) + @TotalInvoiceNet
			,@ProjectKey = ProjectKey
			,@TaskKey = TaskKey
			,@ItemKey = ItemKey
			,@OfficeKey = OfficeKey
			,@DepartmentKey = DepartmentKey
			,@LineTotalGross = isnull(BillableCost, 0) -- Was AppliedCost (379452)
			,@LineTotalCost = isnull(TotalCost, 0)	
			from tPurchaseOrderDetail (nolock)
			where PurchaseOrderDetailKey = @PurchaseOrderDetailKey
			
		if @RequireItems = 1
			if @ItemKey is null
				begin
					rollback tran
					return -15
				end										

		if ISNULL(@ItemKey, 0) > 0
			Select @ExpenseAccountKey = ExpenseAccountKey from tItem (NOLOCK) Where ItemKey = @ItemKey

		if ISNULL(@ExpenseAccountKey, 0) = 0
			Select @ExpenseAccountKey = DefaultExpenseAccountKey from tCompany (NOLOCK) Where CompanyKey = @VendorKey
			
		if ISNULL(@ExpenseAccountKey, 0) = 0
			Select @ExpenseAccountKey = DefaultExpenseAccountKey from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
					
		if @RequireAccounts = 1 and ISNULL(@ExpenseAccountKey, 0) = 0
			begin
				rollback tran
				return -16
			end	
			
		-- check for zero cost spots
		--if @LineTotalCost  = 0
		--	select @Commission = 0
		--else
		--	select @Commission = ((@LineTotalGross  /@LineTotalCost) - 1) * 100
						
		--Comm = (1 - Net/Gross) * 100
		if @LineTotalGross = 0
			select @Commission = 0
		else
			select @Commission = (1 - @LineTotalCost/@LineTotalGross) * 100
																	
		exec @RetVal = sptVoucherDetailUpdate
			@VoucherDetailKey,
			@VoucherKey,
			@PurchaseOrderDetailKey,
			@ClientKey,
			@ProjectKey,
			@TaskKey,
			@ItemKey,
			@ClassKey,
			'''', --Comments
			1,  -- always set quantity to 1 since the line is at spot level or bottom line, either way it s/b 1  
			null,
			null,
			@AmtApplyNet,
			null,
			1,
			null, -- Markup, because null, will be recalculated in sp
			@AmtApplyGross,
			@ExpenseAccountKey,
			0,
			0,
			1, -- LastVoucher
			@OfficeKey,
			@DepartmentKey,
			NULL, -- TargetGLCompanyKey
			1, -- Project Rollup
			@Commission,
			null, -- GrossAmount, because null, will be recalculated in sp
			null,        -- PCurrencyID
			1,           -- PExchangeRate
			@AmtApplyNet,  -- PTotalCost
			1             -- GLCExchangeRate

		if @RetVal < 0
			begin
				rollback tran
				return -19 --Problem applying Total Invoice Net difference
			end
		end
	end -- end Apply the remaining amount			

	if @CloseMonthBLInvoice = 1
	begin -- begin close month
	 -- If the invoice is for less than the order we''ll need to create order revision lines for
	 -- the date range of the Invoice.
		Declare @Remaining_bal decimal(24,4)
		
		if @IgnoreDates = 1
			select @Remaining_bal = sum(isnull(TotalCost,0) - isnull(AppliedCost,0))
			from tPurchaseOrderDetail
			where PurchaseOrderKey = @PurchaseOrderKey
		else
			select @Remaining_bal = sum(isnull(TotalCost,0) - isnull(AppliedCost,0))
			from tPurchaseOrderDetail
			where PurchaseOrderKey = @PurchaseOrderKey
			and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
				
		
		select @Remaining_bal = isnull(@Remaining_bal,0)
		
		if @Remaining_bal <> 0  
			Begin
			-- Which PurchaseOrderDetailKey should we use
			if @LastPurchaseOrderDetailKey is null
				begin
					if @IgnoreDates = 1
						Select @PurchaseOrderDetailKey = max(PurchaseOrderDetailKey)
						From tPurchaseOrderDetail (nolock)
						where PurchaseOrderKey = @PurchaseOrderKey
					else
						Select @PurchaseOrderDetailKey = max(PurchaseOrderDetailKey)
						From tPurchaseOrderDetail (nolock)
						where PurchaseOrderKey = @PurchaseOrderKey
						and DetailOrderDate between @DateRangeBegin and @DateRangeEnd -- Original date range for the invoice (month)
					
				end
			else
				Select @PurchaseOrderDetailKey = @LastPurchaseOrderDetailKey
			end 
				
			Select @AmtApplyNet = ISNULL(TotalCost, 0) - ISNULL(AppliedCost, 0)
				,@AmtApplyGross = 
					case @BillAt
						when 0 then isnull(BillableCost, 0) - isnull(AmountBilled, 0)
						when 1 then isnull(TotalCost, 0) - isnull(AmountBilled, 0)
						when 2 then isnull(BillableCost, 0) - isnull(TotalCost, 0) - isnull(AmountBilled, 0)
					end 
				,@LineTotalGross = isnull(BillableCost, 0)
				,@LineTotalCost = isnull(TotalCost, 0)
				,@LinkID = SUBSTRING(LinkID, 0, CHARINDEX(''-'', LinkID)) 
				,@SpotLinkID = SUBSTRING(LinkID, CHARINDEX(''-'', LinkID)+1, LEN(LinkID))
				,@StartDate = DetailOrderDate
				,@EndDate = DetailOrderEndDate
				,@Quantity = 1
				,@UnitRate = UnitRate
				,@PODMarkup =ISNULL(Markup,0)
				,@Program = ShortDescription
				,@Comments = LongDescription
				,@OrderDays = OrderDays
				,@OrderTime = OrderTime
				,@UserDate1 = UserDate1
				,@UserDate2 = UserDate2
				,@UserDate3 = UserDate3
				,@UserDate4 = UserDate4
				,@UserDate5 = UserDate5
				,@UserDate6 = UserDate6
				,@OrderLength = OrderLength
				,@ProjectKey = ProjectKey
				,@TaskKey = TaskKey
				,@ItemKey = ItemKey
				,@OfficeKey = OfficeKey
				,@DepartmentKey = DepartmentKey
			from tPurchaseOrderDetail (nolock)
			where PurchaseOrderDetailKey = @PurchaseOrderDetailKey

			if @RequireItems = 1
				if @ItemKey is null
					begin
						rollback tran
						return -15
					end										

			if ISNULL(@ItemKey, 0) > 0
				Select @ExpenseAccountKey = ExpenseAccountKey from tItem (NOLOCK) Where ItemKey = @ItemKey

			if ISNULL(@ExpenseAccountKey, 0) = 0
				Select @ExpenseAccountKey = DefaultExpenseAccountKey from tCompany (NOLOCK) Where CompanyKey = @VendorKey
				
			if ISNULL(@ExpenseAccountKey, 0) = 0
				Select @ExpenseAccountKey = DefaultExpenseAccountKey from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
						
			if @RequireAccounts = 1 and ISNULL(@ExpenseAccountKey, 0) = 0
				begin
					rollback tran
					return -16
				end				
			
			-- Check to see how much of the OrderLine needs to be revsersed
			if ISNULL(@PODMarkup,0) = 0 
				select @PODGross = (@Remaining_bal * -1)
			else
				Select @PODGross = (@Remaining_bal /(1 - (ISNULL(@PODMarkup,0) * .010))	* -1)
			
			
			select @Remaining_bal = (@Remaining_bal * -1)
			
			-- *** Create the Revision line here ***
			
		EXEC @RetVal = sptPurchaseOrderDetailInsert 
			@PurchaseOrderKey = @PurchaseOrderKey,
			@LineNumber = @LineNumber,
			@ProjectKey = @ProjectKey,
			@TaskKey = @TaskKey,
			@ItemKey = @ItemKey,
			@ClassKey = @ClassKey,
			@ShortDescription = @Program,
			@Quantity = -1,
			@UnitCost = @UnitRate,
			@UnitDescription = NULL,
			@TotalCost = @Remaining_bal,
			@UnitRate = @UnitRate,
			@Billable = 1,
			@Markup = @PODMarkup,
			@BillableCost = @PODGross,
			@LongDescription = @Comments,
			@CustomFieldKey = 0,
			@DetailOrderDate = @StartDate,
			@DetailOrderEndDate = @EndDate,
			@UserDate1 = @UserDate1,
			@UserDate2 = @UserDate2,
			@UserDate3 = @UserDate3,
			@UserDate4 = @UserDate4,
			@UserDate5 = @UserDate5,
			@UserDate6 = @UserDate6,
			@OrderDays = @OrderDays,
			@OrderTime = @OrderTime,
			@OrderLength = @OrderLength,
			@Taxable = 0,
			@Taxable2 = 0,
			@OfficeKey = @OfficeKey,
			@DepartmentKey = @DepartmentKey,
			@GrossAmount = @PODGross,
			@PCurrencyID = NULL,
			@PExchangeRate = 1,
			@PTotalCost = @Remaining_bal,
			@SkipRollUps = NULL,
			@InteractiveAdUnitName = NULL,
			@oIdentity = @RevisionPurchaseOrderDetailKey OUTPUT
					
			
			if ISNULL(@RevisionPurchaseOrderDetailKey, 0) > 0
				Begin
					update tPurchaseOrderDetail
					set AutoAdjustment = 2
					where PurchaseOrderDetailKey = @RevisionPurchaseOrderDetailKey
				End
				
				if @RetVal < 0
				begin
					rollback tran
					return -19 --Problem applying Total Invoice Net difference
				end
			
			select @PurchaseOrderDetailKey = -1
			while (1=1)
				begin -- close remaining rows
				    if @IgnoreDates = 1
					    select @PurchaseOrderDetailKey = MIN(PurchaseOrderDetailKey)
						from tPurchaseOrderDetail (nolock)
						where PurchaseOrderDetailKey > @PurchaseOrderDetailKey
						and PurchaseOrderKey = @PurchaseOrderKey
						and isnull(AppliedCost,0) <> TotalCost
					else
					    select @PurchaseOrderDetailKey = MIN(PurchaseOrderDetailKey)
						from tPurchaseOrderDetail (nolock)
						where PurchaseOrderDetailKey > @PurchaseOrderDetailKey
						and PurchaseOrderKey = @PurchaseOrderKey
						and DetailOrderDate between @DateRangeBegin and @DateRangeEnd
						and isnull(AppliedCost,0) <> TotalCost
					
					if @PurchaseOrderDetailKey is NULL 
						break
	--				
					-- add VoucherDetail line
					
								select @AmtApplyNet = isnull(TotalCost, 0) - isnull(AppliedCost, 0)
								,@AmtApplyGross = 
									case @BillAt
										when 0 then isnull(BillableCost, 0) - isnull(AmountBilled, 0)
										when 1 then isnull(TotalCost, 0) - isnull(AmountBilled, 0)
										when 2 then isnull(BillableCost, 0) - isnull(TotalCost, 0) - isnull(AmountBilled, 0)
									end 
								,@LineTotalGross = isnull(BillableCost, 0)
								,@LineTotalCost = isnull(TotalCost, 0)	
								,@ProjectKey = ProjectKey
								,@TaskKey = TaskKey
								,@ItemKey = ItemKey
								,@OfficeKey = OfficeKey
								,@DepartmentKey = DepartmentKey
								from tPurchaseOrderDetail (nolock)
								where PurchaseOrderDetailKey = @PurchaseOrderDetailKey
							
								--what can we apply? if line > than invoice left to allocate, need to adjust
							--	if @AmtApplyNet > @TotalInvoiceNet
							--		select @AmtApplyNet = @TotalInvoiceNet  --apply remaining balance of invoice
									
								-- check for zero cost spots
								--if @LineTotalCost = 0
								--	select @Commission = 0
								--else
								--	select @Commission = ((@LineTotalGross/@LineTotalCost) - 1) * 100
								
								--Comm = (1 - Net/Gross) * 100
								if @LineTotalGross = 0
									select @Commission = 0
								else
									select @Commission = (1 - @LineTotalCost/@LineTotalGross) * 100

								if @BCClientLink = 1 --	link to client through project (required)
									begin
										if isnull(@ProjectKey, 0) = 0
											begin
												rollback tran
												return -13
											end
									
										if isnull(@TaskKey, 0) = 0
											if @RequireTasks = 1
												begin
													rollback tran
													return -14
												end
									end			
								   
								if @RequireItems = 1
									if @ItemKey is null
										begin
											rollback tran
											return -15
										end										

								if ISNULL(@ItemKey, 0) > 0
									Select @ExpenseAccountKey = ExpenseAccountKey from tItem (NOLOCK) Where ItemKey = @ItemKey

								if ISNULL(@ExpenseAccountKey, 0) = 0
									Select @ExpenseAccountKey = DefaultExpenseAccountKey from tCompany (NOLOCK) Where CompanyKey = @VendorKey
									
								if ISNULL(@ExpenseAccountKey, 0) = 0
									Select @ExpenseAccountKey = DefaultExpenseAccountKey from tPreference (NOLOCK) Where CompanyKey = @CompanyKey
											
								if @RequireAccounts = 1 and ISNULL(@ExpenseAccountKey, 0) = 0
										begin
											rollback tran
											return -16
										end
								
								-- If using Projects/Tasks - Check to see if the associated Task is completed
								if ISNULL(@CMP,0) = 0 and ISNULL(@TaskKey,0) > 0
									BEGIN
										exec @RetVal = spTaskValidatePercComp ''tVoucherDetail'',NULL, NULL, @ProjectKey, NULL, @TaskKey, @UserKey
										if @RetVal < -1 
											BEGIN
												rollback tran
												return -21
											END
									END
																		
								exec @RetVal = sptVoucherDetailInsert
									@VoucherKey,
									@PurchaseOrderDetailKey,
									null,
									@ProjectKey,
									@TaskKey,
									@ItemKey,
									@ClassKey,
									'''', --Comments
									1,  -- always set quantity to 1 since the line is at spot level or bottom line, either way it s/b 1  
									null,
									null,
									@AmtApplyNet,
									null,
									1,
									null, -- Markup, because null, will be recalculated in sp
									@AmtApplyGross,
									@ExpenseAccountKey,
									0,
									0,
									1, -- LastVoucher
									@OfficeKey,
									@DepartmentKey,
									1, -- @CheckProject
									@Commission,
									null, -- GrossAmount, because null, will be recalculated in sp
									null,        -- PCurrencyID
									1,           -- PExchangeRate
									@AmtApplyNet,  -- PTotalCost
									@VoucherDetailKey output
					
			--		update tPurchaseOrderDetail 
			--		set Closed = 1
			--		where PurchaseOrderDetailKey = @PurchaseOrderDetailKey
				
				end -- close remaining rows
	end  -- end close month
	
	select @Closed = min(Closed) from tPurchaseOrderDetail POD
	where POD.PurchaseOrderKey = @PurchaseOrderKey
	
	update tPurchaseOrder
	set Closed = @Closed
	where PurchaseOrderKey = @PurchaseOrderKey
		
EXEC sptVoucherRecalcAmounts @VoucherKey

commit tran
	


'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptTaskSetComplete]'
GO
IF OBJECT_ID(N'[dbo].[sptTaskSetComplete]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptTaskSetComplete]
	@TaskKey int,
	@UserKey int,
	@CompleteDate smalldatetime,
	@ServiceKey int,
	@ForcePercCompSeparateOff int = 0,
	@ProjectKey int output,
	@PercComp int output
AS --Encrypt

  /*
  || When     Who Rel   What
  || 01/24/07 GHL 8.4   Added parameter @PercComp to send notifications when the task is complete 
  || 01/30/07 GHL 8.4   Added validation of ActStart and ActComplete before saving                 
  || 02/08/07 GHL 8.4   Added roll down of PercComp, ActStart, ActComplete when PercCompSeparate = 0    
  || 11/03/17 RLB 10621 Added check so that it will only update if the task or task user is not 100 already  
  || 01/31/18 RLB 18.2  (382852) Adding ServiceKey in case the same user is on the same task with Different service   
  || 04/03/26 GAR 26.05.17 (724638) Add optional parameter to force perc complete separate so I can pass in a task and have it completed without having to pass each tTaskUser record
  */
  
	DECLARE	@PercCompSeparate tinyint,
			@PlanStart smalldatetime,
			@ActStart smalldatetime,
			@PlanDuration int,
			@CurrentPercComp int,
			@WithService tinyint

	-- adding a check to see if the task user has the service passed in
	SELECT @WithService = 0

	IF ISNULL(@ServiceKey, 0)  > 0
		IF EXISTS(SELECT 1 FROM tTaskUser (NOLOCK) WHERE TaskKey = @TaskKey AND UserKey = @UserKey AND ServiceKey = @ServiceKey) 
			SELECT @WithService = 1
	
	SELECT	@PercCompSeparate = PercCompSeparate,
			@ProjectKey = ProjectKey,
			@PlanStart = PlanStart,
			@ActStart = ActStart,
			@PlanDuration = PlanDuration,
			@CurrentPercComp = PercComp
	FROM	tTask (NOLOCK)
	WHERE	TaskKey = @TaskKey

	If @ForcePercCompSeparateOff = 1
		SET @PercCompSeparate = 0
	
	IF @PercCompSeparate = 1
		BEGIN
			-- Rollup from tTaskUser to tTask
			SELECT	@ActStart = ActStart,
					@CurrentPercComp = PercComp
			FROM	tTaskUser (NOLOCK)
			WHERE	TaskKey = @TaskKey
			AND     UserKey = @UserKey
			
			IF @ActStart IS NULL
				SELECT @ActStart = @PlanStart
				
			IF @ActStart > @CompleteDate
				SELECT @ActStart = @CompleteDate 
					,@PlanDuration = 0
			
			IF @CurrentPercComp <> 100
			BEGIN
			-- per GG if service does not match just do it the old way and only applies to Track actuals sep
				if @WithService = 0
					UPDATE	tTaskUser
					SET		PercComp = 100,
							ActComplete = @CompleteDate,
							ActStart = @ActStart,
							CompletedByDate = GETUTCDATE(),
							CompletedByKey = @UserKey
					WHERE	TaskKey = @TaskKey
					AND		UserKey = @UserKey
				else
					UPDATE	tTaskUser
					SET		PercComp = 100,
							ActComplete = @CompleteDate,
							ActStart = @ActStart,
							CompletedByDate = GETUTCDATE(),
							CompletedByKey = @UserKey
					WHERE	TaskKey = @TaskKey
					AND		UserKey = @UserKey
					AND     ServiceKey = @ServiceKey
			
				EXEC sptTaskUserRollup @TaskKey			
			END		
		
		END
	ELSE
	BEGIN	
		-- Rolldown from tTask to tTaskUser
		IF @ActStart IS NULL
			SELECT @ActStart = @PlanStart
			
		IF @ActStart > @CompleteDate
			SELECT @ActStart = @CompleteDate 
			      ,@PlanDuration = 0
		IF @CurrentPercComp <> 100
		BEGIN
			UPDATE	tTask
			SET		PercComp = 100,
					ActComplete = @CompleteDate,
					ActStart = @ActStart,
					PlanDuration = @PlanDuration,
					CompletedByDate = GETUTCDATE(),
					CompletedByKey = @UserKey
			WHERE	TaskKey = @TaskKey
	
			EXEC sptTaskUserRolldown @TaskKey			
		END		
			
	END
	
	-- If the task is now 100% complete, we need to send notifications	
	SELECT @PercComp = ISNULL(PercComp, 0)
	FROM   tTask (NOLOCK)
	WHERE  TaskKey = @TaskKey 
	
	'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spProjectLoadTasks]'
GO
IF OBJECT_ID(N'[dbo].[spProjectLoadTasks]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[spProjectLoadTasks]
	(
	@ProjectKey int
	)
AS

/*
|| When       Who Rel      What
|| 05/11/10   CRG 10.5.2.2 Added IconID to the select list
|| 01/10/11   CRG 10.5.4.0 Added ProjectNumber, ProjectName, TaskColor
|| 03/20/11   GWG 10.5.4.2 Added Open To Do Count
|| 03/10/14   RLB 10.5.7.8 (196273) 
|| 07/07/15   RLB 10.5.9.4 Added Work Type ID and Name for plat
|| 07/30/15   RLB 10.5.9.4 Added a few items i had missed
|| 02/04/16   RLB 10.6.0.0 Added Fields for updating task in Plat
|| 02/16/16   CRG 10.6.0.1 Added TotalEstHours
|| 02/09/17   RLB 10.6.1.3 Added for enhancement 328679
|| 02/20/17   RLB 10.6.1.3 Added field for customization
|| 08/10/18   CRG 18.8.0.0 Added OrigPercComp so that we can track changed tasks in the schedule
|| 09/27/18   CRG 18.9.1.1 Now removing tasks with bad SummaryTaskKeys from the table prior to loading
|| 10/01/19   CRG 19.1.0.0 (480550) Now overriding a NULL SegmentColor with ProjectColor
|| 09/07/21   CRG 21.09.18 (569967) Added OrigActStart and OrigActComplete
|| 09/23/22   GAR 22.10.16 (DEV2605) Added AvalaraTaxCodeKey
|| 11/09/22   GAR 22.12.18 (618114) Added Conversation Count
|| 05/08/23   CRG 23.06.18 (604775) Changed Priority to TaskPriorityKey
|| 11/27/24   RLS 25.01.19 (685516) Added AllocatedHoursGross, SumRate and CurrentBudgetLaborGross
|| 12/17/25   CRG 26.02.15 (548907) Added FreqName and filtering out all but the current active recurring task
|| 04/15/26   GAR 26.05.17 (726555) Added DeliverableCount
|| 04/27/26   GAR 26.05.17 (727081) Added BudgetRemainingHours
*/

--Validate the SummaryTaskKeys
SELECT	TaskKey, SummaryTaskKey, RecurringFreq
INTO	#Keys
FROM	tTask (nolock)
WHERE	ProjectKey = @ProjectKey

IF EXISTS(
		SELECT	NULL
		FROM	#Keys
		WHERE	ISNULL(RecurringFreq, 0) > 0)
	DELETE	#Keys
	FROM	vTaskRecurringActive v
	INNER JOIN #Keys k ON v.TaskKey = k.TaskKey
	WHERE	ISNULL(v.RecurringFreq, 0) > 0
	AND		v.RecurringActive <> 1

SELECT	TaskKey
INTO	#BadKeys
FROM	#Keys
WHERE	SummaryTaskKey > 0
AND		SummaryTaskKey NOT IN (SELECT TaskKey FROM #Keys)

IF EXISTS (SELECT 1 FROM #BadKeys)
BEGIN
	DECLARE	@TaskKey int
	SELECT @TaskKey = -1

	WHILE(1=1)
	BEGIN
		SELECT	@TaskKey = MIN(TaskKey)
		FROM	#BadKeys
		WHERE	TaskKey > @TaskKey

		IF @TaskKey IS NULL
			BREAK

		EXEC sptTaskDelete @TaskKey
	END
END

select t.*
			,t.PercComp as OrigPercComp
			,t.ActStart as OrigActStart
			,t.ActComplete as OrigActComplete
			,t.EstHours as EstimateHours
			,t2.TaskName as SummaryTaskName
			,CASE WHEN t.TaskType = 2 THEN ''edit'' 
				  WHEN t.TaskType = 1 THEN 
										case when t.AllowAllocatedHours = 1 then ''edit''
										else '''' end
			 ELSE '''' END AS IconID
			,(select count(*) from tForm f (nolock) 
			   Where f.TaskKey = t.TaskKey 
			   and	f.DateClosed IS NULL) as FormCount
			,ISNULL((Select Sum(ActualHours) from tTime ti (nolock) 
				   Where ti.ProjectKey = t.ProjectKey 
				   And ti.TaskKey = t.TaskKey), 0) as ActualHours
			,ISNULL((Select Sum(Hours) from tTaskUser tau (nolock) 
					   Where tau.TaskKey = t.TaskKey), 0) as AllocatedHours
			,(select count(*) from tAttachment (nolock)
			   Where AssociatedEntity = ''Task'' AND
			   EntityKey = t.TaskKey) as AttachmentCount
			,(SELECT COUNT(*) FROM tActivity a (nolock) INNER JOIN tActivityLink al (nolock) ON a.ActivityKey = al.ActivityKey WHERE al.Entity = ''tTask'' AND al.EntityKey = t.TaskKey AND a.Completed = 0) AS OpenActivities
			,ISNULL((Select Count(*) from tActivity (nolock) Where ActivityEntity = ''ToDo'' and TaskKey = t.TaskKey and Completed = 0), 0) as ToDoCount
			, (SELECT COUNT(*) FROM tActivity a (nolock) WHERE a.TaskKey = t.TaskKey AND Completed = 0 AND a.ActivityEntity = ''ToDo'' AND ParentActivityKey = 0) AS OpenToDos
			,ISNULL(c.CompanyName, ''No Client'') AS CompanyName
			,p.ClientKey
			,ProjectNumber + '' - '' + ProjectName AS Project
			,p.ProjectNumber
			,p.ProjectName
			,p.CompanyKey
			,p.StartDate as ProjectStartDate
			,p.CompleteDate as ProjectCompleteDate
			,p.PercComp as ProjectPercComp
			,p.ProjectStatusKey
			,ps.ProjectStatus
			,ps.ProjectStatusID
			,pbs.ProjectBillingStatusKey
			,pbs.ProjectBillingStatus
			,pbs.ProjectBillingStatusID
			,ISNULL(u.UserName, ''No Account Manager'') AS UserName
			,u.UserKey as AccountManager
			,ISNULL(pt.ProjectTypeName, ''No Project Type'') AS ProjectTypeName
			,pt.ProjectTypeKey			
			,ISNULL(ca.CampaignName, ''No Campaign'') AS CampaignName
			,ca.CampaignKey
			,ISNULL(CAST(ts.SegmentColor as varchar), p.ProjectColor) AS TaskColor
			,ts.SegmentName
			,ISNULL(cps.SegmentName, ''No Campaign Segment'') AS CampaignSegmentName
			,cps.CampaignSegmentKey
			,wt.WorkTypeName
			,wt.WorkTypeID
			 ,CASE 
					WHEN ISNULL(t.TaskConstraint,0) = 0 THEN 
						CASE 
							WHEN p.ScheduleDirection = 1 THEN ''As Soon As Possible'' 
							ELSE ''As Late As Possible''
						END
					WHEN ISNULL(t.TaskConstraint,0) = 1 THEN ''Must Start On'' 
					WHEN ISNULL(t.TaskConstraint,0) = 2 THEN ''Must Finish On'' 
					WHEN ISNULL(t.TaskConstraint,0) = 3 THEN ''Finish No Earlier Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 4 THEN ''Finish No Later Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 5 THEN ''Start No Earlier Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 6 THEN ''Start No Later Than'' 
					WHEN ISNULL(t.TaskConstraint,0) = 7 THEN ''Duration Of Project''
					ELSE ''Client''
			  END AS ConstraintName
			,tp.PriorityName
			,CASE 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 0 THEN ''Any Day''
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 1 THEN ''Sunday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 2 THEN ''Monday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 3 THEN ''Tuesday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 4 THEN ''Wednesday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 5 THEN ''Thursday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 6 THEN ''Friday'' 
					WHEN ISNULL(t.ConstraintDayOfTheWeek,0) = 7 THEN ''Saturday'' 
					ELSE ''Any Day''
			  END AS ConstraintDayOfTheWeekName
			 ,CASE
				WHEN ISNULL(t.MoneyTask, 0) = 1 THEN ISNULL(t.ApprovedCOHours, 0) + ISNULL(t.EstHours, 0)
				ELSE 0
			  END AS TotalEstHours
			  ,ISNULL(tcps.ProjectStatus, '''') as TCProjectStatus
			  ,ISNULL(tcps.ProjectStatusID, '''') as TCProjectStatusID
			  , 0 as LagCustomizationSet
			  ,a.AvalaraTaxCode
			  ,ISNULL((Select count(*) from tActivity a (nolock) inner join tActivityLink al (nolock) on a.ActivityKey = al.ActivityKey  Where al.Entity = ''tTask'' and al.EntityKey = t.TaskKey and a.ParentActivityKey = 0 and a.ActivityEntity = ''Diary''), 0) as ConversationCount
			  ,ISNULL(p.EstLabor, 0)
			  ,ISNULL(tu.GrossAmount, 0) as AllocatedHoursGross
			  ,t.EstLabor + t.ApprovedCOLabor as CurrentBudgetLaborGross
			  ,CASE
				WHEN ISNULL(t.RecurringFreq, 0) = 0 THEN ''None''
				WHEN ISNULL(t.RecurringFreq, 0) = 1 THEN ''Weekly''
				WHEN ISNULL(t.RecurringFreq, 0) = 2 THEN ''Monthly''
			   END AS FreqName
			   ,(Select COUNT(*) from tReviewDeliverable (NOLOCK) Where ProjectKey = p.ProjectKey and TaskKey = tmp.TaskKey and tReviewDeliverable.Completed = 0) as DeliverableCount
			   ,(ISNULL(t.EstHours, 0) +  ISNULL(t.ApprovedCOHours, 0)) - (ISNULL((Select Sum(ActualHours) from tTime ti (nolock) Where ti.ProjectKey = t.ProjectKey And ti.TaskKey = t.TaskKey), 0)) as BudgetRemainingHours
   from #Keys tmp
   inner join tTask t (nolock) on tmp.TaskKey = t.TaskKey
   inner join tProject p (nolock) on t.ProjectKey = p.ProjectKey
   LEFT JOIN (
		SELECT SUM(GrossAmount) AS GrossAmount, TaskKey
		FROM (
			SELECT AHourlyRate * Hours AS GrossAmount, ttu.TaskKey
			FROM tTaskUser ttu (nolock) 
			INNER JOIN tTask tt (nolock) ON ttu.TaskKey = tt.TaskKey
			WHERE ProjectKey = @ProjectKey
		) tus
		GROUP BY TaskKey
	) tu ON t.TaskKey = tu.TaskKey
   left join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
   left join tProjectStatus tcps (nolock) on t.TCProjectStatusKey = tcps.ProjectStatusKey
   left join tTimelineSegment ts (nolock) ON t.TimelineSegmentKey = ts.TimelineSegmentKey
   left join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
   left join tTask t2 (nolock) ON t.SummaryTaskKey = t2.TaskKey
   left join tCompany c (nolock) ON p.ClientKey = c.CompanyKey
   left join vUserName u  (nolock) ON p.AccountManager = u.UserKey
   left join tProjectType pt (nolock) ON p.ProjectTypeKey = pt.ProjectTypeKey
   left join tCampaign ca (nolock) ON p.CampaignKey = ca.CampaignKey
   left join tCampaignSegment cps (nolock) ON p.CampaignSegmentKey = cps.CampaignSegmentKey
   left join tWorkType wt (nolock) on t.WorkTypeKey = wt.WorkTypeKey
   left join tAvalaraTaxCode a (nolock) on t.AvalaraTaxCodeKey = a.AvalaraTaxCodeKey
   left join tTaskPriority tp (nolock) on t.TaskPriorityKey = tp.TaskPriorityKey
  order by t.ProjectOrder

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

/*
	This view shows Entries in the Credit Card Connector. Not actual credit card charges
  || When      Who Rel       What
  || 07/24/13  WDF 10.5.7.0  Created
  || 12/02/13  WDF 10.5.7.4  Added Approved By and Approval Status
  || 01/27/15  WDF 10.5.8.8 (Abelson Taylor) Added Division and Product
  || 03/10/15  WDF 10.5.9.0 (242377) Added [Transfer Out]
  || 08/20/16  GWG 10.6.0.7 Make the dates the same and not point to the date that does nothing.
  || 06/24/19  AMP 19.0.7.0 (467210) Added Charge Status
  || 10/29/19  WDF 19.1.1.0 (486051) Added ''YES/NO'' to Receipt
  || 09/02/20  RLB 20.1.0.0 (523772) making anything using user name common format
  || 09/29/22  RLB 22.10.16 (613559) Added Attachment count from head
  || 03/13/23  RLB 23.04.16 (629165) Adding Office Color and Department Color
  || 02/24/25  RLS 25.03.16 (694024) Added cc.Comment
  || 04/20/26  MCM 26.05.x  (724924) Updated the type of Processed Status to be Nvarchar so report manager is good
*/

SELECT 
    cc.CompanyKey
   ,cc.ProjectKey
   ,cc.GLAccountKey
   ,cc.GLCompanyKey
   ,cc.Amount as [Amount]
   ,cc.PayeeName as [Payee Name]
   ,cc.TransactionPostedDate as [Transaction Date]
   ,cc.TransactionType as [Transaction Type]
   ,cc.FITID as [FITID]
   ,cc.Overhead as [Overhead]
   ,Case ISNULL(cc.Receipt, 0) When 1 then ''YES'' else ''NO'' end as [Receipt]
   ,gl.AccountNumber as [GL Account Number]
   ,gl.AccountName as [GL Account Name]
   ,gl.AccountNumber + '' - '' + gl.AccountName as [GL Account Name Full]
   ,Case When cc.Billable = 1 then ''YES'' else ''NO'' end as [Billable]
   ,Case WHEN ISNULL(cc.CCVoucherKey, 0) = 0 then ''NO'' else ''YES'' end as [Transaction Cleared]
   ,cc.Memo as [Memo]
   ,cc.OriginalMemo as [Original Memo]
   ,ta.TaskID as [Task ID]
   ,ta.TaskName as [Task Name]
   ,ta.TaskID + '' '' + ta.TaskName as [Task Full Name]
   ,p.ProjectNumber as [Project Number]
   ,p.ProjectName as [Project Name]
   ,p.ProjectNumber + '' - '' + p.ProjectName as [Project Full Name]
   ,case (Select COUNT(*)
			from tVoucherDetail (nolock)
		   where VoucherKey = v.VoucherKey
			 and ProjectKey = cc.ProjectKey
			 and ISNULL(TransferToKey, 0) > 0)
		when 0 then ''NO''
		else ''YES''
	end as [Transfer Out]
   ,i.ItemID as [Item ID]
   ,i.ItemName as [Item Name]
   ,i.ItemID + '' '' + i.ItemName as [Item Full Name]
   ,o.OfficeID as [Office ID]
   ,o.OfficeName as [Office Name]
   ,o.OfficeID + '' '' + o.OfficeName as [Office Full Name]
   ,o.OfficeColor as [Office Color]
   ,cl.ClassID as [Class ID]
   ,cl.ClassName as [Class Name]
   ,cl.ClassID + '' '' + cl.ClassName as [Class Full Name]
   ,d.DepartmentName as [Department Name]
   ,d.DepartmentColor as [Department Color]
   ,glc.GLCompanyID as [Company]
   ,c.VendorID as [Vendor ID]
   ,c.CompanyName AS [Vendor Name]
   ,c.VendorID + '' '' + c.CompanyName as [Vendor Full Name]
   ,ea.AccountName as [Expense Account Name]
   ,LTRIM(RTRIM(ISNULL(u.FirstName, '''') + '' '' + ISNULL(u.LastName,''''))) As [Charged By]
   ,v.InvoiceNumber as [Invoice Number]
   ,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Approved By Name]
   ,case isnull(v.Status, 0)
		when 1 then ''Unapproved''
		when 2 then ''Submitted for Approval''
		when 3 then ''Rejected''
		when 4 then ''Approved''
		else Null
	end as [Approval Status]
   ,st.SalesTaxID as [Sales Tax ID]
   ,st.SalesTaxName as [Sales Tax Name]
   ,st.SalesTaxID + '' '' + st.SalesTaxName as [Sales Tax Full Name]
   ,st2.SalesTaxID as [Sales Tax2 ID]
   ,st2.SalesTaxName as [Sales Tax2 Name]
   ,st2.SalesTaxID + '' '' + st2.SalesTaxName as [Sales Tax2 Full Name]
   ,case isnull(cc.CCVoucherKey, 0)
		when -1 then N''Marked as Processed''
		when 0 then N''Unprocessed''
		else N''Processed''
	end as [Processed Status]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cp.ProductID as [Client Product ID]
    ,cp.ProductName as [Client Product]
	,Case v.Status
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case v.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
	end as [Charge Status]
	,case isnull(cc.CCVoucherKey, 0)
		when -1 then (Select Count(*) from tAttachment a (nolock) Where a.AssociatedEntity = ''tCCEntry'' and cc.CCEntryKey = a.EntityKey)
		when 0 then (Select Count(*) from tAttachment a (nolock) Where a.AssociatedEntity = ''tCCEntry'' and cc.CCEntryKey = a.EntityKey)
		else (Select Count(*) from tAttachment a (nolock) Where a.AssociatedEntity = ''tVoucher'' and cc.CCEntryKey = a.EntityKey)
	end as [Attachment Count]
	,cc.Comment as [Comment]
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 tGLAccount gl (nolock) on cc.GLAccountKey = gl.GLAccountKey
	LEFT OUTER JOIN tGLCompany glc (nolock) ON cc.GLCompanyKey = glc.GLCompanyKey
	LEFT OUTER JOIN tVoucher v (nolock) on cc.CCEntryKey = v.CCEntryKey
	LEFT OUTER JOIN tUser u (nolock) on cc.ChargedByKey = u.UserKey
	LEFT OUTER JOIN tUser u2 (nolock) on v.ApprovedByKey = u2.UserKey
	LEFT OUTER JOIN tCompany c (NOLOCK) ON cc.VendorKey = c.CompanyKey
	LEFT OUTER JOIN tDepartment d (nolock) ON cc.DepartmentKey = d.DepartmentKey
	LEFT OUTER JOIN tGLAccount ea (nolock) ON cc.ExpenseAccountKey = ea.GLAccountKey
	LEFT OUTER JOIN tClass cl (nolock) on cc.ClassKey = cl.ClassKey
	LEFT OUTER JOIN tSalesTax st (nolock) on cc.SalesTaxKey = st.SalesTaxKey
	LEFT OUTER JOIN tSalesTax st2 (nolock) on cc.SalesTax2Key = st2.SalesTaxKey
	LEFT OUTER JOIN tClientDivision cd (nolock) on p.ClientDivisionKey = cd.ClientDivisionKey
    LEFT OUTER JOIN tClientProduct  cp (nolock) on p.ClientProductKey  = cp.ClientProductKey




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

ALTER PROCEDURE [dbo].[sptTaskUserUpdateStatus]
	@TaskUserKey int,
	@TaskUserStatusKey int,
	@UserKey int

AS --Encrypt

/*
|| When     Who Rel			What
|| 03/23/16 GAR 10.6.0.2	Created for resource manager board - dragging an assignment to a different status.
|| 05/13/26 RLS 26.05.17	(728544) Added zero/NULL check for @TaskUserStatusKey
*/
	-- (728544) Treat 0 as NULL (unassigned) so the default TaskUserStatus can be applied.
	IF @TaskUserStatusKey = 0
    SELECT @TaskUserStatusKey = NULL

	declare @PercentComplete int
	select @PercentComplete = ISNULL(DefaultPercentComp, 0) from tTaskUserStatus (nolock) where TaskUserStatusKey = @TaskUserStatusKey
		
	-- Thinking all I need to do is update the status and then pass back the perc complete - or should I do all this in the 
	-- update assignment code?
	if isnull(@PercentComplete, 0) < 100
		UPDATE tTaskUser
		SET    TaskUserStatusKey = @TaskUserStatusKey
		WHERE  TaskUserKey = @TaskUserKey 
	else
		UPDATE tTaskUser
		SET    TaskUserStatusKey = @TaskUserStatusKey
		WHERE  TaskUserKey = @TaskUserKey  

	RETURN @PercentComplete



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



ALTER VIEW [dbo].[vListing_Voucher]
AS

/*
|| When     Who Rel  What
|| 11/29/06 CRG 8.35 Wrapped VoucherTotal with ISNULL
|| 10/10/07 CRG 8.5  Added GLCompany and Office
|| 08/25/10 RLB 10534 (88062) added Vendor Company Type and Client Company Type is from the project.
|| 09/28/10 RLB 10535 (91043) added Opening Transaction
|| 08/22/11 GWG 10547 Added Tax Fields
|| 11/28/11 GHL 10550 Change inner join with tUser (approver) to left join
||                    so that we can recover where approver is null
|| 11/29/11 GHL 10550 Added filter on CreditCard = 0
|| 04/25/12 GHL 10555 Added GLCompanyKey for map/restrict
|| 03/01/13 GHL 10565 (167854) Added Vendor Invoice ID/Unique Auto Number
|| 08/29/13 GWG 10571 Added ProjectKey for filtering
|| 01/03/14 WDF 10576 Added [Created By Name] and [Date Created]
|| 01/27/14 GHL 10576 Added Currency
|| 03/20/14 GHL 10578 Added Exchange Rate
|| 01/27/15 WDF 10588 (Abelson Taylor) Added Division and Product
|| 02/11/15 GHL 10589 Added Company Media info for the new media screens
|| 03/05/15 GWG 10590 Added Credit Card info
|| 04/27/15 WDF 10591 (245447) Added [Paid By Client] and [Billed To Client]
|| 06/03/15 WDF 10593 (258625) Changed BilledToClient from ''vd.InvoiceLineKey is not null'' to ''ISNULL(vd.InvoiceLineKey, 0) > 0''
|| 12/15/15 GWG 10599 Added Attachment count
|| 11/16/16 WDF 10610 (318451) Added [Date Updated]
|| 09/22/17 GWG Roll back a name change
|| 08/30/18 MCM 18.9  (418314) Adding in default address info, phones and web site
|| 10/25/18 GHL 18.9.2.0 (423844) Added QuestDownloaded, this is a customization for Quest Diagnostics
|| 12/31/18 RLS 19.1.0 (437657) Added VCardAccepted
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 05/02/22 GHL 22.0.5.0 (594979) Added 2 fields(Labor on Time Entries, Labor on Vendor Invoice)
||                       to compare the 2
|| 07/11/22 GHL 22.0.8.0 (604152) Added v.CustomFieldKey + order type
|| 08/23/23 AMP 23.09.17 (649117) Added ACH Enabled field (Yes/No)
|| 10/03/24 RLB 24.10.20 (680328) Added payment address fields from vendor invoice header
|| 12/06/24 RLB 25.01.19 (689057) Added Paid in CC and Cash
|| 01/29/25 AMP 25.03.16 (691808) Added Date Paid
|| 06/19/25 AMP 25.07.20 (704239) Correction for Vendor Invoice Date Paid when its paid by a Credit Card Charge
|| 10/08/25 RLB 25.11.16 (712796) Added Overhead
|| 01/27/26 AMP 26.03.15 (719364) Added Station or Publication to the Vendor - Connections - Vendor Invoices screen
|| 04/07/26 GAR 26.05.17 (725874) Added Transaction Status (from vListing_Transactions)
|| 05/11/26 MCM 26.05.17 (728460) Removed the Transaciton Status as it was causing duplicates.  This is as the voucher level.
*/


SELECT 
     v.VoucherKey
     ,v.CompanyKey
     ,v.GLCompanyKey
     ,v.VendorKey
     ,v.ProjectKey
	 ,v.CompanyMediaKey
	 ,v.CustomFieldKey
	 ,Case When pot.PurchaseOrderTypeName is NULL then ''General'' else pot.PurchaseOrderTypeName end as [Invoice Type]
    ,c.CompanyName AS [Vendor Name]
    ,c.VendorID AS [Vendor ID]
    ,c.VendorID + '' - '' + c.CompanyName AS [Vendor Full Name]
    ,v.VoucherID AS [Unique Auto Number]
    ,v.InvoiceDate AS [Invoice Date]
	,v.PostingDate AS [Posting Date]
    ,v.DueDate as [Invoice Due Date]
	,v.DateReceived as [Invoice Date Received]
	,LTRIM(RTRIM(ISNULL(cbk.FirstName + '' '','''')  + ISNULL(cbk.LastName,''''))) AS [Created By Name]
	,v.DateCreated as [Date Created]
	,v.DateUpdated as [Date Updated]
	,p.ProjectNumber as [Header Project Number]
	,p.ProjectName as [Header Project Name]
	,p.ProjectNumber + '' '' + p.ProjectName as [Header Full Project Name]
	,cp.CampaignName as [Campaign Name]
	,gl.AccountNumber as [AP Account Number]
	,gl.AccountName as [AP Account Name]
	,cl.ClassID as [Class ID]
	,cl.ClassName as [Class Name]
	,v.TermsPercent as [Terms Percentage Discount]
	,v.TermsDays as [Terms Discount Days]
	,v.TermsNet as [Terms Net Days]
	,v.Description as [Invoice Description]
	,vct.CompanyTypeName as [Vendor Company Type]
	,cct.CompanyTypeName as [Client Company Type]
	,ISNULL(v.VoucherTotal, 0) as [Invoice Amount]
	,ISNULL(v.VoucherTotal, 0) - ISNULL(v.SalesTax1Amount, 0) - ISNULL(v.SalesTax2Amount, 0) as [Invoice Amount No Tax]
	,ISNULL(v.SalesTax1Amount, 0) + ISNULL(v.SalesTax2Amount, 0) as [Invoice Total Tax]
	,ISNULL(v.SalesTax1Amount, 0) as [Invoice Tax 1]
	,ISNULL(v.SalesTax2Amount, 0) as [Invoice Tax 2]
	,v.AmountPaid as [Invoice Amount Paid]
	,v.VoucherTotal - v.AmountPaid as [Amount Open]
	,v.VoucherTotal - v.AmountPaid as [Invoice Amount Open]
    ,v.InvoiceNumber AS [Invoice Number]
	,u.FirstName + '' '' + u.LastName as [Approver Name]
	,case v.OpeningTransaction when 1 then ''YES'' else ''NO'' end as [Opening Transaction]
	,case v.Downloaded when 1 then ''YES'' else ''NO'' end as Downloaded
	,case v.Posted when 1 then ''YES'' else ''NO'' end as Posted
	,Case v.Status
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case v.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
		end as [Invoice Status]
	,v.ApprovalComments as [Approval Comments]
	,ISNULL((Select Count(*) from tTransaction (nolock) Where Entity = ''VOUCHER'' and EntityKey = v.VoucherKey), 0) as [Posting Count]
	,cli.CompanyName as [Client Name]
	,cli.CustomerID as [Client ID]
	,cli.CompanyName as [Client Full Name]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,v.CurrencyID as [Currency]
	,v.ExchangeRate as [Exchange Rate]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cpr.ProductID as [Client Product ID]
    ,cpr.ProductName as [Client Product]
	,cm.MediaKind
	,case c.CCAccepted when 1 then ''YES'' else ''NO'' end as [Credit Cards Accepted]
	,glcc.AccountNumber as [Credit Card Used]
	,c.EmailCCToAddress as [Email Card Info To]
	,CASE WHEN (SELECT COUNT(*) 
                  FROM tVoucherDetail vd (nolock)
                 WHERE vd.VoucherKey = v.VoucherKey 
                   AND v.Status = 4 
                   AND vd.DatePaidByClient IS NOT NULL
                ) > 0 
          THEN ''YES'' 
          ELSE ''NO'' 
     END AS [Paid By Client]
    ,CASE WHEN ((SELECT COUNT(*) 
				   FROM tVoucherDetail vd (nolock)
				  WHERE vd.VoucherKey = v.VoucherKey 
					AND v.Status = 4 
					AND ISNULL(vd.InvoiceLineKey, 0) > 0
				)
				+ 
				(SELECT COUNT(*) 
				   FROM tVoucherDetail vd (nolock) inner join tPurchaseOrderDetail pod (nolock) on pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
				  WHERE vd.VoucherKey = v.VoucherKey 
				    AND v.Status = 4 
				    AND ISNULL(pod.InvoiceLineKey, 0) > 0
				)
			   ) > 0 
		  THEN ''YES'' 
		  ELSE ''NO'' 
	 END AS [Billed To Client],
	 (Select Count(*) from tAttachment a (nolock) inner join tVoucherDetail vd (nolock) on a.EntityKey = vd.VoucherDetailKey and a.AssociatedEntity = ''tVoucherDetail'' Where vd.VoucherKey = v.VoucherKey) as [Line Attachment Count],
	 (Select Count(*) from tAttachment a (nolock) Where a.AssociatedEntity = ''tVoucher'' and v.VoucherKey = a.EntityKey) as [Attachment Count],
	 ad.Address1,
	 ad.Address2,
	 ad.Address3,
	 ad.City,
	 ad.State,
	 ad.PostalCode, 
	 ad.Country,
	 ap.Address1 AS [Payment Address1],   
	 ap.Address2 AS [Payment Address2],   
	 ap.Address3 AS [Payment Address3],   
	 ap.City AS [Payment City],   
	 ap.State AS [Payment State],   
	 ap.PostalCode AS [Payment Postal Code],   
	 ap.Country AS [Payment Country],
	 c.Phone,
	 c.Fax,
	 c.WebSite,
	 case when (c.VCardAccepted is null or c.VCardAccepted = 0) then ''NO'' else ''YES'' end as [Accepts VPay],
	 v.QuestDownloaded  as [Date Time Downloaded],
	 t2.TotalCost as [Labor on Time Entries],
	 vd.TotalCost as [Labor on Vendor Invoice],
	 case when vd.VoucherDetailKey is not null then ''YES'' else ''NO'' end as [Has Labor]
	,case when (c.ACHEnabled is null or c.ACHEnabled = 0) then ''NO'' else ''YES'' end as [ACH Enabled]	
	,(select ISNULL(Sum(Amount), 0) + ISNULL(sum(DiscAmount), 0) from tPaymentDetail (nolock) Where VoucherKey = v.VoucherKey and Prepay = 0) as  [Paid in Cash]
	,(select ISNULL(Sum(Amount), 0) + ISNULL(sum(DiscAmount), 0) from tVoucherCC (nolock) Where VoucherKey = v.VoucherKey) as [Paid in Credit]
	,case when oa.OpenAmount = 0 then dp.PaymentDate else null end as [Date Paid]
	,case when (v.VoucherType  is null or v.VoucherType  = 0) then ''NO'' else ''YES'' end as [Overhead]
	,cm3.PubName AS [Station or Publication]

From
	tVoucher v (nolock)
	Inner Join tCompany c (nolock) on v.VendorKey = c.CompanyKey
	left join tUser u (nolock) on v.ApprovedByKey = u.UserKey
	left join tUser cbk (nolock) on v.CreatedByKey = cbk.UserKey
	left outer join tProject p (nolock) on v.ProjectKey = p.ProjectKey
	left outer join tGLAccount gl (nolock) on v.APAccountKey = gl.GLAccountKey
	left outer join tClass cl (nolock) on v.ClassKey = cl.ClassKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
	left outer join tCompany cli (nolock) on p.ClientKey = cli.CompanyKey
	left outer join tGLCompany glc (nolock) on v.GLCompanyKey = glc.GLCompanyKey
	left outer join tOffice o (nolock) on v.OfficeKey = o.OfficeKey
	left outer join tCompanyType vct (nolock) on c.CompanyTypeKey = vct.CompanyTypeKey
	left outer join tCompanyType cct (nolock) on cli.CompanyTypeKey = cct.CompanyTypeKey
	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 tCompanyMedia cm (nolock) on v.CompanyMediaKey = cm.CompanyMediaKey 
	left outer join tGLAccount glcc (nolock) on c.CCAccountKey = glcc.GLAccountKey
	left outer join tAddress ad (nolock) on c.DefaultAddressKey = ad.AddressKey
	LEFT OUTER JOIN tAddress ap (NOLOCK) ON ISNULL(v.PaymentAddressKey, c.PaymentAddressKey) = ap.AddressKey

	left outer join 
	(
	select sum(ROUND(ActualHours * VendorCostRate, 2)) as TotalCost, VoucherKey
	from tTime t (nolock)
	where t.VoucherKey > 0
	group by t.VoucherKey
	)
	as t2 on t2.VoucherKey = v.VoucherKey
	left outer join tVoucherDetail vd (nolock) on v.VoucherKey = vd.VoucherKey and IsLabor = 1
	left outer join tPurchaseOrderType pot on v.PurchaseOrderTypeKey = pot.PurchaseOrderTypeKey

	-- derived tables to calculate the [Date Paid] field 
	left outer join	(
		SELECT
			v.VoucherKey,			
			ISNULL(v.VoucherTotal, 0) - (ISNULL(pd.PaymentAmount, 0) + ISNULL(vc.CreditAmount, 0) + ISNULL(vcc.CCAmount, 0) - ISNULL(ca.CreditedAmount, 0)) AS OpenAmount
		FROM
			tVoucher v (nolock)
			LEFT JOIN (
				SELECT ISNULL(SUM(Amount), 0) + ISNULL(SUM(DiscAmount), 0) AS PaymentAmount, VoucherKey
				FROM
					tPaymentDetail pd (nolock)
				GROUP BY pd.VoucherKey
			) pd ON v.VoucherKey = pd.VoucherKey
			LEFT JOIN (
				SELECT SUM(Amount) AS CreditAmount, vc.VoucherKey
				FROM
					tVoucherCredit vc (nolock)
				GROUP BY vc.VoucherKey
			) vc ON v.VoucherKey = vc.VoucherKey
			LEFT JOIN (
				SELECT SUM(Amount) AS CCAmount, vcc.VoucherKey
				FROM
					tVoucherCC vcc (nolock)
				GROUP BY vcc.VoucherKey
			) vcc ON v.VoucherKey = vcc.VoucherKey
			LEFT JOIN (
				SELECT SUM(Amount) AS CreditedAmount, CreditVoucherKey
				FROM
					tVoucherCredit ca (nolock)
				GROUP BY ca.CreditVoucherKey
			) ca ON v.VoucherKey = ca.CreditVoucherKey
		) oa ON oa.VoucherKey = v.VoucherKey
	left outer join (
		SELECT MAX(PaymentDate) AS PaymentDate, VoucherKey
		FROM (
			SELECT PaymentDate, VoucherKey
			FROM (
					SELECT p.PaymentDate AS PaymentDate, pd.VoucherKey AS VoucherKey
					FROM
						tPaymentDetail pd (nolock)
						INNER JOIN tPayment p (nolock) ON pd.PaymentKey = p.PaymentKey
					GROUP BY pd.VoucherKey, p.PaymentDate

					UNION

					SELECT v.InvoiceDate AS PaymentDate, vc.VoucherKey
					FROM
						tVoucherCredit vc (nolock)
						INNER JOIN tVoucher v (nolock) ON vc.VoucherKey = v.VoucherKey
					GROUP BY vc.VoucherKey, v.InvoiceDate

					UNION

					SELECT v.InvoiceDate AS PaymentDate, vcc.VoucherKey
					FROM
						tVoucherCC vcc (nolock)
						INNER JOIN tVoucher v (nolock) ON vcc.VoucherCCKey = v.VoucherKey
					GROUP BY vcc.VoucherKey, v.InvoiceDate

					UNION

					SELECT v.InvoiceDate AS PaymentDate, CreditVoucherKey
					FROM
						tVoucherCredit ca (nolock)
						INNER JOIN tVoucher v (nolock) ON ca.CreditVoucherKey = v.VoucherKey
					GROUP BY ca.CreditVoucherKey, v.InvoiceDate
			) x1
		) x2
		GROUP BY x2.VoucherKey
	) dp on dp.VoucherKey = v.VoucherKey
	
	Outer Apply (
				SELECT TOP 1 (cm2.StationID + ''-'' + cm2.Name) as PubName, cm2.CompanyMediaKey, cm3.VoucherKey			
				FROM	tCompanyMedia cm2
						INNER JOIN (
									select	CompanyMediaKey , vd2.VoucherKey, vd2.VoucherDetailKey
									from	tPurchaseOrderDetail pod (nolock)
											INNER JOIN tPurchaseOrder (nolock) po on po.PurchaseOrderKey = pod.PurchaseOrderKey
											INNER JOIN tVoucherDetail vd2 (NOLOCK) ON pod.PurchaseOrderDetailKey = vd2.PurchaseOrderDetailKey											
									) cm3 ON cm2.CompanyMediaKey = cm3.CompanyMediaKey
				WHERE v.VoucherKey = cm3.VoucherKey				
				GROUP BY (cm2.StationID + ''-'' + cm2.Name), cm2.CompanyMediaKey, cm3.VoucherKey, cm3.VoucherDetailKey	
				ORDER BY cm3.VoucherDetailKey DESC
			  ) As cm3

Where ISNULL(v.CreditCard, 0) = 0

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




ALTER VIEW [dbo].[vListing_Deliverables]
AS

/*
|| When			   Who		Rel			What
|| 07/25/2011  MAS  10.x.x.x  Created for new Deliverable Listing
|| 09/06/2011  QMD  10.5.4.9  Added ClientKey
|| 11/01/2011  QMD  10.5.4.9  Added Current Round, Step, Date Sent, Paused, Send as a set
|| 11/11/2011  QMD  10.5.5.0  Added ReviewRoundKey
|| 04/02/2012  MFT  10.5.5.5  Added GLCompanyKey in order to map/restrict
|| 05/01/2012  QMD  10.5.5.5  (142163) Removed Status = 1 clause
|| 09/20/2012  GWG  10.5.6.0  Added Current Approver
|| 01/07/2014  QMD  10.5.7.6  (201409) Changed status Resubmit to Rejected
|| 01/27/2015  WDF  10.5.8.8  (Abelson Taylor) Added Division and Product
|| 08/10/2015  KMC  10.5.9.5  (265971) Updated values returned for ApprovalStatus to be in line with vListing_Deliverables
|| 04/19/2016  GWG  10.6.0.3  Added Project Type
|| 06/29/2018  WDF  18.7.0.0  (408035) Added [File Count] 
|| 08/04/2018  RLB  18.8.0.0  (413393) change how Approver Status was displayed
|| 09/07/2016  RLB  18.9.1.0  (419327) change how Approval Status was displayed
|| 03/22/2019  RLS  19.0.4.0  (446470) Added [Round Count]
|| 08/14/2019  RLB  19.0.9.0  (473466) Changed Approval Status and Approver Status to handle approved with changes
|| 08/29/2019  GAR  19.0.9.0  (476924) Added Deliverable ID
|| 09/19/2019  GAR  19.1.0.0  (476989) Changed Approval Status to be the status of the entire deliverable
|| 09/22/2019  GWG  19.1.0.0  Adding type, status and task and custom fields to the views
|| 10/10/2019  GAR  19.1.1.0  (481255) Adding Current Approver Due Date
|| 02/20/2020  RLS  20.0.3.0  (502033) Added [Page Number] and outer join on tReviewComment
|| 02/24/2020  RLS  20.0.3.0  (501906) Added [Project Manager] and outer join on tUser
|| 04/23/2020  RLS  20.0.5.0  (510289) Added RequestID and RequestName
|| 05/14/2020  RLB  20.0.6.0  (515574)  issue 502033 added an outer join to tReviewCommment. This caused many rows which should not be the case in this listing
|| 06/09/2020  RLS  20.0.7.0  (517205)  Added a.Subject
|| 07/17/2020  RLS  20.0.8.0  (520834)  Added Project Start Date, Project End Date, Campaign Start Date and Campaign End Date
|| 09/02/2020  RLB  20.1.0.0  (523772) making anything using user name common format
|| 06/09/2021  WDF  21.07.18  (559492) Added [Date Round Approved]
|| 02/09/2022  AMP  22.03.20  (584605) Added Custom Project Fields  
|| 04/15/2022  RLB  22.05.15  (587411) added completed field
|| 08/11/2023  RLB  23.09.17  (648008) added project type color, Deliverable Status Color and Type Color
|| 01/28/2025  GAR  25.02.16  (689798) Added Task Plan Start Date, Task Actual Start Date, Task Plan Complete Date, Task Actual Completion Date
|| 04/20/2026  RLB  26.05.17  (726348) Added Union since projectkey can mean project or campaign dependant on +- number
*/

SELECT
	 rd.ReviewDeliverableKey
	,rd.OwnerKey 
	,rd.CompanyKey	
	,r.ReviewRoundKey
	,p.GLCompanyKey
	,p.ProjectKey
	,rd.CustomFieldKey
	,p.CustomFieldKey AS CustomFieldKey2
	,rd.Description AS [Description]
	,rd.DeliverableName AS [Deliverable Name]
	,rd.DueDate AS [Due Date]
	,p.ProjectNumber AS [Project Number]
	,p.ProjectName AS [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' '' + c.CompanyName as [Client Full Name]
	,r.RoundName AS [Current Round]
	,(SELECT Count(*) FROM tReviewRoundFile (NOLOCK) WHERE ReviewRoundKey = r.ReviewRoundKey) As [File Count] 
	,(SELECT Count(*) FROM tReviewRound (NOLOCK) WHERE ReviewDeliverableKey = rd.ReviewDeliverableKey) As [Round Count] 
	,Case a.EnableRouting
		WHEN 1 THEN ''In Order''
		WHEN 0 THEN ''Everyone''
	 END AS [Routing]
	,CASE a.Internal 
		WHEN 1 THEN ''Internal''
		WHEN 0 THEN ''External''
	 END AS [Current Step]
	 ,CASE ISNULL(a.Pause,0)
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Paused]
	 ,CASE a.LoginRequired
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Login Required]
	 ,CASE a.AllApprove
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Everyone Must Review]
	 ,CASE rd.Approved
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Approved]
	 ,CASE rd.Completed
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Completed]
	 ,rd.ApprovedDate as [Date Approved]
	,r.DateSent AS [Date Sent]
	--,Case When a.ActiveStep = 1 then a.ApproverStatus else
	--	Case When rd.Approved = 1 then ''Approved'' else ''Rejected'' end 
	-- end as [Approval Status]
	 ,Case When a.ActiveStep = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Reviewing'' end
	 Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		Else 
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		End 
	 End as [Approval Status]
	 ,Case When a.ActiveStep = 1 then a.ApproverStatus 
	  Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		ELSE
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		END
	End As [Approver Status]
	,u.UserName as [Account Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
	,own.UserName as [Deliverable Owner]
	,Case p.Active When 1 Then ''YES'' else ''NO'' end as [Active Project]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,cp.ProductID as [Client Product ID]
    ,cp.ProductName as [Client Product]
	,pt.ProjectTypeName as [Project Type]
	,pt.ProjectTypeColor as [Project Type Color]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign Name]
	,ca.CampaignID + '' - '' + ca.CampaignName as [Campaign Full Name]
	,rd.DeliverableID AS [Deliverable ID]
	,ds.StatusName as [Status]
	,ds.StatusColor as [Deliverable Status Color]
	,t.TaskID + '' - '' + t.TaskName as [Current Task]
	,dt.TypeName as [Deliverable Type]
	,dt.TypeColor as [Deliverable Type Color]
	,(SELECT MIN(DueDate) FROM tApprovalStepUser (NOLOCK) WHERE ActiveUser = 1 AND CompletedUser = 0 AND ApprovalStepKey = a.ApprovalStepKey) AS [Current Approver Due Date]
	,pr.RequestID as [Request ID]
	,reqdef.RequestName as [Request Type]
	,a.Subject as [Current Step Name]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project End Date]
	,ca.StartDate as [Campaign Start Date]
	,ca.EndDate as [Campaign End Date]
	,(SELECT MAX(DateRoundApproved) FROM tReviewRound (NOLOCK) WHERE ISNULL(CompletedDate, RejectedDate) is not null AND ReviewDeliverableKey = rd.ReviewDeliverableKey) AS [Date Round Approved]
	,t.PlanStart as [Task Plan Start Date]
	,t.ActStart as [Task Actual Start Date]
	,t.PlanComplete as [Task Plan Complete Date]
	,t.ActComplete as [Task Actual Complete Date]
FROM tReviewDeliverable rd (NOLOCK)
	left outer join tProject p (NOLOCK) ON rd.ProjectKey = p.ProjectKey
	left outer join tCampaign ca (NOLOCK) on p.CampaignKey = ca.CampaignKey
	left outer join tProjectType pt (NOLOCK) on p.ProjectTypeKey = pt.ProjectTypeKey
	left outer join tCompany c (NOLOCK) on p.ClientKey = c.CompanyKey
	left outer join tReviewRound r (NOLOCK) ON rd.ReviewDeliverableKey = r.ReviewDeliverableKey AND r.LatestRound = 1
	left outer join tApprovalStep a (NOLOCK) ON a.EntityKey = r.ReviewRoundKey and a.Entity = ''tReviewRound'' and a.ActiveStep = 1
	left outer join vUserName u (NOLOCK) on p.AccountManager = u.UserKey
	left outer join vUserName own (NOLOCK) on rd.OwnerKey = own.UserKey
	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 tDeliverableStatus ds (NOLOCK) on rd.DeliverableStatusKey = ds.DeliverableStatusKey
	left outer join tTask t (NOLOCK) on rd.TaskKey = t.TaskKey
	left outer join tDeliverableType dt (NOLOCK) on rd.DeliverableTypeKey = dt.DeliverableTypeKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey 
	left outer join tRequest pr (nolock) on rd.RequestKey = pr.RequestKey
	left outer join tRequestDef reqdef (nolock) on pr.RequestDefKey = reqdef.RequestDefKey
Where rd.ProjectKey > 0


UNION

SELECT
	 rd.ReviewDeliverableKey
	,rd.OwnerKey 
	,rd.CompanyKey	
	,r.ReviewRoundKey
	,ca.GLCompanyKey
	,null
	,rd.CustomFieldKey
	,null AS CustomFieldKey2
	,rd.Description AS [Description]
	,rd.DeliverableName AS [Deliverable Name]
	,rd.DueDate AS [Due Date]
	,'''' AS [Project Number]
	,'''' AS [Project Name]
	,'''' AS [Project Full Name]
	,c.CustomerID as [Client ID]
	,c.CompanyName as [Client Name]
	,c.CustomerID + '' '' + c.CompanyName as [Client Full Name]
	,r.RoundName AS [Current Round]
	,(SELECT Count(*) FROM tReviewRoundFile (NOLOCK) WHERE ReviewRoundKey = r.ReviewRoundKey) As [File Count] 
	,(SELECT Count(*) FROM tReviewRound (NOLOCK) WHERE ReviewDeliverableKey = rd.ReviewDeliverableKey) As [Round Count] 
	,Case a.EnableRouting
		WHEN 1 THEN ''In Order''
		WHEN 0 THEN ''Everyone''
	 END AS [Routing]
	,CASE a.Internal 
		WHEN 1 THEN ''Internal''
		WHEN 0 THEN ''External''
	 END AS [Current Step]
	 ,CASE ISNULL(a.Pause,0)
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Paused]
	 ,CASE a.LoginRequired
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Login Required]
	 ,CASE a.AllApprove
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Everyone Must Review]
	 ,CASE rd.Approved
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Approved]
	 ,CASE rd.Completed
		WHEN 1 THEN ''YES''
		WHEN 0 THEN ''NO''
	 END AS [Deliverable Completed]
	 ,rd.ApprovedDate as [Date Approved]
	,r.DateSent AS [Date Sent]
	--,Case When a.ActiveStep = 1 then a.ApproverStatus else
	--	Case When rd.Approved = 1 then ''Approved'' else ''Rejected'' end 
	-- end as [Approval Status]
	 ,Case When a.ActiveStep = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Reviewing'' end
	 Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		Else 
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		End 
	 End as [Approval Status]
	 ,Case When a.ActiveStep = 1 then a.ApproverStatus 
	  Else
		Case When ISNULL(rd.Approved, 0) = 1 then case rd.ApprovedWithChanges when 1 then ''Approved With Changes'' else ''Approved'' end
		ELSE
			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''
				When r.Status IS NULL or r.Status = 1 then ''Unsubmitted''
			End 
		END
	End As [Approver Status]
	,u.UserName as [Account Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
	,own.UserName as [Deliverable Owner]
	,Case ca.Active When 1 Then ''YES'' else ''NO'' end as [Active Project]
	,null as [Client Division ID]
    ,null as [Client Division]
    ,null as [Client Product ID]
    ,null as [Client Product]
	,null as [Project Type]
	,null as [Project Type Color]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign Name]
	,ca.CampaignID + '' - '' + ca.CampaignName as [Campaign Full Name]
	,rd.DeliverableID AS [Deliverable ID]
	,ds.StatusName as [Status]
	,ds.StatusColor as [Deliverable Status Color]
	,t.TaskID + '' - '' + t.TaskName as [Current Task]
	,dt.TypeName as [Deliverable Type]
	,dt.TypeColor as [Deliverable Type Color]
	,(SELECT MIN(DueDate) FROM tApprovalStepUser (NOLOCK) WHERE ActiveUser = 1 AND CompletedUser = 0 AND ApprovalStepKey = a.ApprovalStepKey) AS [Current Approver Due Date]
	,pr.RequestID as [Request ID]
	,reqdef.RequestName as [Request Type]
	,a.Subject as [Current Step Name]
	,NULL as [Project Start Date]
	,NULL as [Project End Date]
	,ca.StartDate as [Campaign Start Date]
	,ca.EndDate as [Campaign End Date]
	,(SELECT MAX(DateRoundApproved) FROM tReviewRound (NOLOCK) WHERE ISNULL(CompletedDate, RejectedDate) is not null AND ReviewDeliverableKey = rd.ReviewDeliverableKey) AS [Date Round Approved]
	,t.PlanStart as [Task Plan Start Date]
	,t.ActStart as [Task Actual Start Date]
	,t.PlanComplete as [Task Plan Complete Date]
	,t.ActComplete as [Task Actual Complete Date]
FROM tReviewDeliverable rd (NOLOCK)
	left outer join tCampaign ca (NOLOCK) on ABS(rd.ProjectKey) = ca.CampaignKey
	left outer join tCompany c (NOLOCK) on ca.ClientKey = c.CompanyKey
	left outer join tReviewRound r (NOLOCK) ON rd.ReviewDeliverableKey = r.ReviewDeliverableKey AND r.LatestRound = 1
	left outer join tApprovalStep a (NOLOCK) ON a.EntityKey = r.ReviewRoundKey and a.Entity = ''tReviewRound'' and a.ActiveStep = 1
	left outer join vUserName u (NOLOCK) on ca.AEKey = u.UserKey
	left outer join vUserName own (NOLOCK) on rd.OwnerKey = own.UserKey
	left outer join tDeliverableStatus ds (NOLOCK) on rd.DeliverableStatusKey = ds.DeliverableStatusKey
	left outer join tTask t (NOLOCK) on rd.TaskKey = t.TaskKey
	left outer join tDeliverableType dt (NOLOCK) on rd.DeliverableTypeKey = dt.DeliverableTypeKey
	left outer join tUser pm (nolock) on ca.PMKey = pm.UserKey 
	left outer join tRequest pr (nolock) on rd.RequestKey = pr.RequestKey
	left outer join tRequestDef reqdef (nolock) on pr.RequestDefKey = reqdef.RequestDefKey
Where rd.ProjectKey < 0

























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

/*
|| When     Who Rel      What
|| 03/02/07 BSH 8.4.0.4  Added Primary Conact.
|| 03/19/07 GHL 8.4.0.8  Added Emailed
|| 03/26/07 RTC 8.4.1    (7972, 8118) Added the client division and product fields from the invoice header project.
|| 10/10/07 CRG 8.5      Added Company and Office
|| 11/06/07 CRG 8.5      (9309) Added Project Name
|| 01/07/08 GWG 8502      Added the user defined fields
|| 02/11/08 BSH 1.000     Added ASC_Selected
|| 02/14/08 GHL 1.000     Added GLCompanyKey so that we can charge credit cards from the listing 
|| 06/11/08 GHL 8513     (27755) Setting now Advance Bill Unapplied to 0 if the invoice is not an advance bill
|| 12/16/08 GHL 10.015   (42441) Added Advance Bill Sales Tax Unapplied
|| 03/17/09 RTC 10.5	  Removed user defined fields.
|| 07/09/09 MAS 10.5	 (56913)Added AccountManager
|| 09/29/09 GWG 10.511	 (63864) Modified the column Amount Billed to not include credits. Looks at Retainer Amount
|| 01/04/10 RLB 10.516   (71241) Added Project Account Manager
|| 05/19/10 RLB 10.523   (79987) Added Client Project Number, Client Primary Contact and Custom Fields for Company, Project and contacts
|| 07/28/10 RLB 10.533   (78955) Added Project Full Name & description
|| 08/13/10 RLB 10.533   (87534) Added Company Type and Parent Company
|| 09/28/10 RLB 10535    (91043) Added Opening Transaction
|| 11/15/10 RLB 10.538   (91722) Added Invoice Template and Invoice Layout
|| 12/15/11 GWG 10.551	  Added Project Campaign Name 
|| 07 18/12 RLB 10.558   (137183) Added Invoice Campaign Name
|| 08/27/12 RLB 10.559   (152497) added Billing Code
|| 09/06/12 KMC 10.5.6.0 (151883) Update query to return the Billing Group Code per recommendations from Gil
|| 09/11/12 MFT 10.559   Added Alternate Payer
|| 09/15/12 GWG 10.560   Fixed link to billing group code to get it from the project based on the invoice header
|| 09/27/12 GHL 10.560   Since we added tInvoice.BillingGroupKey, get Billing Group Code from tBillingGroup, joining with that new field 
|| 06/27/13 GWG 10.569   Added project key to limit visibility to assigned projects.
|| 07/01/13 GHL 10.569   (181721) Added Campaign ID
|| 01/03/14 WDF 10.576   (188500) Added [Date Created] and [Created By]
|| 01/27/14 GHL 10.576   Added Currency 
|| 03/20/14 GHL 10.578   Added Exchange Rate 
|| 04/9/14  GWG 10.578   Added project team and project status
|| 07/2/14  GWG 10.581   Added Sales Tax names
|| 11/24/14 GAR 10.586   (237300) Added bill to state and company state.
|| 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
|| 12/30/15 WDF 10.599   (283249) Added ISNULL to HeaderComment
|| 06/30/16 GHL 10.605   Added Billing Worksheet field
|| 04/02/17 GWG 10.614   Adding Overhead client to the view
|| 06/03/17 GWG 10.616   Adding the project budget and billed columns
|| 11/14/17 DDM 18.1.0   Added Contact Email and Name for Invoice (either Client.BillingEmailContact or Invoice.PrimaryContact)
|| 06/5/18  GWG 18.6.0   Added some aging fields for graphs
|| 10/15/18 AMP 18.9.2   Added the encrypted EIN Number column for the Client Invoice Views
|| 02/25/19 WDF 19.030   (446567) Formatted [Invoice Month]; Removed [Invoice Month Name]
|| 04/11/19 GHL 19.500   (447171) show home currency instead of blank currency
|| 03/17/20 AMP 20.0.4.0 (507139) Added "Allow Credit Card Payments Online"
|| 05/21/20 AMP 20.0.6.0 (504219) Added the Campaign Product Name and Campaign Division Name
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 09/08/20 GAR 20.1.0.0 (528498) Added Campaign Account Manager of the Campaign that is linked in the Header of the Invoice
|| 02/22/22 RLS 22.03.20 (587445) Added Campaign Custom Fields
|| 04/12/22 RLS 22.05.15 (595489) Override CustomFieldKey4 to pull from the invoice if there is no project
|| 08/03/22 GAR 22.09.18 (606205) Added campaign segment from the project
|| 06/12/23 RLB 23.07.16 (634098) Added Project manager options from company, project and campaign
|| 10/02/24 RLS 24.10.20 (683849) Added [Delivery Date]
|| 11/25/24 RLB 24.12.15 (688446) Added Current Labor Budget Gross from project header
|| 04/13/26 AMP 26.05.17 (726231) Added Advance Bill Liability Account fields
*/

SELECT 
	i.InvoiceKey,
	i.CompanyKey, 
	i.ClientKey,
	i.GLCompanyKey,
	i.ProjectKey,
	i.InvoiceNumber AS [Invoice Number],
	i.InvoiceDate as [Invoice Date],
	i.PostingDate as [Posting Date],
	i.DueDate AS [Due Date], 
	case i.AdvanceBill when 1 then ''YES'' else ''NO'' end as [Advance Billing Invoice],
	case c.Overhead when 1 then ''YES'' else ''NO'' end as [Overhead Client],
	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],
	i.DateCreated AS [Date Created],
	c.CustomFieldKey,
	cpc.CustomFieldKey as CustomFieldKey3,
	pr.CustomFieldKey as CustomFieldKey2,
	ISNULL(camp.CustomFieldKey, camp2.CustomFieldKey) as CustomFieldKey4,
    c.CompanyName AS [Client Name], 
    c.CustomerID AS [Client ID],
    ct.CompanyTypeName AS [Company Type],
    pc.CompanyName AS [Parent Company], 
    c.CustomerID + '' - '' + c.CompanyName AS [Client Full Name], 
	LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager],
	LTRIM(RTRIM(ISNULL(pam.FirstName + '' '','''')  + ISNULL(pam.LastName,''''))) AS [Project Account Manager],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Sales Person],
	LTRIM(RTRIM(ISNULL(cpc.FirstName + '' '','''')  + ISNULL(cpc.LastName,''''))) AS [Client Primary Contact],
	LTRIM(RTRIM(ISNULL(cbk.FirstName + '' '','''')  + ISNULL(cbk.LastName,''''))) AS [Created By],
    pt.TermsDescription AS Terms, 
    glAR.AccountNumber AS [AR Account Number], 
    glAR.AccountName AS [AR Account Name], 
	glSales.AccountNumber AS [Default Sales Account Number], 
    glSales.AccountName AS [Default Sales Account Name],
	cl.ClassID as [Class ID],
	cl.ClassName as [Class Name],
    pr.ProjectNumber as [Project Number],
	pr.ProjectName as [Project Name],
	pr.ProjectNumber + '' - '' + pr.ProjectName AS [Project Full Name],
	pr.ClientProjectNumber as [Client Project Number],
	pr.Description as [Project Description],
	camp.CampaignName as [Project Campaign Name],
	camp2.CampaignName as [Invoice Campaign Name],
	camp.CampaignID as [Project Campaign ID],
	camp2.CampaignID as [Invoice Campaign ID],
	cs.SegmentName as [Campaign Segment],
	cd.DivisionName as [Division Name],
	cd.DivisionID as [Division ID],
	cp.ProductName as [Product Name],
	cp.ProductID as [Product ID],
	cd2.DivisionName as [Camp Division Name],	
	cp2.ProductName as [Camp Product Name],	
	ISNULL(i.InvoiceTotalAmount, 0) as [Amount Total],
	ISNULL(i.TotalNonTaxAmount, 0) as [Amount Non Tax Total],
	ISNULL(i.SalesTaxAmount, 0) as [Amount Sales Tax],
	ISNULL(i.AmountReceived, 0) as [Amount Received],
    ISNULL(i.WriteoffAmount, 0) AS [Amount Writeoff], 
    ISNULL(i.RetainerAmount, 0) AS [Amount Applied From Adv Bill], 
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(AmountReceived, 0) - ISNULL(WriteoffAmount, 0) - ISNULL(i.RetainerAmount, 0) as [Amount Open],
    ISNULL(i.HeaderComment, '''') as [Invoice Comment], 
	i.ApprovalComments as [Approval Comments],
	it.TemplateName AS [Invoice Template],
	lo.LayoutName AS [Invoice Layout],
	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 [Approval Status],
    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.Printed when 1 then ''YES'' else ''NO'' end as Printed,
	case i.OpeningTransaction when 1 then ''YES'' else ''NO'' end as [Opening Transaction],
	case i.Emailed when 1 then ''YES'' else ''NO'' end as Emailed,
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Invoice Approver],
	LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Primary Contact],
	(Select Count(*) from tTransaction (nolock) Where Entity = ''INVOICE'' and EntityKey = i.InvoiceKey) as [Posting Count],
	
	ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) 
	Where AdvBillInvoiceKey = i.InvoiceKey),0) as [Advance Bill Applied],
	
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(i.RetainerAmount, 0) as [Amount Billed],

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

	CASE WHEN i.AdvanceBill = 1 THEN
		ISNULL(i.SalesTaxAmount, 0) - ISNULL((Select Sum(Amount) from tInvoiceAdvanceBillTax (nolock) 
		Where AdvBillInvoiceKey = i.InvoiceKey),0)
	ELSE 0 END as [Advance Bill Sales Tax Unapplied],
	
	ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where InvoiceKey = i.InvoiceKey),0) as [Applied Advance Billings],
	ISNULL((Select Sum(Amount) from tInvoiceCredit (nolock) Where CreditInvoiceKey = i.InvoiceKey), 0) as [Credit Amount Applied],
	ISNULL((Select Sum(Amount) from tInvoiceCredit (nolock) Where InvoiceKey = i.InvoiceKey),0) as [Applied Credits]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,ap.CompanyName AS [Alternate Payer]
	,ap.CustomerID AS [Alternate Payer ID]
	,bg.BillingGroupCode as [Billing Group Code]
	,bg.Description as [Billing Group Description]
	,case when i.CurrencyID is not null then i.CurrencyID else prefs.CurrencyID end as [Currency]
	,i.ExchangeRate as [Exchange Rate]
	,tt.TeamName as [Project Team Name]
	,ps.ProjectStatus as [Project Status]
	,st1.SalesTaxID as [Sales Tax 1 Code]
	,st2.SalesTaxID as [Sales Tax 2 Code]
	,st1.SalesTaxName as [Sales Tax 1 Name]
	,st2.SalesTaxName as [Sales Tax 2 Name]
	,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 c.BillingAddressKey IS NOT NULL THEN ab.State ELSE ad.State END
			AS [Company State]
  ,0 AS ASC_Selected
  ,cast(b.BillingID as varchar(20)) as [Billing Worksheet]
  ,pr.EstLabor + pr.ApprovedCOLabor + pr.EstExpenses + pr.ApprovedCOExpense + ISNULL(pr.SalesTax,0) + ISNULL(pr.ApprovedCOSalesTax,0) as [Project Total Budget]
  ,ISNULL(pru.BilledAmount, 0) as [Project Amount Billed]
  ,pr.EstLabor + pr.ApprovedCOLabor as [Current Budget Labor Gross] -- [Estimate Total Labor]
  ,CASE WHEN cbc.Email IS NOT NULL THEN cbc.Email
		WHEN ic.Email IS NOT NULL THEN ic.Email
		ELSE ''''
		END ContactEmail		
  ,CASE WHEN cbc.UserKey IS NOT NULL THEN LTRIM(RTRIM(ISNULL(cbc.FirstName + '' '','''')  + ISNULL(cbc.LastName,'''')))
		WHEN ic.UserKey IS NOT NULL  THEN LTRIM(RTRIM(ISNULL(ic.FirstName + '' '','''')  + ISNULL(ic.LastName,'''')))
		ELSE ''''
		END ContactName
  ,ISNULL(i.ParentInvoice,0) ParentInvoice
  ,CASE WHEN cbc.UserKey IS NOT NULL THEN cbc.UserKey
  		WHEN ic.UserKey IS NOT NULL  THEN ic.UserKey
		ELSE NULL
		END ContactKey	
  ,Case WHEN DATEDIFF(d, i.InvoiceDate, GETDATE()) <= 30 then ''0 - 30'' 
		WHEN DATEDIFF(d, i.InvoiceDate, GETDATE()) > 30 and  DATEDIFF(d, i.InvoiceDate, GETDATE()) <= 60 then ''30 - 60''  
		WHEN DATEDIFF(d, i.InvoiceDate, GETDATE()) > 60 and  DATEDIFF(d, i.InvoiceDate, GETDATE()) <= 90 then ''60 - 90'' 
		WHEN DATEDIFF(d, i.InvoiceDate, GETDATE()) > 90 then ''90+'' end as [Invoice Date Aging]
  ,Case WHEN DATEDIFF(d, i.DueDate, GETDATE()) <= 30 then ''0 - 30'' 
		WHEN DATEDIFF(d, i.DueDate, GETDATE()) > 30 and  DATEDIFF(d, i.DueDate, GETDATE()) <= 60 then ''30 - 60''  
		WHEN DATEDIFF(d, i.DueDate, GETDATE()) > 60 and  DATEDIFF(d, i.DueDate, GETDATE()) <= 90 then ''60 - 90'' 
		WHEN DATEDIFF(d, i.DueDate, GETDATE()) > 90 then ''90+'' end as [Due Date Aging]
  ,RIGHT(''0'' + CAST(DATEPART(Month, i.InvoiceDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, i.InvoiceDate) AS [Invoice Month]
  ,CASE
		WHEN LEN(c.EINNumber) >= 3 THEN ''*********'' + SUBSTRING(c.EINNumber, LEN(c.EINNumber) - 2, 3)
		ELSE c.EINNumber
	END AS [EIN Number]
  ,CASE	WHEN c.CCReceipts = 1 THEN ''YES'' ELSE ''NO'' END AS [Allow Credit Card Payments Online]
  ,cam.UserName AS [Campaign Account Manager]
  ,camp2pm.UserName AS [Campaign Project Manager]
  ,ppm.UserName AS [Project Manager]
  ,cpm.UserName AS [Client Project Manager]
  ,i.DeliveryDate AS [Delivery Date]
  ,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]

  FROM tInvoice i (nolock)
	INNER JOIN tCompany c (nolock) ON i.ClientKey = c.CompanyKey 
	INNER JOIN tPreference prefs (NOLOCK) on i.CompanyKey = prefs.CompanyKey
	LEFT OUTER JOIN tUser ic (nolock) ON i.PrimaryContactKey = ic.UserKey
	LEFT OUTER JOIN tUser cbc (nolock) ON c.BillingEmailContact = cbc.UserKey
    LEFT OUTER JOIN tGLAccount glAR (nolock) ON i.ARAccountKey = glAR.GLAccountKey 
	LEFT OUTER JOIN tGLAccount glSales (nolock) ON c.DefaultSalesAccountKey = glSales.GLAccountKey 
	LEFT OUTER JOIN tClass cl (nolock) on i.ClassKey = cl.ClassKey
	LEFT OUTER JOIN tPaymentTerms pt (nolock) ON i.TermsKey = pt.PaymentTermsKey
	LEFT OUTER JOIN tUser u (nolock) on i.ApprovedByKey = u.UserKey
    LEFT OUTER JOIN tProject pr (nolock) on i.ProjectKey = pr.ProjectKey
	LEFT OUTER JOIN tProjectRollup pru (nolock) on i.ProjectKey = pru.ProjectKey
    LEFT OUTER JOIN tCampaign camp (nolock) on pr.CampaignKey = camp.CampaignKey
	LEFT OUTER JOIN tClientDivision cd (nolock) on pr.ClientDivisionKey = cd.ClientDivisionKey
	LEFT OUTER JOIN tClientProduct cp (nolock) on pr.ClientProductKey = cp.ClientProductKey
    LEFT OUTER JOIN tUser u1 (nolock) on i.PrimaryContactKey = u1.UserKey
	LEFT OUTER JOIN tUser am (nolock) on c.AccountManagerKey = am.UserKey
	LEFT OUTER JOIN tUser sales (nolock) on c.SalesPersonKey = sales.UserKey
	LEFT OUTER JOIN tUser pam (nolock) on pr.AccountManager = pam.UserKey
	LEFT OUTER JOIN tUser cpc (nolock) on c.PrimaryContact = cpc.UserKey
	LEFT OUTER JOIN tUser cbk (nolock) on i.CreatedByKey = cbk.UserKey
	LEFT OUTER JOIN tGLCompany glc (nolock) on i.GLCompanyKey = glc.GLCompanyKey
	LEFT OUTER JOIN tOffice o (nolock) on i.OfficeKey = o.OfficeKey
	LEFT OUTER JOIN tCompany pc (nolock) on c.ParentCompanyKey = pc.CompanyKey
	LEFT OUTER JOIN tCompanyType ct (nolock) on c.CompanyTypeKey = ct.CompanyTypeKey
	LEFT OUTER JOIN tInvoiceTemplate it (nolock) on i.InvoiceTemplateKey = it.InvoiceTemplateKey
	LEFT OUTER JOIN tLayout lo (nolock) on i.LayoutKey = lo.LayoutKey
	LEFT OUTER JOIN tCampaign camp2 (nolock) on i.CampaignKey = camp2.CampaignKey
	LEFT OUTER JOIN tCompany ap (nolock) ON i.AlternatePayerKey = ap.CompanyKey
	LEFT OUTER JOIN tBillingGroup bg (nolock) on i.BillingGroupKey = bg.BillingGroupKey 
	LEFT OUTER JOIN tTeam tt (nolock) on pr.TeamKey = tt.TeamKey
	LEFT OUTER JOIN tProjectStatus ps (nolock) on pr.ProjectStatusKey = ps.ProjectStatusKey
	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 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 tBilling b (nolock) on i.BillingKey = b.BillingKey
	LEFT OUTER JOIN tClientProduct cp2 (nolock) on camp2.ClientProductKey = cp2.ClientProductKey
	LEFT OUTER JOIN tClientDivision cd2 (nolock) on camp2.ClientDivisionKey = cd2.ClientDivisionKey	
	LEFT OUTER JOIN vUserName cam (nolock) on camp2.AEKey = cam.UserKey
	LEFT OUTER JOIN vUserName camp2pm (nolock) on camp2.PMKey = camp2pm.UserKey
	LEFT OUTER JOIN vUserName ppm (nolock) on pr.ProjectManager = ppm.UserKey
	LEFT OUTER JOIN vUserName cpm (nolock) on c.ProjectManagerKey = cpm.UserKey
	LEFT OUTER JOIN tCampaignSegment cs (nolock) on pr.CampaignSegmentKey = cs.CampaignSegmentKey 
	LEFT OUTER JOIN tGLAccount glLiab (nolock) ON i.LiabilityAccountKey = glLiab.GLAccountKey

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

AS --Encrypt

/*
|| When      Who Rel      What
|| 12/14/09  CRG 10.5.1.4 Added AEName
|| 1/12/10   CRG 10.5.1.6 Added call to sptWorkTypeCustomGetCampaignList
|| 1/14/10   CRG 10.5.1.7 Added @CompanyKey on call to sptWorkTypeCustomGetCampaignList
|| 3/5/10    CRG 10.5.1.9 Added LayoutName
|| 4/6/10    GHL 10.5.2.1 Added ContactName
|| 5/13/10   CRG 10.5.2.2 (80503) Now retruning EditBillBy to tell the UI whether the BillBy can be changed.
||                        EditBillBy is 0 if any projects are linked to this campaign where their ClientKey does not match the campaign''s ClientKey.
|| 8/9/10    GHL 10.5.3.3 (86008) Added list of projects for the campaign
|| 8/17/10   CRG 10.5.3.3 Modified to use sptCampaignGetProjectList which already existed, so that the project data coming back is consistent. 
|| 8/19/10   CRG 10.5.3.3 Now calling sptCampaignSegmentGetList so that all segment lists returned are the same.
||                        Also consolidated the get for ClientKey and CompanyKey into one query
|| 11/2/10   CRG 10.5.3.7 (92555) Added a check to see if estimates exists to determine whether the "Use Multiple Segments" checkbox is enabled.
||                        We have to check here because the campaign''s estimates aren''t loaded on the screen until the user goes to the "Estimates" tab.
|| 11/17/10  GHL 10.538   Added project template list for drag and drop on segment grid 
|| 09/14/11  GWG 10.548   Expanded logic to edit bill by to include companies in the parent child chain
|| 09/15/11  GWG 10.548   Fixed the expanded logic. needed an AND instead of an OR
|| 04/25/12  GHL 10.555   Added GL company info
|| 09/25/15  RLB 10.5.9.7 Added Favorite and Plat Fields
|| 11/13/17  RLB 10.6.2.2 Filtered out inactive templetes
|| 12/04/17  RLB 10.6.2.2 change to filter on template active not active
|| 10/01/19  GAR 19.1.0.0 (481551) - Add the project manager from the client if there is one
|| 11/26/19  RLS 19.1.2.0 (489887) - Added the condition: OR af.ActionID = ''campaigns.production.myCampaigns'' to the LEFT JOIN on tAppFavorite
|| 01/21/20  GHL 20.0.2.0 (496238) Added LeadID to create projects with number including the LeadID
|| 04/16/20  GAR 20.0.5.0 (473704) Added Project Manager Name - if there is no project manager use the one from the client
|| 07/31/20  RLB 20.0.9.0 (519569) Added project count for this issue
|| 01/23/23  GAR 23.02.19 (628520) Added setting from the client for not allowing project creation
|| 09/05/23  RLB 23.10.15 (649724) Added project Type
|| 01/14/26  MCM 26.02.x  (719575) Added requestID
|| 04/14/26  GAR 26.05.17 (725987) Added RequestedByName
*/

	DECLARE	@EditBillBy tinyint,
			@CompanyKey int,
			@ClientKey int,
			@EstimatesExist tinyint
	
	SELECT	@EditBillBy = 1, --Default to allow BillBy edit
			@EstimatesExist = 0 --Default to No
	
	SELECT	@ClientKey = ClientKey,
			@CompanyKey = CompanyKey
	FROM	tCampaign (nolock)
	WHERE	CampaignKey = @CampaignKey
	
	--If there are projects tied to this campaign where their ClientKey does not match the campaign''s ClientKey or the parent company, then the BillBy cannot be edited
	IF EXISTS
			(SELECT	NULL
			FROM	tProject p (nolock)
			INNER JOIN tCompany c (nolock) ON c.CompanyKey = p.ClientKey
			WHERE	CampaignKey = @CampaignKey
			AND		(c.CompanyKey <> @ClientKey AND c.ParentCompanyKey <> @ClientKey))
		SELECT @EditBillBy = 0

	IF EXISTS
			(SELECT	NULL
			FROM	tEstimate (nolock)
			WHERE	CampaignKey = @CampaignKey)
		SELECT @EstimatesExist = 1

	SELECT	ca.*
			,isnull(ca.CampaignID + '' - '', '''') + isnull(ca.CampaignName, '''') as CampaignFullName
			,glc.GLCompanyID
			,glc.GLCompanyName
			,c.CustomerID
			,c.CompanyName
			,isnull(c.CustomerID + '' - '', '''') + isnull(c.CompanyName, '''') as ClientFullName
			,c.ContactOwnerKey as ClientOwnerKey
			,u.UserName AS AEName
			,l.LayoutName
			,cont.UserName as ContactName
			,cont.Phone1 as ContactPhone
			,cont.Email as ContactEmail
			,cont.OwnerKey as ContactOwnerKey
			,ctd.DivisionName
			,ctp.ProductName
			,CASE ca.BillBy
				WHEN 1 THEN ''Project''
				WHEN 2 THEN ''Campaign''
			END as BillByName
			,CASE ca.OneLinePer
				WHEN 0 THEN ''Project''
				WHEN 9 THEN ''Billing Item and Item''
				WHEN 8 THEN ''Project, Billing Item and Item''
				WHEN 1 THEN ''Project and Task''
			END as OneLinePerLabel
			,@EditBillBy AS EditBillBy
			,@EstimatesExist AS EstimatesExist
			,CASE WHEN ISNULL(af.AppFavoriteKey, 0) > 0 THEN 1 ELSE 0 END AS IsFavorite
			,ISNULL(pm.UserName, pm_client.UserName) AS ProjectManagerName
			,ld.LeadID
			,(SELECT COUNT(*) from tProject p (NOLOCK) WHERE p.CampaignKey = ca.CampaignKey) As ProjectCount
			,c.DoNotUse
			,rq.RequestID
			,rq.RequestedBy as RequestedByName
	FROM	tCampaign ca (nolock)
	INNER JOIN tCompany c (nolock) ON c.CompanyKey = ca.ClientKey
	LEFT JOIN tLayout l (nolock) ON ca.LayoutKey = l.LayoutKey
	LEFT JOIN vUserName u (nolock) ON ca.AEKey = u.UserKey
	LEFT JOIN vUserName cont (nolock) ON ca.ContactKey = cont.UserKey
	LEFT JOIN vUserName pm_client (nolock) ON c.ProjectManagerKey = pm_client.UserKey
	LEFT JOIN vUserName pm (nolock) ON ca.PMKey = pm.UserKey
	LEFT JOIN tClientDivision ctd (nolock) on ca.ClientDivisionKey = ctd.ClientDivisionKey
	LEFT JOIN tClientProduct ctp (nolock) on ca.ClientProductKey = ctp.ClientProductKey
	LEFT JOIN tGLCompany glc (nolock) ON ca.GLCompanyKey = glc.GLCompanyKey
	LEFT JOIN tAppFavorite af (nolock) ON ca.CampaignKey = af.ActionKey AND (af.ActionID = ''cm.campaigns'' OR af.ActionID = ''campaigns.production.myCampaigns'') AND af.UserKey = @UserKey
	LEFT JOIN tLead ld (nolock) on ca.LeadKey = ld.LeadKey
	LEFT JOIN tRequest rq (nolock) on ca.RequestKey = rq.RequestKey

	WHERE	ca.CampaignKey = @CampaignKey
			
	EXEC sptCampaignSegmentGetList @CampaignKey
	
	EXEC sptWorkTypeCustomGetCampaignList @CompanyKey, @CampaignKey

	EXEC sptCampaignGetProjectList @CampaignKey, 0 --Include Tasks

	select tProject.ProjectKey, tProject.ProjectNumber, tProject.ProjectName, isnull(tProject.ProjectNumber + '' - '', '''') + isnull(tProject.ProjectName, '''') as ProjectFullName, tProjectType.ProjectTypeName
	from tProject (nolock) 
	left join tProjectType (nolock) on tProject.ProjectTypeKey = tProjectType.ProjectTypeKey
	where tProject.CompanyKey = @CompanyKey 
	and tProject.Template = 1 and ISNULL(TemplateActive, 1) = 1
	order by isnull(ProjectNumber + '' - '', '''') + isnull(ProjectName, '''')
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptUserGetInfo]'
GO
IF OBJECT_ID(N'[dbo].[sptUserGetInfo]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER Procedure [dbo].[sptUserGetInfo]
 (
  @UserKey int
 )
AS --Encrypt

  /*
  || 11/27/07 GHL 8.5		removed *= join for SQL 2005
  || 12/21/07 GHL 8.5		Added comments after logo because Task Manager looks for go+CR
  || 10/1/08  GWG 10.5		Added Client ID and removed the inner join to tCompany
  || 11/08/11 GHL 10.5.5.0	(114741) Added Security Level
  || 11/07/13 RLB 10.5.7.4	(195465) Added CompanyTimeZoneIndex
  || 07/31/14 QMD 10.5.8.2	changed the default action to today.creative
  || 10/20/14 GWG 10.5.8.5	Added company language ID
  || 10/30/14 MAS 10.5.8.5	Removed stand alone p.LanguageID column, Using ISNULL(ISNULL(u.LanguageID, p.LanguageID), ''EN'') as LanguageID
  || 07/28/15 GWG 10.5.9.4  Added Customizations to the call
  || 12/15/15 GWG 10.5.9.9 Added inactivetimeout to the final get
  || 5/15/18  GWG 18.6.0    Added cascading culture
  || 7/26/19  RLS 19.0.8    (471116) Added cascading ActionID
  || 10/25/19 GWG 19.1.1	Added calls for lab strings so they dont have to be loaded on pages where needed like customizations
  || 2/1/25   GWG 25.02.16  Added in Theme calls
  || 03/25/26 CRG 26.04.19  (721964) Added HasAutomation
  */
  
 Declare @OwnerCompanyKey INT, @ClientLogin tinyint, @DefaultAction varchar(300)
 
 SELECT @OwnerCompanyKey = OwnerCompanyKey, @ClientLogin = ISNULL(ClientVendorLogin, 0)
 FROM tUser (nolock)
 WHERE UserKey = @UserKey
 
 Select @DefaultAction = ''today.creative''
 
 if @ClientLogin = 1
	Select @DefaultAction = ''someaction''
 
 IF @OwnerCompanyKey IS NULL

  SELECT  u.*
         ,c.CompanyName AS CompanyName
         ,c.CustomerID as ClientID
		 ,c.TimeZoneIndex AS CompanyTimeZoneIndex
         ,u.CompanyKey AS LoggedCompanyKey
         ,sg.GroupName    AS SecurityGroupName
		 ,sg.SecurityLevel
         ,p.StyleSheetKey
         ,p.ShowLogo--Trick Task Manager during Installs
         ,c.WebSite
         ,c.CustomLogo--Trick Task Manager during Installs
         ,p.AffiliateKey
         ,p.ReportLogo--Trick Task Manager during Installs
         ,p.SmallLogo--Trick Task Manager during Installs
		 ,p.Customizations
         ,ISNULL(p.ProductVersion, ''CM'') as ProductVersion
         ,ISNULL(ISNULL(u.LanguageID, p.LanguageID), ''EN'') as LangID
         ,p.ApplicationName
         ,ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture)) as Culture
		 ,p.IdleLogout
		 ,ISNULL(u.DefaultActionID, ISNULL(sg.DefaultActionID,@DefaultAction)) as ActionID

		 ,(Select ''|''+ LabID  AS [text()]   
            From tLab l inner join tLabCompany lc on l.LabKey = lc.LabKey Where lc.CompanyKey = u.CompanyKey
            For XML PATH ('''')) as CompanyLabs
	  	 ,(Select ''|''+ SUBSTRING(SessionID, 5, 4000)  AS [text()]   
            From tAppSession Where Entity = ''user'' and EntityKey = u.UserKey and SessionID like ''LAB_%'' and Value = 1
            For XML PATH ('''')) as UserLabs
		 ,ISNULL(ISNULL(u.Theme, p.Theme), 1) as ColorTheme
		 ,CASE
			WHEN EXISTS (SELECT 1 
						FROM	tAutoRule ar (nolock) 
						WHERE	ar.CompanyKey = u.CompanyKey 
						AND		ar.Active = 1 
						AND		ar.IsDeleted <> 1
						AND		(ar.Private <> 1 OR ar.CreatedBy = @UserKey)) THEN 1
			ELSE 0
		  END AS HasAutomation
  FROM    tUser u (NOLOCK)
          LEFT OUTER JOIN tCompany c (NOLOCK) ON u.CompanyKey = c.CompanyKey
          LEFT OUTER JOIN tSecurityGroup  sg (NOLOCK) ON u.SecurityGroupKey = sg.SecurityGroupKey
          INNER JOIN tPreference p (NOLOCK) ON u.CompanyKey = p.CompanyKey
		  LEFT OUTER JOIN tOffice o (nolock) on u.OfficeKey = o.OfficeKey
  WHERE   u.UserKey           = @UserKey
 
 ELSE
 
  SELECT  u.*
         ,c.CompanyName AS CompanyName
         ,c.CustomerID as ClientID
		 ,c.TimeZoneIndex AS CompanyTimeZoneIndex
         ,u.OwnerCompanyKey AS LoggedCompanyKey
         ,sg.GroupName    AS SecurityGroupName
         ,sg.SecurityLevel
         ,p.StyleSheetKey
         ,p.ShowLogo--Trick Task Manager during Installs
         ,c.WebSite
         ,ISNULL(cl.CustomLogo, c.CustomLogo) as CustomLogo--Trick Task Manager during Installs
         ,p.AffiliateKey
         ,p.ReportLogo--Trick Task Manager during Installs
         ,p.SmallLogo--Trick Task Manager during Installs
		 ,p.Customizations
         ,ISNULL(p.ProductVersion, ''CM'') as ProductVersion 
         ,ISNULL(ISNULL(u.LanguageID, p.LanguageID), ''EN'') as LangID
         ,p.ApplicationName
         ,ISNULL(u.UserCulture, ISNULL(o.OfficeCulture, p.Culture)) as Culture
		 ,p.IdleLogout
		 ,ISNULL(u.DefaultActionID, ISNULL(sg.DefaultActionID,@DefaultAction)) as ActionID
		 ,(Select ''|''+ LabID  AS [text()]   
            From tLab l inner join tLabCompany lc on l.LabKey = lc.LabKey Where lc.CompanyKey = u.OwnerCompanyKey
            For XML PATH ('''')) as CompanyLabs
	  	 ,(Select ''|''+ SUBSTRING(SessionID, 5, 4000)  AS [text()]   
            From tAppSession Where Entity = ''user'' and EntityKey = u.UserKey and SessionID like ''LAB_%'' and Value = 1
            For XML PATH ('''')) as UserLabs
		 ,ISNULL(ISNULL(u.Theme, p.Theme), 1) as ColorTheme
		 ,CASE
			WHEN EXISTS (SELECT 1
						FROM	tAutoRule ar (nolock) 
						WHERE	ar.CompanyKey = u.OwnerCompanyKey 
						AND		ar.Active = 1 
						AND		ar.IsDeleted <> 1
						AND		(ar.Private <> 1 OR ar.CreatedBy = @UserKey)) THEN 1
			ELSE 0
		  END AS HasAutomation
  FROM    tUser u (NOLOCK)
          INNER JOIN tCompany c (NOLOCK) ON u.OwnerCompanyKey = c.CompanyKey
          LEFT OUTER JOIN tCompany cl (NOLOCK) ON u.CompanyKey = cl.CompanyKey
          LEFT OUTER JOIN tSecurityGroup sg (NOLOCK) ON u.SecurityGroupKey = sg.SecurityGroupKey
          INNER JOIN tPreference p  (NOLOCK) ON u.OwnerCompanyKey = p.CompanyKey
		  LEFT OUTER JOIN tOffice o (nolock) on u.OfficeKey = o.OfficeKey
  WHERE   u.UserKey = @UserKey
 

 return 1 

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[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 gla.EntityKey = @UserKey and gla.Entity = ''User'')


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'Altering [dbo].[sptProjectStatusInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptProjectStatusInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptProjectStatusInsert]
	@CompanyKey int,
	@ProjectStatusID nvarchar(30),
	@ProjectStatus nvarchar(200),
	@DisplayOrder int,
	@StatusCategory smallint,
	@IsActive tinyint,
	@Active tinyint,
	@TimeActive tinyint,
	@ExpenseActive tinyint,
	@Locked tinyint,
	@OnHold tinyint,
	@ProjectStatusColor varchar(50) null,
	@oIdentity INT OUTPUT
AS --Encrypt

/*
|| When      Who Rel      What
|| 7/11/18   RLS 18.8     (TODO 4515) Added @Active parameter.
|| 05/11/21  RLS 21.0.6.0 (556492) Changed ProjectStatusID to nvarchar 
|| 05/11/21  RLS 21.0.6.0 (556492) Changed ProjectStatus to nvarchar
|| 03/31/26  GAR 26.04.19 (723332) Added ProjectStatusColor
*/

	IF EXISTS(
		SELECT 1
		FROM tProjectStatus (NOLOCK) 
		WHERE 	ProjectStatusID = @ProjectStatusID AND
			CompanyKey = @CompanyKey
		)
		RETURN -1

	INSERT tProjectStatus
		(
		CompanyKey,
		ProjectStatusID,
		ProjectStatus,
		DisplayOrder,
		StatusCategory,
		IsActive,
		Active,
		TimeActive,
		ExpenseActive,
		Locked,
		OnHold,
		ProjectStatusColor
		)

	VALUES
		(
		@CompanyKey,
		@ProjectStatusID,
		@ProjectStatus,
		@DisplayOrder,
		@StatusCategory,
		@IsActive,
		@Active,
		@TimeActive,
		@ExpenseActive,
		@Locked,
		@OnHold,
		@ProjectStatusColor
		)
	
	SELECT @oIdentity = @@IDENTITY

	RETURN 1
	



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




ALTER PROCEDURE [dbo].[sptProjectStatusUpdate]
	@ProjectStatusKey int,
	@CompanyKey int,
	@ProjectStatusID nvarchar(30),
	@ProjectStatus nvarchar(200),
	@DisplayOrder int,
	@StatusCategory smallint,
	@IsActive tinyint,
	@Active tinyint,
	@TimeActive tinyint,
	@ExpenseActive tinyint,
	@Locked tinyint,
	@OnHold tinyint,
	@IncludeInForecast tinyint,
	@IsDefault tinyint = 0,
	@UpdateBaseline tinyint = 0,
	@ProjectStatusColor varchar(50) null

AS --Encrypt
  /*
  || When     Who Rel      What
  || 08/26/09 MAS 10.5.0.8 Added insert logic
  || 9/5/12   CRG 10.5.6.0 Added IncludeInForecast
  || 7/11/18  RLS 18.8     (TODO 4515) Added @Active parameter.
  || 10/08/19 RLS 18.8     (457489) Added IsDefault
  || 05/11/21 RLS 21.0.6.0 (556492) Changed ProjectStatusID to nvarchar
  || 05/11/21 RLS 21.0.6.0 (556492) Changed ProjectStatus to nvarchar
  || 08/05/24 CRG 24.09.15 (673989) Added UpdateBaseline
  || 03/31/26 GAR 26.04.19 (723332) Added ProjectStatusColor
  */

 if (@IsDefault = 1) -- make them all zero first
	BEGIN
		UPDATE tProjectStatus SET IsDefault = 0 WHERE CompanyKey = @CompanyKey 
	END

If @ProjectStatusKey <= 0
	BEGIN
		INSERT tProjectStatus
		(
		CompanyKey,
		ProjectStatusID,
		ProjectStatus,
		DisplayOrder,
		StatusCategory,
		IsActive,
		Active,
		TimeActive,
		ExpenseActive,
		Locked,
		OnHold,
		IncludeInForecast,
		IsDefault,
		UpdateBaseline,
		ProjectStatusColor
		)

		VALUES
		(
		@CompanyKey,
		@ProjectStatusID,
		@ProjectStatus,
		@DisplayOrder,
		@StatusCategory,
		@IsActive,
		@Active,
		@TimeActive,
		@ExpenseActive,
		@Locked,
		@OnHold,
		@IncludeInForecast,
		@IsDefault,
		@UpdateBaseline,
		@ProjectStatusColor
		)
					
		RETURN @@IDENTITY
	END
ELSE
	BEGIN
		IF EXISTS(
			SELECT 1
			FROM tProjectStatus (NOLOCK) 
			WHERE 
				ProjectStatusID = @ProjectStatusID AND
				CompanyKey = @CompanyKey AND
				ProjectStatusKey <> @ProjectStatusKey
		)

		RETURN -1
		
		UPDATE
			tProjectStatus
		SET
			CompanyKey = @CompanyKey,
			ProjectStatusID = @ProjectStatusID,
			ProjectStatus = @ProjectStatus,
			DisplayOrder = @DisplayOrder,
			StatusCategory = @StatusCategory,
			IsActive = @IsActive,
			Active = @Active,
			TimeActive = @TimeActive,
			ExpenseActive = @ExpenseActive,
			Locked = @Locked,
			OnHold = @OnHold,
			IncludeInForecast = @IncludeInForecast,
			IsDefault = @IsDefault,
			UpdateBaseline = @UpdateBaseline,
			ProjectStatusColor = @ProjectStatusColor
		WHERE
			ProjectStatusKey = @ProjectStatusKey 
		
		UPDATE
			tProject
		SET
			Active = @IsActive
		WHERE
			ProjectStatusKey = @ProjectStatusKey

		RETURN @ProjectStatusKey
	END

RETURN 1


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

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
    ,@TaskKey                               as taskKey
    ,@ServiceKey                            as serviceKey
    ,@Hours                                 as hours

drop table #errors
return 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAITimeSubmitTimesheet]'
GO
IF OBJECT_ID(N'[dbo].[spApiAITimeSubmitTimesheet]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spApiAITimeSubmitTimesheet]
    (
        @CompanyKey  int,
        @UserKey     int,
        @WorkDate    smalldatetime
    )
AS --Encrypt

/*
|| When      Who Rel        What
|| 03/10/26  QMD 26.03.15   Created for AI time tool
*/

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].[sptMediaPlanDetailCreateOrderDetail]'
GO
IF OBJECT_ID(N'[dbo].[sptMediaPlanDetailCreateOrderDetail]', 'P') IS NOT NULL
EXEC sp_executesql N'


ALTER procedure [dbo].[sptMediaPlanDetailCreateOrderDetail]
	(
	@PurchaseOrderKey int
	,@MediaPlanDetailKey int
	)
	as
--Encrypt

  /*
  || When     Who Rel      What
  || 05/30/19 GHL 19.060   Created for new media plans
  ||                       creates a POD from a media plan detail
  || 06/12/19 GHL 19.070   Added update of MediaPlanDetailKey on POD
  || 10/06/19 GHL 19.110   Fixed line number calculation
  || 01/25/22 MAS 22.02.20 Check to see if Department is required
  || 03/14/22 MAS 23.3.19  (632405) Set SkipRollUps = 1 When calling sptPurchaseOrderDetailInsert to prevent the rollups from being called multiple times
  || 12/15/25 MCM 26.01.18 (716597) Updated the SalesTax logic to match the Vouchers
  || 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName
  */

  /*
  Still todo: multi currency data 
  */

  -- vars for the tMediaPlanDetail table 
  declare 	@MediaPlanVendorKey [int],
	@SpotLinkID [varchar](50) ,
	@StartDate [smalldatetime] ,
	@EndDate [smalldatetime] ,
	--Description] [varchar](max) ,
	@OrderDays [varchar](50) ,
	@OrderTime [varchar](50) ,
	@OrderLength [varchar](50) ,
	@Date1 [smalldatetime] ,
	@Date2 [smalldatetime] ,
	@Quantity [decimal](24, 6) ,
	@Cost [decimal](24, 6) ,
	@UnitCost [decimal](24, 6) ,
	@Markup [decimal](24, 6) ,
	@Gross [decimal](24, 6) ,
	@AmountToBill [decimal](24, 6) ,
	@DateAdded [smalldatetime] ,
	@DateModified [smalldatetime] ,
	@Status [varchar](100) 

  -- other vars
  declare @ItemKey int  -- from tMediaPlanVendor
  declare @LineNumber int
  declare @RetVal int
  declare @NewKey int
  declare @ProjectKey int
  declare @TaskKey int	-- stays null
  declare @OfficeKey int
  declare @DepartmentKey int -- stays null?
  declare @ClassKey int
  declare @PCurrencyID varchar(100)
  declare @PExchangeRate decimal(24,7)
  declare @RequireDepartment tinyint
  declare @CompanyKey int
  declare @Taxable int
  declare @Taxable2 int

  select @ItemKey = mpv.ItemKey,
    @MediaPlanVendorKey = mpd.MediaPlanVendorKey,
	@SpotLinkID  = mpd.SpotLinkID,
	@StartDate  = mpd.StartDate,
	@EndDate  = mpd.EndDate,
	--Description] [varchar](max) ,
	@OrderDays  = mpd.OrderDays,
	@OrderTime  = mpd.OrderTime,
	@OrderLength = mpd.OrderLength,
	@Date1 = mpd.Date1,
	@Date2 = mpd.Date2,
	@Quantity = mpd.Quantity ,
	@Cost = mpd.Cost ,
	@UnitCost =  mpd.UnitCost,
	@Markup = mpd.Markup,
	@Gross = mpd.Gross,
	@AmountToBill = mpd.AmountToBill,
	@DateAdded = mpd.DateAdded,
	@DateModified = mpd.DateModified,
	@Status = mpd.Status
 from tMediaPlanDetail mpd (nolock)
	inner join tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
 where mpd.MediaPlanDetailKey = @MediaPlanDetailKey
  

select @LineNumber = max(LineNumber)
from tPurchaseOrderDetail (nolock)
where PurchaseOrderKey = @PurchaseOrderKey

if isnull(@LineNumber,0) = 0
	select @LineNumber = 1
else
	select @LineNumber = @LineNumber + 1 

select @ProjectKey = ProjectKey 
      ,@PCurrencyID = PCurrencyID
	  ,@PExchangeRate = PExchangeRate
	  ,@ClassKey = ClassKey
	  ,@CompanyKey = CompanyKey
from tPurchaseOrder (nolock)
where PurchaseOrderKey = @PurchaseOrderKey

-- Check department is required 
select @RequireDepartment = RequireDepartment
from tPreference (nolock)
where CompanyKey = @CompanyKey

select @DepartmentKey = DepartmentKey
from tItem (nolock)
where ItemKey = @ItemKey

if @RequireDepartment = 1 
	if @DepartmentKey is null -- department is required
		begin
		  update tMediaPlanDetail set ErrMsgOrder = ''department is required and has not been set on the item.'' where MediaPlanDetailKey = @MediaPlanDetailKey
		  return 1	
		end		

-- get office and from project
select @OfficeKey = OfficeKey 
from  tProject (nolock)
where ProjectKey = @ProjectKey

-- Get the taxable information from the item, if applicable
if isnull(@ItemKey, 0) > 0				
	select @Taxable = Taxable
			,@Taxable2 = Taxable2
	from  tItem (nolock)
	where ItemKey = @ItemKey
else
	select @Taxable = 0
			,@Taxable2 = 0

	EXEC @RetVal = sptPurchaseOrderDetailInsert 
		@PurchaseOrderKey = @PurchaseOrderKey,
		@LineNumber = @LineNumber,
		@ProjectKey = @ProjectKey,
		@TaskKey = @TaskKey,
		@ItemKey = @ItemKey,
		@ClassKey = @ClassKey,
		@ShortDescription = NULL,
		@Quantity = @Quantity,
		@UnitCost = @UnitCost,
		@UnitDescription = NULL,
		@TotalCost = @Cost,
		@UnitRate = NULL,
		@Billable = 1,
		@Markup = @Markup,
		@BillableCost = @AmountToBill,
		@LongDescription = NULL,
		@CustomFieldKey = 0,
		@DetailOrderDate = @StartDate,
		@DetailOrderEndDate = @EndDate,
		@UserDate1 = @Date1,
		@UserDate2 = @Date2,
		@UserDate3 = NULL,
		@UserDate4 = NULL,
		@UserDate5 = NULL,
		@UserDate6 = NULL,
		@OrderDays = @OrderDays,
		@OrderTime = @OrderTime,
		@OrderLength = @OrderLength,
		@Taxable = @Taxable,
		@Taxable2 = @Taxable2,
		@OfficeKey = @OfficeKey,
		@DepartmentKey = @DepartmentKey,
		@GrossAmount = @Gross,
		@PCurrencyID = @PCurrencyID,
		@PExchangeRate = @PExchangeRate,
		@PTotalCost = @Cost,
		@SkipRollUps = 1,
		@InteractiveAdUnitName = NULL,
		@oIdentity = @NewKey OUTPUT

	if isnull(@NewKey, 0) > 0
	begin		
		-- and update the fields coming from the media plans
		Update tPurchaseOrderDetail 
		Set tPurchaseOrderDetail.LinkID = @SpotLinkID
			,tPurchaseOrderDetail.ShortDescription = mpd.Description
			,tPurchaseOrderDetail.MediaPlanDetailKey = @MediaPlanDetailKey
		From tMediaPlanDetail mpd (nolock)
		Where tPurchaseOrderDetail.PurchaseOrderDetailKey = @NewKey
		and  mpd.MediaPlanDetailKey = @MediaPlanDetailKey 

		-- these 2 errors are unlikely
		if @@ERROR <> 0
		begin
			exec sptPurchaseOrderDetailDelete @NewKey
			update tMediaPlanDetail set ErrMsgOrder = ''Error linking to actual order detail record'' where MediaPlanDetailKey = @MediaPlanDetailKey
			return 1
		end

		Update tMediaPlanDetail 
		Set    PurchaseOrderDetailKey = @NewKey
		Where  MediaPlanDetailKey = @MediaPlanDetailKey 
	
		if @@ERROR <> 0
		begin
			exec sptPurchaseOrderDetailDelete @NewKey
			update tMediaPlanDetail set ErrMsgOrder = ''Error linking to actual order detail record'' where MediaPlanDetailKey = @MediaPlanDetailKey
		end

	end
	else 
	begin
		if @RetVal = -3
			update tMediaPlanDetail set ErrMsgOrder = ''The project does not accept expenses'' where MediaPlanDetailKey = @MediaPlanDetailKey
	end
		
	return 1



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptStrataPrintOrderDetail]'
GO
IF OBJECT_ID(N'[dbo].[sptStrataPrintOrderDetail]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptStrataPrintOrderDetail]
	(
		@PurchaseOrderKey int,
		@UserKey int,
		@LinkID varchar(50),
		@StartDate smalldatetime,
		@Quantity decimal(24,4),
		@Program varchar(max),
		@Comments varchar(1000),
		@Date1 smalldatetime,
		@Date2 smalldatetime,
		@TotalGross decimal(24,6),
		@TotalNet decimal(24,6),
		@TotalClientGross decimal(24,6), -- NOT USED - REMOVE
		@TotalClientNet decimal(24,6),
		@IlStatus varchar(5),
		@IlCost decimal(24,6),  -- Use this to pass in the DFA Unit Rate
		@IlNetPercent decimal(24,6),
		@CalCltNetType decimal(24,6),
		@IlCltNetPercent decimal(24,6),
		@IlCltGrossPercent decimal(24,6) = 0,
		@CMP tinyint = 0,	-- syncing from CMP?  WMJ = 0 / CMP = 1
		@NetCost decimal(24,6) = NULL, -- Updated Print option for deprecated CalCltNetType
		@CltNet decimal(24,6) = NULL, -- Update Print option for deprecated CalCltNetType
		@InteractiveAdUnitName varchar(100) = null -- only used for interactive orders, to pass the AdUnitName in for client costing calculations
	)
AS --Encrypt

  /*
  || When     Who Rel      What
  || 10/03/06 RTC 8.3566   Added logic to handle auto-revision lines for print orders.
  || 11/16/06 CRG 8.3571   Modified to get ClassKey from tPurchaseOrder.
  || 02/05/07 RTC 8.4.0.2  When creating two line adjustments, insure the second ine''s total cost <> 0
  || 04/17/07 BSH 8.4.5    DateUpdated needed to be updated.
  || 10/01/07 GHL 8.5      Added DateClosed logic
  || 10/05/07 BSH 8.5      Insert OfficeKey to PO Detail, get from Estimate or Project based on ClientLink. 
  || 04/28/09 RTC 10.0.2.4 (50959) Corrected issues with zero quantity revision line generation.
  || 10/07/09 MAS 10.5.1.9 () Calculate Client Costing
  || 10/07/09 MAS 10.5.1.9 (67320) Removed rounding when calculating Client Costing UnitRate/UnitCost also set Commision/Markup = 0 when UnitRate = 0
  || 11/11/09 MAS 10.5.1.3 (47035)
  || 11/17/09 MAS 10.5.1.9 (68648) Removed ISNULL(UseClientCosting,0) when getting UseClientCosting from tPurchaseOrder as it was forcing 
  ||					    No Client Costing, when it should have pulled it out of the Pref table					 
  || 01/14/09 MAS 10.5.1.6 (71874) Changed the Client Costing calculation for Interactive Orders
  || 10/19/10 MAS 10.5.3.7 (92477) Added support for a new Strata Print Client Costing option "Client Gross % statistic"
  || 11/11/10 MAS 10.5.3.8 Reset the PO Header closed flag to 0 when a new line is added.
  ||                       Changed the way we determine if a revision line should be created.  We were using an AVG(UnitCost), we now use TotalCost
  || 12/09/10 MAS 10.5.3.9 (96319)Both print and interactive are always a quantity of 1.  Only create an adjustment line if the @NetTotalCost has changed
  ||                       Always use quantity 0 for adjustment lines.  
  ||                       Delete the auto revision line if the adjustment would result in a $0 line	
  || 03/15/11 MAS 10.5.3.9 (105980)Account for a DetailOrderDate change
  || 05/24/11 MAS 10.5.4.4 (109450)Verify the Task and Project are accepting changes before performing an update/insertion.  Previsouly we were
  ||                       checking the project''s status only in sptStrataMediaEstimateUpdate.  So, if during a sync an order that 
  ||                       was not accepting changes was included (and no changes were actually made) they would get an error.
  || 06/15/11 MAS 10.5.4.5 (114001)If not using tasks (TaskKey is 0 or NULL), always defualt @TaskAcceptingUpdates = 1 
  || 08/30/11 MAS 10.5.4.7 (119003)Compare the SUM of TotalCost and BillableCost against the @TotGross and @TotNet to see if something changed
  || 07/11/12 MAS 10.5.5.7 (148195)Changed the precision of the client costing params
  || 08/23/12 MAS 10.5.5.9 (152132)Changed the precision of all the rest of the client costing params
  || 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @Program(ShortDescription) from 200 to 300
  || 03/14/13 MAS 10.5.6.6 Added @CalCltNetType 100 to support Interactive changes.  The new interactive changes use a query that already calculates the
  ||					   Order net and gross.
  || 05/08/13 MAS 10.5.6.7 Added @TotalClientGross & @TotalClientNet to support Interactive changes
  || 11/15/13 MAS 10.5.7.5 (196866) Use @TotalGross for the Interactive Gross.  ORDERED_GROSS_COST (from the Strata query)
  || 12/17/13 GHL 10.5.7.4  Added PCurrency and PExchangeRate parms when calling sptPurchaseOrderDetailInsert
  || 02/03/14 GHL 10.5.7.6  Added update of PTotalCost when updating directly tPurchaseOrderDetail
  || 02/05/14 PLC 10.5.7.6  Fixed client net for interactive. 
  || 04/29/14 RLB 10.5.7.9 (214240)Changed the length of @Program(ShortDescription) from 300 to max
  || 06/11/14 GHL 10.5.8.1  Added UserKey = null when calling sptPurchaseOrderDetailDelete, UserKey is used to log print orders with media WS  
  || 08/23/17 MAS 10.6.1.9 (359558) sptPurchaseOrderDetailDelete returns multiple values - pass them back to VB
  || 03/26/19 MAS 19.0.4.0 (451596) Per Stata, as of v22.3 of SBMS, Treat @CalCltNetType 2 an 5 the same
  || 05/06/19 GHL 19.0.5.0 (456404) Added update of GrossAmount, because the triggers do not seem to update them
  || 11/19/19 MAS 19.1.2.0 (487649) Updated the way we do rounding.  Round rates/commisones to 4 spaces, and costs to 2. Apply rounding after all calculations
  || 11/23/20 MAS 20.1.2.0 (520509) Added @NetCpst And @ClientNet to support @CalCltNetType deprecation (v22.3) - TODO Clean up Old code after a couple releases.
  || 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
  || 01/25/24 MAS 24.2.18 (660506) Added sptActionLog when updating PurchaseOrder or PurchaseOrderDetail Closed flags
  || 04/22/26 MCM 26.5.x  (725435) Added @InteractiveAdUnitName for PurcahseOrderDetail
  */
    
Declare @PODKey int
Declare @ProjectKey int, @TaskKey int, @ItemKey int, @RetVal int, @NewKey int, @TotNet money, @TotGross money, @Markup decimal(24,4)
declare @AppliedCost money
declare @TotalCost money 
declare @Closed tinyint
declare @AllowChangesAfterClientInvoice tinyint
declare @GeneratePrebilledRevisions tinyint
declare @ShowAdjustmentsAsSingleLine tinyint
declare @Prebilled as tinyint
declare @NetQuantity decimal(24,4)
declare @NetTotalCost money
declare @NetBillableCost money
declare @AdjUnitCost money
declare @AdjTotalCost money
declare @AdjBillableCost money
declare @ExistingPODAdjKey int
declare @ExistingPODAdjTotalCost money
declare @ExistingPODAdjBillableCost money
declare @NewAdjustmentNumber int
declare @NewAdjustmentNumber2 int
declare @CustomFieldKey int
declare @ObjectFieldSetKey int
declare @CompanyKey int
declare @LineNumber int 
declare @ClassKey int
declare @OfficeKey int
declare @IOClientLink int
declare @MediaEstimateKey int
declare @DepartmentKey int
declare @RequireDepartment tinyint 
declare @DFA tinyint
declare @UnitDescription varchar(30)
declare @UseClientCosting tinyint 
declare @POClientCosting tinyint 
declare @UnitCost money
declare	@UnitRate money
declare	@Commission decimal(24,4)
declare @ProjectAcceptingUpdates int
declare @TaskAcceptingUpdates int
declare @CurrTotalCost money
declare @CurrBillableCost money
declare @CurrentDate smalldatetime
declare @ActionLogComment varchar(1000)
declare @AdjustmentNumber int

Select 
	 @ProjectKey = ProjectKey, @TaskKey = TaskKey, @ItemKey = ItemKey
	,@CompanyKey = CompanyKey
	,@ClassKey = ClassKey
	,@MediaEstimateKey = MediaEstimateKey
	,@POClientCosting = UseClientCosting
From tPurchaseOrder (nolock) Where PurchaseOrderKey = @PurchaseOrderKey

Select @CurrentDate = CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime) 

-- determine if order lines (spots) can be updated after client invoice has been created
-- determine if revision lines should be auto generated for prebilled lines
-- determine if one or two revision lines should be created
select @AllowChangesAfterClientInvoice = isnull(IOAllowChangesAfterClientInvoice, 0)
      ,@GeneratePrebilledRevisions = isnull(IOGeneratePrebilledRevisions, 0)
      ,@ShowAdjustmentsAsSingleLine = isnull(IOShowAdjustmentsAsSingleLine, 1)
      ,@IOClientLink = isnull(IOClientLink,1)
      ,@RequireDepartment = RequireDepartment
      ,@UseClientCosting = IOUseClientCosting
      ,@DFA = CASE ISNULL(CHARINDEX(''dfa'',Customizations), 0) When 0 then 0 Else 1 End
  from tPreference (nolock)
 where CompanyKey = @CompanyKey

-- If POD ClientCosting is NULL use the system setting
if @POClientCosting is null
	Begin
		Select @POClientCosting = @UseClientCosting
		
		Update tPurchaseOrder 
		Set UseClientCosting = @POClientCosting
		Where PurchaseOrderKey = @PurchaseOrderKey
	End

-- print lines can have a line that has been cancelled but still marked as billed
-- transfer these lines but at zero cost, if the generate automatic revision lines 
-- option is set a full reversal adjustemnt line wil be generated
if Upper(@IlStatus) = ''Z''
	Begin
		Select @UnitCost = 0
		Select @UnitRate = 0
		Select @Commission = 0
	End
else
	Begin
		-- Interactive and Print order are handled the same except for the calculations, 
		-- @CalCltNetType = 0 for interactive orders, @CalCltNetType = 100 for NEW interactive orders
		--  @CalCltNetType = 200 for UPDATED Print orders
		-- @CalCltNetType = 99 DFA orders (does not use client costing)
		if @POClientCosting = 1
			begin
				Select @UnitCost = -- Net
					case @CalCltNetType
						when 0 then @TotalNet * (1 - @IlNetPercent)   -- Interactive Order
						when 100 then @TotalNet						  -- New Interactive Order. The Net that goes into WMJ is always the SBMS Vendor Net.
						when 200 then @NetCost						  -- Updated Print Order (deprecated CalCltNetType) 
						else @IlCost * (1 - @IlNetPercent)			  -- Print/DFA Order
					end
				Select @UnitRate = -- Gross
					case @CalCltNetType
						when 0 then @TotalGross * (1 - @IlCltNetPercent)			-- Interactive Order
						-- Fix to use Client Net
						when 100 then @TotalClientNet								-- New Interactive Order. The WMJ Gross is Vendor Gross from SBMS if using Client Costing. Fix to use Client Net
						when 200 then @CltNet										-- Updated Print Order (deprecated CalCltNetType)
						when 1 then @UnitCost + (@IlCost * @IlCltNetPercent)		-- Print Order
						when 2 then @UnitCost + (@UnitCost * @IlCltNetPercent)	
						when 3 then @UnitCost / (1 - @IlCltNetPercent)	
						when 4 then @IlCost * @IlCltGrossPercent * (1 - @IlCltNetPercent)
						when 5 then @UnitCost + (@UnitCost * @IlCltNetPercent)	-- Per Stata, as of v22.3 of SBMS, Treat @CalCltNetType 2 an 5 the same
					end
				if @UnitRate = 0
					Select @Commission = 0
				else	
					Select @Commission = ROUND((1 - @UnitCost / @UnitRate) * 100, 4)
			end
		else
			begin
				Select @UnitCost = -- Net
					case @CalCltNetType
						when 0 then @TotalNet * (1 - @IlNetPercent)	-- Interactive Order
						when 100 then @TotalNet						-- New Interactive Order. The Net that goes into WMJ is always the SBMS Vendor Net.
						when 200 then @NetCost						  -- Updated Print Order (deprecated CalCltNetType)
						else @IlCost * (1 - @IlNetPercent)			-- Print/DFA Order
					end
				Select @UnitRate = -- Gross
					case @CalCltNetType
						when 0 then @TotalNet			-- Interactive Order
						when 100 then @TotalGross		-- New Interactive Order. ORDERED_GROSS_COST (from the Strata query)
						when 200 then @IlCost			-- Updated Print Order (deprecated CalCltNetType)
						else @IlCost -- Old Print/DFA Order
					end	
				Select @Commission = @IlNetPercent * 100
			end
	End
		
if @IOClientLink = 1
	select @OfficeKey = OfficeKey
	from tProject (nolock)
	where ProjectKey = @ProjectKey
else
	select @OfficeKey = OfficeKey
	from tMediaEstimate (nolock)
	where MediaEstimateKey = @MediaEstimateKey

select @DepartmentKey = DepartmentKey
from tItem (nolock)
where ItemKey = @ItemKey

if @RequireDepartment = 1 -- department is required
	if @DepartmentKey is null
		return -3	
     
Select @PODKey = MIN(PurchaseOrderDetailKey)
From tPurchaseOrderDetail (NOLOCK) Where PurchaseOrderKey = @PurchaseOrderKey and LinkID = @LinkID

if ISNULL(@DFA, 0) = 1
	Begin
		select @TotNet = @TotalNet
		select @TotGross = @TotalGross
		select @UnitDescription = @IlStatus		
	end
Else
	Begin
		select @TotNet = ROUND(ISNULL(@UnitCost, 0) * ISNULL(@Quantity, 0), 2) 
		select @TotGross = ROUND(ISNULL(@UnitRate, 0) * ISNULL(@Quantity, 0), 2)
		Select @UnitDescription = null
	End
	
-- If using Projects/Tasks - Check to see if the associated Task is completed
if ISNULL(@CMP,0) = 0 and ISNULL(@TaskKey,0) > 0
	BEGIN
		exec @RetVal = spTaskValidatePercComp ''tPurchaseOrderDetail'',@PODKey, NULL, @ProjectKey, NULL, @TaskKey, @UserKey
		if @RetVal < 0 
			select @TaskAcceptingUpdates = 0 -- return -4 
		else
			select @TaskAcceptingUpdates = 1
	END	
else
	BEGIN
	-- Default to allow tasks to accept updates
		select @TaskAcceptingUpdates = 1
	END
	
-- determine if the project is accepting updates
if exists(Select 1 from tProject p (NOLOCK) 
		  inner join tProjectStatus ps (NOLOCK) on p.ProjectStatusKey = ps.ProjectStatusKey
		  Where p.ProjectKey = @ProjectKey and  ps.ExpenseActive = 1 )	
	Begin
		Select @ProjectAcceptingUpdates = 1
	End
Else
	Begin
		-- if there isn''t a project set for this order, then accept changes
		if ISNULL(@ProjectKey,0) = 0
			Select @ProjectAcceptingUpdates = 1
		else
			Select @ProjectAcceptingUpdates = 0
	End			  
			
if @PODKey is null
BEGIN
	if ISNULL(@TaskAcceptingUpdates,0) = 0 
		return -4
	if ISNULL(@ProjectAcceptingUpdates,0) = 0 
		return -6
	
exec @RetVal = sptPurchaseOrderDetailInsert
    @PurchaseOrderKey = @PurchaseOrderKey,
    @LineNumber = 0,
    @ProjectKey = @ProjectKey,
    @TaskKey = @TaskKey,
    @ItemKey = @ItemKey,
    @ClassKey = @ClassKey,
    @ShortDescription = @Program,
    @Quantity = @Quantity,
    @UnitCost = @UnitRate,
    @UnitDescription = @UnitDescription,
    @TotalCost = @TotNet,
    @UnitRate = NULL,
    @Billable = 1,
    @Markup = @Commission,
    @BillableCost = @TotGross,
    @LongDescription = @Comments,
    @CustomFieldKey = 0,
    @DetailOrderDate = @StartDate,
    @DetailOrderEndDate = NULL,
    @UserDate1 = @Date1,
    @UserDate2 = @Date2,
    @UserDate3 = NULL,
    @UserDate4 = NULL,
    @UserDate5 = NULL,
    @UserDate6 = NULL,
    @OrderDays = NULL,
    @OrderTime = NULL,
    @OrderLength = NULL,
    @Taxable = 0,
    @Taxable2 = 0,
    @OfficeKey = @OfficeKey,
    @DepartmentKey = @DepartmentKey,
    @GrossAmount = @TotGross,
    @PCurrencyID = NULL,
    @PExchangeRate = 1,
    @PTotalCost = @TotNet,
    @SkipRollUps = NULL,
	@InteractiveAdUnitName = @InteractiveAdUnitName,
    @oIdentity = @NewKey OUTPUT
		
	Update tPurchaseOrderDetail Set LinkID = @LinkID Where PurchaseOrderDetailKey = @NewKey

--Cast(Cast(DatePart(mm,@StartDate) as varchar) + ''/'' + Cast(DatePart(dd,@StartDate) as varchar) + ''/'' + Cast(DatePart(yyyy,@StartDate) as varchar) as datetime),

END
ELSE
BEGIN

		-- make sure this line is not on a billing worksheet
		if exists(select 1 
		            from tBillingDetail bd (nolock) inner join tBilling b (nolock) on bd.BillingKey = b.BillingKey
		           where bd.EntityKey = @PODKey 
		            and bd.Entity = ''tPurchaseOrderDetail''
		             and b.Status < 5)
			return -2 
			
		-- if this is an existing line and it has been invoiced, do not allow changes if the system options do not allow
		select @Prebilled = 0
		if exists(select 1 from tPurchaseOrderDetail (nolock) Where PurchaseOrderDetailKey = @PODKey and InvoiceLineKey is not null)		
			begin
				select @Prebilled = 1
				if @GeneratePrebilledRevisions = 0 and @AllowChangesAfterClientInvoice = 0
						-- the line was prebilled and system options do not allow any kind of updating
						return -1
			end	
				
		-- check to see if something changed between strata and WMJ and if the project/task allows changes
		select @LineNumber = LineNumber
				from tPurchaseOrderDetail (nolock)
				where PurchaseOrderDetailKey = @PODKey
				
		Select 	@CurrTotalCost = SUM(ISNULL(TotalCost,0)),
				@CurrBillableCost = SUM(ISNULL(BillableCost,0))
				from tPurchaseOrderDetail (nolock) 
				Where PurchaseOrderKey = @PurchaseOrderKey
				and LineNumber = @LineNumber			
					
		if 	@CurrTotalCost <> @TotNet or
			@CurrBillableCost <> @TotGross 
			begin
				if ISNULL(@TaskAcceptingUpdates,0) = 0 
					return -4
				if ISNULL(@ProjectAcceptingUpdates,0) = 0 
					return -6
			end

		-- check to see if the Strata order date has changed since the original sync, if so, update the line and all revisions. (105980)
		if @StartDate <> (Select DetailOrderDate from tPurchaseOrderDetail (nolock) Where PurchaseOrderDetailKey = @PODKey)
			begin
				-- get current values from original line and any automatic or manual revision lines associated to it for a period within the flight
				select @LineNumber = LineNumber
				from tPurchaseOrderDetail (nolock)
				where PurchaseOrderDetailKey = @PODKey
				
				update tPurchaseOrderDetail 
				set DetailOrderDate = @StartDate
				where PurchaseOrderKey = @PurchaseOrderKey
				and LineNumber = @LineNumber
			end
		
		-- is this a prebilled line that may require auto-revision line(s) to be created
		if @Prebilled = 1 and @GeneratePrebilledRevisions = 1
			begin
				-- get current values from original line and any automatic or manual revision lines associated to it for a period within the flight
				select @LineNumber = LineNumber
				from tPurchaseOrderDetail (nolock)
				where PurchaseOrderDetailKey = @PODKey
				
				if @ShowAdjustmentsAsSingleLine = 1
					select @NetQuantity = sum(Quantity)
							,@NetTotalCost = sum(TotalCost)
							,@NetBillableCost = sum (BillableCost)
					from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and LineNumber = @LineNumber
					---and ((isnull(AutoAdjustment,0) = 0)  -- include billed and unbilled manual adjustment lines
					---	or (isnull(AutoAdjustment,0) = 1 and InvoiceLineKey is not null))  -- only include billed auto-adjustment lines since we will reuse the existing unbilled auto adjustment line for the update below
				else -- two line adjustments
					-- include billed and unbilled manual adjustment lines
					-- include billed and unbilled auto-adjustment lines
					select @NetQuantity = sum(Quantity)
							,@NetTotalCost = sum(TotalCost)
						   ,@NetBillableCost = sum (BillableCost)
					from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and LineNumber = @LineNumber
				
				-- verify something has changed, requiring a revision				
				if @NetTotalCost <> @TotNet
					begin
						-- determine if we need to create one or two adjustment lines
						if @ShowAdjustmentsAsSingleLine = 1
							begin

								-- If we have an existing @ExistingPODAdj line, we''ll need to exclude it from the adjustment amount
								-- since it was included in @NetTotalCost and @NetBillableCost
								Select @ExistingPODAdjTotalCost = 0
								Select @ExistingPODAdjBillableCost = 0
								
								-- look to see if an existing auto adjustment line exists that has not been billed and adjust it
								-- otherwise create a new adjustment line
								select @ExistingPODAdjKey = min(PurchaseOrderDetailKey), 
									   @ExistingPODAdjTotalCost = ISNULL(SUM(TotalCost), 0),
								       @ExistingPODAdjBillableCost = ISNULL(SUM(BillableCost), 0),
									   @AdjustmentNumber = max(AdjustmentNumber)
								from tPurchaseOrderDetail (nolock)
								where PurchaseOrderKey = @PurchaseOrderKey
								and LineNumber = @LineNumber
								and InvoiceLineKey is null  -- only unbilled lines
								and AutoAdjustment = 1  -- it was originally added using this procedure, do not update manual lines
							
								-- calculate values to be inserted
								-- if Unit Cost did change, we need to generate a line with quantity of 1 or -1 for the net difference to avoid rounding issues
								begin
									-- if billed gross/net > current transaction total, client was overbilled
									if @NetBillableCost > @TotGross
										select @AdjTotalCost = ((@NetTotalCost - @ExistingPODAdjTotalCost) - @TotNet)  * -1
												,@AdjBillableCost = ((@NetBillableCost - @ExistingPODAdjBillableCost) - @TotGross) * -1
												,@AdjUnitCost = (@NetBillableCost - @ExistingPODAdjBillableCost) - @TotGross
									-- net/gross < sum of existing billed transactions, client was underbilled
									else
										select @AdjTotalCost = @TotNet - (@NetTotalCost - @ExistingPODAdjTotalCost)
												,@AdjBillableCost = @TotGross - (@NetBillableCost - @ExistingPODAdjBillableCost)
												,@AdjUnitCost = @TotGross - (@NetBillableCost - @ExistingPODAdjBillableCost) 								
								end
								
								if @ExistingPODAdjKey is not null  -- update the existing auto-adjustment line
									begin
										-- Delete this line if it adjusted to zero
										if (@ExistingPODAdjTotalCost - @AdjTotalCost) = 0 and (@ExistingPODAdjBillableCost - @AdjBillableCost ) = 0 
											or ( @AdjTotalCost = 0 and @AdjBillableCost = 0 )
											begin
												-- sptPurchaseOrderDetailDelete returns multiple values
												exec @RetVal = sptPurchaseOrderDetailDelete @ExistingPODAdjKey, null
												
												IF @RetVal < 0 
													BEGIN
														SELECT @RetVal =
															CASE @RetVal
																WHEN -1 THEN -11 -- You can not modify a purchase order line that has a vendor invoice applied
																WHEN -2 THEN -12 -- You can not modify a purchase order that has been closed
															END
		
														RETURN @RetVal
													END
											end
										else
											begin
												update tPurchaseOrderDetail
													set
													Quantity = 0,
													Markup = @Commission,
													UnitCost = @AdjUnitCost,
													TotalCost = @AdjTotalCost,
													PTotalCost = @AdjTotalCost,
													BillableCost = @AdjBillableCost,
													GrossAmount = @AdjBillableCost
												where PurchaseOrderDetailKey = @ExistingPODAdjKey

												set @ActionLogComment = ''Adjustment Line'' + CAST(@AdjustmentNumber AS VARCHAR(20)) + ''Updated by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
												exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Updated'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
												
												update tPurchaseOrder
												set DateUpdated = @CurrentDate,Closed = 0
												where PurchaseOrderKey = @PurchaseOrderKey 

												set @ActionLogComment = ''Opened by Strata Sync''
												exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Opened'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
											end
									end									
								else -- create a new single adjustment line
									begin

										select @NewAdjustmentNumber = isnull(max(AdjustmentNumber),0)
										from tPurchaseOrderDetail (nolock)
										where PurchaseOrderKey = @PurchaseOrderKey
										and LineNumber = @LineNumber	

										select @NewAdjustmentNumber = @NewAdjustmentNumber + 1					
										
										-- get new ObjectFieldSetKey
										select @CustomFieldKey = CustomFieldKey
										from tPurchaseOrderDetail (nolock)
										where PurchaseOrderDetailKey = @PODKey 
										
										IF ISNULL(@CustomFieldKey,0) > 0
											exec spCF_CopyFieldSet @CustomFieldKey, 1, @ObjectFieldSetKey output
											
										insert tPurchaseOrderDetail
											(
											PurchaseOrderKey,
											LineNumber,
											ProjectKey,
											TaskKey,
											ItemKey,
											ClassKey,
											ShortDescription,
											Quantity,
											UnitCost,
											UnitDescription,
											TotalCost,
											PTotalCost,
											UnitRate,
											Billable,
											Markup,
											BillableCost,
											GrossAmount,
											LongDescription,
											CustomFieldKey,
											DetailOrderDate,
											DetailOrderEndDate,
											UserDate1,
											UserDate2,
											UserDate3,
											UserDate4,
											UserDate5,
											UserDate6,
											OrderDays,
											OrderTime,
											OrderLength,
											Taxable,
											Taxable2,
											OfficeKey,
											DepartmentKey,
											AutoAdjustment,
											AdjustmentNumber,
											InteractiveAdUnitName
											)
										select
											PurchaseOrderKey,
											LineNumber,
											ProjectKey,
											TaskKey,
											ItemKey,
											ClassKey,
											ShortDescription,
											0, -- @AdjQuantity,
											@AdjUnitCost,
											UnitDescription,
											@AdjTotalCost,
											@AdjTotalCost,
											null,  -- @UnitRate,
											Billable,
											@Commission,
											@AdjBillableCost,
											@AdjBillableCost,
											LongDescription,
											@ObjectFieldSetKey,
											DetailOrderDate,
											DetailOrderEndDate,
											UserDate1,
											UserDate2,
											UserDate3,
											UserDate4,
											UserDate5,
											UserDate6,
											OrderDays,
											OrderTime,
											OrderLength,
											Taxable,
											Taxable2,
											OfficeKey,
											DepartmentKey,
											1, -- AutoAdjustment			
											@NewAdjustmentNumber,
											@InteractiveAdUnitName
										from tPurchaseOrderDetail (nolock)
										where PurchaseOrderDetailKey =  @PODKey
										
										set @ActionLogComment = ''Adjustment Line'' + CAST(@NewAdjustmentNumber AS VARCHAR(20)) + ''added by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
										exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Added'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  

										update tPurchaseOrder
										set DateUpdated = @CurrentDate,Closed = 0
										where PurchaseOrderKey = @PurchaseOrderKey 	
										
										set @ActionLogComment = ''Opened by Strata Sync''
										exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Opened'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
									end									
							end
							
						-- show adjustments as two lines
						else  
							begin
								-- calculate values to be inserted
								-- regardless of what changed, always reverse the original line and any adjustment line(s) and insert a new line for the new amounts

								-- create a reversal for the net of all existing lines
								if @NetQuantity <> 0
								begin									

									select @NewAdjustmentNumber = isnull(max(AdjustmentNumber),0)
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and LineNumber = @LineNumber	

									select @NewAdjustmentNumber = @NewAdjustmentNumber + 1
										
									--Get new ObjectFieldSetKey
									select @CustomFieldKey = CustomFieldKey
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey = @PODKey 
									
									IF ISNULL(@CustomFieldKey,0) > 0
										exec spCF_CopyFieldSet @CustomFieldKey, 1, @ObjectFieldSetKey output
										
									insert tPurchaseOrderDetail
										(
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										Quantity,
										UnitCost,
										UnitDescription,
										TotalCost,
										PTotalCost,
										UnitRate,
										Billable,
										Markup,
										BillableCost,
										GrossAmount,
										LongDescription,
										CustomFieldKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										AutoAdjustment,
										AdjustmentNumber
										)
									select
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										0, -- @NetQuantity * -1,
										case @NetQuantity
											when 0 then ROUND((@NetBillableCost), 4)
											else ROUND((@NetBillableCost * -1)/(@NetQuantity * -1),4)
										end,
										UnitDescription,
										@NetTotalCost * -1,
										@NetTotalCost * -1,
										null, --(@NetBillableCost * -1)/(@NetQuantity * -1), -- UnitRate
										Billable,
										case @NetBillableCost
											when 0 then 0
											else 100 - ROUND((@NetTotalCost * -1)/(@NetBillableCost * -1)*100, 4)
										end,
										@NetBillableCost * -1,
										@NetBillableCost * -1,
										LongDescription,
										@ObjectFieldSetKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										1,  -- AutoAdjustment
										@NewAdjustmentNumber								
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey =  @PODKey
									
									set @ActionLogComment = ''Adjustment Line'' + CAST(@NewAdjustmentNumber AS VARCHAR(20)) + ''added by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
									exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Added'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  

									update tPurchaseOrder
									set DateUpdated = @CurrentDate,Closed = 0
									where PurchaseOrderKey = @PurchaseOrderKey  

									set @ActionLogComment = ''Opened by Strata Sync''
									exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Opened'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
								end
								
								-- create a new adjustment line
								if @Quantity <> 0 and @TotNet <> 0
								begin		
																						
									select @NewAdjustmentNumber2 = isnull(max(AdjustmentNumber),0)
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and LineNumber = @LineNumber	

									select @NewAdjustmentNumber2 = @NewAdjustmentNumber2 + 1

									--Get new ObjectFieldSetKey
									select @CustomFieldKey = CustomFieldKey
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey = @PODKey 
									
									IF ISNULL(@CustomFieldKey,0) > 0
										exec spCF_CopyFieldSet @CustomFieldKey, 1, @ObjectFieldSetKey output
										
									insert tPurchaseOrderDetail
										(
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										Quantity,
										UnitCost,
										UnitDescription,
										TotalCost,
										PTotalCost,
										UnitRate,
										Billable,
										Markup,
										BillableCost,
										GrossAmount,
										LongDescription,
										CustomFieldKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										AutoAdjustment,
										AdjustmentNumber
										)
									select
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										@Quantity,
										case @Quantity
											when 0 then @TotGross
											else ROUND(@TotGross/@Quantity, 4)
										end,
										UnitDescription,
										@TotNet,
										@TotNet,
										null,  --@UnitRate,
										Billable,
										@Commission,
										@TotGross,
										@TotGross,
										LongDescription,
										@ObjectFieldSetKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										1, -- AutoAdjustment
										@NewAdjustmentNumber2											
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey =  @PODKey
									
									set @ActionLogComment = ''Adjustment Line'' + CAST(@NewAdjustmentNumber AS VARCHAR(20)) + ''added by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
									exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Added'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  

									update tPurchaseOrder
									set DateUpdated = @CurrentDate, Closed = 0
									where PurchaseOrderKey = @PurchaseOrderKey  

									set @ActionLogComment = ''Opened by Strata Sync''
									exec @RetVal = sptActionLogInsert ''Purchase Order'',@PurchaseOrderKey,@CompanyKey,@ProjectKey,''Opened'',@CurrentDate,''Strata Link'',@ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
								end -- Quantity > 0								
							end
					end
				else
					-- nothing has changed since prebilling, simply return
					return 1
			end
			
		-- this is an existing unbilled line or an existing prebilled line and system options allow updates to it
		else	
			begin	
				-- check if line & PO need to be reopened
				select @AppliedCost = AppliedCost
					,@TotalCost = TotalCost
					,@Closed = Closed
				from tPurchaseOrderDetail (nolock)
				where PurchaseOrderDetailKey = @PODKey
				     
				if @Closed = 1 and @TotNet <> @TotalCost and @TotNet <> @AppliedCost
					begin
						update tPurchaseOrderDetail 
						set Closed = 0, DateClosed = NULL 
						where PurchaseOrderDetailKey = @PODKey

						set @ActionLogComment = ''OrderLine Line'' + CAST(@LineNumber AS VARCHAR(20)) + ''Opened by Strata Sync''
						exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
					
						update tPurchaseOrder
						set Closed = 0,DateUpdated = @CurrentDate
						where PurchaseOrderKey = @PurchaseOrderKey		

						set @ActionLogComment = ''Opened by Strata Sync''
						exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
					end
							
				Update tPurchaseOrderDetail
					Set
					ProjectKey = @ProjectKey,
					TaskKey = @TaskKey,
					ItemKey = @ItemKey,
					ClassKey = @ClassKey,
					ShortDescription = @Program,
					LongDescription = @Comments,
					Quantity = @Quantity,
					Markup = @Commission,
					UnitCost = @UnitRate,
					TotalCost = @TotNet,
					PTotalCost = @TotNet,
					BillableCost = @TotGross,
					GrossAmount = @TotGross,
					DetailOrderDate = @StartDate,
					UserDate1 = @Date1,
					UserDate2 = @Date2,
					OfficeKey = @OfficeKey,
					DepartmentKey = @DepartmentKey
				Where
					PurchaseOrderDetailKey = @PODKey
					
				update tPurchaseOrder
				set DateUpdated = @CurrentDate
				where PurchaseOrderKey = @PurchaseOrderKey 

			end
END

exec sptPurchaseOrderDetailUpdateApprover @PurchaseOrderKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptStrataBCOrderDetail]'
GO
IF OBJECT_ID(N'[dbo].[sptStrataBCOrderDetail]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptStrataBCOrderDetail]
	(
		@PurchaseOrderKey int,
		@UserKey int,
		@LinkID varchar(50),
		@SpotLinkID varchar(50),
		@StartDate smalldatetime,
		@EndDate smalldatetime,
		@Quantity decimal(24,4),
		@Program varchar(max),
		@Comments varchar(1000),
		@OrderDays varchar(50),
		@OrderTime varchar(50),
		@OrderLength varchar(50),
		@Cost decimal(24,6),
		@StnCltWeight decimal(24,6),
		@CltWeight decimal(24,6),
		@StnWeight decimal(24,6),
		@CMP tinyint = 0	-- syncing from CMP?  WMJ = 0 / CMP = 1
	)

AS --Encrypt

/*
|| When     Who Rel     What
|| 11/16/06 CRG 8.3571  Modified to get the ClassKey from tPurchaseOrder.
|| 11/30/06 CRG 8.3571  Modified to update the ClassKey on an existing detail line.
|| 02/05/07 RTC 8.4.0.2 When creating two line adjustments, insure the second ine''s total cost <> 0
|| 04/17/07 BSH 8.4.5   DateUpdated needed to be updated.
|| 10/01/07 GHL 8.5     Added update of DateClosed
|| 10/01/07 BSH 8.5     Insert OfficeKey to PO Detail, get from Estimate or Project based on ClientLink. 
|| 05/27/09 RTC 8.5.3.7 (53517) Corrected single adjustment line calculations
|| 10/07/09 MAS 10.5.1.9() Calculate Client Costing
|| 10/07/09 MAS 10.5.1.9 (67320) Removed rounding when calculating Client Costing UnitRate/UnitCost also set Commision/Markup = 0 when UnitRate = 0
|| 11/11/09 MAS 10.5.1.3 (47035)
|| 11/11/10 MAS 10.5.3.8 Reset the PO Header closed flag to 0 when a new line is added.
||                       Changed the way we determine if a revision line should be created.  We were using an AVG(UnitCost), we now use TotalCost
|| 01/20/11 MAS 10.5.4   (100689, 100759) Changed the way were are calculating revision lines.  We Look at quantity, TotalCost and BillableCost
||						 if any of them change, we generate a revision line.  The revision lines can have any combination of Qty, TotalCost and 
||                       Billiable cost, so long as the total match that of Strata.  We do not try and keep UnitCost insync with Strata!	
|| 08/16/11 MAS 10.5.4.7 (118934) Was using the @TotGross by error when calculating revision Net amounts.  Should have been using @TotNet
|| 08/23/12 MAS 10.5.5.9 (152132)Changed the precision of all the client costing params
|| 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @Program(ShortDescription) from 200 to 300
|| 05/07/13 WDF 10.5.6.8 ( 175953) For existing line updates, deleted revision(s) if no changes detected.
|| 12/17/13 GHL 10.5.7.4  Added PCurrency and PExchangeRate parms when calling sptPurchaseOrderDetailInsert
|| 01/27/14 GHL 10.5.7.6 Added update of PTotalCost in inserts/updates of tPurchaseOrderDetail
|| 04/29/14 RLB 10.5.7.9 (214240)Changed the length of @Program(ShortDescription) from 300 to max
|| 08/14/14 PLC 10.5.8.3 (226102)Changed the logic to not delete details on vouchers and include those dollars as well.
|| 07/09/15 PLC 10.5.9.3 (260717)Changed client costing logic to better handle non standard percentages.
|| 04/26/16 PLC 10.5.9.3 (260717)Removed logic to delte revisions if nothing changed.  Now looking for changes with revision lines
|| 04/26/16 MAS 10.6.1.9 (360677)Changed  @UnitCost & @UnitRate from money type to decimal(24,4)
|| 02/02/17 MAS 10.2.0   (382984) Update the ShortDescription and LongDescription fields if they change (382984)
|| 09/24/18 GHL 18.9.1   (419955) Added last check of POD.Closed to prevent situation where PO.Closed = 1 and exists POD.Closed = 0
|| 05/06/19 GHL 19.0.5.0 (456404) Added update of GrossAmount, because the triggers do not seem to update them
|| 11/19/19 MAS 19.1.2.0 (487649) Updated the way we do rounding.  Round rates/commisones to 4 spaces, and costs to 2. Apply rounding after all calculations
|| 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
|| 01/25/24 MAS 24.2.18 (660506) Added sptActionLog when updating PurchaseOrder or PurchaseOrderDetail Closed flags
|| 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName
*/

Declare @PODKey int
Declare @ProjectKey int, @TaskKey int, @ItemKey int, @RetVal int, @NewKey int, @TotNet money, @TotGross money, @Markup decimal(24,4)
declare @LineNumber int 
declare @UserDate1 smalldatetime
declare @UserDate2 smalldatetime
declare @UserDate3 smalldatetime
declare @UserDate4 smalldatetime
declare @UserDate5 smalldatetime
declare @UserDate6 smalldatetime
declare @Date1Days int
declare @Date2Days int
declare @Date3Days int
declare @Date4Days int
declare @Date5Days int
declare @Date6Days int
declare @CompanyKey int
declare @CompanyMediaKey int 
declare @CurrAppliedCost money
declare @CurrTotalCost money 
declare @Closed tinyint
declare @FullLinkID varchar(50)
declare @LinkIDVersion tinyint
declare @LinkIDLen int
declare @AllowChangesAfterClientInvoice tinyint
declare @GeneratePrebilledRevisions tinyint
declare @ShowAdjustmentsAsSingleLine tinyint
declare @Prebilled as tinyint
declare @NetQuantity decimal(24,4)
declare @NetUnitCost money
declare @NetTotalCost money
declare @NetBillableCost money
declare @SomethingChanged tinyint
declare @AdjQuantity decimal(24,4)
declare @AdjUnitCost money, @AdjTotalCost money, @AdjBillableCost money
declare @ExistingPODAdjKey int
declare @NewAdjustmentNumber int
declare @NewAdjustmentNumber2 int
declare @CustomFieldKey int
declare @ObjectFieldSetKey int
declare	@ClassKey int, @OfficeKey int
declare @BCClientLink int
declare @MediaEstimateKey int
declare @DepartmentKey int
declare @RequireDepartment tinyint, @UseClientCosting tinyint, @POClientCosting tinyint 
declare @UnitCost decimal(24,4), @UnitRate decimal(24,4)
declare	@Commission decimal(24,4)
declare @CurrentDate smalldatetime
declare @ActionLogComment varchar(1000)
declare @AdjustmentNumber int

	select @ProjectKey = ProjectKey
		  ,@TaskKey = TaskKey
		  ,@ItemKey = ItemKey
		  ,@CompanyMediaKey = CompanyMediaKey
		  ,@CompanyKey = CompanyKey
		  ,@ClassKey = ClassKey
		  ,@MediaEstimateKey = MediaEstimateKey
		  ,@POClientCosting = UseClientCosting -- do not allow the users to switch between using and not using client costings
	  from tPurchaseOrder (nolock)
	 where PurchaseOrderKey = @PurchaseOrderKey

	Select @CurrentDate = CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime) 

	-- determine if order lines (spots) can be updated after client invoice has been created
	-- determine if revision lines should be auto generated for prebilled lines
	-- determine if one or two revision lines should be created
	select @AllowChangesAfterClientInvoice = isnull(BCAllowChangesAfterClientInvoice, 0)
	      ,@GeneratePrebilledRevisions = isnull(BCGeneratePrebilledRevisions, 0)
	      ,@ShowAdjustmentsAsSingleLine = isnull(BCShowAdjustmentsAsSingleLine, 1)
	      ,@BCClientLink = isnull(BCClientLink,1)
          ,@RequireDepartment = RequireDepartment
          ,@UseClientCosting = BCUseClientCosting
      from tPreference (nolock)
     where CompanyKey = @CompanyKey
	
	-- If PO ClientCosting is NULL use the system setting
	if @POClientCosting is null
		Begin
			Select @POClientCosting = @UseClientCosting
			
			Update tPurchaseOrder 
			Set UseClientCosting = @POClientCosting
			Where PurchaseOrderKey = @PurchaseOrderKey
		End
		
	if @POClientCosting = 1
		begin
			Select @UnitRate = @Cost * @CltWeight * @StnCltWeight
			Select @UnitCost = @Cost * @StnWeight
			if @UnitRate = 0
				Select @Commission = 0
			else
				Select @Commission = ROUND((1 - @UnitCost / @UnitRate) * 100, 4)
		end
	else
		begin
			Select @UnitRate = @Cost
			Select @UnitCost = @Cost * @StnWeight
			Select @Commission = (1 - @StnWeight) * 100
		end
	    
     if @BCClientLink = 1
		select @OfficeKey = OfficeKey
		from tProject (nolock)
		where ProjectKey = @ProjectKey
	else
		select @OfficeKey = OfficeKey
		from tMediaEstimate (nolock)
		where MediaEstimateKey = @MediaEstimateKey
	
	select @DepartmentKey = DepartmentKey
	from tItem (nolock)
	where ItemKey = @ItemKey
	
	if @RequireDepartment = 1 -- department is required
		if @DepartmentKey is null
			return -3	
          	 
	-- handle old and new variations of the link id, always convert old version to new version
	select @FullLinkID = LinkID
	  from tPurchaseOrderDetail (nolock)
	 where PurchaseOrderKey = @PurchaseOrderKey
	   and LinkID = @LinkID
	 and DetailOrderDate = @StartDate 
	   and DetailOrderEndDate = @EndDate
	   
	-- did we find the line without the spot id as part of the link id (old version)?
	if @FullLinkID is not null
		begin
			-- found it with simple version, update with detailed link id version
			select @FullLinkID = @LinkID + ''-'' + @SpotLinkID	
			select @LinkIDVersion = 1
		end
	else
		begin
			-- could not find it with simple link id, try with detailed version
			select @FullLinkID = LinkID
			  from tPurchaseOrderDetail (nolock)
			 where PurchaseOrderKey = @PurchaseOrderKey 
			   and LinkID = @LinkID + ''-'' + @SpotLinkID
			   and DetailOrderDate = @StartDate 
			   and DetailOrderEndDate = @EndDate
				 	
			if @FullLinkID is not null
				-- found it with detailed version
				select @LinkIDVersion = 2
			else
				-- it must be a new line
				select @FullLinkID = @LinkID + ''-'' + @SpotLinkID
		end		
			
	if @LinkIDVersion is not null  -- not a new line
		begin
			if @LinkIDVersion = 1
				begin
					select @LineNumber = min(isnull(LineNumber,1))
					  from tPurchaseOrderDetail (nolock)
					 where PurchaseOrderKey = @PurchaseOrderKey
					   and LinkID = @LinkID
					  
					select @PODKey = min(PurchaseOrderDetailKey)
					  from tPurchaseOrderDetail (nolock) 
					 where PurchaseOrderKey = @PurchaseOrderKey 
					   and LinkID = @LinkID
					   and DetailOrderDate = @StartDate 
					   and DetailOrderEndDate = @EndDate	
				end			   
			else
				begin
					select @LineNumber = min(isnull(LineNumber,1))
					  from tPurchaseOrderDetail (nolock)
					 where PurchaseOrderKey = @PurchaseOrderKey
					   and LinkID = @LinkID + ''-'' + @SpotLinkID
				   	
					select @PODKey = min(PurchaseOrderDetailKey)
					  from tPurchaseOrderDetail (nolock) 
					 where PurchaseOrderKey = @PurchaseOrderKey 
					   and LinkID = @LinkID + ''-'' + @SpotLinkID
					   and DetailOrderDate = @StartDate 
					   and DetailOrderEndDate = @EndDate	
				end			   	

		end
	else
		begin
			-- if this spot is new and has a zero quantity, no need to add it and burn keys
			if ISNULL(@Quantity, 0) = 0
				return 1
			else
				-- must be a new spot, check if it is the first spot on the line or a new line
				select @LineNumber = isnull((select min(LineNumber)
											    from tPurchaseOrderDetail (nolock)
											   where PurchaseOrderKey = @PurchaseOrderKey 
												 and left(LinkID,len(@LinkID)) = @LinkID)
											,(select isnull(max(LineNumber),0)
												from tPurchaseOrderDetail (nolock)
											   where PurchaseOrderKey = @PurchaseOrderKey)+1) 
		end
	select @TotNet = ROUND(ISNULL(@UnitCost, 0) * ISNULL(@Quantity, 0), 2)
	      ,@TotGross = ROUND(ISNULL(@UnitRate, 0) * ISNULL(@Quantity, 0), 2)
	
	
	-- calc media dates if used
	select @Date1Days = isnull(Date1Days,0)
	  from tStringCompany sc (nolock) inner join tCompanyMedia cm (nolock) on sc.CompanyKey = cm.CompanyKey
	 where sc.CompanyKey = @CompanyKey
	   and sc.StringID = ''MediaBroadcast1''
	   and sc.StringSingular is not null
	   and cm.CompanyMediaKey = @CompanyMediaKey
	   
	select @Date2Days = isnull(Date2Days,0)
	  from tStringCompany sc (nolock) inner join tCompanyMedia cm (nolock) on sc.CompanyKey = cm.CompanyKey
	 where sc.CompanyKey = @CompanyKey
	   and sc.StringID = ''MediaBroadcast2''
	   and sc.StringSingular is not null
	   and cm.CompanyMediaKey = @CompanyMediaKey
	   
	select @Date3Days = isnull(Date3Days,0)
	  from tStringCompany sc (nolock) inner join tCompanyMedia cm (nolock) on sc.CompanyKey = cm.CompanyKey
	 where sc.CompanyKey = @CompanyKey
	   and sc.StringID = ''MediaBroadcast3''
	   and sc.StringSingular is not null
	   and cm.CompanyMediaKey = @CompanyMediaKey
	   
	select @Date4Days = isnull(Date4Days,0)
	  from tStringCompany sc (nolock) inner join tCompanyMedia cm (nolock) on sc.CompanyKey = cm.CompanyKey
	 where sc.CompanyKey = @CompanyKey
	   and sc.StringID = ''MediaBroadcast4''
	   and sc.StringSingular is not null
	   and cm.CompanyMediaKey = @CompanyMediaKey
	   
	select @Date5Days = isnull(Date5Days,0)
	  from tStringCompany sc (nolock) inner join tCompanyMedia cm (nolock) on sc.CompanyKey = cm.CompanyKey
	 where sc.CompanyKey = @CompanyKey
	   and sc.StringID = ''MediaBroadcast5''
	   and sc.StringSingular is not null
	   and cm.CompanyMediaKey = @CompanyMediaKey
	   
	select @Date6Days = isnull(Date6Days,0)
	  from tStringCompany sc (nolock) inner join tCompanyMedia cm (nolock) on sc.CompanyKey = cm.CompanyKey
	 where sc.CompanyKey = @CompanyKey
	   and sc.StringID = ''MediaBroadcast6''
	   and sc.StringSingular is not null
	   and cm.CompanyMediaKey = @CompanyMediaKey
	 
	if @Date1Days > 0
		select @UserDate1 = dateadd(d,@Date1Days*-1,@StartDate)
	   
	if @Date2Days > 0
		select @UserDate2 = dateadd(d,@Date2Days*-1,@StartDate)
	   
	if @Date3Days > 0
		select @UserDate3 = dateadd(d,@Date3Days*-1,@StartDate)
	   
	if @Date4Days > 0
		select @UserDate4 = dateadd(d,@Date4Days*-1,@StartDate)
	   
	if @Date5Days > 0
		select @UserDate5 = dateadd(d,@Date5Days*-1,@StartDate)
	   
	if @Date6Days > 0
		select @UserDate6 = dateadd(d,@Date6Days*-1,@StartDate)
	   
	if @PODKey is null
	BEGIN		
		-- If using Projects/Tasks - Check to see if the associated Task is completed
		if ISNULL(@CMP,0) = 0 and ISNULL(@TaskKey,0) > 0
			BEGIN
				exec @RetVal = spTaskValidatePercComp ''tPurchaseOrderDetail'',@PODKey, NULL, @ProjectKey, NULL, @TaskKey, @UserKey
				if @RetVal < -1 
					return -4 
			END
		
		EXEC @RetVal = sptPurchaseOrderDetailInsert 
			@PurchaseOrderKey = @PurchaseOrderKey,
			@LineNumber = @LineNumber,
			@ProjectKey = @ProjectKey,
			@TaskKey = @TaskKey,
			@ItemKey = @ItemKey,
			@ClassKey = @ClassKey,
			@ShortDescription = @Program,
			@Quantity = @Quantity,
			@UnitCost = @UnitRate,
			@UnitDescription = NULL,
			@TotalCost = @TotNet,
			@UnitRate = NULL,
			@Billable = 1,
			@Markup = @Commission,
			@BillableCost = @TotGross,
			@LongDescription = @Comments,
			@CustomFieldKey = 0,
			@DetailOrderDate = @StartDate,
			@DetailOrderEndDate = @EndDate,
			@UserDate1 = @UserDate1,
			@UserDate2 = @UserDate2,
			@UserDate3 = @UserDate3,
			@UserDate4 = @UserDate4,
			@UserDate5 = @UserDate5,
			@UserDate6 = @UserDate6,
			@OrderDays = @OrderDays,
			@OrderTime = @OrderTime,
			@OrderLength = @OrderLength,
			@Taxable = 0,
			@Taxable2 = 0,
			@OfficeKey = @OfficeKey,
			@DepartmentKey = @DepartmentKey,
			@GrossAmount = @TotGross,
			@PCurrencyID = NULL,
			@PExchangeRate = 1,
			@PTotalCost = @TotNet,
			@SkipRollUps = NULL,
			@InteractiveAdUnitName = NULL,
			@oIdentity = @NewKey OUTPUT
			
		Update tPurchaseOrderDetail Set LinkID = @FullLinkID Where PurchaseOrderDetailKey = @NewKey

	END
	ELSE
	BEGIN
		-- handle existing line updates

		-- If using Projects/Tasks - Check to see if the associated Task is completed
		if ISNULL(@CMP,0) = 0 and ISNULL(@TaskKey,0) > 0
			BEGIN
				exec @RetVal = spTaskValidatePercComp ''tPurchaseOrderDetail'',@PODKey, NULL, @ProjectKey, NULL, @TaskKey, @UserKey
				if @RetVal < -1 
					return -4 
			END
					
		-- make sure this line is not on a billing worksheet
		if exists(select 1 
		            from tBillingDetail bd (nolock) inner join tBilling b (nolock) on bd.BillingKey = b.BillingKey
		           where bd.EntityKey = @PODKey 
		            and bd.Entity = ''tPurchaseOrderDetail''
		             and b.Status < 5)
			return -2 
			
		-- if this is an existing line/spot and it has been invoiced, do not allow changes if the system options do not allow
		select @Prebilled = 0
		if exists(select 1 from tPurchaseOrderDetail (nolock) Where PurchaseOrderDetailKey = @PODKey and InvoiceLineKey is not null)		
			begin
				select @Prebilled = 1
				if @GeneratePrebilledRevisions = 0 and @AllowChangesAfterClientInvoice = 0
						-- the line was prebilled and system options do not allow any kind of updating
						return -1
			end
	
		-- we can safely update the ShortDescription and LongDescription fields if they change (382984)
		Declare @ShortDescription varchar(max)
		Declare @LongDescription varchar(1000)

		Select @ShortDescription = ISNULL(ShortDescription, ''''), @LongDescription = ISNULL(LongDescription, '''')
		From tPurchaseOrderDetail (nolock)
		Where PurchaseOrderDetailKey = @PODKey

		If @ShortDescription <> ISNULL(@Program, '''') OR @LongDescription <> ISNULL(@Comments, '''')
			BEGIN
				Update tPurchaseOrderDetail 
				Set ShortDescription = @Program, LongDescription = @Comments
				Where PurchaseOrderKey = @PurchaseOrderKey
				and LineNumber = @LineNumber
				and DetailOrderDate = @StartDate 
				and DetailOrderEndDate = @EndDate
				and ISNULL(AutoAdjustment, 0) <> 1 -- Don''t update manaully adjust lines
			END
		 
		-- is this a prebilled line that may require auto-revision line(s) to be created
		if @Prebilled = 1 and @GeneratePrebilledRevisions = 1
			begin
				-- get current values from original line and any automatic or manual revision lines associated to it for a period within the flight
				if @ShowAdjustmentsAsSingleLine = 1
					select @NetQuantity = sum(Quantity)
							,@NetTotalCost = sum(TotalCost)
							,@NetBillableCost = sum (BillableCost)
					from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and LineNumber = @LineNumber
					and DetailOrderDate = @StartDate 
					and DetailOrderEndDate = @EndDate	
					and ((isnull(AutoAdjustment,0) = 0)  -- include billed and unbilled manual adjustment lines
						or (isnull(AutoAdjustment,0) = 1 and InvoiceLineKey is not null)
						or exists (select 1 from tVoucherDetail vd (nolock) -- include records on vendor invoices
						where vd.PurchaseOrderDetailKey = tPurchaseOrderDetail.PurchaseOrderDetailKey) )  -- only include billed auto-adjustment lines since we will reuse the existing unbilled auto adjustment line for the update below
				else -- two line adjustments
					-- include billed and unbilled manual adjustment lines
					-- include billed and unbilled auto-adjustment lines
					select @NetQuantity = sum(Quantity)
							,@NetTotalCost = sum(TotalCost)
							,@NetBillableCost = sum (BillableCost)
					from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and LineNumber = @LineNumber
					and DetailOrderDate = @StartDate 
					and DetailOrderEndDate = @EndDate	
				
				-- verify something has changed, requiring a revision
				select @SomethingChanged = 0
				
				if @NetQuantity <> @Quantity or @NetTotalCost <> @TotNet or @NetBillableCost <>  @TotGross
					select @SomethingChanged = 1

				if @SomethingChanged = 1
					begin
						-- determine if we need to create one or two adjustment lines
						if @ShowAdjustmentsAsSingleLine = 1
							begin
								-- calculate values to be inserted
								-- Reconcile Quantity, TotalCoast and BillableCost.  DO NOT worry about the UnitCost
								-- this could result in POD records with just quanitity changes, just TotalCost and TotalBillable changes or both
								-- if billed gross/net > current transaction total, client was overbilled
								if @NetBillableCost > @TotGross
									select @AdjQuantity = @Quantity - @NetQuantity
									       -- ,@AdjTotalCost = ((@NetTotalCost - @TotNet) * (1 - (@Commission/100)))  * -1
									        ,@AdjTotalCost = (@NetTotalCost - @TotNet) * -1
											,@AdjBillableCost = (@NetBillableCost - @TotGross) * -1
											,@AdjUnitCost = ABS((@NetBillableCost - @TotGross) / IsNull(Nullif(@AdjQuantity, 0), 1)) --this is really the unit rate used in the UI
								-- net/gross < sum of existing billed transactions, client was underbilled
								else
									select @AdjQuantity = @Quantity - @NetQuantity
										    -- ,@AdjTotalCost = (@TotNet - @NetTotalCost) * (1 - (@Commission/100))
										    ,@AdjTotalCost = (@TotNet - @NetTotalCost)
											,@AdjBillableCost = @TotGross - @NetBillableCost 
											,@AdjUnitCost = ABS((@TotGross - @NetBillableCost) / IsNull(Nullif(@AdjQuantity, 0), 1)) --this is really the unit rate used in the UI									
								-- look to see if an existing auto adjustment line exists that has not been billed and adjust it
								-- otherwise create a new adjustment line
								select @ExistingPODAdjKey = min(PurchaseOrderDetailKey)
								from tPurchaseOrderDetail (nolock)
								where PurchaseOrderKey = @PurchaseOrderKey
								and LineNumber = @LineNumber
								and DetailOrderDate = @StartDate 
								and DetailOrderEndDate = @EndDate	
								and InvoiceLineKey is null  -- only unbilled lines
								and AutoAdjustment = 1  -- it was originally added using this procedure, do not update manual lines
														
								if @ExistingPODAdjKey is not null  -- update the existing auto-adjustment line
									begin
										update tPurchaseOrderDetail
											set
											Quantity = @AdjQuantity,
											Markup = @Commission,
											UnitCost = @AdjUnitCost,
											TotalCost = @AdjTotalCost,
											PTotalCost = @AdjTotalCost,
											BillableCost = @AdjBillableCost,
											GrossAmount = @AdjBillableCost
										where PurchaseOrderDetailKey = @ExistingPODAdjKey									
						
						                update tPurchaseOrder
										set DateUpdated = @CurrentDate
										where PurchaseOrderKey = @PurchaseOrderKey
									end
								else -- create a new single adjustment line
									begin
									-- first check to see if an existing Adjustment Number can be used
									select @NewAdjustmentNumber  = min(isnull(AdjustmentNumber,0))
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and LineNumber = @LineNumber
									and AutoAdjustment = 1  -- it was originally added using this procedure, do not update manual lines
									and UnitCost = @AdjUnitCost  --cannot be mixed since UI treats multiple lines as group for this field
									and AdjustmentNumber not in (select AdjustmentNumber
																		from tPurchaseOrderDetail (nolock)
																		where PurchaseOrderKey = @PurchaseOrderKey
																		and LineNumber = @LineNumber
																		and AutoAdjustment = 1							
																		and DetailOrderDate = @StartDate 
																		and DetailOrderEndDate = @EndDate	
																		)
									if isnull(@NewAdjustmentNumber,0) = 0
										begin
											select @NewAdjustmentNumber = isnull(max(AdjustmentNumber),0)
											from tPurchaseOrderDetail (nolock)
											where PurchaseOrderKey = @PurchaseOrderKey
											and LineNumber = @LineNumber	

											select @NewAdjustmentNumber = @NewAdjustmentNumber + 1
										end									
										
										-- get new ObjectFieldSetKey
										select @CustomFieldKey = CustomFieldKey
										from tPurchaseOrderDetail (nolock)
										where PurchaseOrderDetailKey = @PODKey 
										
										IF ISNULL(@CustomFieldKey,0) > 0
											exec spCF_CopyFieldSet @CustomFieldKey, 1, @ObjectFieldSetKey output
											
										insert tPurchaseOrderDetail
											(
											PurchaseOrderKey,
											LineNumber,
											ProjectKey,
											TaskKey,
											ItemKey,
											ClassKey,
											ShortDescription,
											Quantity,
											UnitCost,
											UnitDescription,
											TotalCost,
											PTotalCost,
											UnitRate,
											Billable,
											Markup,
											BillableCost,
											GrossAmount,
											LongDescription,
											CustomFieldKey,
											DetailOrderDate,
											DetailOrderEndDate,
											UserDate1,
											UserDate2,
											UserDate3,
											UserDate4,
											UserDate5,
											UserDate6,
											OrderDays,
											OrderTime,
											OrderLength,
											Taxable,
											Taxable2,
											OfficeKey,
											DepartmentKey,
											AutoAdjustment,
											AdjustmentNumber
											)
										select
											PurchaseOrderKey,
											LineNumber,
											ProjectKey,
											TaskKey,
											ItemKey,
											ClassKey,
											ShortDescription,
											@AdjQuantity,
											@AdjUnitCost,
											UnitDescription,
											@AdjTotalCost,
											@AdjTotalCost,
											null,  -- @UnitRate,
											Billable,
											@Commission,
											@AdjBillableCost,
											@AdjBillableCost,
											LongDescription,
											@ObjectFieldSetKey,
											DetailOrderDate,
											DetailOrderEndDate,
											UserDate1,
											UserDate2,
											UserDate3,
											UserDate4,
											UserDate5,
											UserDate6,
											OrderDays,
											OrderTime,
											OrderLength,
											Taxable,
											Taxable2,
											OfficeKey,
											DepartmentKey,
											1, -- AutoAdjustment			
											@NewAdjustmentNumber								
										from tPurchaseOrderDetail (nolock)
										where PurchaseOrderDetailKey =  @PODKey
										
										set @ActionLogComment = ''Adjustment Line'' + CAST(@NewAdjustmentNumber AS VARCHAR(20)) + ''Added by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
										exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Added'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  

                                        update tPurchaseOrder
										set DateUpdated = @CurrentDate, Closed = 0 
										where PurchaseOrderKey = @PurchaseOrderKey 

										set @ActionLogComment = ''Opened by Strata Sync''
										exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
									end									
							end
							
						-- show adjustments as two lines
						else  
							begin
								-- calculate values to be inserted
								-- regardless of what changed, always reverse the original line and any adjustment line(s) and insert a new line for the new amounts

								-- create a reversal for the net of all existing lines
								if @NetQuantity <> 0
								begin									
									-- first check to see if an existing Adjustment Number can be used
									select @NewAdjustmentNumber  = min(isnull(AdjustmentNumber,0))
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and LineNumber = @LineNumber
									and AutoAdjustment = 1  -- it was originally added using this procedure, do not update manual lines
									and AdjustmentNumber not in (select AdjustmentNumber
																						from tPurchaseOrderDetail (nolock)
																						where PurchaseOrderKey = @PurchaseOrderKey
																						and LineNumber = @LineNumber
																						and AutoAdjustment = 1							
																						and DetailOrderDate = @StartDate 
																						and DetailOrderEndDate = @EndDate	
																						)
									if isnull(@NewAdjustmentNumber,0) = 0
										begin
											select @NewAdjustmentNumber = isnull(max(AdjustmentNumber),0)
											from tPurchaseOrderDetail (nolock)
											where PurchaseOrderKey = @PurchaseOrderKey
											and LineNumber = @LineNumber	

											select @NewAdjustmentNumber = @NewAdjustmentNumber + 1
										end
										
									--Get new ObjectFieldSetKey
									select @CustomFieldKey = CustomFieldKey
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey = @PODKey 
									
									IF ISNULL(@CustomFieldKey,0) > 0
										exec spCF_CopyFieldSet @CustomFieldKey, 1, @ObjectFieldSetKey output
										
									insert tPurchaseOrderDetail
										(
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										Quantity,
										UnitCost,
										UnitDescription,
										TotalCost,
										PTotalCost,
										UnitRate,
										Billable,
										Markup,
										BillableCost,
										GrossAmount,
										LongDescription,
										CustomFieldKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										AutoAdjustment,
										AdjustmentNumber
										)
									select
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										@NetQuantity * -1,
										case @NetQuantity
											when 0 then ROUND((@NetBillableCost),4)
											else ROUND((@NetBillableCost * -1)/(@NetQuantity * -1), 4)
										end,
										UnitDescription,
										@NetTotalCost * -1,
										@NetTotalCost * -1,
										null, --(@NetBillableCost * -1)/(@NetQuantity * -1), -- UnitRate
										Billable,
										case @NetBillableCost
											when 0 then 0
											else 100 - ROUND((@NetTotalCost * -1)/(@NetBillableCost * -1)*100, 4)
										end,
										@NetBillableCost * -1,
										@NetBillableCost * -1,
										LongDescription,
										@ObjectFieldSetKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										1,  -- AutoAdjustment
										@NewAdjustmentNumber								
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey =  @PODKey

									set @ActionLogComment = ''Adjustment Line'' + CAST(@NewAdjustmentNumber AS VARCHAR(20)) + ''Added by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
									exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Added'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
									
                                    update tPurchaseOrder
									set DateUpdated = @CurrentDate,Closed = 0 
									where PurchaseOrderKey = @PurchaseOrderKey 

									set @ActionLogComment = ''Opened by Strata Sync''
									exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  

								end
								
								-- create a new adjustment line
								if @Quantity <> 0  and @TotNet <> 0
								begin																
									-- first check to see if an existing Adjustment Number can be used
									select @NewAdjustmentNumber2 = min(isnull(AdjustmentNumber,0))
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderKey = @PurchaseOrderKey
									and LineNumber = @LineNumber
									and AutoAdjustment = 1  -- it was originally added using this procedure, do not update manual lines
									and AdjustmentNumber <> @NewAdjustmentNumber  -- first adjustment line - full backout
									--and UnitCost = @AdjUnitCost  --cannot be mixed since UI treats multiple lines as group for this field
									and AdjustmentNumber not in (select AdjustmentNumber
																		from tPurchaseOrderDetail (nolock)
																		where PurchaseOrderKey = @PurchaseOrderKey
																		and LineNumber = @LineNumber
																		and AutoAdjustment = 1							
																		and DetailOrderDate = @StartDate 
																		and DetailOrderEndDate = @EndDate
																		and AdjustmentNumber <> @NewAdjustmentNumber  -- first adjustment line - full backout
																		)
									if isnull(@NewAdjustmentNumber2,0) = 0
										begin
											select @NewAdjustmentNumber2 = isnull(max(AdjustmentNumber),0)
											from tPurchaseOrderDetail (nolock)
											where PurchaseOrderKey = @PurchaseOrderKey
											and LineNumber = @LineNumber	

											select @NewAdjustmentNumber2 = @NewAdjustmentNumber2 + 1
										end

									--Get new ObjectFieldSetKey
									select @CustomFieldKey = CustomFieldKey
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey = @PODKey 
									
									IF ISNULL(@CustomFieldKey,0) > 0
										exec spCF_CopyFieldSet @CustomFieldKey, 1, @ObjectFieldSetKey output
										
									insert tPurchaseOrderDetail
										(
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										Quantity,
										UnitCost,
										UnitDescription,
										TotalCost,
										PTotalCost,
										UnitRate,
										Billable,
										Markup,
										BillableCost,
										GrossAmount,
										LongDescription,
										CustomFieldKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										AutoAdjustment,
										AdjustmentNumber
										)
									select
										PurchaseOrderKey,
										LineNumber,
										ProjectKey,
										TaskKey,
										ItemKey,
										ClassKey,
										ShortDescription,
										@Quantity,
										case @Quantity
											when 0 then @TotGross
											else ROUND(@TotGross/@Quantity, 4)
										end,
										UnitDescription,
										@TotNet,
										@TotNet,
										null,  --@UnitRate,
										Billable,
										@Commission,
										@TotGross,
										@TotGross,
										LongDescription,
										@ObjectFieldSetKey,
										DetailOrderDate,
										DetailOrderEndDate,
										UserDate1,
										UserDate2,
										UserDate3,
										UserDate4,
										UserDate5,
										UserDate6,
										OrderDays,
										OrderTime,
										OrderLength,
										Taxable,
										Taxable2,
										OfficeKey,
										DepartmentKey,
										1, -- AutoAdjustment
										@NewAdjustmentNumber											
									from tPurchaseOrderDetail (nolock)
									where PurchaseOrderDetailKey =  @PODKey

									set @ActionLogComment = ''Adjustment Line'' + CAST(@NewAdjustmentNumber AS VARCHAR(20)) + ''Added by Strata Sync for Line '' + CAST(@LineNumber AS VARCHAR(20))
									exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Added'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
									
                                    update tPurchaseOrder
									set DateUpdated = @CurrentDate, Closed = 0 
									where PurchaseOrderKey = @PurchaseOrderKey 

									set @ActionLogComment = ''Opened by Strata Sync''
									exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
								end -- Quantity > 0								
							end
					end
				--else  -- Removed logic because the compare logic includes these lines.
				--   begin
				--		-- nothing has changed since prebilling...remove any revision and return
				--		delete from tPurchaseOrderDetail
				--		 where PurchaseOrderKey = @PurchaseOrderKey
				--		   and LineNumber = @LineNumber
				--		   and DetailOrderDate = @StartDate 
				--		   and DetailOrderEndDate = @EndDate	
				--		   and isnull(AutoAdjustment,0) = 1 
				--		   and InvoiceLineKey is null
				--		   and not exists (select 1 from tVoucherDetail vd (nolock) -- include records on vendor invoices
				--		where vd.PurchaseOrderDetailKey = tPurchaseOrderDetail.PurchaseOrderDetailKey)  


				--		return 1
				--	end
			end
			
		-- this is an existing unbilled line or an existing prebilled line and system options allow updates to it
		else	
			begin			
				-- get current values
				select @CurrAppliedCost = AppliedCost
					  ,@CurrTotalCost = TotalCost
					  ,@Closed = Closed
				from tPurchaseOrderDetail (nolock)
				where PurchaseOrderDetailKey = @PODKey
		 			
				if @Closed = 1 
				and @TotNet <> @CurrTotalCost 
				and @TotNet <> @CurrAppliedCost
					begin
						update tPurchaseOrderDetail 
						set Closed = 0, DateClosed = NULL 
						where PurchaseOrderDetailKey = @PODKey

						set @ActionLogComment = ''OrderLine Line'' + CAST(@LineNumber AS VARCHAR(20)) + ''Opened by Strata Sync''
						exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Added'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  

						update tPurchaseOrder
						set Closed = 0, DateUpdated = @CurrentDate
						where PurchaseOrderKey = @PurchaseOrderKey

						set @ActionLogComment = ''Opened by Strata Sync''
						exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
					end
						     
				Update tPurchaseOrderDetail
					Set
					ProjectKey = @ProjectKey,
					TaskKey = @TaskKey,
					ItemKey = @ItemKey,
					ShortDescription = @Program,
					LongDescription = @Comments,
					Quantity = @Quantity,
					Markup = @Commission,
					UnitCost = @UnitRate,
					TotalCost = @TotNet,
					PTotalCost = @TotNet,
					BillableCost = @TotGross,
					GrossAmount = @TotGross,
					OrderDays = @OrderDays,
					OrderTime = @OrderTime,
					OrderLength = @OrderLength,
					DetailOrderDate = @StartDate,
					DetailOrderEndDate = @EndDate,
					UserDate1 = @UserDate1,
					UserDate2 = @UserDate2,
					UserDate3 = @UserDate3,
					UserDate4 = @UserDate4,
					UserDate5 = @UserDate5,
					UserDate6 = @UserDate6,
					LinkID = @FullLinkID,
					ClassKey = @ClassKey,
					OfficeKey = @OfficeKey,
					DepartmentKey = @DepartmentKey
				Where
					PurchaseOrderDetailKey = @PODKey
					
                update tPurchaseOrder
				set DateUpdated = @CurrentDate 
				where PurchaseOrderKey = @PurchaseOrderKey 
			end
	END

	-- final check to prevent situations where PO Closed = 1 and exists POD Closed = 0
	If exists(Select 1 from tPurchaseOrderDetail (NOLOCK) Where PurchaseOrderKey = @PurchaseOrderKey and ISNULL(Closed, 0) = 0)
		begin
			Update tPurchaseOrder Set Closed = 0 Where PurchaseOrderKey = @PurchaseOrderKey

			set @ActionLogComment = ''Opened by Strata Sync''
			exec @RetVal = sptActionLogInsert ''Purchase Order'', @PurchaseOrderKey, @CompanyKey, @ProjectKey,''Opened'', @CurrentDate,''Strata Link'', @ActionLogComment, @CurrentDate, @CompanyKey, @UserKey, NULL  
		end
	else
		Update tPurchaseOrder Set Closed = 1 Where PurchaseOrderKey = @PurchaseOrderKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vListing_Lead]'
GO
IF OBJECT_ID(N'[dbo].[vListing_Lead]', 'V') IS NOT NULL
EXEC sp_executesql N'







ALTER VIEW [dbo].[vListing_Lead]
AS

/*
  || When     Who Rel      What
  || 10/13/06 WES 8.3567   Added Custom Fields Key
  || 02/09/09 GWG 10.5	   Made cmfolderkey force to 0 so that a no folder check can be made.
  || 03/11/09 MAS 10.5	   Added Last and Next Activity columns, renamed columns, removed user_defined columns.
  || 04/03/09 GWG 10.5     Minor fixes to views
  || 04/30/09 CRG 10.5.0.0 Added Next/Last Activity Types, Days Since Last Activity, and No Activity Since.
  ||                       Removed = from column aliases because it caused problems in listings.
  || 05/18/09 MAS 10.5.0.0 Changed Stage to Left Outer join
  || 08/05/09 GWG 10.5.0.6 Fixed the Owner Name to come from the correct place
  || 08/15/09 GWG 10.5.0.7 Added Lead custom field for access to the user defined fields
  || 09/30/09 GWG 10.5.1.1 Fixed join out to tCMFolder to be based on Lead, not company
  || 10/09/09 GHL 10.5.1.2 (59665) Added DateAdded
  || 02/08/09 GWG 10.5.1.8 Fixed joins out to non required tables (status, stage, acct mgr)
  || 03/08/10 RLB 10.5.1.9 (76113)Account Manager is pulled from lead Company Keys Account Manager
  || 03/10/10 RLB 10.5.2.0 Add padding to Forecasted and Actual close month 
  || 06/11/10 RLB 10.5.3.1 (67960) Added Date Modified enhancement
  || 04/22 11 RLB 10.5.4.3 (109575) Fixed join on tLeadStageHistory 
  || 05/9/11  GWG 10.5.4.3 Fixed the fix to the join on tLeadStageHistory
  || 07/15/11 GWG 10.5.4.6 Added Converted to Type and Converted To (project name or campaign)
  || 11/07/11 RLB 10.5.5.0 (125619) Added for protection
  || 12/08/11 RLB 10.5.5.1 (113208) Added Primary Contact email
  || 02/14/12 MFT 10.5.5.2 (99506) Added ParentCompany
  || 06/21/12 GHL 10.5.5.7 Added GL Company info
  || 09/20/12 GWG 10.5.6.0 Added the sale amount to the view
  || 01/28/13 WDF 10.5.6.4 (165956) Modified Date Created
  || 10/02/13 MAS 10.5.7.3 (179034) Added ClientDivisionKey & ClientProductKey
  || 04/15/15 RLB 10.5.9.1 Added companies contactownerkey it is used in Plat for opp count
  || 09/15/15 RLB 10.5.9.6 Added LeadID
  || 09/27/15 GWG 10.5.9.6 change next and last act date to DateModified
  || 10/01/15 GHL 10.5.9.6 Added project info (for advanced features) 
  || 10/12/15 WDF 10.5.9.7 Added Company Next/Last Activity Dates
  || 11/4/15  GWG 10.5.9.7 Revert the Last Dates to Activity date
  || 03/01/16 WDF 10.6.0.1 (291115) Changed Inner Join to Left Join for tLead.ContactCompanyKey = tCompany.CompanyKey
  || 02/05/17 GWG 18.2.0  Change lead ID to opp id
  || 02/19/18 GAR 18.3.0.0  (373196) Added No Folder as NULL option to aid in searching
  || 09/21/18 RLS 18.9.1   (421374) Added tLead.Months
  || 02/18/20 GHL 20.0.3.0 (496238) Added campaign info (for advanced features) 
  || 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
  || 10/07/20 GAR 20.1.1.0 (529824) Added ConvertedFromOpportunityDate
  || 10/29/20 RLB 20.1.1.0 (534206) added company website field
  || 11/19/20 AMP 20.1.2.0 (537289) Added Campaign Account Manager from the linked campaign
  || 05/20/21 RLS 21.0.6.0 (556492) Changed Description to nvarchar
  || 06/16/21 RLS 21.0.7.0 (562155) Added [Stage name Only]
  || 01/16/22 RLS 21.0.7.0 (579797) Added [Project Manager Name]
  || 08/11/23 RLB 23.09.17 (648008) added project type color, Next Activity Status Color and Last Activity Status Color
  || 11/24/25 RLS 25.12.14 (712146) Added [Project Made Live Date
  || 04/21/26 RLB 26.05.17 (726860) change Project Made Live Date To pull max date because there could be more than one and that caused multiple rows
*/

SELECT 
	 tLead.CompanyKey
	,tLead.GLCompanyKey
	,ISNULL(tLead.CMFolderKey, 0) as CMFolderKey
	,tCompany.CustomFieldKey
	,tLead.CustomFieldKey as LeadCustomFieldKey
	,tLead.LeadKey
	,tLead.ContactCompanyKey
	,tLead.ContactKey
	,tLead.AccountManagerKey
	,tLead.Subject
	,tLead.LeadID AS [Opportunity ID]
	,LTRIM(RTRIM(ISNULL(tUser.FirstName + '' '','''')  + ISNULL(tUser.LastName,''''))) AS ContactName
	,tCompany.CompanyName
	,tLead.Subject AS [Opportunity Name]
	,tCompany.CompanyName as [Company Name]
	,tCompany.CustomerID as [Company Client ID]
	,tCompany.WebSite as [Website]
	,CASE when tCompany.BillableClient = 1 then ''YES'' else ''NO'' end AS [Billable Client]
	,LTRIM(RTRIM(ISNULL(tUser.FirstName + '' '','''')  + ISNULL(tUser.LastName,''''))) AS [Primary Contact Name]
	,tUser.Email AS [Primary Contact Email]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager Name]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager Name]
	,CASE 
		WHEN tUser.MiddleName IS NULL THEN LTRIM(RTRIM(ISNULL(tUser.FirstName,'''') + '' '' + ISNULL(tUser.LastName,''''))) 
		ELSE LTRIM(RTRIM(ISNULL(tUser.FirstName,'''') + '' '' + SUBSTRING(tUser.MiddleName, 1, 1) + '' '' + ISNULL(tUser.LastName,''''))) 
	END AS [User Full Name]
	,tProjectType.ProjectTypeName AS [Project Type Name]
	,tProjectType.ProjectTypeColor as [Project Type Color]
	,CASE when tLeadStatus.Active = 1 then ''YES'' else ''NO'' end AS [Active]
	,cast(tLeadStage.DisplayOrder as varchar) + '' - '' + tLeadStage.LeadStageName AS [Stage Name]
	,tLeadStage.LeadStageName AS [Stage Name Only]
	,tLeadStage.DisplayOrder AS [Stage Display Order]
	,tLeadOutcome.Outcome AS [Outcome]
	,tLeadStatus.LeadStatusName AS [Status]
	,tCompanyType.CompanyTypeName as [Company Type]
	,tLead.OutcomeComment AS [Outcome Comment]
	,tLead.CurrentStatus as [Next Steps]
	,tLead.Probability AS [Probability]
	,tLead.Labor as [Labor Amount]
	,tLead.SaleAmount as [Sale Amount]
	,tLead.SaleAmount * tLead.Probability / 100 AS [Forecasted Sale Amount]
	,tLead.OutsideCostsGross AS [Production Gross]
	,tLead.OutsideCostsPerc as [Production Margin]
	,tLead.MediaGross as [Media Gross]
	,tLead.MediaPerc as [Media Margin]
	,tLead.OutsideCostsGross * OutsideCostsPerc / 100 as [Production Net]
	,tLead.MediaGross * MediaPerc / 100 as [Media Net]
	,tLead.AGI as [AGI]
	,tLead.DateUpdated as [Date Modified]
	,tLead.StartDate as [Start Date]
	,tLead.DateAdded as [Date Created]
	,tLead.EstCloseDate as [Forecasted Close Date]
	,tLead.BidDate as [Estimate Due Date]
	,tLead.DateConverted as [Date Converted]
	,tLead.Months
	,DATEPART("YYYY", tLead.EstCloseDate) AS [Forecasted Close Year]
	,RIGHT(''0'' + CAST(DATEPART(Month, tLead.EstCloseDate) AS VARCHAR(2)), 2) AS [Forecasted Close Month]
	,tLead.ActualCloseDate AS [Actual Close Date]
	,DATEPART("YYYY", tLead.ActualCloseDate) AS [Actual Close Year]
	,RIGHT(''0'' + CAST(DATEPART(Month, tLead.ActualCloseDate) AS VARCHAR(2)), 2) AS [Actual Close Month]
	,CAST(tLead.Comments AS NVARCHAR(MAX)) AS [Description]
	-- WWP
	,CASE tLead.WWPCurrentLevel
		WHEN 2 THEN ''2 - Contemplating''
		WHEN 3 THEN ''3 - Planning''
		WHEN 4 THEN ''4 - Action''
		ELSE ''1 - Unaware''
	END AS [WWP Current Level w Name]
	, tLead.WWPCurrentLevel as [WWP Current Level]
	,CASE WHEN tLead.WWPNeedSupply = 1 THEN ''YES'' ELSE ''NO'' END AS [WWP Needs Equals Supply]
	,tLead.WWPNeedSupplyComment AS [WWP Needs Equals Supply Comment]
	,CASE WHEN tLead.WWPTimeline = 1 THEN ''YES'' ELSE ''NO'' END AS [WWP Timeline]
	,tLead.WWPTimelineComment AS [WWP Timeline Comment]
	,CASE WHEN tLead.WWPDecisionMakers = 1 THEN ''YES'' ELSE ''NO'' END AS [WWP Decision Makers]
	,tLead.WWPDecisionMakersComment AS [WWP Decision Makers Comment]
	,CASE WHEN tLead.WWPBudget = 1 THEN ''YES'' ELSE ''NO'' END AS [WWP Budget]
	,tLead.WWPBudgetComment AS [WWP Budget Comment]
	,LTRIM(RTRIM(ISNULL(owner.FirstName + '' '','''')  + ISNULL(owner.LastName,''''))) AS [Company Owner]
	,LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Sales Person]
	,CASE WHEN lo.PositiveOutcome = 1 THEN ''YES'' ELSE ''NO'' END AS [Positive Outcome Indicator]
	,tLead.Competitors AS [Competitors]
	,(Select Max(HistoryDate) from tLeadStageHistory (NOLOCK) Where tLead.LeadKey = tLeadStageHistory.LeadKey)  AS [Stage Date]
	,LTRIM(RTRIM(ISNULL(tUser1.FirstName + '' '','''')  + ISNULL(tUser1.LastName,''''))) AS [Opportunity Owner Name]
	,so.SourceName AS [Company Source]
	,ISNULL(folder.FolderName, ''No Folder'') AS [Folder]

	,lastActivity.ActivityDate AS [Last Activity Date]
	,lastActivity.Subject AS [Last Activity Subject]
	,lastActivity.Notes AS [Last Activity Notes]
	,lcomp.ActivityDate as [Company Last Activity Date]
	,LTRIM(RTRIM(ISNULL(lau.FirstName + '' '','''')  + ISNULL(lau.LastName,''''))) AS [Last Activity Assigned To]

	,nextActivity.ActivityDate AS [Next Activity Date]
	,nextActivity.Subject AS [Next Activity Subject]
	,ncomp.ActivityDate as [Company Next Activity Date]
	,LTRIM(RTRIM(ISNULL(nau.FirstName + '' '','''')  + ISNULL(nau.LastName,''''))) AS [Next Activity Assigned To]
	 ,atNext.TypeName AS [Next Activity Type]
	 ,atNext.TypeColor AS [Next Activity Type Color]
	 ,atLast.TypeName AS [Last Activity Type]
	 ,atLast.TypeColor as [Last Activity Type Color]
	 ,DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) AS [Days Since Last Activity]
	 ,CASE
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 90 THEN ''90 Days''
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 60 THEN ''60 Days''
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 30 THEN ''30 Days''
		WHEN DATEDIFF(day, lastActivity.ActivityDate, GETDATE()) > 7 THEN ''7 Days''
		ELSE NULL
	  END AS [No Activity Since]
	 ,CASE
		WHEN ConvertEntity = ''tProject'' THEN ''Project''
		WHEN ConvertEntity = ''tCampaign'' THEN ''Campaign''
		ELSE NULL
	  END as [Converted To Type]
	 ,CASE
		WHEN ConvertEntity = ''tProject'' THEN (Select ProjectNumber + '' - '' + ProjectName from tProject (nolock) Where ProjectKey = ConvertEntityKey)
		WHEN ConvertEntity = ''tCampaign'' THEN (Select CampaignID + '' - '' + CampaignName from tCampaign (nolock) Where CampaignKey = ConvertEntityKey)
		ELSE NULL
	  END as [Converted To]
	,ConvertedFromOpportunityDate as [Date Converted From Opportunity]
	,pc.CompanyName as [Parent Company Name]
	,pc.ContactOwnerKey
    ,glc.GLCompanyID as [GL Company ID]
    ,glc.GLCompanyName as [GL Company Name]
    ,cd.ClientDivisionKey
    ,cd.DivisionName as [Division Name]
    ,cp.ClientProductKey
    ,cp.ProductName as [Product Name]
	,p.ProjectNumber as [Project Number]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName as [Project Full Name]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignName as [Campaign Name]
	,ca.CampaignID + '' - '' + ca.CampaignName as [Campaign Full Name]
	,ISNULL(LTRIM((SELECT STUFF((SELECT '', '' + ListName 
        FROM tMarketingListList mll (NOLOCK)
			INNER JOIN tUser mlUser (NOLOCK) ON mll.EntityKey = mlUser.UserKey AND mll.Entity = ''tUserLead''
			INNER JOIN tMarketingList ml (NOLOCK) ON mll.MarketingListKey = ml.MarketingListKey
		WHERE UserKey = tUserLead.UserLeadKey
            FOR XML PATH('''')) ,1,1,''''))), '''') AS [Marketing Groups]
	,LTRIM(RTRIM(ISNULL(cam.FirstName + '' '','''')  + ISNULL(cam.LastName,''''))) AS [Campaign Account Manager]
	,(Select Max(ActionDate) from tActionLog (NOLOCK) Where p.ProjectKey = tActionLog.EntityKey AND Action = ''Project Made Live'' )  AS [Project Made Live Date]
	
FROM tLead
	LEFT OUTER JOIN tCompany (nolock) ON tLead.ContactCompanyKey = tCompany.CompanyKey
	LEFT OUTER JOIN	tCompany pc (nolock) ON tCompany.ParentCompany = pc.CompanyKey
	LEFT OUTER JOIN tLeadStatus (nolock) ON tLead.LeadStatusKey = tLeadStatus.LeadStatusKey
	LEFT OUTER JOIN tLeadStage (nolock) ON tLead.LeadStageKey = tLeadStage.LeadStageKey
	LEFT OUTER JOIN tUser tUser1 (nolock) ON tLead.AccountManagerKey = tUser1.UserKey
	LEFT OUTER JOIN tUser (nolock) ON tLead.ContactKey = tUser.UserKey
	Left OUTER JOIN tUser am (nolock) ON tCompany.AccountManagerKey = am.UserKey
	Left OUTER JOIN tUser pm (nolock) ON tCompany.ProjectManagerKey = pm.UserKey
	LEFT OUTER JOIN tLeadOutcome (nolock) ON tLead.LeadOutcomeKey = tLeadOutcome.LeadOutcomeKey
	LEFT OUTER JOIN tProjectType (nolock) ON tLead.ProjectTypeKey = tProjectType.ProjectTypeKey
	LEFT OUTER JOIN tCompanyType (nolock) on tCompany.CompanyTypeKey = tCompanyType.CompanyTypeKey
	LEFT OUTER JOIN tActivity lastActivity (NOLOCK) on tLead.LastActivityKey = lastActivity.ActivityKey
	LEFT OUTER JOIN tUser lau (NOLOCK) ON lastActivity.AssignedUserKey = lau.UserKey
	LEFT OUTER JOIN tActivity nextActivity (NOLOCK) on tLead.NextActivityKey = nextActivity.ActivityKey
	LEFT OUTER JOIN tUser nau (NOLOCK) ON nextActivity.AssignedUserKey = nau.UserKey
	LEFT OUTER JOIN tUser sales (NOLOCK) ON tCompany.SalesPersonKey = sales.UserKey
	LEFT OUTER JOIN tLeadOutcome lo (NOLOCK) ON tLead.LeadOutcomeKey = lo.LeadOutcomeKey
	LEFT OUTER JOIN tUser owner (NOLOCK) ON tCompany.ContactOwnerKey = owner.UserKey
	LEFT OUTER JOIN tActivity lcomp (NOLOCK) ON tCompany.LastActivityKey = lcomp.ActivityKey
	LEFT OUTER JOIN tActivity ncomp (NOLOCK) ON tCompany.NextActivityKey = ncomp.ActivityKey
	LEFT OUTER JOIN tCMFolder folder (NOLOCK) on tLead.CMFolderKey = folder.CMFolderKey
	LEFT OUTER JOIN	tSource so (NOLOCK) on tCompany.SourceKey = so.SourceKey
	LEFT OUTER JOIN tActivityType atNext (NOLOCK) ON nextActivity.ActivityTypeKey = atNext.ActivityTypeKey
	LEFT OUTER JOIN tActivityType atLast (NOLOCK) ON lastActivity.ActivityTypeKey = atLast.ActivityTypeKey
	LEFT OUTER JOIN tGLCompany glc (NOLOCK) ON tLead.GLCompanyKey = glc.GLCompanyKey
	LEFT OUTER JOIN tClientDivision cd(NOLOCK) ON tLead.ClientDivisionKey = cd.ClientDivisionKey
	LEFT OUTER JOIN tClientProduct cp(NOLOCK) ON tLead.ClientProductKey = cp.ClientProductKey
	LEFT OUTER JOIN tProject p (NOLOCK) ON tLead.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tCampaign ca (NOLOCK) ON tLead.CampaignKey = ca.CampaignKey
	Left OUTER JOIN tUser cam (nolock) ON ca.AEKey = cam.UserKey	
	LEFT OUTER JOIN tUserLead (nolock) ON tLead.ContactCompanyKey = tUserLead.CompanyKey

	  



















'
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]
(
	@UserKey int,
	@StartDate datetime,
	@EndDate datetime,
	@UTCOffsetHours	int      = 0
)
as

-- 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, DATEADD(HOUR, (@UTCOffsetHours), cal.EventStart) as EventStart, DATEADD(HOUR, (@UTCOffsetHours), 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 = @UserKey and cal.EventStart >= @StartDate and cal.EventEnd <= @EndDate

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, DATEADD(HOUR, (@UTCOffsetHours), cal.EventStart) as EventStart, DATEADD(HOUR, (@UTCOffsetHours), 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 = @UserKey and cc.EventStart >= @StartDate and cc.EventEnd <= @EndDate
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPurchaseOrderDetailUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderDetailUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptPurchaseOrderDetailUpdate]
	@PurchaseOrderDetailKey int,
	@PurchaseOrderKey int,
	@LineNumber int = NULL,
	@ProjectKey int,
	@TaskKey int,
	@ItemKey int,
	@ClassKey int,
	@ShortDescription varchar(max),
	@Quantity decimal(24,4),
	@UnitCost money,
	@UnitDescription varchar(30),
	@TotalCost money,
	@UnitRate money,
	@Billable tinyint,
	@Markup decimal(24,4),
	@BillableCost money,
	@LongDescription nvarchar(max),
	@CustomFieldKey int,
	@DetailOrderDate smalldatetime,
	@DetailOrderEndDate smalldatetime,
	@UserDate1 smalldatetime,
	@UserDate2 smalldatetime,
	@UserDate3 smalldatetime,
	@UserDate4 smalldatetime,
	@UserDate5 smalldatetime,
	@UserDate6 smalldatetime,
	@OrderDays varchar(50),
	@OrderTime varchar(50),
	@OrderLength varchar(50),
	@Taxable tinyint,
	@Taxable2 tinyint,
	@OfficeKey int,
	@DepartmentKey int,
	@AdjustmentNumber int = 0,
	@SelectUpdate tinyint = 0,
	@Quantity1 decimal(24, 4) = null,
	@Quantity2 decimal(24, 4) = null,
	@LineType varchar(50) = null,
	@MediaPremiumKey int = null,
	@PremiumAmountType varchar(50) = null,
	@PremiumPct decimal(24, 4) = null,
	@GrossAmount money = null,
	@Commission decimal(24, 4) = null,
	@NoFinancialUpdate tinyint = 0, --This is used when called from sptPurchaseOrderDetailUpdateFromWorksheet since the financial fields are updated there
	@PCurrencyID varchar(10) = null,
	@PExchangeRate decimal(24,7) = 1,
	@PTotalCost money = null,
	@DetailVendorKey int = null,
	@Bucket int = NULL,
	@SalesTaxAmount money = 0,
	@SalesTax1Amount money = 0,
	@SalesTax2Amount money = 0,
	@UpdateSingleSpot int = 0, -- For BO only, 0 update the line (i.e. several spots), 1 update a single spot (for WJAPP screen)
	@MaterialsSent tinyint = 0,
	@MaterialsSentDate smalldatetime = null,
	@InteractiveAdUnitName varchar(100) = null



AS --Encrypt

 /*
  || When     Who Rel    What
  || 12/07/06 GHL 8.4    Added restriction on changes of IO 
  || 02/20/07 GHL 8.4    Added project rollup section
  || 04/13/07 BSH 8.4.5  DateUpdated needed to be updated.
  || 07/16/07 BSH 8.5    (9659)Update OfficeKey, DepartmentKey 
  || 1/21/09  GWG 10.018 Added Rounding protection on cost and gross
  || 12/11/09 MFT 10.515 Added insert logic
  || 04/30/10 GHL 10.522 (79762) Do not update spots which have been transferred out
  || 07/20/10 MFT 10.532 Changed insert test to ISNULL(@PurchaseOrderDetailKey, 0) < 1 to support data manager updates
  || 10/14/10 MFT 10.536 Added -5 error return test, modified error test in INSERT section
  || 11/02/10 MFT 10.537 Added @AdjustmentNumber to insert to allow for document level saving
  || 07/01/11 GHL 10.546 (111482) Added call to sptPurchaseOrderRollupAmounts for tax amounts 
  || 08/28/12 RLB 10.559 (94289, 150065) Changes made for enhancment
  || 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @ShortDescription from 200 to 300
  || 08/30/13 CRG 10.5.7.1 Added @LineType, @MediaPremiumKey, @PremiumAmountType, @PremiumPct, @GrossAmount
  || 10/04/13 CRG 10.5.7.3 Added @Commission
  || 12/17/13 GHL 10.5.7.5 Added currency parameters
  || 12/26/13 CRG 10.5.7.4 Modified LineNumber logic for Interactive orders
  || 1/3/13   CRG 10.5.7.6 Added @DetailVendorKey
  || 01/20/14 GHL 10.575 For import compare isnull(PTotalCost, 0) to 0 rather than PTotalCost to NULL
  || 03/14/14 CRG 10.5.7.7 Added @Bucket (When @Bucket is not NULL, it indicates that this is a new Broadcast order and not a Legacy one)
  || 04/28/14 RLB 10.5.7.9 (214240) increasing the description length and allow updated of prebilled or applied line for description and comments other fields should be locked down.
  || 05/08/14 RLB 10.5.7.9 (215598) since fields are locked down in PO allow update to a closed PO
  || 07/17/14 GHL 10.5.8.2 Do not restore MediaPremiumKey because we may go from a manual premium to a stored premium or viceversa
  || 08/13/14 GHL 10.5.8.3 If @NoFinancialUpdate = 1, do not check if it is billed, because we restore the financial data anyway
  || 08/22/14 GHL 10.5.8.3 Added sales tax amounts
  || 01/08/15 GAR 10.5.8.8 Added POKind = 0 to code where we assign next line numbers.
  || 08/11/15 GHL 10.5.9.5 (263071) LongDescription is now varchar(max)
  || 08/23/17 GHL 10.6.1.9 Added parameter @UpdateSingleSpot to save a single spot (WJAPP) instead of a line with multiple spots (WMJ)
  || 09/20/19 AMP 19.1.0.0 (477552) Added an update to tPurchaseOrder to set the header Materials Sent = 0 when there is a line on the order that is not marked ''Materials Sent''
  || 03/16/21 RLS 21.0.4.0 (550747) Changed @LongDescription to nvarchar(max)
  || 06/25/21 GHL 21.0.7.0 Added validation of PCurrencyID and PExchangeRate (in case of timing issue on the UI)
  || 09/15/21 GHL 21.1.0.0 (568830) Added validation of item if it is requird
  || 04/22/26 MCM 26.5.x   (725435) Added @InteractiveAdUnitName for PurcahseOrderDetail
  */
declare @POKind smallint
declare @FlightInterval tinyint
declare @FlightStartDate smalldatetime
declare @FlightEndDate smalldatetime
declare @DefaultDate smalldatetime
declare @CompanyKey int
declare @AllowChangesAfterClientInvoice tinyint
declare @InvoiceLineKey int
declare @OldProjectKey int
declare @GLCompanyKey int
declare @ExchangeRate decimal(24,7)
declare @PODate smalldatetime
declare @CurrencyID varchar(10)
declare @RequireItems int

select @DefaultDate = cast(datepart(yyyy,getdate()) as varchar(4)) + ''-'' + cast(datepart(mm,getdate()) as varchar(2)) + ''-'' + cast(datepart(dd,getdate()) as varchar(2)) 

SELECT
	@GLCompanyKey = ISNULL(GLCompanyKey, 0),
	@POKind = POKind,
	@FlightInterval = ISNULL(FlightInterval, 3),
	@FlightStartDate = ISNULL(FlightStartDate, @DefaultDate),
	@FlightEndDate = ISNULL(FlightEndDate,ISNULL(FlightStartDate, @DefaultDate)),
	@PODate = ISNULL(PODate, @DefaultDate),
	@ExchangeRate = isnull(ExchangeRate, 1),
	@CompanyKey = CompanyKey,
	@CurrencyID = CurrencyID
FROM tPurchaseOrder po (nolock)
WHERE po.PurchaseOrderKey = @PurchaseOrderKey

IF EXISTS(
	SELECT *
	FROM tProject p (nolock)
	WHERE
		p.ProjectKey = @ProjectKey AND
		ISNULL(p.GLCompanyKey, 0) <> @GLCompanyKey
) RETURN -5

-- fix to prevent timing issues where the project is changed and then saved
-- without getting the currency and exchange rate
declare @MultiCurrency int
declare @ProjectCurrencyID varchar(10)
declare @RateHistory int

select @MultiCurrency = pref.MultiCurrency 
from  tPreference pref (nolock)
where pref.CompanyKey = @CompanyKey

if @ProjectKey > 0 and @MultiCurrency = 1
	begin
		select @ProjectCurrencyID = CurrencyID from tProject (nolock) where ProjectKey = @ProjectKey
		if isnull(@PCurrencyID, '''') <> isnull(@ProjectCurrencyID, '''')
		begin
			select @PCurrencyID = @ProjectCurrencyID
			if isnull(@PCurrencyID, '''') = ''''
				select @PExchangeRate = 1
			else
			begin
				if isnull(@PCurrencyID, '''') = isnull(@CurrencyID, '''') 
					select @PExchangeRate = @ExchangeRate
				else
					exec sptCurrencyGetRate @CompanyKey, @GLCompanyKey, @PCurrencyID, @PODate, @PExchangeRate output, @RateHistory output
			end

			if @PExchangeRate > 0
				select @PTotalCost = (@TotalCost * @ExchangeRate) / @PExchangeRate 
						,@BillableCost = (@GrossAmount * @ExchangeRate) / @PExchangeRate
		end
	end

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

if isnull(@PTotalCost, 0) = 0
	select @PTotalCost = @TotalCost

if isnull(@GrossAmount, 0) = 0
	select @GrossAmount = @BillableCost

IF ISNULL(@PurchaseOrderDetailKey, 0) < 1
	BEGIN --INSERT LOGIC
			select @RequireItems = RequireItems from tPreference (nolock) where CompanyKey = @CompanyKey
		if isnull(@RequireItems, 0) = 1 and isnull(@ItemKey, 0) = 0
			return -7

		if @POKind IN (1,2)
			begin
				if exists(SELECT 1
								FROM tPurchaseOrder po (NOLOCK)
								 WHERE po.PurchaseOrderKey = @PurchaseOrderKey
								 AND po.Closed = 1)
				update tPurchaseOrder
						 set Closed = 0
					 where PurchaseOrderKey = @PurchaseOrderKey
			end
		else
			begin
				IF EXISTS (SELECT 1
							 FROM tPurchaseOrder po (NOLOCK)
							WHERE po.PurchaseOrderKey = @PurchaseOrderKey
								AND (po.Closed = 1 or po.Downloaded = 1))
					RETURN -2
			end 
	  
		if ISNULL(@ProjectKey, 0) > 0
			IF NOT EXISTS(Select 1 from tProject p (nolock) inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
				Where p.ProjectKey = @ProjectKey and ps.ExpenseActive = 1)
				Return -3 
		
		DECLARE @NextNum as int
		
		-- Default value for NextNum
		SELECT @NextNum = ISNULL(Max(LineNumber),0) + 1 FROM tPurchaseOrderDetail (NOLOCK) WHERE PurchaseOrderKey = @PurchaseOrderKey
		
		if @POKind IN (0, 1, 4)
			begin
				if isnull(@LineNumber,0) > 0
					begin
						select @NextNum = @LineNumber
					end
			end
		
		if @POKind = 2
			begin
				-- associate this line to an existing line if importing from Strata or SmartPlus
				if isnull(@LineNumber,0) > 0
					begin
						select @NextNum = @LineNumber					
					end 
				else
						begin
						-- line number will be zero, use calculated number and calculate dates
						if @FlightInterval = 1 and @DetailOrderDate is null
							select @DetailOrderDate = @FlightStartDate
									,@DetailOrderEndDate = @FlightStartDate
						if @FlightInterval = 2 and @DetailOrderDate is null
							select @DetailOrderDate = @FlightStartDate
									,@DetailOrderEndDate = dateadd(d,6,@FlightStartDate)
						if @FlightInterval = 3 and @DetailOrderDate is null
							begin
								select @DetailOrderDate = isnull(@DetailOrderDate,@FlightStartDate)
											,@DetailOrderEndDate = isnull(@DetailOrderEndDate,@FlightEndDate)
							end	
					end			
			end 

		if @POKind = 2
			begin
				if exists(select 1 from tPurchaseOrderDetail (nolock)
					where PurchaseOrderKey = @PurchaseOrderKey
					and   LineNumber = @NextNum -- This is what we insert, so compare with @NextNum
					and   AdjustmentNumber = @AdjustmentNumber
					and   DetailOrderDate = @DetailOrderDate
					)
					return -6
			end

if @GrossAmount is null
	select @GrossAmount = @BillableCost
		
		INSERT tPurchaseOrderDetail
			(
			PurchaseOrderKey,
			LineNumber,
			AdjustmentNumber,
			ProjectKey,
			TaskKey,
			ItemKey,
			ClassKey,
			ShortDescription,
			Quantity,
			UnitCost,
			UnitDescription,
			TotalCost,
			UnitRate,
			Billable,
			Markup,
			BillableCost,
			LongDescription,
			CustomFieldKey,
			DetailOrderDate,
			DetailOrderEndDate,
			UserDate1,
			UserDate2,
			UserDate3,
			UserDate4,
			UserDate5,
			UserDate6,
			OrderDays,
			OrderTime,
			OrderLength,
			Taxable,
			Taxable2,
			OfficeKey,
			DepartmentKey,
			Quantity1,
			Quantity2,
			LineType,
			MediaPremiumKey,
			PremiumAmountType,
			PremiumPct,
			GrossAmount,
			Commission,
			PCurrencyID,
			PExchangeRate,
			PTotalCost,
			DetailVendorKey,
			Bucket,
			SalesTaxAmount,
			SalesTax1Amount,
            SalesTax2Amount,
			MaterialsSent,
			MaterialsSentDate,
			InteractiveAdUnitName)

		VALUES
			(
			@PurchaseOrderKey,
			@NextNum,		-- @LineNumber,
			@AdjustmentNumber,
			@ProjectKey,
			@TaskKey,
			@ItemKey,
			@ClassKey,
			@ShortDescription,
			@Quantity,
			@UnitCost,
			@UnitDescription,
			Round(@TotalCost, 2),
			@UnitRate,
			@Billable,
			@Markup,
			Round(@BillableCost, 2),
			@LongDescription,
			@CustomFieldKey,
			@DetailOrderDate,
			@DetailOrderEndDate,
			@UserDate1,
			@UserDate2,
			@UserDate3,
			@UserDate4,
			@UserDate5,
			@UserDate6,
			@OrderDays,
			@OrderTime,
			@OrderLength,
			@Taxable,
			@Taxable2,
			@OfficeKey,
			@DepartmentKey,
			@Quantity1,
			@Quantity2,
			@LineType,
			@MediaPremiumKey,
			@PremiumAmountType,
			@PremiumPct,
			@GrossAmount,
			@Commission,
			@PCurrencyID,
			@PExchangeRate,
			@PTotalCost,
			@DetailVendorKey,
			@Bucket,
			@SalesTaxAmount,
			@SalesTax1Amount,
            @SalesTax2Amount,
			@MaterialsSent,
			@MaterialsSentDate,
			@InteractiveAdUnitName
			)
		
		SELECT @PurchaseOrderDetailKey = SCOPE_IDENTITY()
		
		exec sptPurchaseOrderDetailUpdateApprover @PurchaseOrderKey
		
		exec sptPurchaseOrderRollupAmounts @PurchaseOrderKey

		RETURN @PurchaseOrderDetailKey
	END --END INSERT LOGIC

	--START UPDATE LOGIC

	select @LineNumber = LineNumber
	      ,@AdjustmentNumber = AdjustmentNumber
	      ,@InvoiceLineKey = isnull(InvoiceLineKey,0)
		  ,@OldProjectKey = ProjectKey
	  from tPurchaseOrderDetail (nolock)
	 where PurchaseOrderDetailKey = @PurchaseOrderDetailKey

	select @POKind = POKind 
		  ,@FlightInterval = isnull(FlightInterval,3)
		  ,@CompanyKey = CompanyKey
	  from tPurchaseOrder (nolock)
	 where PurchaseOrderKey = @PurchaseOrderKey

	-- for BO, make sure that POKey/LineNumber/AdjustmentNumber/DetailOrderDate is unique (single or wjapp mode)
	if @POKind = 2 and @UpdateSingleSpot = 1
	begin
		if exists(select 1 from tPurchaseOrderDetail (nolock)
			where PurchaseOrderKey = @PurchaseOrderKey
			and   LineNumber = @LineNumber
			and   AdjustmentNumber = @AdjustmentNumber
			and   DetailOrderDate = @DetailOrderDate
			and   PurchaseOrderDetailKey <> @PurchaseOrderDetailKey
			)
			return -6
	end
	 

	-- determine if order lines (spots) can be updated after client invocie has been created
	select @AllowChangesAfterClientInvoice = 
	       case when @POKind = 0 then 0
		       when @POKind = 1 then isnull(IOAllowChangesAfterClientInvoice, 0)
		       when @POKind = 2 then isnull(BCAllowChangesAfterClientInvoice, 0)
	        end
      from tPreference (nolock)
     where CompanyKey = @CompanyKey

	if @POKind = 2  -- is this a broadcast (spot level) order?
		begin
			-- changes cannot be made after a vendor invoice has been received, make sure none of the spots get updated since they shared information
			IF EXISTS (SELECT 1 FROM tVoucherDetail (NOLOCK)
						where PurchaseOrderDetailKey in (select PurchaseOrderDetailKey
														   from tPurchaseOrderDetail (nolock)
														  where PurchaseOrderKey = @PurchaseOrderKey
															and LineNumber = @LineNumber
															and AdjustmentNumber = @AdjustmentNumber))
				RETURN -1
		end
/*	
	else
		begin
			IF EXISTS (SELECT 1 FROM   tVoucherDetail vd (NOLOCK)
						inner join tPurchaseOrderDetail pod (NOLOCK) on pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey
						WHERE  pod.PurchaseOrderDetailKey = @PurchaseOrderDetailKey)
				RETURN -1	
		end
*/

	--make sure PO is not closed
/*	IF EXISTS (SELECT 1
	           FROM		tPurchaseOrder po (NOLOCK)
	           WHERE  po.PurchaseOrderKey = @PurchaseOrderKey
	           AND    (po.Closed = 1))
		RETURN -2
		
	-- make sure the project is accepting expenses
	if ISNULL(@ProjectKey, 0) > 0
		IF NOT EXISTS(Select 1 from tProject p (nolock) inner join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
			Where p.ProjectKey = @ProjectKey and ps.ExpenseActive = 1)
			Return -3 
*/
			
DECLARE @CurrentStatus int
DECLARE @Revision int

--Get existing values for Optional Parms
DECLARE @OldQuantity1 decimal(24, 4),
		@OldQuantity2 decimal(24, 4),
		@OldLineType varchar(50),
		@OldMediaPremiumKey int,
		@OldPremiumAmountType varchar(50),
		@OldPremiumPct decimal(24, 4),
		@OldGrossAmount money,
		@OldCommission decimal(24, 4),
		@OldDetailVendorKey int,
		@OldBucket int
		
SELECT	@OldQuantity1 = Quantity1,
		@OldQuantity2 = Quantity2,
		@OldLineType = LineType,
		@OldMediaPremiumKey = MediaPremiumKey,
		@OldPremiumAmountType = PremiumAmountType,
		@OldPremiumPct = PremiumPct,
		@OldGrossAmount = GrossAmount,
		@OldCommission = Commission,
		@OldDetailVendorKey = DetailVendorKey,
		@OldBucket = Bucket
FROM	tPurchaseOrderDetail (nolock)
WHERE	PurchaseOrderDetailKey = @PurchaseOrderDetailKey

IF @Quantity1 IS NULL SELECT @Quantity1 = @OldQuantity1
IF @Quantity2 IS NULL SELECT @Quantity2 = @OldQuantity2
IF @LineType IS NULL SELECT @LineType = @OldLineType
--IF @MediaPremiumKey IS NULL SELECT @MediaPremiumKey = @OldMediaPremiumKey -- otherwise we cannot change to/from manual premium
IF @PremiumAmountType IS NULL SELECT @PremiumAmountType = @OldPremiumAmountType
IF @PremiumPct IS NULL SELECT @PremiumPct = @OldPremiumPct
IF @Commission IS NULL SELECT @Commission = @OldCommission
IF @DetailVendorKey IS NULL SELECT @DetailVendorKey = @OldDetailVendorKey
IF @Bucket IS NULL SELECT @Bucket = @OldBucket

IF @NoFinancialUpdate = 1
BEGIN
	--If we''re not updating the financial numbers, get their existing values
	SELECT	@Quantity1 = Quantity1,
			@Quantity2 = Quantity2,
			@Quantity = Quantity,
			@UnitCost = UnitCost,
			@Markup = Markup,
			@TotalCost = TotalCost,
			@PTotalCost = TotalCost,
			@BillableCost = BillableCost,
			@GrossAmount = GrossAmount,
			@LineType = LineType,
			@SalesTaxAmount = SalesTaxAmount,
			@SalesTax1Amount = SalesTax1Amount,
            @SalesTax2Amount = SalesTax2Amount
	FROM	tPurchaseOrderDetail (nolock)
	WHERE	PurchaseOrderDetailKey = @PurchaseOrderDetailKey
END
	
	if @POKind = 2 AND @UpdateSingleSpot = 0 AND @Bucket IS NULL -- is this a LEGACY broadcast (spot level) order?
	    if @FlightInterval = 3  -- is this a summary flight?
			begin
				if @InvoiceLineKey > 0 -- has the line been invoiced?
					begin
						if @SelectUpdate = 0 and @AllowChangesAfterClientInvoice = 0 -- if changes are not allowed after invoice
							return -4
					end
				
				-- update the summary line (spot)
				UPDATE
					tPurchaseOrderDetail
				SET
					PurchaseOrderKey = @PurchaseOrderKey,
					ProjectKey = @ProjectKey,
					TaskKey = @TaskKey,
					ItemKey = @ItemKey,
					ClassKey = @ClassKey,
					ShortDescription = @ShortDescription,
					UnitCost = @UnitCost,
					UnitDescription = @UnitDescription,
					TotalCost = Round(@TotalCost, 2),
					UnitRate = @UnitRate,
					Billable = @Billable,
					Markup = @Markup,
					BillableCost = Round(@BillableCost, 2),
					LongDescription = @LongDescription,
					CustomFieldKey = @CustomFieldKey,
					DetailOrderDate = @DetailOrderDate,
					DetailOrderEndDate = @DetailOrderEndDate,				
					OrderDays = @OrderDays,
					OrderTime = @OrderTime,
					OrderLength = @OrderLength,
					Taxable = @Taxable,
					Taxable2 = @Taxable2,
					OfficeKey = @OfficeKey,
					DepartmentKey = @DepartmentKey,
					Quantity1 = @Quantity1,
					Quantity2 = @Quantity2,
					LineType = @LineType,
					MediaPremiumKey = @MediaPremiumKey,
					PremiumAmountType = @PremiumAmountType,
					PremiumPct = @PremiumPct,
					GrossAmount = @GrossAmount,
					Commission = @Commission,
					PCurrencyID = @PCurrencyID,
					PExchangeRate = @PExchangeRate,
					PTotalCost = ROUND(@PTotalCost,2),
					DetailVendorKey = @DetailVendorKey,
					Bucket = @Bucket,
					SalesTaxAmount = @SalesTaxAmount,
			        SalesTax1Amount = @SalesTax1Amount,
                    SalesTax2Amount = @SalesTax2Amount,
					MaterialsSent = @MaterialsSent,
			        MaterialsSentDate = @MaterialsSentDate
				WHERE PurchaseOrderKey = @PurchaseOrderKey 
				  and LineNumber = @LineNumber
				  and AdjustmentNumber = @AdjustmentNumber
				  and TransferToKey is null -- ignore records transferred out
			end 	  
	    else  -- not a summary broadcast order
			begin
				-- have any of the spots on this line been invoiced?
				if exists (select 1 from tPurchaseOrderDetail (nolock)
				            where PurchaseOrderKey = @PurchaseOrderKey
				              and LineNumber = @LineNumber
				              and AdjustmentNumber = @AdjustmentNumber
				              and isnull(InvoiceLineKey,0) > 0)
					begin
						if @SelectUpdate = 1 OR @AllowChangesAfterClientInvoice = 1 -- if changes are allowed after invoice
							update tPurchaseOrderDetail
							   set PurchaseOrderKey = @PurchaseOrderKey,
								   ProjectKey = @ProjectKey,
								   TaskKey = @TaskKey,
								   ItemKey = @ItemKey,
								   ClassKey = @ClassKey,
								   ShortDescription = @ShortDescription,
								   UnitCost = @UnitCost,
								   UnitDescription = @UnitDescription,
								   TotalCost = Round(@TotalCost, 2),
								   UnitRate = @UnitRate,
								   Billable = @Billable,
								   Markup = @Markup,
								   BillableCost = Round(@BillableCost, 2),
								   LongDescription = @LongDescription,
								   CustomFieldKey = @CustomFieldKey,
								   OrderDays = @OrderDays,
								   OrderTime = @OrderTime,
								   OrderLength = @OrderLength,
								   Taxable = @Taxable,
								   Taxable2 = @Taxable2,
								   OfficeKey = @OfficeKey,
								   DepartmentKey = @DepartmentKey,
								   Quantity1 = @Quantity1,
								   Quantity2 = @Quantity2,
								   LineType = @LineType,
								   MediaPremiumKey = @MediaPremiumKey,
								   PremiumAmountType = @PremiumAmountType,
								   PremiumPct = @PremiumPct,
								   GrossAmount = @GrossAmount,
								   Commission = @Commission,
								   PCurrencyID = @PCurrencyID,
								   PExchangeRate = @PExchangeRate,
								   PTotalCost = ROUND(@PTotalCost,2),
								   DetailVendorKey = @DetailVendorKey,
								   Bucket = @Bucket,
								   SalesTaxAmount = @SalesTaxAmount,
								   SalesTax1Amount = @SalesTax1Amount,
								   SalesTax2Amount = @SalesTax2Amount,
								   MaterialsSent = @MaterialsSent,
					               MaterialsSentDate = @MaterialsSentDate
						 where PurchaseOrderKey = @PurchaseOrderKey 
							   and LineNumber = @LineNumber
							   and AdjustmentNumber = @AdjustmentNumber		
							   and TransferToKey is null -- ignore records transferred out
						-- else, do nothing, only update spot level info
					end
				else  -- no spots have been invoiced, update line level information
					update tPurchaseOrderDetail
					    set PurchaseOrderKey = @PurchaseOrderKey,
						    ProjectKey = @ProjectKey,
							TaskKey = @TaskKey,
							ItemKey = @ItemKey,
							ClassKey = @ClassKey,
							ShortDescription = @ShortDescription,
							UnitCost = @UnitCost,
							UnitDescription = @UnitDescription,
							TotalCost = Round(@TotalCost, 2),
							UnitRate = @UnitRate,
							Billable = @Billable,
							Markup = @Markup,
							BillableCost = Round(@BillableCost, 2),
							LongDescription = @LongDescription,
							CustomFieldKey = @CustomFieldKey,
							OrderDays = @OrderDays,
							OrderTime = @OrderTime,
							OrderLength = @OrderLength,
							Taxable = @Taxable,
							Taxable2 = @Taxable2,
							OfficeKey = @OfficeKey,
							DepartmentKey = @DepartmentKey,
							LineType = @LineType,
							Quantity1 = @Quantity1,
							Quantity2 = @Quantity2,
							MediaPremiumKey = @MediaPremiumKey,
							PremiumAmountType = @PremiumAmountType,
							PremiumPct = @PremiumPct,
							GrossAmount = @GrossAmount,
							Commission = @Commission,
							PCurrencyID = @PCurrencyID,
							PExchangeRate = @PExchangeRate,
							PTotalCost = ROUND(@PTotalCost,2),
							DetailVendorKey = @DetailVendorKey,
							Bucket = @Bucket,
							SalesTaxAmount = @SalesTaxAmount,
			                SalesTax1Amount = @SalesTax1Amount,
                            SalesTax2Amount = @SalesTax2Amount,
							MaterialsSent = @MaterialsSent,
			                MaterialsSentDate = @MaterialsSentDate
					  where PurchaseOrderKey = @PurchaseOrderKey 
						and LineNumber = @LineNumber
						and AdjustmentNumber = @AdjustmentNumber				
						and TransferToKey is null -- ignore records transferred out
			end
	else -- not a broadcast order, update POs and IOs
	BEGIN
		-- for IO, check if we can change
		IF @POKind = 1 And @InvoiceLineKey > 0 And @NoFinancialUpdate = 0 And @AllowChangesAfterClientInvoice = 0 AND @SelectUpdate = 0 
			RETURN -4
	
		UPDATE
			tPurchaseOrderDetail
		SET
			PurchaseOrderKey = @PurchaseOrderKey,
			ProjectKey = @ProjectKey,
			TaskKey = @TaskKey,
			ItemKey = @ItemKey,
			ClassKey = @ClassKey,
			ShortDescription = @ShortDescription,
			Quantity = @Quantity,
			UnitCost = @UnitCost,
			UnitDescription = @UnitDescription,
			TotalCost = Round(@TotalCost, 2),
			UnitRate = @UnitRate,
			Billable = @Billable,
			Markup = @Markup,
			BillableCost = Round(@BillableCost, 2),
			LongDescription = @LongDescription,
			CustomFieldKey = @CustomFieldKey,
			DetailOrderDate = @DetailOrderDate,
			DetailOrderEndDate = @DetailOrderEndDate,
			UserDate1 = @UserDate1,
			UserDate2 = @UserDate2,
			UserDate3 = @UserDate3,
			UserDate4 = @UserDate4,
			UserDate5 = @UserDate5,
			UserDate6 = @UserDate6,
			OrderDays = @OrderDays,
			OrderTime = @OrderTime,
			OrderLength = @OrderLength,
			Taxable = @Taxable,
			Taxable2 = @Taxable2,
			OfficeKey = @OfficeKey,
			DepartmentKey = @DepartmentKey,
			Quantity1 = @Quantity1,
			Quantity2 = @Quantity2,
			LineType = @LineType,
			MediaPremiumKey = @MediaPremiumKey,
			PremiumAmountType = @PremiumAmountType,
			PremiumPct = @PremiumPct,
			GrossAmount = @GrossAmount,
			Commission = @Commission,
			PCurrencyID = @PCurrencyID,
			PExchangeRate = @PExchangeRate,
			PTotalCost = ROUND(@PTotalCost,2),
			DetailVendorKey = @DetailVendorKey,
			Bucket = @Bucket,
			SalesTaxAmount = @SalesTaxAmount,
			SalesTax1Amount = @SalesTax1Amount,
            SalesTax2Amount = @SalesTax2Amount,
			MaterialsSent = @MaterialsSent,
			MaterialsSentDate = @MaterialsSentDate,
			InteractiveAdUnitName = @InteractiveAdUnitName
		WHERE
			PurchaseOrderDetailKey = @PurchaseOrderDetailKey 
	END

	IF @MaterialsSent = 0
	BEGIN
	  UPDATE tPurchaseOrder
	  SET    MaterialsSent = 0
	  WHERE PurchaseOrderKey = @PurchaseOrderKey
	END
	 

	exec sptPurchaseOrderDetailUpdateApprover @PurchaseOrderKey
		
	exec sptPurchaseOrderRollupAmounts @PurchaseOrderKey

	EXEC sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1 
	IF @ProjectKey <> @OldProjectKey
		EXEC sptProjectRollupUpdate @OldProjectKey, 5, 1, 1, 1, 1 
	
RETURN @PurchaseOrderDetailKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spCMPurge]'
GO
IF OBJECT_ID(N'[dbo].[spCMPurge]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[spCMPurge]
	@MonthsToKeep INT = 9
AS

/*
|| When      Who Rel      What
|| 2/26/09   CRG 10.5.0.0 (sptCalendarReminderPurge) Created to keep the tCalendarReminder table as small as possible. 
||                        This SP will be run by the ScheduleUpdate service in TaskManager.
|| 06/11/09  QMD 10.5.0.0 Created new proc to handle all purges. The purge proc is called from the Task Manager
|| 09/01/09  QMD 10.5.0.9 Added logic to clean up tSyncActivity.
|| 09/18/09  CRG 10.5.1.0 Added code to ensure that tCalendarReminder dates are valid before it tries to cast it as a date.
|| 09/15/10  QMD 10.5.3.5 Added delete for tCalendarAttendeeUpdateLog
|| 08/31/11  CRG 10.5.4.7 Added tWebDavLog
|| 02/10/14  KMC 10.5.7.7 Added tEmailSendLog
|| 02/19/14  KMC 10.5.7.7 Added tWMJLog
|| 03/27/14  CRG 10.5.7.8 Added tBuyUpdateLog and tBuyUpdateLogDetail
|| 11/03/14  CRG 10.5.8.6 Added tVPaymentLog
|| 04/28/15  KMC 10.5.9.1 Added tSyncCalendar
|| 06/27/16  KMC 10.6.0.5 Added tApiLog
|| 08/03/16  KMC 10.6.0.6 Removed tApiLog per Quinton.  Will add separate logging and cleanup for API
|| 04/12/17  KMC 10.6.1.5 Added tApiLog
|| 08/16/18  CRG 10.8.9.0 Now removing tCalendarReminder rows with invalid dates to prevent error when casting as smalldatetime
|| 08/20/18  CRG 18.9.0   Added tTaskUserHourLog and tTaskUserHour Snapshot
|| 03/06/20  CRG 20.0.4.0 Added tGridPrint
|| 07/24/20  CRG 20.0.8.0 Added tEmailData and tUrl
|| 09/23/20  CRG 20.1.0.0 Added tEmailError
|| 10/23/20  CRG 20.1.1.0 Added tCrossProjectPredsErrors
|| 12/10/20  CRG 21.0.1.0 Added tTaskSummaryTaskErrors
|| 04/02/21  CRG 21.04.18 Added tScheduleProcessLog, tScheduleProcessCrossProjectPredLog, and tScheduleProcessCrossProjectLog
|| 05/12/21  CRG 21.06.20 Added tRTNLog
|| 07/15/21  QMD 21.08.20 Changed email logs to 2 months
|| 10/21/21  GAR 21.12.19 (DEV2501-514) Added tSlackLog
|| 10/25/21  CRG 21.11.14 Added tBurnChartLog
|| 12/14/21  QMD 22.01.16 Added tRTNQueue
|| 01/05/22  CRG 22.01.23 (582743) Added tBlockoutCacheLog
|| 01/10/22  QMD 22.01.23 (582691) changed tapilog to 7 days
|| 02/04/22  QMD 22.02.23 (582691) changed tapilog to 90 days
|| 05/17/22  CRG 22.05.15 Added tDBLog
|| 06/22/22  CRG 22.07.17 Changed tDBLog purge to be based on CompleteTime
|| 07/01/22  KMC 22.07.17 Added purge of tAppHistory
|| 10/21/22  CRG 22.11.20 (615895) Added tReminderCacheLog
|| 11/29/22  CRG 22.12.18 Added tReminderCacheGenerationLog and tReminderCacheErrorLog
|| 12/05/22  GAR 22.12.18 (DEV2605-691) Added tAvalaraLog
|| 04/25/23  CRG 23.06.18 (630097) Added tSMSSendLog
|| 08/28/24  CRG 24.10.20 (681784) Created to log the RTN refresh requests coming back from client browsers
|| 01/02/25  KMC 25.01.19 Added tBackupLog
|| 03/06/25  CRG 25.04.20 (696816) Added call to spPurgeBurnChart
|| 06/13/25  CRG 25.07.20 Added tScheduleBatch and tScheduleBatchDetail
|| 09/02/25  KMC 25.09.21 Removed tWMJLog since not being used
|| 09/11/25  KMC 25.09.21 Changed tEmailSendLog from 2 months to 60 days
|| 03/18/26  CRG 25.04.19 Added tAutoEvent and tAutoEventAction
*/

DECLARE @CalendarLog_MonthsToKeep INT 
SELECT	@CalendarLog_MonthsToKeep = 3

DECLARE @EmailLog_DaysToKeep INT
SELECT	@EmailLog_DaysToKeep = 60

DECLARE	@BuyLog_MonthsToKeep INT
SELECT	@BuyLog_MonthsToKeep = 13

DECLARE	@DaysToKeep int
SELECT	@DaysToKeep = 2

DECLARE	@VPaymentLog_MonthsToKeep INT
SELECT	@VPaymentLog_MonthsToKeep = 6

DECLARE	@ApiLog_DaysToKeep INT
SELECT	@ApiLog_DaysToKeep = 90

DECLARE	@TaskUserHour_DaysToKeep INT
SELECT	@TaskUserHour_DaysToKeep = 14

DELETE	tCalendarReminder
WHERE	EventMonth < 0
	OR	EventMonth > 11
	OR	EventDay <= 0
	OR	EventDay > 31 --Won''t catch all invalid dates, but it''ll help
	OR	EventYear <= 0
	OR	EventYear > 2079 

DELETE	tCalendarReminder
WHERE	ISDATE(CAST(EventMonth + 1 as varchar) + ''/'' + CAST(EventDay as varchar) + ''/'' + CAST(EventYear as varchar)) = 0

--EventMonth + 1 because the months are stored 0 based for easier use in Flex
DELETE	tCalendarReminder
WHERE	DATEDIFF(DAY,
				CAST(CAST(EventMonth + 1 as varchar) + ''/'' + CAST(EventDay as varchar) + ''/'' + CAST(EventYear as varchar) as smalldatetime),
				GETDATE()) > @DaysToKeep
				
DELETE	tCalendarAttendeeUpdateLog
WHERE	CalendarUpdateLogKey IN (
		SELECT	CalendarUpdateLogKey
		FROM	tCalendarUpdateLog (NOLOCK)
		WHERE	DATEDIFF(MONTH, ActionDate, GETDATE()) > @CalendarLog_MonthsToKeep
		)

DELETE	tCalendarUpdateLog
WHERE	DATEDIFF(MONTH, ActionDate, GETDATE()) > @CalendarLog_MonthsToKeep

DELETE	tUserUpdateLog
WHERE	DATEDIFF(MONTH, ModifiedDate, GETDATE()) > @MonthsToKeep

DELETE	tWebDavLog
WHERE	DATEDIFF(MONTH, ActionDate, GETDATE()) > @MonthsToKeep
				
DELETE	tEmailSendLog
WHERE	DATEDIFF(DAY, ActionDate, GETDATE()) > @EmailLog_DaysToKeep

DELETE	tVPaymentLog
WHERE	DATEDIFF(MONTH, ActionDate, GETDATE()) > @VPaymentLog_MonthsToKeep

DELETE	tBuyUpdateLogDetail
WHERE	BuyUpdateLogKey IN (
		SELECT	BuyUpdateLogKey
		FROM	tBuyUpdateLog (NOLOCK)
		WHERE	DATEDIFF(MONTH, ActionDate, GETDATE()) > @BuyLog_MonthsToKeep
		)

DELETE	tBuyUpdateLog
WHERE	DATEDIFF(MONTH, ActionDate, GETDATE()) > @BuyLog_MonthsToKeep
				
-- Clean up the tSyncActivity table leaving only the most recent unique record.				
DELETE	sa 
FROM	tSyncActivity sa, (	SELECT MAX(LastSync) AS LastSyncDate , CompanyKey, SourceURI, CMFolderKey, UserKey 
										FROM tSyncActivity (NOLOCK)
										GROUP BY CompanyKey, SourceURI, UserKey,CMFolderKey) s
WHERE	sa.SourceURI = s.SourceURI
		AND sa.CompanyKey = s.CompanyKey
		AND sa.UserKey = s.UserKey
		AND ISNULL(sa.CMFolderKey,'''') = ISNULL(s.CMFolderKey,'''')
		AND sa.LastSync < s.LastSyncDate
		
-- Remove anything in tSyncCalendar that has been there for more than a day
-- since the records should be instantly processed.
DELETE tSyncCalendar
 WHERE DATEDIFF(DAY, DateUpdated, GETDATE()) >= 1

DELETE	tApiLog
WHERE	DATEDIFF(DAY, ActionDate, GETDATE()) > @ApiLog_DaysToKeep

--TaskUserHour log tables
DELETE	tTaskUserHourSnapshot
WHERE	TaskUserHourLogKey IN (SELECT TaskUserHourLogKey FROM tTaskUserHourLog (nolock) WHERE DATEDIFF(DAY, SnapshotTime, GETUTCDATE()) > @TaskUserHour_DaysToKeep)

DELETE	tTaskUserHourLog
WHERE	DATEDIFF(DAY, SnapshotTime, GETUTCDATE()) > @TaskUserHour_DaysToKeep

DELETE	tGridPrint
WHERE	DATEDIFF(DAY, TimeStamp, GETDATE()) > @DaysToKeep

DELETE	tEmailData
WHERE	DATEDIFF(DAY, DateAdded, GETDATE()) > 7

DELETE	tUrl
WHERE	DATEDIFF(MONTH, DateExpires, GETDATE()) > @CalendarLog_MonthsToKeep --Per Ken, we want to keep the URL''s around for a few months for debugging purposes

DELETE	tEmailError
WHERE	DATEDIFF(MONTH, ErrorTimeStamp, GETDATE()) > @CalendarLog_MonthsToKeep

DELETE	tCrossProjectPredsErrors
WHERE	DATEDIFF(MONTH, AddedToErrorLog, GETDATE()) > @CalendarLog_MonthsToKeep

DELETE	tTaskSummaryTaskErrors
WHERE	DATEDIFF(MONTH, AddedToErrorLog, GETDATE()) > @CalendarLog_MonthsToKeep

DELETE	tScheduleProcessCrossProjectPredLog
FROM	tScheduleProcessCrossProjectPredLog
INNER JOIN tScheduleProcessLog l ON tScheduleProcessCrossProjectPredLog.ScheduleProcessKey = l.ScheduleProcessKey
WHERE	DATEDIFF(DAY, l.StartTime, GETUTCDATE()) > @TaskUserHour_DaysToKeep

DELETE	tScheduleProcessCrossProjectLog
FROM	tScheduleProcessCrossProjectLog
INNER JOIN tScheduleProcessLog l ON tScheduleProcessCrossProjectLog.ScheduleProcessKey = l.ScheduleProcessKey
WHERE	DATEDIFF(DAY, l.StartTime, GETUTCDATE()) > @TaskUserHour_DaysToKeep

DELETE	tScheduleProcessLog
WHERE	DATEDIFF(DAY, StartTime, GETUTCDATE()) > @TaskUserHour_DaysToKeep

DELETE	tRTNLog
WHERE	DATEDIFF(DAY, ActionDate, GETUTCDATE()) > 5

DELETE	tRTNClientLog
WHERE	DATEDIFF(DAY, ActionDate, GETUTCDATE()) > 5

DELETE	tRTNQueue
WHERE	DATEDIFF(DAY, ActionDate, GETUTCDATE()) > 5

DELETE	tSlackLog
WHERE	DATEDIFF(MONTH, ActionDate, GETUTCDATE()) > 1

DELETE	tBurnChartLog
WHERE	DATEDIFF(DAY, StartTime, GETUTCDATE()) > 2

DELETE	tBlockoutCacheLog
WHERE	DATEDIFF(DAY, StartTime, GETUTCDATE()) > 2

DELETE	tDBLog
WHERE	DATEDIFF(DAY, CompleteTime, GETUTCDATE()) > 7

DELETE tAppHistory 
WHERE DATEDIFF(MONTH, DateAdded, GETUTCDATE()) > 3

DELETE	tReminderCacheLog
WHERE	DATEDIFF(DAY, SendTime, GETUTCDATE()) > 14

DELETE	tReminderCacheGenerationLog
WHERE	DATEDIFF(DAY, GenerationTime, GETUTCDATE()) > 45

DELETE	tReminderCacheErrorLog
WHERE	DATEDIFF(DAY, ErrorTimestamp, GETUTCDATE()) > 45

DELETE	tAvalaraLog
WHERE	DATEDIFF(MONTH, ActionDate, GETUTCDATE()) > 3

DELETE	tSMSSendLog
WHERE	DATEDIFF(DAY, ActionDate, GETUTCDATE()) > 5

DELETE	tBackupLog
WHERE	DateCreated IS NOT NULL AND DATEDIFF(MONTH, DateCreated, GETDATE()) > @MonthsToKeep

DELETE	tScheduleBatchDetail
FROM	tScheduleBatchDetail dtl
INNER JOIN tScheduleBatch b ON dtl.ScheduleBatchKey = b.ScheduleBatchKey
WHERE	DATEDIFF(DAY, b.DateAdded, GETUTCDATE()) > 3

DELETE	tScheduleBatch
WHERE	DATEDIFF(DAY, DateAdded, GETUTCDATE()) > 3

DELETE	tAutoEvent
WHERE	DATEDIFF(DAY, EventDate, GETUTCDATE()) > 30

DELETE	tAutoEventAction
WHERE	DATEDIFF(DAY, StartTime, GETUTCDATE()) > 30

EXEC spPurgeBurnChart'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIGetScheduleDetails]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIGetScheduleDetails]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[spApiAIGetScheduleDetails]
(
	@CompanyKey int,
	@UserKey int,
	@ProjectNumber varchar(300),
	@UserID varchar(300) = NULL
)
As	

Declare @ProjectKey int
Declare @RestrictToGLCompany int
Declare @SecurityGroupKey int
Declare @FilterUserKey int

-- If UserID is provided, try to find the UserKey
Set @FilterUserKey = null
If @UserID is not null and @UserID != ''''
Begin
	-- Try to find by UserID first, then by name (using LIKE for partial matches)
	Select @FilterUserKey = UserKey
	From tUser (nolock)
	Where ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
	  and (UserID like ''%'' + @UserID + ''%'' 
	  or Email + ''|'' +FirstName + '' '' + LastName like ''%'' + @UserID + ''%'')
End

-- Get ProjectKey from ProjectNumber
Select @ProjectKey = ProjectKey 
From tProject (nolock) 
Where CompanyKey = @CompanyKey 
  and ProjectNumber = @ProjectNumber

-- Return empty result if project not found
If @ProjectKey is null
Begin
	Select 
		projectKey = 0,
		projectNumber = '''',
		projectName = '''',
		description = '''',
		planStart = null,
		planComplete = null,
		clientKey = 0,
		clientID = '''',
		clientName = ''''
	Where 1 = 0
	Return
End

-- Check if user has GL company restriction
Select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0) 
From tPreference (nolock) 
Where CompanyKey = @CompanyKey

-- Get user''s security group
Select @SecurityGroupKey = SecurityGroupKey 
From tUser (nolock) 
Where UserKey = @UserKey

-- Create temp table to check project access
Create Table #projectAccess (ProjectKey int)
Insert into #projectAccess (ProjectKey)
Select @ProjectKey

-- Apply GL company security if enabled
If @RestrictToGLCompany = 1
Begin
	Delete #projectAccess 
	Where ProjectKey in (
		Select p.ProjectKey 
		From tProject p (nolock)
		Where p.ProjectKey = @ProjectKey
		  and p.GLCompanyKey not in (
			  Select GLCompanyKey 
			  From tUserGLCompanyAccess (nolock) 
			  Where UserKey = @UserKey
		  )
	)
End

-- Check if user needs to be assigned to the project
Declare @CheckAssignment int
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''
)
Begin
	Select @CheckAssignment = 0
End

-- Apply assignment check if needed
If @CheckAssignment = 1
Begin
	Delete #projectAccess 
	Where ProjectKey not in (
		Select ProjectKey 
		From tAssignment (nolock)
		Where UserKey = @UserKey
	)
End

-- Return project details if user has access, otherwise return empty
Select 
	p.ProjectNumber as projectNumber,
	p.ProjectName as projectName,
	p.Description as description,
	p.StartDate as planStart,
	p.CompleteDate as planComplete,
	c.CustomerID as clientID,
	c.CompanyName as clientName
From tProject p (nolock)
Inner Join tCompany c (nolock) on c.CompanyKey = p.ClientKey
Inner Join #projectAccess pa on pa.ProjectKey = p.ProjectKey
Where p.ProjectKey = @ProjectKey

-- Cleanup
Drop Table #projectAccess

-- Return all tasks for the project with predecessor/successor information
Select 
	t.TaskKey as taskKey,
	t.TaskID as taskID,
	t.TaskName as taskName,
	t.Description as description,
	t.PlanStart as planStart,
	t.PlanComplete as planComplete,
	t.ActStart as actStart,
	t.ActComplete as actComplete,
	t.EstHours as estHours,
	t.TotalActualHours as actHours,
	t.PercComp as percentComplete,
	t.PredecessorsComplete as predecessorsComplete,
	t.SummaryTaskKey as parentTaskKey,
	t.ProjectOrder as displayOrder,
	-- Subquery for predecessors (tasks this task depends on)
	(
		Select pt.TaskID as taskID,
			   pt.TaskName as task,
			   p.Lag as lagDays,
			   p.Type as lagType
		From tTaskPredecessor p (nolock)
		Inner Join tTask pt (nolock) on pt.TaskKey = p.PredecessorKey
		Where p.TaskKey = t.TaskKey
		For JSON Path
	) as predecessors,
	-- Subquery for successors (tasks that depend on this task)
	(
		Select st.TaskID as taskID,
			   st.TaskName as task,
			   p.Lag as lagDays,
			   p.Type as lagType
		From tTaskPredecessor p (nolock)
		Inner Join tTask st (nolock) on st.TaskKey = p.PredecessorKey
		Where p.PredecessorKey = t.TaskKey
		For JSON Path
	) as successors
From tTask t (nolock)
Where t.ProjectKey = @ProjectKey
  and (@FilterUserKey is null or exists (
	  Select 1 
	  From tTaskUser tu (nolock)
	  Where tu.TaskKey = t.TaskKey
		and tu.UserKey = @FilterUserKey
  ))
Order by t.ProjectOrder

-- Return all assignments for the project tasks
Select 
	t.TaskKey as taskKey,
	s.ServiceCode as serviceCode,
	s.Description as service,
	u.FirstName as firstName,
	u.LastName as lastName,
	tu.Hours as allocatedHours,
	ISNULL(tu.APlanStart, t.PlanStart) as assignmentPlanStart,
	ISNULL(tu.APlanComplete, t.PlanComplete) as assignmentPlanComplete,
	tu.PercComp as assignmentPercentComplete
From tTaskUser tu (nolock)
Inner Join tTask t (nolock) on t.TaskKey = tu.TaskKey
Left Outer Join tUser u (nolock) on u.UserKey = tu.UserKey
Left Outer Join tService s (nolock) on s.ServiceKey = tu.ServiceKey
Where t.ProjectKey = @ProjectKey
  and (@FilterUserKey is null or tu.UserKey = @FilterUserKey)


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

SELECT
	i.CompanyKey, 
	isnull(il.TargetGLCompanyKey, i.GLCompanyKey) as GLCompanyKey, 
	p.CustomFieldKey,
	c.CustomFieldKey AS CustomFieldKey2,
    bcu.CustomFieldKey AS CustomFieldKey3,
	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,
	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_ForecastDetail]'
GO
IF OBJECT_ID(N'[dbo].[vReport_ForecastDetail]', 'V') IS NOT NULL
EXEC sp_executesql N'





ALTER view [dbo].[vReport_ForecastDetail]
as

/*
|| When      Who Rel      What
|| 10/04/17  GHL 10.621  (364058) Created for enhancement
||                       similar to query in sptForecastDetailItemGetList
|| 09/02/20  RLB 20.100  (523772) making anything using user name common format
|| 03/13/23  RLB 23.04.16 (629165) Adding Office Color and Department Color and Service Color
|| 04/24/26  GAR 26.05.17 (727129) Adding Account Manager, Client, Currency, Campaign, and Project Type
*/

/*
Forecast details (in tForecastDetail) are:
 invoice, approved project, potential project, opportunity, retainer, item, service

retainer, item, service do not have underlying items in tForecastDetailItem
so we do:
- 1 query (including tForecastDetailItem) for invoice, approved project, potential project, opportunity
- 1 query for retainer
- 1 query for service
- 1 query for item
*/

SELECT
	-- Forecast section
	f.ForecastKey
	,f.CompanyKey
	,f.GLCompanyKey
	,f.ForecastName AS [Forecast Name]
	,cast(f.StartMonth as varchar(2)) AS [Forecast Start Month]
	,cast(f.StartYear as varchar(4)) AS [Forecast Start Year]
	,CASE f.SpreadExpense 
		WHEN 0 THEN ''From the Start''
		WHEN 1 THEN ''To the End''
		WHEN 2 THEN ''Evenly''
	END AS [Spread Expense]
	,f.CreatedDate AS [Forecast Created Date]
	,LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Created By]
	,f.UpdatedDate AS [Updated Date]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Updated By]
	,glc.GLCompanyID AS [Company ID]
	,glc.GLCompanyName AS [Company Name]

	-- Forecast detail section
	-- These are the main entities projects/invoices/etc..
	,case fd.Entity
	    when ''tInvoice'' then ''Invoice''
		when ''tItem'' then ''Item''
		when ''tService'' then ''Service''
		when ''tLead'' then ''Opportunity''
		when ''tProject-Approved'' then ''Approved Project''
		when ''tProject-Potential'' then ''Potential Project''
		when ''tRetainer'' then ''Retainer''
	end as [Forecast Detail Type]

	,fd.EntityName as [Detail Name] -- project #/invoice #, etc...
	,fd.StartDate as [Detail Start Date]
	,fd.Months as [Detail Months]
	,fd.Probability as [Detail Probability]

	-- Forecast detail item section
	,case fdi.Entity
		when ''tLead-Labor'' then ''Opportunity Labor''
		when ''tLead-Production'' then ''Opportunity Production''
		when ''tLead-Media'' then ''Opportunity Media''
		when ''tInvoiceLine'' then ''Invoice Line''
		when ''tEstimateTaskExpense'' then ''Estimate Expense''
		when ''tEstimateTaskLabor'' then ''Estimate Labor''
		when ''tEstimateTask'' then ''Estimate Task'' 
	end as [Detail Item Type]

	,cast(round((fdi.Prior * fd.Probability) / 100.0000, 2)  as money) as [Prior]
	,cast(round((fdi.Month1 * fd.Probability) / 100.0000, 2)  as money) as [Month 1]
	,cast(round((fdi.Month2 * fd.Probability) / 100.0000, 2)  as money) as [Month 2]
	,cast(round((fdi.Month3 * fd.Probability) / 100.0000, 2)  as money) as [Month 3]
	,cast(round((fdi.Month4 * fd.Probability) / 100.0000, 2)  as money) as [Month 4]
	,cast(round((fdi.Month5 * fd.Probability) / 100.0000, 2)  as money) as [Month 5]
	,cast(round((fdi.Month6 * fd.Probability) / 100.0000, 2)  as money) as [Month 6]
	,cast(round((fdi.Month7 * fd.Probability) / 100.0000, 2)  as money) as [Month 7]
	,cast(round((fdi.Month8 * fd.Probability) / 100.0000, 2)  as money) as [Month 8]
	,cast(round((fdi.Month9 * fd.Probability) / 100.0000, 2)  as money) as [Month 9]
	,cast(round((fdi.Month10 * fd.Probability) / 100.0000, 2)  as money) as [Month 10]
	,cast(round((fdi.Month11 * fd.Probability) / 100.0000, 2)  as money) as [Month 11]
	,cast(round((fdi.Month12 * fd.Probability) / 100.0000, 2)  as money) as [Month 12]
	,cast(round((fdi.NextYear * fd.Probability) / 100.0000, 2)  as money) as [Next Year]
	,cast(round((fdi.Total * fd.Probability) / 100.0000, 2)  as money) as [Total]

	,case isnull(fdi.AtNet, 0)
		when 0 then ''NET''
		when 1 then ''GROSS''
	end as [Detail Item At Net] 

	 ,gl.AccountNumber as [Account Number]
     ,gl.AccountName as [Account Name]
	 ,gl.AccountNumber + ''-'' + gl.AccountName as [Account Full Name]
	,t.TaskID as [Task ID]
	,t.TaskName as [Task Name]
	,isnull(t.TaskID + ''-'', '''') + t.TaskName as [Task Full Name]

	,case when fdi.Entity = ''tEstimateTaskLabor'' then e_labor.EstimateName 
			when fdi.Entity = ''tEstimateTaskExpense'' then e_exp.EstimateName
			when fdi.Entity = ''tEstimateTask'' then e_task.EstimateName
	end as [Estimate Name]
	,case when fdi.Entity = ''tEstimateTaskLabor'' then e_labor.EstimateNumber 
			when fdi.Entity = ''tEstimateTaskExpense'' then e_exp.EstimateNumber
			when fdi.Entity = ''tEstimateTask'' then e_task.EstimateNumber
	end as [Estimate Number]
	
	,i.ItemID as [Item ID]
	,i.ItemName as [Item Name]
	,i.ItemID + ''-'' + i.ItemName as [Item Full Name]

	,s.ServiceCode as [Service Code]
	,s.Description [Service Description]
	,s.ServiceCode + ''-'' + s.Description as [Service Full Description]
	,s.ServiceColor as [Service Color]
			
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,o.OfficeID + ''-''+ o.OfficeName as [Office Full Name]
	,o.OfficeColor as [Office Color]

	,d.DepartmentName as [Department Name]
	,d.DepartmentColor as [Department Color]
			
	,c.ClassID as [Class ID]
	,c.ClassName as [Class Name]
	,c.ClassID + ''-'' + c.ClassName as [Class Full Name]

	,seg.SegmentName as [Segment Name]
	,u.UserName as [User Name]
	,il.LineSubject as [Invoice Line] 

	,am.UserName as [Account Manager]
	,case when cli.CustomerID is null then cli.CompanyName else isnull(cli.CustomerID + ''-'' + cli.CompanyName,'''') end as [Client ID]
	,fd.CurrencyID as [Currency]
	,isnull(isnull(campaign.CampaignID, pCamp.CampaignID), ''No Campaign'') as [Campaign ID]
	,case when fd.Entity in (''tProject-Potential'', ''tProject-Approved'') then pt.ProjectTypeName else opp_pt.ProjectTypeName end as [Project Type]

FROM
	tForecast f (nolock)
	inner join tForecastDetail fd (nolock) on f.ForecastKey = fd.ForecastKey
	left join tForecastDetailItem fdi (nolock) on fd.ForecastDetailKey = fdi.ForecastDetailKey -- left join because some do not have details

	LEFT JOIN tGLCompany glc (nolock) ON f.GLCompanyKey = glc.GLCompanyKey
	LEFT JOIN tUser u1 (NOLOCK) ON f.CreatedBy = u1.UserKey
	LEFT JOIN tUser u2 (NOLOCK) ON f.UpdatedBy = u2.UserKey

	left join tGLAccount gl (nolock) on fdi.GLAccountKey = gl.GLAccountKey
	left join tTask t (nolock) on fdi.TaskKey = t.TaskKey
	left join tItem i (nolock) on fdi.ItemKey = i.ItemKey
	left join tService s (nolock) on fdi.ServiceKey = s.ServiceKey
	left join vUserName u (nolock) on fdi.UserKey = u.UserKey
	left join tOffice o (nolock) on fdi.OfficeKey = o.OfficeKey
	left join tDepartment d (nolock) on fdi.DepartmentKey = d.DepartmentKey
	left join tClass c (nolock) on fdi.ClassKey = c.ClassKey

	left join tEstimateTaskExpense ete (nolock) on fdi.EntityKey = ete.EstimateTaskExpenseKey 
	left join tEstimate e_exp (nolock) on ete.EstimateKey = e_exp.EstimateKey
	left join tEstimate e_labor (nolock) on fdi.EntityKey = e_labor.EstimateKey
	left join tEstimateTask et (nolock) on fdi.EntityKey = et.EstimateTaskKey
	left join tEstimate e_task (nolock) on et.EstimateKey = e_task.EstimateKey
		 
	left join tInvoiceLine il (nolock) on fdi.EntityKey = il.InvoiceLineKey

	left join tCampaignSegment seg (nolock) on fdi.CampaignSegmentKey = seg.CampaignSegmentKey

	left join vUserName am (nolock) on fd.AccountManagerKey = am.UserKey
	left join tCompany cli (nolock) on fd.ClientKey = cli.CompanyKey
	left join tCampaign campaign (nolock) on fd.EntityKey = campaign.CampaignKey and fd.Entity in (''tCampaign'', ''tCampaign-Approved'')
	left join tProject p (nolock) on fd.EntityKey = p.ProjectKey and fd.Entity in (''tProject-Potential'', ''tProject-Approved'')
	left join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left join tLead l (nolock) on fd.EntityKey = l.LeadKey and fd.Entity = ''tLead''
	left join tProjectType opp_pt (nolock) on l.ProjectTypeKey = opp_pt.ProjectTypeKey
	left join tCampaign pCamp (nolock) on p.CampaignKey = pCamp.CampaignKey

where fd.Entity in (''tInvoice'', ''tLead'', ''tProject-Approved'', ''tProject-Potential'')
and fdi.Total <> 0 

UNION ALL

SELECT
	-- Forecast section
	f.ForecastKey
	,f.CompanyKey
	,f.GLCompanyKey
	,f.ForecastName AS [Forecast Name]
	,cast(f.StartMonth as varchar(2)) AS [Forecast Start Month]
	,cast(f.StartYear as varchar(4)) AS [Forecast Start Year]
	,CASE f.SpreadExpense 
		WHEN 0 THEN ''From the Start''
		WHEN 1 THEN ''To the End''
		WHEN 2 THEN ''Evenly''
	END AS [Spread Expense]
	,f.CreatedDate AS [Forecast Created Date]
	,LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Created By]
	,f.UpdatedDate AS [Updated Date]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Updated By]
	,glc.GLCompanyID AS [Company ID]
	,glc.GLCompanyName AS [Company Name]

	-- Forecast detail section
	-- These are the main entities projects/invoices/etc..
	,''Retainer'' as [Forecast Detail Type]

	,fd.EntityName as [Detail Name] -- project #/invoice #, etc...
	,fd.StartDate as [Detail Start Date]
	,fd.Months as [Detail Months]
	,fd.Probability as [Detail Probability]

	-- Forecast detail item section
	,''Retainer'' as [Detail Item Type]

	,cast(round((fd.Prior * fd.Probability) / 100.0000, 2)  as money) as [Prior]
	,cast(round((fd.Month1 * fd.Probability) / 100.0000, 2)  as money) as [Month 1]
	,cast(round((fd.Month2 * fd.Probability) / 100.0000, 2)  as money) as [Month 2]
	,cast(round((fd.Month3 * fd.Probability) / 100.0000, 2)  as money) as [Month 3]
	,cast(round((fd.Month4 * fd.Probability) / 100.0000, 2)  as money) as [Month 4]
	,cast(round((fd.Month5 * fd.Probability) / 100.0000, 2)  as money) as [Month 5]
	,cast(round((fd.Month6 * fd.Probability) / 100.0000, 2)  as money) as [Month 6]
	,cast(round((fd.Month7 * fd.Probability) / 100.0000, 2)  as money) as [Month 7]
	,cast(round((fd.Month8 * fd.Probability) / 100.0000, 2)  as money) as [Month 8]
	,cast(round((fd.Month9 * fd.Probability) / 100.0000, 2)  as money) as [Month 9]
	,cast(round((fd.Month10 * fd.Probability) / 100.0000, 2)  as money) as [Month 10]
	,cast(round((fd.Month11 * fd.Probability) / 100.0000, 2)  as money) as [Month 11]
	,cast(round((fd.Month12 * fd.Probability) / 100.0000, 2)  as money) as [Month 12]
	,cast(round((fd.NextYear * fd.Probability) / 100.0000, 2)  as money) as [Next Year]
	,cast(round((fd.Total * fd.Probability) / 100.0000, 2)  as money) as [Total]

	,null as [Detail Item At Net] 

	,gl.AccountNumber as [Account Number]
    ,gl.AccountName as [Account Name]
	,gl.AccountNumber + ''-'' + gl.AccountName as [Account Full Name]
	,null as [Task ID]
	,null as [Task Name]
	,null as [Task Full Name]

	,null as [Estimate Name]
	,null as [Estimate Number]

	,null as [Item ID]
	,null as [Item Name]
	,null as [Item Full Name]

	,null as [Service Code]
	,null as [Service Description]
	,null as [Service Full Description]
	,null as [Service Color]
			
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,o.OfficeID + ''-''+ o.OfficeName as [Office Full Name]
	,o.OfficeColor as [Office Color]

	,null as [Department Name]
	,null as [Department Color]
			
	,c.ClassID as [Class ID]
	,c.ClassName as [Class Name]
	,c.ClassID + ''-'' + c.ClassName as [Class Full Name]

	,null as [Segment Name]
	,null as [User Name]
	,null as [Invoice Line] 

	,am.UserName as [Account Manager]
	,case when cli.CustomerID is null then cli.CompanyName else isnull(cli.CustomerID + ''-'' + cli.CompanyName,'''') end as [Client ID]
	,fd.CurrencyID as [Currency]
	,isnull(isnull(campaign.CampaignID, pCamp.CampaignID), ''No Campaign'') as [Campaign ID]
	,case when fd.Entity in (''tProject-Potential'', ''tProject-Approved'') then pt.ProjectTypeName else opp_pt.ProjectTypeName end as [Project Type]

FROM
	tForecast f (nolock)
	inner join tForecastDetail fd (nolock) on f.ForecastKey = fd.ForecastKey
	left join tForecastDetailItem fdi (nolock) on fd.ForecastDetailKey = fdi.ForecastDetailKey -- left join because some do not have details

	LEFT JOIN tGLCompany glc (nolock) ON f.GLCompanyKey = glc.GLCompanyKey
	LEFT JOIN tUser u1 (NOLOCK) ON f.CreatedBy = u1.UserKey
	LEFT JOIN tUser u2 (NOLOCK) ON f.UpdatedBy = u2.UserKey

	inner join tRetainer r (nolock) on fd.EntityKey = r.RetainerKey
	left outer join tGLAccount gl (nolock) on r.SalesAccountKey = gl.GLAccountKey
	left outer join tOffice o (nolock) on r.OfficeKey = o.OfficeKey
	left outer join tClass c (nolock) on r.ClassKey = c.ClassKey

	left join vUserName am (nolock) on fd.AccountManagerKey = am.UserKey
	left join tCompany cli (nolock) on fd.ClientKey = cli.CompanyKey
	left join tCampaign campaign (nolock) on fd.EntityKey = campaign.CampaignKey and fd.Entity in (''tCampaign'', ''tCampaign-Approved'')
	left join tProject p (nolock) on fd.EntityKey = p.ProjectKey and fd.Entity in (''tProject-Potential'', ''tProject-Approved'')
	left join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left join tLead l (nolock) on fd.EntityKey = l.LeadKey and fd.Entity = ''tLead''
	left join tProjectType opp_pt (nolock) on l.ProjectTypeKey = opp_pt.ProjectTypeKey
	left join tCampaign pCamp (nolock) on p.CampaignKey = pCamp.CampaignKey

where fd.Entity in (''tRetainer'')

UNION ALL

SELECT
	-- Forecast section
	f.ForecastKey
	,f.CompanyKey
	,f.GLCompanyKey
	,f.ForecastName AS [Forecast Name]
	,cast(f.StartMonth as varchar(2)) AS [Forecast Start Month]
	,cast(f.StartYear as varchar(4)) AS [Forecast Start Year]
	,CASE f.SpreadExpense 
		WHEN 0 THEN ''From the Start''
		WHEN 1 THEN ''To the End''
		WHEN 2 THEN ''Evenly''
	END AS [Spread Expense]
	,f.CreatedDate AS [Forecast Created Date]
	,LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Created By]
	,f.UpdatedDate AS [Updated Date]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Updated By]
	,glc.GLCompanyID AS [Company ID]
	,glc.GLCompanyName AS [Company Name]

	-- Forecast detail section
	-- These are the main entities projects/invoices/etc..
	,''Service'' as [Forecast Detail Type]

	,fd.EntityName as [Detail Name] -- project #/invoice #, etc...
	,fd.StartDate as [Detail Start Date]
	,fd.Months as [Detail Months]
	,fd.Probability as [Detail Probability]

	-- Forecast detail item section
	,''Service'' as [Detail Item Type]

	,cast(round((fd.Prior * fd.Probability) / 100.0000, 2)  as money) as [Prior]
	,cast(round((fd.Month1 * fd.Probability) / 100.0000, 2)  as money) as [Month 1]
	,cast(round((fd.Month2 * fd.Probability) / 100.0000, 2)  as money) as [Month 2]
	,cast(round((fd.Month3 * fd.Probability) / 100.0000, 2)  as money) as [Month 3]
	,cast(round((fd.Month4 * fd.Probability) / 100.0000, 2)  as money) as [Month 4]
	,cast(round((fd.Month5 * fd.Probability) / 100.0000, 2)  as money) as [Month 5]
	,cast(round((fd.Month6 * fd.Probability) / 100.0000, 2)  as money) as [Month 6]
	,cast(round((fd.Month7 * fd.Probability) / 100.0000, 2)  as money) as [Month 7]
	,cast(round((fd.Month8 * fd.Probability) / 100.0000, 2)  as money) as [Month 8]
	,cast(round((fd.Month9 * fd.Probability) / 100.0000, 2)  as money) as [Month 9]
	,cast(round((fd.Month10 * fd.Probability) / 100.0000, 2)  as money) as [Month 10]
	,cast(round((fd.Month11 * fd.Probability) / 100.0000, 2)  as money) as [Month 11]
	,cast(round((fd.Month12 * fd.Probability) / 100.0000, 2)  as money) as [Month 12]
	,cast(round((fd.NextYear * fd.Probability) / 100.0000, 2)  as money) as [Next Year]
	,cast(round((fd.Total * fd.Probability) / 100.0000, 2)  as money) as [Total]

	,null as [Detail Item At Net] 

	,gl.AccountNumber as [Account Number]
    ,gl.AccountName as [Account Name]
	,gl.AccountNumber + ''-'' + gl.AccountName as [Account Full Name]
	,null as [Task ID]
	,null as [Task Name]
	,null as [Task Full Name]

	,null as [Estimate Name]
	,null as [Estimate Number]

	,null as [Item ID]
	,null as [Item Name]
	,null as [Item Full Name]

	,s.ServiceCode as [Service Code]
	,s.Description as [Service Description]
	,s.ServiceCode + ''-'' + s.Description as [Service Full Description]
	,s.ServiceColor as [Service Color]
			
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,o.OfficeID + ''-''+ o.OfficeName as [Office Full Name]
	,o.OfficeColor as [Office Color]

	,d.DepartmentName as [Department Name]
	,d.DepartmentColor as [Department Color]
			
	,c.ClassID as [Class ID]
	,c.ClassName as [Class Name]
	,c.ClassID + ''-'' + c.ClassName as [Class Full Name]

	,null as [Segment Name]
	,null as [User Name]
	,null as [Invoice Line] 

	,am.UserName as [Account Manager]
	,case when cli.CustomerID is null then cli.CompanyName else isnull(cli.CustomerID + ''-'' + cli.CompanyName,'''') end as [Client ID]
	,fd.CurrencyID as [Currency]
	,isnull(isnull(campaign.CampaignID, pCamp.CampaignID), ''No Campaign'') as [Campaign ID]
	,case when fd.Entity in (''tProject-Potential'', ''tProject-Approved'') then pt.ProjectTypeName else opp_pt.ProjectTypeName end as [Project Type]

FROM
	tForecast f (nolock)
	inner join tForecastDetail fd (nolock) on f.ForecastKey = fd.ForecastKey
	left join tForecastDetailItem fdi (nolock) on fd.ForecastDetailKey = fdi.ForecastDetailKey -- left join because some do not have details

	LEFT JOIN tGLCompany glc (nolock) ON f.GLCompanyKey = glc.GLCompanyKey
	LEFT JOIN tUser u1 (NOLOCK) ON f.CreatedBy = u1.UserKey
	LEFT JOIN tUser u2 (NOLOCK) ON f.UpdatedBy = u2.UserKey

	inner join tService s (nolock) on fd.EntityKey = s.ServiceKey
	left outer join tGLAccount gl (nolock) on s.GLAccountKey = gl.GLAccountKey
	left outer join tOffice o (nolock) on fd.OfficeKey = o.OfficeKey
	left outer join tClass c (nolock) on s.ClassKey = c.ClassKey
	left outer join tDepartment d (nolock) on s.DepartmentKey = d.DepartmentKey

	left join vUserName am (nolock) on fd.AccountManagerKey = am.UserKey
	left join tCompany cli (nolock) on fd.ClientKey = cli.CompanyKey
	left join tCampaign campaign (nolock) on fd.EntityKey = campaign.CampaignKey and fd.Entity in (''tCampaign'', ''tCampaign-Approved'')
	left join tProject p (nolock) on fd.EntityKey = p.ProjectKey and fd.Entity in (''tProject-Potential'', ''tProject-Approved'')
	left join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left join tLead l (nolock) on fd.EntityKey = l.LeadKey and fd.Entity = ''tLead''
	left join tProjectType opp_pt (nolock) on l.ProjectTypeKey = opp_pt.ProjectTypeKey
	left join tCampaign pCamp (nolock) on p.CampaignKey = pCamp.CampaignKey

where fd.Entity in (''tService'')

UNION ALL

SELECT
	-- Forecast section
	f.ForecastKey
	,f.CompanyKey
	,f.GLCompanyKey
	,f.ForecastName AS [Forecast Name]
	,cast(f.StartMonth as varchar(2)) AS [Forecast Start Month]
	,cast(f.StartYear as varchar(4)) AS [Forecast Start Year]
	,CASE f.SpreadExpense 
		WHEN 0 THEN ''From the Start''
		WHEN 1 THEN ''To the End''
		WHEN 2 THEN ''Evenly''
	END AS [Spread Expense]
	,f.CreatedDate AS [Forecast Created Date]
	,LTRIM(RTRIM(ISNULL(u1.FirstName + '' '','''')  + ISNULL(u1.LastName,''''))) AS [Created By]
	,f.UpdatedDate AS [Updated Date]
	,LTRIM(RTRIM(ISNULL(u2.FirstName + '' '','''')  + ISNULL(u2.LastName,''''))) AS [Updated By]
	,glc.GLCompanyID AS [Company ID]
	,glc.GLCompanyName AS [Company Name]

	-- Forecast detail section
	-- These are the main entities projects/invoices/etc..
	,''Misc Item'' as [Forecast Detail Type]

	,fd.EntityName as [Detail Name] -- project #/invoice #, etc...
	,fd.StartDate as [Detail Start Date]
	,fd.Months as [Detail Months]
	,fd.Probability as [Detail Probability]

	-- Forecast detail item section
	,''Misc Item'' as [Detail Item Type]

	,cast(round((fd.Prior * fd.Probability) / 100.0000, 2)  as money) as [Prior]
	,cast(round((fd.Month1 * fd.Probability) / 100.0000, 2)  as money) as [Month 1]
	,cast(round((fd.Month2 * fd.Probability) / 100.0000, 2)  as money) as [Month 2]
	,cast(round((fd.Month3 * fd.Probability) / 100.0000, 2)  as money) as [Month 3]
	,cast(round((fd.Month4 * fd.Probability) / 100.0000, 2)  as money) as [Month 4]
	,cast(round((fd.Month5 * fd.Probability) / 100.0000, 2)  as money) as [Month 5]
	,cast(round((fd.Month6 * fd.Probability) / 100.0000, 2)  as money) as [Month 6]
	,cast(round((fd.Month7 * fd.Probability) / 100.0000, 2)  as money) as [Month 7]
	,cast(round((fd.Month8 * fd.Probability) / 100.0000, 2)  as money) as [Month 8]
	,cast(round((fd.Month9 * fd.Probability) / 100.0000, 2)  as money) as [Month 9]
	,cast(round((fd.Month10 * fd.Probability) / 100.0000, 2)  as money) as [Month 10]
	,cast(round((fd.Month11 * fd.Probability) / 100.0000, 2)  as money) as [Month 11]
	,cast(round((fd.Month12 * fd.Probability) / 100.0000, 2)  as money) as [Month 12]
	,cast(round((fd.NextYear * fd.Probability) / 100.0000, 2)  as money) as [Next Year]
	,cast(round((fd.Total * fd.Probability) / 100.0000, 2)  as money) as [Total]

	,null as [Detail Item At Net] 

	,gl.AccountNumber as [Account Number]
    ,gl.AccountName as [Account Name]
	,gl.AccountNumber + ''-'' + gl.AccountName as [Account Full Name]
	,null as [Task ID]
	,null as [Task Name]
	,null as [Task Full Name]

	,null as [Estimate Name]
	,null as [Estimate Number]

	,i.ItemID as [Item ID]
	,i.ItemName as [Item Name]
	,i.ItemID + ''-'' + i.ItemName as [Item Full Name]

	,null as [Service Code]
	,null as [Service Description]
	,null as [Service Full Description]
	,null as [Service Color]
			
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,o.OfficeID + ''-''+ o.OfficeName as [Office Full Name]
	,o.OfficeColor as [Office Color]

	,d.DepartmentName as [Department Name]
	,d.DepartmentColor as [Department Color]
			
	,c.ClassID as [Class ID]
	,c.ClassName as [Class Name]
	,c.ClassID + ''-'' + c.ClassName as [Class Full Name]

	,null as [Segment Name]
	,null as [User Name]
	,null as [Invoice Line] 

	,am.UserName as [Account Manager]
	,case when cli.CustomerID is null then cli.CompanyName else isnull(cli.CustomerID + ''-'' + cli.CompanyName,'''') end as [Client ID]
	,fd.CurrencyID as [Currency]
	,isnull(isnull(campaign.CampaignID, pCamp.CampaignID), ''No Campaign'') as [Campaign ID]
	,case when fd.Entity in (''tProject-Potential'', ''tProject-Approved'') then pt.ProjectTypeName else opp_pt.ProjectTypeName end as [Project Type]

FROM
	tForecast f (nolock)
	inner join tForecastDetail fd (nolock) on f.ForecastKey = fd.ForecastKey
	left join tForecastDetailItem fdi (nolock) on fd.ForecastDetailKey = fdi.ForecastDetailKey -- left join because some do not have details

	LEFT JOIN tGLCompany glc (nolock) ON f.GLCompanyKey = glc.GLCompanyKey
	LEFT JOIN tUser u1 (NOLOCK) ON f.CreatedBy = u1.UserKey
	LEFT JOIN tUser u2 (NOLOCK) ON f.UpdatedBy = u2.UserKey

	inner join tItem i (nolock) on fd.EntityKey = i.ItemKey
	left outer join tGLAccount gl (nolock) on i.SalesAccountKey = gl.GLAccountKey
	left outer join tOffice o (nolock) on fd.OfficeKey = o.OfficeKey
	left outer join tClass c (nolock) on i.ClassKey = c.ClassKey
	left outer join tDepartment d (nolock) on i.DepartmentKey = d.DepartmentKey

	left join vUserName am (nolock) on fd.AccountManagerKey = am.UserKey
	left join tCompany cli (nolock) on fd.ClientKey = cli.CompanyKey
	left join tCampaign campaign (nolock) on fd.EntityKey = campaign.CampaignKey and fd.Entity in (''tCampaign'', ''tCampaign-Approved'')
	left join tProject p (nolock) on fd.EntityKey = p.ProjectKey and fd.Entity in (''tProject-Potential'', ''tProject-Approved'')
	left join tProjectType pt (nolock) on p.ProjectTypeKey = pt.ProjectTypeKey
	left join tLead l (nolock) on fd.EntityKey = l.LeadKey and fd.Entity = ''tLead''
	left join tProjectType opp_pt (nolock) on l.ProjectTypeKey = opp_pt.ProjectTypeKey
	left join tCampaign pCamp (nolock) on p.CampaignKey = pCamp.CampaignKey

where fd.Entity in (''tItem'')



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

ALTER VIEW [dbo].[vReport_Invoice_TransactionsCosts]
AS

/*
|| When     Who Rel    What
|| 03/27/15 WDF 10.5.9.0 (231686) Derived from vReport_Invoice_Transactions.  Added [Transaction Item Type] and [Transaction Total Cost Net Amount]
|| 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.
|| 07/25/17 GHL 10.6.1.8 (355845) Added Markup = 100 * Gross/Net -100
||                        derived from Gross = Net (1 + Markup/100)   
|| 08/27/18 GHL 18.9.0.0 (416918) Added Parent Invoice field
|| 04/15/20 GAR 20.0.5.0 (510595) Added Posting Month
|| 06/25/20 AMP 20.0.7.0 (518668) Added Invoice Created Date
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 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 for line and transaction
|| 04/07/25 AMP 25.05.18 (697727) Added Media Plan ID and Media Plan Name
|| 05/07/25 RLS 25.06.15 (698744) Added  CustomFieldKey3 for Campaign custom fields
|| 04/13/26 GAR 26.05.17 (726197) Added Project Address if it exists for Avalara
*/

SELECT 
	pti.CompanyKey, 
	pti.GLCompanyKey, 
	p.CustomFieldKey,
	c.CustomFieldKey as CustomFieldKey2,
	cp.CustomFieldKey as CustomFieldKey3,
	cd.DivisionName as [Division Name],
	cd.DivisionID as [Division ID],
	pd.ProductName as [Product Name],
	pd.ProductID as [Product ID],
	pti.InvoiceNumber AS [Invoice Number],
	pti.InvoiceDate AS [Invoice Date], 
	pti.PostingDate as [Posting Date],
	DATENAME(Year, pti.PostingDate) + ''_'' + RIGHT(''0'' + CAST(DATEPART(Month, pti.PostingDate) AS VARCHAR(2)), 2) AS [Posting Month],
	pti.DueDate AS [Due Date], 
	case pti.AdvanceBill when 1 then ''YES'' else ''NO'' end as [Advance Billing Invoice],
	case i.ParentInvoice when 1 then ''YES'' else ''NO'' end as [Parent 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],
	pti.ClientName AS [Client Name], 
	pti.CustomerID AS [Client ID], 
	pti.CustomerID + '' - '' + pti.ClientName AS [Client Full Name], 
	pti.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],
	pc.CompanyName as [Parent Company Name],
	pt.TermsDescription AS Terms, 
	glAR.AccountNumber AS [AR Account Number],
	glAR.AccountName AS [AR Account Name],
	glAR.AccountNumber + '' - '' + glAR.AccountName AS [AR 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], 
	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],
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where AdvBillInvoiceKey = i.InvoiceKey),0) as [Advance Bill Unapplied],
	ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where InvoiceKey = i.InvoiceKey),0) as [Applied Advance Billings],
	Case pti.InvoiceStatus
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case pti.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
		end as [Invoice Status],
	case i.Downloaded when 1 then ''YES'' else ''NO'' end as Downloaded, 
	case pti.Posted when 1 then ''YES'' else ''NO'' end as Posted,
	case i.Printed when 1 then ''YES'' else ''NO'' end as Printed, 
	case i.Emailed when 1 then ''YES'' else ''NO'' end as Emailed, 
	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],
	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],
	glSales.AccountNumber + '' - '' + glSales.AccountName AS [Sales GL Account],
    glSales.AccountNumber AS [Sales GL Account Number],
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Invoice Approver],
	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],
	prt.ProjectTypeName as [Line Project Type],
	prt.ProjectTypeColor as [Line Project Type Color],
	cp.CampaignName as [Campaign Name],
	cp.CampaignID as [Campaign ID],
	ct.CompanyTypeName as [Company Type],
	pti.ContactName as [Printed Name],
	pti.PrimaryContactName as [Client Primary Contact],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Sales Person],
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Estimate Total],
	(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]

	,pti.TransactionDate as [Transaction Date]
	,pti.Type as [Transaction Type]
	,pti.ItemType as [Transaction Item Type]
	,pti.ItemID as [Transaction Item ID]
	,pti.ItemName as [Transaction Item Name]
	,pti.Quantity as [Transaction Quantity]
	,pti.UnitCost as [Transaction Unit Amount]
	,pti.TotalCostNet as [Transaction Total Cost Net Amount]
	,pti.TotalCost as [Transaction Total Amount]
	,pti.BillableCost as [Transaction Billable Amount]
	,ISNULL(pti.AmountBilled, 0) as [Transaction Amount Billed]

	,case when pti.Type = ''LABOR'' then 0
	else
		case when pti.TotalCost = 0 then 0
		else ROUND(((pti.AmountBilled * 100.00) / pti.TotalCost ) - 100.00, 2)
		end
	end as [Transaction Markup]

	,pti.Description as [Transaction Description]
	,pti.Comments as [Transaction Comments]
	,pti.BilledDifference as [Transaction Billed Difference]
	,p2.ProjectNumber as [Transaction Project Number]
	,p2.ProjectName as [Transaction Project Name]
	,p2.ProjectNumber + '' - '' + p2.ProjectName as [Transaction Project Full Name]
	,p2pt.ProjectTypeName as [Transaction Project Type]
	,p2pt.ProjectTypeColor as [Transaction Project Type Color]
	,o2.OfficeID as [Transaction Office ID]
	,o2.OfficeName as [Transaction Office Name]
	,o2.OfficeColor as [Transaction Office Color]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,o.OfficeColor as [Office Color]
	,d.DepartmentName as Department
	,d.DepartmentColor as [Department Color]
	,CASE il.Entity
		WHEN ''tService'' THEN s.ServiceCode
		WHEN ''tItem'' THEN item.ItemID
		ELSE NULL
	END AS [Billing Item ID]
	,t.TaskID AS [Task ID]
	,t.TaskName as [Task Name]
	,tat.TaskAssignmentType as [Task Type]
	,t.Description as [Task Description]
    ,pti.VendorID as [Vendor ID]
    ,pti.VendorName as [Vendor Name]
    ,pti.PurchaseOrderNumber as [Order Number] 
    ,pti.MediaEstimateID as [Media Estimate ID]
    ,pti.MediaEstimateName as [Media Estimate Name]
    ,pti.BilledComment as [Billed Comment]
    ,p.ProjectKey
    ,i.CurrencyID as [Currency]
    ,i.ExchangeRate as [Exchange Rate]
	,trs.RateSheetName as [Service Rate Sheet]
	,irs.RateSheetName as [Item Rate Sheet]
	,pti.TitleName as [Billing Title Name]
	,pti.TitleID as [Billing Title ID]
	,ret.Title as [Line Retainer Name]
	,i.DateCreated as [Invoice Created Date]
	,camp2pm.UserName AS [Campaign Project Manager]
	,cpm.UserName AS [Client Project Manager]
	,ppm.UserName AS [Project Manager]
	,mp2.PlanID  as [Media Plan ID]
	,mp2.PlanName as [Media Plan Name]
	,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 
	INNER JOIN vProjectTransPOInvoice pti (nolock) on pti.InvoiceLineKey = il.InvoiceLineKey
	INNER JOIN tCompany c (nolock) ON pti.ClientKey = c.CompanyKey 
	LEFT OUTER JOIN tCompany pc (nolock) ON c.ParentCompanyKey = pc.CompanyKey 
    LEFT OUTER JOIN tGLAccount glSales (nolock) ON pti.SalesAccountKey = glSales.GLAccountKey
    LEFT OUTER JOIN tGLAccount glAR (nolock) ON i.ARAccountKey = glAR.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 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 u (nolock) on i.PrimaryContactKey = u.UserKey
	--LEFT OUTER JOIN tUser pc (nolock) on c.PrimaryContact = pc.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 tProject p2 (nolock) ON pti.ProjectKey = p2.ProjectKey
	LEFT OUTER Join tTask t (nolock) on pti.TaskKey = t.TaskKey
	LEFT OUTER JOIN tTaskAssignmentType tat (nolock) on t.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey
	LEFT OUTER JOIN tProjectType p2pt (nolock) on p2.ProjectTypeKey = p2pt.ProjectTypeKey
	left outer join tGLCompany glc (nolock) on pti.GLCompanyKey = glc.GLCompanyKey
	left outer join tOffice o (nolock) on il.OfficeKey = o.OfficeKey
	left outer join tOffice o2 (nolock) on p2.OfficeKey = o2.OfficeKey
	left outer join tDepartment d (nolock) on il.DepartmentKey = d.DepartmentKey
	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 tTimeRateSheet trs (nolock) on p.TimeRateSheetKey = trs.TimeRateSheetKey
	left outer join tItemRateSheet irs (nolock) on p.ItemRateSheetKey = irs.ItemRateSheetKey
	left outer join tRetainer ret (nolock) on il.RetainerKey = ret.RetainerKey
	LEFT OUTER JOIN vUserName camp2pm (nolock) on cp.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 
				 (SELECT mp.PlanID, mp.PlanName, pod.PurchaseOrderKey
				  FROM
					  tPurchaseOrderDetail pod
					  INNER JOIN tMediaPlanDetail mpd (nolock) on mpd.PurchaseOrderDetailKey =  pod.PurchaseOrderDetailKey
					  INNER JOIN tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
				  	  INNER JOIN tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey						
				  GROUP BY mp.PlanID, mp.PlanName, pod.PurchaseOrderKey) AS mp2 on mp2.PurchaseOrderKey = pti.ParentKey
WHERE (il.LineType = 2)

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

	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

	-- Administrators bypass all security checks
	if @IsAdministrator = 0 or @IsAdministrator is null
	begin
		-- Check GL Company security
		select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
		from tPreference (nolock)
		where CompanyKey = @CompanyKey

		if @RestrictToGLCompany = 1 and @ProjectKey is not null
		begin
			-- Get project''s GL company
			select @ProjectGLCompanyKey = GLCompanyKey
			from tProject (nolock)
			where ProjectKey = @ProjectKey

			-- Check if user has access to this GL company
			if 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.'', ''projectNumber'')
			end
		end

		-- Check if user needs to be assigned to the project
		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''
		)
		begin
			set @CheckAssignment = 0
		end

		if @CheckAssignment = 1 and @ProjectKey is not null
		begin
			if not exists (
				select 1
				from tAssignment (nolock)
				where ProjectKey = @ProjectKey
				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.'', ''projectNumber'')
			end
		end

		-- 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 (''schedEdit'', ''prjEdit'')
		)
		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

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

		if @DisplayOrder = 1 --This will be inserted directly below the parent
			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		SummaryTaskKey = @ParentTaskKey
			and		DisplayOrder = @DisplayOrder - 1

		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,
			@ParentTaskKey,
			@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].[vReport_Invoice_Transactions]'
GO
IF OBJECT_ID(N'[dbo].[vReport_Invoice_Transactions]', 'V') IS NOT NULL
EXEC sp_executesql N'











ALTER VIEW [dbo].[vReport_Invoice_Transactions]
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.
|| 05/18/07 GHL 8.5    Merged vReport_Invoice and vReport_Transactions
|| 10/11/07 CRG 8.5    Fixed Header Class join
||                     Added Office, Department and GLCompany
|| 11/07/07 CRG 8.5    (10950) Added Billing Item ID
|| 11/7/07  GWG 8.5	   Added transaction project type
|| 01/11/08 GHL 8.501  (19211) Added Task info 
|| 09/24/08 GHL 10.009 (35422) Getting now SalesAccountKey from service or item instead of invoice line
|| 02/24/09 GWG 10.020 Added the billed difference column
|| 03/17/09  RTC 10.5	  Removed user defined fields.
|| 8/13/09  GWG 10.5.06  Added Sales person to the list
|| 10/13/09 GHL 10.512 (64451) Added Vendor ID and Name
|| 10/30/09 GWG 10.5.1.3 Added Task Description
|| 11/02/09 GHL 10.5.1.3 Added Order Number
|| 12/10/09 GHL 10.514 (68925) Added Estimate ID + Name
|| 01/06/10 RLB 10.516   Added Task Type
|| 03/14/11 GHL 10.542 (105923) Added invoice info such as InvoiceKey, InvoiceNumber to vProjectTransPOInvoice to force IX_tTime_3
||                      Found out that if InvoiceNumber is pulled from vReport_Invoice_Transactions, there is table scan on tTime
||                      If InvoiceNumber is pulled in vProjectTransPOInvoice, there is no table scan on tTime
|| 07/28/11 GHL 10.546  (111859) Added custom fields # 2 and Parent Company 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
|| 03/22/13 WDF 10.5.6.6 (172390) Added BilledComment
|| 11/06/14 GHL 10.5.8.6 (230365) Added currency and exchange rate
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
|| 01/28/15 GHL 10.5.5.8 Added Title data for Abelson
|| 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.
|| 07/25/17 GHL 10.6.1.8 (355845) Added Markup = 100 * Gross/Net -100
||                        derived from Gross = Net (1 + Markup/100)
|| 08/27/18 GHL 18.9.0.0 (416918) Added Parent Invoice field        
|| 06/12/19 MCM 19.0.7.0 (449142) Added Unit Rate from the voucherDetail table which gets pull in thru vProjectTransPOInvoice
|| 01/06/20 AMP 20.0.2.0 (490365) Added ''Station or Publication Name'' from the tCompanyMedia table which gets pulled in thru vProjectTransPOInvoice
|| 04/15/20 GAR 20.0.5.0 (510595) Added Posting Month
|| 05/22/20 AMP 20.0.6.0 (515852) Added Target GL Company Name which gets pull in thru vProjectTransPOInvoice
|| 06/25/20 AMP 20.0.7.0 (518668) Added Invoice Created Date
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 02/15/23 RLS 23.03.19 (627785) Added [Project Status] and [Project Billing Status]
|| 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 for line and transaction
|| 05/07/25 RLS 25.06.15 (698744) Added  CustomFieldKey3 for Campaign custom fields
|| 04/13/26 GAR 26.05.17 (726197) Added Project Address if it exists for Avalara
*/

SELECT 
	pti.CompanyKey, 
	pti.GLCompanyKey, 
	p.CustomFieldKey,
	c.CustomFieldKey as CustomFieldKey2,
	cp.CustomFieldKey as CustomFieldKey3,
	cd.DivisionName as [Division Name],
	cd.DivisionID as [Division ID],
	pd.ProductName as [Product Name],
	pd.ProductID as [Product ID],
	pti.InvoiceNumber AS [Invoice Number], 
	pti.InvoiceDate AS [Invoice Date], 
	pti.PostingDate as [Posting Date],
	DATENAME(Year, pti.PostingDate) + ''_'' + RIGHT(''0'' + CAST(DATEPART(Month, pti.PostingDate) AS VARCHAR(2)), 2) AS [Posting Month],
	pti.DueDate AS [Due Date], 
	case pti.AdvanceBill when 1 then ''YES'' else ''NO'' end as [Advance Billing Invoice],
	case i.ParentInvoice when 1 then ''YES'' else ''NO'' end as [Parent 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],
	pti.ClientName AS [Client Name], 
	pti.CustomerID AS [Client ID], 
	pti.CustomerID + '' - '' + pti.ClientName AS [Client Full Name], 
	pti.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],
	pc.CompanyName as [Parent Company Name],
	pt.TermsDescription AS Terms, 
	glAR.AccountNumber AS [AR Account Number],
	glAR.AccountName AS [AR Account Name],
	glAR.AccountNumber + '' - '' + glAR.AccountName AS [AR 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], 
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL(AmountReceived, 0) - ISNULL(WriteoffAmount, 0) - ISNULL(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],
	ISNULL(i.InvoiceTotalAmount, 0) - ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where AdvBillInvoiceKey = i.InvoiceKey),0) as [Advance Bill Unapplied],
	ISNULL((Select Sum(Amount) from tInvoiceAdvanceBill (nolock) Where InvoiceKey = i.InvoiceKey),0) as [Applied Advance Billings],
	Case pti.InvoiceStatus
		When 1 then ''Not Sent For Approval''
		When 2 then ''Sent For Approval''
		When 3 then ''Rejected''
		When 4 then 
			Case pti.Posted When 1 then ''Posted'' else ''Approved Not Posted'' end
		end as [Invoice Status],
	case i.Downloaded when 1 then ''YES'' else ''NO'' end as Downloaded, 
	case pti.Posted when 1 then ''YES'' else ''NO'' end as Posted,
	case i.Printed when 1 then ''YES'' else ''NO'' end as Printed, 
	case i.Emailed when 1 then ''YES'' else ''NO'' end as Emailed, 
	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],
	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],
	glSales.AccountNumber + '' - '' + glSales.AccountName AS [Sales GL Account],
    glSales.AccountNumber AS [Sales GL Account Number],
	LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS [Invoice Approver],
	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],
	prt.ProjectTypeName as [Line Project Type],
	prt.ProjectTypeColor as [Line Project Type Color],
	cp.CampaignName as [Campaign Name],
	cp.CampaignID as [Campaign ID],
	ct.CompanyTypeName as [Company Type],
	pti.ContactName as [Printed Name],
	pti.PrimaryContactName as [Client Primary Contact],
	LTRIM(RTRIM(ISNULL(sales.FirstName + '' '','''')  + ISNULL(sales.LastName,''''))) AS [Sales Person],
	p.EstLabor + p.ApprovedCOLabor + p.EstExpenses + p.ApprovedCOExpense as [Estimate Total],
	(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]

	,pti.TransactionDate as [Transaction Date]
	,pti.Type as [Transaction Type]
	,pti.ItemID as [Transaction Item ID]
	,pti.ItemName as [Transaction Item Name]
	,pti.Quantity as [Transaction Quantity]
	,pti.UnitCost as [Transaction Unit Amount]
	,pti.TotalCost as [Transaction Total Amount]
	,pti.BillableCost as [Transaction Billable Amount]

	,case when pti.Type = ''LABOR'' then 0
	else
		case when pti.TotalCost = 0 then 0
		else ROUND(((pti.AmountBilled * 100.00) / pti.TotalCost ) - 100.00, 2)
		end
	end as [Transaction Markup]

	,ISNULL(pti.AmountBilled, 0) as [Transaction Amount Billed]
	,pti.Description as [Transaction Description]
	,pti.Comments as [Transaction Comments]
	,pti.BilledDifference as [Transaction Billed Difference]
	,p2.ProjectNumber as [Transaction Project Number]
	,p2.ProjectName as [Transaction Project Name]
	,p2.ProjectNumber + '' - '' + p2.ProjectName as [Transaction Project Full Name]
	,p2pt.ProjectTypeName as [Transaction Project Type]
	,p2pt.ProjectTypeColor as [Transaction Project Type Color]
	,o2.OfficeID as [Transaction Office ID]
	,o2.OfficeName as [Transaction Office Name]
	,o2.OfficeColor as [Transaction Office Color]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,o.OfficeID as [Office ID]
	,o.OfficeName as [Office Name]
	,o.OfficeColor as [Office Color]
	,d.DepartmentName as Department
	,d.DepartmentColor as [Department Color]
	,CASE il.Entity
		WHEN ''tService'' THEN s.ServiceCode
		WHEN ''tItem'' THEN item.ItemID
		ELSE NULL
	END AS [Billing Item ID]
	,t.TaskID AS [Task ID]
	,t.TaskName as [Task Name]
	,tat.TaskAssignmentType as [Task Type]
	,t.Description as [Task Description]
    ,pti.VendorID as [Vendor ID]
    ,pti.VendorName as [Vendor Name]
    ,pti.PurchaseOrderNumber as [Order Number] 
    ,pti.MediaEstimateID as [Media Estimate ID]
    ,pti.MediaEstimateName as [Media Estimate Name]
    ,pti.BilledComment as [Billed Comment]
    ,p.ProjectKey
    ,i.CurrencyID as [Currency]
    ,i.ExchangeRate as [Exchange Rate]
	,trs.RateSheetName as [Service Rate Sheet]
	,irs.RateSheetName as [Item Rate Sheet]
	,pti.TitleName as [Billing Title Name]
	,pti.TitleID as [Billing Title ID]
	,ret.Title as [Line Retainer Name]
	,pti.UnitRate as [Transaction Unit Rate]
    ,pti.MediaName as [Station or Publication Name]	
	,glc2.GLCompanyName as [Target GL Company Name]
	,i.DateCreated as [Invoice Created Date]
	,ISNULL(ps.ProjectStatus,'''') as [Project Status]
	,ISNULL(pb.ProjectBillingStatus, '''') as [Project Billing Status]
	,camp2pm.UserName AS [Campaign Project Manager]
	,cpm.UserName AS [Client Project Manager]
	,ppm.UserName AS [Project Manager]
	,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 
	INNER JOIN vProjectTransPOInvoice pti (nolock) on pti.InvoiceLineKey = il.InvoiceLineKey
	INNER JOIN tCompany c (nolock) ON pti.ClientKey = c.CompanyKey 
	LEFT OUTER JOIN tCompany pc (nolock) ON c.ParentCompanyKey = pc.CompanyKey 
    LEFT OUTER JOIN tGLAccount glSales (nolock) ON pti.SalesAccountKey = glSales.GLAccountKey
    LEFT OUTER JOIN tGLAccount glAR (nolock) ON i.ARAccountKey = glAR.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 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 u (nolock) on i.PrimaryContactKey = u.UserKey
	--LEFT OUTER JOIN tUser pc (nolock) on c.PrimaryContact = pc.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 tProject p2 (nolock) ON pti.ProjectKey = p2.ProjectKey
	LEFT OUTER Join tTask t (nolock) on pti.TaskKey = t.TaskKey
	LEFT OUTER JOIN tTaskAssignmentType tat (nolock) on t.TaskAssignmentTypeKey = tat.TaskAssignmentTypeKey
	LEFT OUTER JOIN tProjectType p2pt (nolock) on p2.ProjectTypeKey = p2pt.ProjectTypeKey
	left outer join tGLCompany glc (nolock) on pti.GLCompanyKey = glc.GLCompanyKey
	left outer join tOffice o (nolock) on il.OfficeKey = o.OfficeKey
	left outer join tOffice o2 (nolock) on p2.OfficeKey = o2.OfficeKey
	left outer join tDepartment d (nolock) on il.DepartmentKey = d.DepartmentKey
	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 tTimeRateSheet trs (nolock) on p.TimeRateSheetKey = trs.TimeRateSheetKey
	left outer join tItemRateSheet irs (nolock) on p.ItemRateSheetKey = irs.ItemRateSheetKey
	left outer join tRetainer ret (nolock) on il.RetainerKey = ret.RetainerKey
	left outer join tGLCompany glc2 (nolock) on pti.TargetGLCompanyKey = glc2.GLCompanyKey
	left outer join tProjectStatus ps on p2.ProjectStatusKey = ps.ProjectStatusKey
	left outer join tProjectBillingStatus pb on p2.ProjectBillingStatusKey = pb.ProjectBillingStatusKey
	LEFT OUTER JOIN vUserName camp2pm (nolock) on cp.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
WHERE (il.LineType = 2)

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddActivity]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddActivity]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER Procedure [dbo].[spApiAIAddActivity]
(
	@CompanyKey int,
	@UserKey int,
	@ProjectNumber varchar(300) = null,
	@TaskID varchar(300) = null,
	@OpportunityID varchar(300) = null,
	@CompanyName varchar(500) = null,
	@ContactName varchar(500) = null,
	@Subject varchar(1000),
	@Body varchar(max) = null,
	@ActivityDate smalldatetime = null,
	@EmailTo varchar(max) = null,
	@AssignedTo varchar(500) = null
)

as --Encrypt

/*
|| When      Who Rel        What
|| 01/20/25  AI  25.01.20   Created - Add activity via API with email recipients
|| 01/21/25  AI  25.01.21   Updated - Added support for opportunities, companies, contacts; made project optional
|| 07/10/25  AI  25.07.10   Added @AssignedTo parameter to look up assigned user by name, email, or UserID
*/

	declare @ProjectKey int
	declare @TaskKey int
	declare @LeadKey int
	declare @ClientCompanyKey int
	declare @ContactKey int
	declare @ActivityKey int
	declare @ErrorCount int
	declare @SecurityGroupKey int
	declare @IsAdministrator bit
	declare @RestrictToGLCompany tinyint
	declare @CheckAssignment tinyint
	declare @ProjectGLCompanyKey int
	declare @RootActivityKey int
	declare @ProjectName varchar(500)
	declare @EntityCount int
	declare @Entity varchar(100)
	declare @AssignedUserKey int

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


	-- Validate required parameters
	-- Validate that either Subject or Body is provided
	if (@Subject is null or LTRIM(RTRIM(@Subject)) = '''') 
	   and (@Body is null or LTRIM(RTRIM(@Body)) = '''')
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''Either Subject or Body must be provided.'', ''subject'')
	end

	-- If only Body is provided, set Subject to first 40 characters
	if (@Subject is null or LTRIM(RTRIM(@Subject)) = '''') 
	   and @Body is not null and LTRIM(RTRIM(@Body)) <> ''''
	begin
		set @Subject = LEFT(LTRIM(RTRIM(@Body)), 40)
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- Look up project if ProjectNumber is provided
	if @ProjectNumber is not null and LTRIM(RTRIM(@ProjectNumber)) <> ''''
	begin
		select @ProjectKey = ProjectKey, @ProjectName = ProjectName
		from tProject (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(ProjectNumber) = UPPER(@ProjectNumber)

		if @ProjectKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Project not found for ProjectNumber: '' + @ProjectNumber + '' - Activity will be created without project link.'', ''projectNumber'')
		end
	end

	-- Look up opportunity if OpportunityID is provided
	if @OpportunityID is not null and LTRIM(RTRIM(@OpportunityID)) <> ''''
	begin
		select @LeadKey = LeadKey
		from tLead (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadID) = UPPER(@OpportunityID)

		if @LeadKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Opportunity not found for OpportunityID: '' + @OpportunityID + '' - Activity will be created without opportunity link.'', ''opportunityID'')
		end
	end

	-- Look up company if CompanyName is provided
	if @CompanyName is not null and LTRIM(RTRIM(@CompanyName)) <> ''''
	begin
		select @ClientCompanyKey = CompanyKey
		from tCompany (nolock)
		where OwnerCompanyKey = @CompanyKey
		and (UPPER(CompanyName) = UPPER(@CompanyName) or UPPER(CustomerID) = UPPER(@CompanyName))

		if @ClientCompanyKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Company not found for CompanyName: '' + @CompanyName + '' - Activity will be created without company link.'', ''companyName'')
		end
	end

	if @ClientCompanyKey is null and @ProjectKey is not null
		Select @ClientCompanyKey = ClientKey from tProject (nolock) Where ProjectKey = @ProjectKey

	-- Look up contact if ContactName is provided
	if @ContactName is not null and LTRIM(RTRIM(@ContactName)) <> ''''
	begin
		select top 1 @ContactKey = UserKey
		from tUser (nolock)
		where ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
		and (UPPER(FirstName + '' '' + LastName) LIKE ''%'' + UPPER(@ContactName) + ''%''
			or UPPER(Email) = UPPER(@ContactName))

		if @ContactKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Contact not found for ContactName: '' + @ContactName + '' - Activity will be created without contact link.'', ''contactName'')
		end
	end

	-- Validate that at least one entity was found
	set @EntityCount = 0
	if @ProjectKey is not null set @EntityCount = @EntityCount + 1
	if @LeadKey is not null set @EntityCount = @EntityCount + 1
	if @ClientCompanyKey is not null set @EntityCount = @EntityCount + 1
	if @ContactKey is not null set @EntityCount = @EntityCount + 1

	if @EntityCount = 0
	begin
		insert into #errors (errorType, errorCode, errorMessage, fieldName)
		values (''error'', ''REQUIRED_FIELD'', ''At least one valid entity (project, opportunity, company, or contact) must be provided.'', ''general'')
	end

	-- Get task key if TaskID is provided (only valid with a project)
	if @TaskID is not null and LTRIM(RTRIM(@TaskID)) <> '''' and @ProjectKey is not null
	begin
		select @TaskKey = TaskKey
		from tTask (nolock)
		where ProjectKey = @ProjectKey
		and UPPER(TaskID) = UPPER(@TaskID)

		if @TaskKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Task not found for TaskID: '' + @TaskID + '' - Activity will be created without task link.'', ''taskID'')
		end
	end

	-- Security checks: Get user''s security group and administrator status
	select @SecurityGroupKey = SecurityGroupKey,
		   @IsAdministrator = Administrator
	from tUser (nolock)
	where UserKey = @UserKey
	and CompanyKey = @CompanyKey

	-- Administrators bypass all security checks
	if @IsAdministrator = 0 or @IsAdministrator is null
	begin
		-- Check GL Company security (only for projects)
		select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
		from tPreference (nolock)
		where CompanyKey = @CompanyKey

		if @RestrictToGLCompany = 1 and @ProjectKey is not null
		begin
			-- Get project''s GL company
			select @ProjectGLCompanyKey = GLCompanyKey
			from tProject (nolock)
			where ProjectKey = @ProjectKey

			-- Check if user has access to this GL company
			if 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.'', ''projectNumber'')
			end
		end

		-- Check if user needs to be assigned to the project (only for projects)
		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''
		)
		begin
			set @CheckAssignment = 0
		end

		if @CheckAssignment = 1 and @ProjectKey is not null
		begin
			if not exists (
				select 1
				from tAssignment (nolock)
				where ProjectKey = @ProjectKey
				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.'', ''projectNumber'')
			end
		end
	end

	if not exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID in (''prjnotes'', ''useActivities'')
		)
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
				values (''error'', ''ACCESS_DENIED'', ''User does not have rights to this feature.'', ''projectNumber'')
		end

	-- Return errors if security checks or validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -103
	end

	-- Create temp table for email recipients
	create table #emailRecipients (
		UserKey int
	)

	if @ContactKey > 0
		insert into #emailRecipients (UserKey) values (@ContactKey)

	-- Parse @EmailTo string if provided
	if @EmailTo is not null and LTRIM(RTRIM(@EmailTo)) <> ''''
	begin
		-- Replace semicolons with commas for uniform splitting
		set @EmailTo = REPLACE(@EmailTo, '';'', '','')

		-- Parse comma-separated values and match to tUser
		declare @RecipientValue varchar(500)
		declare @Position int

		while CHARINDEX('','', @EmailTo) > 0
		begin
			set @Position = CHARINDEX('','', @EmailTo)
			set @RecipientValue = LTRIM(RTRIM(SUBSTRING(@EmailTo, 1, @Position - 1)))
			set @EmailTo = SUBSTRING(@EmailTo, @Position + 1, LEN(@EmailTo))

			if @RecipientValue <> ''''
			begin
				-- Try to match by Email, UserID, or FullName
				insert into #emailRecipients (UserKey)
				select distinct TOP 1 UserKey
				from tUser (nolock)
				where ISNULL(OwnerCompanyKey, CompanyKey) = @CompanyKey
				and Active = 1
				and (
					UPPER(Email) = UPPER(@RecipientValue)
					or UPPER(UserID) = UPPER(@RecipientValue)
					or UPPER(FirstName + '' '' + LastName) LIKE ''%'' + UPPER(@RecipientValue) + ''%''
				)
				and UserKey not in (select UserKey from #emailRecipients where UserKey is not null)
			end
		end

		-- Process the last value (or only value if no commas)
		set @RecipientValue = LTRIM(RTRIM(@EmailTo))
		if @RecipientValue <> ''''
		begin
			insert into #emailRecipients (UserKey)
			select distinct TOP 1 UserKey
			from tUser (nolock)
			where CompanyKey = @CompanyKey
			and Active = 1
			and (
				UPPER(Email) = UPPER(@RecipientValue)
				or UPPER(UserID) = UPPER(@RecipientValue)
				or UPPER(ISNULL(FirstName, '''') + '' '' + ISNULL(LastName, '''')) = UPPER(@RecipientValue)
			)
			and UserKey not in (select UserKey from #emailRecipients where UserKey is not null)
		end
	end
	if @ProjectKey is null
		Select @Entity = ''Activity''
	else
		Select @Entity = ''Diary''

	-- Resolve assigned user: look up by name, email, or UserID if @AssignedTo is provided
	set @AssignedUserKey = @UserKey

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

		if @AssignedUserKey is null
		begin
			set @AssignedUserKey = @UserKey
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Assigned user not found for AssignedTo: '' + @AssignedTo + '' - Activity will be assigned to the requesting user.'', ''assignedTo'')
		end
	end
		

	-- Insert the activity
	insert into tActivity (
		CompanyKey,
		ParentActivityKey,
		RootActivityKey,
		Type,
		Subject,
		ProjectKey,
		TaskKey,
		ContactCompanyKey,
		ContactKey,
		LeadKey,
		AssignedUserKey,
		OriginatorUserKey,
		ActivityDate,
		Notes,
		DateAdded,
		DateUpdated,
		AddedByKey,
		UpdatedByKey,
		GLCompanyKey,
		SendNotification,
		ActivityEntity,
		VisibleToClient,
		UID
	)
	values (
		@CompanyKey,
		0,
		0,
		''Email'',
		@Subject,
		@ProjectKey,
		@TaskKey,
		@ClientCompanyKey,
		@ContactKey,
		@LeadKey,
		@AssignedUserKey,
		@UserKey,
		@ActivityDate,
		@Body,
		getutcdate(),
		getutcdate(),
		@UserKey,
		@UserKey,
		@ProjectGLCompanyKey,
		1,
		@Entity,
		0,
		NEWID()
	)

	set @ActivityKey = SCOPE_IDENTITY()

	-- Set RootActivityKey to itself (common pattern for root activities)
	set @RootActivityKey = @ActivityKey

	update tActivity
	set RootActivityKey = @RootActivityKey
	where ActivityKey = @ActivityKey

	-- Insert email recipients into tActivityEmail
	if exists (select 1 from #emailRecipients where UserKey is not null)
	begin
		insert into tActivityEmail (ActivityKey, UserKey, OriginalUser)
		select @ActivityKey, UserKey, 1
		from #emailRecipients
		where UserKey is not null
	end

	-- Link activity to entities in tActivityLink

	-- Link to project
	if @ProjectKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tProject'', @ProjectKey)
	end

	-- Link to task (if task exists)
	if @TaskKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tTask'', @TaskKey)
	end

	-- Link to opportunity
	if @LeadKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tLead'', @LeadKey)
	end

	-- Link to company
	if @ClientCompanyKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tCompany'', @ClientCompanyKey)
	end

	-- Link to contact
	if @ContactKey is not null
	begin
		insert into tActivityLink (ActivityKey, Entity, EntityKey)
		values (@ActivityKey, ''tContact'', @ContactKey)
	end

	-- Return success with ActivityKey and any warnings
	select errorType, errorCode, errorMessage, fieldName
	from #errors
	where errorType = ''warning''

	select @ProjectName as projectName,
			@ActivityKey as activityKey,
			@ProjectKey as projectKey,
			@ProjectName as projectName,
			@TaskKey as taskKey,
			@LeadKey as leadKey,
			@ContactKey as contactKey,
		   (select COUNT(*) from #emailRecipients where UserKey is not null) as recipientCount

	drop table #errors
	drop table #emailRecipients
	
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spApiAIAddUpdateOpportunity]'
GO
IF OBJECT_ID(N'[dbo].[spApiAIAddUpdateOpportunity]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER Procedure [dbo].[spApiAIAddUpdateOpportunity]
(
	@CompanyKey int,
	@UserKey int,
	@OpportunityID varchar(50) = NULL,
	@Subject varchar(200) = NULL,
	@CompanyName varchar(300) = NULL,
	@ContactName varchar(300) = NULL,
	@ProjectType varchar(100) = NULL,
	@Status varchar(50) = NULL,
	@Stage varchar(50) = NULL, 
	@CurrentStatus varchar(300) = NULL,
	@Probability int = 100,
	@SaleAmount decimal(18,2) = 0,
	@StartDate datetime = NULL,
	@EstCloseDate datetime = NULL,
	@Description varchar(max) = NULL
)

as --Encrypt

/*
|| When      Who Rel        What
|| 01/21/25  AI  25.01.21   Created - Add/Update opportunities via API
*/

	declare @LeadKey int
	declare @ClientCompanyKey int
	declare @ContactKey int
	declare @ProjectTypeKey int
	declare @LeadStatusKey int
	declare @LeadStageKey int
	declare @ErrorCount int
	declare @SecurityGroupKey int
	declare @IsAdministrator bit
	declare @RestrictToGLCompany tinyint
	declare @GLCompanyKey int
	declare @HasAddRight tinyint
	declare @HasEditRight tinyint
	declare @IsUpdate tinyint
	declare @Action varchar(20)

	-- Variables to hold current values for update
	declare @CurrentSubject varchar(200)
	declare @CurrentClientCompanyKey int
	declare @CurrentContactKey int
	declare @CurrentProjectTypeKey int
	declare @CurrentLeadStatusKey int
	declare @CurrentLeadStageKey int
	declare @CurrentProbability int
	declare @CurrentSaleAmount decimal(18,2)
	declare @CurrentStartDate datetime
	declare @CurrentEstCloseDate datetime
	declare @CurrentDescription varchar(max)
	declare @CurrentCurrentStatus varchar(300)

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


	-- Determine if this is an insert or update
	set @IsUpdate = 0
	if @OpportunityID is not null and LTRIM(RTRIM(@OpportunityID)) <> ''''
	begin
		-- Check if opportunity exists
		select @LeadKey = LeadKey,
			   @CurrentSubject = Subject,
			   @CurrentClientCompanyKey = CompanyKey,
			   @CurrentContactKey = ContactKey,
			   @CurrentProjectTypeKey = ProjectTypeKey,
			   @CurrentLeadStatusKey = LeadStatusKey,
			   @CurrentLeadStageKey = LeadStageKey,
			   @CurrentCurrentStatus = CurrentStatus,
			   @CurrentProbability = Probability,
			   @CurrentSaleAmount = SaleAmount,
			   @CurrentStartDate = StartDate,
			   @CurrentEstCloseDate = EstCloseDate,
			   @CurrentDescription = Comments,
			   @GLCompanyKey = GLCompanyKey
		from tLead (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadID) = UPPER(@OpportunityID)

		if @LeadKey is not null
			set @IsUpdate = 1
		else
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''NOT_FOUND'', ''Opportunity not found for OpportunityID: '' + @OpportunityID, ''opportunityID'')
		end
	end

	-- Validate required parameters for insert
	if @IsUpdate = 0
	begin
		if @Subject is null or LTRIM(RTRIM(@Subject)) = ''''
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''REQUIRED_FIELD'', ''Subject is required for new opportunities.'', ''subject'')
		end
	end

	-- Return errors if validation failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -100
	end

	-- For update, merge current values with provided values (NULL means keep current)
	if @IsUpdate = 1
	begin
		set @Subject = ISNULL(@Subject, @CurrentSubject)
		set @Probability = ISNULL(@Probability, @CurrentProbability)
		set @SaleAmount = ISNULL(@SaleAmount, @CurrentSaleAmount)
		set @StartDate = ISNULL(@StartDate, @CurrentStartDate)
		set @EstCloseDate = ISNULL(@EstCloseDate, @CurrentEstCloseDate)
		set @Description = ISNULL(@Description, @CurrentDescription)
		set @CurrentStatus = ISNULL(@CurrentStatus, @CurrentCurrentStatus)

		-- For company/contact, only update if explicitly provided
		if @CompanyName is not null
			set @CurrentClientCompanyKey = NULL  -- Force lookup
		if @ContactName is not null
			set @CurrentContactKey = NULL  -- Force lookup
		if @ProjectType is not null
			set @CurrentProjectTypeKey = NULL  -- Force lookup
		-- For status/stage, only update if explicitly provided
		if @Status is null
			set @LeadStatusKey = @CurrentLeadStatusKey
		if @Stage is null
			set @LeadStageKey = @CurrentLeadStageKey
	end

	-- Look up client company if CompanyName is provided
	if @CompanyName is not null and LTRIM(RTRIM(@CompanyName)) <> ''''
	begin
		select @ClientCompanyKey = CompanyKey
		from tCompany (nolock)
		where OwnerCompanyKey = @CompanyKey
		and (UPPER(CompanyName) = UPPER(@CompanyName) or UPPER(CustomerID) = UPPER(@CompanyName))

		if @ClientCompanyKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''NOT_FOUND'', ''Company not found: '' + @CompanyName + '' - A Company is required for an opportunity.'', ''companyName'')
		end
	end
	else if @IsUpdate = 1
	begin
		set @ClientCompanyKey = @CurrentClientCompanyKey
	end

	-- Look up contact if ContactName is provided
	if @ContactName is not null and LTRIM(RTRIM(@ContactName)) <> ''''
	begin
		select top 1 @ContactKey = ContactKey
		from tContact (nolock)
		where OwnerCompanyKey = @CompanyKey
		and (UPPER(FirstName + '' '' + LastName) = UPPER(@ContactName) 
			or UPPER(LastName + '', '' + FirstName) = UPPER(@ContactName)
			or UPPER(Email) = UPPER(@ContactName))
		and (@ClientCompanyKey is null or CompanyKey = @ClientCompanyKey)

		if @ContactKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Contact not found: '' + @ContactName + '' - Opportunity will be created without contact link.'', ''contactName'')
		end
	end
	else if @IsUpdate = 1
	begin
		set @ContactKey = @CurrentContactKey
	end

	-- Look up project type if provided
	if @ProjectType is not null and LTRIM(RTRIM(@ProjectType)) <> ''''
	begin
		select @ProjectTypeKey = ProjectTypeKey
		from tProjectType (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(ProjectTypeName) = UPPER(@ProjectType)

		if @ProjectTypeKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Project Type not found: '' + @ProjectType + '' - Opportunity will be created without project type.'', ''projectType'')
		end
	end
	else if @IsUpdate = 1
	begin
		set @ProjectTypeKey = @CurrentProjectTypeKey
	end

	-- Look up status key if provided
	if @Status is not null and LTRIM(RTRIM(@Status)) <> ''''
	begin
		select @LeadStatusKey = LeadStatusKey
		from tLeadStatus (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadStatusName) = UPPER(@Status)

		if @LeadStatusKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Status not found: '' + @Status + '' - Default status will be used.'', ''status'')
		end
	end
	else
	begin
		select @LeadStatusKey = LeadStatusKey
		from tLeadStatus (nolock)
		where CompanyKey = @CompanyKey and DisplayOrder = 1
	end

	-- Look up stage key if provided
	if @Stage is not null and LTRIM(RTRIM(@Stage)) <> ''''
	begin
		select @LeadStageKey = LeadStageKey
		from tLeadStage (nolock)
		where CompanyKey = @CompanyKey
		and UPPER(LeadStageName) = UPPER(@Stage)

		if @LeadStageKey is null
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''warning'', ''NOT_FOUND'', ''Stage not found: '' + @Stage + '' - Default stage will be used.'', ''stage'')
		end
	end
	else
	begin
		select @LeadStageKey = LeadStageKey
		from tLeadStage (nolock)
		where CompanyKey = @CompanyKey and DisplayOrder = 1
	end

	-- Get user''s security group and administrator status
	select @SecurityGroupKey = SecurityGroupKey,
		   @IsAdministrator = Administrator,
		   @GLCompanyKey = CASE WHEN @IsUpdate = 0 THEN GLCompanyKey ELSE @GLCompanyKey END
	from tUser (nolock)
	where UserKey = @UserKey
	and CompanyKey = @CompanyKey

	-- Administrators bypass all security checks
	if @IsAdministrator = 0 or @IsAdministrator is null
	begin
		-- Check if user has rights to add or edit opportunities
		set @HasAddRight = 0
		set @HasEditRight = 0

		if exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID = ''addOpp''
		)
		begin
			set @HasAddRight = 1
		end

		if exists (
			select 1
			from tRight r (nolock)
			inner join tRightAssigned ra (nolock) on r.RightKey = ra.RightKey
			where ra.EntityType = ''Security Group''
			and ra.EntityKey = @SecurityGroupKey
			and r.RightID = ''useOpp''
		)
		begin
			set @HasEditRight = 1
		end

		if @IsUpdate = 0 and @HasAddRight = 0
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have permission to add opportunities.'', ''general'')
		end

		if @IsUpdate = 1 and @HasEditRight = 0
		begin
			insert into #errors (errorType, errorCode, errorMessage, fieldName)
			values (''error'', ''ACCESS_DENIED'', ''User does not have permission to edit opportunities.'', ''general'')
		end

		-- Check GL Company security for updates
		if @IsUpdate = 1
		begin
			select @RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0)
			from tPreference (nolock)
			where CompanyKey = @CompanyKey

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

	-- Return errors if security checks failed
	select @ErrorCount = COUNT(*) from #errors where errorType = ''error''
	if @ErrorCount > 0
	begin
		select errorType, errorCode, errorMessage, fieldName
		from #errors
		order by errorType desc, fieldName

		drop table #errors
		return -103
	end

	-- Insert or Update
	if @IsUpdate = 0
	begin
		-- Insert new opportunity
		insert into tLead (
			CompanyKey,
			ContactCompanyKey,
			ContactKey,
			ProjectTypeKey,
			LeadStatusKey,
			LeadStageKey,
			Subject,
			CurrentStatus,
			Probability,
			SaleAmount,
			StartDate,
			EstCloseDate,
			Comments,
			AccountManagerKey,
			GLCompanyKey,
			AddedByKey,
			UpdatedByKey,
			DateAdded,
			DateUpdated
		)
		values (
			@CompanyKey,
			@ClientCompanyKey,
			@ContactKey,
			@ProjectTypeKey,
			@LeadStatusKey,
			@LeadStageKey,
			@Subject,
			@CurrentStatus,
			@Probability,
			@SaleAmount,
			@StartDate,
			@EstCloseDate,
			@Description,
			@UserKey,
			@GLCompanyKey,
			@UserKey,
			@UserKey,
			dbo.fFormatDateNoTime(getutcdate()),
			dbo.fFormatDateNoTime(getutcdate())
		)

		set @LeadKey = SCOPE_IDENTITY()

		-- Generate OpportunityID 
		Select @OpportunityID = ISNULL(Max(LeadID), 0) + 1 from tLead (nolock) 
		Where CompanyKey = @CompanyKey

		update tLead
		set LeadID = @OpportunityID
		where LeadKey = @LeadKey

		set @Action = ''created''
	end
	else
	begin
		-- Update existing opportunity
		update tLead
		set CompanyKey = @ClientCompanyKey,
			ContactKey = @ContactKey,
			ProjectTypeKey = @ProjectTypeKey,
			LeadStatusKey = @LeadStatusKey,
			LeadStageKey = @LeadStageKey,
			Subject = @Subject,
			CurrentStatus = @CurrentStatus,
			Probability = @Probability,
			SaleAmount = @SaleAmount,
			StartDate = @StartDate,
			EstCloseDate = @EstCloseDate,
			Comments = @Description,
			DateUpdated = dbo.fFormatDateNoTime(getutcdate()),
			UpdatedByKey = @UserKey
		where LeadKey = @LeadKey

		-- Track stage change history if stage has changed
		if @CurrentLeadStageKey is not null 
			and @LeadStageKey is not null 
			and @CurrentLeadStageKey <> @LeadStageKey
		begin
			insert into tLeadStageHistory (
				LeadKey,
				LeadStageKey,
				HistoryDate,
				Comment,
				Probability,
				SaleAmount,
				EstCloseDate
			)
			values (
				@LeadKey,
				@LeadStageKey,
				dbo.fFormatDateNoTime(getutcdate()),
				@CurrentStatus,
				@Probability,
				@SaleAmount,
				@EstCloseDate
			)
		end

		set @Action = ''updated''
	end

	-- Return success with OpportunityID and any warnings
	select errorType, errorCode, errorMessage, fieldName
	from #errors
	where errorType = ''warning''

	select @OpportunityID as opportunityID,
		   @Subject as subject,
		   @Action as action

	drop table #errors'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[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)  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].[sptPurchaseOrderCopy]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderCopy]', 'P') IS NOT NULL
EXEC sp_executesql N'






ALTER PROCEDURE [dbo].[sptPurchaseOrderCopy]
	@PurchaseOrderKey int,
	@CreatedByKey int = null,
	@OrderedBy nvarchar(200) = null,
	@CopyProjectKey int = null,
	@CopyTaskKey int = null,
	@CopyClassKey int = null,
	@CopyMediaEstimateKey int = null,
	@CopyVendorKey int = null,
	@CopyCompanyMediaKey int = null,
	@oIdentity INT OUTPUT

AS --ENCRYPT

  /*
  || When     Who Rel   What
  || 02/26/07 GHL 8.4   Added project rollup section 
  || 07/18/07 BSH 8.5   (9659)Insert GLCompanyKey, OfficeKey, DepartmentKey         
  || 10/22/08 GHL 10.5  (37963) Added CompanyAddressKey param
  || 09/14/09 GHL 10.5  Added logic for Transfers
  || 10/08/09 GHL 10.512 (65124) Bubbling up the errors from PO insert to show on the UI
  || 11/11/11 MAS 10.5.5.0 (121862) Added Print options, 1 to print all lines, 2 print just open lines
  || 12/19/11 RLB 10.5.5.1 (121862) Fixed SP for new Print option
  || 10/19/12 RLB 10.5.6.1 (157356) When coping setting the createdby and orderbyname to the session user
  || 12/03/12 MAS 10.5.6.2 (161425) Changed the length of @ShortDescription from 200 to 300
  || 12/12/12 WDF 10.5.6.3 (145601) Over-ride Fields for PO Copy
  || 12/06/13 GHL 10.5.7.5 If ordered by is null, get user name from CreatedByKey 
  || 12/16/13 GHL 10.5.7.5 Added currency info to PO header and lines
  || 12/26/13 GHL 10.5.7.5 Added saving of line taxes + other taxes
  || 04/29/14 RLB 10.5.7.9 (214240) increasing short description
  || 06/26/14 WDF 10.5.8.1 (220913) Set PODate to current date rather than date of copied PO
  || 08/28/14 RLB 10.5.8.3 (217703) Fixed PODate pulling in time part
  || 10/02/14 WDF 10.5.8.4 (231800) Set DueDate to current date rather than date of copied PO unless it is Null
  || 08/11/15 GHL 10.5.9.5 (263071) LongDescription is now varchar(max)
  || 02/02/16 WDF 10.6.0.0 (287755) Update the Purchase Order''s detail lines with their original Line Numbers
  || 05/15/18 GHL 18.6.0.0 (400969) Added protection against missing tObjectFieldSet record for custom field on detail
  ||                       This was causing the CF on the header to be copied to the detail
  || 08/22/19 AMP 19.0.9.0 (459791) Added Vendor and Station/Publication when copying a PO,IO, or BO
  || 09/18/19 AMP 19.0.9.0 (479863) Bug fix for 459791 - Set Default value for @CopyCompanyMediaKey = null so that the copy feature works in Classic
  || 02/18/20 MCM 20.0.3.0 (498928) If copying a PO that is associated with a Estimate and Vendor, Project, Task and Class match, then associate new one with PO (ie tEstimateTaskExpenseOrder)
  || 03/22/21 RLS 21.0.4.0 (546075) Changed @OrderedBy to nvarchar
  || 03/22/21 RLS 21.0.4.0 (546075) Changed @Contact to nvarchar
  || 07/23/21 MCM 21.08.   (565359) Added details for tPurchasOrderUser and tPurchasOrder.Description
  || 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
  || 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName

  */

	if isnull(@CreatedByKey, 0) > 0 and isnull(@OrderedBy, '''') = '''' 
		select  @OrderedBy = UserName from vUserName where UserKey = @CreatedByKey

	Declare
	@CompanyKey int,
	@POKind smallint,
	@PurchaseOrderTypeKey int,
	@VendorKey int,
	@ProjectKey int,
	@TaskKey int,
	@ItemKey int,
	@ClassKey int,
	@Contact nvarchar(200),
	@PODate smalldatetime,
	@DueDate smalldatetime,
	@CustomFieldKey int,
	@HeaderTextKey int,
	@FooterTextKey int,
	@ApprovedByKey int,
	@CompanyMediaKey int,
	@MediaEstimateKey int,
	@OrderDisplayMode smallint,
	@BillAt smallint,
	@SalesTaxKey int,
	@SalesTax2Key int,	
	@FlightStartDate smalldatetime,
	@FlightEndDate smalldatetime,
	@FlightInterval tinyint,
	@PrintClientOnOrder tinyint,
	@NewPurchaseOrderKey int,
	@TranType varchar(2),
	@OldPurchaseOrderDetailKey int,
	@RETVAL int,
	@LineNumber int,
	@ShortDescription varchar(max),
	@Quantity decimal(24,4),
	@UnitCost money,
	@UnitDescription varchar(30),
	@TotalCost money,
	@Billable tinyint,
	@Markup decimal(24,4),
	@BillableCost money,
	@LongDescription varchar(max),
	@DetailOrderDate smalldatetime,
	@DetailOrderEndDate smalldatetime,
	@UserDate1 smalldatetime,
	@UserDate2 smalldatetime,
	@UserDate3 smalldatetime,
	@UserDate4 smalldatetime,
	@UserDate5 smalldatetime,
	@UserDate6 smalldatetime,
	@OrderDays varchar(50),
	@OrderTime varchar(50),
	@OrderLength varchar(50),
	@Taxable tinyint,
	@PurchaseOrderNumber varchar(30),
	@Taxable2 tinyint,
	@NewPurchaseOrderDetailKey int,
	@OldPurchaseOrderTrafficKey int,
	@OldPurchaseOrderUserKey int,
	@ISCICode varchar(100),
	@ShowPercent decimal(24,4),
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@Comments varchar(2000),
	@NewTrafficKey INT,
	@AdjustmentNumber INT,
	@MediaRevisionReasonKey INT,
	@ObjectFieldSetKey int,
	@FieldSetKey int,
	@UnitRate money,
	@PrintTraffic tinyint,
	@PrintOption tinyint,
	@Address1 varchar(100),
	@Address2 varchar(100),
	@Address3 varchar(100),
	@City varchar(100),
	@State varchar(50),
	@PostalCode varchar(20),
	@Country varchar(50),
	@DeliveryInstructions varchar(1000),
	@SpecialInstructions varchar(1000),
	@DeliverTo1 varchar(100),
	@DeliverTo2 varchar(100),
	@DeliverTo3 varchar(100),
	@DeliverTo4 varchar(100),
	@GLCompanyKey int,
	@OfficeKey int,
	@DepartmentKey int,
	@CompanyAddressKey int,
	@CurrencyID varchar(10),
	@ExchangeRate decimal(24,7),
	@PCurrencyID varchar(10),
	@PExchangeRate decimal(24,7),
	@GrossAmount money,
	@PTotalCost money,
	@Commission decimal(24,4),
	@SalesTaxAmount money,
	@SalesTax1Amount money,
	@SalesTax2Amount money,
	@EstimateTaskExpenseKey int,
	@OriginalVendorKey int,
	@OriginalProjectKey int,
	@OriginalTaskKey int,
	@OriginalClassKey int,
	@Description nvarchar(max), --this is tPurchaseOrder
	@NotifyUserKey int,
	@InteractiveAdUnitName varchar (200)

	if @CopyProjectKey = -1
		Select @CopyProjectKey = NULL

	if @CopyTaskKey = -1
		Select @CopyTaskKey = NULL

	-- set the project now because we use it later to get the GL company
	IF isnull(@CopyProjectKey, 0) > 0
		SELECT @ProjectKey = @CopyProjectKey
	else
		SELECT @ProjectKey = ProjectKey
		FROM tPurchaseOrder (nolock)
		WHERE PurchaseOrderKey = @PurchaseOrderKey   

	if isnull(@ProjectKey, 0) > 0
		select @GLCompanyKey = GLCompanyKey 
		from   tProject (nolock)
		where  ProjectKey = @ProjectKey
	else
		select @GLCompanyKey = GLCompanyKey 
		FROM tPurchaseOrder (nolock)
		WHERE PurchaseOrderKey = @PurchaseOrderKey   
	

	--Get new contact and new address for the new vendor selected
	IF isnull(@CopyVendorKey, 0) > 0
	BEGIN
		SELECT 
		    @Address1 = addr.Address1,		
			@Address2 = addr.Address2,
			@Address3 = addr.Address3,		
			@City  = addr.City, 				
			@State = addr.State, 				
			@PostalCode = addr.PostalCode, 	
			@Country = addr.Country
		FROM tAddress addr (nolock)
			inner join tCompany c (nolock) on addr.AddressKey = c.DefaultAddressKey
		WHERE c.CompanyKey = @CopyVendorKey
	
		SELECT @Contact = pcu.FirstName + '' '' + pcu.LastName --Primary Contact Name
		FROM tCompany c (nolock)
			 left outer join tUser pcu (nolock) on c.PrimaryContact = pcu.UserKey 
		WHERE c.CompanyKey = @CopyVendorKey

		SELECT @CopyCompanyMediaKey = ISNULL(@CopyCompanyMediaKey,0)
	END

	SELECT @CompanyKey = ISNULL(@CompanyKey, CompanyKey),
	@POKind = POKind,
	@PurchaseOrderTypeKey = PurchaseOrderTypeKey,
	@VendorKey = ISNULL(@CopyVendorKey, VendorKey) ,
	@TaskKey = ISNULL(@CopyTaskKey, TaskKey) ,
	@ItemKey = ItemKey,
	@ClassKey = ISNULL(@CopyClassKey, ClassKey),
	@Contact =ISNULL(@Contact, Contact),
	@PODate = CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime),
	@DueDate = CASE 
                  WHEN DueDate IS NULL THEN NULL
                  ELSE CAST( CAST(MONTH(GETDATE()) as varchar) + ''/'' + CAST(DAY(GETDATE()) as varchar) + ''/'' + CAST(YEAR(GETDATE()) as varchar) as smalldatetime)
               END,
	@CustomFieldKey = CustomFieldKey,
	@HeaderTextKey = HeaderTextKey,
	@FooterTextKey = FooterTextKey,
	@ApprovedByKey = ApprovedByKey,
	@CompanyMediaKey = ISNULL(@CopyCompanyMediaKey, CompanyMediaKey),
	@MediaEstimateKey = ISNULL(@CopyMediaEstimateKey, MediaEstimateKey),
	@OrderDisplayMode = OrderDisplayMode,
	@BillAt = BillAt,
	@SalesTaxKey = SalesTaxKey,
	@SalesTax2Key = SalesTax2Key,	
	@FlightStartDate = FlightStartDate,
	@FlightEndDate = FlightEndDate,
	@FlightInterval = FlightInterval,
	@PrintClientOnOrder = PrintClientOnOrder,
	@PurchaseOrderNumber = NULL,
	@PrintTraffic = PrintTraffic,
	@PrintOption = PrintOption,
    @Address1 = CASE WHEN @CopyVendorKey is null THEN Address1 ELSE @Address1 END,
	@Address2 = CASE WHEN @CopyVendorKey is null THEN Address2 ELSE @Address2 END,
	@Address3 = CASE WHEN @CopyVendorKey is null THEN Address3 ELSE @Address3 END,
	@City = CASE WHEN @CopyVendorKey is null THEN City ELSE @City END,
	@State = CASE WHEN @CopyVendorKey is null THEN State ELSE @State END,
	@PostalCode = CASE WHEN @CopyVendorKey is null THEN PostalCode ELSE @PostalCode END,
	@Country = CASE WHEN @CopyVendorKey is null THEN Country ELSE @Country END,
	@DeliveryInstructions = DeliveryInstructions,
	@SpecialInstructions = SpecialInstructions,
	@DeliverTo1 = DeliverTo1,
	@DeliverTo2 = DeliverTo2,
	@DeliverTo3 = DeliverTo3,
	@DeliverTo4 = DeliverTo4,
	@CompanyAddressKey =  ISNULL(@CompanyAddressKey, CompanyAddressKey),
	@CurrencyID = CurrencyID,
	@ExchangeRate = ExchangeRate,
	@PCurrencyID = PCurrencyID,
	@PExchangeRate = PExchangeRate,
	@OriginalVendorKey = VendorKey,
	@OriginalProjectKey = ProjectKey,
	@OriginalTaskKey = TaskKey,
	@OriginalClassKey = ClassKey,
	@Description = Description
	FROM tPurchaseOrder (nolock)
	WHERE PurchaseOrderKey = @PurchaseOrderKey

	-- make sure that the task belong to the project, if not null, it
	if isnull(@TaskKey, 0) > 0
	begin
		if (select ProjectKey from tTask (nolock) where TaskKey = @TaskKey)
			<> @ProjectKey
			select @TaskKey = null
	end

	-- Make a copy of the custom field
	IF ISNULL(@CustomFieldKey,0) > 0
    BEGIN
		SELECT	@FieldSetKey = FieldSetKey
		FROM	tObjectFieldSet (NOLOCK)
		WHERE	ObjectFieldSetKey = @CustomFieldKey
		
		EXEC spCF_tObjectFieldSetInsert @FieldSetKey, @ObjectFieldSetKey OUTPUT
		
		IF ISNULL(@ObjectFieldSetKey,0) > 0
			INSERT	tFieldValue
					(FieldValueKey, FieldDefKey, ObjectFieldSetKey, FieldValue)
			SELECT	newid(), FieldDefKey, @ObjectFieldSetKey, FieldValue
			FROM	tFieldValue (NOLOCK)
			WHERE	ObjectFieldSetKey = @CustomFieldKey
    END

	exec @RETVAL = sptPurchaseOrderInsert @CompanyKey = @CompanyKey
		,@POKind = @POKind 
		,@PurchaseOrderTypeKey= @PurchaseOrderTypeKey
		,@PurchaseOrderNumber= @PurchaseOrderNumber
		,@VendorKey=@VendorKey
		,@ProjectKey = @ProjectKey
		,@TaskKey = @TaskKey
		,@ItemKey =@ItemKey
		,@ClassKey = @ClassKey
		,@Contact = @Contact 
		,@PODate = @PODate
		,@DueDate = @DueDate
		,@OrderedBy = @OrderedBy
		,@CustomFieldKey = @ObjectFieldSetKey
		,@HeaderTextKey = @HeaderTextKey
		,@FooterTextKey = @FooterTextKey
		,@ApprovedByKey = @ApprovedByKey
		,@CreatedByKey = @CreatedByKey
		,@CompanyMediaKey = @CompanyMediaKey
		,@MediaEstimateKey = @MediaEstimateKey 
		,@OrderDisplayMode = @OrderDisplayMode
		,@BillAt = @BillAt
		,@SalesTaxKey = @SalesTax2Key 
		,@SalesTax2Key = @SalesTaxKey
		,@FlightStartDate = @FlightStartDate
		,@FlightEndDate = @FlightEndDate 
		,@FlightInterval = @FlightInterval
		,@PrintClientOnOrder = @PrintClientOnOrder
		,@PrintTraffic = @PrintTraffic
		,@PrintOption = @PrintOption
		,@GLCompanyKey = @GLCompanyKey
		,@CompanyAddressKey = @CompanyAddressKey
		,@CurrencyID = @CurrencyID
		,@ExchangeRate = @ExchangeRate
		,@PCurrencyID = @PCurrencyID
		,@PExchangeRate = @PExchangeRate
		,@Description = @Description 
		,@oIdentity = @NewPurchaseOrderKey OUTPUT

	SELECT @oIdentity = @NewPurchaseOrderKey
	IF @RETVAL <> 1
		RETURN @RETVAL

	--Update PurchaseOrder Address information
	exec sptPurchaseOrderAddressUpdate
		@NewPurchaseOrderKey,
		@Address1,
		@Address2,
		@Address3,
		@City,
		@State,
		@PostalCode,
		@Country,
		@DeliveryInstructions,
		@SpecialInstructions,
		@DeliverTo1,
		@DeliverTo2,
		@DeliverTo3,
		@DeliverTo4
			
	SELECT @OldPurchaseOrderTrafficKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @OldPurchaseOrderTrafficKey = MIN(PurchaseOrderTrafficKey)
		FROM tPurchaseOrderTraffic (NOLOCK) 
		WHERE PurchaseOrderKey = @PurchaseOrderKey
		AND PurchaseOrderTrafficKey > @OldPurchaseOrderTrafficKey

		IF @OldPurchaseOrderTrafficKey IS NULL
                  BREAK
		
		SELECT @PurchaseOrderKey = PurchaseOrderKey,
			@ISCICode = ISCICode, 
			@ShowPercent = ShowPercent,
			@StartDate = StartDate,
			@EndDate = EndDate,
			@Comments = Comments
		FROM tPurchaseOrderTraffic (NOLOCK)
		WHERE PurchaseOrderTrafficKey = @OldPurchaseOrderTrafficKey

		exec sptPurchaseOrderTrafficInsert
			@NewPurchaseOrderKey,
			@ISCICode, 
			@ShowPercent,
			@StartDate,
			@EndDate,
			@Comments,
			@NewTrafficKey OUTPUT
	END

	--Copy data into tPurchaseOrderUser aka notify users
	SELECT @OldPurchaseOrderUserKey = -1
	WHILE (1=1)
	BEGIN
		SELECT @OldPurchaseOrderUserKey = MIN(UserKey)
		FROM tPurchaseOrderUser (NOLOCK) 
		WHERE PurchaseOrderKey = @PurchaseOrderKey
		AND UserKey > @OldPurchaseOrderUserKey

		PRINT @OldPurchaseOrderUserKey

		IF @OldPurchaseOrderUserKey IS NULL
		BEGIN
            BREAK
		end

		SELECT
			@NotifyUserKey= UserKey
			FROM tPurchaseOrderUser (NOLOCK)
			WHERE UserKey = @OldPurchaseOrderUserKey

		exec sptPurchaseOrderUserInsert @PurchaseOrderKey= @NewPurchaseOrderKey
			,@UserKey = @NotifyUserKey, @NotificationSent = 0
	END
	
	CREATE TABLE #PO_LineNbr (NewPurchaseOrderDetailKey int
	                         ,LineNumber int)
	
	SELECT @OldPurchaseOrderDetailKey = -1
      WHILE (1=1)
      BEGIN
            SELECT @OldPurchaseOrderDetailKey = MIN(PurchaseOrderDetailKey)
            FROM   tPurchaseOrderDetail (NOLOCK)
            Where  PurchaseOrderKey = @PurchaseOrderKey 
            AND PurchaseOrderDetailKey > @OldPurchaseOrderDetailKey
            AND TransferToKey is null

			IF @OldPurchaseOrderDetailKey IS NULL
                  BREAK
            
			SELECT @PurchaseOrderKey = PurchaseOrderKey,
			@LineNumber = LineNumber,
			@ProjectKey = ISNULL(@CopyProjectKey, ProjectKey),
			@TaskKey = ISNULL(@CopyTaskKey, TaskKey) ,
			@ItemKey = ItemKey,
			@ClassKey = ISNULL(@CopyClassKey, ClassKey),
			@ShortDescription = ShortDescription,
			@Quantity = Quantity,
			@UnitCost = UnitCost,
			@UnitDescription = UnitDescription ,
			@TotalCost = TotalCost,
			@Billable = Billable ,
			@Markup = Markup,
			@BillableCost = BillableCost ,
			@LongDescription = LongDescription ,
			@CustomFieldKey = CustomFieldKey,
			@DetailOrderDate = DetailOrderDate ,
			@DetailOrderEndDate = DetailOrderEndDate,
			@UserDate1 = UserDate1,
			@UserDate2 = UserDate2,
			@UserDate3 = UserDate3,
			@UserDate4 = UserDate4,
			@UserDate5 = UserDate5,
			@UserDate6 = UserDate6,
			@OrderDays = OrderDays,
			@OrderTime = OrderTime,
			@OrderLength = OrderLength,
			@Taxable = Taxable,
			@Taxable2 = Taxable2,
			@AdjustmentNumber = AdjustmentNumber,
			@MediaRevisionReasonKey = MediaRevisionReasonKey,
			@UnitRate = UnitRate,
			@OfficeKey = ISNULL((SELECT OfficeKey FROM tProject (NOLOCK) WHERE ProjectKey = @ProjectKey), OfficeKey),
			@DepartmentKey = DepartmentKey,
			@GrossAmount = GrossAmount,
			@PTotalCost = PTotalCost,
			@PCurrencyID = PCurrencyID,
			@PExchangeRate = PExchangeRate,
			@Commission = Commission,
			@SalesTaxAmount = SalesTaxAmount,
			@SalesTax1Amount = SalesTax1Amount,
			@SalesTax2Amount = SalesTax2Amount,
			@OriginalProjectKey = ProjectKey,
			@OriginalTaskKey = TaskKey,
			@OriginalClassKey = ClassKey,
			@InteractiveAdUnitName = InteractiveAdUnitName


			FROM   tPurchaseOrderDetail (NOLOCK)
            WHERE PurchaseOrderDetailKey = @OldPurchaseOrderDetailKey

            IF ISNULL(@CustomFieldKey,0) > 0
            BEGIN
				-- blank the field set first for issue 400969 (CustomFieldKey set in tPurchaseOrderDetail but not in tObjectFieldSet)
				SELECT	@FieldSetKey = null
						,@ObjectFieldSetKey = NULL

				-- this is not set if missing
				SELECT	@FieldSetKey = FieldSetKey
				FROM	tObjectFieldSet (NOLOCK)
				WHERE	ObjectFieldSetKey = @CustomFieldKey
				
				-- so only do this if not blank
				if isnull(@FieldSetKey, 0) > 0
				begin
					EXEC spCF_tObjectFieldSetInsert @FieldSetKey, @ObjectFieldSetKey OUTPUT
				
					IF ISNULL(@ObjectFieldSetKey,0) > 0
						INSERT	tFieldValue
								(FieldValueKey, FieldDefKey, ObjectFieldSetKey, FieldValue)
						SELECT	newid(), FieldDefKey, @ObjectFieldSetKey, FieldValue
						FROM	tFieldValue (NOLOCK)
						WHERE	ObjectFieldSetKey = @CustomFieldKey
				end

            END
			ELSE
				SELECT @ObjectFieldSetKey = NULL	


			-- make sure that the task belong to the project, if not null, it
			if isnull(@TaskKey, 0) > 0
			begin
				if (select ProjectKey from tTask (nolock) where TaskKey = @TaskKey)
					<> @ProjectKey
					select @TaskKey = null
			end

		EXEC sptPurchaseOrderDetailInsert 
			@PurchaseOrderKey = @NewPurchaseOrderKey,
			@LineNumber = @LineNumber,
			@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,
			@LongDescription = @LongDescription,
			@CustomFieldKey = @ObjectFieldSetKey,
			@DetailOrderDate = @DetailOrderDate,
			@DetailOrderEndDate = @DetailOrderEndDate,
			@UserDate1 = @UserDate1,
			@UserDate2 = @UserDate2,
			@UserDate3 = @UserDate3,
			@UserDate4 = @UserDate4,
			@UserDate5 = @UserDate5,
			@UserDate6 = @UserDate6,
			@OrderDays = @OrderDays,
			@OrderTime = @OrderTime,
			@OrderLength = @OrderLength,
			@Taxable = @Taxable,
			@Taxable2 = @Taxable2,
			@OfficeKey = @OfficeKey,
			@DepartmentKey = @DepartmentKey,
			@GrossAmount = @GrossAmount,
			@PCurrencyID = @PCurrencyID,
			@PExchangeRate = @PExchangeRate,
			@PTotalCost = @PTotalCost,
			@SkipRollUps = NULL,
			@InteractiveAdUnitName = @InteractiveAdUnitName,
			@oIdentity = @NewPurchaseOrderDetailKey OUTPUT

        INSERT INTO #PO_LineNbr
        SELECT @NewPurchaseOrderDetailKey, @LineNumber
        

		-- Now update the revision history + missing fields in sp insert
		UPDATE tPurchaseOrderDetail
		SET	   AdjustmentNumber = @AdjustmentNumber
			  ,MediaRevisionReasonKey = @MediaRevisionReasonKey
			  ,Commission = @Commission
			  ,SalesTaxAmount = @SalesTaxAmount
			  ,SalesTax1Amount = @SalesTax1Amount
			  ,SalesTax2Amount = @SalesTax2Amount
		WHERE PurchaseOrderDetailKey = @NewPurchaseOrderDetailKey
		
		-- Now copy the taxes
		insert tPurchaseOrderDetailTax (PurchaseOrderDetailKey, SalesTaxKey, SalesTaxAmount)
		select @NewPurchaseOrderDetailKey, SalesTaxKey, SalesTaxAmount
		from   tPurchaseOrderDetailTax (nolock)
		where  PurchaseOrderDetailKey = @OldPurchaseOrderDetailKey

		-- If PO is associated with estimate, associate the new PO with the same estimate
		SELECT @EstimateTaskExpenseKey = ISNULL(EstimateTaskExpenseKey, 0) from tEstimateTaskExpenseOrder (nolock) WHERE PurchaseOrderDetailKey = @OldPurchaseOrderDetailKey

		if @EstimateTaskExpenseKey > 0 
			begin
				if ISNULL(@OriginalVendorKey, -1) = ISNULL(@CopyVendorKey, ISNULL(@VendorKey, -1)) 
					AND ISNULL(@OriginalProjectKey, -1) = ISNULL(@CopyProjectKey, ISNULL(@ProjectKey, -1) )
					AND ISNULL(@OriginalTaskKey, -1) = ISNULL(@CopyTaskKey, ISNULL(@TaskKey, -1)) 
					AND ISNULL(@OriginalClassKey, -1) = ISNULL(@CopyClassKey, ISNULL(@ClassKey, -1)) 
					begin
						insert tEstimateTaskExpenseOrder (EstimateTaskExpenseKey, PurchaseOrderDetailKey)
						values (@EstimateTaskExpenseKey, @NewPurchaseOrderDetailKey)
					end
			end
      END

	IF @POKind = 0
		UPDATE pod
		   SET pod.LineNumber = tmp.LineNumber
          FROM tPurchaseOrderDetail pod INNER JOIN #PO_LineNbr tmp ON (pod.PurchaseOrderDetailKey = tmp.NewPurchaseOrderDetailKey)
         WHERE pod.PurchaseOrderKey = @NewPurchaseOrderKey
	
-- rollup the taxes and totals from the lines to the header on the new PO
EXEC sptPurchaseOrderRollupAmounts @NewPurchaseOrderKey 

-- Run project rollup on original po since project keys were obtained from it
EXEC sptProjectRollupUpdateEntity ''tPurchaseOrder'', @PurchaseOrderKey, 0
		
		

RETURN 1











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
















ALTER VIEW [dbo].[vProjectTransPO]
as

/*
|| When     Who Rel     What
|| 12/21/06 CRG 8.4     Added GLAccountKey
|| 07/10/07 QMD 8.5     Expense Type reference changed to tItem
|| 10/26/07 CRG 8.4.3.9 (14565) Modified to add a column for CostRate for use by vReport_Transactions_NetLabor
|| 11/07/07 CRG 8.5     (9205) Added ClassKey
|| 02/01/08 GHL 8.503   (20472) Added TranKey, UIDTranKey to join with expense receipts in vReport_Transactions
|| 04/10/08 GHL 8.508   (24671) Changed join type between tItem/tExpenseReceipt (case when no item)
|| 04/08/09 GHL 10.022  (50462) Added VendorKey  to add to vReport_Transactions
|| 04/24/09 MFT 10.024	(51139) Added DepartmentName to add to vReport_Transactions and vReport_Transactions_NetLabor
|| 04/28/09 GHL 10.024  (51139) Get department from the lines for misc cost and vouchers only 
|| 06/15/09 GHL 10.027  (54845) Added Transaction Number to get v.InvoiceNumber, ee.EnvelopeNumber + user
|| 09/11/09 GHL 10.5     Added TransferToKey 
|| 01/19/10 GHL 10.517  (72527) Added Billing Item info from service/item
||                       considered as defaults if there is no layout on the project 
|| 01/22/10 RLB 10.517  (72862) If no item on voucher line will pull lines expense account
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
|| 05/25/11 GHL 10.544  (109956) Cloned vProjectTrans and added Open Orders
|| 04/23/12 GHL 10.555  Added GLCompanyKey for map/restrict
||                       --> tTime/tExpenseReceipt
||							p.GLCompanySource = 0 then p.GLCompanyKey
||							p.GLCompanySource = 1 then u.GLCompanyKey
||							p.GLCompanySource is null i.e. no project then u.GLCompanyKey
||                       --> tMiscCost
||							p.GLCompanyKey
||                       --> tVoucherDetail
||							isnull(vd.TargetGLCompanyKey, v.GLCompanyKey)
|| 11/15/12 GWG 10.5.6.2 Added transfer in out dates
|| 06/18/13 MAS 10.5.6.8 (179674) For Media Orders, use the Insertion Date/Flight for the TransactionDate 
|| 01/28/15 GHL 10.5.8.8 Adde Title for Abelson
|| 03/20/15 WDF 10.5.9.0 (AbelsonTaylor) Added AdjustmentType
|| 06/18/15 MCM 10.5.9.3 (260175) In the voucher section having it pull expense account from voucher first and items second
|| 04/12/16 MFT 10.603 (296036) Added WriteOffComment
|| 06/08/16 WDF 10.6.0.5 (303066) Added PurchasedFrom
|| 06/14/16 GHL 10.6.0.5 (303598) take er.DateBilled vs vd.DateBilled when the exp receipt applied to a voucher is prebilled
||                       Was initially in vReport_Transactions_PO. Improves perfo by moving it here
|| 12/07/18 GHL 19.1.0.0 (424920) Added GrossAmount (mainly for VIs with prebilled POs applied, in that case 
||                        GrossAmount = 1000 and BillableCost = 0 )
|| 02/14/19 GHL 19.3.0.0 (445252) Removed LATIN1_GENERAL_ CI_AS collation, this creates conflicts when comparing to other strings 
||                        Force it to COLLATE DATABASE_DEFAULT
|| 04/24/19 GWG 19.050  Distinguish between a voucher and a credit card in the type
|| 05/13/19 GHL 19.0.6.0 (459967) Added Applied Order number
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 05/18/21 AMP 21.06.20.0000 (558708) Added currency field 
|| 02/28/22 RLS 22.03.20 (523772) Added data type specifier (N) to string literals
|| 11/29/22 RLS 22.12.18 (614994) Added TransactionApprovalDate
|| 05/30/23 RLS 23.16.18 (635138) Added TransactionPostingDate
|| 07/18/23 MCM 23.08.xx (645674) Updated the OpenOrder type where clause to be "(InvoiceLineKey > 0 or (ISNULL(AppliedCost, 0) = 0 and pod.Closed = 0))" instead of just "Closed = 0"
|| 01/08/24 RLB 25.02.16 (686787) Added Project Team from Voucher Header or PO Header, PO Header Description and Vendor invoice Description both from header
|| 09/04/25 RLS 25.09.21 (708615) Added PODCustomFieldKey
|| 09/29/25 MCM 25.10.x  (700642) Added TransactionKey - type + underlying Key field
|| 04/28/26 RLS 26.05.17 (724768) Added Contractor
*/

Select
	N''LABOR'' as Type
	,ts.CompanyKey
	,case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey
	,t.TimeSheetKey as ParentKey
	,NULL as PODCustomFieldKey
	,t.ProjectKey
	,t.TaskKey
    ,t.ServiceKey as ItemKey
	,s.ServiceCode as ItemID
	,s.Description as ItemName
	,ActualHours as Quantity
	,ActualRate as UnitCost
	,ROUND(ActualHours * ActualRate, 2) as TotalCost
	,ROUND(ActualHours * ActualRate, 2) as BillableCost
	,ROUND(ActualHours * ActualRate, 2) as GrossAmount
	,ROUND(BilledHours * BilledRate, 2) as AmountBilled
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) COLLATE DATABASE_DEFAULT as Description
	,t.WorkDate as TransactionDate
	,NULL as PurchasedFrom
	,t.InvoiceLineKey
	,t.WriteOff
	,ts.Status
	,WIPPostingInKey
	,WIPPostingOutKey
	,t.OnHold
	,t.WriteOffReasonKey
	,t.WriteOffComment
	,t.Comments as Comments
	,ROUND(t.ActualRate * t.ActualHours, 2) - ISNULL(ROUND(t.BilledHours * t.BilledRate, 2), 0) as BilledDifference
	,NULL as GLAccountKey
	,t.DateBilled
	,t.TransferComment
	,t.CostRate
	,s.ClassKey
	,t.TimeKey AS UIDTranKey
	,NULL AS TranKey
    ,NULL AS TranNumber
	,NULL AS VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,t.TransferToKey AS UIDTransferToKey
    ,NULL AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName) as WorkTypeName
    ,t.TransferInDate
    ,t.TransferOutDate
    ,t.TitleKey
    ,tt.TitleName
    ,tt.TitleID
    ,t.IsAdjustment as AdjustmentType
	,null as AppliedOrderNumber
	,t.CurrencyID
	,ts.DateApproved as TransactionApprovalDate
	,NULL as TransactionPostingDate
	,NULL as ProjectTeam
	,NULL as PODescription
	,NULL as VIDescription
	,N''LABOR'' + Cast(t.TimeKey as varchar(100)) as TransactionKey
from 
	tTime t (nolock)
	inner join tUser u (nolock) on t.UserKey = u.UserKey
	inner join tTimeSheet ts (nolock) on t.TimeSheetKey = ts.TimeSheetKey
	left outer join tService s (nolock) on t.ServiceKey = s.ServiceKey
	left outer join tWorkType wt (nolock) on s.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on s.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = t.ProjectKey
	LEFT JOIN tDepartment d (nolock) on s.DepartmentKey = d.DepartmentKey
	left outer join tProject p (nolock) on t.ProjectKey = p.ProjectKey
	left outer join tTitle tt (nolock) on t.TitleKey = tt.TitleKey

Union ALL

Select
	N''EXPRPT'' as Type
	,ee.CompanyKey
	,case when p.GLCompanySource = 0 then p.GLCompanyKey else u.GLCompanyKey end as GLCompanyKey
	,er.ExpenseEnvelopeKey as ParentKey
	,NULL as PODCustomFieldKey
	,er.ProjectKey
	,er.TaskKey
	,er.ItemKey 
	,i.ItemID
	,i.ItemName
	,er.ActualQty as Quantity
	,er.ActualUnitCost as UnitCost
	,er.ActualCost as TotalCost
	,er.BillableCost as BillableCost
	,er.GrossAmount 
	,er.AmountBilled
	,er.Description COLLATE DATABASE_DEFAULT as Description
	,er.ExpenseDate as TransactionDate
	,NULL as PurchasedFrom
	,er.InvoiceLineKey
	,er.WriteOff
	,ee.Status
	,WIPPostingInKey
	,WIPPostingOutKey
	,er.OnHold
	,er.WriteOffReasonKey
	,er.WriteOffComment
	,er.Comments as Comments
	,NULL
	,i.ExpenseAccountKey AS ExpenseGLAccountKey
	,er.DateBilled
	,er.TransferComment
	,NULL
	,i.ClassKey
	,NULL AS UIDTranKey
	,er.ExpenseReceiptKey AS TranKey
    ,ee.EnvelopeNumber AS TranNumber
	,ee.VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
    ,NULL AS UIDTransferToKey
	,er.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,er.TransferInDate
    ,er.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
    ,null as TitleID
    ,er.AdjustmentType as AdjustmentType
	,null as AppliedOrderNumber
	,ee.CurrencyID
	,ee.DateApproved AS TransactionApprovalDate
	,NULL as TransactionPostingDate
	,NULL as ProjectTeam
	,NULL as PODescription
	,NULL as VIDescription
	,N''EXPRPT'' + Cast(er.ExpenseReceiptKey as varchar(100)) as TransactionKey
from
	tExpenseReceipt er (nolock)
	inner join tExpenseEnvelope ee (nolock) on er.ExpenseEnvelopeKey = ee.ExpenseEnvelopeKey
	left outer join tItem i (nolock) on er.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = er.ProjectKey
	LEFT JOIN tDepartment d (nolock) on i.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on ee.UserKey = u.UserKey
    left outer join tProject p (nolock) on er.ProjectKey = p.ProjectKey

where   er.VoucherDetailKey is null

Union ALL

Select
	N''MISCCOST'' as Type
	,p.CompanyKey
	,p.GLCompanyKey
	,mc.MiscCostKey as ParentKey
	,NULL as PODCustomFieldKey
	,mc.ProjectKey
	,mc.TaskKey
	,mc.ItemKey 
	,i.ItemID
	,i.ItemName as ItemName
	,mc.Quantity
	,mc.UnitCost
	,mc.TotalCost
	,mc.BillableCost
	,mc.BillableCost as GrossAmount
	,mc.AmountBilled
	,mc.ShortDescription COLLATE DATABASE_DEFAULT as Description
	,mc.ExpenseDate as TransactionDate
	,NULL as PurchasedFrom
	,mc.InvoiceLineKey
	,mc.WriteOff
	,4
	,WIPPostingInKey
	,WIPPostingOutKey
	,mc.OnHold
	,mc.WriteOffReasonKey
	,mc.WriteOffComment
	,mc.LongDescription as Comments
	,NULL
	,i.ExpenseAccountKey
	,mc.DateBilled
	,mc.TransferComment
	,NULL
	,mc.ClassKey
	,NULL AS UIDTranKey
	,mc.MiscCostKey AS TranKey
    ,null AS TranKey
	,NULL AS VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,NULL AS UIDTransferToKey
	,mc.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,mc.TransferInDate
    ,mc.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
	,null as TitleID
    ,mc.AdjustmentType as AdjustmentType
	,null as AppliedOrderNumber
	,mc.CurrencyID
	,NULL as TransactionApprovalDate
	,NULL as TransactionPostingDate
	,NULL as ProjectTeam
	,NULL as PODescription
	,NULL as VIDescription
	,N''MISCCOST'' + Cast(mc.MiscCostKey as varchar(100)) as TransactionKey
from
	tMiscCost mc (nolock)
	inner join tProject p (nolock) on mc.ProjectKey = p.ProjectKey
	left outer join tItem i (nolock) on mc.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = mc.ProjectKey
	LEFT JOIN tDepartment d (nolock) on mc.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on mc.EnteredByKey = u.UserKey

Union ALL

Select
	case When v.CreditCard = 1 then N''CREDIT CARD'' else N''VOUCHER'' End as Type
	,v.CompanyKey
	,ISNULL(vd.TargetGLCompanyKey, v.GLCompanyKey) as GLCompanyKey
	,vd.VoucherKey as ParentKey
	,pod.CustomFieldKey as PODCustomFieldKey
	,vd.ProjectKey
	,vd.TaskKey
	,vd.ItemKey 
	,i.ItemID
	,i.ItemName as ItemName
	,vd.Quantity
	,vd.UnitCost
	,vd.TotalCost
	,vd.BillableCost
	,vd.GrossAmount
	,vd.AmountBilled
	,vd.ShortDescription COLLATE DATABASE_DEFAULT as Description
	,v.InvoiceDate as TransactionDate
	,v.BoughtFrom as PurchasedFrom
	,vd.InvoiceLineKey
	,vd.WriteOff
	,v.Status
	,vd.WIPPostingInKey
	,vd.WIPPostingOutKey
	,vd.OnHold
	,vd.WriteOffReasonKey
	,vd.WriteOffComment
	,vd.ShortDescription as Comments
	,NULL
	,vd.ExpenseAccountKey
	,case when er.InvoiceLineKey > 0 then er.DateBilled else vd.DateBilled end as DateBilled
	,vd.TransferComment
	,NULL
	,vd.ClassKey
	,NULL AS UIDTranKey
	,vd.VoucherDetailKey AS TranKey
    ,v.InvoiceNumber AS TranNumber
	,v.VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,NULL AS UIDTransferToKey
	,vd.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,vd.TransferInDate
    ,vd.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
	,null as TitleID
    ,vd.AdjustmentType as AdjustmentType
	,po.PurchaseOrderNumber as AppliedOrderNumber
	,v.CurrencyID
	,v.ApprovedDate AS TransactionApprovalDate
	,v.PostingDate AS TransactionPostingDate
	,Substring((Select '',''+ UserName  AS [text()]   
            From vUserName un (nolock)
            inner join tAssignment a (nolock) on a.UserKey = un.UserKey
			Where v.ProjectKey = a.ProjectKey
            ORDER BY un.UserName
            For XML PATH ('''')
        ), 2, 4000) as ProjectTeam
	,NULL as PODescription
	,v.Description as VIDescription
	,case When v.CreditCard = 1 then N''CREDIT CARD'' else N''VOUCHER'' end + Cast(vd.VoucherDetailKey as varchar(100)) as TransactionKey
from
	tVoucherDetail vd (nolock)
	inner join tVoucher v (nolock) on vd.VoucherKey = v.VoucherKey
	left outer join tItem i (nolock) on vd.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = vd.ProjectKey
	LEFT JOIN tDepartment d (nolock) on vd.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on v.CreatedByKey = u.UserKey
	left outer join tExpenseReceipt er (nolock) on vd.VoucherDetailKey = er.VoucherDetailKey
	left outer join tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
	left outer join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey

Union ALL

Select
	N''OPENORDER'' as Type
	,po.CompanyKey
	,po.GLCompanyKey
	,pod.PurchaseOrderKey as ParentKey
	,pod.CustomFieldKey as PODCustomFieldKey
	,pod.ProjectKey
	,pod.TaskKey
	,pod.ItemKey 
	,i.ItemID
	,i.ItemName as ItemName
	,pod.Quantity
	,pod.UnitCost
	,pod.TotalCost
	,pod.BillableCost
	,pod.GrossAmount
	,pod.AmountBilled
	,pod.ShortDescription COLLATE DATABASE_DEFAULT as Description
	,Case po.PODate 
		When 1 then po.FlightStartDate
		When 2 then po.FlightStartDate
		Else po.PODate
	 end as TransactionDate
	,NULL as PurchasedFrom
	,pod.InvoiceLineKey
	,0 as WriteOff
	,po.Status
	,0 as WIPPostingInKey
	,0 as WIPPostingOutKey
	,pod.OnHold
	,0 as WriteOffReasonKey
	,NULL AS WriteOffComment
	,pod.ShortDescription as Comments
	,NULL -- CostRate
	,i.ExpenseAccountKey
	,pod.DateBilled
	,pod.TransferComment
	,NULL
	,pod.ClassKey
	,NULL AS UIDTranKey
	,pod.PurchaseOrderDetailKey AS TranKey
    ,po.PurchaseOrderNumber AS TranNumber
	,po.VendorKey
	,d.DepartmentName
	,LTRIM(RTRIM(ISNULL(u.FirstName + '' '','''')  + ISNULL(u.LastName,''''))) AS EnteredByUser
	,u.Contractor as Contractor
	,NULL AS UIDTransferToKey
	,pod.TransferToKey AS TransferToKey
    ,wt.WorkTypeID
    ,isnull(wtcust.Subject, wt.WorkTypeName)
    ,pod.TransferInDate
    ,pod.TransferOutDate
    ,null as TitleKey
    ,null as TitleName
	,null as TitleID
    ,null as AdjustmentType
	,null as AppliedOrderNumber
	,po.CurrencyID
	,NULL AS TransactionApprovalDate
	,NULL as TransactionPostingDate
	,Substring((Select '',''+ UserName  AS [text()]   
            From vUserName un (nolock)
            inner join tAssignment a (nolock) on a.UserKey = un.UserKey
			Where po.ProjectKey = a.ProjectKey
            ORDER BY un.UserName
            For XML PATH ('''')
        ), 2, 4000) as ProjectTeam
	,po.Description as PODescription
	,Null as VIDescription
	,N''OPENORDER'' + Cast(pod.PurchaseOrderDetailKey as varchar(100)) as TransactionKey
from
	tPurchaseOrderDetail pod (nolock)
	inner join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
	left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	left outer join tWorkType wt (nolock) on i.WorkTypeKey = wt.WorkTypeKey
    left outer join tWorkTypeCustom wtcust (nolock) on i.WorkTypeKey = wtcust.WorkTypeKey and wtcust.Entity = ''tProject'' and wtcust.EntityKey = pod.ProjectKey
	LEFT JOIN tDepartment d (nolock) on pod.DepartmentKey = d.DepartmentKey
    left outer join tUser u (nolock) on po.CreatedByKey = u.UserKey
where (InvoiceLineKey > 0 or (ISNULL(AppliedCost, 0) = 0 and pod.Closed = 0))



'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptReminderCacheGetQueueItems]'
GO
IF OBJECT_ID(N'[dbo].[sptReminderCacheGetQueueItems]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROC [dbo].[sptReminderCacheGetQueueItems]
AS
/* 
|| When     Who Rel			What 
|| 10/14/22 CRG 22.11.20    (615895) Created
|| 05/04/26 RLB 26.05.17    (724584) limit daily company update to just active and not locked companies
*/

	--First clear out anything more than 24 hours old from the current cache
	DELETE	tReminderCache
	WHERE	DATEDIFF(HOUR, SendTime, GETUTCDATE()) > 24
		
	CREATE TABLE #QueueItems
		(CompanyKey int NULL,
		CalendarKey int NULL,
		ActivityKey int NULL)

	BEGIN TRAN

	--First, insert companies that haven''t had reminders created yet
	INSERT	#QueueItems
			(CompanyKey)
	SELECT	CompanyKey
	FROM	tCompany (nolock)
	WHERE	Active = 1
	AND		ISNULL(Locked, 0) = 0
	AND		OwnerCompanyKey IS NULL
	AND		CompanyKey NOT IN (SELECT CompanyKey FROM tReminderCache (nolock))
	AND		CompanyKey NOT IN (SELECT CompanyKey FROM tReminderCacheCompany (nolock))
	--This will spread out all of the companies on the server over a 4 hour period 
	--so that all companies don''t refresh every day at the same time
	AND		(DATEPART(HOUR, GETDATE()) % 4) = (CompanyKey % 4)

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END

	--Next, insert companies that don''t have a last updated record in tReminderCacheCompany
	INSERT	#QueueItems
			(CompanyKey)
	SELECT	CompanyKey
	FROM	tCompany (nolock)
	WHERE	Active = 1
	AND		ISNULL(Locked, 0) = 0
	AND		OwnerCompanyKey IS NULL
	AND		CompanyKey NOT IN (SELECT CompanyKey FROM tReminderCacheCompany (nolock))
	--This will spread out all of the companies on the server over a 4 hour period 
	--so that all companies don''t refresh every day at the same time
	AND		(DATEPART(HOUR, GETDATE()) % 4) = (CompanyKey % 4)
	AND		CompanyKey NOT IN (SELECT CompanyKey FROM #QueueItems)

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END

	--Next, insert companies that have expired
	INSERT	#QueueItems
			(CompanyKey)
	SELECT	rcc.CompanyKey
	FROM	tReminderCacheCompany rcc (nolock) 
	INNER JOIN tCompany cp (nolock) on rcc.CompanyKey = cp.CompanyKey
	WHERE	DATEDIFF(HOUR, rcc.LastFullUpdate, GETUTCDATE()) > 23
	AND		rcc.CompanyKey NOT IN (SELECT CompanyKey FROM #QueueItems)
	AND		cp.Active = 1 and cp.Locked = 0

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END

	--Next, insert items from the queue
	INSERT	#QueueItems
			(CompanyKey, CalendarKey, ActivityKey)
	SELECT	CompanyKey, CalendarKey, ActivityKey
	FROM	tReminderCacheQueue (nolock)
	WHERE	CompanyKey NOT IN (SELECT CompanyKey FROM #QueueItems)

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END

	DELETE	tReminderCacheQueue

	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN
	END

	COMMIT TRAN

	SELECT	*
	FROM	#QueueItems
	ORDER BY CalendarKey, ActivityKey --To force the NULL ones to the top, so that the Company only queue items get processed first'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptInvoiceLineExpenseGetAll]'
GO
IF OBJECT_ID(N'[dbo].[sptInvoiceLineExpenseGetAll]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROCEDURE [dbo].[sptInvoiceLineExpenseGetAll]
	(
		@InvoiceLineKey int,
		@Percentage decimal(24,4),
		@Mode smallint
	)

As --Encrypt

/*
|| When     Who Rel     What
|| 02/07/07 RTC 8.4.0.3 Corrected Net calculation for Misc Costs, Expense Receipts and Purchase Orders
|| 07/10/07 QMD 8.5     Expense Type reference changed to tItem
|| 10/17/08 GHL 10.010  (37490) Users want to see tExpenseReceipt.ExpenseDate
||                      on tVoucherDetail.SourceDate after they create vouchers 
|| 11/21/08 GHL 10.013  (40810) Matthiew McCarty at Media Logic found a discrepancy of 2 pennies
||                       between invoice line total and the sum of the detail amounts
||                       in case of split billing or @Percentage <> 1
||                       Calculating now a rounding error and adding it to a detail transaction
|| 04/13/10 MFT 10.5.21  Added UnitAmount and Markup calculated fields
|| 04/28/10 MFT 10.5.22  Removed media records from the ''VO'' data set that are linked to PO''s (now shown on the invoice in the BO/IO data sets)
|| 05/16/12 MFT 10.5.5.6 Changed all instances of ExpenseComments to use BilledComment, reverts to whatever field was previously diplayed on ISNULL
|| 12/23/14 MFT 10.5.8.7 Added tVoucher info for Spark44 enhancement (237287)
|| 12/15/20 GHL 21.01.17.0000 (540494) Added MarkupOnTransaction to pull the markup on the transaction and avoid recalc with rounding error
|| 01/04/21 AMP 21.01.24 (539364) Added Project Name as an available component on the Time and Expense sub-sections
|| 10/06/21 AMP 21.11.14.0000 (569383) Added Markup Amount aka Total Gross - Total Cost to be used on the Invoice layout/Expense Fields sub-report
|| 03/03/26 AMP 26.04.19 (722633) Sort expenses by date on the invoice layouts
|| 04/23/26 AMP 26.04.23 (727078) Bug Fix: Removed the change done in 722633 for @Mode = 2
*/

Select @Percentage = @Percentage / 100

Declare @RoundingError as Decimal(24, 4)
Declare @LineTotalAmount as Decimal(24, 4)
Declare @DetailTotalAmount as Decimal(24, 4)
Declare @Type as VARCHAR(2) Select @Type = ''''
Declare @KeyField as Int Select @KeyField = 0

-- Only do this for split billing
If @Percentage <> 1
Begin
	-- get the sum of amount billed, but do not round
	Select @LineTotalAmount = 
		(ISNULL((
	Select SUM(er.AmountBilled * @Percentage)
	From   tExpenseReceipt er (nolock)
	Where  er.InvoiceLineKey = @InvoiceLineKey
		),0))
		+
		(ISNULL((
	Select SUM(vd.AmountBilled * @Percentage)
	From   tVoucherDetail vd (nolock) 
	Where  vd.InvoiceLineKey = @InvoiceLineKey
		),0))
		+
		(ISNULL((
	Select SUM(mc.AmountBilled * @Percentage)
	From   tMiscCost mc (nolock) 
	Where  mc.InvoiceLineKey = @InvoiceLineKey
		),0))
		+
		(ISNULL((
	Select SUM(pod.AmountBilled * @Percentage)
	From   tPurchaseOrder po (nolock)
	Inner Join tPurchaseOrderDetail pod (nolock) on po.PurchaseOrderKey = pod.PurchaseOrderKey 
	Where  pod.InvoiceLineKey = @InvoiceLineKey
	And    po.POKind = 0
		),0))
 
	-- get the sum of rounded amount billed
	Select @DetailTotalAmount = 
		(ISNULL((
	Select SUM(ROUND(er.AmountBilled * @Percentage, 2))
	From   tExpenseReceipt er (nolock)
	Where  er.InvoiceLineKey = @InvoiceLineKey
		),0))
		+
		(ISNULL((
	Select SUM(ROUND(vd.AmountBilled * @Percentage, 2))
	From   tVoucherDetail vd (nolock) 
	Where  vd.InvoiceLineKey = @InvoiceLineKey
		),0))
		+
		(ISNULL((
	Select SUM(ROUND(mc.AmountBilled * @Percentage, 2))
	From   tMiscCost mc (nolock) 
	Where  mc.InvoiceLineKey = @InvoiceLineKey
		),0))
		+
		(ISNULL((
	Select SUM(ROUND(pod.AmountBilled * @Percentage, 2))
	From   tPurchaseOrder po (nolock)
	Inner Join tPurchaseOrderDetail pod (nolock) on po.PurchaseOrderKey = pod.PurchaseOrderKey 
	Where  pod.InvoiceLineKey = @InvoiceLineKey
	And    po.POKind = 0
		),0))

	-- now compare the round of the sums to the sum of the rounds
	Select @RoundingError = ROUND(ISNULL(@LineTotalAmount, 0), 2) - ISNULL(@DetailTotalAmount, 0)

	If @RoundingError <> 0 
	Begin

		select @KeyField = er.ExpenseReceiptKey
		From   tExpenseReceipt er (nolock)
		Where  er.InvoiceLineKey = @InvoiceLineKey

		If @@ROWCOUNT <> 0
			Select @Type = ''ER''

		IF @Type = ''''
		Begin
			Select @KeyField = mc.MiscCostKey
			From   tMiscCost mc (nolock)
			Where  mc.InvoiceLineKey = @InvoiceLineKey

			If @@ROWCOUNT <> 0
				Select @Type = ''MC''
		End

		IF @Type = ''''
		Begin
			Select @KeyField = vd.VoucherDetailKey
			From   tVoucherDetail vd (nolock)
			Where  vd.InvoiceLineKey = @InvoiceLineKey

			If @@ROWCOUNT <> 0
				Select @Type = ''VO''
		End

		IF @Type = ''''
		Begin
			Select @KeyField = pod.PurchaseOrderDetailKey
			From   tPurchaseOrder po (nolock)
			Inner Join tPurchaseOrderDetail pod (nolock) on po.PurchaseOrderKey = pod.PurchaseOrderKey 
			Where  pod.InvoiceLineKey = @InvoiceLineKey
			And    po.POKind = 0

			If @@ROWCOUNT <> 0
				Select @Type = ''PO''
		End
	End -- Rounding error
End -- Split Billing

if @Mode = 1
BEGIN
	Select 
		''ER'' as Type,
		er.ExpenseReceiptKey as KeyField,
		er.ExpenseDate as ExpenseDate,
		er.ActualQty * @Percentage as Quantity, 
		er.ActualUnitCost * @Percentage as UnitCost,
		er.Description as ExpenseDescription, 
		ISNULL(er.BilledComment, er.Comments) as ExpenseComments, 
		case when @Percentage = 1 then er.AmountBilled 
		else
		case when @Type = ''ER'' and er.ExpenseReceiptKey = @KeyField 
			then (ROUND(er.AmountBilled * @Percentage, 2)) + @RoundingError
			else (ROUND(er.AmountBilled * @Percentage, 2))
			end 
		end as AmountBilled,
		CASE er.ActualQty * @Percentage WHEN 0 THEN 0 ELSE
			(case when @Type = ''ER'' and er.ExpenseReceiptKey = @KeyField 
						then (ROUND(er.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(er.AmountBilled * @Percentage, 2))
			end) / (er.ActualQty * @Percentage)
			END AS UnitAmount,
		er.ActualCost * @Percentage As Net,
		CASE WHEN
			CASE er.ActualCost * @Percentage WHEN 0 THEN 0 ELSE
				case when @Percentage = 1 then er.AmountBilled 
				else
					case when @Type = ''ER'' and er.ExpenseReceiptKey = @KeyField 
						then (ROUND(er.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(er.AmountBilled * @Percentage, 2))
					end 
				end / (er.ActualCost * @Percentage) END <> 0
			THEN
				(CASE er.ActualCost * @Percentage WHEN 0 THEN 0 ELSE
									case when @Percentage = 1 then er.AmountBilled 
									else
										case when @Type = ''ER'' and er.ExpenseReceiptKey = @KeyField 
											then (ROUND(er.AmountBilled * @Percentage, 2)) + @RoundingError
											else (ROUND(er.AmountBilled * @Percentage, 2))
										end 
					end / (er.ActualCost * @Percentage) END - 1) * 100
			ELSE
				CASE er.ActualCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then er.AmountBilled 
					else
						case when @Type = ''ER'' and er.ExpenseReceiptKey = @KeyField 
							then (ROUND(er.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(er.AmountBilled * @Percentage, 2))
						end 
					end / (er.ActualCost * @Percentage) END
			END AS Markup,
		i.ItemName AS ItemDescription,
		NULL AS VendorName,
		NULL AS VoucherDate,
		NULL AS VoucherID,
		NULL AS VoucherTotal,
		ROUND(ISNULL(er.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(er.ActualCost,0.00)* @Percentage, 2) As MarkupAmount,
		-- if there is no split billing and the billed = gross, get the markup from the transaction
		case when @Percentage = 1 and er.AmountBilled = er.BillableCost then er.Markup else null end as MarkupOnTransaction,		
		p.ProjectNumber + '' - ''+ p.ProjectName AS ProjectName	
	From
		tExpenseReceipt er (nolock)
		left outer join tItem i (nolock) on er.ItemKey = i.ItemKey
		left outer join tProject p (nolock) on er.ProjectKey = p.ProjectKey
	Where
		er.InvoiceLineKey = @InvoiceLineKey

	UNION ALL

	Select
		''MC'' as Type,
		mc.MiscCostKey as KeyField,
		mc.ExpenseDate as ExpenseDate,
		mc.Quantity * @Percentage as Quantity,
		mc.UnitCost * @Percentage as UnitCost,
		mc.ShortDescription as ExpenseDescription,
		ISNULL(mc.BilledComment, mc.LongDescription) as ExpenseComments,
		case when @Percentage = 1 then mc.AmountBilled 
		else
		case when @Type = ''MC'' and mc.MiscCostKey = @KeyField 
			then (ROUND(mc.AmountBilled * @Percentage, 2)) + @RoundingError
			else (ROUND(mc.AmountBilled * @Percentage, 2))
		end
		end as AmountBilled,
		CASE mc.Quantity * @Percentage WHEN 0 THEN 0 ELSE
			case when @Percentage = 1 then mc.AmountBilled 
					else
					case when @Type = ''MC'' and mc.MiscCostKey = @KeyField 
						then (ROUND(mc.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(mc.AmountBilled * @Percentage, 2))
					end
			end / (mc.Quantity * @Percentage)
			END AS UnitAmount,
		mc.TotalCost * @Percentage As Net,
		CASE WHEN
			CASE mc.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
				case when @Percentage = 1 then mc.AmountBilled 
				else
					case when @Type = ''MC'' and mc.MiscCostKey = @KeyField 
						then (ROUND(mc.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(mc.AmountBilled * @Percentage, 2))
					end
				end / (mc.TotalCost * @Percentage) END <> 0
			THEN
				(CASE mc.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then mc.AmountBilled 
					else
						case when @Type = ''MC'' and mc.MiscCostKey = @KeyField 
							then (ROUND(mc.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(mc.AmountBilled * @Percentage, 2))
						end
					end / (mc.TotalCost * @Percentage) END - 1) * 100
			ELSE
				CASE mc.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then mc.AmountBilled 
					else
						case when @Type = ''MC'' and mc.MiscCostKey = @KeyField 
							then (ROUND(mc.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(mc.AmountBilled * @Percentage, 2))
						end
					end / (mc.TotalCost * @Percentage) END
			END AS Markup,     
		i.ItemName AS ItemDescription,
		NULL AS VendorName,
		NULL AS VoucherDate,
		NULL AS VoucherID,
		NULL AS VoucherTotal,
		ROUND(ISNULL(mc.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(mc.TotalCost,0.00)* @Percentage, 2) As MarkupAmount,
		-- if there is no split billing and the billed = gross, get the markup from the transaction
		case when @Percentage = 1 and mc.AmountBilled = mc.BillableCost then mc.Markup else null end as MarkupOnTransaction,
		p.ProjectNumber + '' - ''+ p.ProjectName AS ProjectName
	from
		tMiscCost mc (nolock)
		left outer join tItem i (nolock) on mc.ItemKey = i.ItemKey
		left outer join tProject p (nolock) on mc.ProjectKey = p.ProjectKey
	Where
		mc.InvoiceLineKey = @InvoiceLineKey
		
	UNION ALL

	Select
		''VO'' as Type,
		vd.VoucherDetailKey as KeyField,
		Isnull(vd.SourceDate, v.InvoiceDate)  as ExpenseDate,
		vd.Quantity * @Percentage as Quantity,
		vd.UnitCost * @Percentage as UnitCost,
		vd.ShortDescription as ExpenseDescription,
		vd.BilledComment as ExpenseComments,
		case when @Percentage = 1 then vd.AmountBilled 
		else
		case when @Type = ''VO'' and vd.VoucherDetailKey = @KeyField 
			then (ROUND(vd.AmountBilled * @Percentage, 2)) + @RoundingError
			else (ROUND(vd.AmountBilled * @Percentage, 2))
		end
		end as AmountBilled,
		CASE vd.Quantity * @Percentage WHEN 0 THEN 0 ELSE
			case when @Percentage = 1 then vd.AmountBilled 
					else
					case when @Type = ''VO'' and vd.VoucherDetailKey = @KeyField 
						then (ROUND(vd.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(vd.AmountBilled * @Percentage, 2))
					end
			end / (vd.Quantity * @Percentage)
			END AS UnitAmount,
		vd.TotalCost * @Percentage As Net,
		CASE WHEN
			CASE vd.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
				case when @Percentage = 1 then vd.AmountBilled 
				else
					case when @Type = ''VO'' and vd.VoucherDetailKey = @KeyField 
						then (ROUND(vd.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(vd.AmountBilled * @Percentage, 2))
					end
				end / (vd.TotalCost * @Percentage) END <> 0
			THEN
				(CASE vd.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then vd.AmountBilled 
					else
						case when @Type = ''VO'' and vd.VoucherDetailKey = @KeyField 
							then (ROUND(vd.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(vd.AmountBilled * @Percentage, 2))
						end
					end / (vd.TotalCost * @Percentage) END - 1) * 100
			ELSE
				CASE vd.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then vd.AmountBilled 
					else
						case when @Type = ''VO'' and vd.VoucherDetailKey = @KeyField 
							then (ROUND(vd.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(vd.AmountBilled * @Percentage, 2))
						end
					end / (vd.TotalCost * @Percentage) END
			END AS Markup,
		i.ItemName AS ItemDescription,
		CompanyName AS VendorName,
		InvoiceDate AS VoucherDate,
		VoucherID,
		VoucherTotal,
		ROUND(ISNULL(vd.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(vd.TotalCost,0.00)* @Percentage, 2) As MarkupAmount,
		-- if there is no split billing and the billed = gross, get the markup from the transaction
		case when @Percentage = 1 and vd.AmountBilled = vd.BillableCost then vd.Markup else null end as MarkupOnTransaction,
		p.ProjectNumber + '' - ''+ p.ProjectName AS ProjectName	
	from
		tVoucher v (nolock)
		INNER JOIN tCompany c (nolock) ON v.VendorKey = c.CompanyKey
		INNER JOIN tVoucherDetail vd (nolock) on
			v.VoucherKey = vd.VoucherKey
		left outer join tItem i (nolock) on vd.ItemKey = i.ItemKey
		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 tProject p (nolock) on p.ProjectKey = vd.ProjectKey
	Where
		vd.InvoiceLineKey = @InvoiceLineKey AND
		(vd.PurchaseOrderDetailKey IS NULL OR po.POKind = 0)
		
	UNION ALL

	Select
		''PO'' as Type,
		pod.PurchaseOrderDetailKey as KeyField,
		po.PODate as ExpenseDate,
		pod.Quantity * @Percentage as Quantity,
		pod.UnitCost * @Percentage as UnitCost,
		pod.ShortDescription as ExpenseDescription,
		ISNULL(pod.BilledComment, pod.LongDescription) as ExpenseComments,
		case when @Percentage = 1 then pod.AmountBilled 
		else
		case when @Type = ''PO'' and pod.PurchaseOrderDetailKey = @KeyField 
			then (ROUND(pod.AmountBilled * @Percentage, 2)) + @RoundingError
			else (ROUND(pod.AmountBilled * @Percentage, 2))
		end 
		end as AmountBilled,
		CASE pod.Quantity * @Percentage WHEN 0 THEN 0 ELSE
			case when @Percentage = 1 then pod.AmountBilled 
					else
					case when @Type = ''PO'' and pod.PurchaseOrderDetailKey = @KeyField 
						then (ROUND(pod.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(pod.AmountBilled * @Percentage, 2))
					end 
			end / (pod.Quantity * @Percentage)
			END AS UnitAmount,
		pod.TotalCost * @Percentage As Net,
		CASE WHEN
			CASE pod.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
				case when @Percentage = 1 then pod.AmountBilled 
				else
					case when @Type = ''PO'' and pod.PurchaseOrderDetailKey = @KeyField 
						then (ROUND(pod.AmountBilled * @Percentage, 2)) + @RoundingError
						else (ROUND(pod.AmountBilled * @Percentage, 2))
					end 
				end / (pod.TotalCost * @Percentage) END <> 0
			THEN
				(CASE pod.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then pod.AmountBilled 
					else
						case when @Type = ''PO'' and pod.PurchaseOrderDetailKey = @KeyField 
							then (ROUND(pod.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(pod.AmountBilled * @Percentage, 2))
						end 
				end / (pod.TotalCost * @Percentage) END - 1) * 100
			ELSE
				CASE pod.TotalCost * @Percentage WHEN 0 THEN 0 ELSE
					case when @Percentage = 1 then pod.AmountBilled 
					else
						case when @Type = ''PO'' and pod.PurchaseOrderDetailKey = @KeyField 
							then (ROUND(pod.AmountBilled * @Percentage, 2)) + @RoundingError
							else (ROUND(pod.AmountBilled * @Percentage, 2))
						end 
				end / (pod.TotalCost * @Percentage) END
			END AS Markup,
		i.ItemName AS ItemDescription,
		NULL AS VendorName,
		NULL AS VoucherDate,
		NULL AS VoucherID,
		NULL AS VoucherTotal,
	    ROUND(ISNULL(pod.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(pod.TotalCost,0.00)* @Percentage, 2) As MarkupAmount,
		-- if there is no split billing and the billed = gross, and the POKind = 0 get the markup from the transaction (BI/IO have a commission)
		case when @Percentage = 1 and po.POKind = 0 and pod.AmountBilled = pod.BillableCost then pod.Markup else null end as MarkupOnTransaction,
		p.ProjectNumber + '' - ''+ p.ProjectName AS ProjectName	
	from
		tPurchaseOrder po (nolock)
		INNER JOIN tPurchaseOrderDetail pod (nolock) on
			po.PurchaseOrderKey = pod.PurchaseOrderKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
		left outer join tProject p (nolock) on pod.ProjectKey = p.ProjectKey
	Where
		pod.InvoiceLineKey = @InvoiceLineKey and
	po.POKind = 0

ORDER BY ExpenseDate ASC
END

if @Mode = 2
BEGIN

Select 
	ItemDescription,	
	Sum(Quantity) as Quantity,
	Sum(AmountBilled) as AmountBilled,
	Sum(Net) as Net,
	NULL AS MarkupOnTransaction -- will be recalculated in the report in VB
	
From (

	Select 
		''ER'' as Type,
		er.ExpenseReceiptKey as KeyField,
		er.ExpenseDate as ExpenseDate,
		er.ActualQty * @Percentage as Quantity, 
		er.ActualUnitCost * @Percentage as UnitCost,
		er.Description as ExpenseDescription, 
		ISNULL(er.BilledComment, er.Comments) as ExpenseComments, 
		er.AmountBilled * @Percentage as AmountBilled,	
		er.ActualCost * @Percentage As Net,
		i.ItemName AS ItemDescription,
	    ROUND(ISNULL(er.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(er.ActualCost,0.00)* @Percentage, 2) As MarkupAmount
	From
		tExpenseReceipt er (nolock)
		left outer join tItem i (nolock) on er.ItemKey = i.ItemKey
	Where
		er.InvoiceLineKey = @InvoiceLineKey

	UNION ALL

	Select
		''MC'' as Type,
		mc.MiscCostKey as KeyField,
		mc.ExpenseDate as ExpenseDate,
		mc.Quantity * @Percentage as Quantity,
		mc.UnitCost * @Percentage as UnitCost,
		mc.ShortDescription as ExpenseDescription,
		ISNULL(mc.BilledComment, mc.LongDescription) as ExpenseComments,
		mc.AmountBilled * @Percentage as AmountBilled,
		mc.TotalCost * @Percentage As Net,	  
		i.ItemName AS ItemDescription,
        ROUND(ISNULL(mc.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(mc.TotalCost,0.00)* @Percentage, 2) As MarkupAmount
	from
		tMiscCost mc (nolock)
		left outer join tItem i (nolock) on mc.ItemKey = i.ItemKey
	Where
		mc.InvoiceLineKey = @InvoiceLineKey
		
	UNION ALL

	Select
		''VO'' as Type,
		vd.VoucherDetailKey as KeyField,
		Isnull(vd.SourceDate, v.InvoiceDate) as ExpenseDate,
		vd.Quantity * @Percentage as Quantity,
		vd.UnitCost * @Percentage as UnitCost,
		vd.ShortDescription as ExpenseDescription,
		vd.BilledComment as ExpenseComments,
		vd.AmountBilled * @Percentage as AmountBilled,
		vd.TotalCost * @Percentage As Net,
		i.ItemName AS ItemDescription,
 	    ROUND(ISNULL(vd.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(vd.TotalCost,0.00)* @Percentage, 2) As MarkupAmount
	from
		tVoucher v (nolock)
		INNER JOIN tVoucherDetail vd (nolock) on
			v.VoucherKey = vd.VoucherKey
		left outer join tItem i (nolock) on vd.ItemKey = i.ItemKey
		left outer join tPurchaseOrderDetail pod (nolock) on vd.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey
		left outer join tPurchaseOrder po (nolock) on pod.PurchaseOrderKey = po.PurchaseOrderKey
	Where
		vd.InvoiceLineKey = @InvoiceLineKey AND
		(vd.PurchaseOrderDetailKey IS NULL OR po.POKind = 0)
		
	UNION ALL

	Select
		''PO'' as Type,
		pod.PurchaseOrderDetailKey as KeyField,
		po.PODate as ExpenseDate,
		pod.Quantity * @Percentage as Quantity,
		pod.UnitCost * @Percentage as UnitCost,
		pod.ShortDescription as ExpenseDescription,
		ISNULL(pod.BilledComment, pod.LongDescription) as ExpenseComments,
		pod.AmountBilled * @Percentage as AmountBilled,
		pod.TotalCost * @Percentage As Net,
		i.ItemName AS ItemDescription,
		ROUND(ISNULL(pod.AmountBilled,0.00) * @Percentage, 2) - ROUND(ISNULL(pod.TotalCost,0.00)* @Percentage, 2) As MarkupAmount
	from
		tPurchaseOrder po (nolock)
		INNER JOIN tPurchaseOrderDetail pod (nolock) on
			po.PurchaseOrderKey = pod.PurchaseOrderKey
		left outer join tItem i (nolock) on pod.ItemKey = i.ItemKey
	Where
		pod.InvoiceLineKey = @InvoiceLineKey and
	po.POKind = 0
	
	) as Detail
	
Group By
	ItemDescription

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





ALTER VIEW [dbo].[vReport_OrderDetail]
AS

/*
|| When     Who Rel		What
|| 07/20/18	MAS 18.8.0	(395210) Created. 
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color and department
|| 04/07/25 AMP 25.05.18 (697727) Added Media Plan ID and Media Plan Name
|| 12/01/25 RLS 26.01.18 (713662) Added [Materials Sent Date] and [Account Manager]
|| 01/15/25 RLB 26.02.15 (719253) Added Line Date which is a copy of Insertion Date for SQL scrubbing reasons
|| 01/16/25 RLB 26.02.15 (719243) Added Item Sales Account
|| 04/23/26 MCM 26.05.x  (725435) Added InteractiveAdUnitName as Ad Size
*/

SELECT 
	 po.CompanyKey
	,po.GLCompanyKey
	,pod.CustomFieldKey
	,cl.CustomFieldKey as CustomFieldKey2
    ,po.PurchaseOrderNumber AS [Order Number]
    ,c.VendorID AS [Vendor ID]
    ,c.CompanyName AS [Vendor Name]
    ,c.VendorID + '' - '' + c.CompanyName AS [Vendor Full Name]
	,st.StationID as [Publication ID]
	,st.Name as [Publication Name]
	,st.StationID + '' - '' + st.Name as [Publication Full Name]
    ,po.Contact AS [Vendor Contact]
    ,po.Address1 AS [Address 1]
    ,po.Address2 AS [Address 2]
    ,po.Address3 AS [Address 3]
    ,po.City AS [Address City]
    ,po.State AS [Address State]
    ,po.PostalCode AS [Address Postal Code]
    ,po.Country AS [Address Country]
    ,po.DateCreated AS [Date Created]
    ,po.PODate AS [Order Date]
    ,po.OrderedBy AS [Ordered By]
    ,po.SpecialInstructions AS [Special Instructions]
    ,po.DeliveryInstructions AS [Traffic Instructions]
    ,po.Revision AS [Revision Number]
    ,po.ApprovedDate AS [Approved Date]
	,Case ISNULL(po.POKind, 0) 
		When 0 Then ''Purchase Order''
		When 1 Then ''Insertion Order''
		When 2 Then ''Broadcast Order''
	 End As [Order Type]
    ,Case When po.Closed = 1 then ''Closed'' else 
		case po.Status 
			when 1 then ''Not Sent For Approval''
			when 2 then ''Sent for Approval''
			when 3 then ''Rejected''
			when 4 then ''Open Approved'' end 
		end as [Status]
    ,case po.Closed when 1 then ''YES'' else ''NO'' end as [Closed]
    ,case po.Downloaded when 1 then ''YES'' else ''NO'' end as [Downloaded]
	,me.EstimateID as [Media Estimate ID]
	,me.EstimateName as [Media Estimate Name]
	,me.EstimateID + '' - '' + me.EstimateName as [Media Estimate Full Name]
    ,pod.LineNumber AS [Line Number]
    ,p.ProjectName AS [Project Name]
    ,p.ProjectNumber AS [Project Number]
    ,p.ProjectNumber + '' - '' + p.ProjectName AS [Project Full Name]
	,cp.CampaignName as [Campaign Name]
	,cp.CampaignID as [Campaign ID]
    ,t.TaskID AS [Task ID]
    ,t.TaskName AS [Task Name]
    ,t.TaskID + '' - '' + t.TaskName AS [Task Full Name]
    ,pod.ShortDescription AS [Caption]
    ,pod.LongDescription AS [Line Comments]
	,i.ItemID as [Item ID]
	,i.ItemName as [Item Name]
	,gla.AccountNumber + '' - '' + gla.AccountName as [Item Expense Account]
	,gla2.AccountNumber + '' - '' + gla2.AccountName as [Item Sales Account]
    ,pod.TotalCost AS [Net Amount]
	,ISNULL(pod.AccruedCost, 0) as [Line Accrued Cost]
	,pod.TotalCost - ISNULL(pod.AccruedCost, 0) as [Line Accrued Cost Difference]
	,pod.AdjustmentNumber as [Adjustment Number]
	,Case when pod.InvoiceLineKey > 0 then 0 else ISNULL(pod.AmountBilled, 0) - pod.BillableCost end as [Billed Difference]
    ,ISNULL((Select Sum(PrebillAmount) from tVoucherDetail (nolock) Where tVoucherDetail.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey), 0) as [Line Amount Unaccrued]
    ,ISNULL(pod.AccruedCost, 0) - ISNULL((Select Sum(PrebillAmount) from tVoucherDetail (nolock) Where tVoucherDetail.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey), 0) as [Line Amount Left To Unaccrue]
	,ISNULL(pod.AppliedCost, 0) AS [Applied Invoices]
	,ISNULL(pod.TotalCost, 0) - ISNULL(pod.AppliedCost, 0) AS [Open Amount]
	,case when pod.InvoiceLineKey > 0 then ISNULL(pod.AmountBilled, 0) else 0 end as [Amount Billed]
	,pod.DetailOrderDate as [Insertion Date]
	,pod.DetailOrderDate as [Line Date]
	,pod.Markup as [Markup Percent]
	,case when pod.InvoiceLineKey > 0 then ISNULL(pod.AmountBilled, 0) else 0 end 
	+ ISNULL((Select Sum(ISNULL(AmountBilled, 0)) from tVoucherDetail vd (nolock) Where pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey and vd.InvoiceLineKey > 0), 0) as [Total Billed]
	,case pod.Markup when 1 then ''YES'' else ''NO'' end as [Commission]
	,(Select Sum(ISNULL(AmountBilled, 0)) from tVoucherDetail vd (nolock) Where pod.PurchaseOrderDetailKey = vd.PurchaseOrderDetailKey and vd.InvoiceLineKey > 0) as [Amount Billed On Vendor Invoices]
    ,pod.BillableCost AS [Gross Amount]
	,pod.UserDate1 as [User Defined Date 1]
	,pod.UserDate2 as [User Defined Date 2]
	,pod.UserDate3 as [User Defined Date 3]
	,pod.UserDate4 as [User Defined Date 4]
	,pod.UserDate5 as [User Defined Date 5]
	,pod.UserDate6 as [User Defined Date 6]
	,pod.UserDate1 as [Space Close]
	,pod.UserDate2 as [Materials Due]
	,iv.InvoiceNumber as [Line Invoice Number]
	,iv.PostingDate as [Line Date Billed]
	,iv.InvoiceDate as [Invoice Date]
	,iv.InvoiceNumber as [Invoice Number]
	,iv.TotalNonTaxAmount as [Invoice Non Tax Total]
	,iv.SalesTaxAmount as [Invoice Sales Tax Total]
	,iv.InvoiceTotalAmount as [Invoice Total]
	,ISNULL(iv.InvoiceTotalAmount, 0) - ISNULL(iv.AmountReceived, 0) - ISNULL(iv.WriteoffAmount, 0) - ISNULL(iv.RetainerAmount, 0) as [Invoice Amount Open]
	,iv.HeaderComment as [Invoice Comment]

	,case pod.Closed when 1 then ''YES'' else ''NO'' end as [Line Closed]

	,CASE ISNULL(po.POKind, 0)
		WHEN 0 THEN cl.CompanyName
		WHEN 1 THEN
			CASE ISNULL(pref.IOClientLink, 1) -- 1 Project, 2 - Estimate
				WHEN 1 THEN cl.CompanyName
				ELSE cl2.CompanyName
			END  
		WHEN 2 THEN
			CASE ISNULL(pref.BCClientLink, 1)
				WHEN 1 THEN cl.CompanyName
				ELSE cl2.CompanyName
			END  			
	END as [Client Name]

    ,CASE ISNULL(po.POKind, 0)
		WHEN 0 THEN cl.CustomerID
		WHEN 1 THEN
			CASE ISNULL(pref.IOClientLink, 1) -- 1 Project, 2 - Estimate
				WHEN 1 THEN cl.CustomerID
				ELSE cl2.CustomerID
			END  
		WHEN 2 THEN
			CASE ISNULL(pref.BCClientLink, 1)
				WHEN 1 THEN cl.CustomerID
				ELSE cl2.CustomerID
			END  
	END as [Client ID]

	,CASE ISNULL(po.POKind, 0) -- UserFullName
			WHEN 0 THEN sales.UserFullName
		WHEN 1 THEN
			CASE ISNULL(pref.IOClientLink, 1) -- 1 Project, 2 - Estimate
				WHEN 1 THEN sales.UserFullName
				ELSE sales2.UserFullName
			END  
		WHEN 2 THEN
			CASE ISNULL(pref.BCClientLink, 1) 
				WHEN 1 THEN sales.UserFullName
				ELSE sales2.UserFullName
			END  
	END as [Sales Person]

	,mm.MarketID as [Market ID]
    ,mm.MarketName as [Market Name]
	,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]
	,o.OfficeName as [Office Name]
	,o.OfficeColor as [Office Color]
	,d.DepartmentName as Department
	,d.DepartmentColor as [Department Color]
	,Case When pod.TransferToKey IS NULL Then ''NO'' else ''YES'' end as [Transferred Out]
	,p.ProjectKey
	,po.[Description] as [Order Description]
	,po.CurrencyID as [Currency]
	,cd.DivisionID as [Client Division ID]
    ,cd.DivisionName as [Client Division]
    ,pc.ProductID as [Client Product ID]
    ,pc.ProductName as [Client Product]
	,mp2.PlanID  as [Media Plan ID]
	,mp2.PlanName as [Media Plan Name]
	,pod.MaterialsSentDate AS [Materials Sent Date]
	,pod.InteractiveAdUnitName AS [Ad Size]
	,ISNULL(AMProj.UserFullName, AMClient.UserFullName) AS [Account Manager]
FROM 
	tPurchaseOrder po (nolock)
	INNER JOIN tPurchaseOrderDetail pod (nolock) ON po.PurchaseOrderKey = pod.PurchaseOrderKey
	INNER JOIN tPreference pref (nolock) ON po.CompanyKey = pref.CompanyKey
    INNER JOIN tCompany c (nolock) ON po.VendorKey = c.CompanyKey 
	LEFT OUTER JOIN tTask t (nolock) ON pod.TaskKey = t.TaskKey 
	LEFT OUTER JOIN tProject p (nolock) ON pod.ProjectKey = p.ProjectKey
	LEFT OUTER JOIN tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	LEFT OUTER JOIN tCompanyMedia st (nolock) on po.CompanyMediaKey = st.CompanyMediaKey
	LEFT OUTER JOIN tItem i (nolock) on pod.ItemKey = i.ItemKey
	Left OUTER JOIN tGLAccount gla (nolock) on i.ExpenseAccountKey = gla.GLAccountKey
	Left OUTER JOIN tGLAccount gla2 (nolock) on i.SalesAccountKey = gla2.GLAccountKey
	left outer join tMediaEstimate me (nolock) on po.MediaEstimateKey = me.MediaEstimateKey
	LEFT OUTER JOIN tCompany cl2 (nolock) on me.ClientKey = cl2.CompanyKey
	left outer join tCampaign cp (nolock) on p.CampaignKey = cp.CampaignKey
    left outer join tMediaMarket mm (nolock) on st.MediaMarketKey = mm.MediaMarketKey
	left outer join tClass cla (nolock) on pod.ClassKey = cla.ClassKey
	left outer join tGLCompany glc (nolock) on po.GLCompanyKey = glc.GLCompanyKey
	left outer join tOffice o (nolock) on pod.OfficeKey = o.OfficeKey
	left outer join tDepartment d (nolock) on pod.DepartmentKey = d.DepartmentKey
	left outer join tInvoiceLine il (nolock) on pod.InvoiceLineKey = il.InvoiceLineKey
	left outer join tInvoice iv (nolock) on il.InvoiceKey = iv.InvoiceKey
	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 vUserName sales (nolock) on cl.SalesPersonKey = sales.UserKey
	left outer join vUserName sales2 (nolock) on cl2.SalesPersonKey = sales2.UserKey
	left outer join 
				 (SELECT mp.PlanID, mp.PlanName, pod.PurchaseOrderKey
				  FROM
					  tPurchaseOrderDetail pod
					  INNER JOIN tMediaPlanDetail mpd (nolock) on mpd.PurchaseOrderDetailKey =  pod.PurchaseOrderDetailKey
					  INNER JOIN tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
				  	  INNER JOIN tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey						
				  GROUP BY mp.PlanID, mp.PlanName, pod.PurchaseOrderKey) AS mp2 on mp2.PurchaseOrderKey = pod.PurchaseOrderKey	  
left outer join vUserName AMProj (nolock) on p.AccountManager = AMProj.UserKey
left outer join vUserName AMClient (nolock) on cl.AccountManagerKey = AMClient.UserKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[vReport_Transactions_PO]'
GO
IF OBJECT_ID(N'[dbo].[vReport_Transactions_PO]', 'V') IS NOT NULL
EXEC sp_executesql N'














ALTER VIEW [dbo].[vReport_Transactions_PO]
AS

/*
|| When     Who Rel     What
|| 10/11/06 WES 8.3567  Added Date Billed
|| 10/12/06 WES 8.3567  Added Retainer Name
|| 10/13/06 WES 8.3567  Added Project Billing Status
|| 10/16/06 WES 8.3567  Added Posting Date
|| 12/18/06 GWG 8.4     Added WIP Posting Dates
|| 12/21/06 CRG 8.4     Added Billed On Invoice, Invoice Posting Date, Expense Account Number, Expense Account Name
|| 02/26/07 BSH 8.4     Added WriteOff Date, Cost and Billable Amount
|| 10/11/07 CRG 8.5     Added GLCompany, Class
|| 11/07/07 CRG 8.5     (9205) Modified to get Class from the Transactions rather than the Project.
|| 11/07/07 CRG 8.5     (9581) Added Marked as Billed
|| 02/01/08 GHL 8.5     (20472) Added logic for expense receipts on voucher
|| 03/04/08 GWG 8.5     (22285) Changed Writeoff amount to be sensitive to the write off field
|| 03/08/08 GWG 8.5     (22734) Added Campaign Name
|| 04/02/09 RLB 10.02.2 (50160) Fixed project billing status it was not pulling data correctly
|| 04/08/09 GHL 10.022  (50462) Added Vendor Name and Total Labor Cost
|| 04/14/09 GHL 10.023  (51139) Added Client Division/Client Product 
|| 04/14/09 GHL 10.023  (51139) Added Company Type/Last Task Due Date
|| 04/24/09 MFT 10.024	(51139) Added Transaction Department
|| 06/15/09 GHL 10.027  (54845) Added Transaction Number to get v.InvoiceNumber, ee.EnvelopeNumber + user
|| 09/11/09 GHL 10.5     Added Transferred Out
|| 01/19/10 GHL 10.517  (72527) Added Billing Item info
|| 02/18/10 GHL 10.518  (73756) Added Amount Billed Approved
|| 05/25/11 GHL 10.544  (109956) Cloned vReport_Transactions_PO but using now vProjectTransPO
||                      i.e. has open orders
|| 07/27/11 RLB 10.546  (111324) Added Campaign Segment
|| 09/20/11 RLB 10.548  (121590) Removed Total Labor Cost column per Mikes request
|| 09/21/11 RLB 10.548  (119193) Added Project Close Date 
|| 04/03/12 GHL 10.555  Added GLCompanyKey for map/restrict
|| 06/22/12 RLB 10.557  (146849) Added Transaction Month and year
|| 08/17/12 RLB 10.559 (151960) Added Billing Group Code
|| 09/28/12 GHL 10.560 Getting now BillingGroupCode from tBillingGroup
|| 10/29/12 CRG 10.5.6.1 (156391) Added ProjectKey
|| 11/15/12 GWG 10.5.6.2 Added transfer in out dates
|| 01/30/13 GHL 10.5.6.4 (166680) Added Billing Method
|| 11/06/14 WDF 10.5.8.6 (233050) Added Billing Manager
|| 01/27/15 WDF 10.5.8.8 (Abelson Taylor) Added Division and Product ID
|| 01/29/15 GHL 10.5.8.8 (Abelson Taylor) Added Title
|| 03/20/15 WDF 10.5.9.0 (Abelson Taylor) Added AdjustmentType
|| 10/05/15 GHL 10.5.9.7 (272410) Added check of Write Off flag when pulling Write Off Date
|| 04/12/16 MFT 10.6.0.3 (296036) Added WriteOffComment
|| 06/08/16 WDF 10.6.0.5 (303066) Added PurchasedFrom
|| 06/14/16 GHL 10.6.0.5 (303598) move er.DateBilled vs vd.DateBilled when the exp receipt applied to a voucher is prebilled
||                       to vProjectTransPO. Improves perfo by moving it there
|| 07/12/16 WDF 10.6.0.6 (299976) Added Campaign Custom Fields
|| 08/16/16 KMC 10.6.0.7 (308209) Added [Parent Company Name] and [Parent Division Name] from the company page (Client Setup...Billing).
|| 02/08/17 WDF 10.6.1.3 (331895) Added [Project Description]
|| 05/20/17 GWG 10.6.1.5 Added project primary contact and email
|| 05/15/18 GWG 18.5.0.0 added campaign active
|| 08/15/18 WDF 18.9.0.0 (415376) Added [CustomFieldKey3]
|| 10/09/18 RLS 18.9.2.0 (423590) Added [Current Budget Expense Gross],[Current Budget Hours],[Current Budget Labor Gross],[Current Total Budget],[Current Total Budget wo Tax]. Taken from vReport_Transactions
|| 12/06/18 MFT 19.1.0.0 (434596) Wrapped LayoutKey in ISNULL
|| 12/07/18 GHL 19.1.0.0 (424920) Added [Gross Amount] = GrossAmount (mainly for VIs with prebilled POs applied 
||                        , in that case GrossAmount = 1000 and BillableCost = 0 )
|| 05/13/19 GHL 19.0.6.0 (459967) Added Applied Order number
|| 07/09/19 RLS 19.0.8.0 (468625) Added [Summary Task ID], [Summary Task Name] and [Summary Task Full Name]
|| 07/18/19 GAR 19.0.8.0 (470619) Adding Project Manager
|| 07/29/19 WDF 19.0.8.0 (471596) Corrected alias of [Campaign Active] from cp to ca
|| 07/30/19 WDF 19.0.8.0 (472402) Corrected format of [Campaign Full Name] for linking in Report
|| 11/01/19 AMP 19.1.2.0 (486097) Added ''Yes''/''No'' to be able to filter by Planning Project
|| 02/18/20 AMP 20.0.3.0 (500814) Added Client Project Number 
|| 09/02/20 RLB 20.1.0.0 (523772) making anything using user name common format
|| 05/18/21 AMP 21.06.20.0000 (558708) Added currency field 
|| 05/16/22 RLS 22.06.19 (596563) Added [Transaction Month Formatted]
|| 08/03/22 MFT 22.0.8.0 (607757) Added "s" to "Time and Material"
|| 11/29/22 RLS 22.12.18 (614994) Added TransactionApprovalDate
|| 03/13/23 RLB 23.04.16 (629165) Adding Office Color
|| 05/30/23 RLS 23.16.18 (635138) Added TransactionPostingDate
|| 08/11/23 RLB 23.09.17 (648008) added project type color
|| 08/22/24 RLS 24.09.15 (663719) Added [Current Budget Expense Net]
|| 01/08/24 RLB 25.02.16 (686787) Added Project Team from Voucher Header or PO Header, PO Header Description and Vendor invoice Description both from header
|| 02/24/25 RLS 25.03.16 (691112) Added [Media Plan Name], [Media Plan ID], [Station Name], [Station ID], [Publication ID], [Publication Name], [Media Estimate ID], [Media Estimate Name]
|| 04/07/25 RLB 25.05.18 (698512) Added Do Not Post WIP from the project
|| 09/04/25 RLS 25.09.21 (708615) Added PODCustomFieldKey
|| 09/29/25 MCM 25.10.x  (700642) Added TransactionKey 
|| 04/28/26 RLS 26.05.17 (724768) Added [Contractor]
*/

Select 
	p.CompanyKey
	,pt.GLCompanyKey
	,p.CustomFieldKey
	,ca.CustomFieldKey as [CustomFieldKey2]
	,cl.CustomFieldKey as [CustomFieldKey3]
	,pt.PODCustomFieldKey as [CustomFieldKey4]
	,p.ProjectNumber as [Project Number]
	,p.ProjectName as [Project Name]
	,p.ProjectNumber + '' - '' + p.ProjectName  as [Project Full Name]
	,p.Description as [Project Description]
	,p.StartDate as [Project Start Date]
	,p.CompleteDate as [Project Complete Date]
	,p.CreatedDate as [Project Creation Date]
	,p.ProjectCloseDate as [Project Close Date]

	,p.EstExpenses + p.ApprovedCOExpense as [Current Budget Expense Gross]
	,p.EstHours + p.ApprovedCOHours as [Current Budget Hours]
	,p.EstLabor + p.ApprovedCOLabor as [Current Budget Labor Gross]
	,p.EstLabor + p.EstExpenses + ISNULL(p.SalesTax, 0) + p.ApprovedCOLabor + p.ApprovedCOExpense + ISNULL(p.ApprovedCOSalesTax, 0) as [Current Total Budget]
	,p.EstLabor + p.EstExpenses + p.ApprovedCOLabor + p.ApprovedCOExpense as [Current Total Budget wo Tax]
	,Case p.PlanningProject When 1 THEN ''YES'' ELSE ''NO'' END as [Planning Project]
	,Case p.DoNotPostWIP WHEN 1 THEN ''YES'' ELSE ''NO'' END as [Do Not Post WIP]

	,bg.BillingGroupCode as [Billing Group Code]
 	,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]
	,ps.ProjectStatus as [Project Status]
	,Case p.NonBillable When 1 then ''YES'' else ''NO'' end as [Non Billable Project]
	,Case p.BillingMethod When 1 then ''Time and Materials'' when 2 then ''Fixed Fee'' else ''Retainer'' end as [Billing Method]
	,cl.CustomerID as [Client ID]
	,cl.CompanyName as [Client Name]
	,cl.CustomerID + '' '' + cl.CompanyName as [Client Full Name]
	,t.TaskID as [Task ID]
	,t.TaskName as [Task Name]
	,o.OfficeName as [Office Name]
	,o.OfficeColor as [Office Color]
	,pty.ProjectTypeName as [Project Type]
	,pty.ProjectTypeColor as [Project Type Color]
	,LTRIM(RTRIM(ISNULL(am.FirstName + '' '','''')  + ISNULL(am.LastName,''''))) AS [Account Manager]
	,LTRIM(RTRIM(ISNULL(bm.FirstName + '' '','''')  + ISNULL(bm.LastName,''''))) AS [Billing Manager]
	,LTRIM(RTRIM(ISNULL(pm.FirstName + '' '','''')  + ISNULL(pm.LastName,''''))) AS [Project Manager]
	,pt.TransactionDate
	,pt.PurchasedFrom as [Purchased From]
	,DATENAME(Month, pt.TransactionDate) as [Transaction Month]
	,RIGHT(''0'' + CAST(DATEPART(Month, pt.TransactionDate) AS VARCHAR(2)), 2) + '' '' + DATENAME(Month, pt.TransactionDate) AS [Transaction Month Formatted]
	,CAST(DATEPART(Year, pt.TransactionDate) AS VARCHAR(4)) as [Transaction Year]
	,pt.Type as [Transaction Type]
	,pt.ItemID as [Item ID]
	,pt.ItemName as [Item Name]
	,pt.Quantity
	,pt.UnitCost as [Unit Cost]
	,pt.TotalCost as [Total Cost]
	,pt.BillableCost as [Billable Amount]
	,pt.GrossAmount as [Gross Amount]
	,case when pt.WriteOff = 1 then pt.TotalCost else 0 end as [Write Off Total Cost]
	,case when pt.WriteOff = 1 then pt.BillableCost else 0 end as [Write Off Billable Amount]
	,pt.TransferComment as [Transfer Comment]
	,pt.Comments
	,Case pt.WriteOff When 1 then ''YES'' else ''NO'' end as [Write Off]
	,Case pt.OnHold When 1 then ''YES'' else ''NO'' end as [On Hold]
	,Case pt.Status 
		When 1 then ''Not Sent''
		When 2 then ''Sent for Approval''
		When 3 then ''Rejected''
		When 4 then ''Approved''
	end as [Approval Status]
	,wor.ReasonName as [Write Off Reason]
	,pt.WriteOffComment AS [Write Off Comment]
	,rn.Title as [Retainer Name]
	,pbs.ProjectBillingStatus as [Project Billing Status]
	,wpi.PostingDate as [WIP Posting In Date]
	,wpo.PostingDate as [WIP Posting Out Date]
	,gl.AccountNumber AS [Expense Account Number]
	,gl.AccountName AS [Expense Account Name]
	,pt.DateBilled as [Write Off Date]
	,glc.GLCompanyID as [Company ID]
	,glc.GLCompanyName as [Company Name]
	,cla.ClassID as [Class ID]
	,cla.ClassName as [Class Name]
	,ca.CampaignName as [Campaign Name]
	,ca.CampaignID as [Campaign ID]
	,ca.CampaignID + '' - '' +  ca.CampaignName as [Campaign Full Name]
	,cs.SegmentName as [Campaign Segment]
	-- All these should change if there is a billed expense receipt  	
	,case when er.InvoiceLineKey > 0 then pt.Description + '' - Prebilled on expense report''  else pt.Description end as [Transaction Description] 
	,case when er.InvoiceLineKey > 0 then er.AmountBilled else pt.AmountBilled end as [Amount Billed] 
    ,case when er.InvoiceLineKey > 0 then
		case when isnull(eri.InvoiceStatus, 0) = 4 then er.AmountBilled else 0 end
    else
		case when isnull(i.InvoiceStatus, 0) = 4 then pt.AmountBilled else 0 end
	end as [Amount Billed Approved]
	,pt.DateBilled as [Date Billed]
	,case when er.InvoiceLineKey > 0 then eri.InvoiceNumber else i.InvoiceNumber end as [Invoice Number]
	,case when er.InvoiceLineKey > 0 then eri.PostingDate else i.PostingDate end as  [Invoice Posting Date]
	,case when er.InvoiceLineKey > 0 then pt.BillableCost - er.AmountBilled else pt.BilledDifference end as [Billed Difference]	
	,CASE 
		WHEN ISNULL(er.InvoiceLineKey, -1) > 0 THEN ''YES''
		WHEN ISNULL(pt.InvoiceLineKey, -1) > 0 THEN ''YES''
		ELSE ''NO''
	END AS [Billed On Invoice]
	,CASE 
		WHEN ISNULL(er.InvoiceLineKey, -1) = 0 THEN ''YES''
		WHEN ISNULL(pt.InvoiceLineKey, -1) = 0 THEN ''YES''
		ELSE ''NO''
	END AS [Marked as Billed]
	,v.CompanyName as [Vendor Name]
	,v.VendorID + '' '' + v.CompanyName as [Vendor Full Name]
	,cv.DivisionName as [Client Division]
	,cv.DivisionID as [Client Division ID]
	,cp.ProductName as [Client Product]
	,cp.ProductID as [Client Product ID]
	,ct.CompanyTypeName as [Company Type]
	,(SELECT MAX(t2.PlanComplete) FROM tTask t2 (NOLOCK) WHERE t2.ProjectKey = p.ProjectKey) as [Last Task Due Date]
	,pt.DepartmentName AS [Transaction Department]
    ,pt.TranNumber AS [Transaction Number]
    ,pt.EnteredByUser AS [Entered By]
    ,case when pt.UIDTransferToKey is not null then ''YES''
          when pt.TransferToKey is not null then ''YES''
          else ''NO''
     end as [Transferred Out]
    ,pt.TransferInDate as [Transferred In Date]
    ,pt.TransferOutDate as [Transferred Out Date]
    ,case when ISNULL(p.LayoutKey, 0) = 0 then pt.WorkTypeID 
		  else 
              case when pt.Type = ''LABOR'' then wts.WorkTypeID else wt.WorkTypeID end 
     end as [Billing Item ID] 
    ,case when ISNULL(p.LayoutKey, 0) = 0 then pt.WorkTypeName 
		  else 
              case when pt.Type = ''LABOR'' then isnull(wtcusts.Subject, wts.WorkTypeName) else isnull(wtcust.Subject, wt.WorkTypeName) end 
     end as [Billing Item Name] 
	,p.ProjectKey
	,pt.TitleName as [Billing Title Name]
	,pt.TitleID as [Billing Title ID]
	,case when pt.AdjustmentType is null then null
	      when pt.AdjustmentType = 0 and pt.TransferOutDate is not null then ''Transfer''
	      when pt.AdjustmentType = 1 then ''Edited after Posting to WIP''
	      when pt.AdjustmentType = 2 then ''Title Adjustment''
	      when pt.AdjustmentType = 3 then ''Undo Writeoff after Posting out of WIP''
	      else null
	      end as [Adjustment Type]
	,parentCompany.CompanyName as [Parent Company Name]
	,pcd.DivisionName as [Parent Division Name]
	,LTRIM(RTRIM(ISNULL(bc.FirstName + '' '','''')  + ISNULL(bc.LastName,''''))) AS [Project Primary Contact]
	,bc.Email as [Project Primary Contact Email] 
	,Case ca.Active When 1 then ''YES'' else ''NO'' end as [Campaign Active]
	,Case p.Active When 1 then ''YES'' else ''NO'' end as [Project Active]
	,pt.AppliedOrderNumber as [Applied Order Number] 
	,st.TaskID as [Summary Task ID]
	,st.TaskName as [Summary Task Name]
	,ISNULL(st.TaskID + '' '', '''') + ISNULL(st.TaskName, '''') as [Summary Task Full Name]
	,p.ClientProjectNumber as [Client Project Number]	
	,ISNULL(pt.CurrencyID, pref.CurrencyID) AS [Currency] --Get currency from the project transaction, if there is no currency set, use home currency from preferences	
	,pt.TransactionApprovalDate As [Transaction Approval Date]
	,pt.TransactionPostingDate as [Transaction Posting Date]
	,p.BudgetExpenses + p.ApprovedCOBudgetExp as [Current Budget Expense Net]
	,pt.ProjectTeam as [Project Team]
	,pt.PODescription as [PO Description]
	,pt.VIDescription as [Vendor Invoice Description]
	,pt.TransactionKey
	,mp.PlanName as [Media Plan Name]
	,mp.PlanID as [Media Plan ID]
	,cm.Name as [Station Name]
	,cm.StationID as [Station ID]
	,cm.StationID as [Publication ID]
	,cm.Name as [Publication Name]
	,me.EstimateID as [Media Estimate ID]
	,me.EstimateName as [Media Estimate Name]
	,case when pt.Contractor = 1 then ''YES'' else ''NO'' end as [Contractor]
From vProjectTransPO pt (nolock)
	inner join tProject p (nolock) on pt.ProjectKey = p.ProjectKey
	left outer join tPreference pref (nolock) on pref.CompanyKey = p.CompanyKey
	Left Outer join tTask t (nolock) on pt.TaskKey = t.TaskKey
	Left Outer join tTask st (nolock) on t.SummaryTaskKey = st.TaskKey
	Left Outer Join tProjectType pty (nolock) on p.ProjectTypeKey = pty.ProjectTypeKey
	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 bm (nolock) on p.BillingManagerKey = bm.UserKey
	Left Outer Join tInvoiceLine il (nolock) on pt.InvoiceLineKey = il.InvoiceLineKey
	Left Outer Join tInvoice i (nolock) on il.InvoiceKey = i.InvoiceKey
	left outer join tCompany cl (nolock) on p.ClientKey = cl.CompanyKey
	left outer join tCompany parentCompany (nolock) on cl.ParentCompanyKey = parentCompany.CompanyKey
	left outer join tClientDivision pcd (nolock) on cl.ParentCompanyDivisionKey = pcd.ClientDivisionKey
	Left outer Join tProjectStatus ps (nolock) on p.ProjectStatusKey = ps.ProjectStatusKey
	Left outer Join tWriteOffReason wor (nolock) on pt.WriteOffReasonKey = wor.WriteOffReasonKey
	left outer join vUserName kp1 (nolock) on p.KeyPeople1 = kp1.UserKey
	left outer join vUserName kp2 (nolock) on p.KeyPeople2 = kp2.UserKey
	left outer join vUserName kp3 (nolock) on p.KeyPeople3 = kp3.UserKey
	left outer join vUserName kp4 (nolock) on p.KeyPeople4 = kp4.UserKey
	left outer join vUserName kp5 (nolock) on p.KeyPeople5 = kp5.UserKey
	left outer join vUserName kp6 (nolock) on p.KeyPeople6 = kp6.UserKey
	left outer join tRetainer rn (nolock) on p.RetainerKey = rn.RetainerKey
	left outer join tProjectBillingStatus pbs (nolock) on p.ProjectBillingStatusKey = pbs.ProjectBillingStatusKey
	left outer join tWIPPosting wpi (nolock) on pt.WIPPostingInKey = wpi.WIPPostingKey
	left outer join tWIPPosting wpo (nolock) on pt.WIPPostingOutKey = wpo.WIPPostingKey
	left outer join tGLAccount gl (nolock) on pt.GLAccountKey = gl.GLAccountKey
	left outer join tClass cla (nolock) on pt.ClassKey = cla.ClassKey
	left outer join tGLCompany glc (nolock) on pt.GLCompanyKey = glc.GLCompanyKey
	left outer join tExpenseReceipt er (nolock) on pt.Type = ''VOUCHER'' AND pt.TranKey = er.VoucherDetailKey
	Left Outer Join tInvoiceLine eril (nolock) on er.InvoiceLineKey = eril.InvoiceLineKey
	Left Outer Join tInvoice eri (nolock) on eril.InvoiceKey =eri.InvoiceKey
	Left Outer Join tCampaign ca (nolock) on p.CampaignKey = ca.CampaignKey
	left outer join tCompany v (nolock) on pt.VendorKey = v.CompanyKey
	left outer join tClientDivision cv (nolock) on p.ClientDivisionKey = cv.ClientDivisionKey
    left outer join tClientProduct cp (nolock) on p.ClientProductKey = cp.ClientProductKey
    left outer join tCompanyType ct (nolock) on cl.CompanyTypeKey = ct.CompanyTypeKey

    left outer join tLayoutBilling lb (nolock) on p.LayoutKey = lb.LayoutKey and lb.Entity = ''tItem'' and pt.Type <> ''LABOR'' and lb.EntityKey = pt.ItemKey
    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 tLayoutBilling lbs (nolock) on p.LayoutKey = lbs.LayoutKey and lbs.Entity = ''tService'' and pt.Type = ''LABOR'' and lbs.EntityKey = pt.ItemKey
    left outer join tWorkType wts (nolock) on lbs.ParentEntityKey = wts.WorkTypeKey and lbs.ParentEntity = ''tWorkType''
    left outer join tWorkTypeCustom wtcusts (nolock) on lbs.ParentEntityKey = wtcusts.WorkTypeKey and wtcusts.Entity = ''tProject'' and wtcusts.EntityKey = p.ProjectKey
	left outer join tCampaignSegment cs (nolock) on p.CampaignSegmentKey = cs.CampaignSegmentKey 
	left outer join tBillingGroup bg (nolock) on p.BillingGroupKey = bg.BillingGroupKey
	left outer join tUser bc (nolock) on p.BillingContact = bc.UserKey
	left outer join tUser pm (nolock) on p.ProjectManager = pm.UserKey
	left outer join tPurchaseOrder purchOrder (nolock) on pt.ParentKey = purchOrder.PurchaseOrderKey AND pt.Type = ''OPENORDER''
	left outer join tPurchaseOrderDetail purchOrderDet (nolock) on pt.TranKey = purchOrderDet.PurchaseOrderDetailKey AND pt.Type = ''OPENORDER''
	left outer join tCompanyMedia cm (nolock) on purchOrder.CompanyMediaKey = cm.CompanyMediaKey
	left outer join tMediaEstimate me (nolock) on purchOrder.MediaEstimateKey = me.MediaEstimateKey
	left outer join 
				 (SELECT mp.PlanID, mp.PlanName, pod.PurchaseOrderKey
				  FROM
						tPurchaseOrderDetail pod
					  INNER JOIN tMediaPlanDetail mpd (nolock) on mpd.PurchaseOrderDetailKey =  pod.PurchaseOrderDetailKey
					  INNER JOIN tMediaPlanVendor mpv (nolock) on mpd.MediaPlanVendorKey = mpv.MediaPlanVendorKey
				  	INNER JOIN tMediaPlan mp (nolock) on mpv.MediaPlanKey = mp.MediaPlanKey						
				  GROUP BY mp.PlanID, mp.PlanName, pod.PurchaseOrderKey) AS mp on mp.PurchaseOrderKey = purchOrderDet.PurchaseOrderKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptEstimateTaskExpenseToPOD]'
GO
IF OBJECT_ID(N'[dbo].[sptEstimateTaskExpenseToPOD]', 'P') IS NOT NULL
EXEC sp_executesql N'



ALTER PROCEDURE [dbo].[sptEstimateTaskExpenseToPOD]
	(
		@PurchaseOrderKey int
		,@UserKey INT
		,@CheckTaskPercComp INT = 0
	)
AS -- Encrypt

/*
|| When     Who Rel    What
|| 01/05/16 GHL 10.599 Created for the new WJAPP PO add screen where estimated expenses are selected to create a PO
||                     The difference with sptEstimateTaskExpenseToPOAll is that the PO is already created in VB
||                     sptEstimateTaskExpenseToPOAll is a push to PO
||                     sptEstimateTaskExpenseToPOD is a pull from the estimate(s)
|| 12/18/17 GHL 18.010 (377348) Validate department and office if they are required
|| 11/07/18 GHL 18.930 (428631) When validating the PO limits to the the Net on the PO, convert to home currency 
|| 02/06/19 GHL 19.2.0.0 (440666) Adding now *002 from the estimate number to the PO number for SPARK44NUMBER customization
|| 03/28/19 GHL 19.4.0.0 (448458/440666) for the SPARK44PONUMBER they do not want to affect the PO Number but they want to change the 
||                        way the project number is displayed on the PO print out, they want basically the estimate number=project number + ''*002'' 
|| 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
|| 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName
*/

	SET NOCOUNT ON

	DECLARE @PurchaseOrderDetailKey INT
		   ,@PurchaseOrderTypeKey int
		   ,@PurchaseOrderNumber varchar(100)
		   ,@UserName As VARCHAR(200)
		   ,@RetVal int
		   ,@InternalApprover int
		   ,@CompanyKey int
		   ,@ProjectKey int
		   ,@OrderDate smalldatetime
		   ,@ClassKey int
		   ,@TaskKey int
		   ,@ItemKey int
		   ,@ShortDescription varchar(300)
		   ,@LongDescription varchar(max)
		   ,@Quantity decimal(24,4)
		   ,@UnitCost money
		   ,@UnitDescription varchar(30)
		   ,@TotalCost money
		   ,@UnitRate money
		   ,@Billable tinyint
		   ,@Markup decimal(24,4)
		   ,@BillableCost money
		   ,@Taxable int
		   ,@Taxable2 int
		   ,@QuoteDetailKey int
		   ,@QuoteKey int
		   ,@GLCompanyKey int
		   ,@OfficeKey int
		   ,@DepartmentKey int
		   ,@PurchaseOrderDetailTypeFieldSet int
		   ,@ObjectFieldSetKey int
		   ,@CurrencyID varchar(10) -- PO currency
		   ,@ExchangeRate decimal(24,7)
		   ,@PCurrencyID varchar(10) -- Project currency
		   ,@PExchangeRate decimal(24,7)
		   ,@RateHistory int
		   ,@PTotalCost money
		   ,@GrossAmount money
		   ,@ItemType INT

	declare @NewQuantity decimal(24,4)
		   ,@NewTotalCost money
		   ,@NewBillableCost money
		   
	-- Assume done in VB
	-- CREATE TABLE #tExpense (ExpenseKey int identity(1,1),  EstimateTaskExpenseKey int null)
	
	-- Create a temp table to hold the Quote Detail Keys
	CREATE TABLE #tQuoteDetailKeys (QuoteDetailKey int null, QuoteKey int null)
	
	-- Extract info from PO	  
	select @CompanyKey = po.CompanyKey
		  ,@ProjectKey = po.ProjectKey
		  ,@OfficeKey = p.OfficeKey
		  ,@CurrencyID = po.CurrencyID
	      ,@PCurrencyID = po.PCurrencyID
		  ,@ExchangeRate = po.ExchangeRate
		  ,@PExchangeRate = po.PExchangeRate
		  ,@OrderDate = po.PODate
		  ,@ClassKey = po.ClassKey
		  ,@PurchaseOrderNumber = po.PurchaseOrderNumber
		  ,@PurchaseOrderTypeKey = po.PurchaseOrderTypeKey
	from  tPurchaseOrder po (nolock)
		  inner join tPreference pref (nolock) on po.CompanyKey = pref.CompanyKey
		  left outer join tProject p (nolock) on po.ProjectKey = p.ProjectKey
	where PurchaseOrderKey = @PurchaseOrderKey 

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

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

	--Added for setting the Detail Default LineType (177872) if there is a POType then set the Detail Type
	IF @PurchaseOrderTypeKey > 0
		SELECT @PurchaseOrderDetailTypeFieldSet = ISNULL(DetailFieldSetKey, 0) FROM tPurchaseOrderType (nolock) WHERE PurchaseOrderTypeKey = @PurchaseOrderTypeKey


	-- Added for spark44 customization
	--   Approver set to InternalApprover of Estimate for Spark44 only. 
	--   Otherwise, set Approver to UserKey
	declare @Customizations varchar(1000)
	declare @RequireOffice int
	declare @RequireDepartment int
	declare @RequireTasks int
	declare @RequireItems int

	SELECT @Customizations = UPPER(ISNULL(Customizations, ''''))
	      ,@RequireOffice = isnull(RequireOffice, 0)
		  ,@RequireDepartment = isnull(RequireDepartment, 0)
		  ,@RequireTasks = isnull(RequireTasks, 0)
		  ,@RequireItems = isnull(RequireItems, 0)
	  FROM tPreference (NOLOCK)
	 WHERE CompanyKey = @CompanyKey 
	 
	 if @RequireOffice = 1 and isnull(@OfficeKey, 0) = 0
		return -10

	 if @RequireDepartment = 1 and exists (select 1 from #tExpense expe
		inner join tEstimateTaskExpense ete (nolock) on ete.EstimateTaskExpenseKey = expe.EstimateTaskExpenseKey
		inner join tItem i (nolock) on ete.ItemKey = i.ItemKey
		where isnull(i.DepartmentKey, 0) = 0 
		)
		return -11

	if @RequireItems = 1 and exists (select 1 from #tExpense expe
		inner join tEstimateTaskExpense ete (nolock) on ete.EstimateTaskExpenseKey = expe.EstimateTaskExpenseKey
		where isnull(ete.ItemKey, 0) = 0 
		)
		return -12

	if @ProjectKey > 0 and @RequireTasks = 1 and exists (select 1 from #tExpense expe
		inner join tEstimateTaskExpense ete (nolock) on ete.EstimateTaskExpenseKey = expe.EstimateTaskExpenseKey
		where isnull(ete.TaskKey, 0) = 0 
		)
		return -13


	 -- Extract info from estimate, could be more than 1 estimate though... 
	SELECT @InternalApprover = e.InternalApprover
	FROM   tEstimate e (nolock)
	inner join tEstimateTaskExpense ete (nolock) on e.EstimateKey = ete.EstimateKey
	inner join #tExpense b (NOLOCK) ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey	

	IF charindex(''SPARK44'',@Customizations) > 0 
		update tPurchaseOrder
		set ApprovedByKey = @InternalApprover
		where PurchaseOrderKey = @PurchaseOrderKey  

	SELECT @UserName = isnull(FirstName, '''') + '' '' + isnull(LastName, '''')
	FROM   tUser (NOLOCK)
	WHERE  UserKey = @UserKey
					   
	-- For the Loops
	DECLARE	@EstimateTaskExpenseKey INT
		   ,@ExpenseKey INT
	
	BEGIN TRANSACTION

	SELECT @ExpenseKey = -1	
	WHILE (1=1)
	BEGIN
		SELECT @ExpenseKey = MIN(ExpenseKey)
		FROM   #tExpense 
		WHERE  ExpenseKey > @ExpenseKey	

		IF @ExpenseKey IS NULL
			BREAK

		SELECT @EstimateTaskExpenseKey = EstimateTaskExpenseKey
		FROM  #tExpense
		WHERE ExpenseKey = @ExpenseKey
				 
		-- Extract info from estimate detail
		SELECT  @TaskKey = ete.TaskKey
				,@ItemKey = ete.ItemKey
				,@QuoteDetailKey = ete.QuoteDetailKey
				,@ShortDescription = ete.ShortDescription
				,@LongDescription = ete.LongDescription
				,@Billable = ete.Billable
				,@Quantity = CASE e.ApprovedQty
				WHEN 1 THEN ete.Quantity WHEN 2 THEN ete.Quantity2 WHEN 3 THEN ete.Quantity3
				WHEN 4 THEN ete.Quantity4 WHEN 5 THEN ete.Quantity5 WHEN 6 THEN ete.Quantity6
				ELSE ete.Quantity END
				,@UnitCost = CASE e.ApprovedQty 
				WHEN 1 THEN ete.UnitCost WHEN 2 THEN ete.UnitCost2 WHEN 3 THEN ete.UnitCost3 
				WHEN 4 THEN ete.UnitCost4 WHEN 5 THEN ete.UnitCost5 WHEN 6 THEN ete.UnitCost6
				ELSE ete.UnitCost END	
				,@TotalCost = CASE e.ApprovedQty 
				WHEN 1 THEN ete.TotalCost WHEN 2 THEN ete.TotalCost2 WHEN 3 THEN ete.TotalCost3 
				WHEN 4 THEN ete.TotalCost4 WHEN 5 THEN ete.TotalCost5 WHEN 6 THEN ete.TotalCost6
				ELSE ete.TotalCost END	
				,@UnitDescription = CASE e.ApprovedQty
				WHEN 1 THEN ete.UnitDescription WHEN 2 THEN ete.UnitDescription2 WHEN 3 THEN ete.UnitDescription3 
				WHEN 4 THEN ete.UnitDescription4 WHEN 5 THEN ete.UnitDescription5 WHEN 6 THEN ete.UnitDescription6
				ELSE ete.UnitDescription END	
				,@Markup = CASE e.ApprovedQty
				WHEN 1 THEN ete.Markup WHEN 2 THEN ete.Markup2 WHEN 3 THEN ete.Markup3 
				WHEN 4 THEN ete.Markup4 WHEN 5 THEN ete.Markup5 WHEN 6 THEN ete.Markup6
				ELSE ete.Markup END	
				,@UnitRate = CASE e.ApprovedQty
				WHEN 1 THEN ete.UnitRate WHEN 2 THEN ete.UnitRate2 WHEN 3 THEN ete.UnitRate3
				WHEN 4 THEN ete.UnitRate4 WHEN 5 THEN ete.UnitRate5 WHEN 6 THEN ete.UnitRate6
				ELSE ete.UnitRate END
				,@BillableCost = CASE e.ApprovedQty
				WHEN 1 THEN ete.BillableCost WHEN 2 THEN ete.BillableCost2 WHEN 3 THEN ete.BillableCost3 
				WHEN 4 THEN ete.BillableCost4 WHEN 5 THEN ete.BillableCost5 WHEN 6 THEN ete.BillableCost6
				ELSE ete.BillableCost END
				,@Taxable = ete.Taxable
				,@Taxable2 = ete.Taxable2						
			FROM  tEstimateTaskExpense ete (NOLOCK)
				INNER JOIN tEstimate e (NOLOCK) ON ete.EstimateKey = e.EstimateKey
			WHERE ete.EstimateTaskExpenseKey = @EstimateTaskExpenseKey
		
			SELECT @DepartmentKey = DepartmentKey
			      ,@ItemType = ItemType
			FROM   tItem i (NOLOCK)
			WHERE  i.ItemKey = @ItemKey

			
			-- Only do this if there is no foreign currency at all
			if @CurrencyID is null And @PCurrencyID is null 
			begin 
				select @NewQuantity = isnull(@Quantity, 0)
						,@NewTotalCost = isnull(@TotalCost, 0)      
 						,@NewBillableCost =isnull(@BillableCost, 0) 

				-- by default, PTotalCost = TotalCost and GrossAmount = BillableCost
				select @PTotalCost = @NewTotalCost
						,@GrossAmount = @NewBillableCost

			end
			else
			begin
				select @NewQuantity = isnull(@Quantity, 0)
						,@NewTotalCost = isnull(@TotalCost, 0)      -- will need to be recalc''ed in Vendor Currency 
 						,@NewBillableCost =isnull(@BillableCost, 0) -- This is fine in Project Currency

				-- PTotalCost is Project Currency, so same as TotalCost
				select @PTotalCost = @NewTotalCost

				-- but we need to convert using exchange rates, from project currency to vendor currency
				select @UnitCost = (@UnitCost * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency
						,@NewTotalCost = (@NewTotalCost * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency
						,@UnitRate = (@UnitRate * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency
						,@GrossAmount = (@NewBillableCost * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency


				select @UnitCost = round(@UnitCost, 4)
						,@NewTotalCost = round(@NewTotalCost, 2)
						,@UnitRate = round(@UnitRate, 4)
						,@GrossAmount = round(@GrossAmount, 2)

				IF @ItemType > 0 
				BEGIN
					select @UnitCost = @UnitRate
					select @UnitRate = null
					IF @GrossAmount <> 0
						SELECT @Markup = (1 - (@NewTotalCost/@GrossAmount)) * 100
					ELSE
						SELECT @Markup = 0
				END

			end
						
			
			IF @CheckTaskPercComp = 1 AND ISNULL(@TaskKey, 0) > 0
			BEGIN
				EXEC @RetVal = spTaskValidatePercComp ''tPurchaseOrderDetail'', 0, null, null,null, @TaskKey, @UserKey, 1
				IF @RetVal <=0
				BEGIN
					ROLLBACK TRANSACTION
					RETURN -8
				END
			END
					
			--Add the QuoteDetailKey to the Temp Table
			IF ISNULL(@QuoteDetailKey, 0) > 0
				INSERT #tQuoteDetailKeys (QuoteDetailKey) VALUES (@QuoteDetailKey)

			EXEC @RetVal = sptPurchaseOrderDetailInsert 
				@PurchaseOrderKey = @PurchaseOrderKey,
				@LineNumber = 0,
				@ProjectKey = @ProjectKey,
				@TaskKey = @TaskKey,
				@ItemKey = @ItemKey,
				@ClassKey = @ClassKey,
				@ShortDescription = @ShortDescription,
				@Quantity = @NewQuantity,
				@UnitCost = @UnitCost,
				@UnitDescription = @UnitDescription,
				@TotalCost = @NewTotalCost,
				@UnitRate = @UnitRate,
				@Billable = @Billable,
				@Markup = @Markup,
				@BillableCost = @NewBillableCost,
				@LongDescription = @LongDescription,
				@CustomFieldKey = NULL,
				@DetailOrderDate = @OrderDate,
				@DetailOrderEndDate = NULL,
				@UserDate1 = NULL,
				@UserDate2 = NULL,
				@UserDate3 = NULL,
				@UserDate4 = NULL,
				@UserDate5 = NULL,
				@UserDate6 = NULL,
				@OrderDays = NULL,
				@OrderTime = NULL,
				@OrderLength = NULL,
				@Taxable = @Taxable,
				@Taxable2 = @Taxable2,
				@OfficeKey = @OfficeKey,
				@DepartmentKey = @DepartmentKey,
				@GrossAmount = @GrossAmount,
				@PCurrencyID = @PCurrencyID,
				@PExchangeRate = @PExchangeRate,
				@PTotalCost = @PTotalCost,
				@SkipRollUps = NULL,
				@InteractiveAdUnitName = NULL,
				@oIdentity = @PurchaseOrderDetailKey OUTPUT

			IF @RetVal <> 1
			BEGIN
				ROLLBACK TRANSACTION
				RETURN -6
			END

			IF @RetVal = 1 
			BEGIN
				insert tEstimateTaskExpenseOrder (EstimateTaskExpenseKey, PurchaseOrderDetailKey)
				values (@EstimateTaskExpenseKey, @PurchaseOrderDetailKey)

				IF @@ERROR <> 0
				BEGIN
					ROLLBACK TRANSACTION
					RETURN -7 
				END
		
				--Need If there is a default Detail Type need to set CustomFieldKey on the new detail line
				IF @PurchaseOrderDetailTypeFieldSet > 0
				BEGIN
					EXEC spCF_tObjectFieldSetInsert @PurchaseOrderDetailTypeFieldSet, @ObjectFieldSetKey OUTPUT

					IF ISNULL(@ObjectFieldSetKey,0) > 0
					BEGIN
						UPDATE tPurchaseOrderDetail
						Set CustomFieldKey = @ObjectFieldSetKey
						WHERE PurchaseOrderDetailKey = @PurchaseOrderDetailKey

						IF @@ERROR <> 0
						BEGIN
							ROLLBACK TRANSACTION
							RETURN -9 
						END
					END

				END
			END
					
	END

	COMMIT TRANSACTION 

	--EXEC sptPurchaseOrderRecalcAmounts @PurchaseOrderKey 

	--Update the QuoteKeys in the Temp Table
	UPDATE	#tQuoteDetailKeys
	SET		QuoteKey = qd.QuoteKey
	FROM	tQuoteDetail qd (nolock)
	WHERE	#tQuoteDetailKeys.QuoteDetailKey = qd.QuoteDetailKey

	--Copy the Spec Sheets from the Quotes to the POs
	SELECT @QuoteKey = -1
	WHILE (1=1)
	BEGIN
		SELECT	@QuoteKey = MIN(QuoteKey)
		FROM	#tQuoteDetailKeys
		WHERE	QuoteKey > @QuoteKey
				
		IF @QuoteKey IS NULL
			BREAK
				
		--Copy all Spec Sheets from this Quote that haven''t already been linked to the PO
		INSERT	tSpecSheetLink
				(SpecSheetKey,
				Entity,
				EntityKey,
				CompanyKey)
		SELECT	SpecSheetKey,
				''PO'',
				@PurchaseOrderKey,
				CompanyKey
		FROM	tSpecSheetLink (nolock)
		WHERE	Entity = ''Est''
		AND		EntityKey = @QuoteKey
		AND		SpecSheetKey NOT IN
					(SELECT SpecSheetKey
					FROM	tSpecSheetLink (nolock)
					WHERE	Entity = ''PO''
					AND		EntityKey = @PurchaseOrderKey)
				
	END
							

	-- and finally check that the approver has the correct limit to approve
	-- Note: a special process in the UI will be done for Spark44 LA/NY who have the custom SPARK44POAPPROVER

	IF charindex(''SPARK44'',@Customizations) = 0
	BEGIN
		DECLARE @POLimit money
		DECLARE @IOLimit money
		DECLARE @BCLimit money
		DECLARE @POKind INT
		DECLARE @ApprovedByKey INT
		DECLARE @RemoveApprover INT

		SELECT @ApprovedByKey = ApprovedByKey, @TotalCost = isnull(PurchaseOrderTotal, 0) - isnull(SalesTaxAmount, 0), @POKind = POKind
		FROM   tPurchaseOrder (nolock)
		WHERE  PurchaseOrderKey = @PurchaseOrderKey
		
		IF @ApprovedByKey > 0
		BEGIN
			SELECT @POLimit = POLimit, @IOLimit = IOLimit, @BCLimit = BCLimit FROM tUser (nolock) WHERE UserKey = @ApprovedByKey
			 
			SELECT @RemoveApprover = 0

			SELECT @TotalCost = ROUND(@TotalCost * @ExchangeRate, 2) -- convert to HC

			IF @POKind = 0 And @TotalCost > isnull(@POLimit,0)
				SELECT @RemoveApprover = 1
			IF @POKind = 1 And @TotalCost > isnull(@IOLimit, 0)
				SELECT @RemoveApprover = 1
			IF @POKind = 2 And @TotalCost > isnull(@BCLimit, 0)
				SELECT @RemoveApprover = 1

			IF @RemoveApprover = 1
				update tPurchaseOrder
				set ApprovedByKey = 0 -- Anybody who has the correct limit
				where PurchaseOrderKey = @PurchaseOrderKey  

		END		
	END 
	
	-- Note: for Spark44 LA/NY who have the custom SPARK44PONUMBER they want to add *002 from the estimate
	/* removed 3/28/19 they want to change the printout only, not the PO number
	IF charindex(''SPARK44PONUMBER'',@Customizations) > 0
	BEGIN
		if charindex(''*'', @PurchaseOrderNumber) = 0
		BEGIN
			declare @EstimateNumber varchar(50)

			-- this assumes that we have a single estimate
			select @EstimateNumber = e.EstimateNumber
			from   #tExpense expe
				inner join tEstimateTaskExpense ete (nolock) on ete.EstimateTaskExpenseKey = expe.EstimateTaskExpenseKey
				inner join tEstimate e (nolock) on ete.EstimateKey = e.EstimateKey

			if @EstimateNumber is not null and charindex(''*'', @EstimateNumber) > 0
			BEGIN
				select @PurchaseOrderNumber = isnull(@PurchaseOrderNumber, '''') +  substring(@EstimateNumber, charindex(''*'', @EstimateNumber), len(@EstimateNumber) - charindex(''*'', @EstimateNumber) + 1)
					select @PurchaseOrderNumber
				if @PurchaseOrderNumber is not null
					update tPurchaseOrder
					set    PurchaseOrderNumber = @PurchaseOrderNumber
					where  PurchaseOrderKey = @PurchaseOrderKey
			END

		END
	END
	*/

	-- Project rollup for trantype = 5 po 
	EXEC sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1
	
	RETURN 1

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptReminderCacheCompanyUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptReminderCacheCompanyUpdate]', 'P') IS NOT NULL
EXEC sp_executesql N'ALTER PROC [dbo].[sptReminderCacheCompanyUpdate]
	@CompanyKey int
AS
/* 
|| When     Who Rel			What 
|| 10/14/22 CRG 22.11.20    (615895) Created
|| 04/28/25 RLB 26.05.17    (727383) Hard Code to one hour before projects are rescheduled
*/
	-- going to try to default an hr before project are scheduled to nightly update
	Declare @DefaultStartTime as DateTime, @RescheduleProjects smalldatetime
	select @RescheduleProjects = ISNULL(RescheduleProjects, GETUTCDATE()) from tPreference where CompanyKey = @CompanyKey
	SELECT @DefaultStartTime = DATEADD(HOUR, -1, @RescheduleProjects)

	IF EXISTS (SELECT NULL From tReminderCacheCompany (nolock) WHERE CompanyKey = @CompanyKey)
		UPDATE	tReminderCacheCompany
		SET		LastFullUpdate = @DefaultStartTime
		WHERE	CompanyKey = @CompanyKey
	ELSE
		INSERT	tReminderCacheCompany (CompanyKey, LastFullUpdate)
		VALUES	(@CompanyKey, @DefaultStartTime)'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoActionUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoActionUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptAutoActionUpdate]
  @ActionKey int,
  @RuleKey int,
  @ActionType varchar(50),
  @DisplayOrder int,
  @Options varchar(max) = NULL
AS
UPDATE tAutoAction
SET
  RuleKey = @RuleKey,
  ActionType = @ActionType,
  DisplayOrder = @DisplayOrder,
  Options = @Options
WHERE
  ActionKey = @ActionKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoEventDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoEventDelete]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptAutoEventDelete]
  @AutoEventKey int
AS
DELETE FROM tAutoEvent
WHERE AutoEventKey = @AutoEventKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[spRMGetAssignmentsForUser]'
GO
IF OBJECT_ID(N'[dbo].[spRMGetAssignmentsForUser]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROC [dbo].[spRMGetAssignmentsForUser]
	@CompanyKey int,
	@UserKey int,
	@LoggedUserKey int,
	@StartDate smalldatetime,
	@EndDate smalldatetime,
	@PredecessorsComplete tinyint,
	@IncludeCompleted tinyint,
	@ShowAssignmentZeroAllocated tinyint,
	@SessionUserOnly tinyint = 0,
	@DefaultTimeStart datetime = null,
	@OpenToDoOnly  tinyint = 0,
	@OpenDeliverablesOnly tinyint = 0,
	@ProjectKey int = NULL, -- NULL = any ProjectKey that fits the other filters, > 0 = filter for only this ProjectKey, -1 = filter for only ProjectKeys in #ProjectKeys
	@RecalcRequiredCheck tinyint = 0,
	@UsePreloadTable tinyint = 0
AS

/*
|| When      Who Rel      What
|| 03/19/18  CRG 18.4.0   Created to get the assignment and bucket data for only ONE week
|| 03/20/18  GWG 18.4.0   Added PercCompSeparate
|| 04/11/18  GWG 18.5.0   Add in setting to exclude completed
|| 04/10/18  CRG 18.5.0   Added WorkAnyDay, Offset, and BucketStart
|| 04/11/18  CRG 18.5.0   Added the Work day columns
|| 04/12/18  GWG 18.5.0   Added in filter for tasks in current work zone	
|| 05/14/18  GWG 18.5.0   Only showing active projects
|| 05/24/18  GWG 18.6.0   Change selection logic to look at the assignment plan start/complete and take into account anything completed before this week.
|| 06/20/18  RLB 18.7.0   (406703) included completed on first day of week
|| 07/31/18  GHL 18.8.0   (412719) For the prior tasks (i.e. more than 1 week) take the sum of Hours, not the hours of a single bucket
|| 08/14/18  CRG 18.9.0   Added Retainer adjusted hours
|| 11/05/18  RLS 18.9.3   (428022) Use tu.APlanStart and tu.APlanComplete if they''re populated in place of t.PlanStart & t.PlanComplete
|| 12/04/18  RLB 18.9.3   (433476) Added option showAssignmentZeroAllocated which was not being used but should be
|| 12/05/18  RLB 18.9.3   (434169) changed actual hours only to pull for week selected since actuals will get put into buckets
|| 04/09/19  CRG 19.0.5.0 (454523) Added PlanningProject
|| 04/11/19  RLB 19.0.5.0 (453695) Added session user only check for creative today page displaying to do''s for other users
|| 04/30/19  RLB 19.0.5.0 (454584) returning Priority so it can be displayed
|| 07/08/19  GWG 19.0.8.0 Removed the verified check as we don''t use it anymore
|| 09/19/19  GAR 19.1.0.0 (471065) Added ServiceDescription to match up with what is on the card view
|| 02/27/19  RLB 20.0.3.0 (499430) pulling all actual hours before the week start 
|| 03/31/20  CRG 20.0.4.0 (509048) Modified actual hours queries to not use temp tables
|| 04/10/20  CRG 20.0.5.0 (510153) Added RemainingHours column to temp table for use in VB
|| 10/23/20  RLB 20.1.1.0 (534454) Added open deliverables
|| 11/02/20  RLS 20.1.2.0 (535729) Changed @Description to nvarchar
|| 11/11/20  RLB 20.1.2.0 (524218) added Task ID needed for new hand off changes
|| 11/17/20  RLS 20.1.2.0 (535729) Changed TaskName and FormattedName to nvarchar
|| 11/23/20  RLS 20.1.2.0 (535729) Changed ProjectName and FormattedProjectName to nvarchar
|| 12/30/20  GAR 21.03.14 (536183) Added UpdateCount for use in today.creative task cards
|| 01/05/21  RLS 21.0.2.0 (535729) Changed @ADescription to nvarchar
|| 02/02/21  RLS 21.0.2.0 (546075) Changed @CompanyName to nvarchar
|| 02/11/21 RLS 21.0.3.0 (535729) Changed SummaryTaskName and SummaryTask to nvarchar
|| 03/08/21 RLS 21.0.4.0 (551203) Description to NVARCHAR(MAX)
|| 03/31/21 RLB 21.04.18  (552297) Added DefaultTimeStart because of SQL Timezone Issues
|| 04/02/21 RLS 21.0.5.0  (550053) Added @OpenToDoOnly for Creative Today tile view
|| 05/03/21 CRG 21.0.5.16 (556855) Added optional @ProjectKey for real time notifications
|| 07/26/21 RLS 21.0.8.0  (566012) Changed the update to TaskUserStatusKey to use the view
|| 08/10/21 RLS 21.0.9.0  (564254) Changed ServiceDescription and ServiceName to nvachar
|| 04/14/22 AMP xx.xx.xx  (DEV2506-485) Changed the Open To Do count to be the To Dos that are not tied to a deliverable
|| 04/19/22 RLB 22.05.15  (594696) open to do''s count is pulled off completed from approved
|| 04/27/22 RLB 22.04.17  (596854) removed deliverablekey filter to dos on deliverable 
|| 06/16/22 CRG 22.07.17 (603297) Modified OpenToDos to use new rollup table
|| 07/28/22 WDF 22.08.14 (607092) Added filter @OpenDeliverablesOnly; Modified OpenToDos to check for NULL
|| 08/26/22 RLB 22.09.18 (610285) moving projectnumber up to varchar100
|| 10/13/22 RLB 22.11.20 (610106) added pull of LimitProjectServices
|| 12/14/22 GAR 23.01.15 (623551) Update UpdateCount field - need to include conversations and activitylinks
|| 03/24/23 CRG 23.04.16 (635471) Added @RecalcRequiredCheck to populate #RecalcTask and stop before loading all of the time data, in order to improve performance
|| 04/14/23 CRG 23.05.14 Added @UsePreloadTable flag to use #tPreload instead of getting the tasks directly from tTask
|| 05/08/23 CRG 23.06.18 (604775) Now using tTaskPriority
|| 05/14/24 RLB 24.06.16 (659813) Adding ExcludeFromRM option
|| 06/12/24 RLB 24.07.14 (670085) added ActualHoursTotal pulling all actual hrs and assignedservicekey. Added ActualHoursTotalThisWeek and ActualHoursTotalToday for today creative rm card
|| 08/28/24 CRG 24.10.20 (681784) Added #ProjectKeys temp table to allow RTN updates of multiple ProjectKeys at one time
|| 10/15/24 GAR 24.10.20 (683966) Added ProjectColor to today.creatives
|| 02/12/25 CRG 25.03.16 (694437) Setting a temporary display order for any rows that don''t already have one set, so it sorts properly in the TaskBoard
|| 06/30/25 RLS 25.07.20 (701652) Added AllTaskUsers
|| 10/28/25 RLS 25.11.16 (711139) Added AllTaskUserNames
|| 11/10/25 RLS 25.11.16 (715510) Changed AllTaskUserNames in the temp table to NVARCHAR(4000) to match the substring length in the update statement. Fix for above issue (711139) where the field was added
|| 11/25/25 RLB 25.12.14 (715205) The option  Show Assignments with Zero Allocated will also remove tasks with no allocated in the week
|| 12/12/25 RLB 25.12.14 (717593) change on issue (715205) to include any PercComp= 100 withj no weekly hrs left if the screen should display 100 complete assignments 
|| 12/23/25 RLB 25.12.14 (717593) made the above fix at the wrong spot move to the correct one
|| 04/10/26 GAR 26.05.17 (723471) Added AccountManagerName and ProjectManagerName
*/

	declare @SecurityGroupKey int, @Administrator tinyint, @RateLevel int

	Select @SecurityGroupKey = SecurityGroupKey,  @Administrator = ISNULL(Administrator, 0), @RateLevel = RateLevel from tUser (nolock) Where UserKey = @UserKey

	if ((@Administrator = 1) OR exists (Select 1 from tRightAssigned (nolock) Where RightKey = 90933 and EntityType = ''Security Group'' and EntityKey = @SecurityGroupKey))
		begin
			if @SessionUserOnly = 1 
			 SELECT @SessionUserOnly = 0
		end

	CREATE TABLE #tTask (
			 TaskUserKey INT NULL  
			 ,TaskKey INT NULL  
			 ,FormattedName NVARCHAR(535) NULL  
			 ,TaskName NVARCHAR(535) NULL 
			 ,TaskID NVARCHAR(50) NULL 
			 ,ProjectFullName NVARCHAR(255) NULL  
			 ,Description NVARCHAR(MAX) NULL  
			 ,ProjectKey INT NULL
			 ,PlanStart SMALLDATETIME NULL  
			 ,PlanComplete SMALLDATETIME NULL  
			 ,ActStart SMALLDATETIME NULL  
			 ,ActComplete SMALLDATETIME NULL  
			 ,PlanDuration INT NULL
			 ,Hours DECIMAL(24, 4) NULL  			 
			 ,WorkAnyDay INT NULL
			 ,UserKey INT NULL
			 ,ServiceKey INT NULL
			 ,ServiceName NVARCHAR(100)
			 ,ServiceDescription NVARCHAR(100)
			 ,CompanyKey INT NULL
			 ,CompanyName NVARCHAR(200)
			 ,WorkSun INT NULL
			 ,WorkMon INT NULL
			 ,WorkTue INT NULL
			 ,WorkWed INT NULL
			 ,WorkThur INT NULL
			 ,WorkFri INT NULL
			 ,WorkSat INT NULL
			 ,PercComp INT NULL   
			 ,PercCompSeparate TINYINT NULL
			 ,ActualHours DECIMAL(24, 4) NULL  
			 ,ProjectNumber VARCHAR(155) NULL 
			 ,ProjectName NVARCHAR(155) NULL 
			 ,ClientKey INT NULL
			 ,ProjectOrder INT NULL
			 ,SummaryTaskID NVARCHAR(30) NULL
			 ,SummaryTaskName NVARCHAR(500) NULL
			 ,SummaryTask NVARCHAR(531) NULL
			 ,APlanStart SMALLDATETIME NULL 
			 ,APlanComplete SMALLDATETIME NULL
			 ,ManualAdjustment TINYINT NULL
			 ,TaskUserStatusKey int NULL
			 ,TaskUserDisplayOrder int NULL
			 ,DueBy VARCHAR(200) NULL
			 ,ADescription NVARCHAR(MAX) NULL
			 ,OpenToDos INT NULL
			 ,TrackBudget TINYINT NULL
			 ,RecalcRequired tinyint NULL
			 ,ActualHourRecalcDate smalldatetime NULL
			 ,PrevHours decimal(24, 4) NULL
			 ,PredecessorsComplete tinyint NULL
			 ,TaskUserOrigHours DECIMAL(24, 4) NULL  
			 ,NumWeeks int NULL
			 ,BucketCount int NULL
			 ,DisplayHours DECIMAL(24, 4) NULL
			 ,Offset int NULL
			 ,BucketStart smalldatetime NULL
			 ,Retainer tinyint NULL
			 ,RetainerKey int NULL
			 ,PlanningProject tinyint NULL
			 ,Priority int NULL
			 ,PriorityName VARCHAR(100)
			 ,ActualHoursBefore DECIMAL(24, 4) NULL 
			 ,RemainingHours DECIMAL(24, 4) NULL 
			 ,OpenDeliverables INT NULL
			 ,UpdateCount INT NULL
			 ,LimitProjectServices tinyint NULL
			 ,ActualHoursTotal DECIMAL(24, 4) NULL 
			 ,AssignedServiceKey INT NULL 
			 ,ActualHoursTotalThisWeek DECIMAL(24, 4) NULL
			 ,ActualHoursTotalToday DECIMAL(24, 4) NULL
			 ,ProjectColor VARCHAR(10) NULL
			 ,AllTaskUsers TEXT NULL
			 ,AllTaskUserNames NVARCHAR(4000) NULL
			 ,AccountManagerName NVARCHAR(500) NULL
			 ,ProjectManagerName NVARCHAR(500) NULL
			 ) 

	CREATE TABLE #tTime (TaskKey INT NULL, DetailTaskKey INT NULL, ServiceKey INT NULL, ActualHours DECIMAL(24, 4) NULL)  

	DECLARE	@RestrictToGLCompany int, 
			@ShowActualHours tinyint

	SELECT	@RestrictToGLCompany = ISNULL(RestrictToGLCompany, 0), 
			@ShowActualHours = ISNULL(p.ShowActualHours, 0)
	FROM	tPreference p (nolock) 
	WHERE	CompanyKey = @CompanyKey

	SELECT	@RestrictToGLCompany = ISNULL(@RestrictToGLCompany, 0)

	SELECT @DefaultTimeStart = ISNULL(@DefaultTimeStart, GETDATE())

	IF @UsePreloadTable = 1
		INSERT #tTask (TaskUserKey, TaskKey, FormattedName, TaskName, TaskID, ProjectFullName, Description, ProjectKey, PlanStart, PlanComplete,
				PlanDuration, Hours, ServiceKey, UserKey, CompanyKey, PercComp, PercCompSeparate, ActualHours, ProjectNumber, ProjectName, ClientKey, SummaryTaskID,
				SummaryTaskName, SummaryTask, TaskUserDisplayOrder, DueBy, TaskUserOrigHours, RecalcRequired, WorkAnyDay, WorkSun, WorkMon, WorkTue, WorkWed, WorkThur, WorkFri, WorkSat,
				Retainer, RetainerKey, PlanningProject, LimitProjectServices, AssignedServiceKey,AllTaskUsers,AllTaskUserNames)
			SELECT TaskUserKey, TaskKey
					,FormattedName 
					,TaskName
					,TaskID
					,ProjectFullName
					,Description
					,ProjectKey
					,PlanStart
					,PlanComplete
					,PlanDuration
					,Hours    
					,ServiceKey
					,UserKey
					,CompanyKey
					,PercComp
					,PercCompSeparate
					,0 --ActualHours
					,ProjectNumber 
					,ProjectName 
					,ClientKey
					,NULL   -- SummaryTaskID
					,NULL   -- SummaryTaskName
					,NULL   -- SummaryTask
					,TaskUserDisplayOrder
					,DueBy
					,TaskUserOrigHours
					,RecalcRequired		
					,WorkAnyDay
					,WorkSun
					,WorkMon
					,WorkTue
					,WorkWed
					,WorkThur
					,WorkFri
					,WorkSat
					,Retainer
					,RetainerKey
					,PlanningProject
					,LimitProjectServices
					,AssignedServiceKey
					,NULL -- AllTaskusers
					,NULL -- AllTaskUserNames
					
			FROM	#tPreload (NOLOCK) 
			WHERE	PlanComplete >= @StartDate
			AND		PlanStart <= @EndDate
			AND		(ActComplete is null OR ActComplete >= @StartDate)
			AND		(@RecalcRequiredCheck = 0 OR RecalcRequired = 1)
	ELSE
		INSERT #tTask (TaskUserKey, TaskKey, FormattedName, TaskName, TaskID, ProjectFullName, Description, ProjectKey, PlanStart, PlanComplete,
				 PlanDuration, Hours, ServiceKey, UserKey, CompanyKey, PercComp, PercCompSeparate, ActualHours, ProjectNumber, ProjectName, ClientKey, SummaryTaskID,
				 SummaryTaskName, SummaryTask, TaskUserDisplayOrder, DueBy, TaskUserOrigHours, RecalcRequired, WorkAnyDay, WorkSun, WorkMon, WorkTue, WorkWed, WorkThur, WorkFri, WorkSat,
				 Retainer, RetainerKey, PlanningProject, LimitProjectServices, AssignedServiceKey,AllTaskUsers,AllTaskUserNames)
			SELECT tu.TaskUserKey, t.TaskKey
					,ISNULL(t.TaskID + ''-'', '''') + t.TaskName As FormattedName 
					,t.TaskName
					,t.TaskID
					,p.ProjectNumber + ''-'' + p.ProjectName AS ProjectFullName
					,t.Description
					,t.ProjectKey
					,ISNULL(tu.APlanStart, t.PlanStart)
					,ISNULL(tu.APlanComplete, t.PlanComplete)
					,t.PlanDuration
					,tu.Hours    
					,tu.ServiceKey
					,tu.UserKey
					,u.CompanyKey
					,tu.PercComp
					,PercCompSeparate
					,0 --ActualHours
					,p.ProjectNumber 
					,p.ProjectName 
					,p.ClientKey
					,NULL   -- SummaryTaskID
					,NULL   -- SummaryTaskName
					,NULL   -- SummaryTask
					,ISNULL(tu.DisplayOrder, -1) AS TaskUserDisplayOrder
					,t.DueBy
					,tu.OrigHours
					,tu.RecalcRequired		
					,t.WorkAnyDay
					,p.WorkSun
					,p.WorkMon
					,p.WorkTue
					,p.WorkWed
					,p.WorkThur
					,p.WorkFri
					,p.WorkSat
					,p.Retainer
					,p.RetainerKey
					,p.PlanningProject
					,p.LimitProjectServices
					,ISNULL(tu.ServiceKey, u.DefaultServiceKey)
					,NULL -- AllTaskUsers
					,NULL -- AllTaskUserNames

			FROM	tProject p (NOLOCK) 
			INNER JOIN tTask t (NOLOCK) ON p.ProjectKey = t.ProjectKey
			INNER JOIN tTaskUser tu (NOLOCK) ON t.TaskKey = tu.TaskKey
			INNER JOIN tUser u (NOLOCK) ON tu.UserKey = u.UserKey
			INNER JOIN tProjectStatus ps (NOLOCK) ON p.ProjectStatusKey = ps.ProjectStatusKey
			WHERE	(@ProjectKey IS NULL 
					OR p.ProjectKey = @ProjectKey
					OR (@ProjectKey = -1 AND p.ProjectKey IN (SELECT ProjectKey FROM #ProjectKeys)))
			AND		tu.UserKey = @UserKey
			AND		ISNULL(tu.APlanComplete, t.PlanComplete) >= @StartDate
			AND		ISNULL(tu.APlanStart, t.PlanStart) <= @EndDate
			AND		ISNULL(ps.OnHold, 0) = 0
			AND     ISNULL(p.ExcludeFromRM, 0) = 0
			AND		p.Active = 1
			AND		PredecessorsComplete >= @PredecessorsComplete
			AND		(tu.ActComplete is null OR tu.ActComplete >= @StartDate)
			AND		(@RecalcRequiredCheck = 0 OR tu.RecalcRequired = 1)

		IF @RecalcRequiredCheck = 1
		BEGIN
			--Assume #RecalcTask is already created
			DELETE	#RecalcTask

			INSERT	#RecalcTask
					(TaskKey, PlanStart, PlanComplete, PlanDuration)
			SELECT DISTINCT t.TaskKey, t.PlanStart, t.PlanComplete, t.PlanDuration
			FROM	#tTask t
			INNER JOIN tProject p (nolock) ON t.ProjectKey = p.ProjectKey
			WHERE	p.CompanyKey = @CompanyKey --Just to make sure it''s the correct company''s data in the temp table

			SELECT	*
			FROM	#tTask

			RETURN
		END

		
		UPDATE	#tTask
		SET		#tTask.ADescription = tu.ADescription,
				#tTask.RecalcRequired = tu.RecalcRequired,
				#tTask.ActualHourRecalcDate = tu.ActualHourRecalcDate,
				#tTask.APlanStart = tu.APlanStart,
				#tTask.APlanComplete = tu.APlanComplete,
				#tTask.ManualAdjustment = tu.ManualAdjustment,
				#tTask.TaskUserOrigHours = tu.OrigHours,
				#tTask.PercComp = ISNULL(#tTask.PercComp, 0)
		FROM	tTaskUser tu (nolock)
		WHERE	#tTask.TaskUserKey = tu.TaskUserKey
	
		UPDATE	#tTask
		SET		#tTask.CompanyName = c.CompanyName,
				#tTask.ProjectColor = p.ProjectColor
		FROM	tCompany c (nolock)
		INNER JOIN tProject p (nolock) ON c.CompanyKey = p.ClientKey 
		WHERE	#tTask.ProjectKey = p.ProjectKey

		UPDATE	#tTask
		SET		#tTask.ServiceName = s.Description
				,#tTask.ServiceDescription = Case @RateLevel 
					When 1 then ISNULL(s.Description1, s.Description)
					When 2 then ISNULL(s.Description2, s.Description)
					When 3 then ISNULL(s.Description3, s.Description)
					When 4 then ISNULL(s.Description4, s.Description)
					When 5 then ISNULL(s.Description5, s.Description)
					else s.Description
				end
		FROM	tService s (nolock)
		WHERE	#tTask.ServiceKey = s.ServiceKey

		UPDATE #tTask
		SET	   #tTask.AccountManagerName = am.FirstName + '' '' + am.LastName
			   ,#tTask.ProjectManagerName = pm.FirstName + '' '' + pm.LastName
		FROM	#tTask t
			INNER JOIN tProject p (nolock) ON t.ProjectKey = p.ProjectKey
			LEFT OUTER JOIN tUser am (nolock) on p.AccountManager = am.UserKey
			LEFT OUTER JOIN tUser pm (nolock) on p.ProjectManager = pm.UserKey
		
		if @SessionUserOnly = 0 
		begin
			UPDATE	#tTask
			SET		#tTask.OpenToDos = (SELECT SUM(r.OpenToDoCount) FROM tOpenToDoRollup r (nolock) WHERE r.TaskKey = t.TaskKey),
					#tTask.TrackBudget = t.TrackBudget,
					#tTask.PredecessorsComplete = ISNULL(t.PredecessorsComplete, 0)
			FROM	tTask t (nolock)
			WHERE	#tTask.TaskKey = t.TaskKey

			UPDATE	#tTask
			SET		#tTask.OpenDeliverables = (SELECT COUNT(*) FROM tReviewDeliverable (nolock) WHERE TaskKey = t.TaskKey and ISNULL(Completed, 0) = 0),
					#tTask.TrackBudget = t.TrackBudget,
					#tTask.PredecessorsComplete = ISNULL(t.PredecessorsComplete, 0)
			FROM	tTask t (nolock)
			WHERE	#tTask.TaskKey = t.TaskKey
		end

		if @SessionUserOnly = 1 
		begin
			UPDATE	#tTask
			SET		#tTask.OpenToDos = (SELECT SUM(r.OpenToDoCount) FROM tOpenToDoRollup r (nolock) WHERE r.TaskKey = t.TaskKey AND (r.AssignedUserKey = @UserKey or ISNULL(r.AssignedUserKey, 0) = 0)),
					#tTask.TrackBudget = t.TrackBudget,
					#tTask.PredecessorsComplete = ISNULL(t.PredecessorsComplete, 0)
			FROM	tTask t (nolock)
			WHERE	#tTask.TaskKey = t.TaskKey

			UPDATE	#tTask
			SET		#tTask.OpenDeliverables = (SELECT COUNT(*) FROM tReviewDeliverable rd (nolock) WHERE rd.TaskKey = t.TaskKey and ISNULL(rd.Approved, 0) = 0),
					#tTask.TrackBudget = t.TrackBudget,
					#tTask.PredecessorsComplete = ISNULL(t.PredecessorsComplete, 0)
			FROM	tTask t (nolock)
			WHERE	#tTask.TaskKey = t.TaskKey
			AND     (#tTask.UserKey = @UserKey or isnull(UserKey, 0) = 0)

		end

		Delete #tTask Where APlanStart is not null and APlanStart > @EndDate
		Delete #tTask Where APlanComplete is not null and APlanComplete < @StartDate
		if @IncludeCompleted = 0
			Delete #tTask Where PercComp = 100 or ISNULL(APlanComplete, PlanComplete) > @EndDate  -- don''t show completed items or items where continue into the current period

		if @ShowAssignmentZeroAllocated = 0
			Delete #tTask Where ISNULL(Hours, 0) = 0  -- remove task assignments with no allocated hours
		
		if isnull(@OpenToDoOnly, 0) > 0
			delete #tTask where isnull(OpenToDos, 0) = 0

		if isnull(@OpenDeliverablesOnly, 0) > 0
			delete #tTask where OpenDeliverables = 0

		-- added to pull actaul hrs entered today
		declare @TodayStartDate as datetime , @TodayEndDate as DateTime
		select @TodayStartDate = CAST(CAST(GETDATE() as date) as datetime)
		select @TodayEndDate = DATEADD(day, 1, @TodayStartDate)
		select @TodayEndDate = DATEADD(second,-1, @TodayEndDate)

		-- if preference to show time regardless of the service is true
		IF @ShowActualHours = 1
		BEGIN

		-- new for total actual hours
			INSERT #tTime (TaskKey, DetailTaskKey, ServiceKey, ActualHours)  
			SELECT ti.TaskKey, ti.DetailTaskKey, ti.ServiceKey, ti.ActualHours   
			FROM tTime ti WITH (INDEX=IX_tTime_1, NOLOCK)  
				,(select Distinct(TaskKey) from #tTask (nolock)) as ta     
			WHERE ti.UserKey = @UserKey  
			AND   (ti.TaskKey = ta.TaskKey OR ti.DetailTaskKey = ta.TaskKey)
	
			UPDATE #tTask  
			SET    #tTask.ActualHoursTotal = ISNULL(  
			   (SELECT SUM(ti.ActualHours) FROM #tTime ti   
			   WHERE (ti.TaskKey = #tTask.TaskKey OR ti.DetailTaskKey = #tTask.TaskKey))   
			   ,0)  




			UPDATE #tTask  
			SET    #tTask.ActualHours = t.ActualHours 
			FROM   
					(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours   
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate <= @EndDate
							AND     ti.WorkDate >= @StartDate
							AND		((ti.WorkDate < dbo.fFormatDateNoTime(@DefaultTimeStart) AND Verified = 1) OR Verified = 0)) alltime
					GROUP BY DetailTaskKey) t
			WHERE	t.DetailTaskKey = #tTask.TaskKey

			-------- get all actual hours before the start of this week
			UPDATE	#tTask  
			SET		#tTask.ActualHoursBefore = tb.ActualHours 
			FROM	
					(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate < @StartDate) alltime
					GROUP BY DetailTaskKey) tb
			WHERE	tb.DetailTaskKey = #tTask.TaskKey

			------ all actual hours entered this week including today''s
			UPDATE #tTask  
			SET    #tTask.ActualHoursTotalThisWeek = t.ActualHours 
			FROM   
					(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours   
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate <= @EndDate
							AND     ti.WorkDate >= @StartDate
							AND		((ti.WorkDate <= dbo.fFormatDateNoTime(@DefaultTimeStart) AND Verified = 1) OR Verified = 0)) alltime
					GROUP BY DetailTaskKey) t
			WHERE	t.DetailTaskKey = #tTask.TaskKey


			UPDATE #tTask  
			SET    #tTask.ActualHoursTotalToday = t.ActualHours 
			FROM   
					(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours   
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate <= @TodayEndDate
							AND     ti.WorkDate >= @TodayStartDate
							) alltime
					GROUP BY DetailTaskKey) t
			WHERE	t.DetailTaskKey = #tTask.TaskKey


		END
		ELSE
		BEGIN

		-- new for total actual hours
			INSERT #tTime (TaskKey, DetailTaskKey, ServiceKey, ActualHours)  
			SELECT ti.TaskKey, ti.DetailTaskKey, ti.ServiceKey, ti.ActualHours   
			FROM tTime ti WITH (INDEX=IX_tTime_1, NOLOCK)  
				,#tTask ta     
			WHERE ti.UserKey = @UserKey  
			AND   (ti.TaskKey = ta.TaskKey OR ti.DetailTaskKey = ta.TaskKey)
			AND   (ta.AssignedServiceKey is null OR ti.ServiceKey = ta.AssignedServiceKey)

			UPDATE #tTask  
			SET    #tTask.ActualHoursTotal = ISNULL(  
			   (SELECT SUM(ti.ActualHours) FROM #tTime ti   
			   WHERE (ti.TaskKey = #tTask.TaskKey OR ti.DetailTaskKey = #tTask.TaskKey) AND (#tTask.AssignedServiceKey is null OR ti.ServiceKey = #tTask.AssignedServiceKey))   
			   ,0)  


			-- the task service must match or be null
			UPDATE	#tTask  
			SET		#tTask.ActualHours = t.ActualHours 
			FROM	
					(SELECT	DetailTaskKey, ServiceKey, SUM(ActualHours) AS ActualHours
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.ServiceKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate <= @EndDate
							AND		ti.WorkDate >= @StartDate
							AND		ti.WorkDate < dbo.fFormatDateNoTime(@DefaultTimeStart)
							AND		(ta.ServiceKey is null
									OR
									ti.ServiceKey = ta.ServiceKey)) alltime
					GROUP BY DetailTaskKey, ServiceKey) t
			WHERE	t.DetailTaskKey = #tTask.TaskKey

			---------- get all actual hours before the start of this week
			UPDATE #tTask  
			SET    #tTask.ActualHoursBefore = ti.ActualHours 
			FROM   
					(SELECT	DetailTaskKey, ServiceKey, SUM(ActualHours) AS ActualHours  
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.ServiceKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate < @StartDate
							AND		(ta.ServiceKey is null
									OR
									ti.ServiceKey = ta.ServiceKey)) alltime
					GROUP BY DetailTaskKey, ServiceKey) ti
			WHERE	ti.DetailTaskKey = #tTask.TaskKey


				------ all actual hours entered this week including today''s
			UPDATE #tTask  
			SET    #tTask.ActualHoursTotalThisWeek = t.ActualHours 
			FROM   
					(SELECT	DetailTaskKey, SUM(ActualHours) AS ActualHours   
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate <= @EndDate
							AND     ti.WorkDate >= @StartDate
							AND		((ti.WorkDate <= dbo.fFormatDateNoTime(@DefaultTimeStart) AND Verified = 1) OR Verified = 0)) alltime
					GROUP BY DetailTaskKey) t
			WHERE	t.DetailTaskKey = #tTask.TaskKey


			UPDATE	#tTask  
			SET		#tTask.ActualHoursTotalToday = t.ActualHours 
			FROM	
					(SELECT	DetailTaskKey, ServiceKey, SUM(ActualHours) AS ActualHours
					FROM	(SELECT	ISNULL(ti.DetailTaskKey, ti.TaskKey) AS DetailTaskKey, ti.ServiceKey, ti.WorkDate, ti.ActualHours
							FROM	tTime ti (NOLOCK)
							INNER JOIN #tTask ta ON ti.ProjectKey = ta.ProjectKey AND ISNULL(ti.DetailTaskKey, ti.TaskKey) = ta.TaskKey
							WHERE	ti.UserKey = @UserKey
							AND		ti.WorkDate <= @TodayEndDate
							AND		ti.WorkDate >= @TodayStartDate
							AND		(ta.ServiceKey is null
									OR
									ti.ServiceKey = ta.ServiceKey)) alltime
					GROUP BY DetailTaskKey, ServiceKey) t
			WHERE	t.DetailTaskKey = #tTask.TaskKey

		END

		UPDATE	#tTask
		SET		#tTask.ProjectOrder = t.ProjectOrder,
				#tTask.ActStart = t.ActStart,
				#tTask.ActComplete = t.ActComplete,
			    #tTask.Priority = t.TaskPriorityKey
		FROM	tTask t
		WHERE	t.TaskKey = #tTask.TaskKey

		UPDATE	#tTask
		SET		#tTask.PriorityName = tp.PriorityName
		FROM	tTaskPriority tp
		WHERE	#tTask.Priority = tp.TaskPriorityKey

		-- Update Summary Task fields
		UPDATE   #tTask
		SET      #tTask.SummaryTaskID = st.TaskID
				,#tTask.SummaryTaskName = st.TaskName
				,#tTask.SummaryTask = ISNULL(st.TaskID + ''-'', '''') + ISNULL(st.TaskName, '''')
		FROM     tTask t (nolock) left outer join tTask st (NOLOCK) on t.SummaryTaskKey = st.TaskKey
		WHERE    t.TaskKey = #tTask.TaskKey

		-- no need to do bucketing and status if just getting prior tasks
		if @IncludeCompleted = 1
		BEGIN

			UPDATE	#tTask
			SET		TaskUserStatusKey = vtus.TaskUserStatusKey
			FROM	vTaskUserStatus vtus (nolock)
			WHERE	vtus.TaskUserKey = #tTask.TaskUserKey


			UPDATE	#tTask
			SET		DisplayHours = v.Hours,
					Offset = v.Offset,
					BucketStart = v.BucketStart
			FROM	#tTask t
			INNER JOIN vTaskUserHour v ON t.TaskUserKey = v.TaskUserKey
			WHERE	v.BucketStart BETWEEN @StartDate AND @EndDate

			IF EXISTS (SELECT NULL FROM #tTask WHERE Retainer = 1)
			BEGIN
				UPDATE	#tTask
				SET		#tTask.DisplayHours = v.AdjustedHours
				FROM	#tTask
				INNER JOIN vTaskUserHourRetainerAdjusted v ON #tTask.RetainerKey = v.RetainerKey AND #tTask.TaskUserKey = v.TaskUserKey AND #tTask.BucketStart = v.BucketStart AND #tTask.UserKey = v.UserKey AND #tTask.ServiceKey = v.ServiceKey
				WHERE	#tTask.Retainer = 1
			END			
		END
	
		-- GHL: for the prior tasks/weeks, get the sum (in that case the number of days should be around 2 months, I compare to 10 days)
		DECLARE @DateDiff INT
		SELECT @DateDiff = DATEDIFF(DAY, @StartDate, @EndDate)
		
		if @DateDiff > 10
			UPDATE	#tTask
			SET		DisplayHours = (select sum(v.Hours)
			FROM vTaskUserHour v 
			WHERE #tTask.TaskUserKey = v.TaskUserKey
			AND	v.BucketStart BETWEEN @StartDate AND @EndDate
			)

		if @ShowAssignmentZeroAllocated = 0
		BEGIN
			if @IncludeCompleted = 1
				Delete #tTask Where ISNULL(DisplayHours, 0) = 0  and PercComp < 100  -- remove task assignments with no allocated hours in the week as long as the task is not complete since the option to who completed task is true
			else
			Delete #tTask Where ISNULL(DisplayHours, 0) = 0  -- remove task assignments with no allocated hours in the week
		END

		-- GAR-536183: add the update count to use in the tasks cards in today creative
		-- GAR-623551: add the other areas of the update count - conversations, activity links
		UPDATE	#tTask
			SET		UpdateCount = 
			-- if you modify this field, also modify sptAppFavoriteGetList, spRMGetAssignmentsForUser, and sptTaskUserGetTaskList2
			-- get all with task on activity
				(select Count(*) from tActivity a (nolock)
					left outer join (Select * from tAppRead (nolock) Where UserKey = @UserKey) as ar on a.ActivityKey = ar.EntityKey and ar.Entity = ''tActivity''
					Where a.ActivityEntity = ''Diary'' and a.TaskKey = #tTask.TaskKey and ISNULL(ar.IsRead, 0) = 0) +
			-- get any links with taskkey on them
				(select Count(*) from tActivityLink al (nolock)
					inner join tActivity a (nolock) on al.ActivityKey = a.ActivityKey and al.Entity = ''tTask''
					left outer join tActivity lda (nolock) on  al.EntityKey = lda.ActivityKey
					left outer join (Select * from tAppRead (nolock) Where UserKey = @UserKey) as ar on al.ActivityKey = ar.EntityKey and ar.Entity = ''tActivity''
					where al.EntityKey = #tTask.TaskKey and a.ActivityEntity = ''Diary'' and al.EntityKey <> a.TaskKey and ISNULL(ar.IsRead, 0) = 0) +
			-- get spec sheets
				(select Count(*) from tSpecSheet ss (nolock)
					left outer join (Select * from tAppRead (nolock) Where UserKey = @UserKey) as ar on ss.SpecSheetKey = ar.EntityKey and ar.Entity = ''tSpecSheet''
					Where ss.EntityKey = #tTask.ProjectKey and ss.Entity = ''Project'' and ISNULL(ar.IsRead, 0) = 0)

		/* Update negative TaskUserDisplayOrders to temporary display orders, so that the default sort order in the task cards is PlanComplete */
		DECLARE	@MaxDisplayOrder int,
				@MinPlanComplete smalldatetime

		SELECT	@MaxDisplayOrder = MAX(TaskUserDisplayOrder)
		FROM	#tTask
		WHERE	TaskUserDisplayOrder > 0

		SELECT	@MaxDisplayOrder = ISNULL(@MaxDisplayOrder, 0)

		SELECT	@MinPlanComplete = MIN(PlanComplete)
		FROM	#tTask
		WHERE	ISNULL(TaskUserDisplayOrder, 0) <= 0
		AND		PlanComplete IS NOT NULL

		--Set the temporary display order for the task cards to the number of days between the minimum PlanComplete in the list and the PlanComplete on the row
		--This will sort the items on the TaskBoard by PlanComplete, if they were never dragged/dropped before, or if the sort was cleared
		IF @MinPlanComplete IS NOT NULL
			UPDATE	#tTask
			SET		TaskUserDisplayOrder = DATEDIFF(DAY, @MinPlanComplete, PlanComplete) + @MaxDisplayOrder
			WHERE	ISNULL(TaskUserDisplayOrder, 0) <= 0
			AND		PlanComplete IS NOT NULL

		update #tTask 
		set AllTaskUsers = (
		Substring((Select '',''+ LTRIM(str(ttu.UserKey))  AS [text()]   
					From tTaskUser ttu
					WHERE ttu.TaskKey = #tTask.TaskKey
					For XML PATH ('''')),2, 4000) 

		)

		update #tTask
		set AllTaskUserNames = (
			Substring((Select '',''+ LTRIM(vu.UserFullName) AS [text()]   
					From vUserName vu (nolock)
					INNER JOIN tTaskUser ttusr (nolock) on vu.UserKey = ttusr.UserKey
					WHERE ttusr.TaskKey = #tTask.TaskKey
					For XML PATH ('''')),2, 4000)
)
		
		/* Select the return data */
		SELECT	*
		FROM	#tTask
		
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE procedure [dbo].[sptAutoRuleDelete]
(
	@RuleKey int
)
as


update tAutoRule Set IsDeleted = 1 Where RuleKey = @RuleKey


/* dont actually delete 
Delete tAutoEventAction Where RuleKey = @RuleKey
Delete tAutoEvent Where RuleKey = @RuleKey
Delete tAutoRuleTarget Where RuleKey = @RuleKey
Delete tAutoAction Where RuleKey = @RuleKey
Delete tAutoRule Where RuleKey = @RuleKey
*/'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptPurchaseOrderDetailCopyLine]'
GO
IF OBJECT_ID(N'[dbo].[sptPurchaseOrderDetailCopyLine]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptPurchaseOrderDetailCopyLine]
	@PurchaseOrderDetailKey int,
	@oIdentity int OUTPUT
AS --Encrypt

  /*
  || When     Who Rel     What
  || 02/26/07 GHL 8.4     Added project rollup section
  || 07/30/07 BSH 8.4.3.3 (10744)Fix PurchaseOrderTotal on POs, not calculated on copy line. 
  || 06/02/09 RLB 10.0.2.6(53960) Will pull the Office and Department onto the copied line.        
  || 09/14/09 GHL 10.5    Added logic for Transfers
  || 07/06/11 GHL 10.546  (11482) Added tax amounts on the line
  || 12/01/15 GHL 10.598  Added Multi currency fields
  || 09/20/19 AMP 19.1.0.0 (477552) Added Materials Sent, and Materials Sent Date onto the copied line
  || 04/30/26 MCM 26.05.x (725435) Added @InteractiveAdUnitName
  */
	DECLARE	@PurchaseOrderKey int,
			@LineNumber int,
			@POKind smallint,
			@CopyLineNumber int,
			@CustomFieldKey int,
			@FieldSetKey int,
			@ObjectFieldSetKey int,
			@ProjectKey int
			
	SELECT	@PurchaseOrderKey = PurchaseOrderKey,
			@CustomFieldKey = CustomFieldKey,
			@ProjectKey = ProjectKey
	FROM	tPurchaseOrderDetail (NOLOCK)
	WHERE	PurchaseOrderDetailKey = @PurchaseOrderDetailKey
	
	SELECT	@POKind = POKind
	FROM	tPurchaseOrder (NOLOCK)
	WHERE	PurchaseOrderKey = @PurchaseOrderKey

	SELECT	@LineNumber = MAX(LineNumber)
	FROM	tPurchaseOrderDetail (NOLOCK)
	WHERE	PurchaseOrderKey = @PurchaseOrderKey
	
	SELECT	@LineNumber = ISNULL(@LineNumber, 0) + 1
	
	--Get new ObjectFieldSetKey
    IF ISNULL(@CustomFieldKey,0) > 0
    BEGIN
		SELECT	@FieldSetKey = FieldSetKey
		FROM	tObjectFieldSet (NOLOCK)
		WHERE	ObjectFieldSetKey = @CustomFieldKey
		
		EXEC spCF_tObjectFieldSetInsert @FieldSetKey, @ObjectFieldSetKey OUTPUT
		
		IF ISNULL(@ObjectFieldSetKey,0) > 0
			INSERT	tFieldValue
					(FieldValueKey, FieldDefKey, ObjectFieldSetKey, FieldValue)
			SELECT	newid(), FieldDefKey, @ObjectFieldSetKey, FieldValue
			FROM	tFieldValue (NOLOCK)
			WHERE	ObjectFieldSetKey = @CustomFieldKey
    END
	
	IF (@POKind = 0) OR (@POKind = 1) --PO or IO
	BEGIN
		INSERT	tPurchaseOrderDetail
				(PurchaseOrderKey, 
				LineNumber, 
				LinkID, 
				ProjectKey, 
				TaskKey, 
				ClassKey, 
				ShortDescription, 
				LongDescription, 
				ItemKey, 
				Quantity, 
				UnitCost, 
				UnitDescription, 
				TotalCost,
				UnitRate,
				Billable, 
				Markup, 
				BillableCost, 
				AppliedCost, 
				MakeGoodKey, 
				CustomFieldKey, 
				QuoteReplyDetailKey, 
				InvoiceLineKey, 
				AmountBilled, 
				AccruedCost, 
				DateBilled, 
				Closed, 
				DetailOrderDate, 
				DetailOrderEndDate, 
				UserDate1, 
				UserDate2, 
				UserDate3, 
				UserDate4, 
				UserDate5, 
				UserDate6, 
				OrderDays, 
				OrderTime, 
				OrderLength, 
				OnHold, 
				Taxable, 
				Taxable2, 
				BilledComment, 
				TransferComment, 
				AdjustmentNumber, 
				MediaRevisionReasonKey,
				OfficeKey,
				DepartmentKey,
				SalesTaxAmount,
				SalesTax1Amount,
				SalesTax2Amount,
				Commission,
				PTotalCost,
				GrossAmount,
				PCurrencyID,
				PExchangeRate,
				MaterialsSent,
				MaterialsSentDate,
				InteractiveAdUnitName
				)
		SELECT	PurchaseOrderKey, 
				@LineNumber, 
				NULL, --LinkID
				ProjectKey, 
				TaskKey, 
				ClassKey, 
				ShortDescription, 
				LongDescription, 
				ItemKey, 
				Quantity, 
				UnitCost, 
				UnitDescription, 
				TotalCost, 
				UnitRate,
				Billable, 
				Markup, 
				BillableCost, 
				NULL, --AppliedCost
				NULL, --MakeGoodKey
				@ObjectFieldSetKey, --CustomFieldKey
				NULL, --QuoteReplyDetailKey
				NULL, --InvoiceLineKey
				NULL, --AmountBilled
				NULL, --AccruedCost
				NULL, --DateBilled
				0, --Closed
				DetailOrderDate,
				DetailOrderEndDate,
				UserDate1, 
				UserDate2, 
				UserDate3, 
				UserDate4, 
				UserDate5, 
				UserDate6, 
				OrderDays, 
				OrderTime, 
				OrderLength, 
				0, --OnHold
				Taxable, 
				Taxable2, 
				NULL, --BilledComment
				NULL, --TransferComment
				0, --AdjustmentNumber
				NULL, --MediaRevisionReasonKey
				OfficeKey,
				DepartmentKey,
				SalesTaxAmount,
				SalesTax1Amount,
				SalesTax2Amount,
				Commission,
				PTotalCost,
				GrossAmount,
				PCurrencyID,
				PExchangeRate,
				MaterialsSent,
				MaterialsSentDate,
				InteractiveAdUnitName

		FROM	tPurchaseOrderDetail (NOLOCK)
		WHERE	PurchaseOrderDetailKey = @PurchaseOrderDetailKey
	END
	
	IF @POKind = 2 --BC
	BEGIN
		SELECT	@CopyLineNumber = LineNumber
		FROM	tPurchaseOrderDetail (NOLOCK)
		WHERE	PurchaseOrderDetailKey = @PurchaseOrderDetailKey
			
		INSERT	tPurchaseOrderDetail
				(PurchaseOrderKey, 
				LineNumber, 
				LinkID, 
				ProjectKey, 
				TaskKey, 
				ClassKey, 
				ShortDescription, 
				LongDescription, 
				ItemKey, 
				Quantity, 
				UnitCost, 
				UnitDescription, 
				TotalCost, 
				UnitRate,
				Billable, 
				Markup, 
				BillableCost, 
				AppliedCost, 
				MakeGoodKey, 
				CustomFieldKey, 
				QuoteReplyDetailKey, 
				InvoiceLineKey, 
				AmountBilled, 
				AccruedCost, 
				DateBilled, 
				Closed, 
				DetailOrderDate, 
				DetailOrderEndDate, 
				UserDate1, 
				UserDate2, 
				UserDate3, 
				UserDate4, 
				UserDate5, 
				UserDate6, 
				OrderDays, 
				OrderTime, 
				OrderLength, 
				OnHold, 
				Taxable, 
				Taxable2, 
				BilledComment, 
				TransferComment, 
				AdjustmentNumber, 
				MediaRevisionReasonKey,
				OfficeKey,
				DepartmentKey,
				SalesTaxAmount,
				SalesTax1Amount,
				SalesTax2Amount,
				Commission,
				PTotalCost,
				GrossAmount,
				PCurrencyID,
				PExchangeRate,
				MaterialsSent,
				MaterialsSentDate
				)
		SELECT	PurchaseOrderKey, 
				@LineNumber, 
				NULL, --LinkID
				ProjectKey, 
				TaskKey, 
				ClassKey, 
				ShortDescription, 
				LongDescription, 
				ItemKey, 
				Quantity, 
				UnitCost, 
				UnitDescription, 
				TotalCost, 
				UnitRate,
				Billable, 
				Markup, 
				BillableCost, 
				NULL, --AppliedCost
				NULL, --MakeGoodKey
				@ObjectFieldSetKey, --CustomFieldKey 
				NULL, --QuoteReplyDetailKey
				NULL, --InvoiceLineKey
				NULL, --AmountBilled
				NULL, --AccruedCost
				NULL, --DateBilled
				0, --Closed
				DetailOrderDate,
				DetailOrderEndDate,
				UserDate1, 
				UserDate2, 
				UserDate3, 
				UserDate4, 
				UserDate5, 
				UserDate6, 
				OrderDays, 
				OrderTime, 
				OrderLength, 
				0, --OnHold
				Taxable, 
				Taxable2, 
				NULL, --BilledComment
				NULL, --TransferComment
				0, --AdjustmentNumber
				NULL, --MediaRevisionReasonKey
				OfficeKey,
				DepartmentKey,
				SalesTaxAmount,
				SalesTax1Amount,
				SalesTax2Amount,
				Commission,
				PTotalCost,
				GrossAmount,
				PCurrencyID,
				PExchangeRate,
				MaterialsSent,
				MaterialsSentDate
		FROM	tPurchaseOrderDetail  (NOLOCK)
		WHERE	PurchaseOrderKey = @PurchaseOrderKey
		AND		LineNumber = @CopyLineNumber
		AND		AdjustmentNumber = 0
		AND     TransferToKey is null
		
	END
	
	SELECT	@oIdentity = @@IDENTITY

	-- Media have no taxes	
	if @POKind = 0
		insert tPurchaseOrderDetailTax (PurchaseOrderDetailKey, SalesTaxKey, SalesTaxAmount)
		select @oIdentity, SalesTaxKey, SalesTaxAmount
		from   tPurchaseOrderDetailTax (nolock) where PurchaseOrderDetailKey = @PurchaseOrderDetailKey

	exec sptPurchaseOrderRollupAmounts @PurchaseOrderKey

	-- Project rollup, trantype = 5 or po
	EXEC sptProjectRollupUpdate @ProjectKey, 5, 1,1,1,1
	
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleTargetDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleTargetDelete]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptAutoRuleTargetDelete]
  @RuleKey int,
  @Entity varchar(50) = NULL,
  @EntityKey int = NULL
AS

	IF @Entity IS NOT NULL AND @EntityKey IS NOT NULL
		DELETE	tAutoRuleTarget
		WHERE	RuleKey = @RuleKey
		AND		Entity = @Entity
		AND		EntityKey = @EntityKey
	ELSE
		DELETE	tAutoRuleTarget
		WHERE	RuleKey = @RuleKey
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptApiQueueInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptApiQueueInsert]', 'P') IS NOT NULL
EXEC sp_executesql N'

ALTER PROCEDURE [dbo].[sptApiQueueInsert]	
	@CompanyKey	INT, 
	@Entity		VARCHAR(100),
	@EntityKey	INT,
	@Action		VARCHAR(50),
	@ApiHookKey INT = NULL
AS --Encrypt

/*
|| When      Who Rel             What
|| 05/20/21  QMD 21.06.20.0000   (DEV2554) Created new proc for webhooks. This is a general insert into the queue
|| 02/15/24  MCM 24.03.x         (664959) In the check to see if we need to add a new item, added check where Attempts <= 11
|| 03/12/26  CRG 26.04.19        Added optional @ApiHookKey
*/

	IF @ApiHookKey IS NULL
	BEGIN
		SELECT @ApiHookKey = ApiHookKey FROM tApiHook (NOLOCK) WHERE CompanyKey = @CompanyKey AND Entity = @Entity AND [Action] = @Action

		IF ISNULL(@ApiHookKey,'''') = ''''
			RETURN -1

		IF NOT EXISTS (
					SELECT	1 
					FROM	tApiQueue aq (NOLOCK) INNER JOIN tApiHook a (NOLOCK) ON aq.ApiHookKey = a.ApiHookKey									   
					WHERE	a.Entity = @Entity
							AND a.[Action] = @Action
							AND aq.Entity = @Entity
							AND aq.EntityKey = @EntityKey
							AND ISNULL(aq.Attempts, 1) <= 11
					)
			INSERT	tApiQueue (CompanyKey,Entity,EntityKey,Action,ActionDate,ApiHookKey)	
			VALUES	(@CompanyKey, @Entity, @EntityKey, @Action, GETDATE(), @ApiHookKey)
	END
	ELSE
	BEGIN
		--We have the ApiHookKey, just make sure that the same Entity/EntityKey is not in the queue already for this hook
		IF NOT EXISTS (
					SELECT	1 
					FROM	tApiQueue (NOLOCK)								   
					WHERE	ApiHookKey = @ApiHookKey
							AND Entity = @Entity
							AND EntityKey = @EntityKey
							AND ISNULL(Attempts, 1) <= 11
					)
			INSERT	tApiQueue (CompanyKey,Entity,EntityKey,Action,ActionDate,ApiHookKey)	
			VALUES	(@CompanyKey, @Entity, @EntityKey, @Action, GETDATE(), @ApiHookKey)
	END'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleTargetInsert]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleTargetInsert]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptAutoRuleTargetInsert]
  @RuleKey int,
  @Entity varchar(50),
  @EntityKey int
AS

	IF NOT EXISTS(
			SELECT	NULL 
			FROM	tAutoRuleTarget (nolock) 
			WHERE	RuleKey = @RuleKey
			AND		Entity = @Entity
			AND		EntityKey = @EntityKey)
		INSERT	tAutoRuleTarget 
				(RuleKey, 
				Entity, 
				EntityKey)
		VALUES	(@RuleKey, 
				@Entity, 
				@EntityKey)
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoActionDelete]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoActionDelete]', 'P') IS NULL
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[sptAutoActionDelete]
	@ActionKey int = NULL,
	@RuleKey int = NULL
AS
	
	--List of ApiHookKeys to delete
	CREATE TABLE #ApiHook
			(ApiHookKey int null,
			ActionKey int null)

	IF @ActionKey IS NOT NULL
	BEGIN
		INSERT	#ApiHook
		SELECT	ApiHookKey, ActionKey
		FROM	tAutoAction (nolock)
		WHERE	ActionKey = @ActionKey

		DELETE	tAutoAction
		WHERE	ActionKey = @ActionKey
	END
	ELSE
	BEGIN
		INSERT	#ApiHook
		SELECT	ApiHookKey, ActionKey
		FROM	tAutoAction (nolock)
		WHERE	RuleKey = @RuleKey

		DELETE	tAutoAction
		WHERE	RuleKey = @RuleKey
	END

	--Remove ApiHookKeys from the list to delete if they are still in other action records
	DELETE	#ApiHook
	WHERE	ApiHookKey IN 
				(SELECT ApiHookKey 
				FROM tAutoAction (nolock) 
				WHERE ActionKey NOT IN 
					(SELECT ActionKey FROM #ApiHook))

	DELETE	tApiHook
	WHERE	ApiHookKey IN 
				(SELECT ApiHookKey FROM #ApiHook)'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptEstimateTaskExpenseToPOAll]'
GO
IF OBJECT_ID(N'[dbo].[sptEstimateTaskExpenseToPOAll]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptEstimateTaskExpenseToPOAll]
	(
		@EstimateKey INT
		,@UserKey INT
		,@iItemType INT
		,@CheckTaskPercComp INT = 0
	)
AS -- Encrypt

/*
|| When     Who Rel    What
|| 09/19/06 CRG 8.35   Modified to copy the spec sheets from the corresponding quotes to the new POs.
|| 02/26/07 GHL 8.4    Added project rollup section
|| 07/19/07 BSH 8.5    (9659)Added GLCompanyKey, OfficeKey(from project)
||                     and DepartmentKey(from item).
|| 03/06/07 BSH 8.5    (21931)Markup calculated for media orders
|| 10/22/08 GHL 10.5   (37963) Added CompanyAddressKey param on po
|| 03/31/09 RLB 10.022 (49843) when creating BO''s or IO''s UnitCost = UnitRate and UnitRate = null
|| 11/04/09 GHL 10.513 (47035) Added checking of task 100% complete
|| 11/17/09 GHL 10.513 Corrected typo in spTaskValidatePercComp
|| 11/30/09 GHL 10.513 (69313) Only validate task if not null
|| 01/25/10 RLB 10.517 (73101) Added DefaultPOType when creating PO''s from Estimate
|| 02/16/10 GHL 10.518  Added left join with tProject, return of po detail key in temp 
|| 03/01/10 GHL 10.519  Added  PurchaseOrderKey so that flash screen can load it PO
|| 08/2/10  RLB 10.533 (86639) Added ITem Type so it would open the correct PO type 
|| 06/08/11 GHL 10.545 Getting now CompanyAddressKey from tGLCompany
|| 07/06/11 GHL 10.546 (111482) Added PO line tax amounts
|| 09/29/11 GHL 10.548 (122470) The tax keys must come from the vendor, not from the estimate
||                     because taxes on the estimate are for billing purpose only
|| 11/11/11 MAS 10.5.5.0 (121862) Added Print options, 1 to print all lines, 2 print just open lines
|| 12/19/12 RLB 10.5.5.1 (121862) Fixed SP for new Print option
|| 04/09/12 GHL 10.5.5.5 (138964) Creating now the PO detail records in the same order than on the estimate
|| 05/24/12 MFT 10.5.5.6 (144454) Added @HeaderTextKey and @FooterTextKey default
|| 08/31/12 RLB 10.5.5.9 (152847) Wrapped the PO header and detail in a Transaction
|| 10/16/12 GHL 10.5.6.1 (156817) Added error returns -51, -52 to improve error messages
|| 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @ShortDescription from 200 to 300
|| 05/10/13 RLB 10.5.6.8 (177872) Change made to set PO Line type default if there is one set on the Header
|| 05/10/13 RLB 10.5.6.8 (176832) change made to set the correct default sales taxes keys for the vendor
|| 12/16/13 GHL 10.5.7.5 Added currency info, use defaults for now when calling sptPurchaseOrderInsert
|| 12/17/13 GHL 10.5.7.5 Added PCurrency and PExchangeRate parms when calling sptPurchaseOrderDetailInsert
|| 01/10/14 GHL 10.5.7.6 Getting now CurrencyID from the project/campaign
|| 07/14/14 GHL 10.5.8.2 (220671) Allowing now for multiple POs to be linked to each expense line
||                       + corrections (remove checks of existing tEstimateTaskExpense.PurchaseOrderDetailKey)
|| 10/10/14 GHL 10.5.8.5 (232692) Fixed pulling the CurrencyID from the project (was only pulling from the campaign)
|| 10/20/14	GAR	10.5.8.5 (233416) FlightStartDate and FlightEndDate were not getting added to a PO creation when they are
||						 + populated in the project for broadcast orders.  Added code to pull them and add them.
|| 10/17/14 GHL 10.5.8.5 (233422) Differentiate between vendor currency and project currency 
||                       Also calculate GrossAmount and PTotalCost. 
||                       Return an error when we have multicurrency and media types because the media screens
||                       do not handle multicurrency
|| 11/17/14 GHL 10.5.8.6 (236604) For regular POs (i.e not media) allow foreign currencies
|| 12/19/14 GHL 10.5.8.7 (240240) Removed the complexity of taking in account multiple POs for each expense
||                        because the current logic does not consider negative net and gross and frankly this is not required.
||                        Now each time the user creates a PO from the estimate screen, we use same net and gross
|| 03/23/15 WDF 10.5.9.0 (249423) SPARK44 customization...Set PO ApprovedByKey to Estimate InternalApprover
|| 08/11/15 GHL 10.5.9.5 (263071) LongDescription is now varchar(max)
|| 01/05/16 GHL 10.5.9.9 Changed error to -10 when using currency with media (was -9 already used elsewhere)
|| 11/15/17 GHL 10.6.2.2 (371827) Get GLCompanyKey from campaign or opportunity if applicable
|| 06/05/18 GHL 18.7.0.0 DEV1787 Todo 4528 Allowing now foreign currencies on media
|| 08/17/18 GHL 18.9.0.0 Checking now if office and dept are required 
|| 01/25/19 GHL 19.2.0.0 (446608) Reading now PO Text from the vendor instead of preference for custom SPARK44POTEXT 
||                       Also set the PO approver again for custom SPARK44 because the POD insert resets it  
|| 02/06/19 GHL 19.2.0.0 (440666) Adding now *002 from the estimate number to the PO number for SPARK44PONUMBER customization
|| 02/19/19 GHL 19.3.0.0 (446608A) Remove checking of SPARK44POTEXT, this is available to all now
|| 03/07/19 GHL 19.3.0.0 (448458) For Spark44 and also other companies now, use the new  PO approver with the lowest PO limit
|| 03/28/19 GHL 19.4.0.0 (448458/440666) for the SPARK44PONUMBER they do not want to affect the PO Number but they want to change the 
||                        way the project number is displayed on the PO print out, they want basically the estimate number=project number + ''*002'' 
|| 04/06/21 GHL 21.05.16 (554250) Getting specific errors from PO Insert
|| 08/03/21 AMP 21.08.15 (566970) Added description parmater to sptPurchaseOrderInsert this proc was missed when the change for #565359 was made 
|| 01/24/23 AMP 23.03.19 (620412) Added @DueDate defaulted to Today''s date for creating a PO from an estimate
|| 03/14/22 MAS 23.3.19  (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
|| 12/31/24 MFT 25.01.00 (690975) Allow media Orders to be in forign currency
|| 01/09/25 MCM 25.02.x  (691714) Get the appropriate PO header and Footer for IO/BO
|| 01/27/25 MFT 25.02.00 (693071) Set header/footer based on POType defaults
|| 11/25/25 AMP 25.12.14 (711647) Added PO Type to Estimate Edit Settings to be used when creating the order
|| 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName
*/

	SET NOCOUNT ON

	DECLARE @PurchaseOrderKey int
		   ,@PurchaseOrderDetailKey INT
		   ,@PurchaseOrderTypeKey int
		   ,@PurchaseOrderNumber varchar(100)
		   ,@UserName As VARCHAR(200)
		   ,@RetVal int
		   ,@ApprovedQty int
		   ,@POApprover int
		   ,@InternalApprover int
		   ,@CompanyKey int
		   ,@CampaignKey int
		   ,@ProjectKey int
		   ,@LeadKey int
		   ,@OrderDate smalldatetime
		   ,@DueDate smalldatetime
		   ,@RequireClasses smallint
		   ,@RequireOffice smallint
		   ,@RequireDepartment smallint
		   ,@ClassKey int
		   ,@TaskKey int
		   ,@ItemKey int
		   ,@ShortDescription varchar(300)
		   ,@LongDescription varchar(max)
		   ,@Quantity decimal(24,4)
		   ,@UnitCost money
		   ,@UnitDescription varchar(30)
		   ,@TotalCost money
		   ,@UnitRate money
		   ,@Billable tinyint
		   ,@Markup decimal(24,4)
		   ,@BillableCost money
		   ,@HeaderTextKey int
		   ,@FooterTextKey int
		   ,@SalesTaxKey int
		   ,@SalesTax2Key int
		   ,@Taxable int
		   ,@Taxable2 int
		   ,@SalesTax1Amount MONEY
		   ,@SalesTax2Amount MONEY 
		   ,@Contact varchar(200)
		   ,@QuoteDetailKey int
		   ,@QuoteKey int
		   ,@GLCompanyKey int
		   ,@OfficeKey int
		   ,@DepartmentKey int
		   ,@CompanyAddressKey int
		   ,@PurchaseOrderDetailTypeFieldSet int
		   ,@ObjectFieldSetKey int
		   ,@CurrencyID varchar(10) -- Vendor currency
		   ,@ExchangeRate decimal(24,7)
		   ,@PCurrencyID varchar(10) -- Project currency
		   ,@PExchangeRate decimal(24,7)
		   ,@RateHistory int
		   ,@FlightStartDate smalldatetime
		   ,@FlightEndDate smalldatetime
		   ,@PTotalCost money
		   ,@GrossAmount money
		   ,@EstimateNumber varchar(50)

	-- Added for links to multiple PODs
	 declare @PODQuantity decimal(24,4)
		   ,@PODTotalCost money
		   ,@PODBillableCost money
		   ,@PODCount int
		   ,@NewQuantity decimal(24,4)
		   ,@NewTotalCost money
		   ,@NewBillableCost money

	declare @POItemType int = 0
    declare @IOItemType int = 1
	declare @BOItemType int = 2
	-- Assume done in VB
	-- CREATE TABLE #tExpense (ExpenseKey int identity(1,1),  EstimateTaskExpenseKey int null, ItemType int null ,
	-- , PurchaseOrderKey int null, PurchaseOrderNumber varchar(100) null
	-- ,PODBillableCost money null, PODCount int null)
	
	-- Create a temp table to hold the Quote Detail Keys
	CREATE TABLE #tQuoteDetailKeys (QuoteDetailKey int null, QuoteKey int null)
		  
	-- Cannot pass GETDATE() directly as a stored proc parameter!	   
	SELECT @OrderDate = GETDATE()
	SELECT @OrderDate = CONVERT(smalldatetime, CONVERT(VARCHAR(10), @OrderDate ,101), 101)

	SELECT @DueDate= GETDATE()
	SELECT @DueDate = CONVERT(smalldatetime, CONVERT(VARCHAR(10), @DueDate ,101), 101)

	-- Extract info from estimate 
	SELECT @ApprovedQty = e.ApprovedQty
	      ,@InternalApprover = e.InternalApprover
		  ,@ProjectKey = e.ProjectKey
		  ,@CompanyKey = e.CompanyKey
		  ,@GLCompanyKey = p.GLCompanyKey
		  ,@OfficeKey = p.OfficeKey
		  ,@PCurrencyID = p.CurrencyID
		  ,@RequireClasses = isnull(pref.RequireClasses, 0)
		  ,@RequireOffice = isnull(pref.RequireOffice, 0)
		  ,@RequireDepartment = isnull(pref.RequireDepartment, 0)
		  ,@CompanyAddressKey = glc.AddressKey	
		  ,@CampaignKey = e.CampaignKey		
		  ,@LeadKey = e.LeadKey
		  ,@FlightStartDate = p.FlightStartDate
		  ,@FlightEndDate = p.FlightEndDate
		  ,@EstimateNumber = e.EstimateNumber	
	FROM   tEstimate e (nolock)
			LEFT JOIN tProject p (NOLOCK) ON e.ProjectKey = p.ProjectKey
			INNER JOIN tPreference pref (NOLOCK) ON e.CompanyKey = pref.CompanyKey
			LEFT OUTER JOIN tGLCompany glc (nolock) on p.GLCompanyKey = glc.GLCompanyKey 
	WHERE  e.EstimateKey = @EstimateKey	
	AND ((isnull(e.ExternalApprover, 0) > 0 and  e.ExternalStatus = 4) Or (isnull(e.ExternalApprover, 0) = 0 and  e.InternalStatus = 4))
	
	-- Not Approved
	IF @@ROWCOUNT = 0
		RETURN -1

	-- we must correct with the info on the campaign
	if isnull(@CampaignKey, 0) > 0
		select @PCurrencyID = CurrencyID
		      ,@GLCompanyKey = GLCompanyKey 
		from tCampaign (nolock) where CampaignKey = @CampaignKey

	-- or correct with the info on the opportunity
	if isnull(@LeadKey, 0) > 0
		select @GLCompanyKey = GLCompanyKey 
		from tLead (nolock) where LeadKey = @LeadKey


	select @PExchangeRate = 1
	if isnull(@PCurrencyID, '''') = ''''
		select @PCurrencyID = null

	if @PCurrencyID is not null
		exec sptCurrencyGetRate @CompanyKey, @GLCompanyKey, @PCurrencyID, @OrderDate, @PExchangeRate output, @RateHistory output
	
	if isnull(@PExchangeRate, 0) <=0
		select @PExchangeRate = 1

	-- Added for spark44 customization
	--   Approver set to InternalApprover of Estimate for Spark44 only. 
	--   Otherwise, set Approver to UserKey
	declare @Customizations varchar(1000)

	SELECT @Customizations = UPPER(ISNULL(Customizations, ''''))
	  FROM tPreference (NOLOCK)
	 WHERE CompanyKey = @CompanyKey 
	 
	SELECT @POApprover = @UserKey
	IF charindex(''SPARK44'',@Customizations) > 0
		SELECT @POApprover = @InternalApprover


	-- We must have 1 item without PO
	/* Not now since we can have multiple POS				
	IF NOT EXISTS (SELECT 1
					   FROM   tEstimateTaskExpense ete (NOLOCK)
							INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey
							LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
					   WHERE  ete.EstimateKey = @EstimateKey
					   AND    isnull(ete.PurchaseOrderDetailKey, 0) = 0
					   AND    isnull(i.ItemType, 0) = @iItemType
					   )
					   RETURN -2
	*/

	-- We must have a Vendor				
	IF NOT EXISTS (SELECT 1
					   FROM   tEstimateTaskExpense ete (NOLOCK)
							INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey					   
							LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
					   WHERE  ete.EstimateKey = @EstimateKey
					   --AND    isnull(ete.PurchaseOrderDetailKey, 0) = 0 -- multiple POs
					   AND    isnull(ete.VendorKey, 0) > 0
					   AND    isnull(i.ItemType, 0) = @iItemType
					   )
					   RETURN -3
				
	-- We must have a Class				
	IF @RequireClasses = 1
		IF NOT EXISTS (SELECT 1
					   FROM   tEstimateTaskExpense ete (NOLOCK)
							INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey					   
							LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
					   WHERE  ete.EstimateKey = @EstimateKey
					   --AND    isnull(ete.PurchaseOrderDetailKey, 0) = 0 -- multiple POs
					   AND    isnull(ete.VendorKey, 0) > 0
					   AND    isnull(ete.ClassKey, 0) > 0
					   AND    isnull(i.ItemType, 0) = @iItemType
					   )
					   RETURN -4

	-- we must have an office if required
	 if @RequireOffice = 1 and isnull(@OfficeKey, 0) = 0
		return -10

	-- We must have a department on the item if this is required
	IF @RequireDepartment = 1
		IF NOT EXISTS (SELECT 1
					   FROM   tEstimateTaskExpense ete (NOLOCK)
							INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey					   
							LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
					   WHERE  ete.EstimateKey = @EstimateKey
					   AND    isnull(i.DepartmentKey, 0) > 0
					   AND    isnull(i.ItemType, 0) = @iItemType
					   )
					   RETURN -11


	SELECT @UserName = isnull(FirstName, '''') + '' '' + isnull(LastName, '''')
	FROM   tUser (NOLOCK)
	WHERE  UserKey = @UserKey
					   
	-- For the Loops
	DECLARE	@EstimateTaskExpenseKey INT
		   ,@ExpenseKey INT
		   ,@VendorKey int
		   ,@ItemType INT
	
	SELECT @ItemType = -1
		  
	WHILE (1=1)
	BEGIN
		SELECT @ItemType = MIN(ISNULL(i.ItemType, 0))
		FROM   tEstimateTaskExpense ete (NOLOCK)
			INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey
			LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
		WHERE  ete.EstimateKey = @EstimateKey  
		AND    ISNULL(i.ItemType, 0) > @ItemType	-- ItemType can be 0	
		--AND    ISNULL(ete.PurchaseOrderDetailKey, 0) = 0 -- multiple POS
		AND    isnull(ete.VendorKey, 0) > 0			-- VendorKey should never be 0
		AND    (@RequireClasses = 0 OR (@RequireClasses = 1 AND  isnull(ete.ClassKey, 0) > 0)) 
		AND    isnull(i.ItemType, 0) = @iItemType
		
		IF @ItemType IS NULL
			BREAK

		SELECT @VendorKey = -1
		WHILE (1=1)
		BEGIN
			--Delete all of the Quote Detail Keys from the previous PO
			TRUNCATE TABLE #tQuoteDetailKeys
		
			SELECT @VendorKey = MIN(ete.VendorKey)
			FROM   tEstimateTaskExpense ete (NOLOCK)
				INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey
				LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
			WHERE  ete.EstimateKey = @EstimateKey  
			AND    ISNULL(ete.VendorKey, 0) > @VendorKey	
			--AND    ISNULL(ete.PurchaseOrderDetailKey, 0) = 0 -- multiple POs
			AND    ISNULL(i.ItemType, 0) = @ItemType	
			AND    isnull(ete.VendorKey, 0) > 0
			AND    (@RequireClasses = 0 OR (@RequireClasses = 1 AND  isnull(ete.ClassKey, 0) > 0)) 
			
			IF @VendorKey IS NULL
				BREAK

			-- Pickup any class that match the criteria
			-- If the system requires a class we will capture one
			SELECT @ClassKey = ete.ClassKey
			FROM   tEstimateTaskExpense ete (NOLOCK)
			INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey
			LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
			WHERE  ete.EstimateKey = @EstimateKey  
			AND    ISNULL(ete.VendorKey, 0) = @VendorKey	
			--AND    ISNULL(ete.PurchaseOrderDetailKey, 0) = 0 -- multiple POs
			AND    ISNULL(i.ItemType, 0) = @ItemType	
			AND    isnull(ete.VendorKey, 0) > 0
			AND    (@RequireClasses = 0 OR (@RequireClasses = 1 AND  isnull(ete.ClassKey, 0) > 0)) 
						
			SELECT @Contact = u.FirstName + '' '' + u.LastName

				  -- Sales taxes comme from the vendor, not from the estimate
				  -- Sales taxes on the estimates are for billing purpose only
			      ,@SalesTaxKey = c.VendorSalesTaxKey
				  ,@SalesTax2Key = c.VendorSalesTax2Key

				  ,@CurrencyID = c.CurrencyID
				  ,@ExchangeRate = 1
			FROM   tCompany c (NOLOCK)
				LEFT OUTER JOIN tUser u (NOLOCK) ON c.PrimaryContact = u.UserKey
			WHERE c.CompanyKey = @VendorKey	
			
			if isnull(@CurrencyID, '''') = ''''
				select @CurrencyID = null

			if @CurrencyID is not null
				exec sptCurrencyGetRate @CompanyKey, @GLCompanyKey, @CurrencyID, @OrderDate, @ExchangeRate output, @RateHistory output

			if isnull(@ExchangeRate, 0) <=0
				select @ExchangeRate = 1
			
			declare @PrefHeaderTextKey int
			declare @PrefFooterTextKey int
	
		-- get PO type from the Estimate Settings, otherwise use the default set in trans prefs
	       SELECT @PurchaseOrderTypeKey = PurchaseOrderTypeKey 
		                                  FROM tEstimate (nolock)
		     					          WHERE EstimateKey = @EstimateKey
		   SELECT @PurchaseOrderTypeKey = ISNULL(@PurchaseOrderTypeKey,ISNULL(DefaultPOType, 0))
				
				-- get PO text from the preference
				,@PrefHeaderTextKey = CASE WHEN @ItemType = @POItemType THEN ISNULL(POHeaderStandardTextKey, 0)
											WHEN @ItemType = @IOItemType THEN ISNULL(IOHeaderStandardTextKey, 0)
											WHEN @ItemType = @BOItemType THEN ISNULL(BOHeaderStandardTextKey, 0)
											ELSE ISNULL(POHeaderStandardTextKey, 0)
										END
				,@PrefFooterTextKey = CASE WHEN @ItemType = @POItemType THEN ISNULL(POFooterStandardTextKey, 0)
											WHEN @ItemType = @IOItemType THEN ISNULL(IOFooterStandardTextKey, 0)
											WHEN @ItemType = @BOItemType THEN ISNULL(BOFooterStandardTextKey, 0)
											ELSE ISNULL(POFooterStandardTextKey, 0)
										END
			FROM tPreference (NOLOCK)
			WHERE CompanyKey = @CompanyKey
			
			-- get PO text from the default type
			SELECT
				@HeaderTextKey = ISNULL(StandardHeaderTextKey, 0),
				@FooterTextKey = ISNULL(StandardFooterTextKey, 0)
			FROM tPurchaseOrderType pot (nolock)
			WHERE PurchaseOrderTypeKey = @PurchaseOrderTypeKey
			
			-- get PO text from the vendor
			SELECT
				@HeaderTextKey = CASE WHEN ISNULL(POHeaderStandardTextKey, 0) > 0 THEN ISNULL(POHeaderStandardTextKey, 0) ELSE @HeaderTextKey END,
				@FooterTextKey = CASE WHEN ISNULL(POFooterStandardTextKey, 0) > 0 THEN ISNULL(POFooterStandardTextKey, 0) ELSE @FooterTextKey END
			FROM tCompany (NOLOCK)
			WHERE CompanyKey = @VendorKey

			if isnull(@HeaderTextKey, 0) = 0
				SELECT @HeaderTextKey = @PrefHeaderTextKey

			if isnull(@FooterTextKey, 0) = 0
				SELECT @FooterTextKey = @PrefFooterTextKey

			--Added for setting the Detail Default LineType (177872) if there is a POType then set the Detail Type
			IF @PurchaseOrderTypeKey > 0
				SELECT @PurchaseOrderDetailTypeFieldSet = ISNULL(DetailFieldSetKey, 0) FROM tPurchaseOrderType (nolock) WHERE PurchaseOrderTypeKey = @PurchaseOrderTypeKey

			BEGIN TRANSACTION	
			-- Insert PO
			EXEC @RetVal = sptPurchaseOrderInsert
				@CompanyKey,
				@ItemType,	-- @POKind smallint,
				@PurchaseOrderTypeKey,	-- @PurchaseOrderTypeKey int,
				NULL,		-- @PurchaseOrderNumber varchar(30),
				@VendorKey,						
				@ProjectKey,
				NULL,		-- @TaskKey,
				NULL,		-- @ItemKey,
				@ClassKey,	
				@Contact,	-- @Contact varchar(200),
				@OrderDate, -- @PODate smalldatetime,
				@DueDate,	-- @DueDate smalldatetime,
				@UserName,	-- @OrderedBy varchar(200),
				NULL,		-- @CustomFieldKey int,
				@HeaderTextKey,		-- @HeaderTextKey int,
				@FooterTextKey,		-- @FooterTextKey int,
				@POApprover,	-- @ApprovedByKey int,
				@UserKey,	-- @CreatedByKey int,
				NULL,		-- @CompanyMediaKey int,
				NULL,		-- @MediaEstimateKey int,
				1,			-- @OrderDisplayMode smallint,
				0,			-- @BillAt smallint,
				@SalesTaxKey,
				@SalesTax2Key,
				@FlightStartDate,
				@FlightEndDate,
				null,
				0, -- Print Client On Order
				0, -- @PrintTraffic
				1, -- @PrintOption
				@GLCompanyKey, 
				@CompanyAddressKey, -- CompanyAddressKey
				@CurrencyID,
				@ExchangeRate,
				@PCurrencyID,	-- PCurrencyID
				@PExchangeRate,	-- PExchangeRate
				null,
				@PurchaseOrderKey OUTPUT
			
			IF @RetVal <> 1
			BEGIN
				ROLLBACK TRANSACTION

				if @RetVal = -1
					return -51 -- Problem with PO #
				else if @RetVal = -2
					return -52 -- Problem with project status not accepting expenses
				else if @RetVal = -3
					return -53 -- Problem with media estimates
				else if @RetVal = -8
					return -58 -- Problem with Vendor ID
				else
					RETURN -5
			END
			
			select @PurchaseOrderNumber = PurchaseOrderNumber
			from   tPurchaseOrder (nolock)
			where  PurchaseOrderKey = @PurchaseOrderKey

			/* removed because they want to change the printout only, not the PO number 
			IF charindex(''SPARK44PONUMBER'',@Customizations) > 0
			BEGIN
				-- spark44 LA NY wants to add *002 to the PO
				if charindex(''*'', @EstimateNumber) > 0
				BEGIN
					select @PurchaseOrderNumber = isnull(@PurchaseOrderNumber, '''') +  substring(@EstimateNumber, charindex(''*'', @EstimateNumber), len(@EstimateNumber) - charindex(''*'', @EstimateNumber) + 1)
					
					if @PurchaseOrderNumber is not null
						update tPurchaseOrder
						set    PurchaseOrderNumber = @PurchaseOrderNumber
						where  PurchaseOrderKey = @PurchaseOrderKey
				END
			END
			*/

			SELECT @ExpenseKey = -1	
			WHILE (1=1)
			BEGIN
				SELECT @ExpenseKey = MIN(b.ExpenseKey)
				FROM   tEstimateTaskExpense ete (NOLOCK)
					INNER JOIN #tExpense b ON ete.EstimateTaskExpenseKey = b.EstimateTaskExpenseKey
					LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
				WHERE  ete.EstimateKey = @EstimateKey  
				AND    b.ExpenseKey > @ExpenseKey	
				--AND    ISNULL(ete.PurchaseOrderDetailKey, 0) = 0 -- multiple POs
				AND    ISNULL(i.ItemType, 0) = @ItemType	
				AND    ISNULL(ete.VendorKey, 0) = @VendorKey	
				AND    isnull(ete.VendorKey, 0) > 0
				AND    (@RequireClasses = 0 OR (@RequireClasses = 1 AND  isnull(ete.ClassKey, 0) > 0)) 
				

				IF @ExpenseKey IS NULL
					BREAK

				SELECT @EstimateTaskExpenseKey = EstimateTaskExpenseKey
				FROM #tExpense
				WHERE ExpenseKey = @ExpenseKey
				 
				-- Extract info from estimate detail
				SELECT   @VendorKey = ete.VendorKey
						,@ClassKey = ete.ClassKey
						,@TaskKey = ete.TaskKey
						,@ItemKey = ete.ItemKey
						,@QuoteDetailKey = ete.QuoteDetailKey
						,@ShortDescription = ete.ShortDescription
						,@LongDescription = ete.LongDescription
						,@Billable = ete.Billable
						,@Quantity = CASE @ApprovedQty
						WHEN 1 THEN ete.Quantity WHEN 2 THEN ete.Quantity2 WHEN 3 THEN ete.Quantity3
						WHEN 4 THEN ete.Quantity4 WHEN 5 THEN ete.Quantity5 WHEN 6 THEN ete.Quantity6
						ELSE ete.Quantity END
						,@UnitCost = CASE @ApprovedQty 
						WHEN 1 THEN ete.UnitCost WHEN 2 THEN ete.UnitCost2 WHEN 3 THEN ete.UnitCost3 
						WHEN 4 THEN ete.UnitCost4 WHEN 5 THEN ete.UnitCost5 WHEN 6 THEN ete.UnitCost6
						ELSE ete.UnitCost END	
						,@TotalCost = CASE @ApprovedQty 
						WHEN 1 THEN ete.TotalCost WHEN 2 THEN ete.TotalCost2 WHEN 3 THEN ete.TotalCost3 
						WHEN 4 THEN ete.TotalCost4 WHEN 5 THEN ete.TotalCost5 WHEN 6 THEN ete.TotalCost6
						ELSE ete.TotalCost END	
						,@UnitDescription = CASE @ApprovedQty
						WHEN 1 THEN ete.UnitDescription WHEN 2 THEN ete.UnitDescription2 WHEN 3 THEN ete.UnitDescription3 
						WHEN 4 THEN ete.UnitDescription4 WHEN 5 THEN ete.UnitDescription5 WHEN 6 THEN ete.UnitDescription6
						ELSE ete.UnitDescription END	
						,@Markup = CASE @ApprovedQty
						WHEN 1 THEN ete.Markup WHEN 2 THEN ete.Markup2 WHEN 3 THEN ete.Markup3 
						WHEN 4 THEN ete.Markup4 WHEN 5 THEN ete.Markup5 WHEN 6 THEN ete.Markup6
						ELSE ete.Markup END	
						,@UnitRate = CASE @ApprovedQty
						WHEN 1 THEN ete.UnitRate WHEN 2 THEN ete.UnitRate2 WHEN 3 THEN ete.UnitRate3
						WHEN 4 THEN ete.UnitRate4 WHEN 5 THEN ete.UnitRate5 WHEN 6 THEN ete.UnitRate6
						ELSE ete.UnitRate END
						,@BillableCost = CASE @ApprovedQty
						WHEN 1 THEN ete.BillableCost WHEN 2 THEN ete.BillableCost2 WHEN 3 THEN ete.BillableCost3 
						WHEN 4 THEN ete.BillableCost4 WHEN 5 THEN ete.BillableCost5 WHEN 6 THEN ete.BillableCost6
						ELSE ete.BillableCost END
						,@Taxable = ete.Taxable
						,@Taxable2 = ete.Taxable2						
					FROM  tEstimateTaskExpense ete (NOLOCK)
						INNER JOIN tEstimate e (NOLOCK) ON ete.EstimateKey = e.EstimateKey
						LEFT JOIN tProject p (NOLOCK) ON e.ProjectKey = p.ProjectKey
						LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey 
					WHERE ete.EstimateTaskExpenseKey = @EstimateTaskExpenseKey
					
					-- Only do this if there is no foreign currency at all
					if @CurrencyID is null And @PCurrencyID is null 
					begin 
						-- Removed this because of 240240, this becomes too complex when TotalCost < 0

						/*
						-- since we link to several PODs, calculate the existing amounts on POs 
						select @PODQuantity = sum(pod.Quantity) 
							  ,@PODTotalCost = sum(pod.TotalCost)
							  ,@PODBillableCost = sum(pod.BillableCost)
						from tPurchaseOrderDetail pod (nolock)
							inner join tEstimateTaskExpenseOrder eteo (nolock) on eteo.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey 
						where eteo.EstimateTaskExpenseKey = @EstimateTaskExpenseKey

						select @NewQuantity = isnull(@Quantity, 0) - isnull(@PODQuantity, 0)
							  ,@NewTotalCost = isnull(@TotalCost, 0) - isnull(@PODTotalCost, 0)
							  ,@NewBillableCost = isnull(@BillableCost, 0) - isnull(@PODBillableCost, 0)
						  
						if @NewQuantity <0
							select @NewQuantity = 0
						if @NewTotalCost <0
							select @NewTotalCost = 0
						if @NewBillableCost <0
							select @NewBillableCost = 0

						--If POKind is Media, recalculate markup to reflect as commission. 
						IF @ItemType > 0 
						BEGIN
							select @UnitCost = @UnitRate
							select @UnitRate = null
							IF @NewBillableCost <> 0
								SELECT @Markup = (1 - (@NewTotalCost/@NewBillableCost)) * 100
							ELSE
								SELECT @Markup = 0
						END
						*/

						select @NewQuantity = isnull(@Quantity, 0)
							  ,@NewTotalCost = isnull(@TotalCost, 0)      
 							  ,@NewBillableCost =isnull(@BillableCost, 0) 

						-- by default, PTotalCost = TotalCost and GrossAmount = BillableCost
						select @PTotalCost = @NewTotalCost
						      ,@GrossAmount = @NewBillableCost

					end
					else
					begin
						-- if foreign currency are involved, do not take in account other PODs
						-- because of complexity in case the vendors are of different currencies
						select @NewQuantity = isnull(@Quantity, 0)
							  ,@NewTotalCost = isnull(@TotalCost, 0)      -- will need to be recalc''ed in Vendor Currency 
 							  ,@NewBillableCost =isnull(@BillableCost, 0) -- This is fine in Project Currency

						-- PTotalCost is Project Currency, so same as TotalCost
						select @PTotalCost = @NewTotalCost

						-- but we need to convert using exchange rates, from project currency to vendor currency
						select @UnitCost = (@UnitCost * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency
						      ,@NewTotalCost = (@NewTotalCost * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency
							  ,@UnitRate = (@UnitRate * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency
							  ,@GrossAmount = (@NewBillableCost * @PExchangeRate) / @ExchangeRate  -- In Vendor Currency


						select @UnitCost = round(@UnitCost, 4)
						      ,@NewTotalCost = round(@NewTotalCost, 2)
							  ,@UnitRate = round(@UnitRate, 4)
						      ,@GrossAmount = round(@GrossAmount, 2)

						IF @ItemType > 0 
						BEGIN
							select @UnitCost = @UnitRate
							select @UnitRate = null
							IF @GrossAmount <> 0
								SELECT @Markup = (1 - (@NewTotalCost/@GrossAmount)) * 100
							ELSE
								SELECT @Markup = 0
						END

					end
				
					
					SELECT @DepartmentKey = DepartmentKey
					FROM   tItem i (NOLOCK)
					WHERE  i.ItemKey = @ItemKey

					IF @CheckTaskPercComp = 1 AND ISNULL(@TaskKey, 0) > 0
					BEGIN
						EXEC @RetVal = spTaskValidatePercComp ''tPurchaseOrderDetail'', 0, null, null,null, @TaskKey, @UserKey, 1
						IF @RetVal <=0
						BEGIN
							ROLLBACK TRANSACTION
							RETURN -8
						END
					END
					
					--Add the QuoteDetailKey to the Temp Table
					IF ISNULL(@QuoteDetailKey, 0) > 0
						INSERT #tQuoteDetailKeys (QuoteDetailKey) VALUES (@QuoteDetailKey)

					EXEC @RetVal = sptPurchaseOrderDetailInsert 
						@PurchaseOrderKey = @PurchaseOrderKey,
						@LineNumber = 0,
						@ProjectKey = @ProjectKey,
						@TaskKey = @TaskKey,
						@ItemKey = @ItemKey,
						@ClassKey = @ClassKey,
						@ShortDescription = @ShortDescription,
						@Quantity = @NewQuantity,
						@UnitCost = @UnitCost,
						@UnitDescription = @UnitDescription,
						@TotalCost = @NewTotalCost,
						@UnitRate = @UnitRate,
						@Billable = @Billable,
						@Markup = @Markup,
						@BillableCost = @NewBillableCost,
						@LongDescription = @LongDescription,
						@CustomFieldKey = NULL,
						@DetailOrderDate = @OrderDate,
						@DetailOrderEndDate = NULL,
						@UserDate1 = NULL,
						@UserDate2 = NULL,
						@UserDate3 = NULL,
						@UserDate4 = NULL,
						@UserDate5 = NULL,
						@UserDate6 = NULL,
						@OrderDays = NULL,
						@OrderTime = NULL,
						@OrderLength = NULL,
						@Taxable = @Taxable,
						@Taxable2 = @Taxable2,
						@OfficeKey = @OfficeKey,
						@DepartmentKey = @DepartmentKey,
						@GrossAmount = @GrossAmount,
						@PCurrencyID = @PCurrencyID,
						@PExchangeRate = @PExchangeRate,
						@PTotalCost = @PTotalCost,
						@SkipRollUps = NULL,
						@InteractiveAdUnitName = NULL,
						@oIdentity = @PurchaseOrderDetailKey OUTPUT

					IF @RetVal <> 1
					BEGIN
						ROLLBACK TRANSACTION
						RETURN -6
					END

					IF @RetVal = 1 
					BEGIN
						insert tEstimateTaskExpenseOrder (EstimateTaskExpenseKey, PurchaseOrderDetailKey)
						values (@EstimateTaskExpenseKey, @PurchaseOrderDetailKey)

						--UPDATE tEstimateTaskExpense 
						--SET PurchaseOrderDetailKey = @PurchaseOrderDetailKey	
						--WHERE  EstimateTaskExpenseKey = @EstimateTaskExpenseKey
						
						IF @@ERROR <> 0
						BEGIN
							ROLLBACK TRANSACTION
							RETURN -7 
						END

						-- since we link to several PODs, calculate the new amounts on POs 
						select @PODBillableCost = sum(pod.BillableCost)
						from tPurchaseOrderDetail pod (nolock)
							inner join tEstimateTaskExpenseOrder eteo (nolock) on eteo.PurchaseOrderDetailKey = pod.PurchaseOrderDetailKey 
						where eteo.EstimateTaskExpenseKey = @EstimateTaskExpenseKey

						-- and the number of PODs
						select @PODCount = count(eteo.PurchaseOrderDetailKey)
						from  tEstimateTaskExpenseOrder eteo (nolock)  
						where eteo.EstimateTaskExpenseKey = @EstimateTaskExpenseKey

						UPDATE #tExpense 
						SET    PODBillableCost = @PODBillableCost  
						      ,PODCount = @PODCount
							  ,PurchaseOrderKey = @PurchaseOrderKey	
							  ,PurchaseOrderNumber = @PurchaseOrderNumber
							  ,ItemType = @ItemType
						WHERE  EstimateTaskExpenseKey = @EstimateTaskExpenseKey

						--Need If there is a default Detail Type need to set CustomFieldKey on the new detail line
						IF @PurchaseOrderDetailTypeFieldSet > 0
						BEGIN
							EXEC spCF_tObjectFieldSetInsert @PurchaseOrderDetailTypeFieldSet, @ObjectFieldSetKey OUTPUT

							IF ISNULL(@ObjectFieldSetKey,0) > 0
							BEGIN
								UPDATE tPurchaseOrderDetail
								Set CustomFieldKey = @ObjectFieldSetKey
								WHERE PurchaseOrderDetailKey = @PurchaseOrderDetailKey

								IF @@ERROR <> 0
								BEGIN
									ROLLBACK TRANSACTION
									RETURN -9 
								END
							END

						END
						
					END -- end POD
					
			END

			COMMIT TRANSACTION 

			EXEC sptPurchaseOrderSetSparkApprover @CompanyKey, @PurchaseOrderKey, @POApprover

			EXEC sptPurchaseOrderRecalcAmounts @PurchaseOrderKey 

			--Update the QuoteKeys in the Temp Table
			UPDATE	#tQuoteDetailKeys
			SET		QuoteKey = qd.QuoteKey
			FROM	tQuoteDetail qd (nolock)
			WHERE	#tQuoteDetailKeys.QuoteDetailKey = qd.QuoteDetailKey

			--Copy the Spec Sheets from the Quotes to the POs
			SELECT @QuoteKey = -1
			WHILE (1=1)
			BEGIN
				SELECT	@QuoteKey = MIN(QuoteKey)
				FROM	#tQuoteDetailKeys
				WHERE	QuoteKey > @QuoteKey
				
				IF @QuoteKey IS NULL
					BREAK
				
				--Copy all Spec Sheets from this Quote that haven''t already been linked to the PO
				INSERT	tSpecSheetLink
						(SpecSheetKey,
						Entity,
						EntityKey,
						CompanyKey)
				SELECT	SpecSheetKey,
						''PO'',
						@PurchaseOrderKey,
						CompanyKey
				FROM	tSpecSheetLink (nolock)
				WHERE	Entity = ''Est''
				AND		EntityKey = @QuoteKey
				AND		SpecSheetKey NOT IN
							(SELECT SpecSheetKey
							FROM	tSpecSheetLink (nolock)
							WHERE	Entity = ''PO''
							AND		EntityKey = @PurchaseOrderKey)
				
			END				
		END	
	END				     				   

	-- Project rollup for trantype = 5 po 
	EXEC sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1
	
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleUpdate]', 'P') IS NULL
EXEC sp_executesql N'
CREATE PROCEDURE [dbo].[sptAutoRuleUpdate]
(
    @RuleKey        INT,
	@CompanyKey		INT,
    @Name           VARCHAR(300),
    @Description    VARCHAR(MAX)     = NULL,
    @Scope          VARCHAR(50)      = NULL,
    @Active         TINYINT          = NULL,
    @IsDeleted      TINYINT          = 0,
    @UserKey	    INT,
    @Private        TINYINT          = NULL,
    @Event          VARCHAR(50),
    @Options        NVARCHAR(MAX)     = NULL,
    @Conditions     NVARCHAR(MAX)     = NULL,
    @NextRunTime    DATETIME         = NULL
)
AS

IF @RuleKey = 0 
BEGIN

INSERT INTO tAutoRule
    (
        CompanyKey,
        Name,
        Description,
        Scope,
        Active,
        IsDeleted,
        CreatedBy,
        DateCreated,
        UpdatedBy,
        DateUpdated,
        Version,
        Private,
        Event,
        Options,
        Conditions,
        NextRunTime
    )
    VALUES
    (
        @CompanyKey,
        @Name,
        @Description,
        @Scope,
        @Active,
        0,
        @UserKey,
        GETUTCDATE(),
        @UserKey,
        GETUTCDATE(),
        1,
        @Private,
        @Event,
        @Options,
        @Conditions,
        @NextRunTime
    )

    SELECT @RuleKey = SCOPE_IDENTITY();
END
ELSE
BEGIN

    UPDATE tAutoRule
    SET
        Name        = @Name,
        Description = @Description,
        Scope       = @Scope,
        Active      = @Active,
        IsDeleted   = @IsDeleted,
        UpdatedBy   = @UserKey,
        DateUpdated = GETUTCDATE(),
        Version     = ISNULL(Version, 0) + 1,
        Private     = @Private,
        Event       = @Event,
        Options     = @Options,
        Conditions  = @Conditions,
        NextRunTime = @NextRunTime
    WHERE
        RuleKey = @RuleKey

	EXEC sptAutoRuleTargetDelete @RuleKey
	EXEC sptAutoActionDelete NULL, @RuleKey
END

RETURN @RuleKey

'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleGetList]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleGetList]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptAutoRuleGetList]
(
	@CompanyKey int,
	@UserKey int
)

as

	Select	r.*, 
			cu.UserFullName AS CreatedByName, 
			uu.UserFullName as LastUpdatedByName
	FROM	tAutoRule r (nolock) 
	LEFT JOIN vUserName cu (nolock) on r.CreatedBy = cu.UserKey
	LEFT JOIN vUserName uu (nolock) on r.UpdatedBy = uu.UserKey
	WHERE	r.CompanyKey = @CompanyKey
	AND		ISNULL(r.IsDeleted, 0) = 0
	AND		(r.Private <> 1 OR r.CreatedBy = @UserKey)
	ORDER BY Scope, Name
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[vAutoRuleTarget]'
GO
IF OBJECT_ID(N'[dbo].[vAutoRuleTarget]', 'V') IS NULL
EXEC sp_executesql N'CREATE VIEW [dbo].[vAutoRuleTarget]
AS

	SELECT	t.*,
			CASE t.Entity
				WHEN ''projectType'' THEN pt.ProjectTypeName
				WHEN ''projectStatus'' THEN ps.ProjectStatus
				WHEN ''client'' THEN ISNULL(c.CustomerID, '''') + '' - '' + ISNULL(c.CompanyName, '''')
				WHEN ''campaign'' THEN ISNULL(camp.CampaignID, '''') + ''-'' + ISNULL(camp.CampaignName, '''')
				WHEN ''project'' THEN ISNULL(p.ProjectNumber, '''') + '' '' + ISNULL(p.ProjectName, '''')
			END AS DisplayLabel
	FROM	tAutoRuleTarget t (nolock)
	LEFT JOIN tProjectType pt (nolock) ON t.Entity = ''projectType'' AND t.EntityKey = pt.ProjectTypeKey
	LEFT JOIN tProjectStatus ps (nolock) ON t.Entity = ''projectStatus'' AND t.EntityKey = ps.ProjectStatusKey
	LEFT JOIN tCompany c (nolock) ON t.Entity = ''client'' AND t.EntityKey = c.CompanyKey
	LEFT JOIN tCampaign camp (nolock) ON t.Entity = ''campaign'' AND t.EntityKey = camp.CampaignKey
	LEFT JOIN tProject p (nolock) ON t.Entity = ''project'' AND t.EntityKey = p.ProjectKey



	
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering [dbo].[sptEstimateTaskExpenseToPO]'
GO
IF OBJECT_ID(N'[dbo].[sptEstimateTaskExpenseToPO]', 'P') IS NOT NULL
EXEC sp_executesql N'
ALTER PROCEDURE [dbo].[sptEstimateTaskExpenseToPO]
	(
		@EstimateTaskExpenseKey INT
		,@UserKey INT
		,@CheckTaskPercComp INT = 0
		,@oType INT OUTPUT
		,@oPurchaseOrderKey INT OUTPUT
		,@oPurchaseOrderDetailKey INT OUTPUT
	)
AS -- Encrypt

  /*
  || When     Who Rel   What
  || 02/26/07 GHL 8.4   Added project rollup section
  || 07/18/07 BSH 8.5   (9659)Added GLCompanyKey, OfficeKey(from project)
  ||                       and DepartmentKey(from item).  
  || 03/06/07 BSH 8.5   (21931)Markup calculated for media orders.
  || 10/22/08 GHL 10.5    (37963) Added CompanyAddressKey param
  || 04/27/09 RLB 10.024 (49843) when creating BO''s or IO''s UnitCost = UnitRate and UnitRate = null
  || 11/04/09 GHL 10.513 (47035) Added checking of task 100% complete
  || 11/17/09 GHL 10.513 Corrected typo in spTaskValidatePercComp
  || 11/30/09 GHL 10.513 (69313) Only validate task if not null
  || 01/25/10 RLB 10.517 (73101) Added DefaultPOType when creating PO''s from Estimate
  || 03/01/10 GHL 10.519 Removed inner join between tEstimate.ProjectKey and tProject.ProjectKey
  || 06/08/11 GHL 10.545 Getting now CompanyAddressKey from tGLCompany
  || 07/06/11 GHL 10.546 (111482) Added PO line tax amounts
  || 11/11/11 MAS 10.5.5.0 (121862) Added Print options, 1 to print all lines, 2 print just open lines
  || 12/19/12 RLB 10.5.5.1 (121862) Fixed SP for new Print option
  || 05/24/12 MFT 10.5.5.6 (144454) Added @HeaderTextKey and @FooterTextKey default
  || 12/03/12 MAS 10.5.6.2 (161425)Changed the length of @ShortDescription from 200 to 300
  || 12/16/13 GHL 10.5.7.5 Added currency info, use defaults for now when calling sptPurchaseOrderInsert
  || 12/17/13 GHL 10.5.7.5 Added PCurrency and PExchangeRate parms when calling sptPurchaseOrderDetailInsert
  || 01/10/14 GHL 10.5.7.6 Getting now CurrencyID from the project/campaign
  || 08/11/15 GHL 10.5.9.5 (263071) LongDescription is now varchar(max)
  || 01/25/19 GHL 19.2.0.0 (446608) Reading now PO Text from the vendor instead of preference for custom SPARK44POTEXT 
  || 02/19/19 GHL 19.3.0.0 (446608A) Remove checking of SPARK44POTEXT, this is available to all now
  || 07/23/21 MCM 21.08    (565359) Added description parmater to sptPurchaseOrderInsert
  || 03/14/22 MAS 23.3.19 (632405) Added SkipRollUps flag to skip the RollupAmount and UpdateApprover.
  || 04/30/26 MCM 26.05.x (725435) Updated call to sptPurchaseOrderDetailInsert to be named parameters and added new parameter for @InteractiveAdUnitName
  */

	SET NOCOUNT ON

	DECLARE @PurchaseOrderKey int
		   ,@PurchaseOrderDetailKey INT
		   ,@PurchaseOrderTypeKey int
		   ,@UserName As VARCHAR(200)
		   ,@RetVal int
		   ,@ApprovedQty int
		   ,@CompanyKey int
		   ,@CampaignKey int
		   ,@ProjectKey int
		   ,@OrderDate smalldatetime
		   ,@RequireClasses smallint
		   ,@ClassKey int
		   ,@VendorKey int
		   ,@TaskKey int
		   ,@ItemKey int
		   ,@ItemType smallint
		   ,@ShortDescription varchar(300)
		   ,@LongDescription varchar(max)
		   ,@Quantity decimal(24,4)
		   ,@UnitCost money
		   ,@UnitDescription varchar(30)
		   ,@TotalCost money
		   ,@UnitRate money
	     ,@Billable tinyint
		   ,@Markup decimal(24,4)
		   ,@BillableCost money
		   ,@QuoteDetailKey int
		   ,@QuoteKey int
		   ,@HeaderTextKey int
		   ,@FooterTextKey int
		   ,@SalesTaxKey int
		   ,@SalesTax2Key int
		   ,@Taxable int
		   ,@Taxable2 int
		   ,@GLCompanyKey int
		   ,@OfficeKey int
		   ,@DepartmentKey int		   
		   ,@Contact varchar(200)
		   ,@CompanyAddressKey int
		   ,@CurrencyID varchar(10)
		   ,@ExchangeRate decimal(24,7)

	-- Extract info from estimate 
	SELECT @ApprovedQty = e.ApprovedQty
		  ,@ProjectKey = e.ProjectKey
		  ,@CampaignKey = e.CampaignKey
	FROM   tEstimate e (nolock)
		INNER JOIN tEstimateTaskExpense ete (NOLOCK) ON ete.EstimateKey = e.EstimateKey
	WHERE  ete.EstimateTaskExpenseKey = @EstimateTaskExpenseKey	
	AND ((isnull(e.ExternalApprover, 0) > 0 and  e.ExternalStatus = 4) Or (isnull(e.ExternalApprover, 0) = 0 and  e.InternalStatus = 4))
	
	-- Not Approved
	IF @@ROWCOUNT = 0
		RETURN -1
				
	-- Extract info from estimate detail
	SELECT   @CompanyKey = e.CompanyKey
			,@GLCompanyKey = p.GLCompanyKey
			,@CurrencyID = p.CurrencyID
	        ,@OfficeKey = p.OfficeKey
			,@RequireClasses = isnull(pref.RequireClasses, 0)
			,@PurchaseOrderDetailKey = ete.PurchaseOrderDetailKey
			,@VendorKey = ete.VendorKey
			,@ClassKey = ete.ClassKey
			,@TaskKey = ete.TaskKey
			,@ItemKey = ete.ItemKey
			,@QuoteDetailKey = ete.QuoteDetailKey
			,@ItemType = isnull(i.ItemType, 0)	-- Regular PO as default
			,@ShortDescription = ete.ShortDescription
			,@LongDescription = ete.LongDescription
			,@Billable = ete.Billable
			,@Quantity = CASE @ApprovedQty
			WHEN 1 THEN ete.Quantity WHEN 2 THEN ete.Quantity2 WHEN 3 THEN ete.Quantity3
			WHEN 4 THEN ete.Quantity4 WHEN 5 THEN ete.Quantity5 WHEN 6 THEN ete.Quantity6
			ELSE ete.Quantity END
			,@UnitCost = CASE @ApprovedQty 
			WHEN 1 THEN ete.UnitCost WHEN 2 THEN ete.UnitCost2 WHEN 3 THEN ete.UnitCost3 
			WHEN 4 THEN ete.UnitCost4 WHEN 5 THEN ete.UnitCost5 WHEN 6 THEN ete.UnitCost6
			ELSE ete.UnitCost END	
			,@TotalCost = CASE @ApprovedQty 
			WHEN 1 THEN ete.TotalCost WHEN 2 THEN ete.TotalCost2 WHEN 3 THEN ete.TotalCost3 
			WHEN 4 THEN ete.TotalCost4 WHEN 5 THEN ete.TotalCost5 WHEN 6 THEN ete.TotalCost6
			ELSE ete.TotalCost END	
			,@UnitDescription = CASE @ApprovedQty
			WHEN 1 THEN ete.UnitDescription WHEN 2 THEN ete.UnitDescription2 WHEN 3 THEN ete.UnitDescription3 
			WHEN 4 THEN ete.UnitDescription4 WHEN 5 THEN ete.UnitDescription5 WHEN 6 THEN ete.UnitDescription6
			ELSE ete.UnitDescription END	
			,@Markup = CASE @ApprovedQty
			WHEN 1 THEN ete.Markup WHEN 2 THEN ete.Markup2 WHEN 3 THEN ete.Markup3 
			WHEN 4 THEN ete.Markup4 WHEN 5 THEN ete.Markup5 WHEN 6 THEN ete.Markup6
			ELSE ete.Markup END
			,@UnitRate = CASE @ApprovedQty
			WHEN 1 THEN ete.UnitRate WHEN 2 THEN ete.UnitRate2 WHEN 3 THEN ete.UnitRate3
			WHEN 4 THEN ete.UnitRate4 WHEN 5 THEN ete.UnitRate5 WHEN 6 THEN ete.UnitRate6
			ELSE ete.UnitRate END
			,@BillableCost = CASE @ApprovedQty
			WHEN 1 THEN ete.BillableCost WHEN 2 THEN ete.BillableCost2 WHEN 3 THEN ete.BillableCost3 
			WHEN 4 THEN ete.BillableCost4 WHEN 5 THEN ete.BillableCost5 WHEN 6 THEN ete.BillableCost6
			ELSE ete.BillableCost END
			,@Taxable = ete.Taxable
			,@Taxable2 = ete.Taxable2
			,@CompanyAddressKey = glc.AddressKey			
		FROM  tEstimateTaskExpense ete (NOLOCK)
			INNER JOIN tEstimate e (NOLOCK) ON ete.EstimateKey = e.EstimateKey
			LEFT JOIN tProject p (NOLOCK) ON e.ProjectKey = p.ProjectKey
			INNER JOIN tPreference pref (NOLOCK) ON e.CompanyKey = pref.CompanyKey
			LEFT OUTER JOIN tItem i (NOLOCK) ON ete.ItemKey = i.ItemKey
			LEFT OUTER JOIN tGLCompany glc (nolock) on p.GLCompanyKey = glc.GLCompanyKey 
		WHERE ete.EstimateTaskExpenseKey = @EstimateTaskExpenseKey
		
	if isnull(@CampaignKey, 0) > 0
		select @CurrencyID = CurrencyID from tCampaign (nolock) where CampaignKey = @CampaignKey

	select @ExchangeRate = 1
	if isnull(@CurrencyID, '''') = ''''
		select @CurrencyID = null

	--If POKind is Media, recalculate markup to reflect as commission. 
	IF @ItemType > 0 
	BEGIN
	    select @UnitCost = @UnitRate
		select @UnitRate = null
		IF @BillableCost <> 0
			SELECT @Markup = (1 - (@TotalCost/@BillableCost)) * 100
		ELSE
			SELECT @Markup = 0
	END
		
	SELECT @DepartmentKey = DepartmentKey
	FROM   tItem i (NOLOCK)
	WHERE  i.ItemKey = @ItemKey

	-- Validate expense
	IF ISNULL(@PurchaseOrderDetailKey, 0) > 0
		RETURN -2
		
	IF ISNULL(@VendorKey, 0) = 0
		RETURN -3
				
	IF ISNULL(@ClassKey, 0) = 0 AND @RequireClasses = 1
		RETURN -4

	IF @CheckTaskPercComp = 1 AND ISNULL(@TaskKey, 0) > 0 
	BEGIN
		EXEC @RetVal = spTaskValidatePercComp ''tPurchaseOrderDetail'', 0, null, null,null, @TaskKey, @UserKey, 1
		IF @RetVal <=0
			RETURN -8
	END
		
	IF ISNULL(@QuoteDetailKey, 0) > 0
	BEGIN
		SELECT @QuoteKey = QuoteKey FROM tQuoteDetail (NOLOCK) WHERE QuoteDetailKey = @QuoteDetailKey  
	END
				
	-- Cannot pass GETDATE() directly as a stored proc parameter!	   
	SELECT @OrderDate = GETDATE()
	SELECT @OrderDate = CONVERT(smalldatetime, CONVERT(VARCHAR(10), @OrderDate ,101), 101)

	SELECT @UserName = isnull(FirstName, '''') + '' '' + isnull(LastName, '''')
	FROM   tUser (NOLOCK)
	WHERE  UserKey = @UserKey

	SELECT @Contact = u.FirstName + '' '' + u.LastName
		
		-- Sales taxes comme from the vendor, not from the estimate
		-- Sales taxes on the estimates are for billing purpose only
		,@SalesTaxKey = c.SalesTaxKey
		,@SalesTax2Key = c.SalesTax2Key

	FROM   tCompany c (NOLOCK)
		LEFT OUTER JOIN tUser u (NOLOCK) ON c.PrimaryContact = u.UserKey
	WHERE c.CompanyKey = @VendorKey	
			

	declare @PrefHeaderTextKey int
	declare @PrefFooterTextKey int
	
	-- get PO text from the preference
	SELECT @PurchaseOrderTypeKey = ISNULL(DefaultPOType, 0)
		,@PrefHeaderTextKey = ISNULL(POHeaderStandardTextKey, 0)
		,@PrefFooterTextKey = ISNULL(POFooterStandardTextKey, 0)
	FROM tPreference (NOLOCK)
	WHERE CompanyKey = @CompanyKey 

	-- get PO text from the vendor
	SELECT @HeaderTextKey = ISNULL(POHeaderStandardTextKey, 0)
			,@FooterTextKey = ISNULL(POFooterStandardTextKey, 0)
	FROM tCompany (NOLOCK)
	WHERE CompanyKey = @VendorKey

	if isnull(@HeaderTextKey, 0) = 0
		SELECT @HeaderTextKey = @PrefHeaderTextKey

	if isnull(@FooterTextKey, 0) = 0
		SELECT @FooterTextKey = @PrefFooterTextKey

	BEGIN TRAN
			
	-- Insert PO
	EXEC @RetVal = sptPurchaseOrderInsert
		@CompanyKey,
		@ItemType,	-- @POKind smallint,
		@PurchaseOrderTypeKey, -- @PurchaseOrderTypeKey int,
		NULL,		-- @PurchaseOrderNumber varchar(30),
		@VendorKey,
		@ProjectKey,
		@TaskKey,
		@ItemKey,
		@ClassKey,
		@Contact,	-- @Contact varchar(200),
		@OrderDate, -- @PODate smalldatetime,
		NULL,		-- @DueDate smalldatetime,
		@UserName,	-- @OrderedBy varchar(200),
		NULL,		-- @CustomFieldKey int,
		@HeaderTextKey,		-- @HeaderTextKey int,
		@FooterTextKey,		-- @FooterTextKey int,
		@UserKey,	-- @ApprovedByKey int,
		@UserKey,	-- @CreatedByKey int,
		NULL,		-- @CompanyMediaKey int,
		NULL,		-- @MediaEstimateKey int,
		1,			-- @OrderDisplayMode smallint,
		0,			-- @BillAt smallint,
		@SalesTaxKey,
		@SalesTax2Key,
		null,
		null,
		null,		
		0, -- Print Client On Order
		0, -- @PrintTraffic
		1, -- @PrintOption
		@GLCompanyKey,
		@CompanyAddressKey, -- CompanyAddressKey
		@CurrencyID,
		@ExchangeRate,
		@CurrencyID,	-- PCurrencyID
		@ExchangeRate,	-- PExchangeRate
		null, --Description
		@PurchaseOrderKey OUTPUT
	
	IF @RetVal <> 1
	BEGIN
		ROLLBACK TRAN
		RETURN -5 
	END
	
	EXEC @RetVal = sptPurchaseOrderDetailInsert 
		@PurchaseOrderKey = @PurchaseOrderKey,
		@LineNumber = 1,
		@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,
		@LongDescription = @LongDescription,
		@CustomFieldKey = NULL,
		@DetailOrderDate = @OrderDate,
		@DetailOrderEndDate = NULL,
		@UserDate1 = NULL,
		@UserDate2 = NULL,
		@UserDate3 = NULL,
		@UserDate4 = NULL,
		@UserDate5 = NULL,
		@UserDate6 = NULL,
		@OrderDays = NULL,
		@OrderTime = NULL,
		@OrderLength = NULL,
		@Taxable = @Taxable,
		@Taxable2 = @Taxable2,
		@OfficeKey = @OfficeKey,
		@DepartmentKey = @DepartmentKey,
		@GrossAmount = @BillableCost,
		@PCurrencyID = @CurrencyID,
		@PExchangeRate = @ExchangeRate,
		@PTotalCost = @TotalCost,
		@SkipRollUps = NULL,
		@InteractiveAdUnitName = NULL,
		@oIdentity = @PurchaseOrderDetailKey

	IF @RetVal <> 1
	BEGIN
		ROLLBACK TRAN
		RETURN -6 
	END
	
	IF @RetVal = 1 
		UPDATE tEstimateTaskExpense 
		SET PurchaseOrderDetailKey = @PurchaseOrderDetailKey	
		WHERE  EstimateTaskExpenseKey = @EstimateTaskExpenseKey
		
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -7 
	END

	IF @QuoteKey IS NOT NULL
	BEGIN
		-- Try to copy the spec sheet links if any from the quote to po
		EXEC sptSpecSheetLinkCopy ''Est'', @QuoteKey, ''PO'', @PurchaseOrderKey
	END
	
	IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RETURN -8 
	END

	EXEC sptPurchaseOrderRecalcAmounts @PurchaseOrderKey 
								
	SELECT @oType = @ItemType
		   ,@oPurchaseOrderDetailKey = @PurchaseOrderDetailKey 
		   ,@oPurchaseOrderKey = @PurchaseOrderKey
		   
	COMMIT TRAN

	-- Project rollup for trantype = 5 po 
	EXEC sptProjectRollupUpdate @ProjectKey, 5, 1, 1, 1, 1
		
	RETURN 1
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoRuleGet]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoRuleGet]', 'P') IS NULL
EXEC sp_executesql N'CREATE Procedure [dbo].[sptAutoRuleGet]
(
	@RuleKey int
)

as

Select * from tAutoRule (nolock) Where RuleKey = @RuleKey

Select * from vAutoRuleTarget (nolock) Where RuleKey = @RuleKey

Select * from tAutoAction (nolock) Where RuleKey = @RuleKey Order by DisplayOrder'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating [dbo].[sptAutoActionTaskUpdate]'
GO
IF OBJECT_ID(N'[dbo].[sptAutoActionTaskUpdate]', 'P') IS NULL
EXEC sp_executesql N'CREATE procedure [dbo].[sptAutoActionTaskUpdate]
(
	@TaskKey int,
	@Action varchar(50),
	@NewKey int = NULL,
	--@NewKeys varchar(max) = null,
	--@FieldName varchar(300) = null,
	--@NewValue varchar(max) = null,
	@NewDate smalldatetime = NULL
)
As

	DECLARE	@ProjectKey int,
			@ScheduleDirection int,
			@TaskConstraint int,
			@PlanStart smalldatetime,
			@PlanComplete smalldatetime


	IF @Action = ''planStart'' OR @Action = ''planComplete''
	BEGIN
		SELECT	@ProjectKey = p.ProjectKey,
				@ScheduleDirection = p.ScheduleDirection
		FROM	tProject p (nolock)
		INNER JOIN tTask t ON t.ProjectKey = p.ProjectKey
		WHERE	t.TaskKey = @TaskKey

		SELECT	@TaskConstraint = TaskConstraint,
				@PlanStart = PlanStart,
				@PlanComplete = PlanComplete
		FROM	tTask (nolock)
		WHERE	TaskKey = @TaskKey

		IF @Action = ''planStart''
		BEGIN
			IF @ScheduleDirection = 1 AND @TaskConstraint = 0
				SELECT @TaskConstraint = 5 --Start No Earlier Than
			
			IF @NewDate > @PlanComplete
				SELECT @PlanComplete = @NewDate

			UPDATE	tTask
			SET		PlanStart = @NewDate,
					PlanComplete = @PlanComplete,
					TaskConstraint = @TaskConstraint,
					ConstraintDate = @NewDate
			WHERE	TaskKey = @TaskKey
		END
		ELSE
		BEGIN
			IF @NewDate < @PlanStart
				SELECT	@NewDate = @PlanStart

			UPDATE	tTask
			SET		PlanComplete = @NewDate
			WHERE	TaskKey = @TaskKey
		END

		--Add it to the scheduling queue
		EXEC sptCrossProjectPredsQueueUpdate @ProjectKey, 0, 0
	END

	IF @Action = ''timelineSegment''
		UPDATE	tTask 
		SET		TimelineSegmentKey = @NewKey 
		WHERE	TaskKey = @TaskKey	
'
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tActivityEmail_UserKey] on [dbo].[tActivityEmail]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tActivityEmail_UserKey' AND object_id = OBJECT_ID(N'[dbo].[tActivityEmail]'))
CREATE NONCLUSTERED INDEX [IX_tActivityEmail_UserKey] ON [dbo].[tActivityEmail] ([UserKey]) INCLUDE ([ActivityKey])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Creating index [IX_tActivity_8] on [dbo].[tActivity]'
GO
IF NOT EXISTS (SELECT 1 FROM sys.indexes WHERE name = N'IX_tActivity_8' AND object_id = OBJECT_ID(N'[dbo].[tActivity]'))
CREATE NONCLUSTERED INDEX [IX_tActivity_8] ON [dbo].[tActivity] ([CompanyKey], [ParentActivityKey], [AssignedUserKey], [ActivityEntity]) INCLUDE ([ActivityDate], [CMFolderKey], [Completed])
GO
IF @@ERROR <> 0 SET NOEXEC ON
GO
PRINT N'Altering trigger [dbo].[tU_tVoucherDetailSalesTax] on [dbo].[tVoucherDetail]'
GO
ALTER TRIGGER [dbo].[tU_tVoucherDetailSalesTax] ON [dbo].[tVoucherDetail] AFTER UPDATE
AS

/*
|| When      Who Rel     What
|| 03/02/26  MFT 26.030  (723453) Created to prevent tax changes after posting
|| 04/17/26  MCM 26.05x  (726753) Updated to allow when setting Taxable = 0 and Taxable2=0 due to spProcessTranTransferVO
|| 04/21/26  MCM 26.05x  (726919) Updated to allow when setting TotalCost or GrossAmount due to spliting (spProcessWIPSplitExpense)
*/

/*This trigger should be set to fire first, so if the transaction is rolled back, other triggers sholud not continue to fire
	EXEC sp_settriggerorder 
			@triggername = 'tU_tVoucherDetailSalesTax',
			@order = 'FIRST',
			@stmttype = 'UPDATE';
*/

BEGIN
	SET NOCOUNT ON

	IF NOT (
			UPDATE(SalesTaxAmount) OR
			UPDATE(SalesTax1Amount) OR
			UPDATE(SalesTax2Amount)
		)
		RETURN

	IF (UPDATE(Taxable) OR UPDATE(Taxable2)) --For Transfers we set the i.Taxable and i.Taxable2 = 0
		RETURN

	IF (UPDATE(TotalCost) OR UPDATE(GrossAmount))  -- for splits they update either TotalCostNet or GrossAmount but not SalesTax
		RETURN


		DECLARE
			@VoucherKey int,
			@VoucherDetailKey int,
			@ProjectKey int,
			@CompanyKey int,
			@ActionDate datetime,
			@Reference varchar(200)

		SELECT
			@VoucherKey = i.VoucherKey,
			@VoucherDetailKey = i.VoucherDetailKey,
			@ProjectKey = ISNULL(i.ProjectKey, 0),
			@CompanyKey = v.CompanyKey,
			@ActionDate = GETDATE(),
			@Reference = 'VoucherDetailKey: ' + LTRIM(STR(i.VoucherDetailKey))
		FROM
			inserted i
			INNER JOIN tVoucher v (nolock) ON i.VoucherKey = v.VoucherKey

		IF EXISTS (
			SELECT *
			FROM
				inserted i
				INNER JOIN deleted d ON i.VoucherDetailKey = d.VoucherDetailKey
				INNER JOIN tVoucher v (nolock) ON i.VoucherKey = v.VoucherKey
			WHERE
				v.Posted = 1 AND 
				(
					ISNULL(i.SalesTaxAmount, 0) != ISNULL(d.SalesTaxAmount, 0) OR
					ISNULL(i.SalesTax1Amount, 0) != ISNULL(d.SalesTax1Amount, 0) OR
					ISNULL(i.SalesTax2Amount, 0) != ISNULL(d.SalesTax2Amount, 0)
				)
		)
		BEGIN
			--'FileVersion' entity is hidden from users
			ROLLBACK TRANSACTION
			EXEC sptActionLogInsert @Entity = 'FileVersion', @EntityKey = @VoucherKey, @CompanyKey = @CompanyKey, @ProjectKey = @ProjectKey, @Action = 'Vendor Invoice TAX UPDATE ERROR', @ActionDate = @ActionDate, @ActionBy = 0, @Comments = 'This posted Voucher attempted to update taxes', @Reference = @Reference, @SourceCompanyID = '';
			RAISERROR('This change is not allowed on a posted Vendor Invoice', 16, 1)
			RETURN
		END

		SET NOCOUNT OFF
END
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
